You define the comparison function like this:

function(a, b) { return a - b }

and then you use it like this:

if (f(x, y) <= 0) { ... }
if (f(x, y) > 0) { ... }

This is a bit tedious. It would be more intuitive like this:

function(a, b) { return a <= b }

and use it like this:

if (f(x, y)) { ... }
if (!f(x, y)) { ... }

Why is it faster?

I don't know, but as @Flambino commented:

  I browsed around the V8 source code and the sort function does a lot of stuff, namely handling sorting of non-array objects, arrays with "holes", and similar cases. All of that before actually sorting anything. I have no idea what exactly is causing the slowdown, but, as mentioned, there's just a lot of stuff going on there. Their implementation is also sorting in-place, which could be a contributing factor. But I honestly haven't dug that deeply

How to make it faster?

Changing the comparison function like this:

function(a, b) { return a < b }

and the bubble sort condition to use 6 instead of 8 (in if (end - start < 6) { ...), together, often yielded faster result in my test runs, but not always, and I don't think that means anything.

The bottom line: I don't know...

Naming and formatting

The code would be more readable if you improved some of the names. For example renaming a and a2 to part1 and part2, respectively. Or even arr1 and arr2. It would make them look more like arrays, instantly.

This may be a matter of taste, but instead of this:

var x = a[i], y = a[i+1];
if(f(x, y) > 0) {a[i] = y; a[i+1] = x;}

I would find this slightly more readable:

var x = a[i];
var y = a[i + 1];
if (f(x, y) > 0) {
    a[i] = y;
    a[i + 1] = x;
}


A few fairly obvious points:
Prefer nullptr over NULL
Unless you really need to support older compilers, you're generally better off using nullptr in new code. If you do use nullptr, you can still support older compilers if really necessary--it's basically just a class that provides conversions for pointer to T and pointer to member.
Prefer member initializer lists over assignment in a constructor
The most obvious example here would be to replace your node constructor:
Node(T val, Node *nxt=NULL) {
    value = val;
    next = nxt;
}

...with one using a member initializer list:
Node(T value, Node *next = nullptr) :
    value(value),
    next(next)
{}

Note that yes, in this case, although the parameter being used to initialize it have the same name, but the compiler can keep track of which is which anyway.
Rule of three/five/zero
Note that in virtually every case, if you provide a destructor and a copy ctor, you also want a copy assignment operator. If you want the better efficiency you can get from move construction/move assignment available in C++11 and later, you'll probably want to add overloads of those that accept rvalue references. I consider it open to debate whether the rule of zero really applies well in this case--I've written a linked list that used smart pointers, but I was never entirely happy with it. It's clumsy but workable in the case of a singly linked list. For a doubly linked list, it's...basically unmanageable.
Side Note
Contrary to your statement, if you don't include a copy ctor, you probably won't get correct results with this sort of class. In particular, the compiler will generate code that does a shallow copy, so only the head pointer in the LinkedList object will be copied. This means if you copy a linked list, you'll end up with both pointing to a single head node. In itself that's not necessarily a problem, but when either of those is destroyed, all the nodes in the list will be destroyed, so in essence you've just destroyed both linked lists, not just the one you intended to. Attempting to use or destroy the one that wasn't supposed to have been destroyed yet will give undefined behavior.


stat the word count for a given stackexchange user

Reviewing your T-SQL script I see that you have a cursor to iterate over Posts from a specific owner. For each body you use a neat trick to determine the word count of the body and use an extra variable to keep the running sum. You use FORMATMESSAGE to shape the data in each row.
Do know that the neat trick for the word count doesn't compensate for cases where two or more spaces are used, or where words are not separated by spaces but by other characters, like line-breaks for example. I'll ignore the fact here that in case of Posts.Body not only the text is stored but also the HTML markup.
I find the script clear and well structured.
If you're looking for an alternative way to accomplish the same output (I ignore the formatting here) I can offer this SEDE query:
DECLARE @UserId int = ##UserId##  -- SDE parameter syntax

SELECT Id
     , LEN(Body ) - LEN(replace(Body , ' ', '')) [count]
     , SUM(LEN(Body ) - LEN(replace(Body , ' ', '')))
         OVER (ORDER BY id) [total count]
FROM posts
WHERE posts.OwnerUserId = @UserId
ORDER BY Id

I have started with your base query as found in the CURSOR but instead added the third column with an OVER( ORDER BY id) clause which enables the calculation of running totals over sets.  I'm a firm believer that when there is a feature available in the language it should be the preferred option, instead of running your own version in script. There is also a higher chance this gets better optimized by the query plan, if not today then possible in the future. Looking at wall-time and the query plan for your version and mine seems to support my gut feeling.
If you want to address the neat trick there are different ways to solve that, for example by evaluation the answers on  Removing repeated duplicated characters but all of those have pros and cons and without confirmation if this is an area you want to have addressed I assume for now you're fine with your method.


Just as adjoin-set simply became cons, union-set can be defined as:

(define union-set append)


Before I answer your question I should point out that:

list = to_a if Range

is incorrect. Range is a constant and if Range is always true. You probably means if is_a?(Range) which would mean list was undefined in most cases.

As a first attempt at solving this I would take the case where an operator is provided and have the method call itself with a block something like below.

module Enumerable
  def my_inject(*args)
    unless block_given?
      operator = args.delete_at(-1)
      initial  = args.first
      return my_inject(initial) { |accumulator, i| accumulator.send(operator, i) }
    end

    list = is_a?(Range) ? to_a : self

    accumulator = args.first
    list.each { |item| accumulator = accumulator ? yield(accumulator, item) : item
    accumulator
  end

end

Note: I didn't test this or check its complexity.

This code is also incorrect. There is actually a difference between an initial value that is not provided and one of nil. It is also possible for the block to to return nil which would cause the yield block not to be called for that iteration. The real solution is to check args.length not just args.first but that would increase your complexity.

To do this properly and still pass Rubocop's checks for complexity (as well as its other checks) you will need to break this method up into a few smaller methods.


Why is it specific to the two properties you have currently? I think it would make sense to make it more generic, but I can't think of a good design to do that.

sealed class RequestScoped : IDisposable

Is it okay for users to call Dispose() by themselves? If not, don't make this type IDisposable and don't make Dispose() public.

private static readonly object key = typeof(RequestScoped);

Since other pieces of code have access to typeof(RequestScoped), they could potentially read or overwrite the RequestScoped instance that's stored in the context by accident. To be on the safe side, I would use new object() here.

/// This method is not thread-safe.

I'm not sure you need to call this out here. Especially since this method is thread-safe, as long as different threads use different contexts.

public static RequestScoped GetOrCreate(System.Web.HttpContext context)

The fact that this method either gets existing object or creates a new one sounds like an implementation detail to me. I would probably call it just Get().

Why are you repeating the namespace for HttpContext instead of using using?

public IDbConnection OpenConnection { get { return connection.Value; } }

Is "open" here supposed to be a verb or an adjective? If verb, then that's not appropriate for a property. If adjective, then it's I think it's not necessary.

public SessionRepository SessionRepo { get { return sessionRepo.Value; } }

I don't see any reason to shorten "repository" to "repo" here, SessionRepository is not that long.

public void Dispose()
{
    if (connection.IsValueCreated)
    {
        try
        {
            if (connection.Value.State == ConnectionState.Open)
            {
                connection.Value.Close();
            }
        }
        catch (Exception)
        {
            // ignore
        }
        connection.Value.Dispose();
    }
}

Why are you not disposing SessionRepository? Is that not necessary?

Also, why are you trying to call Close() and then also call Dispose()? Isn't just Dispose() enough?


Multiple files data processing in Clojure

Don't forget about for

Consider using for instead of map in places where you use an anonymous function with map.  This particularly applies to the outer-most map, since with map what you are maping over is sort of hanging by itself at the end of the code.

(def data
  (for [fsc (->> (clojure.java.io/file "data")
                 (file-seq)
                 (rest))))]
    (->> ...)))

In this case in particular, what you are processing is made more clear with for.

Break the code up into (named) functions

In a similar vein to using for, consider breaking the code up into named functions.  While anonymous functions are obviously sufficient, a good name can bring a lot of clarity to your code.

At minimum, I would put functions like #(* % %) inside a let or letfn:

(let [square (fn [x]
               (* x x)]
  ...)

But if you think you have a use for the same function in other places, make it a top-level definition:

(defn square [x]
  (* x x))

Consider using fn in favor of #(...)

Personally, I eschew the use of #(...) reader syntax to define functions and just use fn instead.  I think the #() syntax was a well-intentioned solution to a largely non-existant problem (verbose anonymous functions), and to the extent anonymous functions are verbose in Lisps, the #() syntax is a poor replacement.  It's barely shorter than an equivalent fn form, arguably more difficult to grok (based on the questions I've seen surrounding it on stackoverflow), and has some fundamental limitations (e.g., can't be nested).

Obviously, this is a very subjective view, and certainly not everyone agrees with it.

Use comments to add clarity

Be sure to use comments to provide high-level descriptions of lower-level operations.  For example, there are a couple places where you use rest to skip the first element in a sequence.  A comment in these places indicating why this element needs to be skipped would go along way.

Likewise, consider adding comments for the major blocks of the code -- i.e., high-level descriptions of each of the loops.  Simple one-liners should be sufficient for most of these.  You might want a little more description for the mergeing part, though, since that seems to be the core of the logic.


What you done looks good but I am wondering if it is not a bit over-engineered.

Here's what I would have done (which is probably under-engineered) :

#include <iostream>

enum TimeUnit
{
    Second = 1,
    Minute = Second*60,
    Hour   = Minute*60,
    Day    = Hour*24,
    Week   = Day*7
};

class Time
{
    public:
        Time(int n = 0, TimeUnit unit = Second) :
            value(n*unit) {};

        bool operator==(const Time& other) const {
            return (value==other.value);
        }

        int convert(TimeUnit unit = Second) const { return value/unit; }

    private:
        const int value; // Assumed to be in seconds.
};

int main()
{
    Time s0;
    Time h0(0,Hour);
    std::cout << (s0 == h0);

    Time s3600(3600);
    Time s3600bis(3600, Second);
    Time m60(60, Minute);
    Time h1(1, Hour);
    std::cout << (s3600 == s3600bis && s3600bis == m60 && m60 == h1);

    return 0;
}

My point is to just take into account the fact that a time is just a value and a unit. We store the value in the easiest format and we convert it on demand. No conversion is actually required for comparison. Adding a new Unit is straightforward (assuming there is a constant factor to multiply - month and year wouldn't work because they do not always last the same time).


Both portions of code could be simplified if you use numbers, instead of words, to represent upvotes and downvotes. So I would change your calls to sendVote to look like this:

sendVote(this.parentNode, 1);
sendVote(this.parentNode, -1);

When modifying elements with javascript, I suggest using element.style.x (or element.style.cssText for multiple attributes) instead of classes, where possible. This is more efficient (browser doesn't have to re-test css selectors for the rest of the page), simpler (don't have to polyfill classList), and it means putting javascript-only css in js files, which means they aren't loaded in browsers that don't support javascript and therefore don't want them anyway. But the main reason is that is allows you to shorten your code to this:

var voteCSS = {
    '1': 'background:blue;',
    '0': 'background:grey;',
    '-1': 'background:red;'
};

function sendVote(element, newVote) {
    var countEl = element.querySelector('.m p'),
        prevVote = +element.dataset.prevVote || 0;

    if (newVote == prevVote)
        newVote = 0;
    countEl.innerHTML = +countEl.innerHTML - prevVote + newVote;
    element.dataset.prevVote = newVote;
    element.style.cssText = voteCSS[newVote];
    // ajax here to /votes/submit?id=x&direction=`newVote`
}

Alternatively, if you want to keep all your CSS in one place, you can make sure that "upvoted" or "downvoted" is the only class the element has, then just use .className. You could still apply default styling by selecting it from above, something like this: .votecontainer div {}.

ps: notice that I didn't use jQuery even once. Try to solve your problems without jQuery before you let yourself use it - a lot of the time you'll find that your solutions are simpler and more efficient without it.


Listening from Mongodb always and triggering

I'm in doubt if your code actually works as you instantiate using obj = first(), but your class is named first_level(). This kind of indicates that either you've left out code, or you have broken code.

Anyway, here are some pointers for you:

Imports should go at start of file – It's generally considere bad style to import stuff within classes or functions
The connection you create is forgotten – You should store the connection, as it is killed when __init__ is completed. You should use something like self.connection = pymongo.... If your code actually is working, then it is because the self.testXXX keeps it alive
Vertical space is good, but you've got too much – The common policy is to have two blank lines in front off functions and classes, and single lines in front of different part you want to differentiate a little from other blocks.
Increase horizontal space – After commas or colons you could benefit from adding spaces. Instead of insert({"_id":value2,"bit":value}) do insert({"_id": value2, "bit": value})
Add comments and/or docstrings – It is hard to read what your code actually does, and why it does it. This should be commented upon.
Avoid busy tight loops – Doing while True with a single function not doing much, is a tight busy loop, and should usually be avoided. At least if doing it this way, you should add a sleep somewhere to avoid hogging resources.

A better solution related to MongoDb

However instead of doing a busy loop with some code which I don't fully grasp, I believe you should look into the monitoring of the mongodb. This would allow you to get notified when commands are executed against the mongodb.

At least, that is how I read the documentation, with little knowledge of mongodb. And this pattern of adding a listener, and then waiting for it to respond is a bettern pattern rather than busy waiting and changing stuff to check if it is alive.


Naming

Class name: Solution A solution for what?
Method name: solution - again I ask: Solution for what?
Parameter name: S - And what on earth is S? Parameter names are by convention named beginning with a lowercase letter.

None of these three names are descriptive names. It is easier to read and understand code when the names tell a bit about what it is that the code does. Now, naming things are hard, and something that programmers do a lot. For this case, consider names such as BracketNestingVerifier, verify and input. You might even be able to come up with better names.

General things

Use Generics for your HashMap. Since Java 1.5, it's been possible to define which kind of HashMap it is. Is it a HashMap of <Integer, String>? <String, Byte>? No, in your case; it's HashMap<Character, Character>
Why do the method return an int when it would make much more sense to return a true/false boolean? Returning a boolean allows you to simplify the end of your method

if (last == -1) { // note the fixed spacing ;)
    return 1;
}
return 0;

To simply return (last == -1);

Spacing

I find that code like this:

for(int i=0; i<S.length(); i++){

Is much more readable if you use spacing (and a better variable name for S of course)

for (int i = 0; i < input.length(); i++) {

Algorithm

Now, about that algorithm... You have a variable called stack and yet it isn't a stack structure, it's only an array. Using a somewhat real stack structure can be helpful. In the code below, I have used the LinkedList class to provide this structure (Even though there is also a Stack class, I like the Deque interface and wanted to go with LinkedList).

In this code, I have improved the variable names, the return type, and I am using a HashSet to store all "special" characters in. The contains method of a HashSet is performing in constant speed, so you should not experience any significant lack of performance. I noticed that in your if-statement, you had hard-coded the values that were put into your HashMap, this is what made me want to add the HashSet.

To make this work, I had to flip the key/values of your HashMap. The key is now the starting character, and the target is the expected ending character.

The loop through the string here is pretty simple and straight-forward:

Have we waited for this character? If so, remove it from the list of expected characters we are waiting for (The "stack")
If the above is not true, does this character have a matching ending character? If it does, add it to the stack
Again, if the above also is not true, is this character regarded as a special character? If it is, then we know here already that we have failed so we can return from the method.

public boolean simonsVerify(String input) {
    HashMap<Character, Character> matches = new HashMap<Character, Character>();
    matches.put('{', '}');
    matches.put('(', ')');
    matches.put('[', ']');

    Set<Character> specialChars = new HashSet<Character>();
    Deque<Character> expected = new LinkedList<Character>();
    for (Entry<Character, Character> ee : matches.entrySet()) {
        specialChars.add(ee.getKey());
        specialChars.add(ee.getValue());
    }

    for (int i = 0; i < input.length(); i++) {
        char next = input.charAt(i);
        Character expect = expected.peekLast();
        if (expect != null && expect == next) {
            expected.removeLast();
        }
        else if (matches.containsKey(next)) {
            expected.addLast(matches.get(next));
        }
        else if (specialChars.contains(next)) {
            return false;
        }
    }
    return true;
}

Here is the testing (with JUnit) I used, for both your original code and also for my method:

@Test
public void testVerifying() {
    assertTrue(verify("{,},({,}),[,]"));

    assertFalse(verify("{(,},({,}),[,]"));
    assertFalse(verify("{,)},({gfdgfd}),[,]"));
    assertFalse(verify("{(,}),({,}),[,]"));

    assertTrue(verify("{,},(,),[[,]]"));
    assertTrue(verify("{,},(,),[,]"));
    assertTrue(verify("{{,}},(,),[,]"));
    assertTrue(verify("{,},((,)),[,]"));
    assertTrue(verify("{,},(,),[,]"));
    assertTrue(verify("(), {{{,}}},(,),[,]"));
}

There might even be a better way to do this algorithm, this is just my way.


Pull, Tag, Save, Delete Multiple Docker Containers

Global variables

These:

cli = docker.APIClient(base_url="unix://var/run/docker.sock")
current_dir = os.getcwd()
repository = sys.argv[2]
tar_dir = os.path.join(current_dir, "move")

probably shouldn't live in the global namespace. Move them to a function, and feed them into other functions or class instances via arguments.

Command-line arguments

Use the built-in argparse library, if not something fancier like Click, rather than direct use of sys.argv. It will allow nicer help generation, etc.

Boolean comparison

if path.exists(tar_dir) is not True:

should just be

if not path.exists(tar_dir):

Pathlib

Use it; it's nice! For instance, if tar_dir is an instance of Path, then you can replace the above with if not tar_dir.exists().

It should also be preferred over manual path concatenation like f"{repository}/{img}"; i.e.

Path(repository) / img

there are other instances that should also use pathlib; for instance rather than manually appending .tar, use with_suffix.

Split unpack

img_t = image.split(":")
img = img_t[0].strip()
t = img_t[1].strip()
image = f"{img}:{t}"

can be

image, t = image.split(':')
image_filename = f'{image.strip()}:{t.strip()}'


Shell agnostic startup flow - env, profile, rc, login

These repeated statements are really ugly:

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "* In .bash_profile"
[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.common_env if it exists"

You can do better by using a function, for example:

msg() {
    [ "$MY_STARTUP_DEBUG" = true ] || return
    echo "$@"
}

msg "* In .bash_profile"
msg "\t* Sourcing ${HOME}/.common_env if it exists"

Extra to: I removed the double-quotes around true, as that's unnecessary.

Whenever you see repeated logic, try to use a function.
Here's another helper function that can simplify much of the code:

source_if_exists() {
    msg "\t* Sourcing $1 if it exists"
    [ -f "$1" ] && source "$1"
}

source_if_exists "${HOME}/.common_env"
source_if_exists "${HOME}/.bash_env"

Note that in the original code, you forgot to double-quote the parameters of the source commands.


Python worker pattern for multithreading

1. Introduction

From a practical point of view, the most important points are that Python has batteries included:

To run tasks in a pool of worker threads, use concurrent.futures.ThreadPoolExecutor.
But if what you really want to do is run external programs via the shell, as suggested by the use of os.system, then you don't need threads at all! Use subprocess.Popen instead.

(Note that on some operating systems, notably macOS, you can only have one call to os.system running at a time. Subsequent calls, even from other threads, have to wait for the first call to finish. On these systems you have to use subprocess.Popen if you want the subprocesses to run in parallel.)

Nonetheless I think it's a good exercise to have a go at writing your own thread pool, and so I'm go to look at how you might improve the code in the post. There's quite a lot of ground to cover, so I'm going to take it in stages, starting by reviewing improving the code in the post, and then identifying and fixing various problems with the design.

2. Initial review

There are no docstrings. How do I use this module? Which classes are public and which are private? Do I create my own Worker objects or do I let the Pool create them for me? What kind of object do I pass for queue? How should I specify the timeout?
The Pool constructor takes timeout and output arguments but these have no effect: they are passed to Worker.__call__ but then they are ignored.
The Pool class has only one method (other than __init__). When you have a class with just one method, then what you need is a function. Not everything needs to be a class! It would simplify the code if it were turned into a function with a specification like this:

def run_shell_commands_in_parallel(commands, max_threads):
    """Run shell commands in parallel. max_threads is the maximum
    number of threads that may run simultaneously.

    """

Running a shell command is not very general. It would make sense to generalize the code to do arbitrary function calls in parallel:

def apply_in_parallel(fun, args, max_threads=4):
    """Apply fun to each of the arguments in parallel. max_threads is the
    maximum number of threads that may run simultaneously.

    """

To try to run a bunch of shell commands in parallel, you'd call it like this:

apply_in_parallel(os.system, ['command1', 'command2', ...])

but now you can use it for other parallel tasks:

apply_in_parallel(print, range(10))

The main thread calls workers.pop(0) and the worker threads call workers.append(self), but the workers data structure is just an ordinary Python list, which is not thread-safe. Whenever you have a data structure that's shared between threads, access to the data structure needs to be synchronized, for example by using a lock to ensure that only one thread can be updating it at a time.
All the Worker objects are identical — their only attribute is self.pool, and that's the same for every worker, so instead of a list of workers all we really need is a count of how many workers are idle.

3. Revised code

Fixing the issues in §1 above yields the following, which does essentially the same thing as the code in the post, but in a simpler way:

def apply_in_parallel(fun, args, max_threads=4):
    """Apply fun to each of the arguments in parallel. max_threads is the
    maximum number of threads to run simultaneously.

    """
    available_workers = max_threads
    available_workers_lock = Lock()

    def worker(arg):
        nonlocal available_workers
        fun(arg)
        with available_workers_lock:
            available_workers += 1

    for arg in args:
        while True:
            with available_workers_lock:
                if available_workers:
                    available_workers -= 1
                    break
        Thread(target=worker, args=(arg,)).start()

4. Problem: busy-waiting

The while True: loop is busy-waiting. If it takes a long time for a worker to become available, the main thread will be wasting effort by repeatedly taking the lock and testing the condition if available_workers: which remains false.

What we'd like instead is to be able to suspend the main thread until a worker becomes available. For this use case what we need is a semaphore, and Python provides us with threading.Semaphore:

from threading import Semaphore, Thread

def apply_in_parallel(fun, args, max_threads=4):
    """Apply fun to each of the arguments in parallel. max_threads is the
    maximum number of threads that may run simultaneously.

    """
    available = Semaphore(max_threads)

    def worker(arg):
        fun(arg)
        available.release()

    for arg in args:
        available.acquire()
        Thread(target=worker, args=(arg,)).start()

5. Problem: can't tell when threads are done

The code in §4 starts the shell commands but does not wait for them all to complete. But in many use cases it is important to wait for workers to finish running before proceding.

To ensure that all threads have finished, we must join them before returning:

from threading import Semaphore, Thread

def apply_in_parallel(fun, args, max_threads=4):
    """Apply fun to each of the arguments in parallel and wait until all
    calls have completed. max_threads is the maximum number of threads
    that may run simultaneously.

    """
    available = Semaphore(max_threads)

    def worker(arg):
        fun(arg)
        available.release()

    threads = []
    for arg in args:
        available.acquire()
        thread = Thread(target=worker, args=(arg,))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

6. Problem: too many threads

The code in §5 creates a new thread for every task, and every thread exits after completing its task. This defeats one of the purposes of having a pool of threads, namely that it avoids some of the overhead of creating new threads by reusing the threads in the pool.

The usual approach to implementing a pool of threads is for each thread to execute another task when it is finished (so long as there are more tasks to run). That means that the main thread is going to need a safe way of sending the tasks to the running threads, and Python provides queue.Queue which is exactly what we want:

from queue import Queue
from threading import Thread

def apply_in_parallel(fun, args, max_threads=4):
    """Apply fun to each of the arguments in parallel and wait until all
    calls have completed. max_threads is the maximum number of threads
    that may run simultaneously.

    """
    queue = Queue()

    def worker():
        while True:
            arg = queue.get()
            fun(arg)
            queue.task_done()

    for _ in range(max_threads):
        Thread(target=worker).start()
    for arg in args:
        queue.put(arg)
    queue.join()

7. Problem: threads are left dangling

The problem with the implementation in §6 is that the worker threads never finish! When all the tasks are done, each worker thread is blocked in queue.get waiting for the next task, but it will never arrive. This is a dangerous resource leak because the number of threads that we can create is limited by the operating system, and so to ensure that we can continue to create new threads later in the program, we must clean up all the threads that we started.

So when all tasks are done, we must tell the threads to exit. A convenient way to do that is to pass in a special sentinel argument that is different from any argument that the caller could pass in:

from queue import Queue
from threading import Thread

def apply_in_parallel(fun, args, max_threads=4):
    """Apply fun to each of the arguments in parallel and wait until all
    calls have completed. max_threads is the maximum number of threads
    that may run simultaneously.

    """
    queue = Queue()
    sentinel = object()

    def worker():
        while True:
            arg = queue.get()
            if arg is sentinel:
                break
            fun(arg)

    threads = []
    for _ in range(max_threads):
        thread = Thread(target=worker)
        threads.append(thread)
        thread.start()
    for arg in args:
        queue.put(arg)
    for _ in range(max_threads):
        queue.put(sentinel)
    for thread in threads:
        thread.join()


Implementation of generic Graph class and Dijkstras

Just a small remark design-wise:

I think you should not extend Node to DijkstraNode, but rather have a Node<Dijkstra>.  Or, if you intent to store info in the DijkstraNode, have a Node<Dijkstra<T>>.


I agree with Adam's comment. Generally, you should avoid rolling-your-own JSON. Just create native CF objects as usual (ie CF arrays and structures). Then use SerializeJSON to generate the JSON string.

SerializeJSON eliminates the need for manual quoting, which dramatically improves the readability of the code IMO. It also handles any escaping of object values automatically (the current code does not). Granted, Adobe's SerializeJSON function does have a few .. "quirks". So you may prefer to use a different implementation. However, the basic approach remains the same.

string function getJSON() output="false"    {
  var result = [];

  for(var row in this.qryLocation)  {
    arrayAppend(result, [ row.LocationID, row.Address & " " & row.City, row.formatted_CreateDate ] );
  }

  return serializeJSON(result);
}


I haven't run the code, but are you sure it does as you expect it to for odd length strings? By padding the last character with a space, you get some... interesting results.

For example, inputting "foo" will return "of o". That doesn't seem quite right to me. I would expect it to return "ofo".  I would do something like this.

private string StringSwap(string stringToSwap)
{
    char[] array = stringToSwap.ToCharArray();

    // even size strings iterate the whole array
    // odd size strings stop one short
    int offset = (stringToSwap.Length % 2)
    for (int i = 0; i < array.Length - offset; i += 2)
    {
        char temp = array[i];
        array[i] = array[i + 1];
        array[i + 1] = temp;
    }
    return new String(array);
}

Essentially, when the mod of 2 equals zero, the code behaves exactly like yours does now, but when the mod of 2 equals one, the loop exits one iteration early, avoiding the IndexOutOfRangeException that prompted you to hack in that white space.

Also note that I changed

    return new string(array);

To

     return new String(array);

It's terribly picky and pedantic, but I find it poor form to use the string alias when you're using it as a class. Seeing a ctor called on a camelCased identifier just looks weird to me. Same goes for things like string.Empty. But, like I said, that's just me being nit picky and pedantic. It's not actually a problem.


Keep-alive
Your sleep method is curious. There are alternates here:
https://stackoverflow.com/questions/20170251/how-to-run-the-python-program-forever
but those are generic to Python; there is a better option for gRPC:

In this case, you can call server.wait_for_termination() to cleanly block the calling thread until the server terminates.

Stopping
You should not only call it on KeyboardInterrupt; you should put it in a finally:
    server.start()
    try:
        # ...
    finally:
        server.stop(0)

This way, the server will be stopped if the user breaks with Ctrl+C, or if there is any other exception. However, I doubt it's necessary to call this at all if you use wait_for_termination.


Rotating an Image using own algorithm in python

The most common method for getting rid of the black dots is to paint over each pixel of the entire destination image with pixels copied from computed positions in the source image, instead of painting the source image pixels into computed positions in the destination image.

for i in range(660):
    for j in range(660):
        xb = int(...)
        yb = int(...)
        if xb in range(self.width) and yb in range(self.height):
            emptyF[i, j] = self.img[xb, yb]

Computing destination pixels positions from the source pixel positions may result in tiny areas unpainted in the destination due to numeric errors/limits.

Computing source pixels positions from the destination pixel position may result in a pixel value being copied to two adjacent locations, and other pixels never being copied from, but this is usually/often unnoticeable.


Cache-optimized matrix multiplication algorithm in C

The block size shouldn't be 12 (more like 1 to 2 orders of magnitude bigger), but I don't know exactly what it should be and it's easier to try some values and see how they work out than trying to predict it.. Likely the blocks shouldn't be square either (and therefore, not all three the same shape), because the eventual kernel will "prefer" a certain direction over the other.

There are inherent inefficiencies in multiplyMatrices due to its "shape" and we can calculate in advance what shape it should have. The Intel(R) Xeon(R) E5-2695 v3 has the Haswell micro-architecture, which has these key properties:

Vector FMA per cycle: 2
Vector FMA latency: 5
Vector loads per cycle: 2
Vector size: 256bit (4 doubles)

This means that, in order to max out the amount of arithmetic that happens, we will need at least 2*5=10 (the throughput-latency product) independent vector accumulators. Unrolling by 2 was a good start, but not close to what is required. Just unrolling more would be easy but there is more to it.

The limited number of loads, only a 1:1 ratio with FMAs at most (otherwise it starts to eat into the arithmetic throughput), means that we must somehow re-use data within a single iteration of the inner loop. Having two loads for each FMA (loading elements from each matrix) is twice the budget, that's definitely out.

So the inner loop itself needs to have a somewhat rectangular footprint to enable data re-use, and that rectangle needs to have an area of at least 10 4-wide vectors. For example it could be 2x5, 5x2, 3x4, 4x3.. that's about it. It can't really be bigger, then we would run out of registers, and spilling accumulators is super out. 3x5 seems like it could be possible, but it does not only require 15 accumulators but also some extra registers to hold the values from the input matrixes and it won't fit. By the way an other way to view the "rectangular footprint" is unrolling the outer two loops. The above sizes are all in numbers of vectors, so in a scalar view one of the directions gets 4 times as big again.

As an example (consider this mainly clarificational as in "how to put all of the above abstract-sounding considerations together into code" and not so much "copy&paste code") I'll pick 5x2 (20x2 scalars). That means the main part of the code would look something like this:

#include <x86intrin.h>

// must be multiple of 20
#define BLOCK_H 120

// must be multiple of 2
#define BLOCK_W 128

// this is the number of columns of mat1 and the number of rows of mat2
// has no relation to the size of the result block
// can be whatever
#define BLOCK_K 128

void matmulBlock(double *result, double *mat1, double *mat2) {
    size_t i, j, k;
    __m256d sum0, sum1, sum2, sum3, sum4;
    __m256d sum5, sum6, sum7, sum8, sum9;
    __m256d tmp0, tmp1, tmp2, tmp3, tmp4;
    __m256d m1, m2;
    size_t N = BLOCK_H;
    for (i = 0; i < BLOCK_W; i += 2) {
        for (j = 0; j < BLOCK_H; j += 20) {
            sum0 = _mm256_load_pd(&result[i * N + j]);
            sum1 = _mm256_load_pd(&result[i * N + j + 4]);
            sum2 = _mm256_load_pd(&result[i * N + j + 8]);
            sum3 = _mm256_load_pd(&result[i * N + j + 12]);
            sum4 = _mm256_load_pd(&result[i * N + j + 16]);

            sum5 = _mm256_load_pd(&result[i * N + j + N]);
            sum6 = _mm256_load_pd(&result[i * N + j + N + 4]);
            sum7 = _mm256_load_pd(&result[i * N + j + N + 8]);
            sum8 = _mm256_load_pd(&result[i * N + j + N + 12]);
            sum9 = _mm256_load_pd(&result[i * N + j + N + 16]);

            for (k = 0; k < BLOCK_K; k++) {
                m1 = _mm256_set1_pd(mat2[i * N + k]);
                m2 = _mm256_set1_pd(mat2[i * N + k + N]);

                tmp0 = _mm256_load_pd(&mat1[k * N + j]);
                tmp1 = _mm256_load_pd(&mat1[k * N + j + 4]);
                tmp2 = _mm256_load_pd(&mat1[k * N + j + 8]);
                tmp3 = _mm256_load_pd(&mat1[k * N + j + 12]);
                tmp4 = _mm256_load_pd(&mat1[k * N + j + 16]);

                sum0 = _mm256_fmadd_pd(m1, tmp0, sum0);
                sum1 = _mm256_fmadd_pd(m1, tmp1, sum1);
                sum2 = _mm256_fmadd_pd(m1, tmp2, sum2);
                sum3 = _mm256_fmadd_pd(m1, tmp3, sum3);
                sum4 = _mm256_fmadd_pd(m1, tmp4, sum4);

                sum5 = _mm256_fmadd_pd(m2, tmp0, sum5);
                sum6 = _mm256_fmadd_pd(m2, tmp1, sum6);
                sum7 = _mm256_fmadd_pd(m2, tmp2, sum7);
                sum8 = _mm256_fmadd_pd(m2, tmp3, sum8);
                sum9 = _mm256_fmadd_pd(m2, tmp4, sum9);
            }

            _mm256_store_pd(&result[i * N + j], sum0);
            _mm256_store_pd(&result[i * N + j + 4], sum1);
            _mm256_store_pd(&result[i * N + j + 8], sum2);
            _mm256_store_pd(&result[i * N + j + 12], sum3);
            _mm256_store_pd(&result[i * N + j + 16], sum4);

            _mm256_store_pd(&result[i * N + j + N], sum5);
            _mm256_store_pd(&result[i * N + j + N + 4], sum6);
            _mm256_store_pd(&result[i * N + j + N + 8], sum7);
            _mm256_store_pd(&result[i * N + j + N + 12], sum8);
            _mm256_store_pd(&result[i * N + j + N + 16], sum9);
        }
    }
}

By the way I didn't test this, I converted it from code that is tested, but it was single precision and row-major and some miscellaneous differences, I may have made some errors in changing it just now. Even if its works, this is ultimately not the most efficient code, this is just step 1: writing code to fit the basic parameters of the machine - it's not optimized beyond that.

Some assumptions are made: result and mat1 both 32-aligned, and zero padding in empty areas (same block size always).

GCC 4.8.5 needs -mfma to compile this but cannot take -march=haswell yet.


Is the use of Struct or Class personal preference?

This MSDN Page states:

  CONSIDER defining a struct instead of a class

  if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

  AVOID defining a struct unless the type has all of the following characteristics:

  It logically represents a single value, similar to primitive types (int, double, etc.).
  It has an instance size under 16 bytes.
  It is immutable.
  It will not have to be boxed frequently.

So if you want to use a class instead of a structure, you can just add the same static goofy method, to get the same style like you get with the structure:

   public static retclass goofie(int isn, string ss)
    {
        retclass dex = new retclass();
        dex.str = ss;
        dex.num = isn;
        if ((dex.str != "") && (dex.num > 0))
        {
            dex.yesno = true;
        }
        return dex;
    }

You can either add this to the Main or better inside the class itself. If you consider the second, you can call it like:

retclass x = retclass.goofie(3, "this is the reclass string");

Console.WriteLine("The String is {0}, the int is {1} and the value
      is {2}", x.str, x.num, x.yesno);


Writing out names of files on local C drive to a text document

First of all, you shouldn't hardcode values like your C:\ or C:\ComputerFiles.txt. If you want to change this, you don't want to edit it at multiple places.

static void filesArray(string path)

The usual .Net naming convention for methods is PascalCase (you'll notice that Main has to follow this convention).

Also, filesArray is pretty bad name for this method. It doesn't tell you what the method does (that it prints somethings). On the other hand, it tells you about an implementation detail (it uses an array), which it shouldn't.

static void addFilesToTextFile(string[] fileArray)

Whenever you call this method, you open and then close a file. I'm not sure about this, but it could add a measurable overhead, considering that you're going to have huge amount of directories.

return (Directory.GetDirectories(path));

The outer parentheses are not necessary here, remove them.

static void Main(string[] args)

If you're not going to use command-line arguments, you can safely remove the args parameter.

DateTime t1 = DateTime.Now;

To measure runtime of your program accurately, you should usually use Stopwatch instead of DateTime. Though if the time is on the order of 50 s, you don't need millisecond accuracy, so DateTime is probably okay.

while (moreDirectories == true)

This whole loop could be simplified if you used Queue<T>. Something like:

//Get array of primary directories in C drive
var directories = new Queue<string>(getDirectories("C:\\"));

//Go through each directory
while (directories.Count > 0)
{
    string directoryName = directories.Dequeue();

    try
    {
        filesArray(directoryName);

        foreach (var subdirectory in getDirectories(directoryName))
            directories.Enqueue(subdirectory);
    }
    catch (Exception)
    {
        Console.WriteLine("Unathorized to access directory: {0}", directoryName);
    }
}

If you don't like that foreach, you could easily create an extension method for it, called something like EnqueueRange().

catch(Exception)

If you're expecting unauthorized access errors, then you should catch UnauthorizedAccessException, nothing else.


Calculation of duration between two timestamps in different rows

You are not giving enough details (such as specific table structure, index, volume, types of queries, etc.) nor your constraints.

Nor do you explain how you come with value 108.

So my answer supposes you have only two timestamps per traceid and that the events are ordered logically in the same order as the timestamps.

SELECT
TIMESTAMPDIFF(MICROSECOND,
    STR_TO_DATE(MIN(`timestamp`), '%Y-%m-%dT%H:%i:%S.%fZ'),
    STR_TO_DATE(MAX(`timestamp`), '%Y-%m-%dT%H:%i:%S.%fZ'))
FROM applogs
GROUP BY traceid

This gives you 6319 which is a number of microseconds between the two. No idea on how you come to 108 from there. Note that it works only if you change your values to have only 6 digits after the dot, as the parser searches for microseconds. See here and the documentation.

If you really need your sub microseconds format you will need to split the string in two, first part being what is used above and last part being the last 3 digits as fractions of microseconds. And then add all of it.

This begs to ask why you are storing such a timestamp in a text field, this is not a good design. That would be the main point of the review: change your model and do not store timestamps in text fields, use the appropriate types of your RDBMS.

PS: since timestamp is the name of a type I do not recommend naming your column with it. Also, on the modeling part, your structure seems to reflect a key-value pattern, which is not always a good idea in RDBMS.


First of all I would highlight a security problem: you're directly exposing your implementation to service users. They just need to try different Client-IDs to connect to different databases. Connection string should be deduced by your application logic from client's authentication (whatever you use for this).

testApi() does not follow common .NET naming guidelines, method names should be Pascal case: TestApi() (also I would consider to use a little bit more descriptive name, TestServiceConnection(), maybe). The same apply for testApiService (TestApiService) and your local variable _myService (prefixes such as _ are controversial but - when used - they denote member fields, not local variables or parameters).

Also classes testApiService and testApiRepo has same naming issue.

BaseConnection is abstract, you'd better also declare its constructor as protected.
_connectionString is initialized only in constructor then it should be marked as readonly.
ConnectionString constructor parameter should be camel case: connectionString.

In GetOpenConnection() you're using a boolean flag mars, they should be used sparely because reading GetOpenConnection(true) you don't immediately understand what it means (true...what?) and whenever possible they should be replaced with enum or different methods. I'd also consider to do not have a default value: do you really call it so often you want to save those few characters?

Be careful when you create and return disposable objects, if something goes wrong creating MyDbConnection (again it should be myDbConnection, also better name is required) object then an exception is thrown and connection isn't immediately destroyed: when a SQL connection is popped from pool is an implementation detail you should not rely on.

All your classes are public and none of them are sealed. Will they be used outside assembly where you declared them? If not then they should not be public. Also TestApiRepo should be renamed and marked as sealed.

There isn't much more I can say about these snippets but I think you should change little bit your architecture. For example what you call BaseConnection in reality is not a connection! It's a factory class where you build connection objects (MyDbConnection) and testApiRepo has nothing to do with that factory (it should not be a derived class) but, instead, accept factory as parameter (or a connection string and then instantiate your ConnectionFactory class).


JavaScript function to convert underscore-case to camel-case (and vice-versa)

Tests

Your test code isn't the clearest. Assuming the rest of the code works as it should, then you should look into making your tests clearer and more reliable.

As it stands, you don't give any expected value for the test results. Having that would enable you to throw an error if the result is wrong as well as if the method throws. Consider something like this:

var tests = [
    {
        'toChange': 'ThisIsPascalCase',
        'toCase': 'toUnderscoreCase',
        'expected': 'this_is_pascal_case'
    }
];

tests.forEach(function(test) {
    var result = changeCase(test.toChange, test.toCase);
    if(!result) {
        console.error("Something has gone wrong!");
        // log extra error details if you want them
    }
    else if(result !== test.expected) {
        console.error("Result doesn't match expected result!");
        // log extra error and environment/stack details
    }
    else {
        console.log("Test passed successfully.");
    }
});

That makes your test code clearer, and provides you with accuracy checking.


As already explained in this answer, there is no need to use a class with an instance method here. In addition, the convention for function names in Python is to use snake_case, not camelCase.

On the other hand, this template is given on the LeetCode submission template, so you are not free to change it.

What you can do is to make the required solution method a wrapper for a free function (which then is universally usable):

def nth_super_ugly_number(n: int, primes: List[int]) -> int:
    # ...

class Solution:
    def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
        return nth_super_ugly_number(n, primes)

Generating the ugly numbers can be separated from counting them (until the nth ugly number is reached) if the former is done with a generator. The generator is now a reusable function as well, and you might want to add a docstring comment:

def super_ugly_numbers(primes: List[int]) -> int:
    """Generate super ugly numbers.

    Super ugly numbers are positive integers whose all prime factors are in
    the given prime list.
    """

    heap = [1]
    seen = set()
    while True:
        num = heapq.heappop(heap)
        yield num
        for p in primes:
            if num * p not in seen:
                seen.add(num * p)
                heapq.heappush(heap, num * p)

def nth_super_ugly_number(n: int, primes: List[int]) -> int:
    ugly_numbers = super_ugly_numbers(primes)
    for _ in range(n - 1):
        next(ugly_numbers)
    return next(ugly_numbers)

The last function can be simplified using itertools.islice:

import itertools

def nth_super_ugly_number(n: int, primes: List[int]) -> int:
    ugly_numbers = super_ugly_numbers(primes)
    return next(itertools.islice(ugly_numbers, n - 1, n))


Checking if a student ID is present in the database

mysql_ is deprecated, and it has been for quite a while. It will be removed in PHP 7, so you should not use it anymore.
you are open to SQL injection. Never put variables directly into SQL queries, always use prepared statements.
if you use prepared statements, you could prepare your queries only once, and then execute them with multiple different values, which might increase your performance.
use one connection across your code instead of creating new ones for every query (this can increase your performance).
profile your code to find out what actually causes performance problems. There is no need to "improve" code that is not causing problems. My guess would be that the curl request is the bottleneck, but without profiling, it's hard to say.
return early to reduce your level of nesting. Eg if (!$cond) return false (or throw an exception).
don't just silently fail, as it will be extremely difficult to debug your code this way. You silently fail if the httpcode of your curl request isn't 200, you silently fail if you can't create a database connection, etc.
don't die in functions, it makes it impossible for the calling code to recover. Throw an exception instead. If you do die, at the very least add a message stating the reason for it, as it will otherwise be really hard to debug your code.


Paginating blog posts from SQL server using nested LINQ statements

Your linq in linq in linq statement is written as a one-liner, with a single semicolon:

return (from b1 in ((from b2 in ((from b3 in dbSet.Include(b3 => b3.Category).Include(b3 => b3.User)
                                  orderby b3.CreationDateStamp ascending
                                  where categories.Contains(b3.CategoryId)
                                  select b3).Take<Blog>(page * pagecount)).Include(b2 => b2.Category).Include(b3 => b3.User) // step one
                     orderby b2.CreationDateStamp descending
                     select b2).Take<Blog>(pagecount)).Include(b1 => b1.Category).Include(b3 => b3.User) // step two
        orderby b1.CreationDateStamp ascending
        select b1).ToList<Blog>(); // step tree

In other words, it's doing too many things - you even have comments to identify the steps!

LINQ queries don't execute until they're materialized - you can take advantage of that and split the complex query into smaller steps that don't iterate the results.

Step one, grab all items up to the end of the desired page - this could be in its own method:

private IEnumerable<Blog> FetchItemsUpToSpecifiedPage(int page, int pageSize, IEnumerable<int> categories)
{
    return (from blog in dbSet.Include(item => blog.Category)
                              .Include(item => blog.User)
            orderby blog.CreationDateStamp ascending
            where categories.Contains(blog.CategoryId)
            select blog)
           .Take(page * pageSize);
}

Notice the following:

pagecount is renamed to a more accurate pageSize; "page count" sounds like like the number of pages, but what you want it to convey is the number of items on a page.
Meaningful identifiers. blog makes for easier reading than b3.
The compiler infers the generic type argument of Take<T> from the source parameter of the extension method, so specifying it is redundant and clutters up the code.

Step two, filter for specified page - again, in its own method:

private IEnumerable<Blog> FilterForSpecifiedPage(int page, int pageSize, IEnumerable<int> categories)
{
    var items = FetchItemsUpToSpecifiedPage(page, pageSize, categories);
    return (from blog in items.Include(item => blog.Category)
                              .Include(item => blog.User)
            orderby blog.CreationDateStamp descending
            select blog)
           .Take(pageSize);
}

Step three, sort and select - at that point that can go inside GetByPage:

public IEnumerable<Blog> GetByPage(int page, int pageSize, IEnumerable<int> categories)
{
    var items = FilterForSpecifiedPage(page, pageSize, categories);
    return (from blog in items.Include(item => blog.Category)
                              .Include(item => blog.User)
            orderby blog.CreationDateStamp ascending
            select blog)
           .ToList();
}

Now, this is strictly equivalent and improves nothing but readability, by un-nesting the queries.

I believe the .Include calls are redundant anywhere other than in the final step, in GetByPage - by including them so deep in the query you're carrying more data than you actually need along the way; I'd try removing them in the two private methods, and see if I get the same results.

Notice I'm returning an IEnumerable<Blog> and not a List<Blog> - the client code shouldn't be adding or removing items from this result set, and so doesn't need a List<Blog>. Rather, it merely needs to enumerate the results, so IEnumerable<Blog> is enough for its needs. And it's an interface, so you're not tying your hands with a specific implementation either.

Your pagination seems rather inefficient, you're sorting back and forth and back again.

Instead of sorting backwards and Takeing, you could look into what Skip can do for you - I believe it could boil down to something like this (untested):

return (from blog in dbSet.Include(item => item.Category)
                          .Include(item => item.User)
        where categories.Contains(blog.CategoryId)
        order by blog.CreationDate)
       .Skip((page - 1) * pageSize)
       .Take(pageSize)
       .ToList();

...which basically means, scratch pretty much everything I said above about extracting to private methods :)


Program to move in a 2d array given instructions, array and starting position

A loop that does different things based on how many times the loop has executed is a code smell.  It's harder to understand then breaking the loop into discrete steps.
And put it in a function.  Pass in the file, so you can use a file or io.StringIO instead of sys.stdin for testing.
def load_problem(file_input):
    r, c, k = map(int, file_input.readline().strip().split())

    instructions = file_input.readline().strip()

    room = [file_input.readline() for _ in range(r)]

    return room, instructions

Simplified find_start() a bit:
def find_start(room):
    for r,row in enumerate(room):
        c = row.find('O')
        if c >= 0:
            return r,c

Code to solve the problem can go in another function.
A set() is great for keeping track of places you've visited.
The duplication of code can be eliminated by using the instruction to select an x-step (dc) and y-step (dr) to be added to the current position.
STEP = {
    '>':( 0, 1),
    'v':( 1, 0),
    '<':( 0,-1),
    '^':(-1, 0)
}

def solve_problem(room, instructions):
    r, c = find_start(room)

    visited = set()
    visited.add((r, c))

    for instruction in instructions:
        dr, dc = STEP[instruction]

        while room[r + dr][c + dc] != '#':
            r += dr
            c += dc
            visited.add((r, c))

    return len(visited)

Drive the whole thing:
room, instructions = load_problem(sys.stdin)
result = solve_problem(room, instructions)
print(result)


Efficent way of synchronizing between data

I think you have two main choices, have the components throw events when they dirty the data.

The plus here is that events are extremely multithreaded friendly.
the minus is the program might have to know about how to sync the dirty data.

The other option is to have an abstract class with two methods doWork() and sync().
First run a parallel call to all the components.dowork
The when all completed run down each components.sync()

This has the plus of the program not knowing about data sync but the component stores its own dirty list and is very customizable as a result..
This has the minus of the components knowing about data sync.


Two implementations of a PHP sign-up page

Escape the hashed password, don't hash the escaped password.... just hash the pw.
Prefer prepared statements over escaping.
Break up the logic into functions.
Please indent better - your formatting is a bit of a mess.
You do not need to use both escaping and prepared statements. Pick one. (Pick prepared statements)

Edit:

In this case, if your IDs are integers, you don't need to escape them or use prepared statements. Just check if they are integers first with is_numeric(). If you know they're integers then you know they're safe.

Generally though, prepared statements are the way to go.


Removing nodes with a given value from a linked list

The input asking for which value to delete can/should be placed in a separate function.  Then the function to remove the nodes can take that value as a parameter.

The two malloc calls for temp and curr near the top are completely unnecessary and just leak memory.  You want to remove nodes, so you shouldn't have to allocate any memory.

If your list consists of a single node where val == x (or, more generally, all nodes in the list have that value), your program will crash.

If the last node in the list matches the value (and there are other nodes that don't), you'd be leaking that node except that you will be stuck in an infinite loop.  You shouldn't need to handle the last node any differently than removing any other node.


The only way to guarantee that the generated filename is truly unique is to actually create the file.  Any other method is vulnerable to a race condition.  Therefore, if you are serious about uniqueness, you should change

public static string CreateFileName(string directory, string filename, bool AppendNumberIfNameAlreadyExists = true)

to

/// Creates a file in the directory with the given filename
///
/// <param name="AppendNumberIfNameAlreadyExists">
/// If true, then a numbered suffix (starting from 0) is appended
/// to the filename if necessary to avoid a name clash.
///
/// If false, then an IOException is thrown if the file already exists.
/// </param>
public static FileStream CreateUniqueFile(string directory, string filename, bool AppendNumberIfNameAlreadyExists = true)


Secure row insertion using a position-based prepared statement

As noted in your other question, that exception handling completely masks the true exception.  It adds no value yet detracts.  There's no reason to do that.  Just allow the exception to throw out of the function.

As for 'security', assuming you properly control the table name, it is safe.  (A better way to phrase that may be that SQL injection is not possible as long as you control $table.)

I might consider writing it a bit differently though:

public function database_add_row($table, $data) {
    $placeholders = implode(', ', array_fill(0, count($data), '?'));
    $sql = "INSERT INTO {$table} VALUES ({$placeholders})";
    $stmt = $this->database->prepare($sql);
    if ($stmt->execute($data)) {
        return $this->database->lastInsertId();
    } else {
        return false;
    }
}

I also might consider using associative arrays.  That would allow you to specify columns (which could be useful if you had default-valued columns or auto incrementing columns).

public function database_add_row($table, $data) {
    $cols = array_keys($data);
    $columns = implode(', ', $cols);
    $placeholders = implode(', ', array_map(function($c) { return ":{$c}"; }, $cols));
    $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
    $stmt = $this->database->prepare($sql);
    if ($stmt->execute($data)) {
        return $this->database->lastInsertId();
    } else {
        return false;
    }
}

Then you would use it like:

$obj->database_add_row("table1", array('column1' => 'val1', 'column2' => 'val2'));

Depending on how far you plan to go with your DB abstractions, you might want to consider a DBAL or ORM library.  The Doctrine Project has quite widely used versions of both of those.


Conversion between enum and string in C++ class header

I would use some template logic to achieve the affect in a more scalable way:

#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>

// This is the type that will hold all the strings.
// Each enumeration type will declare its own specialization.
// Any enum that does not have a specialization will generate a compiler error
// indicating that there is no definition of this variable (as there should be
// be no definition of a generic version).
template<typename T>
struct enumStrings
{
    static char const* data[];
};

// This is a utility type.
// Created automatically. Should not be used directly.
template<typename T>
struct enumRefHolder
{
    T& enumVal;
    enumRefHolder(T& enumVal): enumVal(enumVal) {}
};
template<typename T>
struct enumConstRefHolder
{
    T const& enumVal;
    enumConstRefHolder(T const& enumVal): enumVal(enumVal) {}
};

// The next two functions do the actual work of reading/writing an
// enum as a string.
template<typename T>
std::ostream& operator<<(std::ostream& str, enumConstRefHolder<T> const& data)
{
   return str << enumStrings<T>::data[data.enumVal];
}

template<typename T>
std::istream& operator>>(std::istream& str, enumRefHolder<T> const& data)
{
    std::string value;
    str >> value;

    // These two can be made easier to read in C++11
    // using std::begin() and std::end()
    //
    static auto begin  = std::begin(enumStrings<T>::data);
    static auto end    = std::end(enumStrings<T>::data);

    auto find   = std::find(begin, end, value);
    if (find != end)
    {
        data.enumVal = static_cast<T>(std::distance(begin, find));
    }
    return str;
}

// This is the public interface:
// use the ability of function to deduce their template type without
// being explicitly told to create the correct type of enumRefHolder<T>
template<typename T>
enumConstRefHolder<T>  enumToString(T const& e) {return enumConstRefHolder<T>(e);}

template<typename T>
enumRefHolder<T>       enumFromString(T& e)     {return enumRefHolder<T>(e);}

Then you can use it like this:

// Define Enum Like this
enum X {Hi, Lo};
// Then you just need to define their string values.
template<> char const* enumStrings<X>::data[] = {"Hi", "Lo"};

int main()
{
    X   a=Hi;

    std::cout << enumToString(a) << "\n";

    std::stringstream line("Lo");
    line >> enumFromString(a);

    std::cout << "A: " << a << " : " << enumToString(a) << "\n";
}


I like the use of white space and indentation, makes the code easy to read.

I would start using var for your variable declarations.  It keeps the code cleaner, and easier for your eyes to scan.

Remove the // Do Nothing if statements.  It is redundant and adds extra lines of code that are unneeded.  This should work:

if (!subfeatSet.Contains(newNode.Text))
{
    treeviewFeatsFeats.Nodes.Add(newNode);
    foreach (DataRow subrow in ds.subfeats.Rows)
    {

    ...
}

I would also learn about linq, you can clean up most of your loops with linq.  I would also look into moving some of the inner loops out into their own function.  Moving to a function would remove some duplication you have in your code too.

private void ProcessNode(TreeNode parent, DataSet ds)
{
    var index = ds.subfeats.Columns.IndexOf("feat");
    foreach (var treeNode in (
            from row in ds.subfeats.Rows
            let nodeName = Convert.ToString(row[index])
            where rows.Contains(nodeName)
            select new TreeNode(nodeName)))
    {
        ProcessNode(treeNode, rows);
        parent.Add(treeNode);
    }
}

Now your function looks like this:

var index = ds.feat.Columns.IndexOf("name");
foreach (var treeNode in (
            from row in ds.feat.Rows,
            let nodeName = Convert.ToString(row[index])
            where rows.Contains(nodeName)
            select new TreeNode(nodeName)))
{
   ProcessNode(treeNode, ds);
}

This is a start.  I'm not happy with having to pass DataSet into the functions, but without fully understanding the data structure, I can't think of another way of doing it.


Structuring functions receiving and returning promises?

You're making more work for yourself than necessary.

Check this out:

var fs = require('fs');
var nodefn = require("when/node/function");

var get_some_data = function(filename) {
  return nodefn.call(fs.readFile, filename);
};

var parse_some_data = function(filename, throwError) {
  return get_some_data(filename).then(function(data) {
      // Mimic a synchronous error
      if (throwError) {
        throw new Error('Error parsing data')
      }

      return JSON.parse(data);
    });
};

var stringify_some_data = function(filename, throwParseError, throwLogError) {
  return parse_some_data(filename, throwParseError).then(function(parsedData) {
    // Mimic a synchronous error
    if (throwLogError) {
      throw new Error('Error stringifying data.');
    }

    return JSON.stringify(parsedData);
  });
};

var onSuccess = function(dataString) {
  console.log('Success! ' + dataString);
};
var onError = function(err) {
  console.log('Error! ' + err.message);
};

// "Success! { "data": "obj" }"
stringify_some_data('./data.json').then(onSuccess, onError);

// "Error! ENOENT, open './not_a_file.json'"
stringify_some_data('./not_a_file.json').then(onSuccess, onError);

// "Error! Error parsing data"
stringify_some_data('./data.json', true).then(onSuccess, onError);

// "Error! Error stringifying data."
stringify_some_data('./data.json', false, true).then(onSuccess, onError);

A couple of things to note:

An error thrown anywhere in the promise chain (synchronous or not) will bubble down to your onError handler
Return values of Promise objects are passed as arguments to the next onSuccess handler

I'm still working on grokking how the Promise/A+ spec works. If you've used jQuery.Deferred, you should know that it does not follow the spec (which made using When.js a big learning curve for me). Here's a pretty decent article explaining the Promise/A+ spec. Brian Cavalier (a When.js author) has some blog posts on asynchronous programming which are worth reading, as well.


SQL Procedure that will calculate the Last Price paid for a certain Part

Considering that your subselect is basically the same as your main select, chances are that this subselect is indeed a bit of overkill. Looking at your logic, what you want to achieve is to get the Price of the SalesOrderDetail linked to the SalesOrderHeader with the most recent OrderDate, so let's use an ORDER BY DESC and select only the first answer.

I think this should do the trick:

SELECT TOP 1 SD.Price
FROM SalesOrderHeaders AS SH
INNER JOIN SalesOrderDetails AS SD
    ON SH.Id = SD.HeaderId
WHERE SD.LineItemId = @ItemId
ORDER BY SH.OrderDate DESC


I would advise against this approach, you are correct in the fact that it is simple, however it's not foolproof. There is nothing actually ensuring that someone doesn't just call .Add() on the collection bypassing your extension method which allows for difficult to find bugs/race conditions.

Don't forget that all Monitor.Enter does is ensure that if multiple threads call Monitor.Enter that only 1 can enter a code block at a time. It doesn't prevent a caller on another thread mutating the collection if they don't call Monitor.Enter on the same obejct.

You would be better off either creating a custom collection which inherits from CollectionBase and encapsulating the lock logic in there so that any caller calling .Add() goes through the lock and is unable to bypass it.

Or if you are using .NET 4.0+, look at one of the collections in System.Collections.Concurrent as they are designed for this sort of activity in the first place.


Viewmodel has lots of properties which bind to view

This is a very common problem while working with MVVM. I believe the best solution to resolve this is to implement INotifyPropertyChanged in Models; that way you can directly bind the model properties in view and there will be no need to update them explicitly.

Even MS prescribes doing that -

  Typically, the model implements the facilities that make it easy to
  bind to the view. This usually means it supports property and
  collection changed notification through the INotifyPropertyChanged and
  INotifyCollectionChanged interfaces. Models classes that represent
  collections of objects typically derive from the
  ObservableCollection class, which provides an implementation of the
  INotifyCollectionChanged interface.

Taken from - http://msdn.microsoft.com/en-us/library/gg405484(PandP.40).aspx

Although its up to you to decide whether you want that type of implementation or not; and sometimes its not possible to do this too (e.g. you don't have ownership of model classes).

In case you have doubts about implementing INotifyCollectionChanged in Models, have a look at following SO question -

https://stackoverflow.com/questions/6922130/in-mvvm-model-should-the-model-implement-inotifypropertychanged-interface


Displaying each number of an integer in a sequence

Your method is lying. Not only it's displaying the digits, performing every Console.Write operation that needs to happen, it's also performing the "digit-splitting" logic.

It's more work than what its name says. For a simple coding exercise it's without consequences, but in larger projects if this is a coding habit you have, it can mean much bigger problems.

Separation of Concerns

Let's see what needs to happen here.

Get a valid user input.
Determine what the digits are.
Come up with a string to output.

You haven't included how you're addressing the first concern, so I won't cover it here.

Ideally, the result of determining what the digits are should be just that: some IEnumerable<int> that contains all the digits you want to display. I would make it so that the recursive function that contains the logic for that, works with an IList<int> and adds each digit it finds (instead of outputting it directly to the console).

Then, when your recursive logic completes, you have an IEnumerable<int> to iterate through. Right? Maybe not. string has methods, such as Join() that can make your "digit separator" string very explicit - if you're using .net 4+ you can use the Join<T>(string, IEnumerable<T>) overload:

var input = GetValidUserInput();
if (string.IsNullOrEmpty(input))
{
    return;
}

var digits = SeparateTheDigits(input);

var separator = "  ";
var result = string.Join(separator, digits);

Console.WriteLine(result);

As a result of separating the concerns, you now only write to the console once... and you haven't hard-coded your digit separator into a format string.


Deep cloning and modifying containers from ReactJS this.state

React is all about avoiding side-effects as well as rendering the same state exactly the same every time. You'd want to avoid operations that mutate the existing data structure like push or object assignment.
I'm pretty sure your clone is to prevent your object from being mutated. Instead of clone, create a function that returns your object structure. Just pass in anything that's configurable.
Instead of mutating the entries array with push, create a new array with your new data added using concat.
Use refs to fetch values from inputs instead of jQuery.

Your code could have been summarized into something like this:

function createNewEntry(month, date, year, allDay){
  return {
    month: month,
    date: date,
    year: year,
    allDay: allDay
  };
}

handleSubmit: function(event){
  var month = React.findDOMNode(this.refs.month).value;
  var date = React.findDOMNode(this.refs.date).value;
  var year = React.findDOMNode(this.refs.year).value;
  var allDay = React.findDOMNode(this.refs.allDay).value;
  var newEntry = createNewEntry(month, date, year, allDay);
  var entries = this.state.entries.concat(newEntry);

  this.setState({'entries': entries});
}

If you happen to have interest in persistent data structures (immutable data), then have a look at immutable.js. It's recommended in cases where you don't want to unwantedly mutate data.


What changes should I implement in my templated sorter class so that it performs efficiently?

In the sort() function its currently hardcoded to merge sort which I assume is not intentional. However, if you do allow the user to give an input you should do some error checking. You'll currently get unexpected behaviour if the user enters anything other than 1 or 2.
You should use std::swap rather than implementing your own swap function. Some types can make optimisations over what you've done.
From a design point of view I would argue that c++ is not an inherently object oriented language and that bubblesort and mergesort should be free functions taking a pair of iterators, to allow them to be more easily reused. You've pretty much done this for merge sort already, it uses none of the members of the Sorter class so could just be made a free function.
Your bubble sort implementation is inefficient. It should check if the vector is sorted after each pass, rather than doing the outer loops you could do while(!isSorted(vector)) or similar.
Merge sort has a very big lambda in it for combine. From a readability  point of view I would pull that out into a separate function.
Both mergesort and bubblesort use indices with operator[] to get the elements from the vector. The preferred way to do this in c++ is using iterators, see https://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices
In count() register is deprecated (and strictly is removed since c++17). You should probably avoid using it to improve compatibility.
I would need to think about it more, but I question if while (*(array + i)) in count will always behave as expected. You assume that the array has an end sentinel value that will dereference to null. I don't that's guaranteed. As far as I know there is not an easy way to get the size from a c style array. The normal way to handle this is to require the user to pass in the size as well.
Update on capacity(). Your use of capacity() in the merge sort is not correct. You should use size() instead. size() tells you the number of elements currently in the vector whereas capacity() tells you how many elements the vector reserved space for internally. i.e. if you insert more than this number of things into the vector it will internally reserve more space and do reallocate all the elements. It's important to note that the capacity can be greater than the number of elements in the vector. In your case it works ok as the constructor with a pair of iterators initialises the capacity equal to the size. However, I don't think this is guaranteed and is complier dependant. To see the difference try the following code:

    std::vector<int> v;
    std::cout << 0 << " " << v.size() << " " << v.capacity() <<"\n";
    for( int i = 0; i < 10; ++i)
    {
        v.push_back(i);
        std::cout << i << " " << v.size() << " " << v.capacity() <<"\n";
    }

0 0 0
0 1 1
1 2 2
2 3 4
3 4 4
4 5 8
5 6 8
6 7 8
7 8 8
8 9 16
9 10 16


Use the built-in heapq.merge:

heapq.merge(*iterables)
Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values.


Seeking 5 primes such that concatenating any two of them produces another prime

I looked at your 4primes-20seconds.scm file and noticed a potential improvement.

    (define (get-prime-pairs lst)
  (define (find-all-prime-pairs prime lst)
    (let loop ((prime prime)
               (lst lst)
               (acc '()))
      (if (null? lst) (if (>= (length acc) 3) acc '())
          (if (prime? (list->number (append prime (car lst))))
              (loop prime (cdr lst) (cons (list prime (car lst)) acc))
              (loop prime (cdr lst) acc)))))
  (append-map (lambda (x) (find-all-prime-pairs x lst)) lst))

You may be able to  filter quite a bit more out here because you don't just want every combination of primes that can be concatenated, you should only keep your acc if it's more than length three (for 4 prime and 4 for 5 primes)

I notice you map number->list over your primes and check every combination for a match.  Just this function is n^2 time proportional to lst

You can improves your time of search from n^2 to N*log(p) (where p is the value of the prime being tested

instead of searching low to high for each possible append of primes, search high to low for each possible decomposition

(decompose '(4 6 7)) -> '(((4) (6 7)) ((4 6) (7)))
(decompose '(2)) -> '()
(define (decompose L)
 (let loop ((A L) (B '()) (acc '()))
    (cond ((null? A) acc)
          (else (let ((A (cdr A))
                      (B (append B (list (car A)))))
                  (if (null? A) acc
                  (loop A B (cons (list A B) acc))))))))

(define (get-prime-pairs lst)
  (define (find-all-prime-pairs prime)
    (if (or (null? prime) (null? (cdr prime)))
        '()
        (let ((decomps (decompose prime)))
         (filter (lambda (x) (and (prime? (list->number (car x)))
                                  (prime? (list->number (cadr x)))
                                  (prime? (list->number
                                            (apply append x)))))
                 decomps))))
  (append-map (lambda (x) (find-all-prime-pairs x)) lst))

We make sure both decomposed parts are primes and we also make sure the other combination is prime as well. (we don't have to add it to acc as it's already showed up or will show up later in lst)

You have this even worse n^3 thing going in get-all-combinations-that-satisfy-constraints . @hen you recur down the cars of primes in the get-combinations subdefine and then recur does the cars of the set in can-be-added?, and then in contains? you recur down the cars of allowed-pairs.

My suggestion is to change allowed-pairs from a list of pairs to a hash-map where the key is a prime, and the value is a list of valid pairs. For the pair (3 7), the key 3 should have 7 as a member in it's list, and pair (7 3) key 7 should have 3 in it's list. http://sicp.ai.mit.edu/Fall-2004/manuals/scheme-7.5.5/doc/scheme_12.html#SEC105

Then get-combinations and above would compress to log time. In get-combinations loop initialize primes  to lookup into the above map.

Therefore can-be-added? uses a much shorter N. Instead of allowed-pairs

  (define (can-be-added? prime set) ;psuedo-code use the hash function of your impentation
(let ((friends (hask-lookup prime allowed-pairs-hash-table))
  (let loop ((set set))
(cond ((null? set) #t)
      (contains? friends (car set))
        (can-be-added? prime (cdr set)))
      (else #f)))

I'm not 100% sure this will find all combos, you may have to have get-combination return a list of combos from trying and not-trying the next prime, but if it worked for this problem last time, not doing it should work this time.


Search Android contacts more efficiently

Android Strings

Android provides a nice way of externalizing Strings in a strings.xml resource file. Using it right from the start of your project or as soon as possible is a very good idea, you might regret it later if you don't. Using XML-resources in Android is how to provide internationalization of your application. It is also good to keep all strings in one place, so you can get a nice overview of the strings shown in your application.

Speaking of Strings that are showing in your application, the content of your message String for your AlertDialogs is very questionable. If I as an user would encounter the message "f*ck ya" in an application, I would never ever give it a 5 star rating on Google Play. And it honestly does not give me a good impression of you as a person either.

The "ok" message is already defined as a string message in Android, and if your dialog button should only close the dialog then you can pass null as the listener. So therefore you can use alert.setPositiveButton(android.R.string.ok, null); which greatly improves code readability.

Readability

Speaking of code readability... I feel that you have an excessive amount of empty lines in your code, including but not restricted to:

if(C != null)

{

            alert.setPositiveButton("ok",new DialogInterface.OnClickListener() {

                @Override

                public void onClick(DialogInterface dialogInterface, int i)

        do

        {

            String display_ContactsName = getValue(C, android.provider.ContactsContract.Contacts.DISPLAY_NAME);

Instead consider this:

if(C != null)
{
    ...
    alert.setPositiveButton("ok",new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i)
    ...
        do
        {
            String display_ContactsName = getValue(C, android.provider.ContactsContract.Contacts.DISPLAY_NAME);


Assign object keys to another object's keys dynamically

Another solution to the problem could be expressed using Array.prototype.forEach(), as the following:

viewObject.terms.forEach(function(term, index){
    data['term_id_' + (index + 1)] = term.term_id;
    data['ticker_'  + (index + 1)] = term.its_ticker;
});


Really, the entire thing feels redundant

Well, it all comes down to the choice of programming language. With Java you chose predictability and regularity not power nor shortness. But I can still suggest improvements over this.

Your code does 3 things:

Take an integer input
Count evens, odds and zeros in its digits

2.1 Requires taking the digits of a number
Output this result nicely

3.1 Requires pluralization handling

So you should write three big methods and two smaller helper ones. This will not reduce size but will really increase readibility.

I started the re-factoring by extracting the input method, to show you what I mean in practice:

public class num
{
    public static long integerInput(String prompt) {
        long number;
        boolean validInput = false;
        Scanner input = new Scanner(System.in);

        do
        {
            System.out.print("Please enter an integer:  ");
            String numStr = input.next();

            try {
                number = Long.parseLong(numStr);
                validInput = true;
            } catch (NumberFormatException e) {
                System.out.print("That's not an integer. ");
                number = 0;
            }
        } while (!validInput);
        return number;

    }

    public static void main( String[] args )
    {

        long number = integerInput("The number? ");
        // Break each digit up by dividing by powers of 10.
        int evens = 0, odds = 0, zeros = 0;
        for (long temp = number; temp > 0; temp /= 10)
        {
            int digit = (int)(temp % 10);

            if (digit == 0)
            {
                zeros++;
                System.out.println(digit + " is a zero digit.");
            }
            else if (digit % 2 == 0)
            {
                evens++;
                System.out.println(digit + " is an even digit.");
            }
            else
            {
                odds++;
                System.out.println(digit + " is an odd digit.");
            }
        }

        String evenStr = " even " + ((evens == 1) ? "digit" : "digits");
        String oddStr = " odd " + ((odds == 1) ? "digit" : "digits");
        String zeroStr = (zeros == 1) ? " zero" : " zeros";

        System.out.println(number + " has " + evens + evenStr + ", " + odds + oddStr + ", and "
                + zeros + zeroStr + ".");
    }

}

The remaining 2 / 3 are up to you, good luck :)


Java Multitasking (String concatenation)

JavaDoc, JavaDoc, JavaDoc.

package zad2;

That is not a good package name. It should ideally be:

package com.yourmailprovider.username.stringstuffy;

or

package com.yourwebsite.stringstruffy;

This makes it very easy to see from where the used classes are from.

task.start();
...
task.startNewTread();

Why are there two start methods?

public class StringTask implements Runnable

This is odd, your class implements Runnable but is not supposed to be used as a Runnable. Instead it has its own set of methods. I suggest that you do not implement Runnable and instead encapsulate the Runnable as private inner class.

String line;
String letter;
int amount;
boolean isAborted;
TaskState stat;
boolean wasAborted = false;

Why are all these variables package private and not private?

public StringTask(String s, int i)

These are very, very bad variable names. Here are two simple rules for variables naming:

Name a variable after what it contains or is doing.
You are only allowed to use one letter variable names for dimensions (x, y, z).

while (amount > 0 && !isAborted){
    line += letter;
    amount--;
}

What you want is a StringBuilder. A string concatenation is a very costly operation, everytime you concatenate a string a new String object has to be created (because String is immutable). The StringBuilder instead simply extends its internal buffer.

if(wasAborted == false) stat = TaskState.READY;
else stat = TaskState.ABORTED;

Oh dear, that is awful to read. I know that it looks more complicated, but you really should make a habit out of using braces for ifs:

if (!wasAborted) {
    stat = TaskState.READY;
} else {
    stat = TaskState.ABORTED;
}

public void start (){
    isAborted = false;
    stat = TaskState.RUNNING;
    new Thread(this).start();
    //System.out.println("start");
    //run();
}
public void startNewTread (){
    isAborted = false;
    stat = TaskState.RUNNING;
    new Thread(this).start();
}

Why are there two start methods again? They are even doing the same thing.

public boolean isDone(){
    if (stat == TaskState.READY || stat == TaskState.ABORTED) return true;
    return false;
    }

Now this is a prime example of confusing formatting.

CREATED, RUNNING, ABORTED, READY

What's the difference between READY and CREATED? Why do you care if the task has been aborted or not? Does not clean up its state at some point?

Why is there a separate boolean for if the task has been aborted?


As a simple comment, a function called isJolly should probably return a boolean. Then, the calling function can use that boolean to print either "Jolly" or "Not jolly".


It was quite hard, but I figured it out. You can even pre-create the buffer with some value you know the mergesort will never exceed, and save some object creation overhead.

public class Mergesort
{
    public static void main(String[] args){
        int[] array = new int[]{1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
        array = mergeSort(array, 0, array.length-1);
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    private static int[] mergeSort(int[] a, int p, int q)
    {
        if (q-p < 1) return a;
        int mid = (q+p)/2;

        mergeSort(a, p, mid);
        mergeSort(a, mid+1, q);
        return merge(a, p, q, mid);
    }

    private static int[] merge(int[] a, int left, int right, int mid)
    {
        //buffer - in the worst case, we need to buffer the whole left partition
        int[] buffer = new int[a.length / 2 + 1];
        int bufferSize = 0;
        int bufferIndex = 0;
        int leftHead = left;
        int rightHead = mid+1;

        //we keep comparing unless we hit the boundary on either partition
        while(leftHead <= mid && rightHead <= right){
            //no data in the buffer - normal compare
            if((bufferSize - bufferIndex) == 0){
                //right is less than left - we overwrite left with right and store left in the buffer
                if(a[leftHead] > a[rightHead]){
                    buffer[bufferSize] = a[leftHead];
                    a[leftHead] = a[rightHead];
                    bufferSize++;
                    rightHead++;
                }
            }
            //some data in the buffer - we use buffer (instead of left) for comparison with right
            else{
                //right is less than buffer
                if(buffer[bufferIndex] > a[rightHead]){
                    //we overwrite next left value, but must save it in the buffer first
                    buffer[bufferSize] = a[leftHead];
                    a[leftHead] = a[rightHead];
                    rightHead++;
                    bufferSize++;
                }
                //buffer is less than right = we use the buffer value (but save the overwriten value in the buffer)
                else{
                    buffer[bufferSize] = a[leftHead];
                    a[leftHead] = buffer[bufferIndex];
                    bufferSize++;
                    bufferIndex++;
                }
            }
            leftHead++;
        }
        //now we hit the end of either partition - now we have only two of them (buffer and either left or right)
        //so we do traditional merge using these two
        while(leftHead <= right && (bufferSize - bufferIndex) > 0){
            if(rightHead <= right && a[rightHead] < buffer[bufferIndex]){
                a[leftHead] = a[rightHead];
                rightHead++;
            }
            else{
                if(leftHead <= mid){
                    buffer[bufferSize] = a[leftHead];
                    bufferSize++;
                }
                a[leftHead] = buffer[bufferIndex];
                bufferIndex++;
            }
            leftHead++;
        }
        return a;
    }
}

I did not extensively test it, nor did I measure it. You can try that and post the results.


It would be better to implement SessionHandlerInterface.
Your code is tightly coupled, move session_set_save_handler out from constructor to some bootstrap file. Also this class shouldn't create db connection, it is better to pass it as a constructor parameter:

$conn = new PDO('mysql:host=' . DBHOST . ';dbname=' . DBNAME . ';charset=utf8', DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handler = new MySessionHandler($conn);
session_set_save_handler($handler, true);

Constructor for the session handler:

class Session implements \SessionHandlerInterface
{
    protected $conn;

    public function __construct(\PDO $conn)
    {
        $this->conn = $conn;
    }

    // ....
}

This gives you more freedom, in case you decide to extend PDO you can pass it there. Also you don't need to create separate connection for application and session.
Implementing Interface ensures that you fulfill all requirements.

What I find odd is that you put every query to handler property, they should be local variables, you create them on every method call anyway.


Bash Script - batch rename files in current directory with preview

Checking if a value is not empty

This is a very complicated way to check that value is not empty:

lines=$(echo -en "$value" | wc -m)

if [ "$lines" -gt 0 ]; then

This is equivalent:

if [ "$value" ]; then

Avoid echo -e

It's good to avoid all flags of echo, such as -e,
because they are not portable.
Instead of this:

 echo -e "Folder .script-history does not exist and gets created... \n";

I recommend to add a second empty echo:

echo "Folder .script-history does not exist and gets created..."
echo

The concern about A && B || C

Shellcheck raised an issue here:

 rename "s/$search/$replace/g" ./*\
 && { echo "success :-)"; }\
 || { echo "failed :-("; };;

The issue is that if rename succeeds but then echo success fails,
the || will get executed.
You can ignore this issue, because in the unlikely event that the first echo fails, the second (after the ||) is likely to fail too, so it won't matter.
If you want to be pedantic/bullet-proof, then you have to spell out a proper if-else statement instead of the && ... || chaining.

In any case, the command can be simplified without the grouping:

rename "s/$search/$replace/g" ./* \
&& echo "success :-)" \
|| echo "failed :-(" ;;

I also added spaces in front of the \ before the line breaks,
to make it perfectly clear that the argument before the \ is not being continued on the next line.
Without that, this point would be ambiguous, making the script a bit harder to read.

The concern about read without -r

If the user input contains \, it may not get preserved.
That's hardly ever intended,
and probably you would not want that either.
As a rule of thumb,
it's good to always use read -r.


Frequency analysis for counting keywords

The obvious issue with this is that you first build the list of all keywords and then count them. It would make more sense to count them while you process each line. collections.Counter supports this with an overridden update method:

>>> c = Counter([1, 2, 3])
>>> c
Counter({1: 1, 2: 1, 3: 1})
>>> c.update([1, 4])
>>> c
Counter({1: 2, 2: 1, 3: 1, 4: 1})

Which you can use in your case like this:

from collections import Counter
import csv
import bz2

csv.field_size_limit(999999999)

c = Counter()

with bz2.BZ2File("keywords.csv.bz2") as f:
    reader = csv.reader(f)
    for idx, row in enumerate(reader):
        c.update(term.strip().lower() for term in row)
        if idx % 100000 == 0:
            print idx

with open("counts.txt", 'w+') as fl:
    for k, v in c.most_common():
        fl.write("{} | {}\n".format(k, v))

I don't see the reason for for term in row, the CSV reader already splits the row into a list, so I left it out/moved it into the generator.

You should test the performance of

c.update(term.strip().lower() for term in row)

vs

c.update(map(lower, map(strip, row)))

vs

c.update(map(lambda term: term.strip().lower(), row))

with your file, because I'm not sure how well the double map is implemented in Python 2.x in comparison to using a lambda or a generator expression.

As an additional aside, it might makes sense to not do the update on every iteration, but buffer it for some number of counts. You could use the print as an already existing check to write it out. With this code:

from collections import Counter
import csv
import bz2

csv.field_size_limit(999999999)

c = Counter()
buf = []
with bz2.BZ2File("keywords.csv.bz2") as f:
    reader = csv.reader(f)
    for idx, row in enumerate(reader):
        buf.extend(term.strip().lower() for term in row)
        if idx % 100000 == 0:
            print idx
            c.update(buf)
            buf = []
    c.update(buf)

with open("counts.txt", 'w+') as fl:
    for k, v in c.most_common():
        fl.write("{} | {}\n".format(k, v))

I get some 25% speed increase on my local test file (which has a lot of repeated lines). At this point it becomes a trade-off between the cost of update and extend. in my normal code, this determines the runtime:

29877245 function calls (29877242 primitive calls) in 8.559 seconds
...
999181    2.756    0.000    7.515    0.000 collections.py:528(update)

For the second code it is somewhat shared between update and extend and lower in the sum

23882242 function calls (23882239 primitive calls) in 5.870 seconds
...
    12    1.421    0.118    1.791    0.149 collections.py:528(update)
...
999180    0.779    0.000    3.065    0.000 {method 'extend' of 'list' objects}

I also tried basically your approach, updating the counter only at the end. This is about another 0.2 seconds faster at the cost of potentially unlimited memory usage.


Creating a Basic Success Function for Http

Though your solution would work, I would have gone for something like this:

class Net::HTTPResponse
  def success?
    false
  end
end

class Net::HTTPSuccess
  def success?
    true
  end
end

If you do keep your solution, you could simplify it to:

class Net::HTTPResponse
  def success?
    self.is_a? Net::HTTPSuccess
  end
end


HMSegmentedControl react to tapping on currently selected segment

You can fork the control and do a tiny modification to the code to do what you need.

In touchesEnded:withEvent:, you need to modify this line so it wouldn't check if the tapped segment is the currently selected segment:

    if (segment < sectionsCount)