Append the first half of the first line of /etc/hosts to a conf file

How can I improve on that, on a readability POV? It looks pretty obfuscated to me, but I may just be naive ^^

You're not naive, it looks obfuscated ;-)

A couple of general tips first:

When you find yourself writing the same path twice, put it in a variable

to avoid duplicated hard coded strings
to make it easy to change the path later if needed
to give it a meaningful descriptive name

Avoid echo -n. In general, avoid all echo statements that use any flags like -n, -e, because these are not portable. When you need those extra functions, printf is more portable. Plain echo with no flags, just stuff to print is nice, short and sweet
When you see head and awk in the same pipeline, usually you can rewrite with just awk. It saves the execution of one process.
I think head -NUM is deprecated. To be safe, I suggest to use head -n NUM instead.
To avoid extremely long lines, break the line with a \

A couple of specific tips in the context of your example:

The one-liner first appends some fixed text to the config file,
and then appends some more text by way of awk.
Since awk can print fixed text too, the echo is not needed at all.
xargs seems pointless: you could just redirect the output of awk
The separator ' ' you used with awk seems both unnecessary and error prone. The hosts file might have entries separated by tab. Simply by not specifying a separator, awk will work with both cases, space or tab separated.

Following the suggestions above, the one-liner could be simplified to:

awk '{print "storm.local.hostname: " $1; exit}' < /etc/hosts >> /opt/storm/conf/storm.yaml


Load fifty million integers as quickly as possible in Java

Your code is a bit messy, and having the file name hard-coded in to your function is not great. Also, the "Hungarian Notation" (using things like arg to prefix your function parameters - note, it's a parameter, not an argument, by the way)... is not conventional.

On the other hand, I understand this is an exercise to test performance.... and it's not about the resusability (yet) of the code.

Still, I know from experience that reusability will happen, and your code will need some changes.

I also know, from experience, that memory-mapped IO is much faster in Java than other IO forms, so I figured I would have a kick at this problem.

I took my prime generator I had reveiewed here on Code Review previously ( Thread Safe Prime Generator ) and I generated the first 50,000,000 primes in to a file on my own system, then I tested your code against it (and after changing the file name to a parameter, it worked).

Out of interest, generating and writing to file of the primes took about 5 minutes on my computer - 311 seconds - much of which was probably IO time too.

Then, I converted your function to be:

public static int[] loadByQuantity(int argNumPrimes, String fname) {
    int numPrimes = Math.min(argNumPrimes, 50_000_000);
    int[] primes = new int[numPrimes];
    try (DataInputStream in = new DataInputStream(new FileInputStream(fname))) {
        for (int i = 0; i < primes.length; ++i) {
            primes[i] = in.readInt();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return primes;
}

The only difference is the file-name is now a parameter.

Then I wrote a little test system to time how long your code took for me:

public static void time(Supplier<int[]> task, String name) {
    long nanos = System.nanoTime();
    int[] primes = task.get();
    System.out.printf("Task %s took %.3fms\n", name, (System.nanoTime() - nanos) / 1000000.0);
    System.out.printf("Count %d\nFirst %d\nLast %d\n", primes.length, primes[0], primes[primes.length - 1]);
    System.out.println("----");
}

public static void main(String[] args) {
    int count = 50000000;
    time(() -> loadByQuantity(count, "primes.dat"), "OP");
}

I then implemented the same functionality using an NIO mechanism specifically using memory-mapped IO: http://docs.oracle.com/javase/8/docs/api/java/nio/MappedByteBuffer.html

This type of IO is designed to significantly reduce the amount of memory copies are made of the input file. It also means that Java reads the content out of the OS, without first copying it in to Java's memory space.

For the types of sequential IO this problem has, I expected the performance improvements to be significant.

Further, the MappedByteBuffer has methods getInt() which also decodes 4 bytes in to an int for you: http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#getInt--

Here's the code I came up with. Note, I have used the same exception handling that you use, and also the same array initialization. I believe you should be throwing exceptions from these methods, and not just wrapping them in runtime exceptions:

public static int[] loadByNIO(int argNumPrimes, String fname) {
    int numPrimes = Math.min(argNumPrimes, 50_000_000);
    int[] primes = new int[numPrimes];
    try (FileChannel fc = FileChannel.open(Paths.get(fname))) {
        MappedByteBuffer mbb = fc.map(MapMode.READ_ONLY, 0, numPrimes * 4l);
        for (int i = 0; i < numPrimes; i++) {
            primes[i] = mbb.getInt();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return primes;
}

I then ran the process a couple of times in the main method, and compared the results:

public static void main(String[] args) {
    int count = 50_000_000;
    time(() -> loadByQuantity(count, "primes.dat"), "OP");
    time(() -> loadByNIO(count, "primes.dat"), "NIO");
    time(() -> loadByQuantity(count, "primes.dat"), "OP");
    time(() -> loadByNIO(count, "primes.dat"), "NIO");
}

The NIO operation is, as expected, significantly faster... 1500 times faster

Task OP took 214163.250ms
Count 50000000
First 2
Last 982451653
----
Task NIO took 141.511ms
Count 50000000
First 2
Last 982451653
----
Task OP took 214633.128ms
Count 50000000
First 2
Last 982451653
----
Task NIO took 159.571ms
Count 50000000
First 2
Last 982451653
----

I admit, it is far faster than I was expecting too.... but, the results are correct.

Now, I encourage you to experiment with how to put this concept behind a Java stream, instead of populating the full 50,000,000 in to an array. By streaming the results you can start your "real" computation sooner, without the latency of having to read all the primes from the file. For example, consider what you could do with logic like:

primes.stream().....

where primes was reading the values on-demand from the file.

Here's the full code I have been running:

package prperf;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Paths;
import java.util.function.Supplier;

public class PrimeReader {

    public static int[] loadByQuantity(int argNumPrimes, String fname) {
        int numPrimes = Math.min(argNumPrimes, 50_000_000);
        int[] primes = new int[numPrimes];
        try (DataInputStream in = new DataInputStream(new FileInputStream(fname))) {
            for (int i = 0; i < primes.length; ++i) {
                primes[i] = in.readInt();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return primes;
    }

    public static int[] loadByNIO(int argNumPrimes, String fname) {
        int numPrimes = Math.min(argNumPrimes, 50_000_000);
        int[] primes = new int[numPrimes];
        try (FileChannel fc = FileChannel.open(Paths.get(fname))) {
            MappedByteBuffer mbb = fc.map(MapMode.READ_ONLY, 0, numPrimes * 4l);
            for (int i = 0; i < numPrimes; i++) {
                primes[i] = mbb.getInt();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return primes;
    }

    public static void time(Supplier<int[]> task, String name) {
        long nanos = System.nanoTime();
        int[] primes = task.get();
        System.out.printf("Task %s took %.3fms\n", name, (System.nanoTime() - nanos) / 1000000.0);
        System.out.printf("Count %d\nFirst %d\nLast %d\n", primes.length, primes[0], primes[primes.length - 1]);
        System.out.println("----");
    }

    public static void main(String[] args) {
        int count = 50_000_000;
        time(() -> loadByQuantity(count, "primes.dat"), "OP");
        time(() -> loadByNIO(count, "primes.dat"), "NIO");
        time(() -> loadByQuantity(count, "primes.dat"), "OP");
        time(() -> loadByNIO(count, "primes.dat"), "NIO");
    }

}


How to improve this jQuery code for tabs

I'm going to go through a few main points here about your code but don't be overwhelmed by the size of this book, I prefer to be on the side of too much information than too little.

- Cache your selectors: Probably the most important thing you can do for your code now. As a rule of thumb, if you use a selection more than once, you should cache it. What happens when you use $("someElem") is jQuery queries the DOM to try and find elements that match. So imagine that every time you do that it runs a search. Would it be better if you could save the search results? This way you can look and play with them whenever you want without having to look for them again.  Ex.:

//Something like this:

var childFound = $(container).find(childElement);
/* Here I saved my search to a variable, which I use later.
This will return all "p" elements in "container".
You can filter more and get first element or all the others
The .find() method is just an example, there are countless others you can use
to help you select the elements you want
Methods like .map(), .each(), and .nextAll() will be increadibly useful for you */

//Then use like this
childFound.hide();

You're on the right track by setting up the options variable. This concept will be vital when you start to develop plugins, if that's what you want to do.

- IIFE's: If you have your code in the footer (which you should be doing) what you'll want to do is wrap it in a IIFE. "What the hell is that?" you may ask. A basic syntax looks like this:

(function () {
    //Code goes in here.
})();

You'll see several variations of this all over the internet as you read to find out more. The one I recommend you use in this case is like this:

;(function ($, window, document) {
    //Code goes here and the $ belongs to jQuery
})(jQuery, window, document);

So lets break this down. The ; in the front is a safety net against unclosed scripts, which can be common if you use plugins in Wordpress, or if you concat and minify your files it will protect you from your function becoming an argument.

Then we pass in $, window, and document. We pass in $ and at the bottom assign it to jQuery. So now in this function, no matter what value the $ carried outside, in here it's jQuery. Then we pass in window and document. These are optional in your case, but a good idea since you do use references to window in your code. It saves window as a local variable, and also will be good when you minify your code as the window reference can be changed to something like a or foo automatically. If you don't use a window or document reference you can just remove them all together.

Now keep in mind there might be times where you have to put your script in the header. Modernizr is an example of this. Then you'll probably end up using the document.ready. Don't sweat because all you have to do is this:

jQuery(document).ready(function( $ ) {
    //Code goes here and $ will belong to jQuery.
});

I wouldn't rely on $.noConflict to protect your code from other libraries that use the $ as well.

- Click Event Handler: As was mentioned before, there are several ways to set up your events. The ones that were mentioned were .click() and .on("click"). The .click() method simply calls the .on() method and passes in the click. The .on() method is incredibly useful since you can use it to set up almost any kind of event - not only clicks.  So yes, the one you are using now is "the best" because it saves you a function call. Now saving a single function call in your app won't be a significant increase in performance and you probably won't even notice it. Although arguing over such a small and possibly insignificant changes is really what we developers do best.

Using the .on() method directly is hands down going to be faster, but there are many other things you could be spending your time on that will generate more significant performance results.

- Don't re-invent the wheel: I strongly believe that if there's a working solution out there by all means use it. There are tons of tabs and accordion plugins available I'm sure you can find one that fits your project. If you can't find an exact fit, you can still always tweak it and make it fit. jQuery it self has an entire UI package with tabs, accordions, sliders, and all kinds of cool stuff just ready and waiting to be used. Also the jQuery UI will let you use your own CSS files and customizations really easily. Making a whole new app from scratch should be done if absolutely necessary, or if you're trying to learn (which is your case). Back to the subject of learning, like you said, you are just starting out with jQuery, and with that I highly recommend this screencast by Jeffrey Way called 30 Days to Learn jQuery. He does a really good job of explain some basic principals as well as some more complex concepts.

One thing in specific I'm going to point out is the following:

var details = $(this).next(childElement); //Details here is a jQuery object
//You don't need to wrap it again, just use details.someMethod();
if(details.is(":visible")){
    classToggle($(this), tabClassActive, tabClass);
    details.slideUp("slow");
}else{
    classToggle($(this), tabClass, tabClassActive);
    details.slideDown("slow");
}

When you cache a selection like you did there, the .next() gives you a new jQuery object with the results from the search which then are stored in details. So doing this: $(details) is the same as doing $($("p")). You're wrapping it twice. This is a common mistake with beginners and Jeffery, in that screencast, explains it much better than I ever could.


The static variable 'ACTIVE' can not be messed with from the outside in any way, is therefore safe in the first example.

The only reason I can come up with to still warrant a change to the second snippet is for consistency and future refactors. Suppose you want to change the method where this query appears and you want to give the user the freedom to choose between ACTIVE and ARCHIVED? To prevent yourself from making a very quick change and potentially creating a vulnerability, you should possibly make a habit of escaping every variable.

(Though in the specific case of a status fields where only a specific list of constants is valid I'd definitely also validate that the input is a valid input.)


You can use gsub! and block directly with a clone.

def autolink_string str
  unless str.empty?
    regex = /(\S+\.(com|net|org|edu|gov)(\/\S+)?)/
    str.clone.gsub!(regex) do |match|
      "#{ match }"
    end || str # Return str if no match
  end
end

In console:

> str = "this is a test abc.com"
> result = autolink_string str
=> "this is a test abc.com"
> str
=> "this is a test abc.com"
> result
=> "this is a test abc.com"

> autolink_string "no url here"
=> "no url here"

> autolink_string ""
=> ""

> autolink_string "this is a test abc.com and test twitter.com"
=> "this is a test abc.com and test twitter.com"


It's really hard to tell what this class does. From what you say, I feel like you have a number of TransferTasks and want to have a sort of ProgressTracker for them. So, as for me, your goal is to make user's code look like this:

ProgressTracker progressTracker = new ProgressTracker();
progressTracker.setListener(new ProgressTrackerListener() {
  @Override
  public void onProgressChanged(double progressPercentage) {
    // TODO: update your UI here
  }
});
...
TransferTask transferTask = new UploadTask("/home/jiduvah/1.txt");
progressTracker.track(transferTask);
transferTask.start();

Why? Because it doesn't need any comments to describe what happens here: you just write it in English.

Update - In case you're absolutely sure you like your approach.

First, in this code:

private int round(int num) {
    int temp = num % 5;
    if (temp < 3)
        return num - temp;
    else
        return num + 5 - temp;
}

I see magic like 5 and 3. Looks like it does exactly what you need to do, and you've even wrote about meaning of 5, but 3 is still a mystery.

Then:

double x = progressAmount;
double y = totalAmount;
double result = (x / y) * 100;
return (int) result;

When you divide int by int, you get int. When you divide int by double or double by int, you get double. So you may just write:

double result = 100 * progressAmount / (double)totalAmount;

Regarding the whole idea, I'm not sure whether this code works at all, because it's hard to understand how one should use it.


C++ templated singleton class - properly destroyed?

A classic singleton looks like this (in C++):

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S();
        // Dont forget to declare these two. You want to make sure they
        // are unaccessable otherwise you may accidently get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement
};

It is simple enough that template-ing it is redundant.
Also making it a template start to have other issues that require you to have a very good linker. SO it is worth just doing it explicitly for each object you want to make a singleton.

It is worth noting that it is probably a mistake to use a singleton. The use cases were they actually work well are very limited. Best to create the object in main and pass it as a parameter to everything that needs it.

This article covers a lot of info.

Looking at your code the thing that sticks out is:

template<typename T>
Singleton<T>::~Singleton()
{
    if(Singleton::_instance != 0)
    {
        delete Singleton::_instance;
    }
    Singleton::_instance = 0;
}

You are already in the destructor of the only object. Thus calling delete on _instance is calling delete on yourself (and that must already have been done otherwise you would not be in the destructor).

As you have deduced the problem is that the object is not automatically destroyed. There are several ways of solving this in your code. The best would be to make _instance a std::auto_ptr (std::unique_ptr in C++11). This will mean as a static storage duration object that it will be destroyed at the end of the program (which will call the destructor for you).

That aside C++ code where you have pointers strewn about the place is not real C++ code. You may be using the C++ syntax but you are writing C. There is a very different style attached to C++. You should barely ever see pointers. This is because there is no ownership semantics associated with pointers and one of the big things in C++ is expressing ownership of dynamic storage duration objects.

About the only place you see pointers are in the implementation of containers and smart pointers. As a user you should be using smart pointers or containers (depending on situation) instead of pointers. Where you passing be reference using a pointer (aka C) you should use references (aka C++).


Solving the Burst Balloon problem using Dynamic Programming

Your use of Array for memoization can be extracted into array-memoize.

If one can stop instead of having negative balloons decrease score, go can be condensed into one case.

import Data.Function.ArrayMemoize (arrayMemoFix)
import Data.Array ((!), listArray)

burstDP :: [Int] -> Int
burstDP l = arrayMemoFix ((0,0), (len+1, len+1)) go (1, len) where
  go ds (left, right) = maximum $ 0 :
    [ds (left, k-1) + ds (k+1, right) + b (left-1)*b k*b (right+1) | k <- [left..right]]
  b = (!) $ listArray (0, len+1) (1 : l ++ [1])
  len = length l

If you don't care too much about performance, we can also memoize directly on the balloon list:

burstDP :: [Int] -> Int
burstDP = memoFix3 go 1 1 where go ds l r b = maximum
  [ ds left l x + ds right x r + l*x*r
  | (left, x:right) <- zip (inits b) (tails b)
  ]


Transforming full names to surname and initial

You are doing way too much split()-ing.  You split on ‘-‘, and if you find the length of the split is greater than 1, you split on the ‘-‘ twice more, to get the first and the second part of the hyphenated name.  Split once, and save the result in a list, and access the list elements!

You are doing too much in convertNames().  It would be better to create a convertName() method, which just processes the player name into the desired form.  Then you could call that method from convertNames().

def convertName(player):
    names = player.split(' ')

    if len(names) == 2:
        names[0:1] = names[0].split('-', 1)

    surname = min(len(names)-1, 2)

    return ' '.join(names[surname:]) + ' ' + ''.join(name[0]+'.' for name in names[:surname])

# Test data
for player in ('Novak Djorkovic', 'Jo-Wilferd Tsonga', 'Victor Estrella Burgos', 'Juan Martin Del Potro'):
    print(player, ':', convertName(player))


The sniper: a Zombie searcher for specific tags

When using "simple" Aliases for table names in a query you should alias all the tables, not just some of them. This makes the query appear more consistent. In your query, you have a and q aliases for the two facets of the Posts table (questions and answers, it makes sense), but you should also alias the PostTags and the Tags tables to keep things consistent.

Stylistically, though, your query is otherwise neat, and reads quite well.

When querying tables, you should always offer the optimizer as much information as possible. You're cheating in your queries by ignoring the PostTypeID column (1 for questions, 2 for answers). Don't rely on inferred values like null, or non-null ParentID values to fix a query.

Further, note that you can put constant conditionals in the JOIN syntax for a table. You don't need to force these constants in to the regular where-block. I prefer putting related conditions together even if they are not strictly part of the join between tables. This is a coder-preference thing... you may disagree.

The most significant issue I have with the query is the use of the having-clause, which in my mind has always been a tool-of-last-resort in a SQL query.

Common Table Expressions (CTEs) have made this sort of complexity much simpler by allowing the aggregation in a virtual table before the actual query runs. CTE's are easier to show, than describe, so consider this query with a CTE instead:

WITH BestAnswer as (
  select ParentId, Max(Score) as Score
  from Posts
  where PostTypeId = 2
  group by ParentId
)

SELECT
  q.Id AS [Post Link],
  q.Tags
FROM
  Posts q
    INNER JOIN PostTags pt
    ON    q.Id = pt.PostId
    INNER JOIN Tags t
    ON    pt.TagId = t.id
      AND t.TagName = '##TagName##'
    INNER JOIN BestAnswer a
    ON    q.Id = a.ParentId
      AND a.Score >= ##MinScore:int?0##
      AND a.Score <= ##MaxScore:int?0##
WHERE
      q.PostTypeId = 1
  AND q.AnswerCount > 0
  AND q.AcceptedAnswerId IS NULL

-- TagName: Tag name as you would use in your post
-- MinScore: Highest answer has at least votes:
-- MaxScore: Highest answer has at most votes:

See it in SEDE here.


Searching a nested data structure for 2 attributes

You are correct, this is an inefficient way to do this search. Even if the groupInfo is found in the first iteration of each loop, you still go through (almost) every single element.

First a couple comments on your code:

The return type is lying to me. The function doesn't return BudgetGroupInfo. It returns BudgetGroupInfo | null. The fact that this doesn't complain means that you don't have strictNullChecks on. In my experience, this is the single most helpful feature available. It will let TypeScript tell you about a whole class of errors that it otherwise ignores.
filter.map.forEach is fine if you know only a few elements will be looped over, but if you end up having a lot of data, this will end up taking 3x the time. I don't find it that helpful for readability here, so I'd just pull the checks into the loop function.
TypeScript is generally pretty good about figuring out what variable types are. You don't need to manually type the result of Array#find.

The main trick for optimizing this is to make use of Array#some and change the outer forEach into a find. Here's how I'd write your function:

function getGroupInfo(budCat: string, account: string, budgetGroupInfo: BudgetGroupInfo[]) {
    return budgetGroupInfo.find(group => {
        return group.bcInfo.some(info => {
            if (info.name !== budCat) return false;
            return info.bcAccounts.some(acct => acct.name === account);
        });
    });
}

There are a few subtle differences:

This returns undefined instead of null if there is no result. If this is a problem, it's a straightforward fix.
I removed the return type of the function. TypeScript can infer it easily in this case, and it will still be correctly inferred if you turn on strictNullChecks
If there is multiple matches (I know you said there wouldn't be but...) my version will return the first match, while yours returns the last match.


Storing the API endpoints in a Pythonic way

A tip on the second part, is looking to what Brendan Rhodes has to say about Clean Architecture and bring your IO out as much as possible. This will make testing everything a lot easier, and limit the number of God-methods that do everything from constructing the query, getting the response to parsing and persisting the result

For the first part, I would work with a dict of destinations, that you can persist via json or so

settings = {
    'host': 'https://wallet.shiftnrg.org',
    'entry-points':{
        'start': ('api',),
        'accounts': ('_start', 'accounts'),
        'accounts_open': ('_accounts', 'open'),
        'loader': ('_start', 'loader')
    }

}

that you can dump to and load from json

For the entry-points, I would parse this somewhat like this:

def parse_entry_points(entry_points):
    for name, path in entry_points.items():
        yield name, list(expand_path(entry_points, name))

def expand_path(entry_points, item):
    path = entry_points[item]
    for item in path:
        if item[0] != '_':
            yield item
        else:
            yield from expand_path(entry_points, item[1:])

ENTRY_POINTS = dict(parse_entry_points(entry_points=settings['entry-points']))

Off course you can/should replace the _-placeholder with a unicode symbol that will not figure in the eventual URLs

{'accounts': ['api', 'accounts'],
 'accounts_open': ['api', 'accounts', 'open'],
 'loader': ['api', 'loader'],
 'start': ['api']}

assembling the URL can then be as simple as

from urllib.parse import urljoin
def assemble_url(enty_point):
    parts = constants.ENTRY_POINTS[entry_point]
    return urljoin(constants.HOST, parts)


POSIX-ly finding a specific Java process

Instead of simulating a for (( expr1 ; expr2 ; expr3 )) loop, use a POSIX

    for java_process_entry in $java_process_list

Notice that now you don't need to compute the number of lines, neither invoke sed.

There is noting wrong with early return. return 0 as soon as the desired process is found.

There is no need to store the entire list in a variable, neither invoke awk. Process the jps output sequentially.

All that said, consider

    is_java_program_running()
    {
        jps -l | while read pid java_process_entry; do
            if [ $java_process_entry = "${1}" ]; then return 0; fi
        done
        return 1
    }


Sharon Ben Asher has a good answer using streams. I'd like to add some suggestions for the original code, since beginners are often not familiar with streams in Java.

You have some redundancy in your code, meaning code that is executed multiple times, which can hurt readability, decrease performance and introduce bugs. To tackle the issue, you can save results from method calls in variables and just access the variables multiple times. This also allows you to give the result a new name, and although it might make the code slightly longer in terms of lines of code, it can also make it a lot cleaner, and the individual lines shorter.

The most important example is calling property.getKey() and property.getValue() multiple times. Instead, do that at the beginning of the loop, and save the results in variables.

for (Map.Entry<String, Object> property : properties.entrySet()) {
    String key = property.getKey();
    Object value = property.getValue();

Then you access them in your code, which makes it easier to see where the same values are used. You are using the same method call to access another element of a different map, so again you can use a variable to save the result and make the code clearer and shorter:

    if (existingProperties.containsKey(key)) {
        Object existingObject = existingProperties.get(key);
        if (existingObject instanceof String && value instanceof String) {
            String existingValue = (String) existingObject;
            String newValue = (String) value;

We can improve readability by formatting very long lines (like that long string concatenation) on 2 or 3 lines, introducing newlines where we can devide it into logical parts:

            if (existingValue.equals(newValue)) {
                throw new Exception("Property " + key +
                                    " is existing with value " + newValue +
                                    " in requires " + requiresName);
            }

By the way, there seems to have been a space missing at the start of the string "in requires ", and a typo in " is existsing with value ".


If you are addressing Code Contracts specifically then you should adopt a programming style that reinforces exception handling policy in release build, i.e. whether you require argument validation at runtime and whether Code Contracts will be part of release build or not.

I suggest taking a look at this diagram (copied from Code Contracts user documentation) and consult it with your team.


PEP-8

The Style Guide for Python Code has many stylistic guidelines that all Python programs should follow.

Naming

functions, methods, and variables should all be snake_case.  CapitalWords are reserved for Types and ClassNames.  So movesNeeded should be moves_needed and PegDict should be peg_dict, and so on.

Commas

All commas should be followed by exactly one space. {'A': A,'B': B,'C': C} violates this.

Binary operators

Binary operators should be surrounded by one space.  You mostly follow this, except for the print('Moves: '+ str(moves)) statements at the end.

Exponentiation

movesNeeded = pow(2, discs) - 1

Python has the ** operator, for exponentiation.  Thus, this could be written slightly more compactly:

moves_needed = 2 ** discs - 1

Initial list generation

A = []

for i in range(discs, 0, -1):
    A.append(i)

This is a little verbose.  You are already using the range() method to generate the disc numbers; you could simply create a list directly from the result:

a = list(range(discs, 0, -1))

Moving a Disc

def move(fromm, to):
    to.append(fromm[-1])
    fromm.pop()

I'm going to assume fromm is not a spelling error, but rather avoiding the from keyword.  The PEP-8 recommendation is a trailing underscore: from_.  My personal preference is to use synonyms.

.pop() returns the item removed from the list, which is the value you used fromm[-1] to retrieve.  Therefore, these operations could easily be combine into one statement:

def move(source, destination):
    destination.append(source.pop())

Repeated Code

    print(A)
    print(B)
    print(C)
    print()

You've repeated this code twice.  Once moving the small disc, once moving a larger disc.  Instead of repeating the code, you should move this into a function.  Then, if you change how the discs are shown (curses, GUI, ...), you only have to alter the code once.

def print_pegs(a, b, c):
    print(a)
    print(b)
    print(c)
    print()

Iterating over a container

        for key in PegDict:
            if PossibleMove(PegDict[key]) != None:
                fromPeg = PegDict[key]
                onePossibleMove = PossibleMove(PegDict[key])

In this code, you are iterating over the PegDict, fetching the keys, and using the key to look up the dictionary value.  In fact, you never use the key for anything else.  You do not need the key at all, and could simply iterate over the contents of the dictionary:

        for peg in peg_dict.values():
            if possible_move(peg) != None:
                from_peg = peg
                one_possible_move = possible_move(peg)

But notice we are computing using possible_move(peg) twice.  This is inefficient.  You should compute the result once, save it in a temporary, and use the temporary variable for further tests and assignments:

        for peg in peg_dict.values():
            move = possible_move(peg)
            if move != None:
                from_peg = peg
                one_possible_move = move

More Advanced Changes

Left or Right?

Each iteration, you check if the number of discs was even or odd, and call the moveLeft() or moveRight() function.  Since the number of discs is constant, you always make the same choice.  You could move this decision out of the loop.

move_smallest_disc = move_left if disc % 2 != 0 else move_right

while len(c) != discs:       # A simpler termination condition

    move_smallest_disc()
    print_pegs(a, b, c)
    moves += 1

    ...

But I've a different option...

Cyclic Peg Order

You always move the smallest disc either:

a -> b -> c -> a -> b -> c
a -> c -> b -> a -> c -> b

You can keep track of which order you need with a list:

    if discs % 2 == 1:
        peg = [a, c, b]
    else:
        peg = [a, b, c]

And move the smallest disc from peg[0] to peg[1], without having to hunt for which peg the smallest disc is on:

    move(peg[0], peg[1])

And later rotate the peg list:

    peg = peg[1:] + peg[:1]   # [a, b, c] -> [b, c, a] -> [c, a, b] -> [a, b, c]

After moving the smallest disc onto peg[1], the only possible moves for the larger disc will be peg[0] -> peg[2] or peg[2] -> peg[0], so you can greatly simplify the possible move determination, by just looking at those two pegs:

    source, destination = possible_move(peg[0], peg[2])
    move(source, destination)

Refactored Code

from pathlib import Path
import gettext
gettext.install('hanoi', Path(__file__).parent)

def move(source, destination):
    destination.append(source.pop())

def possible_move(peg1, peg2):
    if peg1 and (not peg2 or peg1[-1] < peg2[-1]):
        return peg1, peg2
    else:
        return peg2, peg1

def print_pegs(a, b, c):
    print(a)
    print(b)
    print(c)
    print()

def tower_of_hanoi(discs):
    a = list(range(discs, 0, -1))
    b = []
    c = []

    minimum_moves = 2 ** discs - 1

    if discs % 2 == 1:
        peg = [a, c, b]
    else:
        peg = [a, b, c]

    moves = 0
    while len(c) != discs:
        if moves % 2 == 0:
            move(peg[0], peg[1])      # Smallest disc now on peg[1]
        else:
            source, destination = possible_move(peg[0], peg[2])
            move(source, destination)
            peg = peg[1:] + peg[:1]   # Rotate the peg ordering

        print_pegs(a, b, c)
        moves += 1

    print()
    print(_('Moves:'), moves)
    print(_('Minimal moves:'), minimum_moves)

if __name__ == '__main__':
    discs = int(input(_('Enter the number of disks: ')))
    tower_of_hanoi(discs)

If you run pygettext on this, you can make a hanoi.pot template file, copy it to hanoi.po and put translations into it:

msgid "Moves:"
msgstr "Liczba ruchów:"

msgid "Minimal moves:"
msgstr "Minimalna liczba ruchów:"

msgid "Enter the number of disks: "
msgstr "Podaj ilość dysków: "

Run msgfmt on that to generate an hanoi.mo file, and store it the subdirectory: pl/LC_MESSAGES.

Running LANG="pl" ./hanoi.py on my machine, gives:

Podaj ilość dysków: 2
[2]
[1]
[]

[]
[1]
[2]

[]
[]
[2, 1]

Liczba ruchów: 3
Minimalna liczba ruchów: 3

With luck, I haven't butchered the translated strings too badly.


Compare an array with a file and form groups from elements of an array

I can't understand your algorithm as written, but some very general advice applies:

Use format() or template strings to format strings.
Rather than creating dynamic dictionary keys, I would create variables data_row, clust (but see naming review below), etc. and assign to indexes in these lists. That way you get rid of the global variables (which are bad for reasons discussed at great length elsewhere), you won't need to format strings all over the place, and you won't need to do the str() conversions. You should also be able to get rid of the array initialization this way, something which is a code smell in garbage collected languages.
Can there really be multiple tab characters between columns? That would be weird. If not, you might get less surprising results using a single tab as the column separator.
Naming could use some work. For example:

In general, don't use abbreviations, especially not single letter ones or ones which shorten by only one or two letters. For example, use index (or [something]_index if there are multiple indexes in the current context) rather than indx, idx, i or j.
data should be something like character_table.
I don't know what obj is, but obj gives me no information at all. Should it be vowels?


ASP.NET Core singleton with a thread-safe property that can be changed

That will lock it down for sure.  If you know you will have more reads then writes, which is common, you should look at the ReaderWriterLockSlim class.   What you have will only allow one read and one write and they all queue up in line waiting their turn.  The ReaderWriterLockSlim class will still only allow one write at a time but allow multiple reads at a time.


jQuery already has a caching mechanism - and I'm not just talking cache: true (which as you say, only works for HEAD/GET, and relies on the browser's built-in caching).

What I'm talking about is promises. Promises are caches themselves, and $.ajax returns a promise. Once resolved or rejected, it'll stay that way, and you can keep calling done/fail/then/always on it, being passed the same arguments every time. The request isn't repeated.

So to start, your example code can be written as just:

var xhr = $.ajax.bind(this, {
    url:'/echo/json/',
    data: data,
    type: 'POST'
})();

xhr.done(function (response) { ... });
xhr.done(function (response) { ... });
xhr.done(function (response) { ... });
// etc...

As long as you have a reference to xhr, the request and response is cached.

The only difference from yours is that the response is passed as-is without the deep copy. But if your requests are JSON, you can always get a pristine response by re-parsing the response yourself:

xhr.done(function (response, status, xhr) {
  var pristineResponse = JSON.parse(xhr.responseText);
});

Incidentally, your example didn't make much sense. You called getData a couple of times but didn't actually do anything with those calls. Besides, calling it from inside the done callback, seems redundant to me:

getData('foo', getter).done(function (response) { // <- the response is right there, no caching necessary
    // do stuff with response. For instance, a deep copy.
});

Not to be harsh, but your current implementation is just kinda pointless, it seems to me. You have to create the getter function, and then manually pass it to getData. Then, if you want to use the cache... you have to pass the getter function again? Shouldn't that just be getData('foo') without the getter if you want the cache? As mentioned, if you have the request's promise, you have a cache already.

However, even if you just call getData('foo'), you have to be prepared to handle a failure, if nothing's been cached. Which, in turn, means that you have to always be ready to perform the request, so you code will be littered with something like this:

getData('foo')
  .done(function (response) {
    // with no existing cache, this won't be called
  })
  .fail(function () {
    // instead we'll have to create the cache
    var getter = $.ajax.bind(something, { // oops, what "this" should we bind to?
      url:'/echo/json/',
      data: data,
      type: 'POST'
    });
    getData('foo', getter).done(function (response) {
      // finally! We can get our response
    });
  });

And you'd have to do this every time, because you don't know if you have a cache or not.

Finally, there's a risk of a race condition. You only set the cache when the request is completed successfully, so if you were to do this:

var getter = $.ajax.bind(this, {
    url:'/echo/json/',
    data: data,
    type: 'POST'
});

// This performs a request. It's asynchronous, so the code here just continues on immediately...
getData('foo', getter);

// ... so this performs *another* request, because nothing's been cached yet
getData('foo', getter);

// Time passes, and the first request completes. A cache is finally created.
// Then the second request completes, and overwrites the just-created cache.

I imagine that's why your example only tried using the cache inside the first done handler. But that's the one place where you don't need the cache, since you have the response.

So, really, I see little benefit in using your code. The only thing it seems to add is the deep copy.

If you want a simpler caching mechanism, I'd suggest something like this:

  var cache = {};
  function cachedAJAX(options) {
    if(!options.cacheKey) {
      return $.ajax(options); // no caching requested; just pass through
    }

    if(!cache[options.cacheKey]) {
      cache[options.cacheKey] = $.ajax(options); // create and cache a new request
    }

    // return the request
    return cache[options.cacheKey];
  };

Now, instead of calling $.ajax, you'd call cachedAJAX, but you'd use all the same options (url, type, data, etc.). There's just one extra option: cacheKey. If that's set, cachedAJAX won't perform a new request if it has a cached one. And it caches immediately, meaning you might cache a soon-to-be-failed request. But there's no race condition.


A value set data structure for rapid statistics queries in Java - follow-up

This is not a Set. A Set contains no duplicate elements. You should rename the class, perhaps to a Bag or a MultiSet.

I'm also worried about this bit:

/**
 * Computes the variance of this set.
 *
 * @return the variance.
 */
public double getVariance() {
    double step1 = squareSum - sum * sum / size;
    return step1 / (size - 1);
}

/**
 * Computes the standard deviation of this set.
 *
 * @return the standard deviation.
 */
public strictfp double getStandardDeviation() {
    return Math.sqrt(getVariance());
}

Either strictfp cascades, and you calculate the variance twice, but in different ways for toString(), or it doesn't, and in that case, no math is being done in this method and the keyword can go.


Using std::array to implement variadic construction of class with list-of-self as subclass

I have a few things to say about your code:

Do you intend to actually do things in the constructors instead of just displaying strings? Knowing this would help the review process. Currently, you do not store anything passed to Item, but if you intend to store things at some point, it may change things.
Instead of using &a[0] which is kind of obscure and not easy to find with a simple search query, you shoud use a.data() which clearly shows the intent.
It would probably be a good idea to pass the std::array by const reference in the constructor instead of passing it by copy. That will avoid useless copies:

template<size_t N>
Block (std::array<Listable, N> const& a) : Block (&a[0], N) { cout << "Barray\n"; }

Of course, that implies that you take const Listable* instead of Listable* at some point (but we come back to my first point: we lack information about what your code is supposed to do). I don't know what you intend to do with this, but passing a pointer to the underlying memory of a temporary doesn't feel right. This may create dangling pointers.

EDIT: since your code isn't supposed to store the pointer, then taking the std::array by copy shoud be safe. But as you noted in the comments, using an rvalue-reference parameters should be even better: it binds to the temporary, you can modify it and no copy is performed. Seems like the best solution.


This code is greatly improved!  Well done.  Still, there are some things that may help you improve your code.

Don't overspecify member functions

Within the Address_book.h file, the member functions are declared like this

void Address_book::resize(size_t entries);
void Address_book::sort();

But they should not include the class prefix in this context.  Instead, write them like this:

void resize(size_t entries);
void sort();

Be aware of signed vs. unsigned

Within the Address_book.cpp file, both functions include a line like this:

for (int i = 0; i < abook.add_book.size(); ++i) {

However, size() often returns an unsigned number, so it would be prudent to make i unsigned as well.  I'd recommend std::size_t as in

for (std::size_t i = 0; i < abook.add_book.size(); ++i) {

Use const where practical

Usually, an extractor (operator <<) does not alter the underlying object.  This is true of your code as well, which is good.  But to make it explicit, declare the parameter as const.  That is, the friend function should be this instead:

std::ostream& operator<<(std::ostream& os, const Address_book& abook);

Avoid the use of this in member functions

The code current contains this function:

void Address_book::sort() {
    std::sort(this->add_book.begin(), this->add_book.end());
}

However, it's usually not a good idea to explictly write this unless you have to.  I'd recommend shortening to this:

void Address_book::sort() {
    std::sort(add_book.begin(), add_book.end());
}

Think of the user

It's not so convenient to count the addresses manually first and then enter them.  Why not have the computer count them?  One simple way to do that would be to have a blank line or end of file signal the end of the input, avoiding the need for the user to manually count addresses first.


A StringBuilder is useful when you're constructing a string where a loop will be directly effecting it, i.e. if you were appending several strings together within a loop, I'd recommend using a StringBuilder. Here's an example of where you might use a StringBuilder.

StringBuilder sb = new StringBuilder()
for (int i = 0; i < someItems.length; i++)
{
    sb.AppendFormat("{0} is item index {1}\n", someItems[i], i);
}
return sb.ToString();

There are some overheads with string.Format, however they aren't huge, especially not in your case. Unless you're concerned about micro-optimisations, I think in this scenario it all falls down to readability, and which you prefer.

An alternative method, which would be slightly faster than string.Format is to simply concatenate the string together, like so:

public string getColumnText(String myParam)
{
    return "" + myParam + "";
}

You may also want to consider ensuring it's safe for your desired output, i.e. do you need to escape quotation marks for myParam, or does it need to be HTML encoded?


Using the stack algorithm for parenthesis matching

Make a separate stack class. Even if this is a one time thing it is good OO practice. Good encapsulation will not allow the main program to access the stack's internal structure, ptr for example. Methods like Stack.isEmpty() would be more user friendly. If popping "below the bottom" of the stack, it's better returning null rather than a specific out of range ptr value. I think the stack should be self-expanding, but if intentional design says it is fixed length then fine.
Design classes with excellent customer service built in.

if (ptr == -1)

I suggest ptr <= -1. This is really the condition and it is more error tolerant. What if some other bug decremented to -2 before this check?

Data structures to simplify code
We want to avoid this:
if(str.charAt(i)== '('|| str.charAt(i)== '{' || str.charAt(i)== '[')

Not extensible, error prone, hard to read. The goal is something like this:
if( OpenDelimiters.contains ( str.charAt(i) ) )

There might be OpenDelimiters, CloseDelimiters, PairDelimiter structures - that might seem like a lot but code gets real simple real fast as seen above. Adding delimiters means no code changes, just add to the data structures.

Edit - RE: if(ptr == -1)
This needs clarification. Please be patient, this is a case of something simple taking extensive explanation to show how and why it is wrong.
The big picture is this:

code the algorithm as precisely as possible
Don't assume simple code is bug free
Even correct arithmetic, at the bits and bytes level can be surprisingly inaccurate.
Make code robust because ongoing maintenance is toxic to code.
Develop good coding techniques that reduce bug risk and apply them consistently

Algorithm vis-a-vis Code
Pretend the program calculated ptr = -2 instead of -1. Then if(ptr == -1) does not catch it. What is the error, the arithmetic or the condition or both? Change the condition to if(ptr == -2) and the program is fixed, right? How about we just throw an exception, is the program fixed now? If it runs why not?

When pop()ing we need to catch "going off the bottom" of the stack. By definition that means an index less than zero. That algorithm definition is accurately coded as ptr < 0.

Given the above, if ptr is -2 - this is not a program error per se. The program will keep running correctly. The pop algorithm handles that condition - index is less than zero.
if ptr is -2 - now this must be coding error because we intended -1. Lucky we're testing for  < 0. Fix the arithmetic bug even if the conditional statement tolerates it. The arithmetic error and the conditional logic are two separate things. Arithmetic errors should be caught in testing. P.S.: throwing exceptions for arithmetic errors is just wrong!!
if(ptr == -1) is not an execution bug but it is wrong. The algorithm is not coded correctly. There is no arithmetic error yet code change has more potential for inducing execution bugs.  The program will fail if the value is anything except -1.

Bit-level numbers
Testing for exact values can bite you. It just became easier for me to quit testing for exactly -1 than to try to out smart the compiler or interpreter or my inadvertent bugs-waiting-to-happen or the idiot maintenance programmer (sometimes that was me).
Binary numbers in memory have inherent problems just like base-10 does. 1/3 in base-10 is .333... to infinity. Sometimes numbers converted to binary are like that.
Sometimes computation induces errors. For example the sum of a taylor series added "forward" can - will - be different from adding "backwards".  I.E. 1/2 + 1/3 + 1/4 + 1/5 ......   Do this for many thousand of terms and you'll see.
Even integer arithmetic can be quirky in some languages. JavaScript, for example, does not have integers. All numbers are stored as floating point in memory. Google "javascript the weird parts" and you'll see funky numeric WTFs.
end Edit


Game prototype with methods to manage players

Bug

In this code, what is the return targetName = name line trying to achieve?

function findPlayer(playerName) { // assigned on line 9
  console.log('found', playerName);
  function isPlayer(targetName) {
    return targetName = name;
  }
  return this.players.find(isPlayer);
}

name is undefined, and probably you wanted to use == instead of =.

Also, the function should not print found ...,
before actually finding anything.

Code organization

The functions that should be called on Game instances should not be in the global namespace.
Not only they pollute the global namespace,
they are not useful and misleading without a Game instance.

Also, unless you want to allow manipulating the players array directly,
it would be better to hide it from users.

Printing inside functions is a bad practice unless it is their dedicated purpose.

This would be a better organization:

function createGame(title) {
  var players = [];

  function addPlayer(name) {
    players.push({ name: name });
  }

  function findPlayer(name) {
    return players.filter(function(player) { return player.name === name; });
  }

  function printPlayers() {
    console.log('Player list:');
    players.forEach(function(player, index) {
      console.log(index, player);
    });
  }

  return {
    title: title,
    addPlayer: addPlayer,
    findPlayer: findPlayer,
    printPlayers: printPlayers
  };
}

"just-in-case" programming

You made it possible to chain calls to createPlayer, along with this comment:

return this; // in case you want to chain? not sure...

When you're not sure to implement something,
there's a really simple rule of thumb you can follow: don't do it.
Everything in the code should have a purpose,
avoid writing code "just in case it might be useful someday".


My take on implementing the Repository Design Pattern in PHP

The autoloading problem.
Using composer is probably the easiest way to autoload classes in PHP right now. You'll only have to declare namespaces, use them, and everything will work with only including the autoload file from composer once.
About your repository pattern implementation.
"Repository Interface"
Nope. Not true. You created an EventRepositoryInterface. The point of an interface is to expose an interface that can be shared by classes implementing it, to be able to modify them (or create other implementations) without having to change the code using them in the first place. Are you going to create a new EventRepository class ?
I'm pretty sure you actually wanted a RepositoryInterface that EventRepository will implement (as well as your other repositories).
EventRepository
This class should be able to handle the $data to make Events one by one, thanks to EventMapper.
Right now its only use is to avoid duplicating SQL requests through the code.
It should check the $data, loop over it, do whatever is needed to get a standard data format (such as an array). Then it should loop over this formatted data, pass each iteration to EventMapper and return an array of Events.
EventMapper
As said earlier, this class should only receive data for one Event and return only one aswell. Also, even though you should have sanitized $data beforehand, you still should check it in this class too. To end with a little nitpicking there, toEvent($data) is usually called hydrate($data).


Exceptions

Exceptions, by their nature, alter the control flow of the program. That's what they're there for. It's just that they should not be used for normal control flow – only in error cases. In your case, a job failing to execute is most likely an error case so I wouldn't object to the usage of exceptions here.

Question yourself, however, what kind of errors you are catching and how you handle them.

It seems that the first (outermost) try / catch block is intended to catch any exception that might be thrown by the job. This looks alright to me. We don't know the job and it might fail for any number of reasons. That should not affect our processing of further jobs. catching Exception also seems appropriate in this case, even though it is normally strongly discouraged. You could even consider catching Throwable but I like Exception better, thinking that if something that is not an Exception gets thrown, the program should probably die immediately.

Well, except that it doesn't.

You are not catching exceptions thrown by the job. Those will be thrown on its own thread and not seen by you. Instead, that thread's uncaught exception handler will deal with them. And the default exception handler – as sad as it is – simply prints a stack trace and otherwise ignores the exception. If you want to change that, you can set a custom uncaught exception handler.

The only case in which your catch gets activated is if creation of the thread fails. And in this case, you're probably in deep trouble anyway and should let your application die, eventually after logging an error. The recovery strategy in the catch is therefore inappropriate here. But let's assume for the following discussion that you've corrected this and the error handling code is in the thread that actually executes the job.

Okay, you have caught an exception from a job that failed for whatever reason. What can you reasonably do now? Your backup strategy is to simply push the job back onto the queue. I'm not sure whether this is a good idea. If some of your jobs can fail for spurious reasons, re-trying a fixed number of times might be a viable strategy. But re-trying forever almost certainly isn't. What if every once in a while you get a job that simply fails unconditionally. Then you keep pushing those jobs in your queue which will slowly but sure enough fill up with garbage jobs that will never succeed but consume precious resources and slow down the processing of jobs that have a real chance to do something useful. If you want to give each job \$n\$ chances, you could manage \$n\$ queues and move failed jobs from queue \$i\$ to queue \$i+1\$ if \$i<n\$ or else drop them onto the floor. Alternatively, you could attach a counter to each job that gets incremented for each failed attempt to execute it.

But your code also handles the case that you cannot push a job back to the queue. I'm not sure whether this is something you should handle. If you're out of memory, let your application die, maybe logging an error. I don't know the nature of your jobs but what good does it do you to have them written to a file? Will you ever re-load them from that file? And if you do, are you sure that this will be a good thing? Imagine that something awkward happens and your application gets flooded with nonsense jobs. Hopefully, it will eventually crash. But now the user re-starts it, hoping that it will behave sane again – only to find that it keeps loading the nonsense jobs from its file log and crashes again.

As a last resort, you log a fatal error. This is not an entirely bad idea. However, if all the things failed that lead up to this situation, I'd rather kill the application and not pretend everything will be fine. You can still log the error but after that, re-throw the exception and die.

I know that unit-testing error handling code can be challenging but I encourage you to do it nevertheless. Feed an intentionally poisoned job to your queue. Make sure that the exception gets caught where you think it should. If you give jobs a second chance, construct a job that fails the first but not the second time. Then construct one that always fails. Construct one that cannot be serialized. If you truly cannot construct a scenario that will execute an error handler, this might be an indicator that the handler is redundant and should be removed from the code.

As a general guideline, don't try to keep your application running no matter what. If things really get bad, giving up is the best thing you can do: „Dead Programs Tell No Lies“.

Readability

The code is not exactly readable. It already got a lot better after you've edited your question to use shorter names instead of the ones your application seems to use. Descriptive names are good but you can also overdo it. If your names simply are that long, I prefer to use auxiliary variables to keep if conditions and function calls reasonable.

What hurts readability more severely, though, is the triple nesting of try-catch blocks.  I suggest you refactor this like so.

boolean handleJob(final Job job) {
    try {
        return firstStrategy(job);
    } catch (final Exception e) {
        // Maybe report the error
    }
    try {
        return secondStrategy(job);
    } catch (final Exception e) {
        // Maybe report the error
    }
    try {
        return thirdStrategy(job);
    } catch (final ThridException e) {
        // Definitely report the error and give up
        return false;
    }
}

Refactoring deeply nested control structures into separate functions and using early returns is a generally useful pattern.

Concurrency

Your code spawns a new thread for each job and immediately detaches from it. This is a bad idea. Creating threads is costly and if you create significantly more than your hardware can execute in parallel, your performance will suffer. Instead of using one thread per job, use a thread pool with a fixed number of threads. This also means that you no longer have to use the threads uncaught exception handler for dealing with exceptions thrown by your jobs but can catch them much more naturally.

I assume that your code runs on Android which already has built-in support for background jobs so you don't even have to roll the code yourself. Just check it out.

The other thing that strikes me is that you simply sleep if your queue is empty. This is not a good strategy. If you set sleepTime1 too low, you'll waste a lot of CPU cycles (and battery) for doing nothing. If you set it too high, your application becomes unresponsive. Instead of sleeping and polling, use proper synchronization techniques. That is, wait() and notify().

1 The question has since been edited to use a hard-coded constant instead of the variable sleepTime.


Performance of Min and Max Sum of array in C#

Performance
The current solution does two things:

Sort the inputs,   O(N log(N))
Sum the inputs,    O(N)

It is possible to calculate the result in a single pass O(N) by reading through the inputs, keeping track of the min, max and sum as we progress and then subtracting the min and max from the sum as we are currently doing.

Note: For the current code

if(arr[i]>=1 && arr[i]<=Math.Pow(10,9))
     sum += arr[i];

does nothing useful, the problem definition says that the inputs are in the range [1,10^9] so the test will never fail.

Religious war trigger
I would push for always using braces around a block, even single line blocks. I have seen too many cases of

if(arr[i]>=1 && arr[i]<=Math.Pow(10,9))
     sum += arr[i];
     // do something else every time, not just when the test passes

The Hint
The 64- bit integer hint means that the sum of the values may exceed the maximum value for a int, so use a long for the sum.


Guard Clauses

You can save a level of nesting by using guard clauses. In this case, it just means removing the else:

auditLog($ES_Client, "Creating new user: ".$username.", ".$fullname.", ".$email.", ".$function.", ".$department.", ".$access);
$checkIfUserExists = getUserDetails($ES_Client,$username)['hits']['total'];
if($checkIfUserExists != 0){
    auditLog($ES_Client, "User ".$username." already exists! Operation aborted.");
    return -1;
}

$hashed_password = crypt($password);
[...]

Error Handling

First of all, your return values are quite confusing. If you were to check them, you would get code like this:

if (addNewUser(...)) {
    // handle the error
}

The problem is that 0 is actually false, while -1 is true. But really, returning integers as error codes is confusing and difficult to use. The numbers themselves don't have any meaning, so you always need to look up what they mean in the documentation (if it even exists).

If you just have a boolean state, you might as well return boolean values.

But really, I would prefer to throw exceptions. Not being able to add a user is an exceptional state after all. This also gives you the option of being more explicit about what went wrong, so a calling method may have a change to recover, or show a better error message to the user.

Hashing

Don't use crypt, especially not without additional arguments. The documentation explicitly warns against this, as it is not secure:

  The salt parameter is optional. However, crypt() creates a weak password without the salt. PHP 5.6 or later raise an E_NOTICE error without it. Make sure to specify a strong enough salt for better security.

You should just use password_hash.

Formatting

Your indentation is partly off.
You are not consistent with your curly bracket positions.
You are also not consistent with your use of spaces.

Use an IDE to fix all of these issues automatically.

Naming

You should be consistent with your variable names. Don't mix camelCase and snake_case without reason.

Generally, your variable names are very clear. But you could shorten some without loosing any meaning. checkIfUserExists for example may be userExists. Although this actually doesn't seem to represent what the variable actually holds (it holds some counter instead).


Instead of having a cache

private static Dictionary<string, ObjectCache> cacheStore;

you could have one keyed of the types:

private static Dictionary<Type, ObjectCache> cacheStore;

This means you don't need to call typeof(T).ToString() everywhere.
You duplicate the code of building the key in all 3 methods - it should be extracted into a private BuildKey(string userId, int year) method. This means if you need to change how the key is built you only need to touch one method rather than all of them.
I would provide a Register method which accepts a type for which to create a new cache rather than hard-coding it in.
The cache policy is also not configurable - which means you are stuck with it unless you want to change the code.
You really really should think hard about whether a static cache is the right way to go. It will give you trouble in unit testing and it will also make it impossible for multiple classes to have different cache with different policies for example.


Your current code
After a long investigation of the problem, I ended up solving more than what you are asking for. I totally misunderstood what your code were actually doing. I found out that your $numbers array is not interesting at all.
The output of your code, the variable $x is the Binomial coefficient for 6 choose 3. (Which is quite funny because in your question you asked about 7 numbers, but in your code you are using 6).
Your code is doing a whole lot of array_pop, next and prev which is just ugly. You need to spend more time thinking about what the algorithm is behind all of this.
Additionally, I don't know what you are intending to do with these lines:
$threes[] .= next($number);

Why use .= ? Last time I checked, .= is for string concatenation. What does that have to do with anything? And why do that when you add a new index to the array? That code does exactly the same as $threes[] = next($number);
You seem to add a whole lot of stuff to the $threes array, but you never end up using it.
Additionally, your $stake, $odds and even $slice seem totally irrelevant here.

Shortening your code
When removing everything related to $threes, and simplifying your multiple $x++ to one $x += ...; your code can be dramatically shortened:
<?php

    $numbers = [2, 8, 16, 30, 44, 48];
    $number  = $numbers;
    $x       = 1;
    echo implode(" | ", $numbers)."
";

    foreach ($numbers as $key) {

        if (count($number) == 6) {
            $x += 10;
        } elseif (count($number) == 5) {
            $x += 6;
        } elseif (count($number) == 4) {
            $x += 3;
        } elseif (count($number) == 3) {
        }
        array_shift($number);
    }

    echo "Total combinations of 3's: ".$x."
";

?>

Then, when removing some more fluff and using an integer variable instead of that $numbers array.
<?php

    $number = 4;
    $x       = 1;
    for ($i = $number; $i >= 0; $i--) {
        if ($i == 6) {
            $x += 10;
        } elseif ($i == 5) {
            $x += 6;
        } elseif ($i == 4) {
            $x += 3;
        }
    }

    echo "Total combinations of 3's: ".$x."
";

?>

So, your code is not very extensible in it's current form. It can only support 3's and a maximum $number of 6... That's not optimal.

A better approach
This is how I calculate the Binomial coefficient in Java - which is in use in my Minesweeper Flags Extreme project, translated into PHP
function nCr($n, $r) {
    if (($r > $n) || ($r < 0)) {
        return 0;
    }
    if (($r == 0) || ($r == $n)) {
        return 1;
    }

    $value = 1;

    for ($i = 0; $i < $r; $i++) {
        $value = $value * ($n - $i) / ($r - $i);
    }

    return $value;
}

echo nCr(8, 4); // Prints 70
echo nCr(6, 3); // Your code example, prints 20

It is very tempting to write $value *= ..., but avoid doing that as the results will not be the same in languages which separates integer division and floating division (not that PHP is one of those languages, but I would still recommend avoiding it).


Style

Python has a style guide called PEP8 which is definitly worth a read.

A few things can be improved :

function name does not respect convention
missing whitespaces
useless parenthesis
name str hides builtin str

Then your code becomes :

def starts_with_article(string):
    '''Return True if the first word of string is "The", "A" or "An"'''

    if string.startswith("The ") and string.find(' ') == 3:
        return True
    elif string.startswith("An ") and string.find(' ') == 2:
        return True
    elif string.startswith("A ") and string.find(' ') == 1:
        return True

    return False

print('"A boy" returned', starts_with_article("A boy"))
print('"An apple" returned', starts_with_article("An apple"))
print('"The cat" returned', starts_with_article("The cat"))
print('"Abyss" returned', starts_with_article("Abyss"))
print('"There" returned', starts_with_article("There"))
print('"Ant" returned', starts_with_article("Ant"))

Don't Repeat Yourself

You are doing the same thing multiple times. You could try to see what is similar and what changes and see if you can use a relevant data structures for the changing parts.

Here I stored the articles in a list to be able to iterate over them.

def starts_with_article(string):
    '''Return True if the first word of string is "The", "A" or "An"'''
    for article in ["The ", "An ", "A "]:
        if string.startswith(article) and string.find(' ') == len(article) - 1:
            return True

    return False

Don't repeat yourself (again)

You are looking for the article followed by a space and then you check if there is a space in the wanted position. There is no need for that check.

def starts_with_article(string):
    '''Return True if the first word of string is "The", "A" or "An"'''
    for article in ["The ", "An ", "A "]:
        if string.startswith(article):
            return True

    return False

Don't repeat yourself (again again)

I have to repeat the whitespace in the different elements of the list I a using. This is easy to forget if I ever need to add an article. Let's add the space as part of the logic.

def starts_with_article(string):
    '''Return True if the first word of string is "The", "A" or "An"'''
    for article in ["The", "An", "A"]:
        if string.startswith(article + ' '):
            return True
    return False

More Python good stuff

The any builtin seems to do what you are doing. Let's use it.

def starts_with_article(string):
    '''Return True if the first word of string is "The", "A" or "An"'''
    return any(string.startswith(article + ' ')
        for article in ["The", "An", "A"])

The best option: reading the documentation

If we look at the startswith documentation, we have:

  prefix can also be a tuple of prefixes to look for.

At that point, your problem is pretty much solved :-)


Some suggestions:

Your algorithm is not doing the same thing as the original.  The original randomizes the entire string each time, except the correct bits, while yours randomizes only one character each time.
You can iterate directly over lists.  So you don't need range(len(target)), you can just do for _ in target.
You should define string.ascii_letters + string.digits + string.punctuation + ' ' as a new variable on a separate line so you can re-use it.
You can use the modulus operator % to keep the index inside the correct bounds.


Selecting the "best" method in this case is likely going to come down to personal preference.

If you wish to use a condition-less one-liner, then insertusernamehere's offering is brief/elegant.  However, it is not instantly comprehensible for the next developer.

min(max($value, 0), 4)

If you want a one-liner with conditions (or without functions), then this is what Billal was mentioning:

$value < 0 ? 0 : ($value > 4 ? 4 : $value)

However, the php manual says:

  It is recommended that you avoid "stacking" ternary expressions.

I personally find switch statements to be too clunky/verbose with the breaking.  While it is nice that it only evaluates $value once, that is of very little benefit in your tiny use case.

Finally, I recommend simply changing your second if statement to elseif so that the second statement is ignored when the first is true.  This method will be fast, clean, and instantly comprehensible.

if ($value < 0) {
    $value = 0;
} elseif ($value > 4) {
    $value = 4;
}

...if > 4 occurs more often than < 0, then reverse the order of the conditionals.

Here is a demo snippet:

$input = [-1, 0, 2, 4, 7];
foreach ($input as $value) {
    echo min(max($value, 0), 4) , "\n";
    echo $value < 0 ? 0 : ($value > 4 ? 4 : $value) , "\n";
    if ($value < 0) {
        $value = 0;
    } elseif ($value > 4) {
        $value = 4;
    }
    echo $value , "\n---\n";
}


Avoiding multiple if conditions in a Car class

If you don't want to return early (because you want to go through all checks to warn about all problems), then you can use a flag to keep track of any problems:

for (Car car : carList) {
    boolean goodToGo = true;
    if (!car.engineOn()) {
        car.warn("How are you planning to participate in a race with an off engine??");
        goodToGo = false;
    }
    if (!car.driverBeltOn()) {
        car.warn("Please wear a damn belt!");
        goodToGo = false;
    }
    if (goodToGo) {
        // Vroooomm....
    }
}

Btw, I guess you forgot a return statement here:

public boolean driverBeltOn() {
    this.driverBeltOn;
}

And I recommend to rename your methods to isDriverBeltOn and isEngineReady, as it's a fairly common practice to prefix boolean getters with "is...".


IMO, there is a cleaner way to do this without even involving metatables. You have a bunch of tables that are nested together that contains some data on each level and you're looking to access and possibility modify a particular branch.

This is not that different from say a HTML DOM tree. This means you can use any standard tree traversal algorithm to find what you're looking for. For example, a table_gsub function(can't think of a better name atm), it takes a table, a string-key you're looking for, and a function to call when a match is found:

function table_gsub(t, selector, f)
    local visit = {}
    for k, v in pairs(t) do
        if type(v) == 'table' then
            table.insert(visit, v)
        end
    end
    if t[selector] then f(t) end
    for _, each in ipairs(visit) do
        table_gsub(each, selector, f)
    end
end

And a convert function to your desire format:

local function convert_format(t)
  assert(type(t.track) == 'string')
  for each in t.track:gmatch "%w[^#]+" do
    table.insert(t, {track = each})
  end
  t.track = nil
end

A simple test to make sure it does the right thing:

table_gsub(profiles, "track", convert_format)
dump(profiles)

It should output something like:

profiles = {
  Goblin = {
    Bars = {
      {
        {
          {
            track = "Cloak of Shadows"
          },
          {
            track = "Anti-Magic Shell"
          },
          {
            track = "Hand of Freedom"
          },
          {
            track = "Spell Reflection"
          }
        },
        {
          track = "..."
        },
        {
          track = "..."
        }
      }
    }
  }
}

You could of course take this idea further with multiple key-string selectors to match against giving you something like jquery-style lua table selection.


Multiple loops versus multiple stringbuilders

Stay with the first solution:

It is easier to read.

Using such a template is the least-obfuscated method to generate the output HTML, as the structure of the template directly corresponds to the structure of the output.

Another important aspect is that when embedding HTML into C# strings, you have to use many escapes.
This makes it harder to read.
I would expect the first template to have comparable or better performance.

Instead of micro-optimizing, one should usually optimize for maintainability first, and let the compiler do its thing. Before optimizing for performance, do a benchmark to find real bottlenecks.

I strongly suspect that the template engine is implemented in a non-moronic way, which means that internally a string builder is used.
Your second solution on the other hand incurs additional overhead by maintaining multiple string builders which are then joined to an intermediate string which are then stuffed into the template – that intermediate string is unnecessary.

But what about having fewer loops? The answer is that it doesn't matter from a theoretical perspective: Executing

foreach (x in things)
    a(x);
foreach (x in things)
    b(x);
foreach (x in things)
    c(x);

does the same amount of work as

foreach (x in things)
{
    a(x);
    b(x);
    c(x);
}

In practice there is some small overhead per loop, but this overhead is usually negligible when compared with the actual work done inside the loop. Do a benchmark to see if this overhead matters.
It appears to be more secure.

In your second solution, you directly interpolate arbitary strings into the HTML via AppendFormat.
Unless you have very good input validation, this would allow for spectacular injection attacks.
Better be safe than sorry, and escape everything.
This is much easier if you use the templating engine rather than doing everything yourself – it's too easy to forget something.

There is another consideration from an UX standpoint:
When reading tabular data, I expect each row to contain a record, and columns to contain different fields for that record.
This makes such data easy to parse by humans and computers alike.
Swapping the axes of your table also means that your template is ever simpler:

        Company
        Address
        Contact Details
        Remove

    @foreach (Customer c in Model.SelectedInstallers)
    {

                @c.Name

                @c.Street

                @c.City

                @c.County

                @c.Postcode

                @c.Telephone

                @c.Website

                    Remove installer

    }

While displaying data row after row scales very well to a large number of records, displaying items horizontally next to each other so that each item occupies a column makes it much easier to compare the data. However, this only scales well up to three items (in my experience), and horizontal scrolling is a big no-no.

Some notes regarding the HTML: The headings of columns or rows should use the  element. While you do this in the second template, the first template only uses plain s.
To style different rows differently, it is tedious to apply classes like first-row, even, or odd.
These not only invite name collisions, but can also be done with much less effort via CSS pseudo-classes such as :nth-child:

/* tr.first-row */
tr:first-child { ... }
/* tr.even */
tr:nth-child(even) { ... }
/* tr.odd */
tr:nth-child(odd)  { ... }

The disadvantage of this solution is that it won't work on older MSIE versions.
But in this case this wouldn't be a problem as the functionality of the table is not impaired – this is an example of progressive enhancement.


The following are a few suggestions on how I'd write the SQL statement.

Source Control

If you don't already have a database project, create one in Visual Studio. Then check it in to source control. Microsoft Azure DevOps Services is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.

Formatting

I would download the following tool for SSMS and Visual Studio, SQL formatter from ApexSQL. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.

Copy & Paste

If you find yourself copying and pasting the same string or number over and over in your query, then you should define it as a variable or create a table. Copy and paste is a design error ~ David Parnas

Commas

I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier.

Where Clause

If you put 1=1 at the top of a WHERE condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the 1=1 so it should have no performance impact. Reference

Common Table Expressions (CTE)

CTE's in your SQL, help with documentation. The expression name can then let other developers know why you used that expression e.g. post_body_filter.

Schema Names

Always reference the schema when selecting an object e.g. [dbo].[Posts].

Keywords

Avoid using keywords as object names. Microsoft Reference

Also check out the book Clean Code. It will change the way you think about naming conventions.

Revised SQL

Without table definitions and sample records I was unable to test this, but it should give you a good start.

WITH
Posts
AS
(
   SELECT tbl.* FROM (VALUES
    ( 1, '01-Jan-2020', 85, 'depend on context', 2)
   , ( 2, '02-Jan-2020', 86, 'base on Context', 2)
   , ( 3, '03-Jan-2020', 87, 'rely on context', 2)
   , ( 4, '04-Jan-2020', 88, 'Count on Context', 2)
   , ( 5, '05-Jan-2020', 89, 'lean on context', 2)
   , ( 6, '06-Jan-2020', 90, 'Take on Context', 2)
   , ( 7, '07-Jan-2020', 91, '... on context', 2)
   , ( 8, '08-Jan-2020', 92, ' on context ...', 2)
   , ( 9, '09-Jan-2020', 93, '... on context ...', 2)
   , ( 10, '10-Jan-2020', 94, '... on ... context ...', 2)
   , ( 11, '11-Jan-2020', 95, '...', 2)
   , ( 12, '12-Jan-2020', 96, '... on context ...', 1)
   ) tbl ([Id], [CreationDate], [Score], [Body], [PostTypeId])
)
,
post_body_filter --here it would be good to name the table expression so others will know why you're filtering them out.
AS
(
   SELECT tbl.* FROM (VALUES
    ( '%depend%')
   , ( '%base%')
   , ( '%rely%')
   , ( '%count%')
   , ( '%lean%')
   , ( '%take%')
   ) tbl ([Body])
)
SELECT
     [po].[Id]
    , [po].[CreationDate]
    , [po].[Score]
    , [po].[Body]
FROM
    [Posts] AS [po]
    LEFT JOIN [post_body_filter] AS [pf] ON [po].[Body] LIKE [pf].[Body] COLLATE SQL_Latin1_General_CP1_CI_AS
WHERE
  1 = 1
  AND [pf].[Body] IS NULL
  AND [po].[Body] LIKE '% on context%'
  AND [po].[PostTypeId] = 2
  ;

Results


This condition

else if (direction.x % 1 !== 0 || direction.y % 1 !== 0)

Doesn't check for integer and is (almost) always false, since direction.x is the result of Math.sign(), which returns an integer (1, 0, or -1) or NaN, which is the only time the condition can be true.

Use point.x instead. I would also use Number.isInteger() to check for integers. This check should also be at the start of your loop, since the first point of the input is currently not getting checked.

I'm not sure what this code is supposed to accomplish.

else if (direction.x === 0 && direction.y === 0) {
  return;
}

What is the desires behavior when you get two identical point after each other? Is it illegal? Throw an error. Should it keep both points? Don't do anything. Should duplicates be deleted? Replace return with continue so it won't get added to the result.


Find common elements in a list of arrays

In your code, you are using arrays to check whether the value is stored.  As you have noted, that operation is \$O(n)\$.  The solution to this is to use objects to check instead.  That operation is \$O(1)\$, meaning that the algorithm goes from \$O(n^2)\$ to \$O(n)\$.

However, there is a problem with storing using objects, namely that all keys need to be strings.  Because of this, we have to convert the strings back into integers after we are done.

Hence, our steps become:

Create a currentValues object.  Initialize it to contain the values of the first list.
Create a commonValues object, leave it empty.
For each of the arrays, except for the first:

Iterate through the array.  If currentValues contains the value, add it to commonValues
Set currentValues = commonValues, and reset commonValues to be an empty object again.

Finally, take the currentValues object, and convert its keys back into integers.

Some code that does the above (I'm no expert with Javascript, while the code works, there may be sub-optimal code here):

var arrays  = [
    [1, 4, 6, 78, 8, 9, 124, 44],
    [44, 6, 9],
    [124, 44, 16, 9]
];
function getCommonElements(arrays){//Assumes that we are dealing with an array of arrays of integers
  var currentValues = {};
  var commonValues = {};
  for (var i = arrays[0].length-1; i >=0; i--){//Iterating backwards for efficiency
    currentValues[arrays[0][i]] = 1; //Doesn't really matter what we set it to
  }
  for (var i = arrays.length-1; i>0; i--){
    var currentArray = arrays[i];
    for (var j = currentArray.length-1; j >=0; j--){
      if (currentArray[j] in currentValues){
        commonValues[currentArray[j]] = 1; //Once again, the `1` doesn't matter
      }
    }
    currentValues = commonValues;
    commonValues = {};
  }
  return Object.keys(currentValues).map(function(value){
    return parseInt(value);
  });
}
console.log(getCommonElements(arrays)); //Prints [9,44]


Firstly, you are missing a var exchange; in your function.

Heavily nested callbacks are no fun for anyone. I would consider using the async library to try to simplify the callbacks.

https://github.com/caolan/async#waterfall

Something like this. The callbacks passed to waterfall are called in series, and any arguments passed to each callback function after the err argument, are passed as the first parameters of the next function.

var that = this is just something you kind of have to get used to. In some cases you can avoid it by using various methods to bind the value of 'this' to the proper value.

Download.prototype.fundamentals = function(exchanges, cb) {

  var that = this,
      exchange = exchanges.pop();

  if (!exchange) return;

  async.waterfall([
    function(callback) {
      that.login(callback);
    },
    function(callback) {
      var path = util.format(that.eoddata.fundamentals['path'], that.token, exchange.code)
      that.get(that.eoddata.fundamentals['host'], path, callback);
    },
    function(data, callback) {
      that.xml(data, function(err, xmldata) {
        err = err || xmldata['@'].Message != 'Success';
        callback(err, xmldata);
      });
    },
    function(xmldata, callback) {
      var stocks = xmldata['FUNDAMENTALS']['FUNDAMENTAL']
      that.insert(stocks, exchange, callback);
      that.fundamentals(exchanges, cb);
    }
  ], function(err) {
    cb(err, exchange.code);
  });
}


HTML: The only change is that they are wrapped in a div id'ed container which will be used in event handling, explained below.

First Question

Second Question

Third Question

JS: Explained in the comments

//shorthand for $(document).ready(fn) is $(fn)
$(function () {

        //container will be used for delegated event handling
    var container = $('#container'),
        //since questions remain static, it's best we reference ahead of time
        questions = $('.question',container);

    //take advantage of delegation which assigns one handler to the parent
    //for all events in it's descendant. Here, we place a handler on container
    //for all question instead of putting a handler per question
    container.on('click', '.question', function (event) {
        var question = $(this);

        //we use 'next' which directly gets the next sibling instead of siblings(selector).
        //though internal implementations might be the same, but at least we avoid
        //writing that many selectors in our implementation
        question
            .next()
            .slideToggle(400);

        //using the referenced questions, we remove the currently clicked, pick
        //their answers that are currently visible and slide them up
        questions
            .not(question)
            .next(':visible')
            .slideUp(400);
    });
});

Here's running code. It's more of a readability and maintainability optimization rather than performance.


First of All you should be using setAnimationListener on animation object. so no need of Handler

progressAnimation.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {
       fireResultActivity(-1); // call your method here
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }
});

As it has built-in listener for Animation, there is no need to create new thread using handler


First of all, putting all your code in the props of your JSX is making it unreadable. Extract this into a function, and have your JSX reference that instead.

Next, for debugging, I would recommend using breakpoints to debug code. console.log() is fine for a quick peek, but it introduces a lot of noise in the code.

Also, when you expand a logged object in the console, you see the object's structure at the time of expanding, not at the time of logging. The object's contents may have already changed between the time it was logged and when you expanded it. If you're not aware of this quirk, you'll easily think your code is broken.

For promises, you're really just mapping. Use array.map() instead of array.reduce(). For emailsMapped, which is also just a mapping operation, since you're adding multiple items, use array.flatMap() for that.

Lastly, you can modify your code so that you can chain the promises instead of nesting them. You can return the promise of axios.all() to chain it to your axios.get().

store.dispatch(dispatchFunc => {
  dispatchFunc({ type: "FETCH_DATA_START" });
  axios
    .get("https://reqres.in/api/users?page=2")
    .then(response => {
      const promises = response.data.data.map(({ id }) => {
        return axios.get(`https://.../comments?postId=${id}`)
      })

      return axios.all(promises)
    })
    .then(responses => {
      const emailsMapped = responses.flatMap(({ data }) => {
        return data.map(({ email }) => email)
      })

      dispatchFunc({
        type: "RECEIVED_DATA",
        payload: emailsMapped
      })
    })
    .catch(err => {
      dispatchFunc({
        type: "FETCH_DATA_ERROR",
        payload: err
      })
    })
})

Now that we've established a more linear flow via chaining, we can take this a bit further and convert it to an async function so that we can use await:

// Note the async here
store.dispatch(async dispatchFunc => {
  dispatchFunc({ type: "FETCH_DATA_START" });

  try {
    // Note the various await before each asynchronous function call

    const response = await axios.get("https://reqres.in/api/users?page=2")

    const promises = response.data.data.map(({ id }) => {
      return axios.get(`https://.../comments?postId=${id}`)
    })

    const responses = await axios.all(promises)

    const emailsMapped = responses.flatMap(({ data }) => {
      return data.map(({ email }) => email)
    })

    dispatchFunc({
      type: "RECEIVED_DATA",
      payload: emailsMapped
    })
  } catch (err) {
    dispatchFunc({
      type: "FETCH_DATA_ERROR",
      payload: err
    })
  }
})


This is missing the point of polymorphism. Its great strength is that you don't need to know or care about the type. With your code, you still need to check type using the instanceof operator.

One way to resolve this is using a variation on the command pattern. First, define a common interface (I used an abstract class) that all three implementations can inherit from. Let call it QueryParameter:

abstract class QueryParameter {
    protected final int index;

    public QueryParameter(int index) {
        this.index = index;
    }

    public abstract void addTo(QueryStatement queryStatement);

}

Now you define three implementations. Here is the String version:

class StringParameter extends QueryParameter {
    private final String value;

    public StringParameter(String value, int index) {
        super(index);
        this.value = value;
    }

    @Override
    public void addTo(QueryStatement queryStatement) {
        queryStatement.setString(index, value);
    }

}

Now, you may construct an arbitrary number of parameters and save them in a collection. Once you've got your QueryStatement ready, simply call the addTo() methods of every parameter in no particular order and you're done!

final Set<QueryParameter> params = new HashSet<>();
//Add bunch of parameters.
params.stream().forEach((param) -> param.addTo(queryStatement));

Of course there are many ways to go about doing this, my example is not necessarily the best fit for you.


let vs const is fundamentally an ES6+ issue:

constCreates a constant whose scope can be either global or local to the block in which it is declared. An initializer for a constant is required. You must specify its value in the same statement in which it's declared.

// wrong
const timer;
// Uncaught SyntaxError: Missing initializer in const declaration

// right
const timer = 60;

letAllows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. Please note that a let variable is initialized to a value only when a parser evaluates it.

function do_something() {
  console.log(bar); // undefined
  console.log(foo); // ReferenceError
  var bar = 1;
  let foo = 2;
};

With that said, change the declaration to let timer;

// Within the first `useEffect`
useEffect(() => {
     let timer; // change this
     if (secCount > 0) {
       timer = setInterval(() => {setSecCount(secCount - 1)}, oneSec);
     }
     if (secCount === 0 && minCount > 0) {
       timer = setInterval(() => {setSecCount(60)}, oneSec);
     }
     return () => clearInterval(timer);
   }, [secCount]);
```


Click a link to delete targeted content using Ajax

I only see two things to "reduce", regarding the line amount.

The if statement in the success callback could be replaced by a ternary operator.
The last e.preventDefault() is redundant, you can squarely remove the whole else part.

$(document).ready(function () {
  $("body").on("click",".delCommentLink",function (e) {
    e.preventDefault();
    var comment_url = $(e.target).parent().attr("href");
    var $commentEle = $(e.target).closest(".comment");
    if (window.confirm("Delete this comment?")) {
      $.ajax({
        type: "get",
        url: comment_url,
        success: function (data) {
          var ret = JSON.parse(data);
          (ret['status'] == 1) ? $commentEle.hide() : alert(ret['msg']);
        },//success
      });//ajax
    }
  });//click event
});

That is 6 lines less...


A faster way to look up for a url in a WebRequest/WebResponse html

I would bet that the regex.Match is the performance problem, as Jeff Atwood describes here.
One thing that I would do is move regex definition to a static variable outside of the function defined as below:
static Regex regex = new Regex(@"WMV Download", RegexOptions.Compiled);

That's the only real thing that jumps out at me. Try taking a look at this blog post for more ideas and information.
Should give you something to try until guys with more experience glance their eyes over it :)


Reading a text file that may have embedded nulls

I find your code hard to read, for the following reasons:

the variable file is not really a file but a buffer
the variable f (which usually stands for file) is a pointer into that buffer
the variable a has a name which does not convey any meaning at all
if the first if statement you indent the brace in the next line, and in the very last if statement the body is in the same line
there are spaces missing in the code at places where I expect them, such as after an if or for
the forever loop is usually written as for (;;), not for( ; ; )
the main block of the code is inside the for loop, and there's not a single empty line in that part. This suggests that the whole block is doing a single thing with no possible interruption or logical break
the comma operator is generally frowned upon
is_done is not really about the work being done, it's more about being successful

Because of all the above reasons, I would write the code differently:

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char buf[1000];
    size_t buflen = 0;
    const size_t granularity = 80;

    while (true) {
        if (granularity > sizeof buf - buflen) {
            errno = ERANGE;
            break;
        }

        size_t nread = fread(buf + buflen, 1, granularity, stdin);
        if (ferror(stdin))
            break;

        buflen += nread;
    }

    for (size_t i = 0; i < buflen; i++)
        printf("%02hhX ", buf[i]);
    fputc('\n', stdout);

    if (ferror(stdin)) {
        perror("stdin");
        return EXIT_FAILURE;
    }
}

And here is what I changed:

I renamed all variables to match their purpose
I replaced the various pointers into the buffer with indexes
I removed the is_done variable since the program should not print an error just because the file is a multiple of 80 bytes
I moved the variable a to a smaller scope by declaring it inside the for loop where it is used; I also renamed it to i, since it is now an index instead of a pointer
I replaced the comma operator with an if statement, since that is the form that is commonly used
I included <stdbool.h> to have a boolean type and the constants true and false
I replaced for (;;) with while (true), which is less magic
I sorted the included headers alphabetically since for headers from the C standard library, the order doesn't matter
I renamed the variable read to nread, to avoid possible conflicts with the POSIX function of the same name