Associating a string with a derived class

Would this solution use memory for every class instance rather than once per class?

Depends on whether your class already contains a vtable pointer or not.

If it does, there will be no additional memory requirements per instance (just another entry in the vtable, which is shared by all instances).

If it doesn't, each class will need an additional vtable pointer (that will be automatically inserted by the compiler to make virtual dispatch work). Also, a vtable will be generated, but those are one per class.

However, since you are already using (and that includes possibly deleting) instances of derived classes via pointer to base class, the base classes destructor (in this case Node::~Node()) should already be marked virtual so the derived classes destructor gets called correctly when deleting the Node*. This means each class should already have a vtable anyways - so no additional per-instance overhead.


All the knight moves in all the right places

Joshua: What's the difference?

Computers sometimes have a hard time to differentiate between things that are apples and oranges to us, some examples are:

if this is a game or if this is real
thermonuclear war and a game of chess
char and int

You have two functions converting from char to int and back:

char num_convert(int *n) {
    for (int i = 0; i < BOARD_LENGTH; i++) {
        if (*n == rows[i]) {
            return cols[i];
        }
    }
}

int alpha_convert(char *c) {
    for (int i = 0; i < BOARD_LENGTH; i++) {
        if (*c == cols[i]) {
            return rows[i];
        }
    }
}

This is not necessary in C, because char and int are kind of the same thing. You can do regular calculations with characters just like you do with integers. Once in character, stay in character.

So when it comes to playing the game of converting between both types, I'd have to say the only winning move is not to play.

the mysterious void add_moves()

I have no idea what this function does.

void add_moves(int c, int n1, int n2) {
    if (c >= 1 && c <= 8) {
        if (n1 >= 1) {
            moves[move_iter++] = num_convert(&c);
            moves[move_iter++] = n1 + '0';
            moves[move_iter++] = ' ';
        }
        if (n2 <= 8) {
            moves[move_iter++] = num_convert(&c);
            moves[move_iter++] = n2 + '0';
            moves[move_iter++] = ' ';
        }
    }
}

Why are there two n but only a single c? What do those values represent?
They are apparently boundary checked, too. Then there's this code block that's pretty much duplicated for both n, which is bad.

        if (n1 >= 1) {
            moves[move_iter++] = num_convert(&c);
            moves[move_iter++] = n1 + '0';
            moves[move_iter++] = ' ';
        }

After all, something is somehow added to moves, which justifies the name add_moves(). But it's not immediately clear to me what's going on in that function and I feel like too much is going on.

a hint in char* valid_moves()

This function takes away a bit of the mystery from what add_moves() is doing. As it calls it with different possible moves of the knight.

add_moves(C - 2, N - 1, N + 1);
add_moves(C - 1, N - 2, N + 2);
add_moves(C + 1, N - 2, N + 2);
add_moves(C + 2, N - 1, N + 1);

This is not very intuitive. Why do I only see 4 lines here? The knight can do 8 moves in general. Now it is clear why add_moves() takes two n values as parameters, but only one c.

This distribution of logic doesn't appear to be plausible. It's like some part of the movement is calculated in one place while the other happens later. If the concerns of the functions were more clearly separated, it would be easier to understand them.

I gave it a try myself. Here's how I did it:

Position type

This is all about positions, so let's create a type for that.

typedef struct
{
    signed char column;
    int row;
}
Position;

We're not in oop land, but we still group data together if it belongs together. This helps a lot when passing it around.

  disclaimer: I often see type names like position_t and I absolutely hate that, which is why I'm not using it. Your naming convention may vary.

relative knight moves as positions

Is 5 meters an absolute position or a difference between two positions? It can very well be both! In the same idea, let's create an array of Position that represent the relative movements a knight can perform.

Position allKnightMovesInAlphabeticalOrder[] =
{
    {-2, -1},
    {-2, +1},
    {-1, -2},
    {-1, +2},
    {+1, -2},
    {+1, +2},
    {+2, -1},
    {+2, +1}
};

#define numberOfKnightMoves 8

As you can see, -2 is a perfectly fine signed char value. 1

If you are uncomfortable reusing the Position type which from its name might suggest to be an absolute position, you can always typedef it to a Move type, which makes the intention more clear.

position check

A handy helper function could solve the sub-problem of whether a certain position is on the board or not.

bool positionIsInChessboard(Position *position)
{
    return
        position->column >= 'a' &&
        position->column <= 'h' &&
        position->row >= 1 &&
        position->row <= 8;
}

You need to #include <stdbool.h> for bool. If you don't want that, you should be able to use _Bool as a return type.

making a move

Another helper function that simply adds two positions together.

void addTwoPositions(Position *a, Position *b, Position *result)
{
    result->column = a->column + b->column;
    result->row = a->row + b->row;
}

Again, as a Position might represent a relative movement, this starts to make sense I hope. If not, recall how a 2D vector in math might represent a fixed point or the difference between two points. This is the same idea.

putting it all together

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

typedef struct
{
    signed char column;
    int row;
}
Position;

Position allKnightMovesInAlphabeticalOrder[] =
{
    {-2, -1},
    {-2, +1},
    {-1, -2},
    {-1, +2},
    {+1, -2},
    {+1, +2},
    {+2, -1},
    {+2, +1}
};

#define numberOfKnightMoves 8

bool positionIsInChessboard(Position *position)
{
    return
        position->column >= 'a' &&
        position->column <= 'h' &&
        position->row >= 1 &&
        position->row <= 8;
}

void addTwoPositions(Position *a, Position *b, Position *result)
{
    result->column = a->column + b->column;
    result->row = a->row + b->row;
}

int main ()
{
    Position testPositions[] =
    {
        {'g', 2},
        {'a', 1},
        {'d', 6},
        {'e', 5},
        {'b', 1}
    };

    int numberOfTestPositions = sizeof(testPositions)/sizeof(Position);

    Position result;

    for(int testPositionIndex = 0; testPositionIndex < numberOfTestPositions; testPositionIndex++)
    {
        printf("%c%d:\t", testPositions[testPositionIndex].column, testPositions[testPositionIndex].row);

        for(int moveIndex = 0; moveIndex < numberOfKnightMoves; moveIndex++)
        {
            addTwoPositions(&testPositions[testPositionIndex], &allKnightMovesInAlphabeticalOrder[moveIndex], &result);

            if(positionIsInChessboard(&result))
            {
                printf("%c%d ", result.column, result.row);
            }
        }

        printf("\r\n");
    }
}

I hard coded the test positions into main() for brevity. the basic idea for every test case is to iterate over all the possible knight moves, perform them via addTwoPositions() and then check the validity of the result with positionIsInChessboard().

I do not build up a buffer as you do in your code simply because that isn't necessary.

Here's what I get as a result in terminal:

$ ./chess
g2: e1 e3 f4 h4
a1: b3 c2
d6: b5 b7 c4 c8 e4 e8 f5 f7
e5: c4 c6 d3 d7 f3 f7 g4 g6
b1: a3 c3 d2

1 thanks @Daniel Jour for pointing out that plain char has an unspecified signedness, which may vary across platforms and compilers.

For me, I get the same output for any of the three versions char, signed char or unsigned char. It's still good practice to use signed char as it makes it more obvious that a Position might be a relative position.


Custom PHP MySQL database queries function - Suggestions for improvement or additions

This monster of a function is hard to use and hard to maintain. Besides, it is bloated with duplicated and/or unnecessary code. Last but not least, the way require "dbconn.script.php"; is called will make your code run slower and make some features (such as transactions) unavailable.
Too many connections
Your current code is connecting to the database every time it runs a query. You shouldn't do that. Always connect strictly  once and then pass a connection variable as a function parameter.
Useless regexp
You already control the return type buy means of $param variable. No need to check the query type manually. It is useless and error prone. What if your query is CALL? SET? REPLACE?
Passing values as array is not that hard.
With your function you have a choice, whether to pass $values as array or not. It makes the code hard to read. At the same time adding two square brackets to your $values is not a big deal. So just just make $values an array mandatory.
Too much tasks for a function
The first question I must ask, why only a single function to perform so many tasks? All right, I can make it you are not familiar with OOP and don't want to use a class (which would be the best solution of course). But why not to make a set of functions, each serving for its own purpose? Why following that horrible practice of procedural mysqli when you have to write a helluvalot of words every time you calling a simple function (mysqli_stmt_get_result($stmt) vs. $stmt->get_result())?
Here is your intended function call
$rows = mysqli_database_query($sql, $id, "affected_rows");

compare it with with a code which is shorter but more meaningful and readable at the same time:
$rows = mysqli_delete($sql, [$id]);

A function name should be meaningful and tell you what does this function do. It should be a function name, not a parameter.
In your place I would create a set of functions. Say, a basic one that just performs a query
function mysqli_database_query($conn, $sql, $values, $return_result = true)
{
    $types = $types ?: str_repeat("s", count($params));
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    return ($return_result) ? $stmt->get_result() : $stmt;
}

and then add some helper functions for various tasks
function mysqli_delete($conn, $sql, $values)
{
    $stmt = mysqli_database_query($conn, $sql, $values, false);
    $return $stmt->affected_rows();
}
function mysqli_assoc($conn, $sql, $values)
{
    $result = mysqli_database_query($conn, $sql, $values);
    $return $result->fetch_assoc();
}
function mysqli_all($conn, $sql, $values)
{
    $result = mysqli_database_query($conn, $sql, $values);
    $return $result->fetch_all(MYSQLI_ASSOC);
}

you can use the following  function instead of that awkward $param = "id" of yours, for any column, not only id. Just select the desired column, i.e. SELECT user_id FROM table ...:
function mysqli_cell($conn, $sql, $values)
{
    $result = mysqli_database_query($conn, $sql, $values);
    $row = $return $result->fetch_row();
    return ($row) ? $row[0] : false;
}


Here's another one, just for the heck of it

$(document).keydown(function (e) {
  var current;

  // return early
  if( e.keyCode !== 38 && e.keyCode !== 40 ) {
    return false;
  }

  // again, return early
  if( $html.hasClass('client-loading') || canAnim === false ) {
    return false;
  }

  current = $('.project-current');

  if( e.keyCode === 38 ) {
    current.prev('.project').click();
  }

  if( e.keyCode === 40 ) {
    current.next('.project').click();
  }

  canAnim = false;
  setTimeout(function () { canAnim = true; }, 2000);
});


Usertool to Edit Forum Members from Desktop

prompt function

So many times you do:

puts "Please enter Username:" # Or something else instead of Username.
username = gets.chomp

In short you print and then read input, what about a function:

def prompt(message)
  puts message
  gets.chomp
end

You can reuse it and save a lot of repetition.

Functional Programming -- No mutation

Ruby leans towards the Function Programming paradigm, so you should stick to it.

One thing is avoiding mutation:

data = {username: username}
...
data[:email_address] = email
...
data[:member_status] = status

You modify data piece by piece, instead do:

...
...
data = {username: username, email_address: email, member_status: status}

It also looks more organized to me.

In fact you may write:

data = { username: prompt("The username? "),
         email_address: prompt("The email address? ")
         member_status: prompt("The member status? ") }

And make the code shorter and more readable.


Starting position

If there is a route to be found, it will go through cell 0 and will be found at first iteration of start_tour. We can remove the loop and just have starting = 0.

Generating legal moves

Various details can be improved in the legal_moves function.

This is a good occasion to use a generator with the keyword yield.

We could compute row and col with a single call to divmod.

We could make computation of new position more straight-forward with intermediates variables for coordinates on each axis.

Because of the way new_position is computed, there is no need for the additional boundary check.

We'd get something like:

def generate_new_positions(visited, position, sq):
    """Yield legal moves"""
    generate_new_positions = [
        (-2, -1),
        (-2, 1),
        (-1, -2),
        (-1, 2),
        (1, -2),
        (1, 2),
        (2, -1),
        (2, 1),
    ]
    # position = row * sq + col
    row, col = divmod(position, sq)

    for dx, dy in generate_new_positions:
        x, y = row + dx, col + dy
        if 0 <= x < sq and 0 <= y < sq:
            new_pos = x * sq + y
            if new_pos not in visited:
                yield new_pos

Separation of concerns: printing vs returning a result

When a result is found, it is printed and a boolean (or None) is returned in the different functions. It would be easier to return either None or the result found and to have that result printed from a single point of the logic.

We'd have something like:

def make_move(move_to, visited, current, route, sq):
    """Carry out the move"""
    for move in move_to:
        visited.add(current)
        new_route = route + str(current) + "-"
        solution_found = next_move(visited, move, new_route, sq)
        visited.remove(current)
        if solution_found:
            return solution_found
    return None

def next_move(visited, current, route, sq):
    """Find the next valid moves and instruct "make_move" to carry them out"""
    if len(visited) == (sq * sq) - 1:
        route += str(current)
        return route
    move_to = generate_new_positions(visited, current, sq)
    return make_move(move_to, visited, current, route, sq)

def start_tour(sq):
    """Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq"""
    starting = 0
    visited = set()
    route = ""
    return next_move(visited, starting, route, sq)

if __name__ == "__main__":
    for square_size in 3, 5, 6:
        ret = start_tour(square_size)
        print("No knights tour could be calculated" if ret is None else ret)

Also, formatting the string could be done in a single place as well. We could use lists for instance in all the logic.

def make_move(move_to, visited, current, route, sq):
    """Carry out the move"""
    for move in move_to:
        visited.add(current)
        new_route = route + [current]
        solution = next_move(visited, move, new_route, sq)
        visited.remove(current)
        if solution:
            return solution
    return None

def next_move(visited, current, route, sq):
    """Find the next valid moves and instruct "make_move" to carry them out"""
    if len(visited) == (sq * sq) - 1:
        return route + [current]
    move_to = generate_new_positions(visited, current, sq)
    return make_move(move_to, visited, current, route, sq)

def start_tour(sq):
    """Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq"""
    starting = 0
    visited = set()
    route = []
    return next_move(visited, starting, route, sq)

if __name__ == "__main__":
    for square_size in 3, 5, 6:
        ret = start_tour(square_size)
        print("No knights tour could be calculated" if ret is None else "-".join((str(e) for e in ret)))

Reducing the duplicated information

We're maintaining a visited set and a route list: both containing roughtly the same data. Maybe we could recompute visited from the route when we need it.

def make_move(move_to, current, route, sq):
    """Carry out the move"""
    for move in move_to:
        solution = next_move(move, route + [current], sq)
        if solution:
            return solution
    return None

def next_move(current, route, sq):
    """Find the next valid moves and instruct "make_move" to carry them out"""
    if len(route) == (sq * sq) - 1:
        return route + [current]
    move_to = generate_new_positions(set(route), current, sq)
    return make_move(move_to, current, route, sq)

def start_tour(sq):
    """Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq"""
    return next_move(0, [], sq)

Simplifying the logic

Having a function A calling a function B itself calling B can make things hard to understand properly because both A and B are hard to understand independently.

Here, we could get rid of make_move by integrating directly in next_move:

def next_move(current, route, sq):
    """Find the next valid moves and carry them out"""
    if len(route) == (sq * sq) - 1:
        return route + [current]
    for move in generate_new_positions(set(route), current, sq):
        solution = next_move(move, route + [current], sq)
        if solution:
            return solution
    return None

More simplification

In next_move, route is almost always used in the expression route + [current]. We could directly define this at the beginning of the function:

def next_move(current, route, sq):
    """Find the next valid moves and carry them out"""
    new_route = route + [current]
    if len(new_route) == (sq * sq):
        return new_route
    for move in generate_new_positions(set(new_route), current, sq):
        solution = next_move(move, new_route, sq)
        if solution:
            return solution
    return None

More importantly, it leads to the question: why do we provide a route AND an element to add to it instead of just having that element in the list.

def next_move(current, route, sq):
    """Find the next valid moves and carry them out"""
    if len(route) == (sq * sq):
        return route
    for move in generate_new_positions(set(route), current, sq):
        solution = next_move(move, route + [move], sq)
        if solution:
            return solution
    return None

def start_tour(sq):
    """Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq"""
    start = 0
    return next_move(start, [start], sq)

Going further, we do not really the current argument anymore as we can compute it from route.

def next_move(route, sq):
    """Find the next valid moves and carry them out"""
    if len(route) == (sq * sq):
        return route
    current = route[-1]
    new_pos = generate_new_positions(set(route), current, sq)
    for move in new_pos:
        solution = next_move(route + [move], sq)
        if solution:
            return solution
    return None

def start_tour(sq):
    """Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq"""
    start = 0
    return next_move([start], sq)

Final code

def generate_new_positions(visited, position, sq):
    """Yield legal moves"""
    generate_new_positions = [
        (-2, -1),
        (-2, 1),
        (-1, -2),
        (-1, 2),
        (1, -2),
        (1, 2),
        (2, -1),
        (2, 1),
    ]
    # position = row * sq + col
    row, col = divmod(position, sq)

    for dx, dy in generate_new_positions:
        x, y = row + dx, col + dy
        if 0 <= x < sq and 0 <= y < sq:
            new_pos = x * sq + y
            if new_pos not in visited:
                yield new_pos

def next_move(route, sq):
    """Find the next valid moves and carry them out"""
    if len(route) == (sq * sq):
        return route
    current = route[-1]
    new_pos = generate_new_positions(set(route), current, sq)
    for move in new_pos:
        solution = next_move(route + [move], sq)
        if solution:
            return solution
    return None

if __name__ == "__main__":
    for square_size in 3, 5, 6:
        ret = next_move([0], square_size)
        print("No knights tour could be calculated" if ret is None else "-".join((str(e) for e in ret)))


std::vector<std::string> ToProperCase(std::vector<std::string>& array)
{
    // ...
    return array;
}

There are many styles when it comes to capitalization. ToProperCase should have a better name to indicate what the function does, which is to capitalize the first letter of each word.

array is a non-local reference being returned by value. Is this intended?

    if (array.empty())
        return array;

    // Loop through each word
    for (std::string& value : array)

While compilers will optimize it, the early return is unnecessary. The range-based for will check to see if array is empty. If it is, the function will return array.

Don't say in comments what can be clearly stated in code. Rather than using variable names like array and value, omit the comment and use words and word respectively. Reserve comments to concisely state intent and keep them crisp.

        // Loop through each character in the word
        for (unsigned int i = 0; i < value.size(); ++i)
        {
            // Capitalise first character
            value[0] &= (~(1 << 5));

            // Convert character to lower case
            if (i > 0)
                value[i] |= (1 << 5);
        }
    }

What is the proper case of a digit? Punctuation? Control characters? Should you be mutating non-alpha characters?

You do more work than necessary here. For every character in the word, you bitwise-and the first character then bitwise-or the current character. You can unswitch the body of the innermost loop by handling the first character before every subsequent character.

    for (auto& word : words)
    {
        if (word.empty()) continue;

        word[0] = std::toupper(static_cast<unsigned char>(word[0]));

        for (auto i = 1u; i < word.size(); ++i)
        {
            word[i] = std::tolower(static_cast<unsigned char>(word[i]));
        }
    }


Error handling You await inside an async function, but without a try/catch surrounding it. So, if Article.findAndCountAll rejects, you'll get an unhandled rejection (which is deprecated in Node) and no response will be sent.
Default destructuring and variable names
const { page } = req.params; // current Page
const { size } = req.params; // items per page
const limit = size || 5;

simplifies to
const { page, size = 5 } = req.params;

and using the size variable. Though, if possible, change the param and variable name to itemsPerPage; it's much more representative of what the variable contains than size. currentPage would also be a bit more precise. Similarly, totalPage, since it contains a number, would sound better as totalPages.
Sorting bug You have:
navBarIndexArray.sort();

This will sort lexiographically, not numerically. For example, it could produce an output of
[1, 11, 2]

Compare numerically instead, eg .sort((a, b) => a - b).
Pagination Or, even better, just insert the indicies in order to begin with.
Your current results don't seem quite natural. When near the end, I'd expect the nav to be full of all nearby pages: eg, when on page 5 of 6, I'd expect 3 4 5 6, not just 4 5 6. Implementing this will require a bit of extra logic, though.
Rather than two loops which do something very similar, identify the last page to display in the nav, then subtract by navBarIndexLimit to identify the first page to display in the nav, then iterate over it. See comments in snippet below:

const navBarIndexLimit = 4;
// currentToLastPageOffset: Amount to add to current page to get last page
// (eg: current page 4 results in last page 6, first page 3)
const currentToLastPageOffset = navBarIndexLimit - 2;
const makeNavbarIndexArr = (currentPage, totalPages) => {
  const lastPage = Math.min(
    totalPages,
    currentPage <= 1
      ? navBarIndexLimit - 1 // If on 0th or 1st page, set last page to 3
      : currentPage + currentToLastPageOffset
  );
  const firstPage = Math.max(lastPage - (navBarIndexLimit- 1), 0);
  // I prefer to create numeric arrays all at once with Array.from:
  return Array.from(
    { length: lastPage - firstPage + 1 },
    (_, i) => firstPage + i
  );
  // But you could also use a for loop and push if you find it easier to read
};
console.log(makeNavbarIndexArr(0, 9));
console.log(makeNavbarIndexArr(1, 9));
console.log(makeNavbarIndexArr(5, 9));
console.log(makeNavbarIndexArr(8, 9));
console.log(makeNavbarIndexArr(9, 9));
.as-console-wrapper {
  max-height: 100% !important;
}

Note that the above takes zero-indexed parameters and returns an array that's zero-indexed, though it's trivial to tweak it to be one-indexed instead if needed.
It's a reasonable amount of code, but the logic that needs to be implemented is somewhat complicated, so there's no avoiding at least some of it. While it could be condensed somewhat (for example, by removing the currentToLastPageOffset variable), that would make it harder to understand.
I highly recommend keeping the function in the snippet above - don't inline it into your page route, so as to clearly separate the calculation logic from the main route logic.
router.get('/?:page', (req, res) => {
    const { currentPage, itemsPerPage = 5 } = req.params;
    const offset = currentPage ? (currentPage - 1) * itemsPerPage : 0; // skip previous items
    Article.findAndCountAll({
        include: User,
        raw: true,
        nest: true,
        limit: itemsPerPage,
        offset,
    })
        .then((articles) => {
            const totalPages = Math.ceil(articles.count / itemsPerPage);
            articles.index = makeNavbarIndexArr(currentPage, totalPages);
            res.render('article/article_home.hbs', { articles });
        })
        .catch((error) => {
            // Handle errors, send error response
        });
});


Comparing two Strings which could be null or blank in a Comparator

I would use boolean variables to make the code more readable:

private int compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
    /* Don't worry too much about this part. */
    String strDate0 = BeanUtils.getProperty(arg0, strProperty); _logger.debug("strDate0 = " + strDate0);
    String strDate1 = BeanUtils.getProperty(arg1, strProperty); _logger.debug("strDate1 = " + strDate1);

    boolean isStrDate0Empty = (strDate0 == null || strDate0.isEmpty());
    boolean isStrDate1Empty = (strDate1 == null || strDate1.isEmpty());

    if (isStrDate0Empty && isStrDate1Empty)
        return 0;
    // at least one of them is not empty
    if (isStrDate0Empty)
        return -1;
    if (isStrDate1Empty)
        return 1;
    //none of them is empty
    return strDate0.compareTo(strDate1);
}


Return the indexs of two numbers that total a given number

Your solutions might have to try all pairs, so you have up to quadratic runtime.
Let's use an allegedly not adequate set to keep track of the numbers we've already seen, so that for each number, we can check in constant time whether we've seen the needed partner:
def find_two_sum(numbers, target_sum):
    """
    :param numbers: (list of ints) The list of numbers.
    :param target_sum: (int) The required target sum.
    :returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum
    """
    seen = set()
    for number in numbers:
        needed = target_sum - number
        if needed in seen:
            i = numbers.index(needed)
            j = numbers.index(number, i + 1)
            return i, j
        seen.add(number)

This only takes linear time.
Other points:

Your function signature seems a bit inappropriate. The question called the target sum "n", not "target_sum". Even your whole program doesn't use "n" anywhere. I always follow the specification (maybe unless the specification is really bad). A middle ground would be to define/read the input into variable n and then name your function parameter like you did. This way, a reader of the question and your code can see the connection.
The question says list of numbers (your docstring even repeats that), not a NumPy array. My code assumes it's indeed a list (I find using list.index a lot better here.)
Your benchmark can be improved. The test case contains a million ints from 1 to 100, and your target sum is 25. You're almost guaranteed to find something quickly, despite the large size and despite your quadratic runtime. Better test a worst case, like list(range(1000)) with target 1997 (the sum of the last two numbers).

Motivated by the comments, here's a benchmark comparing this set+index solution and a dict+enumerate solution (numbers are times, so lower=faster):
Round 1:
2.10 twosum_set
1.77 twosum_set_optimized
2.11 twosum_dict

Round 2:
2.05 twosum_set
1.75 twosum_set_optimized
2.08 twosum_dict

Round 3:
2.14 twosum_set
1.83 twosum_set_optimized
2.11 twosum_dict

They look about equally fast, although the optimized set solution is clearly faster.
That was with my above-mentioned list(range(1000)). Let's use a million instead (and fewer repetitions):
Round 1:
2.64 twosum_set
2.31 twosum_set_optimized
2.84 twosum_dict

Round 2:
2.70 twosum_set
2.36 twosum_set_optimized
2.88 twosum_dict

Round 3:
2.68 twosum_set
2.38 twosum_set_optimized
2.87 twosum_dict

Here the set solution does seem faster than the dict solution, and the optimized set solution is again clearly faster.
Benchmark code:
from timeit import repeat

def twosum_set(numbers, target_sum):
    seen = set()
    for number in numbers:
        needed = target_sum - number
        if needed in seen:
            i = numbers.index(needed)
            j = numbers.index(number, i + 1)
            return i, j
        seen.add(number)

def twosum_set_optimized(numbers, target_sum):
    seen = set()
    add = seen.add           # This is the optimization
    for number in numbers:
        needed = target_sum - number
        if needed in seen:
            i = numbers.index(needed)
            j = numbers.index(number, i + 1)
            return i, j
        add(number)          # This is the optimization

def twosum_dict(numbers, target_sum):
    index = {}
    for i, number in enumerate(numbers):
        needed = target_sum - number
        if needed in index:
            return index[needed], i
        index[number] = i

numbers = list(range(10**3))
repeat_number = 10**4

numbers = list(range(10**6))
repeat_number = 10**1

target_sum = sum(numbers[-2:])

for r in range(3):
    print(f'Round {r+1}:')
    for twosum in twosum_set, twosum_set_optimized, twosum_dict:
        t = min(repeat(lambda: twosum(numbers, target_sum), number=repeat_number))
        print('%.2f' % t, twosum.__name__)
    print()


Cardinal direction enum from range input

Evaluation

For somebody learning Javascript this code isn't bad, however it does have some inefficiencies and practices that are frowned upon (e.g. Global variables). See the suggestions below for advice about improving it.

Suggestions

Semicolon terminators

Unless you are intimately familiar with the statements that need to be terminated by a semicolon it is wise to always terminate each line with a semi-colon.

Selecting elements by class vs id attribute

The first line selects an element from the DOM by the id attribute - i.e. document.querySelector('#orientation'). The next line uses a class selector to select an element: document.querySelector(".degrees"). If there is only one element with class name degrees that matters for this application then an id attribute would be more appropriate than class.

Also, it isn't wrong to use document.querySelector() to get elements by id but using document.getElementById() "is definitely faster" 1 (see this jsPerf test for comparison). Similarly document.getElementsByClassName() is also faster. I would suggest only using document.querySelector() when there is a complex selector (e.g. form lable[for="direction']

Global variables

Any variable not declared with a keyword like var, const or let is considered global. For a small application like this it likely wouldn't lead to any issues but in a larger application it could lead to unintentional side-effects if the same name is used in different functions.

Excess closures

The lines to add event listeners can be simplified:

document.querySelector("#orientation").addEventListener('input', function(event) {
  setCardinalDirection()
})

window.addEventListener("load", function(){
 setCardinalDirection()
})

Instead of wrapping the calls to setCardinalDirection() in an extra function, just pass the name of the function:

document.querySelector("#orientation").addEventListener('input', setCardinalDirection);
window.addEventListener("load", setCardinalDirection);


New

This code can actually be further reduced by using JavaScript's apply:

y = y.concat.apply(y, cats);

The above line will merge all the arrays inside the cats array into a single array and then copy it into y.

This is better than the solution you already have because:

It is faster. No more looping over two arrays.
It is easier to read. If you want, just slap a comment on this line and it is very easy to understand.

Old

it.forEach(function(it){
    y.push(it);
});

This section is over-done. All you are doing is copying the array it into y, and JavaScript already has a built in function for that: Array.prototype.concat.

You can use this function to copy one array into another.

Now, your code becomes this:

var x = cats.forEach(function(it) {
    y = y.concat(it);
});


Implementation

The P_CSV trick is good idea.
I don't know if "input" is supposed to be a file name, a string, a file object, and so on (this is Python's fault, but still). Please use a better name and document that it is a file.
What does {"id": dict(csvfile)} mean in your docstring?
get_elem could be implemented with return self.get(name, default=None). The way you're doing it is misleading, since you're relying on the fact that no return means return None.
This means you can either remove get_elem or find a better name explaining that it's just like get except that it returns None instead of throwing an exception.
I guess you want to use __str__ in Change, and maybe __repr__ (but not echo).
Do you really need Change as it is? Simply store lists in change_list, instead of Changes.
readfile? I'd say readcsv since it is no longer a file, but a P_CSV. If you have a more descriptive name of what those files contain, then use that instead.
J_Comparator doesn't work as requested in the exercise, since it also says what columns were modified.
Setting a list to None is wrong. "No values" is the empty list. You can then use self.change_list.extend(j) without needing to worry about the empty list. It's much more elegant.
Why P and J for the comparators?

Performance

Performance is good: you're using a linear algorithm, even though you're going through the files twice. If you're worried about very very larges files that won't hold in memory, you can use the assumption that the files are sorted to advance in both files simultaneously, and make sure to always have the same unique id in both files. I don't think this is needed, 6000 lines is quite small!


Is it possible to make a re-usable icon component that doesn't create duplicate TemplateRefs

Indeed, although working, this approach looks a bit heavy, because for each new SVG template the icon.component.html file will need to be changed and a respective TemplateRef field has to be created in the component.
It is not clear from the example, but if in your task all the pieces of SVG are static (not generated through the app logic), it can be solved differently. Here are some hints:

for each SVG template, create a file under the application resources: chevron.svg, tick.svg etc, with the respective contents.

in icon.component.ts, add a getter returning the path to the SVG file, for example:

public get svgResourcePath(): string {
  return `/path/to/resource/${this.icon}.svg`;
}

change the icon.component.html, so that it uses a standard HTML image tag, with the value of the src attribute bound to the path:

<img [src]="svgResourcePath"/>

Update

One point I didn't put in my question is that I also need to bind a color to the SVG through an @Input().

As I've mentioned, it was not clear from the initial question. But still there is a solution for that, although it looks a bit longer than my previous suggestion.
I've played a bit and implemented it here.
The ideas behind the approach:

Since SVG code can be included directly in a component template, we can create separate component definitions for all necessary cases, e.g. for tick:

@Component({
  selector: "tick-icon", // does not matter, because we do not intend to insert it through a template
  template: `
    <svg>
      <path
        [attr.fill]="fillColor"
        d="M23.9 3.7L9.7 17.9l-6.8-6.8-2.8 2.6 9.7 9.6L26.7 6.5z"
      />
    </svg>
  `
})
export class TickComponent implements StyleConfigurable {
  private _fillColor: string;

  @Input()
  public set fillColor(fc: string) {
    this._fillColor = fc;
  }

  public get fillColor(): string {
    return this._fillColor;
  }
}

The StyleConfigurable interface here is an interface that defines the SVG styling properties that we want to customize:
export interface StyleConfigurable {
  fillColor: string;
}

Angular components can be instantiated dynamically, so we adjust the algo from the doc for our use case:

export class IconComponent implements OnInit {
  private _icon: string;

  private _fillColor: string;

  // inject the necessary objects for the dynamic instantiation:
  public constructor(
    private _resolver: ComponentFactoryResolver,
    private _containerRef: ViewContainerRef
  ) {}

  public ngOnInit(): void {
    // trigger the SVG icons loading when this component is initialized:
    this.loadIcon();
  }

  // dynamically load the icon:
  private loadIcon(): void {
    const cmpFactory = this._resolver.resolveComponentFactory(this.getTypeForIcon());
    const cmpRef = this._containerRef.createComponent<StyleConfigurable>(
      cmpFactory
    );
    // note this call: instance.fillColor is available through StyleConfigurable
    cmpRef.instance.fillColor = this._fillColor;
  }

  // for each supported value of the 'icon' property, return the corresponding component type:
  private getTypeForIcon(): Type<StyleConfigurable> {
    switch (this._icon) {
      case "tick":
        return TickComponent;
      case "chevron":
        return ChevronComponent;
      default:
        throw Error(`Unrecognized icon: ${this._icon}`);
    }
  }
}

Now the IconComponent can be used as follows:
<app-icon icon="chevron" fillColor="rgb(0, 255, 0)"></app-icon>
<app-icon icon="tick" fillColor="rgb(255, 0, 0)"></app-icon>


Filter by a distinguishing field when making publications using meteor

I can't see how you can filter field B (school) that relies on field A (user) when there's no information about field A.

What is the purpose of showing schools to anonymous users?

If we take the scenario of displaying information to anonymous users without any related functionality (read-only stuff), then perhaps you should have another publication which only publishes 'public' properties of the school entities.


I fear that the credentials could be sniff by some attacker if they are listening to during the connection process. If https is not enabled, the password (if there is no protection) could be seen by any attacker during the HTTP requests.

This point is not directly related as to how you implemented your code, but it will go a long way as to how your code is safe.

string authId = Guid.NewGuid().ToString();

I'm not a security expert, but using GUID for security purpose is something that I would recommend. It seems to be frown upon :

  GUIDs were not designed to be a part of any security system; use of them in a security system is an "off label" use and is therefore a very bad idea. I can't see much at the moment that would break the mechanism.

You should take this advice as-is, and do some more research on it. I would not take a comment on a question as a good reference, but it would make me wonder if it's in fact a good idea.

There is a lot of documentation to help you develop a secure authentication system,but this great question on SO would cover it for most of the important things.

The authentication mechanism looks fine to me. Storing a cookie  and check the value in  the Session is a good way to assure that user is authenticated.

The only drawback is if someone hijack the session and the cookie, he don't need to login with credentials, since the token will assure him that the system see him as an authenticated user. There is not much in your code that you could do to prevent that.

What you will miss most by rolling your own mechanism is some "perk" from using the .Net implementation. From what I've previously done at school and search, you'll miss the [Authorize][3] properties where your code could look :

[Authorize]
public ActionResult Private()
{
    return View();

}

Which would hide all the cookie related code. What that could help you is, if for a specific reason you can't use cookies you won't need to change all the place where you were verifying the identity of your user. This is just for code readability and maintenance, this is not related to security.


Java class for simple statistics calculations

Don't overdo Single Responsibility Principle

You have four classes, three of which calculate the mean, median, and mode respectively.  The thing is though that their responsibility doesn't match their names.  They have responsibility over the data, which they then express as the statistics.  But if all the Mode is responsible for is the mode, then it shouldn't know about the data.  All it should know about is the Mode itself.

Consider instead making one class with multiple methods.  Then the class can have the data as a member.

Don't overuse static

        private static int mode;
        private static HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();

This means that every single instance of this class has the same mode and hm.

        private int mode;
        private Map<Integer, Integer> counts = new HashMap<>();

I also changed HashMap to Map on the left.  Usually you make types the interface rather than the implementation.  That ensures that you can change the implementation easily later if desired.

I changed hm to counts as being more descriptive.

The <> notation will only work in newer versions of Java but saves typing when available.

If you need access to fields, then you should instantiate the class and access the fields through normal methods.  E.g.

        StatisticsCalculator statCalc = new StatisticsCalculator(data);
        statCalc.calculate();
        Set<Integer> modes = getModes();

Now you can create a second object with different data without losing the first.  Or worse, merging with it.

The presumption here is that calculate would calculate all the stats and you could just access them afterwards.  If you always use them together, this is more efficient.  You could also calculate them on a just-in-time basis.

The Map is unnecessary

First, you don't need to make the Map a class field.  It would be fine as a local variable.

Second, since you sort the data to get the median anyway, you might as well use the sorted data to get the mode as well.  With sorted data, you can simply track the mode of the data that you've seen.

    private Set<Integer> calculateMode() {
        Set<Integer> modes = new HashSet<>();
        int largestCount = 0;
        int count = 0;

        int previous = sortedData[0];
        for (int datum : sortedData) {
            if (previous == datum) {
                count++
            } else {
                count = 1;
            }

            if (count > largestCount) {
                largestCount = count;
                modes.clear();
                modes.add(datum);
            } else if (count == largestCount) {
                modes.add(datum);
            }
        }

        return modes;
    }

This version returns a Set, since there is no guarantee that there will be a unique mode.

This method is private because it requires sorted data.  A public version could check if the data was sorted prior to calling the private version.

I renamed temp to previous as being more descriptive.

Because sorting clumps all the like values together, we don't need to store anything but the current and largest counts.

Saying count++ is more idiomatic than count += 1.

I don't verify that there is at least one element in the data.  You might want to throw an exception in that case.  As is, both your original version and this version would crash, as they attempt to access the first element.  It's possible that the correct place to do that validation is outside this method.

What if there's a 0 in the data?

            if (temp == 0){
                mode = ints[0];

If the correct answer is a 0 that is not in the first position, this will return the wrong answer.

Consider making a calculateSum method

If you had a calculateSum method, you could make calculateMean a one liner.  And report the sum of the data if you wanted.


smooth limit = foldlM (`repeatMul` limit) 1

Intermediate steps:

smooth limit = (`inner` 1)
    where inner [] = pure
          inner (x:xs) = flip (`repeatMul` limit) x >=> inner xs

smooth limit = (`inner` 1)
    where inner = foldr (>=>) pure . map (flip (`repeatMul` limit))

smooth limit xs = (foldr (>=>) pure $ map (flip (`repeatMul` limit)) xs) 1

smooth limit = foldl (>>=) (pure 1) . map (flip (`repeatMul` limit))

smooth limit = foldlM (flip id) 1 . map (flip (`repeatMul` limit)) -- did I mention foldlM has its argument order as stupid as repeatMul? :P

Extra answer:

There is no need for the no-duplicates bookkeeping of sets - every natural has a unique prime factorization. Anyway, here as a fold from the right, if repeatMul produced a set:

smooth limit = foldr (foldMap . repeatMul limit) (singleton 1)

Note that this also works for the list case with [1] in place of singleton 1.


Best way to preload images with callback on completion with pure JavaScript (ES6)

Firstly, kudo's to you for trying to use vanilla javascript. Great choice.

 The Question
Let us start with your question:

[Is this code] an optimal way to preload images in pure JavaScript?

Sorry, but that is very subjective so I cannot answer that. I am assuming good will, and thus will rather answer the following question I inferred from your original question:

Am I making good use of common best practices?

Now that is a question I can answer, and the simple answer is no. Sorry :)
Ofcourse, I will not leave you an answer without explanation.

 Consistency and Deliberateness
Firstly, the biggest improvement one can make in their life as a programmer would be consistency. Do not listen to the people who argue about single vs double quotes, or tabs vs spaces. As a software engineer myself, I can wholeheartedly say that all that matters is when you make a choice, you stick to it (at least within the project -- you are allowed to change your mind). Most people do not mind style (it often is enforced to a company standard anyway), but whenever you use any function or syntax, a reader would assume you did so deliberately. Why did you choose both var function and x => y?
I have to admit that javascript tricked us by allowing three ways of creating functions, but that does not mean you should use them all together. Let us look at the ways and their reasons:
function name (args) { /*block*/ }
This is the function declaration statement. This just means that you declare a variable called name and assign the function to it. This was made primarily to support an imperative sequence of steps. It is my personal opinion that it should have been named procedure, because that is what it is.
var name = function (args) { /* block */ }
This is actually what happens when you declare a function, so there is no difference between this and the first type of function -- except for the more letters so I see no reason to use this notation. The only difference that could be made is through the storage modifier (i.e. var in this case), which I will tell you about a bit later.
var name = args => { /*block*/ }
This is javascript's lambda syntax. It allows for a very interesting way to write programs, but only if you stop appending blocks to it:
var add = (x, y) => {
  return x + y;
};
// is actually the same as
var add = (x, y) => x + y;

The arrow function (x => y) is a function that exists of only an expression, with an implied return. But if you use a block, you just turned it into a procedure again which negates the usefulness of the lambda/arrow notation. It can save you a lot of keystrokes, and, if I can add my opinion, looks much more clean.
Taking this into consideration, your code could look like this:
function preload_imgs (src_list, callback) {
    let loaded = 0;
    src_list.forEach(function(src) {
        img = new Image();
        img.onload = function() {
            if (++loaded == src_list.length && callback) {
                callback();
            }
        };
        img.onerror = function(err) {
            console.log(err);
        };
        img.src = src;
    });
};

 Storage and Mutability
Remember the storage modifiers I just talked about? Javascript also has three ways of declaring variables. What a nightmare, right? Well, there is some use to the differences -- have a look:
var x = ...
In the beginning there was only var. It is short for variable, and thus should just declare a variable, right? Nope, javascript is weird. I could go on about why it is the weirdest feature ever, but here is the link about var if you are interested. The main takeaway is that this notation does a lot of stuff behind the scenes, making it a common source of bugs. My opinion: don't use it.
let x = ...
Everyone who has ever used var probably meant to use let. It does not do any fancy stuff, it creates a variable and assigns a value, except that it is block scoped. This variable is only ever accessible within the confines of the closest block, i.e. anything within { curly brackets }. You use only let, so I assume you know of this advantage but I wanted to clarify it nonetheless.
const x = ...
Again, a very autological name: const creates a constant. A constant can only be declared once, and never overwritten. This might sound like a useless trait, but it is actually really important. One of the most famous bugs in the world was caused by mutability (no. 4 on the list, probably more) and cost a whopping $60 million. I am not saying that using const will always save you millions of dollars, but it disallows any overwriting of the value, meaning:

you cannot accidentally overwrite your or anyone else's functions and variables.
you can guarantee that its value will never change, so you can refer to it anywhere safely -- even in a for within a for within a for.
AT&T would have lost $60m less.

Coming back to deliberateness: you declare functions using let, implying you are going to change them, but you are not. I suggest using const to more clearly signal your intentions:
const preload_imgs = function (src_list, callback) {
    let loaded = 0;
    src_list.forEach(function(src) {
        const img = new Image();
        img.onload = function() {
            if (++loaded == src_list.length && callback) {
                callback();
            }
        };
        img.onerror = function(err) {
            console.log(err);
        };
        img.src = src;
    });
};

 I promise to help
Talking about common best practises, there is one thing many javascript developers will run into. That thing is the internet. A great many developers have already walked this path before you, so you bet the industry has some handy stuff up its sleeves to help you become a better programmer.
Javascript has a fool-proof way of handling asynchronous tasks, such as preloading an image. For exactly this reason, promises were implemented. A Promise is a wrapper around an asynchronous task, so we can work with it synchronously. Without going into a lot of detail, let me summarise the most important parts of a Promise:

A promise allows for attaching "callbacks" for when the wrapped task completes

const response = new Promise(request);
response.then(doStuff);

A promise allows for attaching "callbacks" for when the wrapped task fails

const response = new Promise(request);
response.catch(handleError);

Can you see a similarity? Creating an Image and attaching onload/onerror callbacks sounds a lot like creating a Promise! Applying this knowledge to your example gives us the following code:
// Your "preload" function goes as follows
(src) => {
    img = new Image();
    img.onload = () => {
        if (++loaded == src_list.length && callback) {
            callback();
        }
    };
    img.onerror = (err) => {
        console.log(err);
    };
    img.src = src;
}
// Let's update it
const preload = src => new Promise(function(resolve, reject) {
  const img = new Image();
  img.onload = function() {
    // onload is called with an event, not the image so we
    // want to specifically resolve with img.
    resolve(img);
  }
  img.onerror = reject;
  // onerror is called with the error, so we can directly assign "reject" to it.
  img.src = src;
});

You might notice the lack of "free variables" (foreign variables that do not contribute to the function itself). We do not use loaded or src_list because those alter state / are mutable and are a perfect souce for the $60m bug (actually, this is probably the exact type of function that caused the race condition in their software).
We have solved the preload function in a very clean way:
const preload = src => new Promise(function(resolve, reject) {
  const img = new Image();
  img.onload = function() {
    resolve(img);
  }
  img.onerror = reject;
  img.src = src;
});

preload("https://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-12/256/thumbs-up.png");
  .then(img => console.log("Preloaded", img))
  .catch(err => console.error("Failed", err));

BAM! You now have a function that preloads an image, and allows for individual succes and error handling. All we have to do now, is to apply this function to a list of srcs.

➰ Going in loops
You might have thought there were too many ways to declare functions or variables, but wait till you hear in how many ways you can loop over things in javascript!
There is for (let i = 0...), for ... in, for ... of, while, do ... while, and we have not even touched on higher order array traversal functions. I am just going to say it: you never really need a for loop. You can solve any array problem with array functions.

Side note: the Array.forEach function you used is a weird function. It is just a slower version of a for loop with different notation, and I just said you never need a for loop. Either use for (const src of src_list) or use map or filter, but never forEach (this is a guideline, if it prohibits you from being productive then go ahead and do it).

For example, there is the Array.map function. This function takes a transformer, which goes over every element of the array, and transforms that element yielding a new array. That might sound weird so here is an example:
const numbers = [1, 2, 3];
const double = x => x * 2;
const doubledNumbers = numbers.map(double);
// doubledNumbers: [2, 4, 6]

Hmm, taking an array of values and applying a function to every value sounds a lot like what you are trying to do:
// Your old code
src_list.forEach((src) => {
  img = new Image();
  img.onload = () => {
    if (++loaded == src_list.length && callback) {
      callback();
    }
  };
  img.onerror = (err) => {
    console.log(err);
  };
  img.src = src;
});

// Using our "preload" function from before
const requests = src_list.map(preload);
// requests: [Promise<Image>, Promise<Image>, Promise<Image>, ...]

Whoaaaa, one line! But we have not fully refactored yet, because we now have a list of promises that can just resolve at any time and in no particular order. You seem to have understood this problem, but you solved it in a very unsafe way.
let loaded = 0;
//...
img.onload = () => {
    if (++loaded == src_list.length && callback) { /* ... */ }
    //...
}

You keep track of the amount of loaded images in the callback function that triggers when any image is loaded. Pretty clever, but I would bet my house that keeping track of such things in this way will cause bugs. If you google "wait for all promises javascript", you learn of a built in function that takes care of all of this for you! Promise.all takes a list of promises, and returns a promise, that rejects when any promise in that list rejects, or resolves when all promises in the list have resolved. That is exactly what you are trying to achieve:
//using the "requests" list we created a couple examples back
const done = Promise.all(requests);
done
  .then(images => console.log("Preloaded all", images))
  .catch(err => console.error("Failed", err));
// > Preloaded all [Image, Image, Image, ...]

⌛ Conclusion
Hopefully you now have a better understanding of javascript, and the lovely built-in functions that make these things almost as easy as jquery, if not more. Maybe you even learned a lot of things along the way, maybe you were sighing and moaning because you knew most of this stuff -- as long as you learned anything I consider it a success.
To summarise:

Use any kind of function notation but be consistent and deliberate.
Use const for constants and let for variables (I never even use let at all).
Use Promises to wrap asynchronous tasks to allow for really useful manipulation functions and callbacks.
Familiarise yourself with higher-order functions so you never have to use loops again.

And voila, the refactored code:
const preload = src => new Promise(function(resolve, reject) {
  const img = new Image();
  img.onload = function() {
    resolve(img);
  }
  img.onerror = reject;
  img.src = src;
});

const preloadAll = sources =>
  Promise.all(
    sources.map(
      preload));

const sources = [
  'https://i.picsum.photos/id/1000/5626/3635.jpg',
  'https://i.picsum.photos/id/10/2500/1667.jpg',
  'https://homepages.cae.wisc.edu/~ece533/images/cat.png',
  'https://homepages.cae.wisc.edu/~ece533/images/airplane.png'];

preloadAll(sources)
  .then(images => console.log('Preloaded all', images))
  .catch(err => console.error('Failed', err));

Preload to your hearts desire.


A few quick comments:

In __bool__(), rather than using an if statement, just do return bool(self.life). It has the same effect, but it's much cleaner.
Likewise, in __lt__(), you can just do return (self.priority > obj.priority).

Note that the convention in those comparison scenarios is to call the other object other, not obj, so I would recommend renaming the variable.
There are no docstrings or comments, which is going to make life very difficult for anybody reading the code later. You should explain what the code is supposed to be doing, and why – right now it’s just guesswork.


Compose n functions where the innermost function expects multiple arguments

First, there's something weird happening here

const f = uncurry(compn2([sqr, inc, sub]));
console.log(f(5, 2)); // yields 16

I would assume that this composition is doing this

sqr (inc (sub (5) (2)))
// sqr (inc (2 - 5))
// sqr (inc (-3))
// sqr (-2)
// => 4

But upon closer inspect, it's because your uncurry function is unconventionally flipping the arguments

const uncurry = f => (y, x) => f(x) (y);

Nevermind that tho, we don't have to agree on it. I'll show you a way to solve your problem without even depending on it.

I'm going to introduce a function papply which procedurally applies a curried function

const papply = f => ([x,...xs]) =>
  x === undefined ? f : papply (f(x)) (xs)

console.log(papply (x => y => y - x) ([2,5])) // 3
// (x => y => y - x) (2) (5)
// (y => y - 2) (5)
// 5 - 2
// => 3

I'm also going to introduce a dramatically simplified compn – there's nothing wrong with yours, but it will help reduce some of the complexity of the example I provide.

const compn = ([f,...fs]) => x =>
  f === undefined ? x : f(compn (fs) (x))

const inc = x => x + 1

const f = compn ([inc, inc, inc])

console.log(f(3))
// compn ([inc, inc, inc]) (3)
// inc (compn ([inc,inc]) (3))
// inc (inc (compn ([inc]) (3)))
// inc (inc (inc (compn ([]) (3))))
// inc (inc (inc (3)))
// inc (inc (4))
// inc (5)
// => 6

OK, let's get to it then !

const sqr = x => x * x

const inc = x => x + 1

const sub = y => x => x - y

const compn = ([f,...fs]) => x =>
  f === undefined ? x : f(compn (fs) (x))

const papply = f => ([x,...xs]) =>
  x === undefined ? f : papply (f(x)) (xs)

const f = compn([sqr, inc, papply(sub)])

console.log(f([2, 5]));
// sqr (inc (papply (sub) ([2,5]))
// sqr (inc (papply (sub (2)) ([5])))
// sqr (inc (papply (x => x - 2) ([5])))
// sqr (inc (papply (5 - 2) ([])))
// sqr (inc (papply (3) ([])))
// sqr (inc (3))
// sqr (4)
// => 16

Of course it requires that the function is applied a bit differently ...

// this
f([2,5])

// instead of
f(5,2)

I don't think that change will bother you much tho, especially considering every other function of yours (including compn) is manually curried. This stays true to calling all functions with one arg. If multiple values are required, a tuple is provided – or in this case, an Array, as Tuple is absent in JS.

It's an interesting question and I think you had an interesting approach. The complexity ultimately steered me to thinking about a different solution. Just my 2 cents, hope it helped some ^_^


Overall:

Are you sure that you want to keep a static number of connections? Why not keep a minimum set of connections and create new ones when needed?
ConnectionPool shouldn't have static fields as signalpillar said.
You don't check if the connections have timed out after a period of wait
Loggers are nice -> you don't necessary have to remove all useful debug output when going to production
You might want to have some sort of a timeout for the blocking queue depending on the application. Then you would poll rather than take from the queue.

Static initializer:

Is it sensible to catch exceptions per makeConnection - There's probably something wrong if any of them fail.
You don't check if there really are 10 connections in the pool after initialization.
What tt34 said.

Method getConnection:

return is not a method, parenthesis are not needed
do you really want to throw an InterruptedException from your ConnectionPool?

Method releaseConnection:

The same as getConnection

Method makeConnection:

this could be perhaps renamed as connect or openConnection
It would be better that the connection parameters are given as parameters rather hard-coding - you'll probably just testing at the moment but still
You should not just ignore the ClassNotFoundException in Class.forName(...): The program will fail again on the next instruction. Rethrow the exception or wrap it as a run-time exception if you do not want to show the ClassNotFoundException in the method signature
Rather than concatenating multiple strings, consider using String.format


Number of interesting numbers between two given numbers

In that kind of problems, there is a solution a bit more interesting than a straight forward implementation of the logic described.

In your case, you could write a programme to generate the first numbers with the property you are looking for. You'll probably see a pattern that you could reuse (square numbers).

Update as this answer seems to be ignored so far.

Style

It's a good habit to move variable declaration as close as possible to where they are used.

Also, your code probably deserves a bit more spacing (this is how you avoid questions like this one) while a few things can be written in a slightly more concise way.

At this stage, my code looks like :

#include<stdio.h>

int main()
{
    long long int testcase;
    scanf("%lld",&testcase);

    while (testcase--)
    {
        long long int max = 0;
        long long int l, r;
        scanf("%lld %lld",&l,&r);

        for (int i = l ; i <= r; i++)
        {
            long long int count = 0;
            for (int j = 1; j <= i; j++)
            {
                if (i%j == 0)
                {
                    count++;
                }
            }

            if (count % 2)
            {
                max++;
            }
        }
        printf("%lld\n",max);
    }
}

Naming

max is a pretty poor name as it does not convey the right meaning. nb is probably better.

Types

Assuming 1≤L≤R≤10^18 (and not 1018), you will need a long type for i. However you don't need it for testcase.

Code organisation and tests

At the moment, all your code is in the main which makes things hard to test (and thus, to optimise). Let's decompose the code in small functions we'll be able to test and optimise.

At this stage, the code looks like :

#include<stdio.h>
#include<assert.h>

long long int nb_divisors(long long int i)
{
    long long int count = 0;
    for (int j = 1; j <= i; j++)
        if (i%j == 0)
            count++;
    return count;
}

int is_interesting(long long int i)
{
    return nb_divisors(i) % 2;
}

long long int nb_interesting(long long int l, long long int r)
{
    long long int nb = 0;
    for (long long int i = l ; i <= r; i++)
        if (is_interesting(i))
            nb++;
    return nb;
}

int main()
{
    if (0)
    {
        // stdio tests
        long long int testcase;
        scanf("%lld",&testcase);

        while (testcase--)
        {
            long long int l, r;
            scanf("%lld %lld",&l,&r);
            printf("%lld\n", nb_interesting(l, r));
        }
    }
    else
    {
        // automatic tests
        assert(nb_interesting(1, 3) == 1);
        assert(nb_interesting(6, 10) == 1);
    }
}

Algorithm

Here starts the interesting part. Your current algorithm considers all numbers from l to r and when checking if i is interesting or not, iterates all the way from 0 to i. For huge values of r, you'll have many calls to is_interesting and each of these calls will be slow.

A faster nb_divisors (from 0(n) to 0(sqrt(n)))

Let's try to see if we can make nb_divisors faster.

While trying to find divisors of i, you iterate from 1 to i. When you find a divisor d, you can consider d2 = n/d as another divisor. Then you have 3 situations :
 - either d < d2
 - or d2 < d
 - or d == d2.
You can limit yourself to divisors smaller than sqrt(n) and count them twice, then check if we have divisors alone.

my_int nb_divisors2(my_int i)
{
    my_int count = 0;
    my_int j;
    for (j = 1; j*j < i; j++)
        if (i%j == 0)
            count+=2;
    if (j*j == i)
        count++;
    return count;
}

Testing with :

    for (my_int i = 0; i < 1000; i++)
        assert(nb_divisors(i) == nb_divisors2(i));

This seems promising.

nb_divisors went from 0(n) to 0(sqrt(n)). This is particularly brilliant for big values of n.

A faster is_interesting (from 0(sqrt(n)) to 0(1))

Although making nb_divisors faster already makes is_interesting faster, we can make it even faster by re-using the insight we used : most divisors will be counted twice and a divisor will be counted once if and only if the number is a perfect square.

Reusing previous code, we can simply write :

int is_interesting2(my_int i)
{
    my_int j;
    for (j = 1; j*j < i; j++);
    return (j*j == i);
}

but it is still O(sqrt(n)). Using sqrt from math.h, you can write a 0(1) solution (solution taking a constant time):

int is_interesting2(my_int i)
{
    my_int root = sqrt(i);
    return (root && root*root == i);
}

A faster nb_interesting (from super-slow to O(1))

Altough making is_interesting faster already makes nb_interesting much faster, we can re-use what we've found to make it even faster.

First idea is just to count the number of perfect square between l and r. This is easy to write :

my_int nb_interesting2(my_int l, my_int r)
{
    my_int j;
    my_int nb = 0;
    for (j = 1; j*j < l; j++);
    for (     ; j*j <= r; j++)
            nb++;
    return nb;
}

(As usually, it comes along with unit tests to ensure we didn't break anything too badly).

This solution is O(sqrt(r)) as we go through all numbers up to sqrt(r).

We can go faster : let's assume we can compute the number of interesting up to a given number included nb_interesting_from_0(int i), then, we have nb_interesting_between(l, r) = nb_interesting_from_0(r) - nb_interesting_from_0(l - 1).

This fact only becomes interesting when we have a way to compute : nb_interesting_from_0(int i) and we have one, it is simply sqrt(i).

my_int nb_interesting2(my_int l, my_int r)
{
    return sqrt(r) - (my_int)sqrt(l-1);
}

This is 0(1) and pretty simple. Funny thing is that if you were to give me a simple calculator, I'd be able to provide you the number of interesting numbers between two limits very easily.


Bash script for referencing git status output files

Nice try

That's a fantastic idea.
It's very annoying to run git status and then very often type some next command and copy paste selected files from the output.
I long wanted to have something like this but never made time to actually do it.
You gave me the final push, so thanks.

Setting variables dynamically

I don't think your script actually works :-)
At least on my computer, in Bash 3 or 4,
it's not possible to create variables dynamically with set,
for example:

m1=
c=1
set m$c=x
echo $m1

This outputs nothing, because set m$c=x does not actually perform m1=x.

After some research, I found that this works with declare:

m1=
c=1
declare m$c=x
echo $m1

This outputs x alright. Unfortunately, according to help declare:

[...] When
used in a function, makes NAMEs local, as with the `local' command.

That is, the variables created dynamically this way inside the function will not be visible outside, so this is not usable for this purpose.

One obvious option is eval, but not a good one, because eval is evil.
A well-crafted filename in the working tree could wreak havoc.
Even if this is unlikely, I would rather not resort to such option.

Finally, there's a trick with printf -v that will work well:

m1=
c=1
printf -v m$c x
echo $m1

This outputs x, and even when used in a function, m1 will be visible outside.
The only downside is that printf is not POSIX compliant,
but that's probably not a big problem in practice.

Unnecessary repeated processing of git status -s

This is really quite wasteful:

m=$(echo "$gitsall" | grep "^ M")
d=$(echo "$gitsall" | grep "^ D")
u=$(echo "$gitsall" | grep "^??")
a=$(echo "$gitsall" | grep "^A ")
s=$(echo "$gitsall" | grep "^M ")

It would be better to run git status -s just once,
loop over the output,
use a case statement to decide the type of the change,
and set the m, d, u, a, s variables accordingly.

When you go this way, you can also directly create the variables with a count, so that you don't need all those repetitive while loops for each status type.

Arithmetic context

When within $((...)), you don't need to write $ to access the values of variables, for example instead of:

count=$(($count+1))

You can write:

count=$((count+1))

An even shorter equivalent:

((count++))

Current working directory

Instead of $(pwd) it's better to use the $PWD variable.

Local variables

Instead of using the unset command at the end of the function to clear the variables used, it's much better to use local variables, for example:

local m d u a s

Not only this will make sure you don't clear the variables,
it also makes your use correct.
The current use is not correct,
because if some of these variables had value before calling the function,
the values get reset.
When using local, the original values of those variables remain intact in the calling environment.

Alternative implementation

Putting the above together,
the function could be written simpler as:

gits() {
    git status
    mc=1 dc=1 uc=1 ac=1 sc=1
    local line status path name
    while read -r line; do
        [ "$line" ] || continue
        status=${line:0:2}
        path=${line:3}
        case "$status" in
            " M") name=m$((mc++)) ;;
            " D") name=d$((dc++)) ;;
            "??") name=u$((uc++)) ;;
            "A ") name=a$((ac++)) ;;
            "M ") name=s$((sc++)) ;;
            *) echo unsupported status on line: $line
        esac
        printf -v $name "$path"
    done <<< "$(git status -s)"
}


Serving a growing audio file with Django

For large constants consider writing them as an expression and
possibly comment on the size, just in case, to make it easier to
understand.
I'm not particularly fond of waiting for the file to grow, but I guess
if it works it's fine.
Serving static files is implemented in Django, including HTTP range
parsing.  However
the one method
I found only works in debug mode.  Still, I'd try to reuse
django.utils.http.parse_http_range and
django.http.response.PartialHttpResponse if possible, so that not
all of the data is read into memory at once.

Otherwise looks okay I'd say.


Mixing English and Spanish in code is always awkward.  I don't recommend it.  If you must do it, though, try to be consistent, and avoid mixing in English identifiers like var cities.

The localidades array, in which the first string of each member array is special and represents a state, is weird.  An associative array, with the state names as keys, would be better.

In modern practice, the HTML should be free of all JavaScript, and the event hooks are added from the JavaScript.  addEventListener(), which allows the code to add multiple handlers, is preferable to window.onload = …, which only allows one handler.

The "Estado" and "Ciudad" placeholder options should be disabled to prevent them from being selected or submitted.

Below, I've defined a function, selectorDeEstadoYCiudad, which acts as a controller for the two drop-downs.

var localidades = {
  "Baja California": ["Tijuana","Rosarito","Ensenada","Tecate","Mexicali","San Felipe"],
  "Sonora": ["San Luis Río Colorado","Sonoita","Sásabe","Nogales","Naco","Agua Prieta"],
  "Chihuahua": ["El Berrendo","Puerto Palomas","San Jerónimo","Ciudad Juárez","El Porvenir","Ojinaga"],
  "Coahuila": ["Ciudad Acuña","Piedras Negras"],
  "Nuevo León": ["Colombia"],
  "Tamaulipas": ["Nuevo Laredo","Reynosa","Río Bravo","Nuevo Progreso","Matamoros"],
};

function selectorDeEstadoYCiudad(localidades, forma) {
  forma.state.addEventListener('change', function (e) {
    var cajon = forma.city;
    var ciudades = localidades[e.target.value];
    for (var i = 0; i < ciudades.length; i++){
      cajon[i+1] = new Option(ciudades[i], ciudades[i]);
    }
    cajon.length = ciudades.length + 1;
    cajon.value = cajon[0].value;
  });

  var cajon = forma.state;
  for (var estado in localidades) {
    cajon.appendChild(new Option(estado, estado));
  }
}

window.addEventListener('DOMContentLoaded', function() {
  selectorDeEstadoYCiudad(localidades, document.getElementById('forma1'));
});
<form id="forma1" action="">
  <select name="state">
    <option disabled>Estado</option>
  </select>
  <select name="city">
    <option disabled>Ciudad</option>
  </select>
</form>


Find two unique integers in sorted array

For each number in the list, either

there is no next (at end of src list) - add to result list
the next is different - add to the result list, increment result count (if all answers found, return)
the next is the same; skip next, (add 2 to src pointer)

public int[] findUnique(int[] src){
    int[] res =  new int[2];
    int resIdx = 0;

    for(int i = 0; i < src.length;){
        // at the end of the list, or next is different
        if(i == src.length-1 || src[i] != src[i+1]){
            res[resIdx++] = src[i++];
            if (resIdx== 2) break;
        } else{
            // not different; skip next item
            i+=2;
        }
    }
    return res;
}


window.onload = function () {

Mixing DOM-0 event handlers and addEventListener is inconsistent, pick one and stick with it.

window.addEventListener("load", function () {

function bgnAddChllng() {

Don't disemvowel your variables. This isn't Wheel of Fortune, vowels don't cost anything.

function beginAdditionChallenge() {

var addChllng = document.getElementById("addChllng");

Use proper indentation. JSFiddle has a handy TidyUp button to do it for you. Consider a more descriptive ID for the button.

var button = document.getElementById("challengeButton");

addChllng.addEventListener('click', bgnAddChllng, false);

Switching between single and double quotes is inconsistent, pick one and stick with it. useCapture defaults to false, there's no need to explicitly pass it.

button.addEventListener("click", beginAdditionChallenge);

  nesting the actual useful code in an anonymous function seems bloated/hacky to me.

It's a pretty common practice, but if you don't like it, give the function a name and don't nest it, just as you did with the button click event handler.

function beginAdditionChallenge() {
    alert("This is a test alert.");
}

function initChallenge() {
    var button = document.getElementById("challengeButton");
    button.addEventListener("click", beginAdditionChallenge);
}

window.addEventListener("load", initChallenge);


All of the change handlers are basically the same.  You could roll them all into one by using smarter jQuery selectors.

Also, the time object is pointless.  You can just use four separate variables.  I've also moved the dateDbToView() calls to declutter the tr.find(…) lines so that the parallelism is more obvious.

$('.data-inicio, .hora-inicio, .data-final, .hora-final').on('change', 'input', function() {
    var tr = $(this).parent().parent();
    var dStart = tr.find('.data-inicio > input').val();
    var hStart = tr.find('.hora-inicio > input').val();
    var dFinish = tr.find('.data-final > input').val();
    var hFinish = tr.find('.hora-final > input').val();

    tr.find('.duracao > input').val(duration(
        dateDbToView(dStart),  hStart,
        dateDbToView(dFinish), hFinish
    ));
});

I suggest renaming getDuration(…) to duration(…), because it is performing a calculation, rather than retrieving information that already exists.  (For the same reason, we say Math.sin(…) rather than Math.getSin(…)).


I only have some nitpicks about formatting and readability.
Hopefully somebody else will comment specifically about good approaches for treating vertical alignment.

It would be more readable (and the common convention) to put a space after colons.
So instead of:

background-color:rgba(0, 0, 0, 0.1);
text-decoration:underline;

Write as:

background-color: rgba(0, 0, 0, 0.1);
text-decoration: underline;

And don't put two definitions on the same line like this:

vertical-align:middle;  text-decoration:none;

It's better when code reads from top to bottom,
and your eyes can stay focusing on the left,
rather than dipping deeper into the right part, like this:

vertical-align: middle;
text-decoration: none;


Sorting strings by length - functional Python

data = ["something", "something else", "blah", "a string"]
result = [(x, len(x)) for x in sorted(data, key = len)]

Basically, its more straightforward to sort first then decorate. Although, I'm not sure why you would need the length of the list in your tuple. If you don't really need it sorting by length can be much shorter.

EDIT:

If all I wanted was to output the data, I'd do it like this:

for string in sorted(data, key = len):
    print string, len(string)

If you really wanted to eliminate the two references to len you could do:

mykey = len
for string in sorted(data, key = mykey):
    print string, mykey(string)

But unless you are reusing the code with different mykey's that doesn't seem worthwhile.


Power of 2
Instead of using:
(int)Math.pow(2, numbers.size())

You can compute a power of two more efficiently like this:
1 << numbers.size()

You can use 1L to compute it as a long if you think that the power may exceed 31.
Manual bit manipulation
Instead of using a BitSet to find the 1 bits in your int, you can use integer arithmetic to check the bits yourself:
    for (int bit = 0; bit < 32; bit++) {
        if ((i & (1 << bit)) != 0) {
            subset.add(ary[bit]);
        }
    }


Your mergesort has a serious issue. If you run

size=100000
x=rand(1:(2^62),size)
@time(mergesort!(x))

you will find that your algorithm is allocating ram 2.34 million times, and is allocating 37.4 GB The problem comes from this block:

while length(left) != 0 && length(right) != 0
  if left[1] <= right[1]
    result[k] = left[1]
    left      = left[2:end]
  else
    result[k] = right[1]
    right = right[2:end]
  end
  k += 1
end

If you instead write,

left_ind = 1
right_ind = 1
r_ind = 1
while left_ind<=length(left) && right_ind<=length(right)
    if left[left_ind]<right[right_ind]
        result[r_ind]=left[left_ind]
        left_ind += 1
    else
        result[r_ind]=right[right_ind]
        right_ind += 1
    end
    r_ind += 1
end
if left_ind<=length(left)
    result[r_ind:end] = left[left_ind:end]
elseif right_ind<=length(right)
    result[r_ind:end] = right[right_ind:end]
end
result

This drops the time from 3.7 seconds to .2 seconds, and memory allocation to 57MB


Memoization for calculating minimal traversal distance within a positive matrix

Some documentation is sorely needed, both about the problem itself, and the approach taken to solve it.
Making y global is not a good idea. If you want to solve more than one matrix, the caller of this function would be responsible for resetting y between calls. Instead you could pass y around as an argument, perhaps initializing it like this:

def findLeastPath(matrix, y=None, row=0, column=0, path=[], sum_=0):
    if y is None:
        y = numpy.zeros_like(matrix)

I see that the possible moves are only right, down and diagonally down-right. The problem could be solved in a simple way by looping once through the array row by row. One can always easily compute the minimum cost of reaching the current node, because it is only possible to arrive from nodes whose cost has already been computed.
Dijkstra's algorithm is another option if costs are non-negative. Basically, always extend the shortest path by one step. Pro: may not have to visit all the nodes. Con: needs to maintain a priority queue.


You get the job done in 30 minutes and the use of a stack is the way to go, so that's a good start. In my opinion you're writing a little too much (repetitive) code and it could be a lot easier to read if you use a switch-statement instead:

public bool IsValidReview(string s)
{
  Stack<char> endings = new Stack<char>();

  foreach (var curr in s)
  {
    switch (curr)
    {
      case '(':
        endings.Push(')');
        break;
      case '[':
        endings.Push(']');
        break;
      case '{':
        endings.Push('}');
        break;
      case ')':
      case ']':
      case '}':
        if (endings.Count == 0 || endings.Pop() != curr)
          return false;
        break;

    }
  }

  return endings.Count == 0;
}

Here the corresponding ending parenthesis is pushed to the stack instead of the starting one, which makes it easier to check when the ending shows up.

The name myStack doesn't say much, so I have changed it to something more meaningful in the context.


Checking the sum of pairs to match a target value

As a style note, this is a bit of an abuse:

def csop(*params):

The point of *params is to allow things to be passed that cannot be known when the code is written. This is not the case here.  There are only two parameters, and you know what they are.  So you should give them names.

This:

exit()

is also bad form.  Exiting the program from the middle of a function is great way to make bugs that are really hard to find.  In this case simply return

this:

else:
    pass

is completely dead code.  pass is used to mark a block that is empty.  It is a by product of everything in Python being indent sensitive.  But the else is optional so just leave it and the pass off.

And performance wise, you perform the sum() twice.  If it matters to you, this result could be saved instead of evaluating it twice.


Optimising Probabilistic Weighted Moving Average (PEWMA) df.iterrows loop in Pandas

I think you can use just raw numpy arrays for speeding it up:

after #the PEWMA Model you can just use following code:

_x = df[value_col]
_mean, _std, _var = np.zeros(_x.shape), np.zeros(_x.shape), np.zeros(_x.shape)

for i in range(1, len(_x)):
    diff = _x[i] - _mean[i-1]

    p = norm.pdf(diff / _std[i-1]) if _std[i-1] != 0 else 0 # Prob of observing diff
    a_t = a * (1 - beta * p) if (i-1) > T else 1 - 1/i # weight to give to this point
    incr = (1 - a_t) * diff

    # Update Mean, Var, Std
    v = a_t * (_var[i-1] + diff * incr)
    _mean[i] = _mean[i-1] + incr
    _var[i] = v
    _std[i] = np.sqrt(v)

pewm = pd.DataFrame({'Mean': _mean, 'Var': _var, 'Std': _std}, index=df.index)

If you need to apply it to really big data you could make it even faster by using numba package:

from numba import njit

# numba has some issues with stats's norm.pdf so redefine it here as function
@njit
def norm_pdf(x):
    return np.exp(-x**2/2)/np.sqrt(2*np.pi)

@njit
def pwma(_x, a, beta, T):
    _mean, _std, _var = np.zeros(_x.shape), np.zeros(_x.shape), np.zeros(_x.shape)
    _mean[0] = _x[0]

    for i in range(1, len(_x)):
        diff = _x[i] - _mean[i-1]

        p = norm_pdf(diff / _std[i-1]) if _std[i-1] != 0 else 0 # Prob of observing diff
        a_t = a * (1 - beta * p) if (i-1) > T else 1 - 1/(i) # weight to give to this point
        incr = (1 - a_t) * diff

        # Update Mean, Var, Std
        v = a_t * (_var[i-1] + diff * incr)
        _mean[i] = _mean[i-1] + incr
        _var[i] = v
        _std[i] = np.sqrt(v)
    return _mean, _var, _std

# Using :
_mean, _var, _std = pwma(df[value_col].values, 0.99, 0.5, 30)
pewm = pd.DataFrame({'Mean': _mean, 'Var': _var, 'Std': _std}, index=df.index)


isFull fires when assembleBoards returns an empty list; we'd expect to be able to ask that question only once. newBoards and validBoards do not deserve names - if you want the reader to be able to tell what the value means, comments are more appropriate.

Most of the rest of backtrack is about descending into a nested data structure and changing a small part, which lens specializes in: traverse . traverse . filtered (==E) descends into the board, then each of its elements, then each of their E cells. holesOf gives you, roughly speaking, the positions of the targets in the original board - it separates the board into a Cell and a Cell -> Board for each target. peek lets you forget there was an E.

import Control.Comonad.Representable.Store (peek)
import Control.Lens (holesOf, filtered)

backtrack :: Board -> [Board]
backtrack b = case setFirstE b of
  -- board has no more empty cells
  Nothing -> [b]
  -- we only need to place X and O in the first occurence of E, because one of them MUST be correct
  Just setter -> nub $ concatMap backtrack $ filter isValid $ map setter [X,O]

-- Punches the first E out of the board, if any.
setFirstE :: Board -> Maybe (Cell -> Board)
setFirstE = listToMaybe . map (flip peek) . holesOf (traverse . traverse . filtered (==E))


String substitutions in ruby and coding style

There are other ways you could write this but I'm not sure if you'd find any of them cleaner. One option is plain old sprintf. For example:

# assemble file name
fname = sprintf("%s/%s-%i-%s-%ix%i.png", directory, prefix, timestamp,
          commit, size[:width], size[:height])

You could shorten it a little by giving size its own to_s method:

class << size; def to_s; "#{self[:width]}x#{self[:height]}" end end

fname = sprintf("%s/%s-%i-%s-%s.png", directory, prefix, timestamp,
          commit, size)

...and perhaps create other convenience methods along the same lines. But still, very small gains.

Another option would be to make your own super-small template engine, something like this:

def tiny_subst template, bndg
  param_exp   = /:(\w+)[^\w:]+/i
  tmpl_params = template.scan(param_exp).flatten

  proc {
    out_str = template.clone

    tmpl_params.reduce(out_str) do |str, p|
      str.gsub ":#{p}", eval(p, bndg).to_s unless p.empty?
    end
  }
end

tmpl   = ':directory/:prefix-:timestamp-:commit-:size.png'
subber = tiny_subst(tmpl, binding)

directory = 'screenies'
prefix    = 'screenshot'
timestamp = Time.now.to_i
commit    = '0b5c7967887481deb17bcd9039cd3fe0ac4540d4'
size      = '640x960'

subber.yield # => screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-640x960.png

commit  = 'foobarbazquux'
size    = '9000x9000'

subber.yield # => screenies/screenshot-1316535022-foobarbazquux-9000x9000.png

So, that's kinda nice, but is it really worth it? Not for me, but I guess if you really hate "#{this}" it might be.


Thanks for sharing your code.

This is what I think about it

General Coding

program against interfaces

Most of your variables are defines as concrete types (classes you actually instantiate).
You should better declare them as interface types so that it is possible to exchange
the concrete implementation without changing the code all over.

example

static Map<String, ArrayList<String>> dictionaryMap = new HashMap<String, ArrayList<String>>();

should better be

static Map<String, List<String>> dictionaryMap = new HashMap<String, ArrayList<String>>();

or even

static Map<String, Collection<String>> dictionaryMap = new HashMap<String, ArrayList<String>>();

Problem here is that you need to know what interfaces are available and what the
consequences are using them. The public API
is the place to find that information.

Be consistent

Choose the same approach for the same problem

E.g. you use two different types of loops

    for (int i = 0; i < sortString.length(); i++) {
        char c = sortString.charAt(i);
    //...
    // vs.
    for (String word : words) {
        addToMap(createMap(word), word);
    //...

Unless you really need the index variable for something else then accessing the actual
object in the collection loops over you could (and should) stick to the foreach
form

    for (char c : sortString.toCharArray()) {

Learn about the capabilities of the objects provided by the runtime

Especially the class Map has some interesting methods your code could benefit from:
The code

    ArrayList<String> anagramList = dictionaryMap.get(key);
    if (anagramList == null) {
        anagramList = new ArrayList<String>();
        anagramList.add(word);
        dictionaryMap.put(key, anagramList);
    }

could be replaced by

    ArrayList<String> anagramList = dictionaryMap.computeIfAbsent(key,()->new ArrayList<String>());

If you would know that beside (Array-)List which allows duplicates, the Java
Runtime provides another collection type Set which does not hold duplicates, then
you could even get rid of the other if in this method too:

static Map<String, Collection<String>> dictionaryMap = new HashMap<String, Collection<String>>();

private void addToMap(String key, String word) {
    dictionaryMap.computeIfAbsent(key,()-> new HashSet<String>())
                 .add(word);
 }

Avoid arrays

instead of arrays better use Collection types like any implementations of the List
and  Set interfaces. They are more flexible and prevent you to copy data (yourself)
when its size needs to be changed.

use the static key word with intention

You declared the variable dictionaryMap as a class variable although it is not
accessed by any  static method. Unless you understand the consequences you should not use the static key word.

narrow your interfaces

Your method init() has a return value which is not needed since there is no caller
of this method dealing with this return value. Methods with return value usually
are harder to refactor. Especially its harder to split them into smaller methods.

Naming

Finding good names is the hardest part in programming, so always take your time to
think about the names of your identifiers

Please read (and follow) the Java Naming Conventions.

This does not only apply to the casing of the identifiers.
It also applies to how names are "constructed".
E.g.: you named a method getAnagrams().
By conventions the prefix get is reserved for methods, that do not do any processing
but simply return a property of the object.
But your method does a lot more than that.
Therefore a better name could be findAnagramsOf(String word).

avoid single character names

Since the number of characters is quite limited in most languages you will soon run
out of names. This means that you either have to choose another character which is
not so obviously connected to the purpose of the variable. And/or you have to "reuse"
variable names in different contexts. Both makes your code hard to read and understand
for other persons. (Keep in mind that you are that other person yourself if you look
at your code in a few month!)

On the other hand in Java the length of identifier names is virtually unlimited.
There is no penalty in any way for long identifier names. So don't be stingy with
letters when choosing names.

Choose your names from the problem domain

Some of your identifiers (or at least parts of them) have technical meaning.
But your identifiers should convey you business solution.

example: characterCountMap,  c, sortString or arr.

Remember that the technical details may change while the meaning of your identifiers
in respect to the business problem will remain.
so this identifiers might better be:

characterCounts, currentCharacter, sortedCharacters or wordCharacters.


This is called Run-length-encoding and there are many implementations of this on the Internet, for example: http://rosettacode.org/wiki/Run-length_encoding#Python

I have written a solution myself just now but posting it would not really help (it would be like adding another drop in the ocean) so I will comment your code thoroughly instead:

optimization?

This was probably added as an optimization:

    if compressed_string_size >= len(data):
        break

But except for inputs with no consecutive runs whatsoever, the compressed size will exceed the real size only near the end of the compression. Does the overhead of the additional conditional check each loop iteration take less time than the iterations saved? If it does, does it save enough time to justify adding complexity? I suggest you first worry about writing a working program and then apply optimizations with profiling (execution timing).

Additional variable not needed

compressed_string_size = 0

This was probably added as an optimization too, but is it worth it? No, because len runs in O(1) time complexity that is, len does not need to scan the whole list, because lists remember their length, so calling len is almost instantaneous, in fact using that variable is likely a pessimization as log is a very expensive mathematical operation.


A program to find out the number of odd and even Fibonacci numbers between given range

I'm going to assume you tested it for several inputs and got the right values. Your logic seems right so if a couple test cases work, it probably works. But I didn't look carefully for any off-by-one like errors.

There is one logic issue that I see:

You don't set n and  m if N = M. Double check your two if statements in the beginning of the loop; you only check for strict inequality on both sides. One of them should change to a >= or <=, or better yet just use if-else instead of two ifs.

As for optimization...

In terms of an average computer, your program is good enough for any N and M because you specify N,M < 1018. Even if you don't, for-loops by themselves are pretty cheap.

However, there are still optimizations/cleanups.

The biggest one is your last for loop:

for (j=0; j<val; j++)
{
    even++;
    odd+=2;
}

This can just be:

even+=val;
odd+=2*val

Your two if chains can turn into if, else if, else instead of three ifs (same thing for your first if pair, which should just be if else)

if (...) { }
else if (...) { }
else (...) { }

although the compiler will most likely optimize that for you.

I think that's the best you can do for your current algorithm.

However, it seems odd to me that you are checking for all mod cases for n and m; I think your idea is that you know the pattern for the large chunks in between N and M but you want to trim off the edge cases. Now, you won't need to trim down the case when n%3==1 or m%3==0, because you can just treat that as the even++, odd+=2 chunk.

n=m case

In programming you can always cop out :)

Here is how I would address the n=m case even though it's not too beautiful:

if (N == M)
{
  printf("Odd: 0, Even: 0"); //format this to match your output
  break;  // break ends the current for loop iteration in this context
}
else if (N > M)
{
  n = M; m = N;
}
else
{
  n = N; m = M;
}


PHP database class - Managing two connections with different privileges

You want two classes. They extends Database. PublicDatabase and PrivateDatabase, you instantiate whichever you need, and inject whichever you need. That way you can even have the same signature in the constructor in both types.

If you don't have a preference, you just need a database connection in a function, just ask for Database, and either will fit.

Also

You don't need to use gettype, you can hint in the function's signature for the type, it works for all Objects and array. So for example:

public function __construct(array $accessLevel, array $credentials) {

Don't give defaults if you can't handle defaults. Your object won't work if $credentials is empty, don't let it be.
What do your Database object solve? What kind of abstraction it provides? Usually such 'utility' classes are pointless.

Better approach

Your User shouldn't be responsible to save/fetch itself. In fact, if you have a User which doesn't care where it came from, you have a perfectly reusable object, a User that can come from a database, a file, a session, a form, whatever, and work the same.

You should have two objects: the User and the UserMapper, the UserMapper is responsible for fetching information about users and fill them into User objects, as well as saving information from the User object back into the database.

The idea of OOP is separation of responsibilities.