The Fundamentals: Style & Readability

Before we get into optimizing, there are a couple of glaring problems with your coding style—that is, the way the code is written and the way it looks.

The biggest problem is that there is a lot of duplication. You repeat yourself over and over inside the if blocks of the main function. Any time you see repeated code, you should extract it out into a function. Even if there are some subtle differences between the various blocks of code, this can be accommodated by passing parameters to the function to customize its behavior. You want to be DRY—don't repeat yourself. It just makes the code harder to read, harder to maintain, and increases the chances for bugs to slip in.
Variables that never change their values are called constants, and the C++ language has a special way to indicate such variables: the const keyword. Using this helps to prevent bugs, like accidentally writing code that changes a variable's value, when that variable is supposed to be constant.

Thus, the x, y, red, gold, and blue variables declared at the top of the main function should all be const, since these are effectively read-only. Also, I would personally recommend making even local variables whose values do not change after initial initialization (such as hdc and color) explicitly const.

(Also, I'm a little bit obsessive-compulsive, so I like to vertically align all of my assignments. Others may disagree that this is worth the effort, but I use tools in my editor that semi-automate it. I find that it not only makes the code look better overall, but makes inconsistencies—i.e., possible errors—more likely to be caught because they stick out like a sore thumb.)
Speaking of the red, gold, and blue variables, these appear to be magic numbers, the values of which would defy most people's intuition. Why, exactly, would 2039797 be a representation of red?

Instead, you should be declaring these color values using the Win32 RGB macro. This takes individual red, green, and blue color components (a representation with which we are all familiar), and packs them into a 32-bit DWORD. Not only is this more readable, but it also ensures that your code is endianness-independent. The Platform SDK determines whether the encoding is RGB or BGR (in the case of Win32, it is actually BGR).

Furthermore, you should prefer to use the COLORREF type for color values in Windows. While COLORREF is simply a typedef for DWORD, it is clearer and more semantically accurate to use COLORREF. Besides, you used the COLORREF type to store the return value of GetPixel, so you should do it here for the comparison constants in the interest of consistency.
In C++, you should be taking advantage of the RAII paradigm to produce cleaner, more correct code. What I mean by this is that any time you have an unmanaged object (such as a Windows handle), you should wrap that object in a class. Make the class's constructor responsible for allocating the object, and the class's destructor responsible for deallocating/freeing the object. When an object of that class is declared, its unmanaged resources are automatically initialized; when that object goes out of scope, its unmanaged resources are automatically released. This way, the compiler does all of the book-keeping automatically, and you never leak.

Your code as written is actually correct, in that you call ReleaseDC for each call to GetDC, but I bet you had to think about this to make sure that you got it right. Best not to make yourself think so hard. Also, using RAII ensures that your code will be exception safe. (Again, not a problem in this case, since the only code in between GetDC and ReleaseDC is a call to GetPixel and an assignment to a POD type, neither of which can throw, but it's all too easy to add something later and forget to audit carefully for exception safety.)

Most people use a framework like MFC or WTL that provides the wrapper classes for you, but if you're just writing a simple app, you don't necessarily need anything that complicated. It only takes a few lines of code to write a simple wrapper class that does everything you need:

class DC
{
  public:

    explicit DC(HWND hWnd)
        : m_hWnd(hWnd)
        , m_hDC (GetDC(hWnd))
    { }

    ~DC()
    {
        ReleaseDC(m_hWnd, m_hDC);
    }

    HDC Handle()
    {
        return m_hDC;
    }

  private:

    HWND m_hWnd;
    HDC  m_hDC;
};

You could improve this substantially by adding error checking—at the very least, you should probably have an assert that checks for invalid handles and/or failed function calls in debugging builds.
Instead of using the sizeof operator on the type, prefer to use the sizeof operator on the object. For example, change sizeof(INPUT) to sizeof(i). That way, if i ever changes to, say INPUTEX, there will be fewer places in the code that you have to remember to change.
Don't repeat constant literals throughout the code. To be fair, you've only done it one place—inside the pressW function by hardcoding the value 0x57. The damage is relatively contained, but still, 0x57 is repeated twice and this makes changing it in the future an error-prone task. Declare a constant instead.

Better yet, replace the inscrutable 0x57 with 'W'. In other words, let the compiler do the evaluation and determine what the ASCII code of the W character is. The result is the same, but the code is significantly more readable. (Also do the same thing for 0x31, 0x32, and 0x33.)

In most cases, the pressW function should probably be pressKey, and take the virtual-key code as a parameter. Personally, I would prefer writing it this way from the get-go because it's no harder. But you do have to be careful not to make the code you're writing overly generic, because that wastes development time for things you may not ever need (see also YAGNI).

One thing you are doing well, though, is following a consistent style throughout. While K&R is not my preferred brace style, you are using it consistently, and that is really what's most important.

Taking these points into account, here is how I would revise your current implementation:

#include <windows.h>

void pressW();
void waitForColorChange(DWORD x, DWORD y, COLORREF expectedColor);

class DC
{
  public:

    explicit DC(HWND hWnd)
        : m_hWnd(hWnd)
        , m_hDC (GetDC(hWnd))
    { }

    ~DC() {
        ReleaseDC(m_hWnd, m_hDC);
    }

    HDC Handle() {
        return m_hDC;
    }

  private:

    HWND m_hWnd;
    HDC  m_hDC;
};

int main(int argc, char** argv) {
    const DWORD    x    = 566;
    const DWORD    y    = 967;
    const COLORREF red  = RGB(245,  31,  31);
    const COLORREF gold = RGB(187, 171,   0);
    const COLORREF blue = RGB(198, 203, 239);

    while (true) {
        if (GetAsyncKeyState('1')) {
            waitForColorChange(x, y, blue);
        }
        else if (GetAsyncKeyState('2')) {
            waitForColorChange(x, y, red);
        }
        else if (GetAsyncKeyState('3')) {
            waitForColorChange(x, y, gold);
        }
    }
}

void pressW() {
    const WORD vkW = 'W';
    INPUT i;
    i.type           = INPUT_KEYBOARD;
    i.ki.wScan       = MapVirtualKey(vkW, MAPVK_VK_TO_VSC);
    i.ki.time        = 0;
    i.ki.dwExtraInfo = 0;
    i.ki.wVk         = vkW;
    i.ki.dwFlags     = 0;
    SendInput(1, &i, sizeof(i));
    i.ki.dwFlags     = KEYEVENTF_KEYUP;
    SendInput(1, &i, sizeof(i));
}

void waitForColorChange(DWORD x, DWORD y, COLORREF expectedColor) {
    pressW();
    while (true) {
        DC dc(NULL);
        const COLORREF color = GetPixel(dc.Handle(), x, y);
        if (color == expectedColor) {
            pressW();
            break;
        }
    }
}

There are, of course, other equally valid ways of refactoring your code, but the important thing is to be DRY! The above example achieves that, and without significantly changing the object code generated by a compiler (in other words, without slowing anything down at run-time).

Going Deeper: Cautions & Potential Optimizations

The GetAsyncKeyState function actually is asynchronous, meaning that if you call it twice in a row, you will get two different results if the keyboard state changes between those calls. If you're not very careful, this can result in glitchy behavior. You are probably okay here, but this is something to watch out for.

The call also isn't free. Spinning in a busy loop, repeatedly calling GetAsyncKeyState is a good way to burn a bunch of CPU cycles and turn your computer into a space heater. A better design would be to listen for notifications of a key press event, rather than polling for a state change.
Since you're not passing either the KEYEVENTF_SCANCODE or KEYEVENTF_UNICODE flags, you can avoid computing the scan code and initializing that field each time you call SendInput. This won't save you a whole lot of time, but it does elide one function call.

Even if you needed to initialize the scan-code field, you could save yourself some time by calling the MapVirtualKey function once and caching its result in a static (or global) variable. The mapping of virtual-key codes to scan codes is not going to change while your application is running, so there's no need to call the function each time.
You can save another function call by collapsing the two calls to SendInput into one. This function allows you to pass an array of INPUT structures, and it will synthesize a separate event for each one. The key-down event goes in the first INPUT structure, and the key-up event goes in the second INPUT structure. The required modifications to the code are trivial, but just in case:

void pressW() {
    const WORD vkW = 'W';

    INPUT i[2];
    i[1].type           = INPUT_KEYBOARD;
    i[1].ki.wVk         = vkW;
    i[1].ki.time        = 0;
    i[1].ki.dwExtraInfo = 0;
    i[1].ki.dwFlags     = 0;

    i[2].type           = INPUT_KEYBOARD;
    i[2].ki.wVk         = vkW;
    i[2].ki.time        = 0;
    i[2].ki.dwExtraInfo = 0;
    i[2].ki.dwFlags     = KEYEVENTF_KEYUP;

    SendInput(ARRAYSIZE(i), i, sizeof(i));
}

Notice that I've used the ARRAYSIZE macro (defined in the Win32 SDK headers) to automatically determine the size of the array so I don't have to hard-code another constant. This looks like more code, but it actually executes more quickly because the cost of initializing that extra INPUT structure is dwarfed by the cost of a function call.

If you really wanted to go all out, you could recognize that the values of these INPUT structures never change and decide to make it statically-initialized. This saves the compiler from having to emit code that performs the initialization before each call to SendInput. It simply pushes a pointer to constant data in the executable's DATA segment and calls SendInput. Micro-optimization at its finest! A different syntax will be required for this static initialization:

void pressW() {
    const WORD vkW = 'W';
    static INPUT i[2] = {
       { INPUT_KEYBOARD, { vkW, 0, 0,               0 } },
       { INPUT_KEYBOARD, { vkW, 0, KEYEVENTF_KEYUP, 0 } },
    };
    SendInput(ARRAYSIZE(i), i, sizeof(i));
}

(I really wanted to make i const there, but I can't safely do so because the SendInput function expects a non-const pointer to the array of INPUT structures. I could reasonably assume that the function is not going to modify them, but I cannot prove that without inside knowledge of its implementation, so I cannot rely on it.)
Acquiring and releasing a device context (GetDC/ReleaseDC) are not particularly expensive operations, but they aren't exactly free, either. Therefore, it makes good sense to minimize the number of times you do this cycle. It certainly isn't necessary to do it on each iteration of a tight spin loop! The waitForColorChange function that I wrote could do it at the top, then enter the while loop, and only release the DC after it breaks. Using RAII, this is simple:

void waitForColorChange(DWORD x, DWORD y, COLORREF expectedColor) {
    pressW();
    DC dc(NULL);
    while (true) {
        if (GetPixel(dc.Handle(), x, y) == expectedColor) {
            pressW();
            break;
        }
    }
}

But actually, this waitForColorChange function is itself called from within a tight spin loop! In fact, your code could be revised such that the DC is acquired at the beginning of the program, used throughout its lifetime, and released when your program exits (which will happen automatically, thanks to RAII). This will require a bit of refactoring—a const reference to the DC object will need to be passed to the waitForColorChange function—but doesn't make the code any less readable.

The only concern is that, generally speaking, device contexts shouldn't be held onto any longer than necessary. It seems justified in this case because you are actively using it the entire time, but that may just speak to a larger design flaw with your application. I've already mentioned my reservations about polling.

The Main Event: Optimizing GetPixel

At the core of your code's logic is a call to GetPixel to retrieve the current color value of a particular pixel on the screen. That is unfortunate if you're concerned about speed, because GetPixel is a very slow function, indeed. Why is it so slow? The above-linked documentation doesn't give much of a hint. In fact, this API has a dirty little secret: individual pixels cannot be directly manipulated by the graphics subsystem, so GetPixel (and its brother, SetPixel) have to simulate it, which makes an ostensibly simple, straightforward function call into an extremely slow operation. In addition to the usual overhead of a function call, parameter validation, and switching to and from kernel mode, the GetPixel function also has to create a temporary bitmap, copy the contents of the DC into that temporary bitmap, perform all necessary color-mapping, map the coordinates and locate the pixel, retrieve its color value, and then destroy the temporary bitmap. A lot of work for a single pixel!

The throughput of GetPixel is on the order of 100,000 pixels per second, which is usually fast enough. If you want to speed up drawing operations that involve the manipulation of multiple pixels, the general strategy is to minimize overhead by copying the DC's contents into a temporary device-independent bitmap (DIB) and then using pointer arithmetic on this DIB to access individual pixels. This gives you direct access to each pixel, and allows a throughput of millions or more pixels per second. The problem for you is that you cannot simply use a cached snapshot of the screen—you really do need to update it each time through the loop, which means that this strategy doesn't save you a whole lot in terms of overhead. But it'll still be slightly faster.

Here's an approximation of the code that would be required:

COLORREF FastGetPixel(DWORD x, DWORD y)
{
   // Retrieve a device context for the screen.
   const HDC hdcScreen = GetDC(NULL);

   // Create a DIB section.
   BITMAPINFO bi;
   bi.bmiHeader.biSize         = sizeof(bi.bmiHeader);
   bi.bmiHeader.biWidth        = 1;
   bi.bmiHeader.biHeight       = 1;
   bi.bmiHeader.biPlanes       = 1;
   bi.bmiHeader.biBitCount     = 32;
   bi.bmiHeader.biCompression  = BI_RGB;
   bi.bmiHeader.biSizeImage    = ((((static_cast<unsigned int>(bi.bmiHeader.biWidth) * 32U + 31U) / 32U) * 4U) * bi.bmiHeader.biHeight);
   bi.bmiHeader.biClrUsed      = 0;
   bi.bmiHeader.biClrImportant = 0;
   BYTE* pBits;   // points to the DIB section's raw bit data
   const HBITMAP hbmpDIB = CreateDIBSection(hdcScreen,
                                            &bi,
                                            DIB_RGB_COLORS,
                                            reinterpret_cast<void**>(&pBits),
                                            NULL,
                                            NULL);

   // Create a memory device context that is compatible with the screen.
   // We need to select our DIB section into this DC so that we can draw onto it.
   // Specifically, we'll copy a 1x1 pixel area from the screen into our DIB section.
   const HDC     hdcMem  = CreateCompatibleDC(hdcScreen);
   const HBITMAP hbmpOld = static_cast<HBITMAP>(SelectObject(hdcMem, hbmpDIB));
   BitBlt(hdcMem,    0, 0, bi.bmiHeader.biWidth, bi.bmiHeader.biHeight,
          hdcScreen, x, y,
          SRCCOPY);
   SelectObject(hdcMem, hbmpOld);
   GdiFlush();

   // Read the RGB color value of the top-left pixel in our DIB section
   // (which is actually the only pixel that it contains).
   // Note that in a bitmap, the byte order is always RGBA!
   const COLORREF clr = RGB(pBits[2], pBits[1], pBits[0]);

   // Clean up.
   DeleteObject(hbmpDIB);
   DeleteDC(hdcMem);
   ReleaseDC(NULL, hdcScreen);

   return clr;
}

The code can be improved by writing simple C++ wrapper classes to implement automatic resource management, as was discussed above. You should also add error-checking.

To really squeeze speed out of it, you'll need to resort to some ugly tactics. As written, this does much the same thing as the Win32 GetPixel function, and like I mentioned above, your setup is such that you need to call this function repeatedly. The obvious way to make code execute faster is to reduce the amount of code that you have to execute. Here, that means factoring out common tasks and doing them only once:

You don't need to retrieve a screen DC and release it each time through the FastGetPixel function. You can retrieve one once at the start of your program, and free it at the end once you're done.
The values of the BITMAPINFO structure are not changing, so you could make it static const and initialize it only once, instead of each time. This is basically the same as what we did with the INPUT structure.
You don't need to create a new DIB section and free it each time. You can just reuse the same one. Create it once at the start of your program, use it as needed, and free it at the end. (This actually makes the above bullet unnecessary, since the initialization of BITMAPINFO will no longer be on the critical path.)
As with the screen DC, you don't need to create a memory DC and free it each time. Keep the same memory DC, with your DIB section selected into it, and re-use it each time. This saves not only repeated calls to CreateCompatibleDC and DeleteDC, but also repeated calls to SelectObject.

Although making all of these objects global is pretty much breaking every design guideline in the book, sometimes performance concerns justify ugliness. Address maintenance concerns by wrapping them in C++ classes, following a "singleton" pattern.

Now, your inner loop will simply call the following function:

// Required global objects
// (shown here as simple global variables, but should really be managed by
// singleton classes to ensure correct lifetime management)
HDC   hdcScreen;
HDC   hdcDIB;
BYTE* pDIBBits;

COLORREF FastIterativeGetPixel(DWORD x, DWORD y)
{
   // Validate global objects' state in debug builds using assertions
   // so you can easily diagnose problems but don't lose performance
   // in release builds.
   // ...

   // Copy the current contents of the screen into our DIB section.
   BitBlt(hdcDIB, 0, 0, 1, 1, hdcScreen, x, y, SRCCOPY);
   GdiFlush();

   // Retrieve the RGB color value of the top-left pixel in our DIB section
   // (which is actually the only pixel that it contains).
   // Note that in a bitmap, the byte order is always RGBA!
   return RGB(pDIBBits[2], pDIBBits[1], pDIBBits[0]);
}

All initialization and clean-up has been deferred, so that all we need to do is a single BitBlt and, to be on the safe side, a GdiFlush. If you were willing to live a bit dangerously, you could omit the flush. (In fact, you're probably safe omitting it in your case, because all that would happen is you'd get stale color values that didn't accurately reflect the current state of the screen, which would just defer your action until the next time through the loop.)

Applying all of the optimizations mentioned in the last two sections, you should see a significant performance gain—an order of magnitude, if you're lucky. But then you will have hit a wall. Real performance gains will only come—as they always do—with reimagining the fundamental algorithm and/or design of your application. Like finding a way to receive notification from the other application when it has changed the color.


Spiral a matrix of size NxN filled with integers from 1 up to and including n^2

First off, the docstring for a function always needs to come before the argument vector. You did this right in create-numbers-matrix, but in the rest of your functions, your docstring will be treated as part of the function body, evaluated, and ignored.

(require '[clojure.repl :refer [doc]])

(doc rotate-and-chop)
;; -------------------------
;; spiral.core/rotate-and-chop
;; ([m])
;;   nil
;=> nil

Some Clojure lint tools like Eastwood will catch this sort of error. Also, as you can see, the doc function indents the first line of the docstring by two spaces, so it's conventional to indent each line of the docstring after the first by two spaces to make everything line up:

(defn rotate-and-chop
  "repeatedly rotates matrix m 90 degrees and cuts off the
  top till matrix is empty."
  [m]
  (if (empty? m) nil
      (conj (rotate-and-chop (-> m
                                 delete-first-row
                                 rotate-left))
            (get-first-row m))))

(doc rotate-and-chop)
;; -------------------------
;; user/rotate-and-chop
;; ([m])
;;   repeatedly rotates matrix m 90 degrees and cuts off the
;;   top till matrix is empty.
;=> nil

For create-numbers-matrix, your current approach with let works fine. You could also avoid having to name each of the intermediate steps by using ->>:

(defn create-numbers-matrix
  "creates a size x size matrix of numbers from 1 up to and including size."
  [size]
  (->> (range 1 (inc (* size size)))
       (partition size)
       m/matrix))

Your get-first-row, delete-first-row, transpose, and reverse-rows functions are equivalent to the already available first, rest, transpose, and reverse functions, respectively, so I would just remove them; they add no value to your code.

It's conventional to indent the "then" branch (and the "else" branch, if present) of an if or when expression by two spaces. So in rotate-and-chop, since your first branch is nil, it would be more idiomatic to write it as (when-not (empty? m) ,,,) or just (when (seq m) ,,,). Also, it might be more readable to put the call to rotate-and-chop into the threading macro:

(defn rotate-and-chop
  "repeatedly rotates matrix m 90 degrees and cuts off the
  top till matrix is empty."
  [m]
  (when (seq m)
    (conj (-> m rest rotate-left rotate-and-chop)
          (first m))))

In spiral, you use flatten to concatenate the elements of the sequence returned by rotate-and-chop into a single sequence. While this does work in your case, I would generally advise against using flatten, because it can lead to unexpected behavior when you don't know what type of data is in the sequences you're concatenating. Usually you just need to flatten the outermost layer, in which case you can simply apply the concat function:

(defn spiral
  "creates list of values in spiral from grid of size size"
  [size]
  (let [numbers-matrix (create-numbers-matrix size)]
    (apply concat (rotate-and-chop numbers-matrix))))

As you noted in your question, though, this is still considerably longer than the Ruby solution. However, it's quite possible to write a short, idiomatic Clojure solution to this problem:

(defn spiral [m]
  (when (seq m) (concat (first m) (-> m rest m/transpose reverse spiral))))

This is basically a direct translation of the Ruby solution into Clojure, except without that ugly modification of the original matrix. When m is empty, I return an empty result (it's common to treat nil as an empty sequence in Clojure). Otherwise, I return the concatenation of the first row of m with the spiral sequence of the reversal of the transposition of the rest of m. The reason I have to call rest is that, in the original Ruby code, shift causes the side effect of removing the first row from the matrix, which I don't want to do here.

You could test this out with a function that generates an example matrix, similar to your create-numbers-matrix function:

(defn matrix [n]
  (partition n (range 1 (inc (* n n)))))

(spiral (matrix 3))
;=> (1 2 3 6 9 8 7 4 5)


1. Review

The code in the post does not work:

>>> q = PriorityQueue(())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr152757.py", line 8, in __init__
    self._counter = itertools.count()     # unique sequence count
NameError: name 'itertools' is not defined

The problem is that itertools was imported in class scope (not at top level) so you need self.itertools (or to move the imports to the top level).
The class has no docstring. How am I supposed to use this class?
The __init__, add_task and pop_task methods have no docstrings. What arguments do I pass? What do they return?
The objects in the queue are described as "tasks" but priority queues can be used for all sorts of different things — for example, the A* search algorithm uses a priority queue containing unexpanded search nodes. I would use a more generic name like "item" or "element", and change add_task to add, remove_task to remove and pop_task to pop.
The Python style guide (PEP8) recommends that

  Class names should normally use the CapWords convention.

So I would call the class PriorityQueue. You're not obliged to follow this guide, but it will make it easier for you to collaborate with other Python programmers if you do.
If a class has no superclasses, then you can omit the parentheses from the class declaration.
The constructor has a required argument mylist. It would be better if this argument was optional, and if omitted then the constructed queue is empty. This would match the behaviour of other class constructors like queue.PriorityQueue() and collections.deque() which construct empty queues if given no argument.
There is a test if mylist: but this is unnecessary because if mylist is an empty list, then both branches have the same behaviour (setting self.data to the empty list). So you might as well omit the test.
Once you omitted the test on mylist, it doesn't have to be a list any more – any iterable would do. So I would name this argument iterable.
It is perverse that the argument to __init__ must be a list of pairs (priority, task) but when calling add_task you have to supply the arguments (task, priority). This seems likely to be the cause of errors.
The need for _counter is slightly tricky (it's necessary to break ties in case the items cannot be compared for order), so a comment would be a good idea.
self.REMOVED is always the same, so it could be a member of the class. Also, it is only needed for use internally by the class so PEP8 recommends using a name starting with an underscore.
Similarly, self.data ought to have a name starting with an underscore.
Instead of using element[0] and element[1] here:

for element in mylist:
    priority, count, task = element[0], next(self._counter), element[1]
    entry = [priority,count,task]

use tuple unpacking:

for priority, item in iterable:
    entry = [priority, next(self._counter), item]

(But see the next item.)
The code in __init__ duplicates the code in add_task. So it would be simpler if the former called the latter:

for priority, item in iterable:
    self.add(item, priority)

The docstring for remove_task is written from the implementer's point of view: it says, "Mark an existing item as REMOVED". But the user does not need to know how removal is implemented: that's an internal detail of the class which the documented API should hide.
In pop_task you unpack all the elements of the popped entry:

priority, count, item = heapq.heappop(self._data)

but priority and count are not used. It is conventional to use the variable name _ for values that go unused.

2. Revised code

import heapq
import itertools

class PriorityQueue:
    """Collection of items with priorities, such that items can be
    efficiently retrieved in order of their priority, and removed. The
    items must be hashable.

    """
    _REMOVED = object()         # placeholder for a removed entry

    def __init__(self, iterable=()):
        """Construct a priority queue from the iterable, whose elements are
        pairs (item, priority) where the items are hashable and the
        priorities are orderable.

        """
        self._entry_finder = {} # mapping of items to entries

        # Iterable generating unique sequence numbers that are used to
        # break ties in case the items are not orderable.
        self._counter = itertools.count()

        self._data = []
        for item, priority in iterable:
            self.add(item, priority)

    def add(self, item, priority):
        """Add item to the queue with the given priority. If item is already
        present in the queue then its priority is updated.

        """
        if item in self._entry_finder:
            self.remove(item)
        entry = [priority, next(self._counter), item]
        self._entry_finder[item] = entry
        heapq.heappush(self._data, entry)

    def remove(self, item):
        """Remove item from the queue. Raise KeyError if not found."""
        entry = self._entry_finder.pop(item)
        entry[-1] = self._REMOVED

    def pop(self):
        """Remove the item with the lowest priority from the queue and return
        it. Raise KeyError if the queue is empty.

        """
        while self._data:
            _, _, item = heapq.heappop(self._data)
            if item is not self._REMOVED:
                del self._entry_finder[item]
                return item
        raise KeyError('pop from an empty priority queue')


Counting Increasing Subsequences of size K recursive

Concept

You have called this a "Longest Increasing Subsequence" problem, but it's not, is it? It's counting all possible sequences of a specific length, not just the longest. As a result, I think you may have confused yourself in a few ways....

Naming

Your variable and method names are ... horrible. Variables should always be useful names, and, while N and K are referenced in the problem specification, S is not. Additionally, upper-case names are not encouraged... so you should have n and k instead. The method name LCIS is also off, it should be longest_increasing_sequence, and where does the C in LCIS come from?

Standards

Your code compiles OK (with a warning about the missing return in the main method) with basic C compiler. This makes me think you intend to use C99 which compiles it without warnings. But, in C99, you should declare your variables where they are used, not at the beginning of the blocks. For example, you should declare i inside the for-loop.

Globals

Globals are to be avoided.

Algorithm

Your concept of memoization is good, but I am not convinced the recursion is doing what you think it does. I am not convinced the memoization is used at all effectively. Frankly, I struggled to follow your algorithm, in part because memoization does not tell me much about what is being memoized...

I started hacking your code, and ended up restructuring it as a set of nested loops. The resulting complexity is somewhere around \$O(n^3)\$, which sounds really bad, but, for the problem given I am not sure can be improved on... A large part of the complexity is in the determination of the paths, not the combinatorics required to compute the count. I am likely wrong here somewhere, but my performance of the resulting code is more than good enough to be in the right ballpark...

So, I use memoization as well, the system I use is, for each node, starting from the last, to record the number of increasing paths, and how long they are, to the end of the sequence. The last node, for example, can be the last node in the sequence, and thus has a count of 1 in path-length 0 (0 because I zero-base the path length - 0 really means "there is 1 path starting from this node where this node is the last member too").

With that system, I can then work backwards through the sequence, and simply add up the paths that have the right length.

The critical method looks like:

long long count_sequences(const int *seq, const int size, const int path) {
    long long pathcounts[size][size];

    memset(pathcounts, 0, sizeof(pathcounts[0][0]) * size * size);

    long long count = 0;

    // start from end and work back.
    for (int i = size - 1; i >= 0; i--) {
        //printf("  start %d at %d\n", seq[i], i);
        // always 1 step from here to end.
        pathcounts[i][0] = 1;
        for (int j = i + 1; j < size; j++) {

            // check for increasing sequence
            if (seq[j] > seq[i]) {
                //printf("    next %d at %d\n", seq[j], j);

                for (int k = size - j; k >= 0; k--) {
                    pathcounts[i][k + 1] += pathcounts[j][k];
                }
            }
        }
        // zero-based path length - must subtract 1
        count += pathcounts[i][path - 1];
    }

    return count;
}

Note how, at each level we have to look ahead for increasing members, but, we only need to look in to the memoization for increasing members to accumulate path lengths.

Note also how we can accumulate the count as we retreat?

The entire program I have is:

#include <stdio.h>
#include <string.h>
#include <limits.h>

long long count_sequences(const int *seq, const int size, const int path) {
    long long pathcounts[size][size];

    memset(pathcounts, 0, sizeof(pathcounts[0][0]) * size * size);

    long long count = 0;

    // start from end and work back.
    for (int i = size - 1; i >= 0; i--) {
        //printf("  start %d at %d\n", seq[i], i);
        // always 1 step from here to end.
        pathcounts[i][0] = 1;
        for (int j = i + 1; j < size; j++) {

            // check for increasing sequence
            if (seq[j] > seq[i]) {
                //printf("    next %d at %d\n", seq[j], j);

                for (int k = size - j; k >= 0; k--) {
                    pathcounts[i][k + 1] += pathcounts[j][k];
                }
            }
        }
        // zero-based path length - must subtract 1
        count += pathcounts[i][path - 1];
    }

    return count;
}

int main(){

    int n,k;
    while(scanf("%d %d",&n,&k), n != 0 && k != 0) {

        int sequence[n];

        for (int i = 0; i < n; i++) {
            scanf("%d", &sequence[i]);
        }

        long long count = count_sequences(sequence, n, k);

        printf("%lld\n", count);
    }
}

On my computer, with -Wall and -O3, it runs the full dataset in 0.01 seconds.


I don't think it's worth having as one function. Why? Because you don't get to share any of the functionality. Your singular wrapped function just tests if there's a driver value and will execute one of two completely separate code blocks as a result. Instead, consider having the two functions separate, and then a single wrapper function that you can call which will determine which one to call.

In other words:

def get_page_source(url, driver="", element=""):
    if driver:
        return read_page_w_selenium(driver, url, element)
    else:
        return read_page_w_requests(url)

This way you only need to call get_page_source but you're not cramming two unrelated blocks into the same function.

Other notes, you shouldn't set driver as an empty string if you expect an object. Set the default value as None and then test for that.

def get_page_source(url, driver=None, element=""):
    if driver is None:
        return read_page_w_selenium(driver, url, element)

Also it's confusing to change the order of arguments. Make url first in both functions so that the order is consistent.

Instead of using text = None then return text. You could use a premature return and return None, though in Python that's equivalent to return. But I think even better would be the opposite, just use a premature return when you successfully get the text:

def read_page_w_requests(url):
    try:
        headers = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) \
                    Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'}
        r = requests.get(url, headers=headers)
        return r.text
    except Exception, e:
        print "Read page with requests error:", e

Now your exception doesn't even need to return None, because by default a Python function without an explicit return will just return None anyway.


Conceptually, when you want to perform an action at a fixed rate, you want to use an ScheduledExecutorService. This class is designed to handle the use-case of running code at a fixed rate, possibly with an initial delay. The advantage is that you can schedule more than one task, and it also lets you handle all the tasks, eventually cancelling some of them. It's not so much that the while(true) is an issue per se, but doing all those operations with that approach would be a lot more complicated. Furthermore, it wouldn't really let you perform other unrelated actions at the same time as the code getting the badges. Additionally, don't use the Timer class, and always prefer a ScheduleExecutorService, when you can use one.

Rewriting the code to use the service would actually make it more clear. First of all, you want a method that represents the action to perform:

private static void printBadges() {
    JsonArray weeds;
    try {
        weeds = getBadges().get("items").getAsJsonArray();
    } catch (IOException e) {
        e.printStackTrace(); // this should be replaced with a real logger
        return;
    }
    int numberOfWeeds = weeds.size();
    if(numberOfWeeds!=0) {
        System.out.println("[ [Badger](https://www.youtube.com/watch?v=dQw4w9WgXcQ) ] " + numberOfWeeds + " new [Tumbleweed posts](//stackoverflow.com/help/badges/63/tumbleweed)");
    }
    previousBadgeTimestamp = Instant.now();
}

With that method in place, scheduling the task is as easy as

ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(RunBadger::printBadges, 0, 10, TimeUnit.MINUTES);

This documents clearly what is happening, mainly that something scheduled at a fixed rate, and the delay is obvious: 10 minutes. The second parameter is a potential initial delay before performing the action the first time, which I set to 0 here.

A note about the exception handling. The current code catches the exception outside of the while loop, which means that any exception will stop the program from running; generally, this isn't want you want. An exception from getting the badges could occurs for multiple reasons and it shouldn't stop the rest of the code from running (although in this case, there is no other part of the code, but imagine this in a more complex scenario, with other tasks running concurrently). The scheduledAtFixedRate method will suppress the execution of future tasks, thereby cancelling the schedule, if there is an exception thrown by the task: this means that if an exception is thrown, nothing will get executed anymore. Catching and handling the exceptions inside the task, like done in the example above, lets you manage this.

The question of what should happen after scheduling the task remains. If you just want to run it for fun until you kill the process manually, you can just keep this in the main method:

public static void main(String[] args) {
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(Main::printBadges, 0, 1, TimeUnit.SECONDS);
}

The executor service won't be garbage collected and the action will run every 10 minutes, until you kill the JVM yourself. A cleaner approach would be to invoke executorService.shutdown(); when you want the process to stop, as it will correctly stop the executor, and let the main thread finish properly. (Note that it won't block until the tasks are finished; awaitTermination can be used for that). You just need to find the stopping condition, like a specific exception thrown in the task. It could be added as a runtime hook as well, but note that those hooks don't run when killing with SIGKILL.

Other thoughts:

JsonObject root = new JsonParser().parse(json).getAsJsonObject();
return root;

You don't need to store this in a temporary variable just before returning. Returning directly is just as clear, and doesn't introduce a variable.

return new JsonParser().parse(json).getAsJsonObject();

public static JsonObject getBadges() throws IOException

This may tie a bit the code fetching the badges to the code printing the result. In fact, you're only interested in the number of new items, so make that method return the count directly:

public static int getBadgesCount() throws IOException

This way, the rest of the code is hidden from the internal JSON representation of what the API returns.

public static Instant previousBadgeTimestamp

That's very good use of Instant: it represents a point in the timeline in UTC and isn't tied to any specific timezone. When you want to model at what time a system event took place, Instant is the perfect class.

private static final String apiKey = "my api key";

If the API key deserves its constant, why not all the other hard-coded Strings like badgeIdUrl or the rick-rolling very interesting link badger links to? You could even make all of those properties dynamic, by reading them from a file.

if(numberOfWeeds!=0) {

Since this number will never be negative, it is clearer to write

if(numberOfWeeds > 0) {

as it doesn't let the reader wonder whether accepting a negative value was intended or not.

Final point: keep in mind that the StackExchange API has a rate limit in place, and if the API returns a backoff, you have to wait that amount of seconds before making another call.


Joining WorkTypes to WorkGroups via Channels and Users to check authorization

I am understanding that your goal is to return a set of data that a user is authorized to see. I further understand that ChannelUsers and WorkGroupUsers are only used to validate the authorization. (I see you do select ChannelUsers.user_id but I don't think you really need it - you can take it from Users.id instead, I believe).

Given that, I believe you should test an alternative query to see whether this yield better performance. The SQL would be similar to this:

        SELECT
          ${view}
        FROM Timers
        INNER JOIN WorkTypes
          ON Timers.worktype_id=WorkTypes.id
          AND WorkTypes.channel_id=?
        INNER JOIN Channels
          ON Channels.id=ChannelUsers.channel_id
        INNER JOIN Users
          ON Users.id=?
        INNER JOIN WorkGroups
          ON WorkGroupUsers.workgroup_id=WorkGroups.id
        WHERE EXISTS (
            SELECT NULL
            FROM ChannelUsers
            WHERE ChannelUsers.channel_id=WorkTypes.channel_id
              AND ChannelUsers.user_id=Users.id
        ) AND EXISTS (
            SELECT NULL
            FROM WorkGroupUsers
            WHERE WorkGroupUsers.workgroup_id=Channels.workgroup_id
              AND WorkGroupUsers.user_id=Users.id
        );

The main advantage of using EXISTS is that it won't "duplicate" the results as a join would so you don't have to do a DISTINCT; it also stop searching as soon as it has found its match. If you have indices on ChannelUsers(channel_id, user_id) and WorkGroupUsers(workgroup_id, user_id this may help, as EXISTS can blow through the index and thus get an answer faster in that manner.

Profile the original SQL against this and see what you get. The results also will be less with the EXCEPT, so validate this is acceptable.


complement-of
The nicer way to write complement-of is with case instead of cond:
(case char
  ((#\A) #\T)
  ((#\T) #\A)
  ((#\C) #\G)
  ((#\G) #\C)
  (else char))

Function names generally shouldn't end in -of. (That's a way to pronounce function call, but it's not part of the name.) complement is enough. (Although some Schemes have a predefined function by that name, and it would be nice to not collide with it.)
Beware of eq? — it's not reliable on characters. (It's the equivalent of Java's == on Character). Use eqv? instead unless you know what you're doing. (case uses eqv? internally.)
apply-complements
You can simplify apply-complements by using one of Chicken's libraries: (use (srfi 13)) to get string-map, which is like map but saves you having to convert to a list. That plus string-reverse makes apply-complements easy.
...but I wouldn't call it apply-complements, because that sounds like a reference to the apply function. It returns the reverse complement of its argument, so that should be its name: reverse-complement.
If you want to make it faster, try the imperative approach: allocate a string with make-string, loop with do and string-set!. (It's useful to know how to write imperative code, even in functional languages.)
solve-problem
solve-problem has a very ordinary bug: you forgot to close the input port. :) Fortunately, there are functions that do this automatically so you don't have to remember: call-with-input-file and call-with-output-file. They're also safer, because they close the ports on nonlocal exits like exceptions.
The body of a let is an implicit begin, so the begin in solve-problem is not needed.
Formatting: when a function call is split across multiple lines, the arguments are usually aligned, like this:
(write-line (apply-complements (read-line infile-port))
            outfile-port)

solve-problem has a vague name. How about a description of what it does, such as reverse-complement-file? (Names are the best comments.)
...however, reverse-complement is only one of many operations you might want to apply to a file this way. I'd probably write it as a general-purpose transform-file that takes the operation as a parameter: (transform-file reverse-complement src dest). Or I'd write it as two separate operations for reading and writing, since they're often useful separately. (I'd also use read-string and write-string instead of read-line and write-line, so they'd work on files of more than one line.)


Using Factory pattern for parsing system

Design issues

You are unnecessarily restricting the Parser interface by forcing fs to be a std::ifstream& when std::istream& would work as well.
AParser::DoParsing(AData&, std::ifstream&) should be marked override. Same for BParser::DoParsing(BData&, std::ifstream&).
I can't see any specific purpose for IParsing: Why not call AParser::DoParsing or BParser::DoParsing directly?
Besides, parameter d of IParsing::action(std::shared_ptr<Parser<T>> p, T d, std::ifstream& fs) should be of type T&.
FParsing::HandleParsing(std::string, Data&, std::ifstream&) doesn't use any class instance members. Maybe make it static?
Also, parameter type from that function should probably be an enum - no need to use strings for that.
Why allocate two std::shared_ptr in case a valid parser is found if they won't be shared and will be deallocated once the function returns?
What advantage do you hope to get from this extravagant implementation over overloading operator>>(std::istream&, AData&) and operator>>(std::istream&, BData&) instead?


Since there's no real review to do and we're apparently just posting solutions... here's a simple O(n) time O(1) space one:
public static boolean find(int[] a, int z) {
    int i = 0, j = a.length - 1;
    while (i < j) {
        int sum = a[i] + a[j];
        if (sum == z)
            return true;
        if (sum < z) i++; else j--;
    }
    return false;
}

Explanation: Try the ends, i.e., add the smallest and largest value. If the sum is right, bingo. If the sum is too small, then the smallest value is useless (it would need to be added with a number larger than the largest). If the sum is too large, then the largest value is useless. So remove the useless one. But since actually removing it, i.e., creating an array without it, would be expensive, just work with indexes marking the ends of the still potentially useful part of the array.


Sending periodic heartbeats, wondering if there are any timer bugs

Just wondering why you don't set hasStarted = false either in the stop() or in the reset() method.

By doing it in the stop() you could omit the second if in the reset() method.

Seeing a reset() method at least screams for resetting all values to default.


Finding minimal spanning tree of a graph using Kruskal's algorithm

The first two comments already imparted a negative impression of the code — something you definitely don't want to do in an interview.

# Within code v = vertice, r = root, e = edge, u = union, m = make, f = find.

# Global Variables for simplifying code.

The first comment indicates that your function names are horrible.  The second comment indicates that you don't know how to use variables with the correct scope.

G = {
    'vertices': [0, 1, 2, 3, 4, 5, 6, 7],
    'edges': set([
        (1, 6, 5),
        (3, 5, 2),
        …,
        (2, 1, 7),
        ])
    }

Specifying the vertices is redundant, right?  All of the relevant vertices should already be mentioned as one of the endpoints of an edge.  (And if that is not the case, then you have a lone disconnected vertex, and it would be impossible to make a spanning tree.  Such is the case, in fact, with vertex 7 in your example.)

Furthermore, your Question3() function returns a graph as a set of edges.  It would also make sense that it accepts a graph as a set of edges.

The Question3 function should look more like this:

def kruskal_mst(graph_edges):
    vertex_parents = {
        v: v for v in itertools.chain(*[(v1, v2) for v1, v2, w in edges])
    }
    vertex_ranks = {v: 0 for v in vertex_parents}

    mst = set()
    for e in edges:
        v1, v2, weight = e
        if find(v1, vertex_parents) != find(v2, vertex_parents):
            union(v1, v2, vertex_parents, vertex_ranks)
            mst.add(e)
    return mst

print kruskal_mst([
    (1, 6, 5),
    (3, 5, 2),
    (5, 4, 9),
    …,
    (2, 1, 7)
])

Your code ignores edge weights completely.  (Note that your solution uses the (2, 4, 9) edge rather than the lower-cost (4, 2, 3) edge.  Also, to connect vertex 3 into the MST, it uses the (2, 3, 6) edge rather than (3, 5, 2).)


Implementation of Permutation Algorithm B from Topor, 1982

Overall the code is pretty decent, but if you strive for perfection :-), I can offer a few observations from my side.

1. Generics notation

For generic types with a single generic parameter, F# has an alternative syntax, where you put the parameter in front of the constructor, not in angle brackets - e.g. int list instead of List<int> (note the lower-case list by the way - that is also idiomatic).

For example:

let rec mapcons (a: 't) (ps: 't list list) (qs: 't list list): 't list list =

2. Type signatures

Unlike some other ML-style languages (looking at you, Haskell :-), it is not commonplace for F# functions to have explicit type signatures. As a rule, F# code will only have type signatures either in the most tricky places, as documentation, or else in places where the compiler can't do without it, like with objects or interfaces.

Your functions are trivial enough (or at the very least, they don't really gain anything from type signatures) that I would leave the signatures off. For example:

let rec mapcons a ps qs =

3. Explicit recursion

Recursion is bleh. Don't get me wrong, it's super helpful, and the basis of a lot of stuff, we couldn't really live without it. But writing it explicitly is generally bleh. It's hard to get right, and it turns out that most linearly recursive algorithms can be reduced to just a few common patterns (and ultimately - to just fold).

Take your mapcons function: it first prepends a to every list in ps, and then concatenates qs to that. Well, if you want to transform every element of a list, there's an app for that - map:

let mapcons a ps qs = List.map (fun p -> a :: p) ps @ qs

Alternatively, I would consider a list comprehension:

let mapcons a ps qs = [for p in ps -> a :: p] @ qs

This produces the same effect, but looks differently. I'm on the fence about which one I would prefer, but I'm leaning towards the list comprehension.

4. Some trivial mistakes

As already pointed out in the comments (I wasn't quick enough), your removeFirst function needs to be rec, and mapperm + permute should be a recursive block with let rec ... and ....


packagetarget_close()

First of all, you have a copy-and-paste error in packagetarget_close(), where you attempt to free target->min twice, but not target->max.

Next, note that most of the if statements are superfluous.  As per the standard behaviour for free(),

  If ptr is a null pointer, the function does nothing.

packagetarget_open()

You have undefined behaviour due to the way your error-handling works.  The chunk of memory returned by malloc() contains arbitrary junk.  If packagetarget *target = (packagetarget*) malloc(sizeof(packagetarget)) succeeds, but one of the setters fails, then you would call packagetarget_close(), which would then interpret that arbitrary junk as pointers to memory to be freed.  A good way to fix that is to zero the memory before calling any of the setters.  You can either use calloc() instead of malloc(), or memset(), or a struct initializer.

Avoiding malloc()

In C, I prefer the init-cleanup idiom over new-destroy (which you call open-close).  In the init-cleanup idiom, the caller is responsible for providing the chunk of memory to be initialized, which gives the caller the option of providing either stack-based or heap-based memory.

Avoiding goto

While indiscriminate use of goto leads to spaghetti code, there are some circumstances where goto is justifiable, if used in a readily recognizable pattern.

I think that your use of goto isn't horrible, but personally I would prefer to write the if statements as a chain of && expressions.

Suggested solution

#include <stdlib.h>
#include <string.h>

typedef struct packagetarget {
    char *name;
    char *sys;
    char *arch;
    char *min;
    char *ver;
    char *max;
    linkedlist comp;
} packagetarget;

int packagetarget_setname(packagetarget *target, const char *name) {
    if (!target) return 1;
    if (!name) return 2;
    target->name = realloc(target->name, strlen(name) * sizeof(char));
    if (!target->name) return 3;
    strcpy(target->name, name);
    return 0;
}

int packagetarget_setsys(packagetarget *target, const char *sys) {
    …
}

int packagetarget_setarch(packagetarget *target, const char *arch) {
    …
}

int packagetarget_setmin(packagetarget *target, const char *min) {
    …
}

int packagetarget_setver(packagetarget *target, const char *ver) {
    …
}

int packagetarget_setmax(packagetarget *target, const char *max) {
    …
}

packagetarget *packagetarget_cleanup(packagetarget *target) {
    if (target) {
        free(target->name);
        free(target->sys);
        free(target->arch);
        free(target->min);
        free(target->ver);
        free(target->max);
        linkedlist_cleanup(&target->comp);
    }
    return target;
}

packagetarget *packagetarget_init(packagetarget *target) {
    static const packagetarget empty = {};
    if (target) {
        *target = empty;
        if (!(0 == packagetarget_setname(target, "") &&
              0 == packagetarget_setsys(target, PACKAGETARGET_SYS) &&
              0 == packagetarget_setarch(target, PACKAGETARGET_ARCH) &&
              0 == packagetarget_setmin(target, PACKAGETARGET_MIN) &&
              0 == packagetarget_setver(target, PACKAGETARGET_VER) &&
              0 == packagetarget_setmax(target, PACKAGETARGET_MAX) &&
              linkedlist_init(&target->comp))) {
            packagetarget_cleanup(target);
            return NULL;
        }
    }
    return target;
}

int main() {
    packagetarget t;
    if (packagetarget_init(&t)) {
        …
    }
    packagetarget_cleanup(&t);
}


Retrieve random element from array not contained in second array

The choice of the algorithm will depend on how many elements you have in your array, and how many of them you want to select. If you want to pull all names in random order, then shuffling is probably the best choice.

You can easily create a copy of names using names.slice() and shuffle the copy instead of the original array:

function randint(a, b) {
    return a + Math.floor(Math.random() * (b - a));
}

function shuffle(list) {
    list.forEach(function(value, i) {
        var j = randint(i, list.length);
        list[i] = list[j];
        list[j] = value;
    });
    return list;
}

var names  = ['Steve', 'Adam', 'Phillip', 'Thomas', 'John', 'Joseph'];
console.log(shuffle(names.slice()));

Alternatively, you can shuffle an array of numbers [0..N], and use them as indices to the names array:

function range(start, stop) {
    var list = [];
    for (var i = start; i < stop; i++) {
        list.push(i);
    }
    return list;
}

var indices = shuffle(range(0, names.length));

indices.forEach(function(i) {
    console.log(names[i]);
});

Shuffling has a much better time complexity than the original algorithm. For an array of 1000 names, the innermost loop of the original algorithm is executes ~6 million times, while the innermost loop of the shuffle algorithm is executed only 1000 times.


Calculating sum of primes using the CPU and GPU

Try not to use using namespace std.
This is lacking in curly braces and could be bad for maintenance:

if(n == 2)
    return true;
if(n % 2 == 0)
    return false;
uint32_t sr = sqrtf(n);

for(uint32_t i = 3; i <= sr; i += 2)
    if(n % i == 0)
        return false;
return true;

It's a good idea to still use them for single-line statements, and you should especially use them with for loops.  Some extra whitespace in places could be useful as well.

Here's what it should look like:

if (n == 2)
{
    return true;
}
if (n % 2 == 0)
{
    return false;
}

uint32_t sr = sqrtf(n);

for (uint32_t i = 3; i <= sr; i += 2)
{
    if (n % i == 0)
    {
        return false;
    }
}

return true;

Consider finding an alternative to sqrtf() as it can be slow.  It may not make a huge difference in overall runtime, though.  Fortunately, it appears to be thread-safe.
One source of slower performance may be the if statement in prime_sum().  Doing so may cause thread divergence, if threads end up executing different instructions.  You'll have to analyze your code to determine this for sure.
This line seems confusing:

start = time(0) - start;

It appears that the lvalue should instead be named end since you already calculate a starting time beforehand.


Welcome to Code Review.

I would be going through this code quickly.

Read PEP 8. It is de facto standard for coding in python. Generally, we name the variables in lower_case_with_underscore, and any constant used as CONSTANT_UNDERSCORE.
Use in-built functions. You are using your letters_table to find out whether the character is alphabet or not, use isalpha() instead. Similarly you can use ord and chr functions which would allow you to preserve case. Using all of these functions would remove the need of letters_table
Keep consistent comments. Your comments indicated that key default value is 3. It is not, and if I leave input blank, it would raise error.
Make your code modular. You can easily separate your I/O logic with implementation logic. (Use functions)

Since you indicate you want to improve this code yourself, I would refrain from posting refactored version of your code. (If you want me to as an example, I can do that).

Here are some more improvements which you could incorporate:

Allow user an option to select between encryption and decryption mode. (with functions, this would be done by having an extra parameter with default value)
Other encryption logic while maintaining the same I/O logic. (Would help you understand power of function modules)

Some Python code quality skills which might be handy in future:

Write useful docstring (see examples in link). While for this
program, your comments are more than enough, it is useful skill.
Learn to write some assertion tests and then unit tests.


Computing features over the same dataframe

If I was reviewing this code professionally, my first comment would be that you should stick to a style guide. This will govern things like spacing between statements, brackets, operators etc. It can be seen as a kind of nitpicky remark (I certainly did at first) but having a consistent style massively aids readability for you and for others.

The second (style) comment would be that your code is halfway between very pipe-based code and "standard" R style (lots of assignment). This makes it difficult to read. If you're going to go with pipes, stick with it.

Also, when using an ifelse with more than 2 conditions, it's often clearer to use a switch block. This reduces the potential for massive nested ifs, and should also discourage you from doing much branching within the if.

I don't really like how similar the summarise calls are in each case. Ideally I would refactor that, but I think that is somewhat tricky due to how dplyr handles n and n_distinct.

This is how I would rewrite your code, though I would also consult the tidyverse style guide to see their recommendations -- I generally try to avoid programming with dplyr so I'm not that familiar with the style.

filter_by_day_segment_refactor <- function(data, day_segment) {
  ## Minimise the amount done within the if/else clause (also reduces duplication)
  if (day_segment == "daily") {
    fun <- identity
  } else {
    fun <- function(x) filter(x, day_segment == local_day_segment)
  }
  data %>% fun() %>% group_by(local_date)
}

compute_metric_refactor <- function(data, metric, day_segment) {
  ## 3 case switch block with just 1 pipe each,
  ## rather than 3 conditionals with a mix of
  ## pipes and assignment
  switch(metric,
    "countscans" = {
      data %>%
        filter_by_day_segment(day_segment) %>%
        summarise(!!paste("sensor", day_segment, metric, sep = "_") := n())
    },
    "uniquedevices" = {
      data %>%
        filter_by_day_segment(day_segment) %>%
        summarise(!!paste("sensor", day_segment, metric, sep = "_") := n_distinct(value))
    },
    "countscansmostuniquedevice" = {
      data %>% group_by(value) %>%
        mutate(N = n()) %>%
        ungroup() %>%
        filter(N == max(N)) %>%
        filter_by_day_segment(day_segment) %>%
        summarise(!!paste("sensor", day_segment, metric, sep = "_") := n())
    }
  )
}


Correct implementation of Factory pattern in C++

Few small problems with the factory.

You are using a pointer to a method.

        typedef Task* (*create_callback)(map<string, string> vMap);

As the way of creating your object. This is very C like. It also introduces the possibilities of passing a NULL pointer (which is not good).

The more idiomatic way to to declare a functor:

struct TaskCreator
{
    // Leaving Task* for similarities to current code (I will get back to it).
    Task* operator()(std::map<std::string, std::string> vMap) const
    {
        return build(vMap);
    }
    private:
        virtual Task* build(std::map<std::string, std::string> vMap) const =  0;
};

Register objects

Now you should register objects derived from this class with the factory. This will prevent you accidentally passing NULL as a callback.

// This looks incant because there are no `*` here
// But there is a hidden '*' in create_callback
static void register_task(const string& type, create_callback cb);

// I would change this too:
// Notice I am not using `static` here. I will get to that in a second.
void register_task(const string& type, TaskCreator& cb);
                                          //     ^^^  That is important.
// Alternatively you can register via smart pointers.
// But I prefer to pass references. Then make the `TaskCreator` automatically
// Register themselves in their constructor.

Order of construction

You also have another invisible problem in the order of construction across compilation units. Remember that the order of construction of static storage duration objects is undefined across compilation units.

static map<string, create_callback> mTasks;

This object is constructed before main() is called. The problem is you do not know exactly when. As a result if you call register_task() before main() you don't know if it will work because the storage mTasks may not have been created yet.

There are a couple of ways of solving this. The easiest to use a static member of a function as the storage.

static map<string, create_callback>& getTaskStorage()
{
    static map<string, create_callback> mTasks;
    return mTasks;
}

But I would go the other way. And use a factory object pattern.

Factory object

You are using a set of static methods as your factory. I would swing this around and actually create a factory object. The problem with static functions is that it is hard to use test code with them. It is much easier to mock an object than static API.

Ownership

Last. You are not expressing ownership semantics for the created object.

static Task* create_task(const string& type,map<string, string> vMap);

A pointer Task* is totally useless in this situation as you have no idea if the ownership is being retained by the factory (and it will destroy it) or if ownership is being returned to the caller so he can destroy it.

Here you have two options:

Return a reference.

This indicates that the factory is retaining ownership of the created object. This means the object will be destroyed when the factory is destroyed (This implies a factory object).

Return a smart pointer

By returning a smart pointer you are indicating somthing else has ownership. The type of ownersip depends on the type of smart pointer (unique_ptr: ownership is returned to the caller, shared_ptr: ownership is shared and the loss of the last reference will delelte it).

Further Advice.

I would suggest some more specific recommendations. But unfortunately you do not provide the expected usage semantics of your factory. Thus I may write something that is tially usless. If you can write some more details on how you think the factory is going to be used I can give you some more concrete information.

Errors in the code:

class Task
{
     static Task* create(map<string, string>);
};

If you take this address it does not match:

typedef Task* (*create_callback)(map<string, string> vMap);

There is nothing in the standard that guarantees that the calling convention of a normal function matches the calling convention of static methods. It just happens to work on your compiler but it is non portable.

As stated above: What happens of somebody registers a NULL function.

return mTasks[type](vMap);

This line is likely to fail. Using your method you need to validate that the pointer is not NULL wither at the point of setting or at the point were it is used.


Print factors of number using fencepost loop

Just a tiny note:

  In number theory, integer factorization is the decomposition of a composite number into a product of smaller integers.

So a factorization of 12 may be

6 * 2

or

3 * 2 * 2

but not

1 and 2 and 3 and 4 and 6 and 12

What you did is finding all divisors and you should name your method appropriately.

As always, a method both computing and printing something is rather unusable. You should always compute the result in one method, so that you can later either print it or process it further.

For simple methods like yours it doesn't matter much, but it's good habit.


Makefile for a C++ project using Boost, Eigen, and htslib

Couple of things you do that don't match standards.

CXX is usually the C++ compiler
CC  is usually the C   compiler.

CXXFLAGS  are the flags that are applied to the C++ compiler.
CPPFLAGS  are the flags that are applied for the pre-processor.
          This usually means passed to both C and C++ compiler.

CFLAGS    are the flags passed to the C compiler.

LDDFLAGS  are the flags passed to the linker.

Why are you building the tests into your main executable?
Should the test application be generated as a seprate application that includes the normal objects (apart from main) and the test objects.

Why do you have libs outside your lib variable?

$(LIBS) -L $(HTSLIB)

You should have a line earlier in your make file like:

# This adds more libs to the current set of libs.
LIBS    += -L $(HTSLIB)

I am confused why you are including -I ${BOOST} for the C compiler but not the C++ compiler. I did not think there was anything in the boost that could be used by C (I could be wrong but seems strange).

The default rule for C/C++/Linking are:

$(CC)  $(CPPFLAGS) $(CFLAGS) -c
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c
$(CC)  $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)

Unless you need to change these I would not. This means adding values to the existing variables.

Something like this (untested):

# Addition Packages.
SRC_PACKAGES = BOOST EIGEN
LIB_PACKAGES = HTSLIB

# Boost C++ library
ROOT_BOOST▸ = /usr/local/include/boost_1_64_0

# Linear-algebra library
ROOT_EIGEN = /usr/local/Cellar/eigen/3.2.8/include/eigen3

# HTSLIB library for reading BAM files
ROOT_HTSLIB = /Users/tedwong/Sources/QA/htslib

#
# Turn on BFD by compiling with
# make -DHASBFD=1
DFLAGS_1▸   = -DBACKWARD_HAS_BFD # https://github.com/bombela/backward-cpp
DFLAGS▸ ▸   = $(DFLAGS_$(HASBFD))

EXTRA_INCLUDE_DIR▸  = $(foreach loop, $(SRC_PACKAGES) $(LIB_PACKAGES), -I$(ROOT_$(loop)))
EXTRA_LIB_DIR▸  ▸   = $(foreach loop, $(LIB_PACKAGES),                 -L$(ROOT_$(loop)))

# Compiler
CXX▸▸   ▸   = g++
CC▸ ▸   ▸   = $(CXX)
CPPFLAGS▸   += -g -O2 $(EXTRAFLAGS) $(DFLAGS) -Isrc -Isrc/stats
CFLAGS▸ ▸   +=
CXXFLAGS▸   += -std=c++11

# Linker
LDFLAGS▸▸   += $(EXTRA_LIB_DIR)
LDLIBS▸ ▸   += -lpthread -lz -lhts

# Application
SRC_DIR▸▸   = src src/tools src/analyzers src/RnaQuin src/VarQuin src/MetaQuin src/data src/parsers src/writers src/stats src/cufflinks

EXEC        = anaquin
SOURCES     = $(wildcard $(foreach loop, $(SRC_DIR), $(loop)/*.cpp))
OBJECTS     = $(patsubst $(SOURCE), %.cpp, %.o)

$(EXEC): $(OBJECTS)

.PHONEY: clean
clean:
    $(RM) $(EXEC) $(OBJECTS) $(OBJECTS_TEST)


I noticed your commenting style and decided it's worthy of it's own answer.

You admit the comma is not always a comma. So don't call it a comma. I went for separator, which is as neutral as it gets. If you think of something better, go for it.

Also, I think your comments would fit better as a docstring than as comments.

class DecimalValidator(QDoubleValidator):
    def __init__(self, *args):
        QDoubleValidator.__init__(self, *args)
        self.setNotation(QDoubleValidator.StandardNotation)
    def validate(self, input, pos):
        '''
        When we're left of the separator, and separator is pressed,
        remove the inserted separator and move right of the old separator.
        When we're right of the separator, and all decimal places are used already,
        go into overwrite mode (by removing the old digit)
        '''
        sep = self.locale().decimalPoint()
        if pos and (input[pos-1]==sep) and (sep in input[pos:]):
            input = input[:pos-1] + input[pos:]
            pos = input.find(sep)+1
        elif sep in input[:pos] and (len(input.split(sep)[1]) > self.decimals()):
            input = input[:pos] + input[pos+1:]
        return QDoubleValidator.validate(self, input, pos)


Put a lot of work into refactoring this code, trying to maximize for readability and simplicity in an effort to increase maintainability. I'm posting my results here since I know creating recursive, dynamic, no-plugin navigation is an issue Jekyll users often face, and some are likely to land here searching for a solution.

nav.html

{% comment %} Init call with base_url (optional) and max_depth. {% endcomment %}

{% if lvl_base_url == nil %}
  {% assign lvl_base_url = '/' %}
  {% if include.base_url %}
    {% assign lvl_base_url = include.base_url %}
  {% endif %}
{% endif %}

{% assign current_lvl_url_length = lvl_base_url | split: '/' | size %}
{% if lvl_base_url == '/' %}
  {% assign current_lvl_url_length = 1 %}
{% endif %}

{% capture links %}
  {% for node in site.pages %}
    {% assign node_url_length = node.url | split: '/' | size | minus: 1 %}
    {% assign filename = node.url | split: '/' | last %}
    {% if node_url_length == current_lvl_url_length and node.url contains lvl_base_url and filename != 'index.html' and filename contains 'html' %}

        {{ node.title }}
        {% if include.max_depth > current_lvl_url_length | plus: 1 %}
          {% assign lvl_base_url = node.url | replace: '.html' | append: '/' %}

          {% comment %} Include can access parent state; hence no variables passed explicitly: {% endcomment %}
          {% include nav.html %}

          {% comment %} Reverse state changes made by child: {% endcomment %}
          {% assign current_lvl_url_length = current_lvl_url_length | minus: 1 %}
          {% assign directory_to_remove = lvl_base_url | split: '/' | last | append: '/' %}
          {% assign lvl_base_url = lvl_base_url | replace: directory_to_remove %}
        {% endif %}

    {% endif %}
  {% endfor %}
{% endcapture %}

{% assign links = links | strip %}

{% if links.size > 0 %}

{{ links }}

{% endif %}

header.html [example usage]

    {{ site.title }}

        <svg viewBox="0 0 18 15">
          <path fill="#424242"
                d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.031C17.335,0,18,0.665,18,1.484L18,1.484z"/>
          <path fill="#424242"
                d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484 h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z"/>
          <path fill="#424242"
                d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z"/>
        </svg>

      {% if page.url contains '/academy' %}
        {% include nav.html base_url='/academy/' max_depth=3 %}
      {% elsif page.url contains '/college' %}
        {% include nav.html base_url='/college/' max_depth=3 %}
      {% else %}
        {% include nav.html max_depth=2 %}
      {% endif %}


The code looks reasonably short and clear, that's good.
It's obvious that you are a beginner though since your code layout is inconsistent in a few places.  Formatting the code consistently is mostly a boring task, that's why several people wrote programs to perform this formatting automatically.  There are many different formatting styles, try one that fits your own liking and use that style consistently.
One of these programs is ClangFormat.
The result of formatting your code with the default settings is:
#include <stdio.h>

#define MAX_SIZE 100 // Maximum size of the array

int main() {

  int arr[MAX_SIZE];
  int size;
  int i, j, k;

  printf("Enter size of the array : ");
  scanf("%d", &size);

  printf("Enter elements in array : ");
  for (i = 0; i < size; i++) {
    scanf("%d", &arr[i]);
  }

  for (i = 0; i < size; i++) {
    for (j = i + 1; j < size; j++) {

      if (arr[i] == arr[j]) {

        for (k = j; k < size; k++) {
          arr[k] = arr[k + 1];
        }

        size--;

        j--;
      }
    }
  }

  printf("\nArray elements after deleting duplicates : ");
  for (i = 0; i < size; i++) {
    printf("%d\t", arr[i]);
  }

  return 0;
}

In this version, the indentation of each line tells the reader which pieces of the code belong together. In your original version, this was not easy to see.
To advanced programmers, the consistently formatted version looks calm and ordered, just like code should look like. Your original version instead looks chaotic. So far for the first impression.

At your current stage of learning to program, you probably didn't learn how to define functions yet. Functions are an important way to structure your code, so that you can highlight the interesting parts of the code. In this case, the most interesting function of the code would be "remove duplicate elements from an array, given by the first element and the size of the array". In C, this is written like this:
// Removes duplicates, returns the new size of the array.
// Keeps the order of the original elements, removing the duplicates that occur later.
static int
remove_duplicates_from_int_array(int *arr, int arr_size)
{
    // TODO: actually implement this function
}

Separating the code that removes the duplicates from the rest of the code makes it possible to test and analyze this part of the code on its own. For example you can write a standard test case:
#include <assert.h>

...

    size = 3;
    arr[0] = 1;
    arr[1] = 3;
    arr[2] = 1;

    size = remove_duplicates_from_int_array(arr, size);

    assert(size == 2);
    assert(arr[0] == 1);
    assert(arr[1] == 3);

With this code, you don't have to enter the size and the elements yourself anymore, which is a huge time-saver.
Even better would be to extract this test code into its own function:
static void
test_remove_duplicates_from_int_array(void) {
    // the code from above
}

This allows you to quickly run this test code at the start of the program, to ensure that the code still works for the basic test cases, before you even start entering your own test cases manually. Again, this saves a lot of time.

When you carefully inspect your code and "run" it with pen and paper, you will notice that the code reads data from outside of the array. This bug needs to be fixed before you should think about performance. Having fast and wrong code is usually worse than slow and correct code.
This bug is not easy to find when you only look at the input and output, since everything seems to work fine. The tricky thing is that reading from outside of an array invokes undefined behavior, and this means that nothing at all is guaranteed when running this program. To really run into this undefined behavior, you have to enter the array size as 100 and actually enter exactly 100 array elements, something you probably never did since it is quite an effort. Therefore, for simpler testing, you should reduce MAX_SIZE to around 5. This allows you to test the edge cases more quickly.
Except for this bug, the code looks reasonable. After you have fixed this bug, you can start thinking about making the code run faster. That's the tricky part though. As long as the array is short, your current approach is simple and easy to understand. Only if your arrays grow larger you need to get concerned about the algorithm's complexity, which is currently \$\mathcal O(\mathrm{size} \cdot \mathrm{size} \cdot \mathrm{size})\$. That is, for an array with 1000 elements, you would need a billion steps.
To design a more efficient algorithm, print out a sheet of paper with 1000 random numbers and remove the duplicates manually, asking yourself what you do in each step and why. One idea may be to sort the numbers, after which it is much easier to remove the duplicates. But then you lose the original order of the numbers, which may or may not be acceptable.
So far for a few ideas, I'm not going to solve everything for you. :)


The code itself looks good, but I would look into providing a single way of subscribing to events, it will make the job easier for other developers reading and changing the code.

The first method of subscribing (via IEventBroker<T> injection) requires subscriber object to be created first, so it may not receive all events that you may expect it to receive. Every time you create an instance of subscriber it adds a new event subscription thus causing potential memory leaks and side effects. You might need to add Unsubscribe method to IEventBroker<T> if you prefer to leave it.

Second method (the one I would prefer) is better suited for application-wide events since it moves the responsibility of subscription to the infrastructure thus avoiding multiple subscriptions and memory leaks (comparing to first option). It is also easier to unit-test since part of responsibilities are taken away from subscriber.

Update based on question update: Publishing messages also looks good. In this case (following my suggestion to leave only second method of event subscription) I would remove Subscribe method from IEventBroker<T> declaration, and refactor it to non-generic IEventPublisher interface with generic method void Publish<T>(T eventToPublish).


Generate word list based on Spanish text file

Some notes:

open + read + close: Better to use the block form: contents = File.open(path) { |fd| fd.read  } or simply contents = File.read(path)
words = words.something: Don't re-use variable names. New values, new names. For example: sorted_words = words.sort.
Use File.write
Instead of removing chars that you don't want, I'd remove the chars that you do want.
You can apply the processing to the whole file or line and then split.
string.tr(something, '') -> string.delete(something).

I'd write:

words = File.read("quijote.txt").downcase.
  tr("ÁÉÍÓÚÑ", "áéíóúñ").delete("^[a-z]áéíóúüñ \n").
  split.uniq.sort
File.write("quijote-words.txt", words.join("\n"))

If your input file is not UTF8-encoded but, let's say, ISO8859-15, you'd write: File.read("quijote.txt", encoding: "iso8859-15").encode("utf-8").


Passing multiple parameters from the command line in Java

Extract out the common logic before the if. The following is more or less the same:

noOfThreads = Integer.parseInt(args[0]);
noOfTasks = Integer.parseInt(args[1]);
startRange = Integer.parseInt(args[2]);
tableName1 = args[3];
databaseNames.add(tableName1);
if (args.length >= 5) {
    tableName2 = args[4];
    databaseNames.add(tableName2);
}
if (args.length >= 6) {
    tableName3 = args[5];
    databaseNames.add(tableName3);
}

Note that running the program with less than five parameters only prints an exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at ...Main.main(Main.java:16)

You should handle this and print a user friendly error message or usage help.


Couple nitpicks:

Try to stick to PascalCasing for method names. Using _ underscores not only makes your method names look rather messy, the underscore is conventionally used for event handler methods (like Form1_Load, i.e. object_event).
Consistency is king. Your two snippets aren't consistent as far as parameter naming goes: you're using PascalCasing in your top example, and camelCasing in the bottom one. Pick one, stick to it.
The term generic has a specific meaning in the .net world. That's not a generic function. General-purpose, maybe?

A quick Google search didn't yield much interesting results in VB.net, but this StackOverflow answer has a decent C# version of the code - and it just happens to be an actual generic method:

  Most methods in the array class only work with one-dimensional arrays, so you have to perform the copy manually:

T[,] ResizeArray<T>(T[,] original, int rows, int cols)
{
    var newArray = new T[rows,cols];
    int minRows = Math.Min(rows, original.GetLength(0));
    int minCols = Math.Min(cols, original.GetLength(1));
    for(int i = 0; i < minRows; i++)
        for(int j = 0; j < minCols; j++)
           newArray[i, j] = original[i, j];
    return newArray;
}

Now I know this isn't VB, but an array is an array regardless of the language, so I strongly recommend you take a look at the SO answer, as it goes in much more details than I'd care to quote over here.

Bottom line: You cannot use Array.Resize() with multidimensional arrays.


Generic repository with UoW and simple injector

Putting aside the fact that EF already provides both a UoW and Generic Repository, there's still a huge flaw with your UnitOfWork. It disposes a resource it doesn't own. You pass the context in as a constructor arg, store it as a member, and then code analysis yelled at you for not implementing IDisposable, so you disposed of it. The problem is, the UoW has no way of knowing that it's supposed to dispose of the context, because it was injected into the class.

In all the years I've been working with .Net, not once have I actually needed to implement IDisposable. Every single time that I thought I needed to, I didn't. I just needed to keep the lifetime of the IDisposable short and contained within a using block. That's possible if you abandon this folly and implement a domain specific service instead.

public class EFWidgetStore : IWidgetStore
{
    private readonly Func<DbContext> GetContext;
    public EFWidgetStore(Func<DbContext> contextFactory)
    {
        GetContext = contextFactory;
    }

    public Widget Get(int id)
    {
        using (context = GetContext())
        {
            //... get it
        }
    }

    public Widget Get(string name)
    {
         //...
    }

Next up, you've broken Liskov's substitution principle, which is common for these kinds of implementations.

public Task<PagedResult<T>> Find(Expression<Func<T, bool>> predicate, int pageNumber, int pageSize)
{
    throw new NotImplementedException();
}

Although, let's be honest. When will you ever treat a specific repository as an instance of the base class anyway... You've introduced a world of hurt on yourself for no gain what so ever. Please don't do this.


Returning the path to PHP pages for a layout and a view, if they exist

Yes, there is a way:

Identify all parts that differ in the two functions.
Write a new function that takes each of these differences as a parameter.
From the existing functions, call the new function, passing the appropriate values as parameters.
Compare the resulting code with the original code to see whether the refactoring was worth it.

Hint:

   In this case, the differing parts are configKey, fileName, suffix and errorMessage.


Splitting uppercase letters based on a dictionary

Your big O is roughly O(N^2) if you consider your dictionary to be static.

I don't see anything in your solution that I would classify as dynamic programming.  Maybe you could make a DP solution by pre-parsing your dictionary so you don't check substrings multiple times but instead check each letter against each still-matching word.  Some more test cases might turn up some interesting bugs, too.


Write Once Use Everywhere: Multidimensional array traversal

where individual cells reside in an n x n region, and those regions
  reside in an n x n area

First problem, there are no Area or Region or Cell in the code provided.

  I need to be able to address both the regions and the individual cells
  within the regions separately.

Then you should have written something like

class Area {
    Region getRegion(int row, int col);
}

class Region {
    Cell getCell(int row, int coll);
}

class Cell {

}

  so I could write it once and use it everywhere:

Then you should write something composable. void exec(...) is not very composable; because it returns void it can't be pipelined. Extract Streams (or methods returning a value), and keep Consumers (or methods returning void) simple.

For example if your utility method traverseDoubleRowMajor were something like :

Stream<Cell> cellsOf(Area area)

instead of :

TraversalUtil.traverseDoubleRowMajor( (i, j, k, m) -> {
    System.out.println(getCellAt(i, j, k, m)); // or whatever
});

you could then simply do :

 cellsOf(area).forEach(System.out::println);

So how could you write a cellsOfRegion? It'd be easy if you'd first made areas and regions etc explicit as I've shown above:

private static Stream<Cell> cellsOf(Area area) {
    return gridElements(BOUND, BOUND, area::getRegion)
            .flatMap(region -> gridElements(BOUND, BOUND, region::getCell));
}

private static <R> Stream<R> gridElements(int maxRow, int maxCol, BiFunction<Integer, Integer, R> f) {
    return IntStream.range(0, maxRow).boxed().flatMap(row -> (
            IntStream.range(0, maxCol).boxed().map(col -> f.apply(row, col))));
}

EDIT

  For low iterations, how big is the performance hit for setting up the
  pipeline for a steam?

Short answer, you should try for yourself. Longer prediction: In almost all cases IO dominates anyway. Where IO is not involved memory access should dominate. And a pipeline using streams should be faster than a pipeline that puts the intermediate results in collections.

List<A> inputElements = elementsOf(input);
List<A> result1 = pipelineStep1(inputElements);
List<A> result2 = pipelineStep2(result1);
// etc etc...
B resultN = pipelineStepN(resultNMinusOne);

should be slower than

B result = elementsOf(input)
    .filter(pipelineStep1)
    .flatMap(pipelineStep2)
    // etc etc...
    .collect(pipelineStepN);

  And second, is there a way to achieve different traversal orders (i.e.
  not just row major)?

Sure, one solution would be:

private static <R> Stream<R> colMajor(int maxRow, int maxCol, BiFunction<Integer, Integer, R> f) {
    return IntStream.range(0, maxCol).boxed().flatMap(col -> (
            IntStream.range(0, maxRow).boxed().map(row -> f.apply(row, col))));
}

Or with less repetition just

private static <R> Stream<R> colMajor(int maxRow, int maxCol, BiFunction<Integer, Integer, R> f) {
    return gridElements(maxCol, maxRow, (col, row) -> f.apply(row, col);
}

If you do this you may consider renaming method and parameter names accordingly. e.g. instead of names like row and col in gridElements, which you now would be using for both row-major and col-major traversal; canonical names for integer function parameters/loop counters i, j or m, n etc.


The code looks fine but has a few flaws and can be improved. I didn't solve the flaws and change the code: I've left that as an excercise for you.

In general:

Why do you use function expressions instead of function declarations?
I recommend to always use braces, even for single line if statements or for loops. Omitting braces will bite you eventually.
What happens when the parameters of your functions are not numbers or are undefined?

Your code, with my comments added as review points:

// sum(x,y) takes the sum of two numbers
var sum = function(x,y){
    return x + y;
};

// range(x,y,step) gives an array of the range of x and y, with an optional step argument
var range = function(x, y, step){
    if (step == null) step = 1;

    // why do you call this variable arr?
    // It's better to use a meaningful name like result.
    var arr = [];

    // what happens when y is less than x?
    // what happens when step equals zero?

    if (step > 0) {
        for (var i = x; i <= y; i += step)
            arr.push(i);
    } else {
        for (var i = x; i >= y; i += step)
            arr.push(i);
    }
    return arr;
};

// rangeSum(start,end) gives the sum of the range from start to end.
// why do you use other argument names than in the range function?
// it's better to use consistent names.
// By the way: the names of these argument are better than the arguments
// of the range function, so I'd change those to start and end.
var rangeSum = function(start,end){

    // why so complex? You can iterate over the range once and keep a running total.

    var arr = [];
    for (var i = start; i <= end; i++)
        arr.push(i);
    return arr.reduce(function(a,b){
        return a + b;
    });
};


Is there a better way to write insertion sort?

Other than rewriting it in a less pseudo-code-like way:

const insertion = ( array ) => {

    if(!Array.isArray(array))
        throw new Error("array must be an Array");

    if (array.length === 0)
        return [];

    //shallow copy
    const clonedArray = array.slice();

    //Optimized iterative version: https://en.wikipedia.org/wiki/Insertion_sort
    let temp;
    for (let i = 1; i < clonedArray.length; i++) {
      temp = clonedArray[i];
      for (let j = i-1; j >= 0 && clonedArray[j] > temp; j--) {
        clonedArray[j + 1] = clonedArray[j];
      }
      clonedArray[j + 1] = temp;
    }

    return clonedArray;
};

module.exports = insertion;

There isn't much room for improvement from an algorithm perspective, since you're already using the optimized algorithm and you aren't doing anything unnecessary from a JavaScript perspective.

Rewriting it to use for() instead of while() won't have any real effect, other than it just looks less like pseudo-code and more like typical JS. It is really just a code style thing though, and open to opinion.

(Also, dropped isFunction() since you don't seem to use it, but that might just be copy-pasta from the rest of your code.)


Inefficient (slow) loop with calculations in worksheet

Application.ScreenUpdating = False

I find it scary that the corresponding = True is nowhere in your code, for reasons already mentioned. Whenever I turn off screen updating, I find it's good UX to also specify a status bar message, and change the mouse cursor to a hourglass. Something along these lines:

Public Sub ToggleWaitMode(Optional ByVal waitMode As Boolean = False)
    Application.ScreenUpdating = waitMode
    Application.Calculation = IIf(waitMode, xlCalculationManual, xlCalculationAutomatic)
    Application.StatusBar = IIf(waitMode, "Please wait...", vbNullString)
    Application.Cursor = IIf(waitMode, xlWait, xlDefault)
End Sub

Which makes your procedure stub look like this:

Option Explicit

Public Sub DoSomething()
    On Error GoTo ErrHandler
    ToggleWaitMode True

    'do that thing

CleanExit:
    If Not Application.ScreenUpdating Then ToggleWaitMode
    Exit Sub
ErrHandler:
    ToggleWaitMode
    ' handle errors here
    Resume CleanExit
End Sub

  If I turn Calculation on Manual then my values are no good because...

If I understand properly, you need to update $N$13 some 2,000 times with a value that's in "$B$" & i, and then I guess $U$12, $V$12 and $W$12 need to be recalculated accordingly.

You haven't shown us what these cells contain and what cells their formula is referring to, but if they're the only cells that need to be recalculated when $N$13 changes, then you can force calculation like this:

wsInput.Range("$U$12").Calculate
wsInput.Range("$V$12").Calculate
wsInput.Range("$W$12").Calculate

But that might not speed up anything. You're pretty much stuck, since you need to recalculate these three cells before you can do anything, and you need to do that 2,000 times.

I think you're somewhat misusing VBA here, it looks like you could use 3 hidden columns (say, $AA$4:$AC$2004) and use Excel formulas to automatically calculate the would-be "U", "V" and "W" values for each row; the VBA macro could then just copy values from Input!$AA$4:$AC$2004 to Repository!$C$4:$E$2004.. if a macro is even needed for that.

I would suggest naming the ranges/cells in row 12 - anytime you have a specific cell with a specific meaning, it's always better for the VBA code to refer to the meaning rather than the cells' addresses.

I have no clue what these cells mean, but picture this:

Dim interestRate As Double
interestRate = wsInput.Range("InterestRate").Value

This extra abstraction level somewhat decouples the VBA code from the worksheet structure, which allows you to modify [at least parts of] the worksheet without having to modify the VBA code - for example you could insert another row and now InterestRate is read in row 13 instead of 12, and the VBA code couldn't care less.

You can define names in the [Formulas] Ribbon tab, under the [Defined Names] section. Or you can just select the cell and type its name in the address/names dropdown, just left of the formula bar.

This also has the advantage of making your Excel formulas more readable: instead of =$X$12*$N42 a formula can now look like =InterestRate*$N42

One last thing, I know it's common to call a worksheet variable like wsInput, but I find it sounds backwards and looks Hungarian. I'd call it inputSheet instead; wsRepository would be repositorySheet. Also it wouldn't hurt to rename i for row.


Logging module for use in other projects

It's more natural to say "--loglevel", ... than "--log", dest="loglevel", .... A log switch suggests that it takes an argument of a logfile output filename.

Not sure why you need dest for the logfile argument.

You're specifying type of str which is already the default, but maybe you did it to help with type annotations?

Raising "Invalid logging level" is maybe superfluous, better to let the underlying logging library deal with it. Looks like you're reaching across layers.

Naming your module log is perhaps a bit adventurous, as sometimes folks concisely write log.info() instead of logger.info().

In the example, I recommend deleting:

logger = logging.getLogger(__name__)

in favor of conf_logging(logging.getLogger(__name__), args.loglevel, args.logfile).
Perhaps you'd like to make it more convenient for callers, by defaulting loglevel, and letting a caller just pass in __name__ if that's all that is interesting.

Overall, it looks like a useful utility.