Removing by indices several elements from a vector

That's a worthwhile problem to solve, and a good solution.

Trivial fix: std::size_t is misspelt in a couple of places.

One easy change I'd make is that rm can be const std::vector<INT>&, since we won't be modifying it.  That's helpful, as it allows the reference to bind to an rvalue if we want (test by passing std::move(toRemove)).

It might be worthwhile passing rm as an iterator pair; we can still have an overload that accepts std::vector or other container:

#include <algorithm>
#include <cassert>
#include <vector>

template <typename T, typename Iter>
void removeIndicesFromVector(std::vector<T>& v, Iter begin, Iter end)
    // requires std::is_convertible_v<std::iterator_traits<Iter>::value_type, std::size_t>
{
    assert(std::is_sorted(begin, end));
    auto rm_iter = begin;
    std::size_t current_index = 0;

    const auto pred = [&](const T&){
        // any more to remove?
        if (rm_iter == end) { return false; }
        // is this one specified?
        if (*rm_iter == current_index++) { return ++rm_iter, true; }
        return false;
    };

    v.erase(std::remove_if(v.begin(), v.end(), pred), v.end());
}

template <typename T, typename S>
    // requires std::is_convertible_v<S::value_type, std::size_t>
void removeIndicesFromVector(std::vector<T>& v, const S& rm)
{
    using std::begin;
    using std::end;
    assert(std::is_sorted(begin(rm), end(rm)));
    return removeIndicesFromVector(v, begin(rm), end(rm));
}

I've changed the algorithm here to simply count the elements seen, which must be valid because std::remove_if() accepts input iterators and is specified to invoke the predicate exactly std::distance(first, last) times.

The requires lines are commented out, as I didn't manage to get them working as I'd like - I'd appreciate a comment or edit to fix that.

If we feel generous, we might be willing to accept non-sorted input (with a speed penalty, of course):

#include <algorithm>
#include <vector>

template <typename T, typename Iter>
void removeIndicesFromVector(std::vector<T>& v, Iter begin, Iter end)
    // requires std::is_convertible_v<std::iterator_traits<Iter>::value_type, std::size_t>
{
    std::size_t current_index = 0;

    if (std::is_sorted(begin, end)) {

        // sorted version - advance through begin..end
        auto rm_iter = begin;
        const auto pred = [&](const T&) {
            // any more to remove?
            if (rm_iter != end && *rm_iter == current_index++) {
                return ++rm_iter, true;
            }
            return false;
        };
        v.erase(std::remove_if(v.begin(), v.end(), pred), v.end());

    } else {

        // unsorted version - search for each index in begin..end
        const auto pred = [&](const T&) {
            return std::find(begin, end, current_index++) != end;
        };
        v.erase(std::remove_if(v.begin(), v.end(), pred), v.end());
    }
}

template <typename T, typename S>
    // requires std::is_convertible_v<S::value_type, std::size_t>
void removeIndicesFromVector(std::vector<T>& v, const S& rm)
{
    using std::begin;
    using std::end;
    return removeIndicesFromVector(v, begin(rm), end(rm));
}

Test of unordered remove:

#include <array>
#include <iostream>
#include <string>

template <typename T>
void print(const std::vector<T>& v)
{
    for (auto const& e: v) {
        std::cout << e << " ";
    }
    std::cout << std::endl;
}

int main()
{
    std::vector v{"Alice", "Smith", "is", "very", "clever",
                  "and", "is", "very", "nice"};
    print(v);
    removeIndicesFromVector(v, std::array{6u,1u});
    print(v);

    return 0;
}


Looks good. You may also want some other things like getScalar (A single object, or string, as in 1 cell), getDataRow, just the top row, getDataRowCollection, i frequently only use datatable to get the rows, and forget about the columns, so I can iterate over it like so....

DataRowCollection drc = getDataRowCollection("SELECT * FROM tblTest");
for(DataRow r in drc){
    Console.WriteLine(r["name"]);
}

So you could have NonQuery, you may want to test these before using them....

    public DataTable getDataTable(SqlCommand objCmd)
    {
        SqlConnection objConn = null;
        try
        {
            objConn = new SqlConnection(connectionString);
            objCmd.Connection = objConn;
            var objAdapter = new SqlDataAdapter(objCmd);
            var ds = new DataSet();
            objAdapter.Fill(ds);
            return ds.Tables[0];
        }
        finally
        {
            objConn.Close();
        }
    }

    public DataRowCollection getDataRowCollection(SqlCommand objCmd)
    {
        return getDataTable(objCmd).Rows;
    }

    public DataRow getDataRow(SqlCommand objCmd){
        return getDataRowCollection(objCmd)[0];
    }

    public string getScalar(SqlCommand objCmd)
    {
        SqlConnection objConn = null;
        try
        {
            objConn = new SqlConnection(connectionString);
            objCmd.Connection = objConn;
            return objCmd.ExecuteScalar().ToString();
        }
        finally
        {
            objConn.Close();
        }
    }

    public int NonQuery(SqlCommand objCmd)
    {
        SqlConnection objConn = null;
        try
        {
            objConn = new SqlConnection(connectionString);
            objCmd.Connection = objConn;
            return objCmd.ExecuteNonQuery();
        }
        finally
        {
            objConn.Close();
        }
    }

I would recommend writing quite a few variations of the methods, and implement enums for each connection string so you don't mis-type anywhere and have them set in concrete.

Take a look at my getScalar variations....

    public static string getScalar(string query)
    {
        return getScalar(query, defaultConnection);
    }

    public static string getScalar(string query, ConnectionString cs)
    {
        return getScalar(query, new { }, cs);
    }

    public static string getScalar(string query, object param, ConnectionString cs)
    {
        return getScalar(query, param, cs, defaultTimeout);
    }
    public static string Query(string query, object param, int to)
    {
        return getScalar(query, param, defaultConnection, to);
    }

    public static string getScalar(string query, object param, ConnectionString cs, int to)
    {
        return getScalar(ConnectionStringToDb(cs), query, param, to);
    }

    public static string getScalar(MySqlConnection db, string query)
    {
        return getScalar(db, query, defaultTimeout);
    }

    public static string getScalar(MySqlConnection db, string query, int to)
    {
        return getScalar(db, query, null, to);
    }

    public static string getScalar(MySqlConnection db, string query, object param, int to)
    {
        string result = "";
        if (db.State != ConnectionState.Open)
            OpenConnection(db);
        MySqlParameter[] p = ObjectToParameters(param);
        using (db)
        {
            try
            {
                MySqlCommand command = new MySqlCommand();
                command.Connection = db;
                command.CommandText = query;
                command.CommandTimeout = to;
                foreach (MySqlParameter pm in p)
                {
                    command.Parameters.Add(pm);
                }
                result = command.ExecuteScalar().ToString();
            }
            catch { }
        }
        return result;
    }

Also if you class works as expected it should be fine... Looks okay. I use mine day to day, but I use MySql so I'm not to sure on the differences between the two classes, should be relatively the same.


The indentation seems to have gone wrong. This may not be entirely your fault - the Stack Exchange backend converts tabs to spaces - but it makes it harder than it should be to match { and } on some blocks.

The obvious place to look for optimisation is mulinv. One way to speed it up is a logarithm table - basically, do the loop once to fill a table with all 256 cases, and then just look up values in the table. More sophisticated approaches are to use Euclid's algorithm for GCD on elements of \$GF(2^8)\$, or to consider the field \$GF(2^8)\$ as a tower of field extensions, \$GF(2)[x]/p(x)/q(x)\$, which makes it fairly simple to reduce the inversion to one in \$GF(16)\$. You can find more detailed explanations on another site from this network in a rather unusual challenge format: https://codegolf.stackexchange.com/q/9276/194

The rotations for the affine transforms also look ripe for optimisation. If you use a 16-bit integer then

        s = l ^ ((l << 1) | (l >> 7)) ^ ((l << 2) | (l >> 6)) ^ ((l << 3) | (l >> 5)) ^ ((l << 4) | (l >> 4));

can be replaced with

        uint16_t l16 = l;
        uint16_t t = l16 ^ (l16 << 1) ^ (l16 << 2) ^ (l16 << 3) ^ (l16 << 4);
        s = (unsigned char)(t ^ (t >> 8));

and similarly in invsbox.

Finally, a point on names. inst is completely cryptic to me with the context given. Perhaps you could use the full word, comment on the meaning, or consider whether in fact whatever word it abbreviates is inherently what is operated on or merely a specific application.


Find the minimum gap (difference) between adjacent elements in a linked list

You don't need to store the whole previous node, just the value. Also, you can replace checking whether the gap is smaller with min, although it's mainly a matter of taste. And p is a rather opaque variable name

public int minGap() {
    if (front == null || front.next == null) {
        return 0;
    }
    int minGap = Integer.MAX_VALUE;
    int lastValue = front.data;
    ListNode currentNode = front.next;
    while (currentNode != null) {
       minGap = min(minGap, currentNode.data-lastValue);
       lastValue = currentNode.value;
       currentNode = currentNode.next;
    }
    return minGap;
}


When to use a new variable vs string interpolation?

Your refactor seems to have reduced the readability of your code, which is usually the opposite of your intent when refactoring. The code may be terser, and string interpolation and re-use is a part of how you've achieved this, but it doesn't make the code easy to follow. That will make it harder for you and your colleagues to modify it over time.

I actually prefer your original code a lot. You've pulled two methods out of your main execution flow, so it's possible to see at a glance what the code is doing - validate a directory, find all the files in it and do some form of outputting on each. That clarity is missing from the newer code because it is all written at the same level.

Your code makes use of #dup and #clone a lot. These methods are not needed in many of the places you use them, so they add noise to the code. For example files = folder.clone + "*.flv" does not need the #clone call because the + method will create a new String from the content of folder.clone and *.flv. Writing files = folder + "*.flv" would work just fine.

Here is a take on your original code that adds some readability by avoiding repetition and giving fuller names to variables and methods.

    def normalize_directory(dir)
        normalized = dir.gsub('\\', '/')
        normalized += '/' unless normalized.[-1,1] == '/'
    end

    def validate_directory(dir)
        if dir.empty?
            puts "Enter the full directory path of the flv files."
            dir = gets.chomp
        end
        dir = normalize_directory(dir)

        until File.directory?(dir) && !Dir.glob("#{dir}*.flv").empty?
            puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
            dir = gets.chomp
            dir = normalize_directory(dir)
        end

        dir
    end

    def output_html_wrapper(flv_filename, output_folder)
        html_filename = flv_filename.gsub(".flv", ".html")
        vid = flv_filename.slice(0..6)

        html_body = $EMBED.gsub("sample.flv", vid)
        html_output = File.open(html_filename, "w")
        html_output.write(html_body)
        html_output.close

        link = vid.gsub(".flv", ".html")
        link_list = File.open("#{output_folder}List of Links.txt", "a")
        link_list.write($BASE + link + "\n")
        link_list.close

        puts "Files created successfully."
    end

    folder = validate_directory(ARGV[0])
    flvs = Dir.glob("#{folder}*.flv")
    File.delete("#{folder}List of Links.txt") if File.exists?("#{folder}List of Links.txt")
    flvs.each { |flv| output_html_wrapper(flv, folder) }

Being DRY is about keeping a piece of knowledge in one place, whether that's a file name, the way you clean up some input or anything similar. The normalize_directory method I added DRYs up your code by putting in one place the logic for making a valid directory name out of the user's input.

Declaring a variable for a single use is extremely useful if it helps describe what the value is being used for. The vid variable in your code is still a mystery to me regarding what it actually contains. This is a great place to give something a name, and in doing so document your code without comments.


Generating a 1-dim array with explanatory arrows and text and large braces

So here are some points. Do ask if you need clarification:

tikz loads pgf, so having \usepackage{pgf} is redundant.
Personally I'd say only load the libraries you need. You may also use a single \usetikzlibrary, but that is I think just a matter of preference.
The arrows.meta library has replaced arrows (the latter still works, but is considered deprecated, see the manual)
Instead of the right=of, you can use the chains library, and place the nodes on a chain, using a loop to reduce the code if desired. There are other methods of achieving the same thing I think, but chains works fine here.
An alternative of the yshifts and xshifts is to use relative coordinates, e.g. ++(1cm,0) is the point 1cm to the right of the previous active coordinate.
For the vertical arrows: The coordinate (a-|b) has the y-coordinate of a and the x-coordinate of b. See how it's used in the code.
Instead of having above=of x,yshift=y, use above=y of x, e.g. above=1cm of n2.west.
I also added an additional style for the arrows, where the length for shorten < is made an argument. In myarrow/.style={->,shorten <=#1}, #1 indicates the argument, and the style is used as myarrow={<some length>}.
I modified \path[draw] to \draw.
For e.g. lower_bound(20) you could alternatively make the arrow and node in the same path, i.e.

\draw [myarrow=-1pt] (n2.north west) -- ++(0,0.7cm) node[above] {lower\_bound(20)};

This is merely a matter of preference though. One might find it clearer to separate the nodes from the arrows, as in your original code.
The standalone class is very handy for making PDFs consisting of only a tikzpicture.

\documentclass[11pt,border=1pt]{standalone}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
\usepackage{tikz}
\usetikzlibrary{
  backgrounds,
  decorations.pathreplacing,
  chains}
\definecolor{gpcHintergrund}{RGB}{205,229,244}

\begin{document}
\begin{tikzpicture}[
      background rectangle/.style={fill=gpcHintergrund}, show background rectangle,
      every node/.style={align=center, font=\small, minimum height=1.5em, minimum width=1.0cm,node distance=0cm},
        line/.style={ draw, line width=3pt },
        cell/.style = {rectangle, fill=white, draw, text width=1.0cm,outer sep=0pt,on chain}, % added on chain
        capx/.style = {rectangle, draw, text width=1.3cm, color=black!60,outer sep=0pt},
        myarrow/.style={->,shorten <=#1},
      scale=0.95,
      every node/.append style={transform shape},   % (1) scale here first approx. lines stay.
    ]

\begin{scope}[start chain]
\foreach [count=\i] \x in {10,20,...,80}
  \node [cell] (n\i) {\x};

\node[cell,fill=black!20,text=black!60] (ne) {end};
\end{scope}

\node[above=1cm of n2.west] (lb2) {lower\_bound(20)};
  \draw [myarrow=-1pt] (lb2) -- (n2.north west);

\node[above=1cm of n7.west] (ub7) {upper\_bound(60)};
  \draw [myarrow=-1pt] (ub7) -- (n7.north west);

\node[above=0.5cm of n4] (er4) {equal\_range(40)};
  \draw [myarrow=-3pt] (er4.south-|n4.north west) -- (n4.north west);
  \draw [myarrow=-3pt] (er4.south-|n5.north west) -- (n5.north west);

\node[below=1cm of n3.west] (lb25) {lower\_bound(25)};
  \draw [myarrow=-1pt] (lb25) -- (n3.south west);

\node[below=1cm of n7.west] (ub65) {upper\_bound(65)};
  \draw [myarrow=-1pt] (ub65) -- (n7.south west);

\node[below=0.7cm of n4.east] (er45) {equal\_range(45)};
  \draw [myarrow=-3pt] (er45.north) ++(0.45ex,0) coordinate (tmp) -- (tmp|-n5.south west);
  \draw [myarrow=-3pt] (er45.north) -- (n5.south west);

\draw[decoration={brace},decorate,color=black!50]
  (ne.north west) ++(0,1.3cm) -- node[right=6pt] {gefunden} ++(0,-1.1cm);

\draw[decoration={brace,mirror},decorate,color=black!50]
  (ne.south west) ++(0,-1.3cm) -- node[right=6pt] {nicht gefunden} ++(0,1.1cm);

\end{tikzpicture}
\end{document}


Finding and moving the next obstacle in a player's path

Take out the variables that are not changing within the loops and initialise them once.

float gap = Tools.generateFloat(Config.minBlockerGap, Config.maxBlockerGap);
float y = Tools.generateFloat(Config.minBlockerY, Config.maxBlockerY - gap);
float duration = Tools.generateFloat(Config.minBlockerYDuration, Config.maxBlockerYDuration);

It is unnecessary to continue to break out of the for loop to change the playerRotation. so then add within your for loop the playerRotation decrement with two if conditions (the while is unnecessary, it can only change by 1, so cannot exceed greater than 360 or less than 0.

while (true) {

    for (Blocker blocker : blockers) {
        if (playerRotation == (int) blocker.getRotation()) {
            if(lastBlockerMoved != blocker) {
                lastBlockerMoved = blocker;
                blocker.addAction(Actions.moveTo(blocker.getX(), y, duration, Config.blockerInterpolation));
                blocker.addAction(GapSizeAction.getGapSizeAction(gap, duration));

                playerRotation--; //-- is going right, ++ would be going left
                if (playerRotation > 360)
                    playerRotation -= 360;

                if (playerRotation <= 0)
                    playerRotation += 360;

            }
        }
    }
    // If game over -> break;
}

I am not sure of what condition you need to end this game, but you will need to add this within your while loop to break out.


Finding palindromes and the longest word in a string

For the palindrome:

You can probably just use one replace operation, but with a more extensive regex. My regex is rusty but something like /[\W_\s]/g could do.
split, reverse and join could possibly be just one chain.

var reversedString = replaceStrChr.split('').reverse().join('');

Comparisons are essentially boolean values. You can simply do:

return replaceStrChr === stringifyStr;

For the longest word:

Use reduce and carry through the longest word.

var longestWord = str.split(' ').reduce(function(prev, next){
  return next.length > prev.length ? next : prev;
});

str doesn't tell me what the string contains. Only when I saw split(' ') did I realize it was a space-separated string. Rename the variable to show its purpose.


Two sprite-drawing functions for Amara game

I stopped reading through the code when I got to this:

if (descendAttack || rightMouseActionHappening){
  if (!rightMouseActionHappening){
    rightMouseActionHappening = true;
  }
  //200 is pretty badass
}

First, that comment means nothing to the code, get rid of it.

Second thing is that the inside operation will never get called when rightMouseActionHappening is true,  I am not sure how this is supposed to work, if you try something like

if (true) {
    if (false){
        console.log("true");
    }
}

you won't get an answer from it, so what I mean is that you should write this a little more like this

if (descendAttack && !rightMouseActionHappening){
    rightMouseActionHappening = true;
}

because the inner if isn't going to be called if rightMouseActionHappening is true, so don't test for that.

once we have gone this far, if rightMouseActionHappening is true, reassigning it to true isn't going to hurt it at all, so we might as well drop it off.

if (descendAttack){
    rightMouseActionHappening = true;
}

Now, the next statement is another if checking descendAttack again, so we might just want to merge these together like this

if (descendAttack) {
  rightMouseActionHappening = true;
  ctx.save();
  ctx.translate(bugX+60, fly.getDrawAtY()-40 + 90);
  ctx.rotate(Math.PI);
  ctx.drawImage(silverSword, 0, -10);
  ctx.restore();
} else {
  ctx.drawImage(silverSword, bugX+ 60, fly.getDrawAtY()-40);
}

all of your code could use another indentation inside of the functions, so that I know that it is inside of a function.

if (skeleton.getMoveDirection() === "left"){
  facing_left = true;
} else if (skeleton.getMoveDirection() === "right"){
  facing_left = false;
}

I would change this into a simple assignment like this

facing_left = skeleton.getMoveDirection() === "left"

and this

if (facing_left){
  spritesheet_offset_y = 102;
} else {
  spritesheet_offset_y = 0;
}

I would change into a ternary assignment statement like this

spritesheet_offset_y = facing_left ? 102 : 0;


Swift/iOS: Subclassing UILabel and setting properties

You are using IconLabel to act as a container, it contains another UILabel and UIImageView. There is no need that IconLabel should be a UILabel you can just have your label nameLabel and your imageView icon in a UIView container. It means that you need to change :

class IconLabel: UILabel {

to something like

class IconLabelView: UIView {

another note, to keep your custom view generic it's better that you setup the background color outside the class like :

let customView = IconLabelView()
customView.backgroundColor = Theme.supportLightGrayColor

also I think it's better to have two methods for the subview setup and constraints instead of one:

private func addSubviews()

and

private func addConstraints()


There are somethings that I want to point out, that you are doing slightly wrong.

The first one is the argument checking. Argument checking should always be the first thing you do in your code, unless it is an expensive operation or you can't do it in a straight forward manner. In your case you don't have those reasons, so move your argument checking to the beginning. You should also use ArgumentException when your arguments are invalid instead of Exception.
The second one is that you are not following the camelCase convetion for your variables, you are using _camelCase convention which applies to instance fields. Even if you are following your own convention which is not bad, I would not recommend a _camelCase convention.
You shouldn't call the method ToList from LINQ so often. Calling the method ToList transforms what may be a lazy collection to a eager collection (which occupy the memory).

Here follows the review I made to your code, I post some comments regarding some decisions I made. The code I provide may be further reviewed but I think this is a fair starting point.

ServiceData.Models.CalculatedCutOff VarnRunEngine(List<Models.VanRunPrototype.VanRun> vanRuns, DateTime matchDate)
{
    if (vanRuns == null || vanRuns.Count == 0)
        throw new ArgumentException("There are no Vanruns available to work out fitting times", vanRuns);

    System.DayOfWeek dayOfWeek = matchDate.DayOfWeek;
    DateTime dateOfWeekLoop = new DateTime(matchDate.Ticks);
    Models.VanRunPrototype.VanRun vr = null;
    int maxIterations = 14;
    for(int i = 0; i < maxIterations && vr == null; ++i)
    {
        var vrs = vanRuns.Where(v => v.DayOfWeek == (int)dateOfWeekLoop.DayOfWeek &&
                                     v.CutOff > dateOfWeekLoop.TimeOfDay)
                         .OrderBy(t => t.CutOff);

        //vrs will never be null, it may be empty though
        //But you don't really have to check count because you will be iterating it, meaning that there is no problem
        //if vrs is empty. But if you want to preserve this check for any reason you could use vrs.Any()
        //if (vrs != null && vrs.Count() > 0)
        //{
            foreach (var v in vrs)
            {
                if ((vr == null || (vr.FittingFor <= v.FittingFor &&
                                    v.CutOff > vr.CutOff &&
                                    v.WareHouseID == vr.WareHouseID)))

                {
                    vr = v;
                }
            }

            vr = vr ?? vrs.First();
        //}

        //Go to next morning
        dateOfWeekLoop = dateOfWeekLoop.Date + new TimeSpan(8, 0, 0);
        dateOfWeekLoop = dateOfWeekLoop.AddDays(1);
    }

    if(vr == null){
        throw new Exception(string.Format("Couldn't calculate CutOff in {0} iterations", maxIterations));
    }

    DateTime co = dateOfWeekLoop.Date + vr.CutOff;
    return new TyresAndServiceData.Models.CalculatedCutOff()
    {
        CutOffTime = co,
        FittingFor = co.AddMinutes(vr.FittingIn).AddMinutes(vr.FittingInAdjust ?? 0),
        QueryDate = matchDate,
        WareHouseID = vr.WareHouseID ?? 0
    };

}


Design

You are obviously not using classes (as this is a free function). This means you are exposing the implementation details of the linked list to the user. This is bad as you can not guarantee any of the invariants of the list.

Invariants:

All the nodes were allocated with new.
Does your list use sentinels? (not at the moment see below).
(Sure I could come up with more).

Personally I would wrap this up in a class where the user never sees a node object.

Code Re-Use

You have repeated chunks of code that do the same things.

void removeFromList(node* &head, int toBeRemoved){
    // STUFF
        if (head->data == toBeRemoved){
            head = head->next;
            delete temp;
        }
    // STUFF
                    temp->next = temp->next->next;
                    delete removeThis;
                }

You should isolate code that does the same thing in to its own function/method. Then use a decent function name so the code becomes self documenting.

Sentinel

When writting list it is sometimes useful to have a sentinel node. This is a special node in the list that does not carry any data. But it makes manipulating the list easy as you no longer need to worry about a null value (or empty list). Thus the head no longer becomes a special case.

Example: A sentinel list will always contain one item at the head (this head item contains no data). The rest of the API should be coded with the understanding of the sentinel value. So en empty list contains only the sentinel value.

With this assumption we can simplify the code too:

void removeFromList(node* head, int toBeRemoved){
    node* temp = head;
    while (temp->next != nullptr && temp->next->data !=toBeRemoved) {
        temp = temp->next;
    }
    if (temp->next == nullptr && temp->next->data == toBeRemoved){
        node* removeThis = temp->next;
        temp->next = temp->next->next;
        delete removeThis;
    }
}

Use Braces

You don't consistently use braces. This is going to come back and haunt you one day. Any nested statement should have braces (even if it is a single item). Doing this one thing will save you from so many bugs.

            if (temp->next == nullptr)
                //some code to be executed when element not found
                else{
                }

Just add the braces after the if(). Also align your code better.

            if (temp->next == nullptr) {
                //some code to be executed when element not found
            }
            else {
                // Other stuff.
            }

Types and names

In C++ the most important part of the program is the type information. There is nothing more important than types. Get your types correct and you are 85% there in a C++ program.

As a result it is useful to be able to distinguish types from objects in the code. So a common convention is to use a naming scheme. A very common naming scheme is that user defined types have an initial uppercase letter while objects (variables/methods/functions) have an initial lower case letter.

// So
Node*  item;
// rather than
node*  item;

While we are taking about types. The '*' and the '&' are part of the type information so they go with the type not the object. This is the inverse of how C programmers do it.

// So
Node*&  head
// Rather than
node*   &head

Note: Notice how the SO code block picks up the type. This is a reflection of common conventions used in C++.

Re-Design

class LinkedList
{
    struct Node
    {
        Node* next;
        virtual ~Node(){}
    };
    struct DataNode: public Node
    {
        DataNode(Node* next, int val)
            : Node(next)
            , data(val)
        {}
        int    data;
    }

    Node  sentinel;    // Notice I don't dynamically allocate this.

    public:
        ~LinkedList()
        {
            Node* next;
            for(Node* loop = sentinel.next; loop; loop = next) {
                next = loop->next;
                delete loop;
            }
        }
        LinkedList()
            : sentinel{}  // forces zero-initialization
        {}
        // Delete compiler generated methods.
        LinkedList(LinkedList const&)            = delete;
        LinkedList& operator=(LinkedList const&) = delete;

        void add(int val)
        {
            sentinel.next = new DataNode{sentinel.next, val};
        }
        void del(int val)
        {
            for(Node* loop = &sentinel; loop->next; loop=loop->next) {
                if (dynamic_cast<DataNode*>(loop->next)->data == val) {
                    Node* del = loop->next;
                    loop->next = del->next;
                    delete del;
                    break;
                }
            }
        }
};

To see an example of a fully implemented doubly linked list check out this answer.


Your core problem is how to find out top-1 and bottom-1 in a single query. This is essentially a SQL problem and has not much to do with PL/SQL. First I present you the SQL solution and then simply wrap that into PL/SQL.

You didn't provided table definitions. I was lazy and didn't tried to reverse engineer your schema but instead created very simple table that illustrates the solution that you can apply to your real problem.

Other notes that might or might not be relevant to your case:

Use packages when applicable.
PL/SQL is case insensitive so it doesn't matter if use UPPER or lower or MiXed case. I prefer simplicity so I always use lower case. YMMV.
There is no need to convert dates into strings. Instead if you are looking for day granularity use trunc instead of to_char.

trunc example:

SQL> select sysdate, trunc(sysdate), date'2016-01-15' from dual;

SYSDATE             TRUNC(SYSDATE)      DATE'2016-01-15'
------------------- ------------------- -------------------
2016-01-15 11:05:10 2016-01-15 00:00:00 2016-01-15 00:00:00

Elapsed: 00:00:00.16
SQL>

As bonus I also introduced you to standard SQL datetime-literal syntax.

Let's create some data to play with:

-- demonstration purpose only, no resemblance to OP's code
create table items(
 id number
,quantity number
,production_date date
);

-- populate random data
insert into items
select level, floor(dbms_random.value(1, 1000)), sysdate - floor(dbms_random.value(1, 5))
from dual
connect by level <= 1000
;

Use analytic function row_number (you might also consider using rank or dense_rank functions instead) to assign an unique number in ordered sequence to each row. This is the standard way to implement top-N, bottom-N and inner-N queries in Oracle. Note that this example doesn't resolve ties.

with
ordered_items as (
  -- the actual SQL can be arbitrary complex
  select
   id
  ,quantity
  ,production_date
  ,row_number() over (order by quantity asc)  as top_rn
  ,row_number() over (order by quantity desc) as bottom_rn
  from items
  where trunc(production_date) = date'2016-01-14'
)
select
 o1.id as hi_id
,o2.id as lo_id
from       ordered_items o1
inner join ordered_items o2 on o2.bottom_rn = o1.top_rn
where o1.top_rn    = 1
and   o2.bottom_rn = 1
;

The above SQL will turn into the following PL/SQL code:

create or replace procedure get_hi_and_lo_id(
 p_production_date in date
,p_hi_id out number
,p_lo_id out number
) as
begin
  with
  ordered_items as (
    select
     id
    ,quantity
    ,production_date
    ,row_number() over (order by quantity asc)  as top_rn
    ,row_number() over (order by quantity desc) as bottom_rn
    from items
    where trunc(production_date) = trunc(p_production_date)
  )
  select   hi.id,   lo.id
  into   p_hi_id, p_lo_id
  from       ordered_items hi
  inner join ordered_items lo on lo.bottom_rn = hi.top_rn
  where hi.top_rn    = 1
  and   lo.bottom_rn = 1
  ;
exception
  when no_data_found then
    null;
end;
/
show errors

Usage example:

declare
  v_hi_id number;
  v_lo_id number;
begin
  get_hi_and_lo_id(
    p_production_date => sysdate - 1
   ,p_hi_id           => v_hi_id
   ,p_lo_id           => v_lo_id
  );

  dbms_output.put_line('v_hi_id: ' || v_hi_id);
  dbms_output.put_line('v_lo_id: ' || v_lo_id);
end;
/

v_hi_id: 689
v_lo_id: 370

PL/SQL procedure successfully completed.

That seems to be the correct answer with my data:

SQL> select * from items where trunc(production_date) = trunc(sysdate - 1) order by quantity;

        ID   QUANTITY PRODUCTION_DATE
---------- ---------- -------------------
       689         13 2016-01-14 10:44:28
        25         18 2016-01-14 10:44:28
[...]
       334        987 2016-01-14 10:44:28
       370        994 2016-01-14 10:44:28

235 rows selected.

Elapsed: 00:00:00.95
SQL>


Project Euler 6: Difference between sum of squares and square of sum

Looks good to me.

Couple of things to consider though:

You could split out two functions, squareOfSum and sumOfSquares. I think that would make it a little easier to read.
You could make the functions more general by using Seq.sum/Sum.sumBy instead of List.sum/List.sumBy.
While you could use fold, as joranvar mentioned, I think this would make the program much less clear and I would not recommend it (except as an exercise for learning about folds).
There is another way to attack the problem, by using the two identities

\begin{align}
1 + 2 + 3 + \cdots + n &= \frac{n(n + 1)}{2}, \quad \text{and} \\
1^2 + 2^2 + 3^2 + \cdots + n^2 &= \frac{n(n+1)(2n+1)}{6}.
\end{align}


As the conditions of the if statements only depending on some fixed numbers and the arraysize input parameter these values can be precalculated.

int oneThirdArraySize = (int)((1.00 / 3.00) * arraySize);

and then used in the loop like

for (var i = 0; i < arraySize; i++)
{

    if (i <= oneThirdArraySize)
    {
        startNumber = startNumber + 1;
        arr[i] = startNumber;
    }
    // and so on
}

By precalculation of the right side values of the if conditions outside of the loop you can speed this up because right now you do these calculation up to two times for every iteration.

But we can do better because you are using some magic numbers here which we can hide behind some meaningful const variables.

private static const double oneThird = 1d / 3d;
private static const double twoThird = 2d / 3d;

In this way the calculations need to be changed to

int oneThirdArraySize = (int)(oneThird * arraySize);


how can I optimize this code for a powerline?

There are several reasons why your solution is slow. However, the main reason is because you are actually performing all the steps that Luca would do, but the goal is just to determine the number of days Luca would need. So try to think of a way to determine that number by just looking at the all the tower heights once.
It helps to look at a few special cases first. Consider the towers having stricly descending heights:
5, 4, 3, 2, 1

It is clear that nothing has to be done, so this would take 0 days. Now look at the towers having strictly ascending heights:
1, 2, 3, 4, 5

It should be fairly obvious that it will take Luca 4 days to fix this, as the result of every day's worth is that it basically shifts the heights to the left, like so:
day 1: 2, 3, 4, 5, 5
day 2: 3, 4, 5, 5, 5
day 3: 4, 5, 5, 5, 5
day 4: 5, 5, 5, 5, 5

So now let's look at a more complex case:
4, 5, 1, 2, 3

The key insight is that there are two distinct regions of increasing heights:
4, 5 and 1, 2, 3

The first region takes one day to fix, the second two days. But this happens in parallel of course, so it's just a matter of finding the largest region of increasing heights, and subtract one from its length to get the number of days Luca needs. There's just one complication, let's look at this example:
2, 3, 1, 4, 5

Again there are two regions of strictly increasing heights, but it should be clear that since the second region's maximum height is larger than the first region's, it will actually take 4 days to finish the job. So what you should do is divide it in regions that each end at the maximum possible height. For example, take this example:
1, 3, 5, 7, 9, 2, 8, 4, 6
            ^     ^     ^
            |     |     |

I marked the positions of the end of each region. The first region's length is 5, the second and third have length 2. So the number of days necessary is 4. But how to find these maxima efficiently? If you scan forward you wouldn't know where the maximum of the first region is until you've seen all numbers. You then need to repeat this for all the points after the maximum. However, if you work backwards you only need to go through the heights once: you keep track of the maximum so far, and how many points you have visited. As soon as you see a height larger than the maximum you have so far, you store the length so far if that is the largest length you've seen so far, and then replace the current maximum with the new maximum you just found:
int maximum = -1; // assuming no tower has negative height
int length = 0;
int longest = 0;

for (int i = n - 1; i >= 0; i--)
{
    if (s[i] > maximum) {
        if (length > longest)
            longest = length;
        maximum = s[i];
        length = 0;
    } else {
        length++;
    }
}

if (length > longest)
    longest = length;

out << longest << "\n";


Comparing data in SQL using foreign keys

Just think simple:

select f.flight_code, f.origin, f.destination
  from FlightDelays f
  join Airport fo on fo.airport_code = f.origin
  join Airport fd on fd.airport_code = f.destination
 where fo.city_name = fd.city_name

You can try at SQL Fiddle


You're right about enumerating both parameters multiple times. Each call to Count or Last will execute the enumerator. This might of course become very inefficient, especially if your collections have a lot of items.

So what could you do instead? Well, one option would be to replace IEnumerable with the next closest type which is the ICollection. This would guarantee that both collections are already materialized. This however is rarely a good solution so it's preferable to keep it lazy.

But for this, simple LINQ is not enough. You need to work with enumerators directly and implement your extension in such a way that it uses the GetEnumerator method. With it you have the complete control over the enumeration process. With a little bit of logic you can keep you parameters lazy and still be able to validate that the are more values then separators.

You do this by first getting the first value. Then the while will try to get a pair of separators and values to append them to the string. If at some point it could get a separator but not a value, it means that there is at least the same number of separators as values and at this point you can throw an exception. The other case is when there are not enough separators. To detect this you just need to try to get another value after the while. If it works then it means there were not enough separators.

public static string Join(this IEnumerable<string> values, IEnumerable<string> separators)
{
    var result = new StringBuilder();

    using (var value = values.GetEnumerator())
    using (var separator = separators.GetEnumerator())
    {
        if (value.MoveNext())
        {
            result.Append(value.Current);

            while (separator.MoveNext())
            {
                if (value.MoveNext())
                {
                    result
                        .Append(separator.Current)
                        .Append(value.Current);
                }
                else
                {
                    throw new ArgumentException("There are too many separators!");
                }
            }

            if (value.MoveNext())
            {
                throw new ArgumentException("There are not enough separators!");
            }
        }

        return result.ToString();
    }
}

I would also call this extension Join because this is what it does.


Two solutions with min max values - which should be slower?

To answer your question: those solutions are identical performance-wise. There is no "magic" in Min or Max methods: they do the same thing you do in your first solution - compare the two values using if operator. There is no significant performance cost for a method call or for an extra assignment - those operations are so cheap, that you won't solve any real-life performance issue with this kind of optimization. If you will become obsessed with those small things - it will have a negative effect on your code quality. So, instead of asking, which is faster, you should ask yourself which is more clean, readable and OOP-ish. I would go with second solution.

If you want to really speed things up - you should first identify the real problem. In your example - it is the number of iterations, not the number of assignments. So the faster solution would probably involve multi-threading and iterating through different parts of your array simultaneously.


Designing a toy dependency injection library

In your injector you're exposing the dependencies object, in a way that all could access.

You should consider to hide it instead, so people will use just the API as it should be.

This happened because you choose to define your component just with a plain object approach.

If you want to write a lib or an utility, it is better to use one of the module pattern.

For example wrapping your code in a function if you mean to use it within a browser:

!function () {
    const dependencies = {};

    const injector = {
      // my code here
    };

    return injector;
 }()

Or with the node modules if you use in node:

const dependencies = {}

const injector = {
    // your code here..
}

export default injector

So you could expose just the API function you want.

This helps the developer to better understand how you design the lib to be used.


Displaying the total and average for an array input

Avoid Using Namespace std

If you are coding professionally you probably should get out of the habit of using the using namespace std; statement. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This stack overflow question discusses this in more detail.

Variable Naming

Use descriptive variable names so the code is more meaningful and comments are not as necessary, some examples

Current name: Suggested name
number      : maxTestScores
myArray     : testScores

Not currently in code
endTestScoresList : -1 (make -1 a symbolic constant like number is).

Variable Declarations

A good programming habit to get into is to put each variable declaration in a separate statement on a separate line. Instead of

    int myArray[number], //array set
            counter = 0; // current array input number (1~100)
    double total = 0, // total for all scores added up
            average; // the average point for the scores.

it would be better the following way because it is easier to add or delete a variable and it is easier to read and maintain the code.

    int myArray[number];
    int counter = 0;
    double total = 0;
    double average = 0;

In C++ it is also a good habit to initialize all the variables.

Move Loop Invariants out of the Loop

In the following code the variable average is a loop invariant and should not be calculated within the loop. Optimizing compilers may do this for you, but it is better to remove things that don't belong in the loop.

    while (std::cin >> myArray[counter] && myArray[counter] != -1)
    {
        total += myArray[counter]; // adds all inputs for grand total.
        counter++;
        average = total / counter; // grand total / number of input
    }

would be better as

    while (std::cin >> myArray[counter] && myArray[counter] != -1)
    {
        total += myArray[counter]; // adds all inputs for grand total.
        counter++;
    }

    average = total / counter; // grand total / number of input

Possible Bug

As was observed in another answer, if the user entered more than 100 test scores the previous code could throw an index out of range error and the program would crash. Rather than user a for loop as shown in the other answer, the code could be modified to test the index in the while loop:

    while ((counter < number) && std::cin >> myArray[counter] && myArray[counter] != -1)
    {
        total += myArray[counter++]; // adds all inputs for grand total.
    }

    average = total / counter; // grand total / number of input

By putting the test (counter < number) first the std::cin will not be called and the loop will exit, preventing the out of range problem.

Complexity

The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

There are at least 3 possible additional functions that can be called from main().
  - Get the user input
  - Calculate and print the total and average
  - List the scores in decsending order

By reducing the complexity the code becomes easier to read, write, modify and debug.

Prefer '\n' Over std::endl.

As mentioned in another review std::endl calls a system function to flush the output buffer. Sometimes this is needed, but generally to improve performance std::endl isn't called. It might be called after a loop of std::cout has been completed.


It looks like you're trying to create a generic INSERT function to put any data into the given table based on an array, securely.

Since you're using mysqli_ a better approach might be to use bound parameters.

It's not really "good practice" to require your config file in the function (I'm assuming it'll be pulled in anyway), it would be better to pass your $conn variable (which I assume is a mysqli object) into the function.

I'd also structure $data so that it's an associative array of fields to values, for example (as a sort of theoretical person insert). This means your values are bound to the field names within that array which makes a foreach loop less error prone.

$data = array(
    'forename' => "Fred",
    'surname' => "Bloggs",
    'email' => "fred.bloggs@example.com"
);

You'd have to have done any validation checks beforehand of course (making sure that the email is valid for instance).

Now your function could be written:

function dbRowInsert($conn, $table, array $data) {
    $fieldInsert = "";
    $valueInsert = "";
    $valueTypes = "";

    //array for bound parameters
    $paramData = array();

    //loop through the fields
    foreach($data as $fieldName => &$fieldData) {

        //SQL inserts
        $fieldInsert .= "{$table}.{$fieldName}, ";
        $valueInsert .= "?, ";

        //determine the data types for the bound parameters
        if(is_float($fieldData)) { $valueTypes .= "d"; }
        elseif(is_int($fieldData)) { $valueTypes .= "i"; }
        else { $valueTypes .= "s"; }

        //push the field data to the bound parameters array (by reference)
        $paramData[] = &$fieldData;
    }

    //trim the trailing ", " that will have been left
    $fieldInsert = substr($fieldInsert, 0, -2);
    $valueInsert = substr($valueInsert, 0, -2);

    //prepend the bound parameters array with the data types string
    array_unshift($paramData, $valueTypes);

    //prepare the statement
    $stmt = $conn->prepare("INSERT INTO {$table} ({$fieldInsert}) VALUES ({$valueInsert})");

    //error trapping
    if(!$stmt) { throw new Exception("Failed to prepare statement - ERR: {$conn->error}", E_USER_ERROR); }

    //call_user_func_array wouldn't be necessary with PDO as
    //you could bind parameters one at a time in the loop
    call_user_func_array(array($stmt, 'bind_param'), $paramData);

    //execute ... and relax
    $stmt->execute();
}

It looks a bit longer but is has the following advantages:

it uses a prepared statement
the parameters are bound by type so it'll not be attempting to
escape integers as strings for instance

The biggest problem is that it's using mysqli_ which doesn't have a nice way to bind parameters (or values) to the statement when you have an unknown number of parameters to bind ... hence the ugly call_user_func_array usage.

This could easily be mitigated by using PDO rather than mysqli_ though.


Angular directive to disable a button when clicked, allowing re-enabling as needed

One of the main ways in which you can improve this is by using Renderer2 in the directive instead of directly accessing this.el.nativeElement and making changes to it. This might work in most of the cases. But remember, the Angular code might run at other places as well(like in case of Service Workers and in case of Server Side Rendering). In these cases, you might not have direct access to the this.el.nativeElement.

So it's always recommended to use Renderer2 instead. Once you start using the renderer, your directive logic would significantly reduce. Here's how:

import { Directive, OnDestroy, Input, EventEmitter, HostListener, Renderer2, ElementRef } from '@angular/core';
import { Subscription } from 'rxjs';

@Directive({
  selector: '[appDisableAfterClick]'
})
export class DisableAfterClickDirective {

  @Input('appDisableAfterClick') reenableButton: EventEmitter<boolean>;
  subscription: Subscription;

  constructor(
    private renderer: Renderer2,
    private el: ElementRef
  ) {}

  @HostListener('click')
  onClick() {
    this.renderer.setAttribute(this.el.nativeElement, 'disabled', 'true');
  }

  ngOnInit() {
    this.subscription = this.reenableButton.subscribe(value => {
      if(!value)  this.renderer.removeAttribute(this.el.nativeElement, 'disabled');
    });
  }

  ngOnDestroy() {
    this.subscription && this.subscription.unsubscribe();
  }

}

Another thing would be to not have this directive itself in the first place unless you are going to reuse it in several other places in your App.

I've created this StackBlitz for your reference. Just in case.


Flags, flags everywhere

There are constructs in Python that can reduce the amount of needed flags like the for ... else blocks or the try .. else construct. break and return should also be your friends:

def print_fizz_buzz_output(start_end_pair, pair_list):

    start_num, end_num = start_end_pair
    for num in range(start_num, end_num + 1):
        has_divisor = False
        for divisor, text in pair_list:
            if num % divisor == 0:
                has_divisor = True
                print(text, end='')
        if has_divisor:
            print() # New Line
        else:
            print(str(num))

def ask_divisor_text_pairs():
    while True:
        while True:
            divisor = input('Divisor? ')
            try:
                divisor = int(divisor)
            except ValueError:
                print('Invalid input for divisor. Divisor must be a whole number. Please try again.')
            else:
                break

        text = input('Text? ')
        yield (divisor, text)

        while True:
            continue_response = input('Input Another Divisor (y/n)? ')
            if continue_response in ('N', 'n'):
                return
            elif continue_response in ('Y', 'y'):
                break
            else:
                print('Invalid response. Please input "y" or "n"')

def ask_iteration_range() -> tuple:
    while True:
        start_num = input('Start Number? ')
        try:
            start_num = int(start_num)
        except ValueError:
            print('Invalid input for start number. Must be a whole number. Please try again.')
        else:
            break

    while True:
        end_num = input('End Number? ')
        try:
            end_num = int(end_num)
        except ValueError:
            print('Invalid input for end number. Must be a whole number.'
                  ' Please try again.')
        else:
            if end_num < start_num:
                print('Invalid input for end number. Must be greater than or equal to the start number. Please try again.')
            else:
                break

    return start_num, end_num

print_fizz_buzz_output(ask_iteration_range(),list(ask_divisor_text_pairs()))

Factorize out common behaviour

Next we see that you make extensive use of constructs like:

while True:
    value = input('Something')
    try:
        result = convert(value)
    except ValueError:
        print('Error message')
    else:
        break

You can factorize that out:

def ask_something(prompt, type_=int, error_message='Invalid input'):
    while True:
        value = input(prompt)
        try:
            return type_(value)
        except ValueError:
            print(error_message)

def print_fizz_buzz_output(start_end_pair, pair_list):
    start_num, end_num = start_end_pair
    for num in range(start_num, end_num + 1):
        has_divisor = False
        for divisor, text in pair_list:
            if num % divisor == 0:
                has_divisor = True
                print(text, end='')
        if has_divisor:
            print() # New Line
        else:
            print(str(num))

def ask_divisor_text_pairs():
    while True:
        divisor = ask_something('Divisor? ', error_message='Invalid input for divisor. Divisor must be a whole number. Please try again.')
        text = input('Text? ')
        yield (divisor, text)

        while True:
            continue_response = input('Input Another Divisor (y/n)? ')
            if continue_response in ('N', 'n'):
                return
            elif continue_response in ('Y', 'y'):
                break
            else:
                print('Invalid response. Please input "y" or "n"')

def ask_iteration_range() -> tuple:
    start_num = ask_something('Start Number? ', error_message='Invalid input for start number. Must be a whole number. Please try again.')

    while True:
        end_num = ask_something('End Number? ', error_message='Invalid input for end number. Must be a whole number. Please try again.')
        if end_num < start_num:
            print('Invalid input for end number. Must be greater than or equal to the start number. Please try again.')
        else:
            break

    return start_num, end_num

print_fizz_buzz_output(ask_iteration_range(),list(ask_divisor_text_pairs()))

Build strings before printing them

The last flag we didn't take care of is in the print_fizz_buzz_output function. For this one, we need to see the inner for loop as something equivalent to:

text_for_divisor = []
for divisor, text in pair_list:
    if num % divisor == 0:
        text_for_divisor.append(text)
if text_for_divisor:
    print(''.join(text_for_divisor))
else:
    print(num)

So we got rid of the flag but the construct is inneficient. Better use a list-comprehension instead:

text_for_divisor = [text for divisor, text in pair_list if num % divisor == 0]
print(''.join(text_for_divisor) if text_for_divisor else num)

Use if __name__ == '__main__'

@Dex'ter already told you, but trully, you want to take that habit. When you jump into an interactive session and try to debug your functions, you don't want to be prompted about what are your bounds. You want to be able to directly do:

>>> import FizzBuzz as fb
>>> fb.print_fizz_buzz_output((1, 50), [(3, 'Fizz'), (5, 'Buzz')])

Better signature

I would use print_fizz_buzz_output(begin, end, pair_list) instead of requiring a tuple as the begin/end pair, this feel more natural. You would then need to change your main call to print_fizz_buzz_output(*ask_iteration_range(), list(ask_divisor_text_pairs()))

Proposed improvements

def ask_something(prompt, type_=int, error_message='Invalid input'):
    while True:
        value = input(prompt)
        try:
            return type_(value)
        except ValueError:
            print(error_message)

def print_fizz_buzz_output(begin, end, pair_list):
    for num in range(begin, end + 1):
        text_for_divisors = [text for divisor, text in pair_list if num % divisor == 0]
        print(''.join(text_for_divisors) if text_for_divisors else num)

def ask_divisor_text_pairs():
    while True:
        divisor = ask_something('Divisor? ', error_message='Invalid input for divisor. Divisor must be a whole number. Please try again.')
        text = input('Text? ')
        yield (divisor, text)

        while True:
            continue_response = input('Input Another Divisor (y/n)? ')
            if continue_response in ('N', 'n'):
                return
            elif continue_response in ('Y', 'y'):
                break
            else:
                print('Invalid response. Please input "y" or "n"')

def ask_iteration_range() -> tuple:
    start_num = ask_something('Start Number? ', error_message='Invalid input for start number. Must be a whole number. Please try again.')

    while True:
        end_num = ask_something('End Number? ', error_message='Invalid input for end number. Must be a whole number. Please try again.')
        if end_num < start_num:
            print('Invalid input for end number. Must be greater than or equal to the start number. Please try again.')
        else:
            break

    return start_num, end_num

if __name__ == '__main__':
    print_fizz_buzz_output(*ask_iteration_range(), list(ask_divisor_text_pairs()))


SQL Query based on results of preceding query

I would pull all the possible rates and just sort by the most specific.

SELECT @retval = bhrlyrate FROM [MYDATABASE].dbo.inv_hrrate WHERE
adjlevel = @nadjlevel
and cmode = @cmode
and companyid = @ncompanyid
and (client = @client or client = '')
and (holder = @holder OR (holder = '' AND client = ''))
and (scheme = @scheme or (scheme = '' AND holder = '' AND client = ''))
and dworkedfrom <= case when @date_done = '30 december 1899' then dworkedfrom ELSE    @date_done END
and dworkedto >= case when @date_done = '30 december 1899' then dworkedto ELSE @date_done END
ORDER BY scheme DESC, holder DESC, client DESC

That would eliminate some of the looping and requerying you are doing.


Persist values for a known set of keys in Python

1. Separation of concerns

There are three main features in this code:

Restricting the keys that can be stored in a dictionary.
Presenting a dictionary as a namespace.
Adding context manager behaviour to shelves in older versions of Python.

The principle of separation of concerns indicates that these should be implemented separately. See §3 below for one way to do this. This makes the code more understandable, testable, and reuseable.

2. Other review points

There are no docstrings. What does this code do? How do I use it?
The code in __exit__ assumes that Shelf objects have context manager behaviour in Python 3.0 or later. But the documentation says that this behaviour was only added in Python 3.4.
Storing _keys as a list means that checking to see if a key is valid takes time proportional to the number of keys. It would be better to store the keys in a set so that checking validity takes constant time.
There are implementations of __getattr__ and __setattr__ but not __delattr__.
A caller who tried to store a key check_key in the shelve would end up overwriting the method of that name.

3. Revised code

Restricting the keys that can be stored in a dictionary.

import collections.abc

class RestrictedMapping(collections.abc.MutableMapping):
    """A proxy for a mapping that restricts the set of allowable keys.

    >>> d = RestrictedMapping({0:0, 1:1}, range(3))
    >>> del d[1]
    >>> d[2] = 2
    >>> d[3] = 3
    Traceback (most recent call last):
        ...
    KeyError: 3
    >>> sorted(d.items())
    [(0, 0), (2, 2)]

    """
    def __init__(self, mapping, keys):
        keys = set(keys)
        for key in mapping:
            if key not in keys:
                raise ValueError('invalid key {}'.format(key))
        self.keys = keys
        self.mapping = mapping
        super(RestrictedMapping, self).__init__()

    def _check_key(self, key):
        if key not in self.keys:
            raise KeyError(key)

    def __getitem__(self, key):
        self._check_key(key)
        return self.mapping[key]

    def __setitem__(self, key, value):
        self._check_key(key)
        self.mapping[key] = value

    def __delitem__(self, key):
        self._check_key(key)
        del self.mapping[key]

    def __iter__(self):
        return iter(self.mapping)

    def __len__(self):
        return len(self.mapping)

Presenting a dictionary as a namespace.

class Namespace(object):
    """A proxy for a mapping that provides access to items via attribute
    lookup.

    >>> d = dict(a=1, b=2, c=3)
    >>> n = Namespace(d)        # n is now a proxy for d
    >>> n.d = 4
    >>> n.a, n.b, n.c, n.d
    (1, 2, 3, 4)
    >>> del n.b
    >>> sorted(d.items())
    [('a', 1), ('c', 3), ('d', 4)]

    """
    def __init__(self, mapping):
        super(Namespace, self).__setattr__('_mapping', mapping)

    def __getattr__(self, attr):
        return self._mapping[attr]

    def __setattr__(self, attr, value):
        self._mapping[attr] = value

    def __delattr__(self, attr):
        del self._mapping[attr]

Combining restriction on keys, presentation as namespace, and addition of context manager behaviour.

from contextlib import contextmanager
import shelve

@contextmanager
def restricted_shelve(filename, keys):
    shelf = shelve.open(filename)
    try:
        yield Namespace(RestrictedMapping(shelf, keys))
    finally:
        shelf.close()

4. Namespace antipattern

Presenting a mapping as a namespace instead of a dictionary is superficially attractive because n.name is three characters shorter than d['name'], but it's an antipattern in Python. (The only place this pattern is used in the standard library is in the argparse module.)

The problems are:

Attribute names need to be syntactically valid as Python identifiers, so you have to be very sure you're never going to need an attribute called class or return or 1 or whatever.
There will be collisions between the data attributes and the implementation attributes. In my version in §3.2 above you can't have attributes named _mapping or __init__ or __dict__ or __slots__ or ...
There's no easy way to get at the list of attributes.
There's not much you can do with a namespace-like object: the Python standard library usually expects you to use mappings instead. For example, you can't pass a namespace to itertools.ChainMap, or convert it to JSON using json.dumps, or output it as CSV using csv.DictWriter, and so on.

5. Answers to questions

As far as I know, there's no easy way to implement features 1 (restriction on keys) and 2 (presentation as namespace). Feature 3 (adding context manager behaviour) is more easily done using contextlib.contextmanager as shown in §3.3 above.
Your design puts all features into one class. This technique is known as the "big ball of mud".
Since your code knows exactly when it is assigning a special attribute, it can call super().__setattr__ itself, thus avoiding the need for special handling in the __setattr__ method. See §3.2 above.
Your code looks OK to me, but writing __exit__ methods is complicated and so (if you can) it's better to use contextlib.contextmanager which takes care of this complexity for you.
It's sensible to define your own exception classes, but it's good practice to inherit directly from Exception only if there is no close match in the exception hierarchy. Here UnexpectedKeyError is a runtime problem caused by an invalid value of the correct type, so it makes sense to inherit from ValueError.

The BadSpecialKey exception indicates a static programming error, not runtime exceptional behaviour, so I would use an assertion here.
It would be better to avoid having special keys altogther: you'll see in §3 above that I didn't need them. But if you must, then @classmethod makes slightly more sense: in theory you might have a subclass with a different value for _SPECIAL_KEYS.


Are there pitfalls to this solution to read messages from a queue in parallel?

Readability

Use keyword var any time that the initialization of the variable clearly tells what the variable represents. Avoid abbreviations in variable names.

var messageQueue = new MessageQueue(queue);
var semaphore = new SemaphoreSlim(15, 15);

Configuration

Avoid hard-coded settings:

var semaphore = new SemaphoreSlim(15, 15);

Make use of a pattern to allow the number of concurrent processing jobs to be configurable (instance property, configuration file, ..).

Main Loop

The main loop while (true) is considered a code smell by some because it's not clear what the exit conditions are. But what's definately an issue is that the loop never exits. Always make sure the loop has a graceful exit. Since there's a cancellation token provided, why not use it to drive the loop?

sand-box mode:

while (!token.IsCancellationRequested)
{
    // .. loop body
}

explicit mode:

while (true)
{
    token.ThrowIfCancellationRequested();
    // .. loop body
}

Threading Integrity

Once you have acquired the semaphore, you should immediately use the try-finally block to make sure to always release it.

await semaphore.WaitAsync();

// What if the code below throws an exception? The semaphore is not released!
await PeekAsync(messageQueue);
var message = await ReceiveAsync(messageQueue);

await semaphore.WaitAsync();
try
{
    // .. code while holding lock
}
finally
{
    semaphore.Release();
}

MessageQueue

There is no reason to peek before receiving, because both operations are blocking on the same trigger - an incoming message.

await PeekAsync(messageQueue);
var message = await ReceiveAsync(messageQueue);

You can replace the above with:

var message = await ReceiveAsync(messageQueue);


Naming

Variable names should make it very clear what a variable does. One or two letter variables generally don't do that. tb, rR, lI, `lE are all very unclear names.
Do not shorten words in variables if possible. eg limInit, limEnd, rowRes.
Be consistent with your variable names. Either use camelCase or under_score.
your function names are sometimes unclear. What does sqlFetcher fetch that isn't fetched by fetchAllData? Does fetchAllData actually fetch all data? etc.
getResources isn't a very good class name (What is a getResources? ResourceGetter would be semantically better, but still not express what it does very well). Also, what resources? It looks like posts, because post_id is hardcoded (which is odd, since the table name isn't).

SQL

is there a reason for the different getSomething functions? Because it doesn't seem likely that only the title or only the author is needed very often. And a user of this class might think that these are simple getter (as the name implies), while in reality they perform costly database accesses. I would get rid of all of these and return the complete row, ideally wrapped in an object.
Be consistent with your SQL statements. Either SQL keywords are all upper case or all lower case (I prefer upper case).
don't select *, but name the fields you want explicitly.
In sqlFetcher you check $run, which doesn't actually exist.

Your code looks wide open to SQL injection. It is unclear what data is user supplied, but for security reasons I would treat all variable data as user supplied (it doesn't hurt). Use prepared statements with mysqli or PDO everywhere, always.

OOP

Currently, it seems a bit unclear what your class should actually do. Should it be a model that temporarily stores data, as the getter imply? Or should it perform database interactions?

You could easily separate these concerns with a different structure:

class Post {

    private $author;
    private $title;
    // [...]

    public function __construct($author, $title) {
            $this->author = $author;
            $this->title = $title;
            // [...]
    }

    public function getAuthor() {
        return $this->author;
    }

    public function getTitle() {
        return $this->title;
    }
}

class PostDAO {

    function getById($id, $mysqli) {
        $selectById = $mysqli->prepare("SELECT author, title FROM <table_name> WHERE post_id = ?");
        $selectById->bind_param("i", $id);
        $selectById->execute();
        $selectById->bind_result($author, $title);
        $selectById->fetch();
        $post = new Post($author, $title);
        $selectById->close();
        return $post;
    }

    function getAll($mysqli, $amount, $offset = 0) {
        $selectAll = $mysqli->prepare("SELECT author, title FROM <table_name> LIMIT ?,?");
        $selectAll->bind_param("ii", $offset, $amount);
        $selectAll->execute();
        $selectAll->bind_result($author, $title);
        $posts = array();
        while ($selectAll->fetch()) {
            $posts[] = new Post($author, $title);
        }
        $selectAll->close();
        return $posts;
    }
}

You can use it like this:

$mysqli = new mysqli(credentials);
$post = PostDAO::getById($mysqli, 1);
echo $post->getAuthor();

$posts = PostDAO::getAll($mysqli, 5);
echo $posts[0]->getAuthor();

Now it's very clear that calling the getters does not cost very much (time-wise), and your model can be reused. For example, you might already know all the data without needing a database connection (because they are stored in the URL or session, or because you are performing tests and thus set them yourselves). If you only use the Post class in your other classes (such as the views), it can easily be separated from the database.


getString and maxNum should be get_string and max_num, by PEP 8 recommendation.
getString sometimes returns a number, and sometimes returns a string.  This violates the expectation set up by the function name.  Also, a function that is indecisive about its return type is harder to work with.
num = 1; ← No semicolons in Python, please.
The fizzbuzz loop is written idiomatically as for num in range(1, maxNum + 1): …


73 Lines of Mayhem - Parse, Sort and Save to CSV in PHP CLI

This will be much more efficient:

$result = array();

if (($handle = opendir('./txt/')) !== false)
{
    set_time_limit(0);
    ini_set('memory_limit', -1);

    while (($file = readdir($handle)) !== false)
    {
        if (($file != '.') && ($file != '..'))
        {
            if (is_resource($file = fopen('./txt/' . $file, 'rb')) === true)
            {
                while (($email = fgets($file)) !== false)
                {
                    $email = trim(str_replace(array(',', '"'), '', $email));

                    if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false)
                    {
                        $result[strtolower($email)] = true;
                    }
                }

                fclose($file);
            }
        }
    }

    closedir($handle);

    if (empty($result) !== true)
    {
        ksort($result);

        foreach (array_chunk($result, 10000, true) as $key => $value)
        {
            file_put_contents('./emailList-' . ($key + 1) . '.csv', implode("\n", array_keys($value)), LOCK_EX);
        }
    }

    echo 'Done!';
}


It is already short and to the point. One minor formatting change; I would make your class properties upper camel case, which is typical for C#. I also dropped the abbreviations.

public class Address {
   public string HouseNumber { get; set; }
   public string Street { get; set; }
   public string Zip { get; set; }
}

public class Contact {
   public string Email { get; set; }
   public string PhoneNumber { get; set; }
   public Address Address { get; set; }
}


Generate alternate saturday dates list within range in R

A pipe (%>%) solution is the following. I also use the dplyr-package, which you are probably already using as you have the arrange-function in your code. First I create a tibble with the days as input and then we can pipe ahead ;)

library(tidyr)
library(dplyr)

dates <- tibble(days = seq(as.Date("2018-01-01"), Sys.Date() + 365, by = 'day'))

HolidayList <- dates %>%
  # Only keep Saturdays
  filter(weekdays(days) == 'Saturday') %>%
  # Create a group variable (year_month) within we want to select the 2nd and 4th value
  group_by(year_month = format(days, "%Y-%m")) %>%
  # Only keep the 2nd and 4th value in each year_month
  slice(c(2, 4)) %>%
  # Get rid of the grouping
  ungroup() %>%
  # Only select the days column and rename it to Holidays
  select(Holidays = days) %>%
  # Add the extra holiday 2018-11-06
  add_row(Holidays = as.Date("2018-11-06")) %>%
  # similar to unique.data.frame(), but considerably faster:
  distinct() %>%
  # Arrange ascending by Holidays
  arrange(Holidays)

HolidayList
# A tibble: 54 x 1
#      Holidays
#        <date>
#  1 2018-01-13
#  2 2018-01-27
#  3 2018-02-10
#  4 2018-02-24
#  5 2018-03-10
#  6 2018-03-24
#  7 2018-04-14
#  8 2018-04-28
#  9 2018-05-12
# 10 2018-05-26
# ... with 44 more rows


Find hamming distance between two Strings of equal length in Java

Given the limited context, and no information about where the hotspot is in the code, it's difficult to give concrete advice. Here are some musings for your consideration:

For ease of reading, it's preferable to have whitespace after control flow keywords and before the (.

It is suggested to always include curly braces, even when they're not required by the compiler.

Use final where possible to reduce cognitive load on the readers of your code.

word should be private.

There's no apparent reason to use char[] instead of just keeping a pointer to the original String. They're costing you time and space to make, to no benefit.

You can short-circuit out of your for loop if the count ever becomes greater than one. Unless a significant fraction of your inputs have a distance of one, you should see some performance gain here.

Using a boolean instead of an int might make a very small difference in execution time, but that would need to be tested. It also makes the code harder to read.

private class WordArray {

    private final String word;

    private WordArray(final String word) {
        this.word = word;
    }

    private boolean isDistanceOne(final char[] otherWord) {
        assert word.length() == otherWord.length;

        int distance = 0;

        for (int i = 0; i < otherWord.length; i++) {
            if (this.word.charAt(i) == otherWord[i]) {
                continue;
            }

            if (distance > 0) {
                return false;
            }

            distance++;
        }

        return distance == 1;
    }
}


Check if a web element has a specific property and apply changes to the DOM according to the property's existence

Search online for "queryselectorall vs getelementsbytagname" and you will likely see results like this SO post from August 2013 and this post from September 2010. After reading those one can posit that using Element.getElementsByTagName() instead of querySelectorAll() would be quicker, since the selector appears to merely find elements by tag name. Be aware that method returns a Live HTMLCollection so you would need to put the elements into an array before iterating over them. There are some nice tools in ecmascript-6 to do this, like using the spread syntax or calling Array.from().

If you keep the for loop, you could consider using a for...of (also standard with ecmascript-6) in order to eliminate the accessing array elements with bracket notation.

I am not able to find references to those attributes icon="arrow:chevron-open-down" and icon="arrow:chevron-open-right" but if those could be handled in CSS then you could eliminate the whole JS iteration block.


Setting the implementation of an abstract class based on settings in config file using smart pointers

When you have a derived type deleted via a pointer to the base class you need to define a virtual destructor. This also applies when you are using unique_ptr.

// Base class for all position systems
class PositionSystem {
public:
    virtual ~PositionSystem() {}    // You need this or your object will
                                    // not be correctly destroyed.
    virtual int getX() const = 0;
};

You don't need to create an objet and copy it.

    ps = std::make_unique<GPS>(GPS());
                           //  ^^^^^    This creates a automatic object
                           //           When make_unique calls new
                           //           this automatic object is copy constructed
                           //           into the dynamic object.

Simply do this:

    ps = std::make_unique<GPS>();

You have the correct answer. Its an if/switch/command patter that you use to create the correct object. But you don't need to use a unique pointer. You could use a reference rather than a unique_ptr (but a unique_ptr is simpler).

But rather than do it in main I would move this work into a factory specifically for this job.

std::unique_ptr<PositionSystem> ps = positionSystemFactory(settings);

Then you just need to write the factory method:

std::unique_ptr<PositionSystem> positionSystemFactory(Settings const& settings)
{
    // Choose implementation based on settings
    if(settings.position_system == "GPS"){
        return std::make_unique<GPS>();
    }
    else if (settings.position_system == "Galileo"){
        return std::make_unique<Galileo>();
    }
    throw Failure;
}

  am having doubts about using std::make_unique inside the if scope.

Yes it will work as expected.

else if (settings.position_system == "Galileo"){
        ps = std::make_unique<Galileo>(Galileo());
    }

Even though the temp object created by make_unique() will be destroyed when it goes out of scope; this object is assigned to the variable ps where its content is maintained.

How this works: The temp object invokes the templatized move constructor on ps thus resulting in the contained pointer being moved from the temp object into ps (which takes ownership away from the temp object). When the temp object is destroyed it no longer owns the pointer and thus does not delete it.


From spending some time looking at your code

Purely style, but I think grouping statements belonging together and commenting on them sometimes makes your code easier to read

$(document).ready(function(){
  //Take care of the initial quote
  getNewQuote();

  //Take care of click handlers
  $("#newquote").on("click", getNewQuote);//Associate getNewQuote with button
  $("#twitter-share").on("click", tweet);

  //Take care of clipboard
  new Clipboard("#copy-clipboard");
  $("#copy-clipboard").attr("data-clipboard-target", ".quote");
});

I would move the magic constants 1000 to a properly named constant
A logical OR could make this look much cleaner: ( Returns expr1 if it can be converted to true; otherwise, returns expr2. ) "" and undefined cannot be converted to true.

var author = json.quoteAuthor || "Unknown";
$(".quote-author").fadeOut(1000, function() {
  $(this).text("-- "+author);
}).fadeIn(1000);

Inside getNewQuote() I would have placed the JSON call on top of the code
You can have a list of css classes inside a jQuery call:

$("body").css("background-color", newColor);
$(".button-colored").css({"background-color": newColor,
                          "border-color": newColor});

could be

$("body, .button-colored").css("background-color", newColor);
$(".button-colored").css("border-color", newColor});

Though I do wonder how beautiful changing every single element to 1 color is, I would probably have gone with matching background, foreground, and text colors.

Other than that, this code is readable and maintainable.


Sorted insert on a doubly linked list (HackerRank)

One thing I take issue with is that all of this code is in a static. If you're already drinking the Java kool-aid, you can have a brief static wrapper to do your if (head == null) shortcut, but the rest of the code should be one or more methods on DoublyLinkedListNode. Rather than continuing to reference your parameter data, the instance saved to nodeToInsert would, in the method you write, access its this.data.

Overall the question asks you to do a thing that sucks, so it isn't your fault: sorted insertion to a linked list is O(n), but you can do much better with a different choice of data structure, such as an AVL tree. If you're interested, here's an implementation of a sorted list in Java.


Efficiently displaying elements in an array

You can effectively get rid of the switch statement as well as the is_array check in the count ternary if you do the check in the beginning (and exit early at that - so not wasting any cycles).

You can also get rid of

# Only prepend comma if not the first element
if($i > 0) {
    $output .= $separator;
}

If you add a ternary concat to $output (at the expense of gaining 2 opcode calls over the if/else). This would be the function after cleaning it:

function listOut($array = array(), $oxford = false, $conjunction = 'and', $separator = ", ") {
    if(!is_array($array)){ # We're expecting an array
        return false;
    }

    $count = count($array) ?: 0;
    $output = "";

    if($count == 2){ return implode(" $conjunction ", $array); }

    for($i = 0; $i < $count; $i++) {
        # Add a conjunction if it's the last element in the array
        if($i + 1 === $count) {
            $separator = $oxford ? $separator . "$conjunction " : " $conjunction ";
        }

        # Add the element to the return string
        $output .= ($i > 0 ? $separator : "") . $array[$i];
    }

    return $output;
}

and the test outputs:

$array = 'blue';
$array1 = array('orange');
$array2 = array('white', 'gold');
$array3 = array('black', 'white', 'purple');
$array4 = array('black', 'white', 'purple', 'gold');

echo listOut($array) . "
";
echo listOut($array1) . "
"; // orange
echo listOut($array2) . "
"; // white and gold
echo listOut($array3, true) . "
"; // black, white and purple
echo listOut($array4) . "
"; // black, white and purple

Results:

false
orange
white and gold
black, white, and purple
black, white, purple and gold


Instead of having a get_content function you could add a function that only parses a source passed to it, now it can be either the main page or the suggested apps. Note that you're requesting for main page's content twice even though you had it already.
In addition to the above point you could make few more improvements:

Make the code PEP 8 compatible. Currently you will see decent number of issues if you run it on http://pep8online.com/.

Use session to re-use connections. Since we are making requests to the same host this would speed up the requests. From docs:

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3's connection pooling. So if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

Use __name__ == '__main__' to prevent your code from running when it is imported as a module.

After making the changes your code may look like this:
import requests
from bs4 import BeautifulSoup

session = requests.Session()

def get_links(url):
    source = session.get(url).text
    main_app = parse_content(source)
    print(main_app)

    for linked_app in get_linked_app_links(source):
        print(linked_app)

def get_linked_app_links(source):
    soup = BeautifulSoup(source, "html.parser")
    for title in soup.select("a.name"):
        linked_app = get_app_data(title.get("href"))
        yield linked_app

def get_app_data(url):
    source = session.get(url).text
    return parse_content(source)

def parse_content(source):
    broth = BeautifulSoup(source, "html.parser")
    item = {
        "app_name": broth.select("h1[itemprop=name]")[0].text,
        "developer": broth.select("div.left h2")[0].text,
        "price": broth.select("div.price")[0].text
    }
    return item


rand number generator with limits in ruby

Some notes:

Try to learn some functional programming, you shouldn't write Ruby as it were a low-level language (like C). Favor expressions over statements. My 2-cents on the matter, I hope it helps: http://www.slideshare.net/tokland/functional-programming-with-ruby-9975242
Let me show a simple example of using FP. The first 4 lines of your code could be written like this: arr = 980.times.map { (11..989).to_a.sample }
arr4 = []: Why? the next line assigns it to another expression.
range.to_a.sample. That's very inefficient, better rand(range).

I'd write:

ranges = [0..9, 11..989, 990..1000]
output = ranges.flat_map do |range|
  range.map { rand(range) }
end.shuffle


Return a substring containing a certain pattern to VBA

String Operations

regex_search provides various overloads for various input types. You don't need to copy the data into a wstring just to pass it to regex_search.

Since the return string is only a substring of the original, you can simply construct the BSTR from part of the match value, avoiding the erase calls.

ATL

Microsoft's ATL library provides a lot of helper classes for dealing with COM. They can eliminate a lot of boilerplate code.

Regex Library

I haven't used VBA lately but I expect something as common as regular expressions to already be available. If not, I would probably expose COM classes wrapping regex functionality to VBA and keep the actual expressions in VBA closer to the rest of the business code.


Magic numbers 20 and 19?

Instead of this:

char fileName[20];

// Get the filename from the user:
int fileNameLength = read(0,fileName,19);

Define MAX_FILENAME_LENGTH somewhere, and use that as the buffer size parameter, and MAX_FILENAME_LENGTH + 1 as the array size containing the buffer, to account for the terminating null character.

Write in code your intention exactly

Write in code more explicitly what you want.
For example here you say in comment that you want to write a \0 to the final position of the char[], but the code doesn't do exactly that:

// We need to get rid of the new line character caused by terminal
// Replace the new line character with \0
fileName[fileNameLength-1] = fileName[fileNameLength];

Don't assume what might be at an uninitialized memory location.
If you want to set the terminating character to \0,
then do exactly that:

fileName[fileNameLength-1] = '\0';

More magic number 20

All those 20 everywhere:

char buf[20];
int numBytesRead = read(fd,buf,20);
while(numBytesRead) {
    write(1,buf,numBytesRead);
    numBytesRead = read(fd,buf,20);
}

Why not introduce a variable so that you can change it later if you want to:

int bufsize = 20;
char buf[bufsize];
int numBytesRead = read(fd,buf,bufsize);
while(numBytesRead) {
    write(1,buf,numBytesRead);
    numBytesRead = read(fd,buf,bufsize);
}

And why use a buffer of size 20? Why read a file 20 byte at a time? It would be faster to read in larger chunks. Surely you have enough memory to load 4 kbyte at a time. Luckily, now it's easy to change that:

int bufsize = 4096;

Avoid code duplication

In the previous code snippet, read(fd,buf,bufsize); appears twice,
which is not pretty. It can be rewritten without such duplication:

int numBytesRead;
while ((numBytesRead = read(fd, buf, bufsize)) > 0) {
    write(1, buf, numBytesRead);
}
close(fd);

On the other hand, some people find this writing style potentially error prone or confusing. In my opinion code duplication is the bigger evil,
so I still prefer this writing style, which is also shorter.

Comments stating the obvious

// open the file:
int fd = 0;
fd = open(fileName,O_RDONLY);

Is that comment really necessary there? Or is it just noise?

Pointless variable initialization

int fd = 0;
fd = open(fileName,O_RDONLY);

If you're going to set fd to something else, why set it to 0?

Usability

When you run the program,
it prints nothing,
it's just waiting for user input.
It would be better to print a prompt,
for example:

puts("Enter file name:");


Counting occurrences of duplicate items in an array

There are a few things that stand out to me immediately in your code. Some good, some are troubling.
Style
First up, your code is neat, and well structured. Indentation is good, and I even appreciate the fact that you have braced 1-liners and got the space right in your expressions.
Traditionally, C puts the open brace on the new line.... I am not a fan of that, but I don't write C very often, so I stick with a style I use in Java. Just thought I would point that out, though.
Sorting
Your sort algorithm is ... basic, but effective. I would agree that it is a problem. As a suggestion, you should use an insertion sort, and do the sort at the same time as the scanf. That way you load the data in an always-sorted way:
puts("Insert the values:");
for (i = 0; i < N; i++) {
    int val;
    scanf("%d", &val);
    int pos = i;
    while (pos > 0 && values[pos - 1] > val) {
        values[pos] = values[pos - 1];
        pos--;
    }
    values[pos] = val;
}

The above will do a shifting insertion sort. Just a suggestion.
Duplicates.
This is where there are the most significant problems. I would consider your algorithm to be a real overkill one. You can do it all with no extra data, no duplicates[] array, etc. A simple loop through the data should be fine.
int count = 1;
int previous = values[0] + 1; // something different to the start.
for (int i = 0; i < N; i++) {
    if (values[i] != previous) {
        // something changed... reset the counters
        if (count > 1) {
            // report the count of previous duplicates.
            printf("Duplicate %d occurs %d times\n", previous, count);
        }
        previous = values[i];
        count = 0;
    }
    count++;
}
if (count > 1) {
    // catch the last count, if any
    printf("Duplicate %d occurs %d times\n", previous, count);
}


Given an array of integers, find and print its number of negative subarrays on a new line

Your code doesn't work for an empty array. Therefore it is conceptually wrong.

You should rewrite your code to be easily and automatically testable. This means to extract the interesting part of the program and separate it from the rest. In this case, the interesting part is the given an array, find. The code should therefore look like this:

static int countNegativeSubarrays(int... numbers) {
    int count = 0;
    // Your code here
    return count;
}

This method can be called easily from a test method:

static void runSelfTest() {
    if (countNegativeSubarrays() != 0)
        throw new AssertionError();
    if (countNegativeSubarrays(-1) != 1)
        throw new AssertionError();
    if (countNegativeSubarrays(-1, -1) != 3)
        throw new AssertionError();
    if (countNegativeSubarrays(-1, -1, -1) != 6)
        throw new AssertionError();
    if (countNegativeSubarrays(1, -1, -2, 5) != 4)
        throw new AssertionError();
    // Add more test cases here
}

In your main method you should run this self-test before accepting any input from the user.


Monitor

I encourage you to think about critical code fragments and restrict concurrent access to it.

The critical code fragments are the following statements:

...
int prev = map.getOrDefault(i, 0);
map.put(i, prev + 1);
...

They have to be executed single-threaded. As you allow multithreaded execution here, two threads may execute "getOrDefault" directly in sequence thanks to ConcurrentHashMap. But they both will get 0! So your next put-statement will bring your model into an inconsistent state.

So the first thing to do is to define a correct Monitor:

public class CountAtIndex {

    private HashMap<Integer, Integer> map;

    public CountAtIndex() {
        map = new HashMap<>();
    }

    public synchronized void countAt(int index) {
        int previousValue = map.getOrDefault(index, 0);
        map.put(index, previousValue + 1);
    }

    public synchronized int get(int index) {
        return this.map.get(index);
    }

}

I do not use a ConcurrentHashMap as it is not necessary anymore. And it is wrong considering the usecase. Those datastructures are not that beneficial as they seem in the first place as you have to know the usecase to chose the proper datastructure to be synchronized.

Synchronizing is done via the synchronized method modifier. Both, the read access method and the modification access method allow only ONE thread to be in the monitor.

Some may argue to avoid the synchronized modifier because it will introduce a lock on a visible object. Other developers may use the object as a lock as well and a deadlock may happen. My point of view is: If you put a lock on an object that you do not "own" you should know what you are doing. And I think it is a wrong message to allow other developers to not know what they are doing.

Thread

The next to adapt is your thread. First you should define a Runnable instead of deriving from Thread directly. Furthermore the thread should know the usecase specific thread-safe datastructure:

private class CounterRunnable implements Runnable {

    private CountAtIndex monitor;

    public CounterRunnable(CountAtIndex monitor) {
        this.monitor = monitor;
    }

    @Override
    public void run() {

        for (int index = 0; index < 10; index++) {

            try {
                monitor.countAt(index);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

}

Then you can use the Runnable to create a Thread.

...
Thread counterThread = new Thread(new CounterRunnable(countAtIndex))
...

Test

The only thing to determine thread-safety is to acknowledge that your monitor works. All other things can be tested without considering concurrency.

To determine if a monitor is working is to "attack" the critical code fragments.

Write access

As mentioned above following statements are critical:

...
int prev = map.getOrDefault(i, 0); // (1)
map.put(i, prev + 1); // (2)
...

A correct test would be to ...

... run a thread executing statement 1 and stop

... run a second thread and check if it runs into the monitor lock

... if the second thread ran into the monitor lock -> continue with thread 1

... If the thread 1 leaves the monitor -> thread 2 should enter the monitor, execute the statements and leave the monitor.

Read access

Another issue is that the HashMap is not thread-safe anymore so the "get"-method of "CountAtIndex" must prevent modificiation access during read access.

Reading concurrently only is never a problem. So this is not an issue of concurrency.

To test this scenario you have to ...

... start a thread that is modifying (countAt) and stop before it will leave the monitor.

... start thread 2 that will query the index count (get). You have to check if it ran into the monitor lock.

... thread 1 then has to continue and should leave the thread

... thread 2 now should continue and get the proper value.


No your code is correct.

!reference only throws a reference error if its not defined.

window is defined and window["not_defined"] just returns undefined for not defined variables.


Python program for fibonacci sequence using a recursive function

Since other answers have focused on the code quality itself, I'll focus on performance.

Recursive Fibonacci by itself is \$O(2^n)\$ time.

Memoized fibonacci is linear time (check out functools.lru_cache for a quick and easy one). This is because fibonacci only sees a linear number of inputs, but each one gets seen many times, so caching old input/output pairs helps a lot.

Golden-ratio based solutions are approximately \$O(\log(n))\$, using \$\text{Fib}(n) = \frac{\phi^n - (1 - \phi)^n}{\sqrt 5}\$, where \$\phi\$ is the golden number. Note that without arbitrary precision numbers, this approach becomes inaccurate at large values of n. With increased precision, note that the cost of a multiplication increases as well, making the whole process a bit slower than log(n).


Select a location on the map depending on which button is clicked

To DRY up your code, you need to use a variable to call the same code with different input.s It seems like if you had something like this:

const circles = {
   First: myloc,
   Second: myloc1
}

Then you'd be able to dry up the click code:

L.circle(circles[$(this).val()], {
            color: '#7a7777',
            weight: 0.1,
            fillColor: '#7a7777',
            fillOpacity: 0.2,
            radius: 0
        }).addTo(map)