Checking convergence of 2-layer neural network in python

The reasons for the speed discrepancy

The reason for the differences in timing are because evaluating sigmoid_prime() takes far longer than tanh_prime().  You can see this if you use a line profiler such as the line_profiler module.
Is tanh_prime() supposed to be the derivative of tanh()? If so, you might want to double-check your formula.  The derivative of tanh(x) is 1. - tanh(x)**2, not 1. - x**2.
In fact, if you use the the actual definition of the derivative of tanh(), the timings become much more similar.

def tanh_prime_alt(x):
    return 1 - tanh(x)**2

foo = np.random.rand(10000)
%timeit -n 100 tanh_prime(foo)
%timeit -n 100 tanh_prime_alt(foo)
%timeit -n 100 sigmoid_prime(foo)

100 loops, best of 3: 10.2 µs per loop
100 loops, best of 3: 116 µs per loop
100 loops, best of 3: 279 µs per loop

So with this alternate tanh_prime(), the sigmoid method is now only 2× slower, not 20× slower.  I should emphasize that (a) I don't know enough about neural networks to know if 1. - x**2 is an appropriate expression or approximation to the actual derivative of tanh(), but if it is in fact OK, then (b) the reason that activation = 'tanh' is so much faster is because of this approximation/error.
The remaining 2× difference is because in your factored expression of sigmoid_prime(), you are needlessly evaluating sigmoid() twice.  I'd instead do this:

def sigmoid_prime_alt(x):
    sig_x = sigmoid(x)
    return sig_x - sig_x**2

As expected, this speeds things up two-fold relative to your original definition.

foo = np.random.rand(10000)
%timeit -n 100 sigmoid_prime(foo)
%timeit -n 100 sigmoid_prime_alt(foo)

100 loops, best of 3: 248 µs per loop
100 loops, best of 3: 132 µs per loop

Since the sigmoid() function and the tanh() function are related by tanh(x) = 2 * sigmoid(2*x) - 1, i.e. sigmoid(x) = (1 + tanh(x/2.))/2, then iff you are OK with the weird 1 - x**2 approximation for tanh_prime(), you should be able to work out a similar approximation for sigmoid_prime().
You might be interested in the autograd module, which provides a generalized capability to compute symbolic derivatives of most NumPy code.

Other comments

These comments aren't a thorough review, but just some things I noticed.

Why are your weights Python lists instead of NumPy arrays?  If you're already using NumPy, you might as well use it wherever you can.
You probably don't need the for l in range(len(self.weights)): loop, do you?  Can't you use NumPy array slicing and the matrix capabilities of np.dot() to replace this loop?
If you are going to loop, you don't need to do for l in range(len(self.weights)) and then reference self.weights[l].  You can do for weight in self.weights: and then reference weight in your loop code, for example.
Write some docstrings for your functions please!


There is no need to create a new string at each iteration. You can directly append the subslice to the array like this:

arr = append(arr, str[i:])

An other easy optimisation would be to create an array with the correct capacity to save an allocation at each iteration, as we know that arr will have the same length as str:

arr := make([]string, len(str))

so the code can now be rewritten like this:

func new() {
    str := "Hello"

    arr := make([]string, 0, len(str))
    for i := len(str) - 1; i >= 0; i-- {
        arr = append(arr, str[i:])
    }
}

Running a small benchmark comparing the old and the new implementation, we get this result:

goos: linux
goarch: amd64
BenchmarkOld-2           3000000               553 ns/op             240 B/op          4 allocs/op
BenchmarkNew-2          10000000               127 ns/op              80 B/op          1 allocs/op


MongoDB CRUD operations for various types of data in Go

I am also starting out in go (although I used GAE's Datastore), and have spent some time thinking about this. I considered 3 options:
1 Code Generation
I think code generation would be a solid way to approach this solution. There's even a library starting out called streetCURD for PostgreSQL.
Code generation seems like a common way to do things in go. There is also a golang code generation tool called gen.
2 Don't Generalize
Depending on how many times you will copy and paste this, it may not be worth for you to generalize it. However, I find that after a few structs I start doubting this route... and others are not generalizing too: Example1. example2.
3 Interfaces
I ended up using interface{} for somethings (like error checking) which you stated you are not interested in. I felt it made the code more readable, which is my goal.
Looking over your code, it seems like you are interested in a method that return a user or a company- depending in the input, interface{} would be the way to go... (pun not intended).
Since I am just starting out, I'd love to see better responses to this question.


Binary Search For Data Types With Relation Operators

Apart from the fact that you should prefer writing algorithms to work with iterators (to enable you to sort things that aren't arrays, such as std::lists), there are a few things here that are problematic:

Don't make assumptions about the signedness of your U type, which seems to represent the size type of the array. Oftentimes, U will be unsigned (e.g. because it is std::size_t), which means returning -1 on not finding a value might be unexpected behaviour for your users.
Check that _size is greater than zero. If it is not, your program invokes undefined behaviour.
Take toFind by const reference since you don't know which type it will be, whether it will be trivially copyable and so on and so forth. The same is true for m, l and h; you should either make them pointers to elements in the array or make them store the index to their respective elements instead.
Be careful with overflow. In particular, (high + low)/2; may overflow the passed size type and you may end up getting nowhere. Instead, divide them separately and add the results together.

These are the pitfalls and dangers I spotted. There is a lot more to say about your code, however, but I will leave this to somebody else.


number = random.randint(0, 20)

You just told the user that the number is between one and twenty, but you use random.randint(0, 20).  What if the result was 0?  One disgruntled player.  You should be using number = random.randint(1, 20).

prompt = "> "

You aren't hard-coding the value.  That's very good.  Since it is a constant, however, you should use ALLCAPS.

attempts = 5
while attempts > 0:

You are starting out at the high point and decrementing until you get to zero.  That isn't really the number of attempts.  That is how many attempts are left.  I would define a constant for the number of attempts allowed, define attempts as 0, and have the while make sure that attempts is lower than that number.  This becomes especially useful when printing how many attempts it took.  As it is, your program displays the wrong number: the number of attempts that were left.

try:
    guess = int(raw_input(prompt))
except ValueError:
    print "Only numbers are allowed. \n"
    break

It's good that you try to validate the input, but you should use continue instead of break.  One invalid input shouldn't end the program.

print "Nice! You've guessed it right. The number was %d." % number

Using % for a format string isn't officialy deprecated, but it is recommended to use .format().

What if the user wants to play again?  You make him re-run the script.  I would use a while loop and a function:

import random

PROMPT = "> "
GUESSES = 5

def guess_number(start=1, end=20):
    print "I have a number in my mind that's between {}-{}.".format(start, end)
    number = random.randint(start, end)
    attempts = 0
    while attempts < GUESSES:
        print "What's your guess? "

        # Simple validation
        try:
            guess = int(raw_input(prompt))
        except ValueError:
            print "Only numbers are allowed. \n"
            continue

        if guess > number:
            print "Go lower."
        elif guess < number:
            print "Go higher."
        else:
            print "Nice! You've guessed it right. The number was {:d}.".format(number)
            print "And you got it with {:d} attempts!".format(attempts + 1)
            break

        # Increment the attempts each time the guess isn't right.
        attempts += 1

        if attempts == GUESSES:
            print "You didn't guess it; the number was {:d}. You lose.".format(number)
            break
        # Print with the color red.
        print("\033[91m You have {} guesses left. \033[00m").format(attempts)

if __name__ == "__main__":
    print "Welcome to the Number Guesser game."

    again = True
    while again:
        print "I have a number in my mind that's between 1-20."
        guess_number()
        play_again = raw_input("Would you like to play again? ")
        while play_again.lower() not in "yn":
            play_again = raw_input("Invalid input. [y/n] ")
        again = (play_again.lower() == "y")


Avoiding else

If you can avoid else then it can simplify indentation. For example:

if (!fs.existsSync(name)) {
    fs.mkdirSync(name);
} else {
    throw new Error(`directory ${name} already exist`);
}

The error can be thrown the error if the name exists, but if not just go ahead with the call to fs.mkdirSync():

if (fs.existsSync(name)) {
    throw new Error(`directory ${name} already exist`);
}
fs.mkdirSync(name);

In some cases you may have to manually return or exit if the statement inside the first conditional doesn't return early or terminate the process - e.g. inside onCopyDone().

Use const instead of let when appropriate

It is wise to get in the habit of using const for any value that doesn't get re-assigned. Then if you need to have a variable that changes, switch to using let. This affects variables like result in the callback inside replaceInFile().

Arrow functions

The parentheses are not necessary on arrow functions with only one argument. Also, a single line doesn't need to have brackets - while this would lead to the return value of the statement getting returned, it shouldn't matter in most cases - so this:

i.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
});

can be simplified to:

i.stdout.on('data', data => console.log(`stdout: ${data}`));


Check if element is a member of all sets in Scheme

so this is not a question about code, but about conventions. Usually to say "a condition holds for all elements of a set" is the same as "there's no such element in the set that the condition doesn't hold for it". Which there clearly is no such element, in an empty set. So by convention all such "all-are-true" predicates hold for an empty set.

But if you want your function to return #f in such a case, just add simple entry check for this, and convert what you have right now into an inner (nested) definition:

(define memberall
  (lambda (a l-set)
    (and (not (null? l-set))
      (letrec ((alltrue
                 (lambda (l-set)
                   (cond
                     ((null? l-set) #t)
                     ((not (member a (car l-set))) #f)
                     (else (alltrue (cdr l-set)))))))
        (alltrue l-set)))))

Or with named let:

(define memberall
  (lambda (a l-set)
    (and (not (null? l-set))
      (let alltrue ((l-set l-set))
        (cond
          ((null? l-set) #t)
          ((not (member a (car l-set))) #f)
          (else (alltrue (cdr l-set))))))))


This code has a bug. Consider merge_intervals([(0, 3), (1, 2)]). This returns [(0, 2)] although it should be [(0, 3)]. This can be solved through

new_tup = (b[0], max(b[1], tup[1]))

Your code is nice, and implements the simplest thing that works. However, you might want to work on improving your variable names. Neither l, b, or si are very descriptive, and tup and new_tup unnecessarily refer to their type name rather than their meaning. In contrast, merged is a very clear name. A rewrite of the function body might be:

sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0])
merged = []

for higher in sorted_by_lower_bound:
    if not merged:
        merged.append(higher)
    else:
        lower = merged[-1]
        # test for intersection between lower and higher:
        # we know via sorting that lower[0] <= higher[0]
        if higher[0] <= lower[1]:
            upper_bound = max(lower[1], higher[1])
            merged[-1] = (lower[0], upper_bound)  # replace by merged interval
        else:
            merged.append(higher)
return merged

Notice that I decided not to use an explicit tuple(…) constructor – that's mostly useful for converting to tuples from iterables. For tuple literals, you can use the (…, …) syntax.

I also put the comments inside the code, rather than into the docstring. Docstrings are good, but they are intended to explain how to use the function (e.g. what the expected type of parameters is, what the function returns, …). To document implementation details, use normal comments.

You have correctly identified the (average and worst-case) algorithmic complexity as \$O(n \log n)\$. You must consider the sorting. However, best-case complexity is \$O(n)\$, as the Tim Sort used by Python detects already-sorted input.

While your code provides a simple and robust solution, it would be certainly possible to reduce average algorithmic complexity. I expect a kind of self-merging interval tree to have average complexity closer to \$O(n \log m)\$ where \$m\$ is the number of intervals after merging.


Format an Unsigned Byte to a Three ASCII Digits

First observations.

Memory access is costly in terms of cycles. Your solution uses 10 of these. The program I present later on manages to just require 3 accesses to memory.
By placing the most used variables in the zero-page, you obtained the best possible memory access performance, but avoiding variables is preferable.
The FormatUnsigned subroutine uses some 76 bytes and the byte-variables add another 11 bytes. This is a lot for such an humble task. The routine I present later on will be written in 46 43 bytes and only add 3 byte-variables.

An opportunity for optimizing.

lsr
lsr
lsr
lsr
and #$F                 ; get high nybble

You don't need the and #$0F instruction because the 4 lsr instructions in a row already leave the high nibble empty. This shaves off 2 bytes from the program and reduces the number of cycles by 2. These benefits double because you used this construct twice throughout the program.

A unclear comment.

; 6502 routine to format an unsigned byte into a space
; followed by 2 decimal digits if < 100, or 3 decimal
; digits if >= 100.

From this comment I understand that numbers in the range [0,9] will be shown with 1 leading space and 1 leading zero. Wouldn't you agree this to be ugly?
The version I propose next will show 2 leading spaces on such numbers.

My version.

The worst case runs in 108 cycles. This happens with values from 190 to 199.
The best case for this code runs in just 44 cycles. Not surprisingly this is for inputs from 0 to 9.
I personally don't like the decimal mode of the 6502 and so this solution doesn't use it.

    ldx #$20    ;" "
    sec
    sbc #100
    bcc OK1
    ldx #$31    ;"1"
    sbc #100    ;           (1)
    bcc OK1
    inx         ;"2"
    sbc #100    ;           (2)
OK1
    adc #100
    stx char1

    ldy #$2F    ;"0"-1      (4)
    sec
Sub10
    sbc #10     ;           (3)
    iny         ;["0","9"]  (4)
    bcs Sub10
    adc #10
    cpy #$30    ;"0"
    bne OK2
    cpx #$20    ;" "        (5)
    bne OK2     ;           (5)
    ldy #$20    ;" "
OK2
    sty char2

    ora #$30    ;["0","9"]  (6)
    sta char3

(1)(2)(3) The carry flag is already set. No need to use sec before sbc.
(2) This instruction is meant to be a jump over the following adc #100. This would have required 3 bytes using jmp STXCHAR1 or 2 bytes using bcs STXCHAR1. In both cases it would also have taken 3 cycles to run. By writing a complementary subtraction I undo the effect of the following addition, and realise the shortest code and the least cycles!
(4) The peculiar value $2F is correct because the loop at Sub10 always runs at least once the iny instruction. Therefore 1 to 10 iterations of this loop will yield Y-register values from $30 to $39.
(5) This extra code takes care of the 2 leading spaces on numbers from 0 to 9.
(6) Normally here we would like to add 48 to the value in the accumulator holding [0,9]. Using the adc #48 instruction would have required a clc to give correct result. By using the ora #48 the result is equally correct but the code is 1 byte smaller and 2 cycles faster.

Still room for improvements.

In an effort to get rid of the separate sec instruction I came up with a 1 byte smaller solution. This also no longer contains the complementary adc #100 that you commented about.

    ldx #$20    ;" "
    cmp #100
    bcc OK1
    sbc #100
    ldx #$31    ;"1"
    cmp #100
    bcc OK1
    sbc #100
    inx         ;"2"
OK1
    stx char1

Nice, but wouldn't it be possible to combine a few things (the first sbc #100 and the second cmp #100)? Yes. Using sbc #200 and a conditional complementary adc #100 the code has yet again shrunk, this time by another 2 bytes.

    ldx #$20    ;" "
    cmp #100
    bcc OK1
    ldx #$32    ;"2"
    sbc #200
    bcs OK1
    adc #100
    dex         ;"1"
OK1
    stx char1

Some speed measurements.

All of these numbers relate to the first part of the program where the hundreds digit gets calculated.

 Input    Question  Answer1  Answer2  Answer3
-------   --------  -------  -------  -------
  0- 99     24        14       10       10      cycles
100-199     33        20       18       19      cycles
200-255     40        23       21       16      cycles
-------   --------  -------  -------  -------
Average    31.02     18.31    15.53    14.83    cycles
           21        20       19       17       bytes

For the average it is understood that all numbers from 0 to 255 have the same probability.


Find numbers that are palindromic in consecutive number bases

A small performance improvement is possible in the listToInt function,
by using multiplications only instead of exponentiation
(which is Horner's method):

# converts number in base b list representation to integer
def listToInt(digitList, base):
    value = 0
    for val in digitList:
        value = value * base + val
    return value

On my computer this reduced the time to compute the results for
\$ b = 1270, \ldots, 1286 \$ from 130 to 101 seconds.


LeetCode seems to stress preparation for technical interviews, I consider it prudent to start sketching the most simple thing that could possibly do (I take the liberty to substitute the original last word work).
Things I like about your approach:

conceptually simple & clean:
comparing first and last half with one reversed

relying on runtime support in the environment of choice
for comparison and reversal

I do not consider transforming data to facilitate processing cheating, unless it explicitly violates part of the task description.
Things I don't like (this far, you saw it coming) about the execution (of said approach):

missing doc comments

e.g. about a known shortcoming:
using O(n) additional space out of convenience, not need

not defining an explicit predicate isPalindrome()
transforming more than one part of the linked list separately

using repeated code (this may be appropriate in an interview setting, if commented (preferably in the code sketch, too))

declaring the Lists for what they are (implementing class) instead of what use they are (interface)

Giving it a try:

/** Checks a home-grown linked list
 * for palindrome using linear additional space.
 * @param node the first node of the list to check, or null
 * @return the order of values in the list
 *  starting from node stays the same when reversed
 */// compare first half to reverse of second half
static boolean isPalindrome(final ListNode node) {
    final List<Integer> items = new java.util.ArrayList<>();

    for (ListNode n = node ; n != null; n = n.next)
        items.add(n.val);

    int count = items.size(),
        middle = count/2; // middle item in neither sublist for odd count
    final List<Integer> tail = items.subList(count-middle, count);
    java.util.Collections.reverse(tail);
    return count < 2 ||
        items.subList(0, middle).equals(tail);
}
/** Builds a node list from values & prints result of isPalindrome() */
static void checkNodeList(String values) {
    ListNode node, n = node = new ListNode(42); // dummy
    for (byte c: values.getBytes())
        n = n.next = new ListNode(c);
    node = node.next; // skip dummy
    System.out.println("palindrome(" + values
              + "): " + isPalindrome(node));
}
public static void main(String[] args) {
    checkNodeList("");
    checkNodeList("?");
    checkNodeList("!!");
    checkNodeList("codedoc");
    checkNodeList("codedoC");
    checkNodeList("cOdedoc");
    checkNodeList("Maddam");
    checkNodeList("maddam");
    checkNodeList("madDam");
}

[optimizing] this solution - I can't make approach or code any clearer.
LeetCode's follow on: can a single solution achieve O(n) time and O(1) space?:
I know how to do it modifying the input, I doubt it can be done without.
There are many ways to skin cats, thinking how easy it would be using python, I gave turning ListNodes into Lists a try, with loop jamming and use of a sentinel thrown in:

/** Checks a home-grown linked List
 * for palindrome using constant additional space.
 *
Temporarily modifies the list starting with node.
 * @param node null, or the first node of the
 *  List to check
 * @return the order of values in the List
 *  starting from node stays the same when reversed
 */
static boolean isPalindrome(final ListNode node) {
    if (null == node)
        return true;
    ListNode
        last,   // traverses list two steps/turn, stops at last node
        middle, // middle of list part already traversed by last
        reversed = null, // reverse of first half
        slow = middle = last = node;
    // jam "counting" and reversal of first half
    for (ListNode next ; ; last = next.next) {
        next = last.next;
        middle = slow.next;
        if (null == next)
            break;
        slow.next = reversed;
        reversed = slow;
        slow = middle;
        if (null == next.next) {
            last = next;
            break;
        }
    }
    if (null == reversed)
        return true;
    boolean mayBePalindrome = last.val == node.val;
    if (mayBePalindrome) {
        last.val = ~node.val; // turn last into sentinel
        // jam "check" and restoration of first half; single comparison
        while (reversed.val == middle.val) {
            ListNode n = reversed.next;
            reversed.next = slow;
            slow = reversed;
            reversed = n;
            middle = middle.next;
        }
        mayBePalindrome &= middle == last;
        last.val = node.val; // restore
    }
    while (null != reversed) {
        ListNode n = reversed.next;
        reversed.next = slow;
        slow = reversed;
        reversed = n;
    }
    return isPalindrome;
}

/** Prints result of isPalindrome() */
static void check(String init) {
    ListNode node = null == init
        ? null : new ListNode(init, null);
    System.out.println("palindrome(" + node
              + "): " + isPalindrome(node));
}

public static void main(String[] args) {
    check(null);
    check("'");
    check("cc");
    check("codedoc");
    check("codedoC");
    check("cOdedoc");
    check("Maddam");
    check("maddam");
    check("madDam");
}

/** Singly-linked list node class bolstered some to support
 * java.util.List iteration. */
static class ListNode extends java.util.AbstractList<Integer>
    implements List<Integer>
{
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
    ListNode(int x, ListNode n) { val = x; next = n; }
    ListNode(String init, ListNode n) {
        next = n;
        if (null != init && 0 < init.length()) {
            val = init.charAt(0);
            if (1 < init.length())
                next = new ListNode(init.substring(1), n);
        }
    }
    @Override
    public Integer get(int index) {
        if (0 == index)
            return val;
        if (index < 0)
            throw new IllegalArgumentException("index < 0");
        if (null == next)
            throw new IllegalArgumentException("size <= index");
        return next.get(index-1);
    }
    @Override
    public int size() { return null == next ? 1 : 1 + next.size(); }
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
                ListNode head = ListNode.this;
                @Override
                public boolean hasNext() { return null != head; }
                @Override
                public Integer next() {
                    int v = head.val;
                    head = head.next;
                    return v;
                }
            };
    }
}


def chunk_adder(lst):
  for i in lst:
    if len(i) == 1:
      yield i[0]
    else:
      yield sum(i)

sum can happilly consume iterable of size 1, it can even consume iterable of size 0:

>>> sum([1])
1
>>> sum([])
0

So you can simplify it to:

def chunck_adder(iterable):
    for element in iterable:
        yield sum(element)

Which is simply

def chunck_adder(iterable):
    yield from map(sum, iterable)

So you could simplify pascal_next instead:

def pascal_next(lst):
    return list(map(sum, double_chunker(lst)))

def double_chunker(lst):
  leng = len(lst)
  for i in range(leng):
    if i == 0:
      yield [lst[0]]
    elif i == 1:
      yield [lst[0], lst[1]]
    elif i == leng:
      yield [lst[-1]]
    else:
      yield [lst[i-1], lst[i]]
  yield [lst[-1]]

The intent is pretty much the same than the pairwise recipe from itertools. Except you want to yield the first and last element as well.

Here you have two possibilities:

either yield them manually:

import itertools

def double_chunker(lst):
    if not lst:
        return
    a, b = itertools.tee(lst)
    next(b, None)

    yield [lst[0]]
    yield from zip(a, b)
    yield [lst[-1]]

But this forces the argument to be a list, or at least to know if its empty and to implement __getitem__.
or add boundary values to your input so pairwise can work properly:

import itertools

def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

def double_chuncker(iterable):
    extended = itertools.chain([0], iterable, [0])
    return pairwise(extended)

Which I recommend because it happily consume any iterable.

def pascal_triangle(rows):
  end = [[1]]
  for i in range(rows):
    end.append(pascal_next(end[-1]))
  return end

Instead of relying on the list being constructed, I would explicitly store the current row. I would also turn this into an infinite generator because it really is and maybe provide an helper function for convenience:

def pascal_triangle():
    row = [1]
    while True:
        yield row
        row = pascal_next(row)

def pascal_triangle_up_to(n):
    return list(itertools.islice(pascal_triangle(), n))

Full code:

import itertools

def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

def double_chuncker(iterable):
    extended = itertools.chain([0], iterable, [0])
    return pairwise(extended)

def pascal_next(iterable):
    return list(map(sum, double_chuncker(iterable)))

def pascal_triangle():
    row = [1]
    while True:
        yield row
        row = pascal_next(row)

def pascal_triangle_up_to(n):
    return list(itertools.islice(pascal_triangle(), n))

if __name__ == '__main__':
    # Testing
    for row in pascal_triangle():
        print(row, end='')
        if (input()):
            break


By using Zend_Rest_Route you are on a good way. I wouldn't recommend making it the default route though, as I had trouble when using MVC-stuff which required additional params not specified in the route, e.g. for a paginator. You could also move the routing-configuration to your application.ini to keep your Bootstrap-class clean.

I recommend simplifying your getAction() by using:

$id = $this->getRequest()->getParam('id', null);
$id = $this->_request->getParam('id');

Both are identical, but I prefer using the get-methods in case I use them to override the handling of the underlying class-property (in this case $this->_request). The second argument specifies the default value to be used, if the param is not set (by default this is null).

edit: Also, instead of

$this->_todo[count($this->_todo) + 1] = $item;

$this->_todo[] = $item;

this will automatically append $item to $this->_todo, even if the variable is not yet initialized.


Problems with add:

the while(true) is useless
you want to notify_one, not notify_all because you've only added one thing, and so only one thread waiting to remove can remove it.
you should overload for two version which take const T& and T&& (the latter would std::move). This would be optimal in all cases. (analogous to push_back in standard containers)
You may also want to add an emplace to complement the add() versions so you can construct T in-place at the top of the Buffer.
you can use lock_guard instead of unique_lock and scope it with {}s. I'd just say always prefer the lighter weight construct when a heavier weight one isn't strictly needed.

problems with remove:

the while (true) is useless
the cond var lambda can be return !buffer.empty();
the back variable can be std::moved
what happens if you destruct an empty Buffer while a thread is waiting on remove? That case isn't handled at all, and it's a problem
there's no reason to notify_all in remove. Who is it notifying and why?

problems with size:

use a lock_guard unless unique_lock is needed
just do: std::lock_guard<std::mutex> lock{mu}; return buffer.size();


Counting ways to divide a word into palindrome blocks

Exit code

When exiting due to an error, it's good to use a non-zero exit code.
Calling exit() without an explicit value will use the default 0, meaning success.

Naming

The name number_of_block_palindrome_groupings is a bit long an tedious.
How about count_block_palindromes?

List comprehensions

Instead of accumulating a sum with a loop,
you could use a list comprehension:

return sum([1 + count_block_palindromes(string[i:-i])
            for i in range(1, len(string) // 2 + 1)
            if string[:i] == string[-i:]])

Memoization

In case of long input with recursive patterns,
the same substrings may be computed many times repeatedly.
It could be a useful optimization to cache the results of computing each unique input.
An easy way to implement that using functools.lru_cache.

import functools

@functools.lru_cache()
def count_block_palindromes(string):
    # ...

Doc tests

Doc tests are awesome. They are executable documentations serving as unit tests, for example:

def count_block_palindromes(string):
    """
    >>> count_block_palindromes("BONBON")
    1

    >>> count_block_palindromes("ONION")
    1

    >>> count_block_palindromes("BBACBB")
    3

    >>> count_block_palindromes("BABABABABABABABA")
    15

    >>> count_block_palindromes("BABABABABABABAB")
    33

    """
    # ... the code

This is runnable in Pycharm with Control Shift R,
or in the shell with python -mdoctest yourscript.py.


Matching items in different arrays and performing operations on them

Before getting to your question about reducing the duplication, there's another issue I'd like to point out first. The use of default(DateTime) as a check for the absence of a value is incorrect and misleading. default(DateTime) is a valid date. However unlikely it is that you will have a date that equals that value, it is misleading to use because anyone looking at your code that sees a DateTime variable will assume that it holds a proper date value because it has to. As a struct, it can't be represented as null, so it always holds a value. Enter nullable types. DateTime? clearly expresses that the variable can be in a state where it doesn't hold a date value.

That said, it appears you're trying to join the two dictionary and compare in these ways:

When there are matching keys.
When only one of the dictionaries holds a key.

Sounds like a Full Outer Join, which someone has kindly shared a Linq-esque extension method for over on Stack Overflow. Using this, you can concisely and expressively rewrite your methods like so to avoid duplication (note the use of DateTime?):

// Note: I think this is a bad method name (it's the same as the one below,
// which I think is better suited for the name). It should probably express
// the comparison between these Dictionary maps.
public static DateTime? GetEarliestDivergenceTime(Dictionary<int, TimeSeries> baseline, Dictionary<int, TimeSeries> other, DateTime? defaultEarliestDivergenceTime = null)
{
    // Omitting 'FullOuterJoin' code in StackOverflow link:
    var earliestDivergenceTimes = baseline.FullOuterJoin(
        other,
        b => b.Key,
        o => o.Key,
        (b,o) => GetEarliestDivergenceTimeOrDefault(b, o));

    return earliestDivergenceTimes.Min() ?? defaultEarliestDivergenceTime;
}

public static DateTime? GetEarliestDivergenceTime(TimeSeries ts1, TimeSeries ts2, DateTime? defaultEarliestDivergenceTime)
{
    DateTime? earliestDivergenceTime = null;

    if(ts1 != null && ts2 != null)
    {
        // Compare.
    }
    else if(ts1 != null && ts2 == null)
    {
        // Use ts1.
    }
    else if(ts1 == null && ts2 != null)
    {
        // Use ts2.
    }

    // earliestDivergenceTime will be null if both t1 and t2 are null.
    return earliestDivergenceTime ?? defaultEarliestDivergenceTime;
}


You are right that this is not optimal (performance wise). You may want to consider two things:

static variables (those values in there are constants no need to recreate them every time).
merging the arrays.

Consider the following code:

public static function convertArabicNumbers($string) {
    //$engish = array(0,1,2,3,4,5,6,7,8,9);
    static $fromchar = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹',
                             '٠','١','٢','٣','٤','٥','٦','٧','٨','٩');
    static $num = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
    return str_replace($fromchar, $num, $string);
}

I am really uncertain about the right-to-left characters.... should they be transformed in the same way as the left-to-right ones? You're the expert on that one.

Still, you get the idea....


Unit tests should be put in the file they're testing

It's recommended to put the unit tests into the same file as the functions you're testing. This prevents your code from getting out of sync with your tests more easily. Also, you don't want one single large tests.rsfor all your unit tests.

Use proper types in traits

At the moment, as soon as we use any function from Vector3, we end up with a KVector3:

pub trait Vector3 {
    fn dot(&self, v : KVector3) -> f64;
    fn cross(&self, v : KVector3) -> KVector3; // here

    fn zero() -> KVector3;  // here
    fn i_hat() -> KVector3; // here
    fn j_hat() -> KVector3; // here
    fn k_hat() -> KVector3; // here
}

That's probably not what you intended. Use Self instead here. Furthermore, all your functions are fixed to f64, but one can implement all functions from Vector3 for any number type. The following interface encapsulates that:

pub trait Vector3 {
    type Output;

    fn dot(&self, v: Self) -> Self::Output;
    fn cross(&self, v: Self) -> Self;

    fn zero() -> Self;
    fn i_hat() -> Self;
    fn j_hat() -> Self;
    fn k_hat() -> Self;
}

Use derive for canonical implementations

If you use #[derive(PartialEq, Debug)] you don't have to implement both variants yourself.

Consider generics for your structs (and traits)

Your KVector3 only supports f64. However, we can imagine a situation where we want to store f32, for example for GPU calculation. We can use KVector3 also in that circumstance if we make it generic.

Add documentation and examples

Since you're working on a reusable library you want to have some documentation at hand. Furthermore, examples in your documentation are automatically checked with cargo test.


You could translate this recursive Python code.

def xcombinations(items, n):
  if n==0: yield []
  else:
    for i in xrange(len(items)):
        for cc in xcombinations(items[:i]+items[i+1:],n-1):
            yield [items[i]]+cc

in C++ roughly (untested, but you get the idea):

using std::set;

set<set<int>> xcombinations(const set<int> &items, size_t n) {
    set<set<int>> result; // collect for 'return' instead of pythons 'yield'
    if(n==0) return result;
    for(int elem : items) { // ranged-for from C++11
        // 'items' without 'elem', python 'items[:i]+items[i+1:]'
        set<int> temp(items); // copy
        temp.erase(elem); // ...or use 'std::remove_copy_if'
        for(auto cc : xcombinations(temp, n-1)) { // ranged-for from C++11
            cc.insert(elem);
            result.insert(cc); // python yield;
        }
    }
    return result;
}

Note that auto cc creates a copy in the inner loop, where one can add elem before adding it to result.

Instead if the new C++11 ranged-for and auto one can of course just use lengthy iterator-based for-loops.

Using vector instead of set would also work, I guess. There are no set-operations involved here. Actually, now that I think of it, vector would be much better... hmm...

One could save some copying by pulling temp out of the loop, initialize it with a a size of n-1 and use std::remove_copy_if to put the values into it. And if one does that, one can even save the copy of all values by just replacing one in the inner loop, but I can not see how right away.

Ah, well and you need a printing routine, of course.

std::ostream& operator<<(std::ostream &os, const set<int>& items) {
    for(int elem: items)
        os << elem << " ";
    return os;
}
std::ostream operator<<(std::ostream &os, const set<set<int>>& itemss) {
    for(const auto &cc: itemss)
        os << "  {" << cc << "}\n";  // or use 'ostream_iterator' on 'cc'
    return os;
}

int main(/*...*/) {
    set<int> data = {1, 2, 3, 4, 5, 6}; // C++11 init-list
    std::cout << xcombinations(data, data.size()) << std::endl;
}


Use detach to remove the elements from the DOM, append the tables to the detached nodes, then add them back to to DOM:

var table = $( "#myTable" );
var parent = table.parent();

table.detach();

 // ... add lots and lots of rows to table

parent.append( table );

References

Detach Elements to Work with Them
jQuery API: detach


Optimizing runtime on finding the nth perfect power number

Naming

perfect is quite general for a function name. A better choice might be something like nth_perfect_power.

Docstring comments

You have documented the function with a docstring comment, which is good. There is some repetition and verbosity however. I would perhaps use a single-line description, plus a description of what a perfect power is. You could also add some doctest examples:

def nth_perfect_power(n: int) -> int:
    """Return the n'th perfect power.

    A perfect power is a positive integer of the form m ** k with
    m >= 1 and k >= 2. Examples from https://oeis.org/A001597:

    >>> nth_perfect_power(1)
    1
    >>> nth_perfect_power(10)
    49
    >>> nth_perfect_power(50)
    1521
    """

Of course this is largely opinion-based.

Review and performance improvements

The initial assignment

i = 1
for i in range(0, n**2+1):
    // ...
        i += 1

has no effect, and incrementing i within the loop makes the logic difficult to understand. Perhaps this is done to take care of duplicate powers such as \$ 8^2 = 4^3 \$, but there are better approaches to solve that. You can for example move the check for a perfect power to a separate function (where you can early-return).

Apart from the first perfect power \$ i = 1 \$ one only needs to check values \$ m, k \ge 2 \$.

The length of the powers array needs only to be checked again if we added an element, not for each value of \$ i \$.

The last element of an array can be retrieved as powers[-1].

Summarizing these topics so far, we get the following implementation:

def is_perfect_power(i: int) -> bool:
    if i == 1:
        return True
    for k in range(2, i):
        for m in range(2, i):
            if m ** k == i:
                return True
    return False

def nth_perfect_power(n: int) -> int:
    powers = []
    for i in range(1, n**2 + 1):
        if is_perfect_power(i):
            powers.append(i)
            if len(powers) == n:
                break
    return powers[-1]

This is more code than your original, but easier to read and slightly more efficient. It can be improved further: The exponentiation \$ m^k \$ can be replaced by repeated multiplication with \$ m \$. Also the inner loop can be exited as soon as a power is larger than the candidate \$ i \$:

def is_perfect_power(i: int) -> bool:
    if i == 1:
        return True
    for m in range(2, i):
        p = m * m
        while p < i:
            p *= m
        if p == i:
            return True
    return False

With these changes, the \$ 20^\text{th} \$ perfect power is found in approx. 3 milliseconds (compared to 2.6 seconds with your original code), and the \$ 100^\text{th} \$ perfect power is found in approx. 2.5 seconds.

A different approach

Your code determines for every candidate \$ i \$ if it is a perfect power by computing \$ m^k \$ for all \$ m, k \$ in the range \$ 0, \ldots, i \$. This is done for all \$i \$ up to  \$ n^2\$, until \$ n \$ perfect powers are found.

As an example, in order to find the \$ 20^\text{th} \$ perfect power, \$ m^k \$ is computed \$ 3382670\$ times.

We already improved that by restricting the base \$ m \$ and the exponent \$ k \$ to smaller ranges. But for larger values of \$ n \$ we need a different approach.

It is much more efficient to compute all perfect powers (in some range) instead, and then take the \$ n^\text{th} \$ smallest number. Since there can be duplicates (e.g. \$ 8^2 = 4^3 \$), a set should be used to collect the perfect powers.

You already used that there must be \$ n \$ perfect numbers in the range \$ 1, \ldots, n^2 \$. This can still be used to limit the range of the exponent \$ k \$.

As an example, in order to find the \$ 20^\text{th} \$ perfect power we need the numbers \$ m^k \$ in the range \$1, \ldots, 400 \$. The first perfect number \$ 1 \$ can be handled separately, so that \$ m \ge 2 \$ and \$ k \ge 2 \$:

$$
\begin{align}
 m&=2:  4, 8, 16, 32, 64, 128, 256 \\
 m&=3: 9, 27, 81, 243 \\
 m&=4:  16, 64, 256 \\
 m&=5:  25, 125 \\
 m&=6:  35, 216 \\
 m&=7:  49, 343 \\
 m&=8:  64 \\
 \vdots \\
 m&=20: 400
\end{align}
$$

This leads to the following implementation:

def nth_perfect_power(n: int) -> int:
    upper_limit = n * n
    powers = set([1])
    for m in range(2, n + 1):
        p = m * m
        while p <= upper_limit:
            powers.add(p)
            p *= m
    return sorted(powers)[n-1]

This finds the \$ 100000^\text{th} \$ perfect power is found in approx. 0.1 seconds, and the one-millionth perfect power in approx. 1.4 seconds.

For even more performance, we can use a heap structure to store only the \$ n \$ smallest powers found so far. The Python heapq is a min-heap but we need a max-heap. Therefore all powers are multiplied by \$(-1)\$. We start with the list of squares and then add the third, fourth, ... powers. For every base \$ m \$ we can stop as soon as \$ p = m^k \$ is larger than the \$ n \$ smallest powers found so far.

Implementation:

def nth_perfect_power(n: int) -> int:
    heap = [- i * i for i in range(1, n+1)]
    heapq.heapify(heap)
    powers = set(heap)
    for m in range(2, n + 1):
        p = - m * m * m
        if p <= heap[0]:
            break
        while p > heap[0]:
            if not p in powers:
                powers.remove(heapq.heappushpop(heap, p))
                powers.add(p)
            p *= m
    return -heap[0]

This computes the one-millionth perfect power in approx. 0.42 seconds.


C++: Hiding class implementation detail generic

Is the use of preprocessor macros justified here?

To me it seems like overkill. The only non-trivial macro is TL_UTILS_IMPL_START, and that will almost certainly never be useful - usually, the impl class won't need a back-pointer to its wrapper class, but will need other constructor arguments, so you'll usually have to write your own class-specific constructor and initialiser anyway. The other macros are just as verbose as, and much less self-explanatory than, the code they replace.

  Is the code safe?

You need to apply the "Rule of Three" - either implement, or remove, the copy constructor and copy assignment operator. I generally use boost::scoped_ptr for the implementation pointer, which sorts this out for me (as well as removing the need for a destructor body).


Your algorithm does seem to work, but it is very complex.  You are pushing nullptr onto the stack when a node has only one child, so you have to check for x != nullptr (which you do),   and if the top of the stack is nullptr (which again, you do).

A better approach would be:

start with an empty vector
start with an empty stack
start with root as the current node
while you are at a valid node, or if the stack is not empty:

if you are at a valid node:

if it has a left child,

push the current node onto the stack
move to the left child.

otherwise (it doesn't have a left child)

append its value to your vector
move to the right child (even if it doesn't exist)

otherwise (you have moved to a nullptr):

pop a node from the stack
append its value to your vector
move to the right child (even if it doesn't exist)

Notice you never push a nullptr onto the stack.  You never need to push a node onto the stack unless you need to return to it.  When you do return to it, you immediately process it by appending its value and moving to its right child.

Also notice that an empty tree is no longer a special case.


Overwriting native console.log function in JavaScript

I tried hacking around this in various ways and practically the only way I could detect it was wrapped was by having an old reference to console.log and using ===. Since you state your code will run before any other scripts will run, this shouldn't be a problem.

That said, there's also console.info, warn, trace, so maybe you'd want to wrap those too?

From a code quality perspective, your variable naming needs work. You can haul it through a minifier later; what you have right now is unmaintainable. I don't even know what half of it does thanks to the variable naming.


C++ Hashing Passwords - simple algorithm using rand()

Structure
Okay, let's start with the basic overall structure of the function: it's, frankly, not very good. It (unnecessarily) depends on a number of outside variables--from its perspective, essentially globals.
There's no good reason that this couldn't be a nice, pure function--i.e., take an input parameter, do the hash, return a result. No reference to anything outside the function at all.
int HashPassword(std::string const &Combine) {
    unsigned int hash = 0;

    const unsigned int VALUE = Combine.length();
    for (auto Letter : Combine)
    {
        srand(VALUE*Letter);
        hash += 33 + rand() % 92;
    }
    return hash;
}

Naming
Some of the names are pretty good (e.g., Letter, HashPassword) but others (e.g., VALUE, Combine) seem like they're open to some improvement. I can see how you came up with Combine, but that doesn't really make it a good name. VALUE is so generic that it's probably best to avoid it except (perhaps) in something like a class that represents some number, where the VALUE of the object has a fairly obvious meaning.
Magic numbers
The 33 and 92 are a couple of examples of magic numbers. These generally lead to code that's difficult to read (at best).
Security
This hash function provides approximately what's usually referred to as "kid sister" level security. If you have a kid sister, this might be about enough to keep her fooled--but only if she's not very bright or fairly quickly bored.
The most obvious problem is that this just generates a value from each byte, then adds those values together. This means nobody really needs to know your actual password--at most they only need to care about the letters that make up the password. For example, HashPassword("ABC"), and HashPassword("CAB") both produce exactly the same result.
So, to get the right result, we don't really even need to guess their password--we just need to guess some characters that produce the right result--and since nearly every input in the right range maps to a unique result, it doesn't take a lot to come up with a usable result either. For example, let's consider a result of 628. Each input produces a result from 32 to 124, so we might want to use, say, seven characters in a password. So, let's start by computing the result for seven repetitions of each character in the most common range:
for (int i = '0'; i < 'z'; i++) {
    std::string in(7, (char)i);
    std::cout << "in: " << in[0] << ", hash: " << HashPassword(in) / 7 << "\n";
}

So, our smallest result is 32--a little more than the "28" that's left over if we divide 628 by 6, so we want something that produces a result a little less than 100. A quick glance shows that 1 produces a result of 87--that'll probably do. So, if we start with 111111, we should get a result of 6 * 87 = 522. That gives us 106 left over. Another glance through the table shows that "R" gives 106, so an input of 111111R should give us 628. A quick run with     std::cout << HashPassword("111111R"); verifies that it does exactly that.
In case it seems like I hand-picked something that would be easy, I'll point out that I actually got the 628 from hashing "Password"--so to find 111111R, I really did start over from scratch--and I didn't even have to work hard at it--my first attempt worked out easily.
For another approach, I could have started with 5 of something. Let's say 'j', which gives 102. 5 x 102 = 510. I want two more characters to make up the remainder, so for my next character I want to pick something fairly small. Let's say _, which produces 35. With the previous 510, we get 545. A quick subtraction shows that we need 83 more, and a quick search shows that "M" produces 83, so jjjjj_M would work as well (and a quick test verifies that yes, it also produces 628).
Bottom line: from a security viewpoint, this is so weak that it's open to question whether it really even qualifies as "kid sister" level, or if it's too weak to even qualify for that level of "security".


All of what I'm suggesting here will be done by a good optimizing compiler. Some of what I'm suggesting is computer architecture dependent so you should depend on the compiler rather than doing it if you can. Generate assembly code and look at it to better optimize.

First, register assignment isn't guaranteed, it is only a recommendation to the compiler. You want to move your register variable declarations up. The compiler ignores your register allocations when it runs out of registers.

void asn(float *mt2, float *mt4_, unsigned int *sms) {
  register float mx;
  register unsigned int mm = 0, nn = 0;
  register unsigned int a, b;
  unsigned int i, j;
  unsigned long k;

You want to base your register allocations on what is being used most, since k is only used twice it shouldn't be a register. The variables mm, nn, a and b are used the most (sZ * sZ * sZ) so they should be registers.

On many computers counting down (auto decrement) is faster than counting up because decrement and test for zero is one opcode:

    for (i=sZ; --i; ) {
      mx = -1.0f;
      for (a=sZ; --a; ) {
        if (mt2[a*sZ] != -1.0f)
          for (b=sZ; --b; ) {
            if (mt2[a*sZ+b] > mx && mt2[b] != -1.0f) {
              mx = mt2[a*sZ+b];
              mm = a;
              nn = b;
            }
          }
      }

This does impact readability and maintainability so it should not be used unless the optimizing compiler doesn't do it for you.

Testing for equivalency of floating points is to be discouraged because of rounding errors (floating point errors).

Variable names and constants should be longer and clearer, sZ => MatrixSize.


On the whole, I think this is a pretty neat solution to your problem.  A couple of observations...

case == CASE

You lower case everything.  Maybe this is exactly what you're after, but to me, fieldOne and fieldone aren't the same, so I'd want to know about that difference.

Developer time vs test time

symmetricDifference gives back a set of all of the differences, it doesn't discriminate between the left and the right side.  So, if you've added something to FieldsModel and something else to POTENTIAL_FIELDS they would both come back.  The developer then has to go and look at both and reconcile where the problem is.  In reality this might not be a problem because the developer has probably worked on one of the files recently, so would realise which one they'd missed, however it would be better if the test showed what was missing from where.  You could do something like this:

String inConstantButNotModel = constantFields.stream()
        .filter(i -> !reflectFields.contains(i))
        .collect(Collectors.joining(","));
String inModelButNotConstant = reflectFields.stream()
        .filter(i -> !constantFields.contains(i))
        .collect(Collectors.joining(","));

assertThat(String.format("ConstantsMissing: %s\nModelMissing: %s\n",
        inModelButNotConstant,
        inConstantButNotModel))
        .isEqualTo("ConstantsMissing: \nModelMissing: \n");

To give output along the lines of...

ConstantsMissing: field5,field4
ModelMissing: field3


You could you PHP alternate syntax

<?php
/**
 * The Template for displaying all single posts.
 *
 * @package WordPress
 * @subpackage Starkers
 * @since Starkers 3.0
 */
?>

<?php get_header();
<?php get_sidebar(); ?>

    <?php $intro_image = get_post_meta($post->ID, 'Intro Image', true); ?>

        <img src="<?php echo $intro_image; ?>" alt="" />

    <?php if ( have_posts() ? while ( have_posts() ) : the_post()): ?>

            <?php the_content(); ?>

    <?php endwhile; ?>

        <?php $mainbar_left_title = get_post_meta($post->ID, 'Mainbar Left Title', true); ?>
        <?php $mainbar_left_image = get_post_meta($post->ID, 'Mainbar Left Image', true); ?>

<?php echo $mainbar_left_title; ?>

            <img src="<?php echo $mainbar_left_image ?>" alt="" />

            <?php $mainbar_right_title = get_post_meta($post->ID, 'Mainbar Right Title', true); ?>
            <?php $mainbar_right_image = get_post_meta($post->ID, 'Mainbar Right Image', true); ?>

<?php echo $mainbar_right_title; ?>

            <img src="<?php echo $mainbar_right_image ?>" alt="" />

    <?php $mainbar_right_title = get_post_meta($post->ID, 'Mainbar Right Title', true); ?>
    <?php $mainbar_right_image = get_post_meta($post->ID, 'Mainbar Right Image', true); ?>

<?php echo $mainbar_right_title; ?>

        <img src="<?php echo $mainbar_right_image ?>" alt="" />

    <?php if ( have_posts() ? while ( have_posts() ) : the_post()): ?>

            <?php the_content(); ?>

    <?php endwhile; ?>

    <?php get_sidebar('secondary'); ?>

<?php get_footer(); ?>

This follows all WP coding standards from what I can tell and is readable.
I would also suggest changing sections like this:

<?php $mainbar_right_title = get_post_meta($post->ID, 'Mainbar Right Title', true); ?>
<?php $mainbar_right_image = get_post_meta($post->ID, 'Mainbar Right Image', true); ?>

<?php echo $mainbar_right_title; ?>

    <img src="<?php echo $mainbar_right_image ?>" alt="" />

To:

<?php echo get_post_meta($post->ID, 'Mainbar Right Title', true); ?>

    <img src="<?php echo get_post_meta($post->ID, 'Mainbar Right Image', true) ?>" alt="" />

Although that's just personal preference, I find it much more readable.


Converting a string to various number formats

First things first: Export all the things which are different for different types into a policy-class, like std::basic_string and many standard-library classes do.
The main advantage is being actually able to have types with different interfaces without running into compilation-errors or at least warnings:

template<class T>
struct standard_number_traits {
    static T parse(const std::string& in) {
        T out;
        std::stringstream{in} >> out;
        return out;
    }
    using std::to_string;
};

Add specializations as needed for efficiency / versatility / correctness / fun.
Eliminate runtime-checks for having selected an acceptable type, powered by the prior change.
That also allows you to use the same basic C++ type with completely different IO-behavior:

template <class T, class traits_type = standard_number_traits<T>>
struct Number : spg::datatypes::BaseDataType
{
    Number(T val = T{}) : val(val) {}
    // Or is BaseDataType(false) not default-init?
    Number(const std::string& s) : Number(traits_type::parse(s)) {}

    std::string toString() const { return traits_type::to_string(val); }
    int getParamCount() { return 1; }

    T val; // Shall that really be public? Well, might be ok.
};

Profit?


Pickling cars with simple management system in Python

def printCars():
    for i, car in enumerate(cars):
        print("Car #{:d}\n{{\n\tname:{:s}\n\tyear:{:s}\n\tcost:{:s}\n}}\n---\n".format(i+1, car.carName, car.year, car.cost))

cars is a global variable: that should be avoided.

Use dictionaries

    if opt == "import":
        importCars()
    elif opt == "export":
        exportCars()
    elif opt == "add":
        addNewCar()
        printSuccess()
    elif opt == "print":
        printCars()

should be a dictionary.

Also I feel like all your methods should be inside the car class as they are logically connected to it.


You are taking a copy of the inner map, modifying it, then putting it back. That could well be inefficient. You could take the inner map by reference then modify it.

However you can actually make use of the fact that map operator[] inserts if it does not find the element. As that is the behaviour here you can do what you did in 2 lines:

map< int, int > & innerMap = mainMapIt[ID]; // will be created as empty if not found
++innerMap[ imageID ];

On a style issue, one does not commonly use an upper case letter as a variable. You also have ID as a variable but elsewhere your variables begin with a lower case letter. You should be consistent throughout in your style, and ideally adopt what is the most common style for C++ programmers (which is generally agreed to be beginning with a lower-case. Some prefer camel-case and some under-score delimited).

You could also decide instead of nested maps, to have a single map with a key consisting of  std::pair<unsigned long long, int >. This might be slightly more efficient as copying maps around could be expensive. It would mean however that you could not as easily search for all the elements from ID.


Good start. I would like to add a few minor things:

Character encoding

As a good practice, the character encoding should be the first element of the head section - or at least it should come before the title element:

<meta charset="utf-8">
<title>SigmaCubes - Home</title>

  In order for all browsers to recognize a  declaration, it must be

  Within the  element,
  Before any elements that contain text, such as the <title> element, AND
  Within the first 512 bytes of your document, including DOCTYPE and whitespace

From Google Code Archive doctype-mirror - MetaCharsetAttribute.wiki

Be consistent

In HTML5 void elements can have an optional / before the closing >. As it seems that you prefer to add this slash, use it everywhere and not only on some elements, like here:

<meta charset="utf-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta name="author" content="Julian Lachniet" />
<meta name="description" content="Various HTML and JavaScript projects." />

Here are some more information about this topic: HTML 5: Is it
,
, or
?

Valid HTML

Images have a mandatory alt-attribute:

You should add this attribute to all img elements. It will not only help people using screen readers to better understand your website, it might also improve SEO.

For more details, see Wikipedia: https://en.wikipedia.org/wiki/Alt_attribute.

Indentation

Try to indent elements, if possible.

… is easier to conceive as:

Semantics

Your main navigation looks fine. However, the section starting with
 looks a bit like divitis.

Learn about HTML5 semantics and how to structure the content of your website. Here're some related articles on w3.org to get started:

3.2.1. Semantics
4.3. Sections
4.5. Text-level semantics

Inline styles

Try to avoid inline styles. This might work for a small page like this, but will get complicated as your project grows.

Instead add a custom CSS file in addition to Bootstrap, where you expand existing styles and add new classes as well.


If the ajax operation is simple, you can use the shorthand $.get instead. I usually use $.ajax when I alter default AJAX settings.

In addition, your code looks unwieldy because you are encountering what they call "callback pyramid". The way to avoid that is use Promises. And you're in luck, jQuery AJAX operations return promises.

Here's a non-pyramid version.

$.get(numeratorUrl).then(function(data) {
  // When get resolves
  var parseDeferred = $.Deferred();
  parse(data, { columns: true }, function(err, output) {
    if (err) parseDeferred.reject(err);
    else parseDeferred.resolve(output);
  });
  return parseDeferred.promise()
}).then(function(output) {
  // When parse resolves
  _this.globalOptions.data.numeratorData = output;
  return $.get(denominatorUrl)
}).then(function(data) {
  // When second get resolves
  var parseDeferred = $.Deferred();
  parse(data, { columns: true }, function(err, output) {
    if (err) parseDeferred.reject(err);
    else parseDeferred.resolve(output);
  });
  return parseDeferred.promise()
}).then(function(newOutput) {
  // When second parse resolves
  _this.globalOptions.data.denominatorData = newOutput;
}, function(error) {
  // Catch-all for all errors
  _this.showErrorMessage(null, error)
});

Would have been better if parse returned a promise or a value (if it was synchronous). If so, then the code would look like this:

$.get(numeratorUrl).then(function(data) {
  // when get resolves
  return parse(data, { columns: true })
}).then(function(output) {
  // when parse resolves
  _this.globalOptions.data.numeratorData = output;
  return $.get(denominatorUrl)
}).then(function(data) {
  // when second get resolves
  return parse(data, { columns: true });
}).then(function(newOutput) {
  // when second parse resolves
  _this.globalOptions.data.denominatorData = newOutput;
}, function(error) {
  // catch-all for all errors
  _this.showErrorMessage(null, error)
});

Here's the same code, explained:

$.get(numeratorUrl).then(function(data){
  // Listen for $.get response,

  // Unless parse returns a promise, we can use Deferreds to manually
  // create promises, resolve and reject. This is handy especially for
  // async operations that don't operate on promises.

  var parseDeferred = $.Deferred();
  parse(data, { columns: true }, function(err, output){
    if(err) parseDeferred.reject(err);
    else parseDeferred.resolve(output);
  });

  // We return the deferred as a promise, a read-only version of the deferred.
  // This means we lose the resolve and reject interface from the deferred.
  return parseDeferred.promise();

}).then(function(output){
  // Since we returned a promise from the last then, this callback now listens
  // to that promise instead of the $.get()'s promise.

  _this.globalOptions.data.numeratorData = output;

  // Now we do another AJAX call. We return it's value (which is a promise) which
  // means the next chained then listens to this promise instead of the one from
  // parse. Since $.get() returns a promise, we don't need to manually use Deferreds.
  return $.get(denominatorUrl);

}).then(function(data){

  // Use the same pattern as above
  var parseDeferred = $.Deferred();
  parse(data, { columns: true }, function(err, output){
    if(err) parseDeferred.reject(err);
    else parseDeferred.resolve(output);
  });
  return parseDeferred.promise();

}).then(function(newOutput){

  _this.globalOptions.data.denominatorData = newOutput;

}, function(error){
  // Now the nice thing about promises is that errors propagate the
  // same way resolved values propagate. Unless you return a new promise,
  // the succeeding thens will always resolve/reject with the value from
  // the latest resolved/reject promise.
  //
  // If the first $.get() failed, this will catch the error. If the
  // first succeeded, and the parse after it failed, this catches it.
  //
  // In jQuery, I believe their rejection resolves with 3 values,
  // the xhr object, text status and another status - which is not
  // now native promises work. So you might want to look after it.

  _this.showErrorMessage(null, error);
});


Import Excel, unpivot data, output tab-delimited for SQL Import

Path Joining

$srcDir = "C:"
$srcFile = "$SrcDir\ClientGL.xlsx"
$srcTab = "Sheet1"
$outFile = "$SrcDir\ClientGL.txt"

Although it may seem unnecessary in this case, you should know that Join-Path exists.

$srcDir = "C:"
$srcFile = $SrcDir | Join-Path -ChildPath "ClientGL.xlsx"
$srcTab = "Sheet1"
$outFile = Join-Path $SrcDir "ClientGL.txt"

The nice thing about using this (again, unnecessary here) is that it takes care of leading and trailing path separators, so the following:

Join-Path "C:\" "\Windows"
Join-Path "C:" "Windows"

Will both produce C:\Windows. That makes it great for user input.

Write-Host vs Write-Verbose

This can be debated, but some (myself included) take a cautious approach with Write-Host. The reason is that it forces the output to the screen, instead of letting the caller decide whether they want status messages.

Ultimately, you take this on a case-by-case, and sometimes Write-Host is the right tool, and maybe it is for you in this case.

Using Write-Verbose instead, you would normally not see the output, unless you call your script with -Verbose, and then you will see it.

To add support for this, you need to add a parameter block to your script, even if you aren't going to take any parameters.

Top of script:

[CmdletBinding()]
param()

That will automatically add support for -Verbose.

Aliases

If(ps excel){kill -name excel}

and

(Get-Content $outFile) | % {$_ -replace '"', ""} | Out-File -FilePath $outFile -Force

ps is an alias for Get-Process.
kill is an alias for Stop-Process.
% is an alias for ForEach-Object.

I love PowerShell's aliases, but when it comes to writing a script that's meant to be re-used often or might ever be read by other people, I am of the school that one should use the full cmdlet/function name, and use full parameter names.

I use aliases when I'm using PowerShell as a shell and typing commands to run immediately, or to quickly prototype something.

For me it's a matter of clarify and readability, but this is of course personal preference (I have met at least one person who feels differently and uses aliases everywhere).

Reading the first line of a file

$inHeaders = (Get-Content $outFile | Select-Object -First 1).Split("`t")

If you're using PowerShell 2.0, the above line will read every line of the file, and even though Select-Object will only give you back the first 1, it has no way of stopping the pipeline. If your file is large, this could take a very long time.

If you're using PowerShell 3+, then the above will actually only read the first line because Select-Object will stop the pipeline.

Note that Get-Content has a -TotalCount parameter though, so you can use:

$inHeaders = (Get-Content $outFile -TotalCount 1).Split("`t")

and it will read just the first line.

.Split() vs -Split

$inHeaders = (Get-Content $outFile | Select-Object -First 1).Split("`t")

Here you're using the .Split() method of a [String]. PowerShell also has a -Split operator. The operator has a lot of nifty features that from what I've seen no one ever uses, because they don't know they exist or (in my case) they always forget about them when needed.

But the main difference that you probably will remember is that the operator takes a regular expression, and the method takes a string.

There's nothing wrong with either, just wanted you to be aware of the differences.

Accepting Parameters

$srcDir = "C:"
$srcFile = "$SrcDir\ClientGL.xlsx"
$srcTab = "Sheet1"
$outFile = "$SrcDir\ClientGL.txt"

Consider making these parameters that can be passed to the script. You could also make them have defaults that way.

Top of script:

[CmdletBinding()
param(
    [Parameter(
        Mandatory=$false
    )]
    [String]
    $Path = "C:" ,

    [Parameter(
        Mandatory=$false
    )]
    [String]
    $srcTab = "Sheet1"
)

$srcFile = "$Path\ClientGL.xlsx"
$outFile = "$Path\ClientGL.txt"

Now you can call the script like so:

.\MyScript.ps1 -Path "C:\Some\Other\Path\" -srcTab "Expenses"

Now you can see why using Join-Path would save you some headache because you're accepting user input!

Just to break down this param() block a bit:

[Parameter()] can take multiple comma separated options; I've shown you Mandatory. Mandatory means mandatory to be supplied by the caller not to have a value, so when you use a default value like we are here, you don't want to make the parameter mandatory. Parameters are by default optional, so this was unnecessary; I was just demonstrating it.

The entire [Parameter()] attribute is also optional, and could be left out.

[String] is specifying the data type for the parameter. PowerShell will try to coerce input values into this type if possible. Data type is also optional.

$Path: this is the name of the parameter. It is the only part that's mandatory. I used $Path instead of $srcDir because PowerShell has conventions for certain names to represent certain things.

So generally any cmdlet or function that accepts a path will use -Path. Same for -ComputerName, -Identity, -Credential.

Also note that all of these pieces could have been on a single line. I like to separate them for clarity.

For more on these, have a look at Create a Truly Advanced PowerShell Function and the about_Functions_Advanced and about_Functions_Advanced_Parameters help topics.


Scheme, first timer first program, simple list removal technique

In your function firstnprimes there is a typo near the end; more importantly it uses append but it is the wrong function to use there. What does append append? If called with two arguments the 2nd of which is a list, what must the first argument be - a list, or a value?

Another problem is your call (append (car nlist) slist) returns new value, a bigger list, but you do nothing with it. slist's value remains unchanged.

What are the two arguments of firstnprimes function, nlist and slist? What are their initial values? Will any two lists do? Obviously not. So, it seems better to define the real top-level function that is safe and easy to use:

(define myfirstnprimes
  (lambda (n)
    (firstnprimes n (listupto ...) (...))))

Something is missing there, isn't it? Some new, hidden parameter?

Now, you ask how to implement

(define listminusnonprimes
  (lambda (num list)
    ....

you call it as (listMinusNonprimes (car nList) nlist) so we know that initially, num is the first element of list; we also know that list is an ordered list of numbers increasing in value. So we just need to compare num with the list's first element:

   (let ((a (car list)))
     (cond
       ( (< num a) ... (listminusnonprimes ...) )
       ( ... )
       ( ... ))) ))

what are the cases? less-then, equal, greater-then, right? All that's left is to fill in the blanks. In particular, if the two are equal, both need to be removed and num changed to the next multiple of the prime; if num is greater, the top element should be kept; otherwise num should be changed to the next multiple of the prime. New missing parameters come into light here (prime... what prime? next multiple... how to find it?); also it isn't clear what does it mean "to keep" and "to remove", right?

About multiples, just write them down in a sequence first: p, 2p, 3p, 4p, .... Now devise a method of finding the next from the previous one. What information will you have to maintain?

About keeping/removing. There are two ways. One will lead to using set-cdr!, another to using cons, and an additional accumulator parameter. Choose any to your liking.

Lastly, your buildlist builds a descending list towards 2, and listupto just reverses it; instead move the former into the latter and have it build the correct list right away from 2 up to the upper limit, held by listupto's argument:

(define (listupto m)
  (let buildlist ((n 2))
    (if (> n m) ...
      (cons n (buildlist ...)))))

Named let is described e.g. here.


Introduction and solution code

Since you mentioned making the output matrix sampleProb, I am assuming it to be initialized as all zeros. So, here's the vectorized implementation with the mighty bsxfun -

%// Get the subtractions
sub1 = bsxfun(@minus,samples,permute(samples,[3 2 1]))

%// Calculate the sum of normcdf's in a vectorized fashion
sampleProb = bsxfun(@minus,sum(normcdf(sub1),3),normcdf(sub1(1,:,1)))./M

Benchmarking

Benchmarking Code with M = 100 -

M = 100;
samples =  rand(M,M);
sampleProb1 =  zeros(M,M);

disp('---------------------------------------- With Original Approach')
tic
for i = 1:size(samples, 2)
    for j = 1:M
        for k = 1:M
            if (k ~= j)
                sampleProb1(j, i) = sampleProb1(j, i) + normcdf(samples(j, i) - samples(k, i));
            end
        end
    end
end
sampleProb1 = sampleProb1./M;
toc, clear sampleProb1 i j k

disp('---------------------------------------- With Proposed Approach')
tic
%// Get the subtractions
sub1 = bsxfun(@minus,samples,permute(samples,[3 2 1]));

%// Calculate the sum of normcdf's in a vectorized fashion
sampleProb = bsxfun(@minus,sum(normcdf(sub1),3),normcdf(sub1(1,:,1)))./M;
toc

Runtime results -

---------------------------------------- With Original Approach
Elapsed time is 21.425729 seconds.
---------------------------------------- With Proposed Approach
Elapsed time is 0.046284 seconds.


Review:
From extensibility and in pro of having the possibility of including in future versions more operations, it is a good approach. The code is very simple, and it is easy to read so it is very good your design proposal.

The main purpose of applying design patterns is to simplify things, to reach the maximum level of abstraction and allow you to write meaningful code, not just repeat stuff

So, you did good.
However, there are some observations:
package oopdesign.calculator;

//Singleton is a good approach for this problem
public class Calculator {

    //By default any object is null
    //Do not put it as public, you have the getInstance method
    private static Calculator instance;

    //You are limiting the operations to handle
    CalculationStrategy calculationStrategy;

    //This is not a Singleton if you allow the default constructor (its public by default)
    private Calculator() {
    }

    public void setCalculationStrategy(CalculationStrategy calculationStrategy) {
        this.calculationStrategy = calculationStrategy;
    }

    public static Calculator getInstance() {
        if (instance == null)
            instance = new Calculator();
        return instance;
    }

    //You should think about handle the most general data type (this case double)
    public double calculate(double value1, double value2) {
       return calculationStrategy.calculate(value1, value2);
    }
}

package oopdesign.calculator;

public class CalculatorMain {

    public static void main(String[] args) {

        Calculator c = Calculator.getInstance();

        //There is a problem with it, you need to instanciate the strategies
        //each time you need to use it
        c.setCalculationStrategy(new AdditionStrategy());
        System.out.println(c.calculate(5,2));

        //It requires space, plus you are not being efficient by storing
        //there operations (calculation strategies)
        c.setCalculationStrategy(new SubtractionStrategy());
        System.out.println(c.calculate(5,2));

        c.setCalculationStrategy(new MultiplicationStrategy());
        System.out.println(c.calculate(5,2));

        c.setCalculationStrategy(new DivideStrategy());
        System.out.println(c.calculate(5,2));
    }
}

An alternative
import java.util.HashMap;
import java.util.Map;

public class Calculator {

    private static Calculator instance;

    //search in Constant time (approximately)
    private Map<String, CalculationStrategy> calculationStrategies;

    private Calculator() {
        calculationStrategies = new HashMap<>();
    }

    public void addCalculationStrategy(String name, CalculationStrategy strategy) {
        calculationStrategies.put(name, strategy);
    }

    public static Calculator getInstance() {
        if (instance == null)
            instance = new Calculator();
        return instance;
    }

    //double b... means that there may be 0 to n parameters
    //consider that there are unitary operators or functions in a calculator
    public double calculate(String name, double a, double... b) {
        return calculationStrategies.get(name).calculate(a, b);
    }
}

package oopdesign.calculator;

public class Main {

    public static void main(String[] args) {
        Calculator calculator = Calculator.getInstance();

        //Use a lambda instead
        calculator.addCalculationStrategy("+", (a, b) -> a + b[0]);
        //[b] is taken as an array but is a variadic parameter
        calculator.addCalculationStrategy("-", (a, b) -> a - b[0]);
        calculator.addCalculationStrategy("*", (a, b) -> a * b[0]);
        calculator.addCalculationStrategy("/", (a, b) -> a / b[0]);
        calculator.addCalculationStrategy("Abs", (a, b) -> Math.abs(a));
        calculator.addCalculationStrategy("Cos", (a, b) -> Math.cos(a));
        calculator.addCalculationStrategy("Sin", (a, b) -> Math.sin(a));

        System.out.println(calculator.calculate("+", 1, 3));
        System.out.println(calculator.calculate("-", 1, 3));
        System.out.println(calculator.calculate("*", 1, 3));
        System.out.println(calculator.calculate("/", 1, 3));
        System.out.println(calculator.calculate("Abs", -66));
        System.out.println(calculator.calculate("Cos", 75));
        System.out.println(calculator.calculate("Sin", 28));
        System.out.println(calculator.calculate("+", 666, 777));
    }
}

About double b... read this post about Variadic function parameters, as I said, it is a way to have multiple parameters, From 0 To N parameters
Thanks for reading this answer.


Independent cascade model for networkx graphs

Correctness / Readability
I'm not sure if this is a bug, or just an unclearness of the algorithm.
    while updated:
        for ... in ...:
            updated = False
            if ...:
                if ...:
                    if ...:
                        ...
                        updated = True

If you want to loop over the edges, until no change is made, then the updated = False looks like it is in the wrong place.  As it currently stands, if the last edge processed in the for loop fails any of the 3 if conditions, the updated flag is set to False, even if a prior edge set it to True.
Wouldn't the correct implementation be:
    while updated:
        updated = False
        for ... in ...:
            if ...:
                if ...:
                    if ...:
                        ...
                        updated = True

Now, for each while loop iteration, we start by clearing the flag.  Then, if any edge results in updated = True, a change has been made and the while loop is repeated.
If the updated = False was in the correct place, then the readability of the code could be improved with comments explaining why update = True only matters for the last edge returned by the for loop.


skills = new SkillType[2];
skills[0] = a; skills[1] = b; skills[2] = c;

This is simply wrong.  You make an array of size 2 and then put three things in it.

Also, you never set a, b, or c, so you might as well leave off the second line.

public int acost, bcost, ccost;
public int acooldown, bcooldown, ccooldown;

These are never read, so you could delete them.

In general, this code feels incomplete.  Your enum looks about as short as it can be for the functionality.  The rest of the code is unclear about what it is doing.  You could probably delete almost all of it.


Exporting array of tabs to new workbooks, save them based on tab name

I do have a few suggestions:

First of all, you don't need to reactivate your main
workbook every loop, since you hold it's reference in a variable
anyway.
Second, instead of creating new workbook and copying the sheet over, just make a copy to new workbook (i.e. wks.Copy creates copy in new workbook, you can then assign it to a variable since, as you said yourself, it is now the active workbook)
Lastly, unless you want to remove the references (for example if the links contain sensitive information), then I wouldn't worry about it. Excel stores the last value from links in cache within the file.

Depending on your setup, suggestion 2 might actually speed it up a little by reducing the number of actions.

To copy sheet to new workbook, simply ws.Copy, then you can set newWs = Activesheet (or using your naming set NewBook = Activeworkbook) to save it's reference, or just skip that also and put Activeworkbook into your With.


The above implementation has little to no chance of working. The HTTP protocol is quite complex, and none of that complexity is contemplated.

My advice is, don't waste time and energy in this. Use a high-level library.

Also, using low-level code will NOT improve the performance of fetching a document via HTTP -- even if your implementation was blazing-fast 100% polished assembly code, you'd still have to wait centuries (from the CPU point of view) for the data to arrive from the network.


Don't write using namespace std;.
maxHP should be constexpr or at least const.  In general, use const where you can.


Effective Python 2/3 two-dimensional array initialisation

First off don't use multiplication.
It's creates 2 lists, not 7001.

To better show this, hop into IDLE:

>>> a = [[0] * 3] * 3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

No this is not what you want.

In both your other functions you should use _,
this is a convention that says you don't use the result, it's thrown away.

This results in:

def list_comprehension_xrange():
    matrix = [[0 for _ in xrange(A)] for _ in xrange(B)]

If speed is highly important, then you can use a hybrid of multiplication and range or xrange.
From the benchmarks I'd lean towards xrange, but I don't think there is too much difference.

I can't say exactly why these are so fast, it may be because the multiplication doesn't build and destroy an intermarry list.
Or it's not creating a list in Python code but in C. Or it's not building ~A*B amount of objects only ~B amount. But I don't.

I added the following functions, with timers:

def multiplication_range():
    matrix = [[0] * A for _ in range(B)]
def multiplication_xrange():
    matrix = [[0] * A for _ in xrange(B)]

And got the following results:

list_comprehension_xrange: 23.0122457496
list_comprehension_range: 24.9418833563
multiplication: 0.00104575910762
multiplication_range: 3.35667382897
multiplication_xrange: 3.35528033683


Minimum amount of spaces inserted in a given string, such that it gets composed only of elements from a given list

Firstly, great job on creating a solution that works. That is often the first step in creating an optimal solution.

But as you may have noticed, making combinations and permutations based on the number of elements in small_strings will start to scale incredibly as you process longer and longer small_strings arrays.

Mathematically, your solution is concise and straight-forward-- kudos again to that. The approach I will suggest is based on Dynamic Programming and preprocessing. This is to speed up scenarios where you have a very large (>100) number of small_strings.

This approach will use the fact that we can solve the whole problem in the same manner of solving a subset of the problem. Specifically, if we can construct the big_string piece by piece, then we can simply add the result of the part we have constructed and add/recurse it on the rest of the string.

The first idea to consider is building a trie for the strings in small_strings. Also known as a prefix tree, a trie will help us figure out which strings we can use to 'construct' the big_string. I highly recommend understanding the concept of a trie for further insight into this problem.

Secondly, we want to implement a function that explores the problem space in a way that is efficient and breaks on paths that yield no results. This is typical of many DP (Dynamic Programming) problems and often looks like recursion in practice. Knowing when and how to implement this comes with practice. I also highly recommend practicing some classical DP problems if you want to become a skilled developer.

With those points in mind, here's a solution:

def buildTrie(words):
    trie = {}
    for word in words:
        current = trie
        for c in word:
            current = current.setdefault(c, {})
        current['isWord'] = word

    return trie

def findPrefixes(trie, word):
    results = {}
    current = trie

    for length, l in enumerate(word, start=1):
        if l in current:
            current = current[l]
        else:
            break
        if current.get('isWord'):
            results[current['isWord']] = length

    return results

def find_num_spaces(big_string, small_strings):
    trie = buildTrie(small_strings)
    N = len(big_string)

    def helper(index=0):
        nonlocal trie, N

        if index == N:
            return 0

        prefixes = findPrefixes(trie, big_string[index:])

        if prefixes:
            return min(1 + helper(index + length) for length in prefixes.values())
        else:
            return float('inf')

    return helper() - 1

big_string = '3141592653589793238462643383279'
small_strings = ['3', '314', '49', '9001', '15926535897', '14', '9323', '8462643383279', '4', '793', '3141592653589793238462643383278', '314159265358979', '3238462643383279']

assert find_num_spaces(big_string, small_strings) == 1

big_string = '3141592653589793238462643383279'
small_strings = ['3', '314', '49', '9001', '15926535897', '14', '9323', '8462643383279', '4', '793', '3141592653589793238462643383278', '3141592', '65358979323']

assert find_num_spaces(big_string, small_strings) == 2

Since we do our preprocessing in the form of a trie, we know how to efficiently reconstruct our big_string. The general idea here is that we are trading space for time complexity. Storing our strings allows for efficient exploration of the problem space.

Note: I assumed you only needed the number of spaces required-- requiring the specific strings involved would tweak this solution slightly. There would be an additional variable that would track the working solution through the recursion.


Mersenne Twister random-number generator function

Math

Well, I believe usually you could avoid the math, but this is a special case. The main things to cover is random variable, random functions and distributions. It is gonna help a lot. Do note that int distribution is discrete, whereas real distribution is continuous.

Code Review

Incorrect usage of twister

First of all, std::mt19937 generates only 32 bit random numbers. This means that by truncating it to int (not always, depends on the platform), the code will discard higher (or lower) 16 bits of the number.

The twister has state, which means that when function generates one random number, it will discard the state and start from scratch when called again. Although std::random_device might normalize the behavior, the output will not be as intended.
Incorrect usage of distribution

std::uniform_distribution has a constructor taking T min, T max, which means that unsigned long long will overflow the arguments, which I believe is undefined behavior.

Return type is unsigned long long, but generates values are of type int, which means that higher (or lower) bits will be zero or garbage. Both of the cases are wrong.

Different solution

If you want a generator without all of the hoops to jump through, just slam everything into a class. Here is the rough sketch (might not compile):

#include <random>

class uniform_int_generator
{
    std::mt19937_64 twister;
public:
    uniform_int_generator():
                  twister(std::random_device{}())
    {}

    unsigned long long operator()(unsigned long long max_val, unsigned long long min_val)
    {
        std::uniform_int_distribution<unsigned long long> distr(max_val, min_val);
        return distr(twister);
    }
};

You might want to add some customization points using templates. Anyway, if you need more, make this one compile and post question with the updated code.


Class dedicated to transforming API response to the data I need?

Your might actually take it a step further and create a value object for the data, making it much more type safe. Notice I added PHP 7.4 proeprty typehints. I chosen float for the temperature (maybe it's not appropriate, idk), but i definitely don't know what to choose for the main, but it sure deserves a typehint, if it's nested object, create another class for it or maybe pick the wanted information directly into the WeatherStatus class.
final class WeatherStatus
{
  private ??? $main;
  private float $temperature;

  public function __construct(??? $main, float $temperature)
  {
    $this->main = $main;
    $this->temperature = $temperature;
  }

  public function getMain(): ???
  {
    return $this->main;
  }

  public function getTemperature(): float
  {
    return $this->temperature;
  }
}

You can also define an interface for such a method, including a domain specific exception (because just halting the program with die or exit is not very nice thing to do, in that case it would be better to not catch the exception at all).
class WeatherProviderException extends \Exception
{
}

interface IWeatherProvider
{
  /**
   * @throws WeatherProviderException
   */
  public function getWeather(): WeatherStatus;
}

In the implementation I would accept the api url rather then hardcoding it. You may add a static named constructor for the version 2.5 api.
The credentials for openweathermap.org (whatever they are, let me assume a user name and password) might be also promoted to a class or may be passed to the provider constructor as multiple arguments as well.
final class OpenWeatherCredentials
{
  private string $user;
  private string $password;

  // constructor + getters ...
}

class OpenWeatherProvider implements IWeatherProvider
{
  private ClientInterface $client;
  private string $apiUrl;
  private OpenWeatherCredentials $credentials;

  public function __construct(ClientInterface $client, string $apiUrl, OpenWeatherCredentials $credentials)
  {
    $this->client = $client;
    $this->apiUrl = $apiUrl;
    $this->credentials = $credentials;
  }

  public static function createV2_5(ClientInterface $client, OpenWeatherCredentials $credentials): self
  {
    return new self($client, 'https://api.openweathermap.org/data/2.5/weather', $credentials);
  }

  public function getWeather(): WeatherStatus
  {
    $options = [
      // whatever is needed, $this->credentials->get*
    ];

    try {
      // here you called the object $request, but it really is a $response
      $response = $this->client->get($this->apiUrl, $options);
    } catch (GuzzleException $e) {
      throw new WeatherProviderException($e->getMessage(), $e->getCode(), $e);
    }

    try {
      $json = json_decode($response->getBody(), \JSON_THROW_ON_ERROR);
    } catch (\JsonException $e) {
      throw new WeatherProviderException($e->getMessage(), $e->getCode(), $e);
    }

    return new WeatherStatus(
      $json->weather[0]->main,
      (float) $json->main->temp,
    );
  }
}

Also notice how I wrap each statement in separate try-catch to only catch what can be caught. As long as they are handled the same way you try-catch both together but maybe you should catch their common ancestor exception instead to make it even simpler. And I pulled the instantiation of the WeatherStatus out of the try-catch just because I don't expect it to throw GuzzleException nor \JsonException.


An alternative is to simply use what HTML has built-in:

<input type="password" required minlength="8">

will make that input mandatory and enforce a minimum of eight characters. (You can also use these attributes with type="text".) It's no less secure than doing the validation in JavaScript, as you should still validate it server-side anyway. However, it isn't possible to check using HTML attributes that the two password fields are the same.

The :optional and :required CSS pseudo-classes can be used for styling the input based on the required attribute, but you can also use the more general :valid and :invalid pseudo-classes, which will also respond to things like minlength. You can check these pseudo-classes in JavaScript using Element#matches, but you might have to also check for non-standard naming as ${prefix}MatchesSelector.

The only problem with this approach is the browser compatibility: minlength is not supported except by Chrome and Opera, but you can replace it with the pattern attribute which has wider support, along with the required attribute. Except for Safari and IE <10.

More information about <input> is available at MDN and WebPlatform Docs.


Looking at int->roman ...

It simply ignores digits that are too big. 10000 maps to ""!
Surely better to repeat the biggest signifier as often as necessary.
The logic for the  one five ten units for digit is in your head. We can derive them from a list of the symbols in increasing order. And it's easier to wrap them as a single argument to digit.
I've done the string concatenation within digit.
I've dumped the base argument and done the digit-ising inline.

For what it's worth ...

(def symbols "IVXLCDM")

(defn digit [[one five ten] n]
  (let [chars (case n
                4 [one five]
                9 [one ten]
                (cons (when (<= 5 n) five)
                      (repeat (mod n 5) one)))]
    (apply str chars)))

(defn int->roman
  "Returns the Roman numeral representation of n."
  [n]
  {:pre [(integer? n) (pos? n) (odd? (count symbols))]}
  (let [triples (partition 3 2 symbols)
        heads (->> n (iterate #(quot % 10)))
        digits (map (fn [t i] (digit t (mod i 10))) triples heads)
        left-over (nth heads (count triples))
        left-overs (->> (last symbols)
                        (repeat left-over)
                        (apply str))]
    left-over
    (->> (concat digits left-overs)
         reverse
         (apply str))))

For example,

(int->roman 11976)
;"MMMMMMMMMMMCMLXXVI"

It could be made faster as a big fat reduce, but I prefer it slow and fairly clear. It gave me enough trouble!


Increasing the coefficients of two numbers to sum to a targeted value

Rearrange the equation to find one variable from another.

\$R = xX + yY\$
\$xX = R - yY\$
\$x = \frac{R - yY}{X}\$

And so, if you don't want negative values of \$x\$, then you need to limit the range to \$\lfloor \frac{R}{X} \rfloor + 1\$.

This also will return floats, which for the most part shouldn't make a difference as it's a subtype of int. However as we're limiting the results to integers then converting the number to an int could make sense.
I also wouldn't return -1, but would instead use None or an empty list. This is as -1 makes no logical sense.
And rather than extending a list with another list, just return the wanted list. Better you could return a tuple.

This allows for:

def coefTargetSum(R, X, Y):
    for y in range(R // X + 1):
        x = (R - y*Y) / X
        if x % 1 == 0:
            return int(x), y
    return None


If you are looking for ways to optimize your application - you are clearly looking at the wrong place, at least in my opinion. BinaryWriter is a simple wrapper around actual stream. All it does is it converts simple types to byte arrays and writes those to stream. Ofc it is slower, as any other wrapper, but not that much slower. In real life this difference can be ignored.

If writing to NetworkStream is your main performance issue, then consider wrapping it with BufferedStream.

If it isnt, and you are simply curious... then you can always use disassembler to see whats inside BinaryWriter.Write method for yourself.


Python - Simple wrapper class for a bot API

Does it make sense to re-define a RequestException class within this module?

Yes, that makes total sense. Library users should never be expected to catch dependency exceptions. If there's even the slightest chance a user needs to interact with a dependency exception, you should 'copy' it.

If you wish to create a custom exception, it's nearly always better to derive it from an exception category (type error, value error, lookup error, ...) than directly from Exception. ConnectionError would suffice.

The from ex is unnecessary. The previous exception is already preserved as context.

You should also be asking yourself 'does the user really need to see the full stack trace?'. For trivial problems, things like HTTP 4XX or 5XX status codes, you could adjust the exception message to include the code.


I would have just inherited from the built-in collections.deque:

from collections import deque

class Queue(deque):
    def add(self, value):
        self.append(value)

    def top(self):
        return self[0]

    def pop(self):
        return self.popleft()


Finding users with the highest Following vs. Friends ratio

Your code is not working well, and the SQL statement is not formatted nicely either.

Reformatting your code in to logical sections produces.

SELECT CAST(followers_count AS DECIMAL)/ CAST(friends_count AS DECIMAL),
       screen_name
FROM following
ORDER BY CAST(CAST(followers_count AS DECIMAL)/ CAST(friends_count AS DECIMAL) AS INT) DESC
LIMIT 25;

SQLite is notorious for doing calculations based on the wrong affinity of the data values.

I immediately suspected that the SQL was doing integer division on the values even though you are casting them to decimal.

I put some examples together as an SQLFiddle here, and I cast the values to float instead, then used the SQLite round() function to get things decent. Doing floating-point division is what solves the zero-value division before.

This is the SQL I ended up with:

SELECT ROUND(CAST(followers_count AS float) / CAST(friends_count AS float), 2) as ratio,
       screen_name
FROM following
ORDER BY CAST(followers_count AS float) / CAST(friends_count AS float) DESC
LIMIT 25;