Minimalist accordion implementation using vanilla JavaScript

Yes, you should use classList. Right now you overwrite the entire className attribute of the elements. It works, but it also means that you can never use any other class name on the elements. So it's just not a very precise or robust way of doing things; it only works as long as you don't add other classes. And if you do need to add another class to the elements at some point, your script will mess up because the comparison with "" will always fail, and then any and all class names will get summarily removed by your script.

Of course, classList isn't supported everywhere, so you may have to use a shim/polyfill. The nextElementSibling property isn't supported everywhere either, by the way (which, incidentally is why jQuery exists; because browser compatibility is not simple).

I also wonder why you use querySelector in one line, but elementsByClassName in the next line. In both cases you want to find element(s) with a given class name. Of course, in the first case, you want exactly 1 element, and in the other you want a collection. However, if you want 1 particular element, you should probably add an id attribute to that element - not a class - and then use the good old document.getElementById. In other words: Using a class selector and expecting it to only exist on one element is backwards. Classes are meant to be used on an arbitrary number of elements. If you want unique identification, use an id instead.

Also, please don't mix languages in your code. I know it's only two variable names, but especially because it's only two variable names there's no reason to switch language. The DOM API is in English, and even all your CSS classes are in English, so it's simpler and cleaner to just stick to that (by the way, I'm not a native English speaker myself, I just prefer code to be consistent.)

Lastly, I always recommend that you use brace-on-same-line style in JavaScript. There are some assumptions about style in JS interpreters, and brace-on-same-line is one.


Find the closest enemy in a 2D grid with wrapping allowed

Here

enemy_locations = np.where(grid == 2)
enemy_locations = ((x, y) for y, x in zip(
    enemy_locations[0], enemy_locations[1]))

the x/y-coordinates are swapped, and later the x-coordinate of each enemy is subtracted from the y-coordinate of the friend, and vice versa:

moves = [sum((abs(friendly_coords[1] - enemy[0]),
                abs(friendly_coords[0] - enemy[1])))
            for enemy in enemy_locations]

I find that confusing. If you don't swap the coordinates then the computation of the locations becomes simpler

enemy_locations = zip(*np.where(grid == 2))

and the distance computation becomes more logical:

moves = [sum((abs(friendly_coords[0] - enemy[0]),
                abs(friendly_coords[1] - enemy[1])))
            for enemy in enemy_locations]

Making moves a generator instead of a list would be sufficient.

Here

friendly_coords = tuple(int(i) for i in np.where(grid == 1))
assert len(friendly_coords) == 2, "Only one friendly is allowed"

you check if exactly one friend is given. But that check does not work: If there is zero or more than two 1 elements in the array then the int(i) conversion already fails with a

TypeError: only size-1 arrays can be converted to Python scalars

The error message is not appropriate if there is no friend.

Also assertions are for finding programming errors. A grid with zero or more than 2 friends is a wrong parameter and a reason to raise a ValueError:

  Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

My suggestion for that part would be

friendly_locations = list(zip(*np.where(grid == 1)))
if len(friendly_locations) != 1:
    raise ValueError("There must be exactly one friend")
friendly_coord = friendly_locations[0]

In order to compute the “wrapped distances” you augment the array by additional rows and columns. The dimensions of the array increase from \$ (m, n) \$ to at most \$ (2m-1, 2n-1) \$, i.e. the number of elements is almost quadrupled if the friend is located at one of the corners.

This can be completely avoided if the computation of the distance takes the wrapping into account:

def wrapped_distance(p1: Tuple[int, int], p2: Tuple[int, int], shape: Tuple[int, int]):
    """Return the wrapped distance between two points.

    The Manhattan distance from p1 to p2 in a grid of the given shape
    is computed, taking wrapping around the edges of the grid into account.
    """
    deltax = abs(p1[0] - p2[0])
    deltay = abs(p1[1] - p2[1])
    return min(deltax, shape[0] - deltax) + min(deltay, shape[1] - deltay)

And if the array is not modified then there is no need anymore to re-compute the friends's location. Also the pre-scan for the existence of enemies

if 2 not in grid:
    return 0

can now be replaced by calling min() with a default argument.

The main function then becomes:

def calc_closest_enemy(matrix: List[str]) -> int:
    """Calculate the minimum number of moves to reach an enemy.

    (... rest of your docstring omitted ...)
    """
    grid = np.array([list(s) for s in matrix], dtype=np.int32)

    friendly_locations = list(zip(*np.where(grid == 1)))
    if len(friendly_locations) != 1:
        raise ValueError("There must be exactly one friend")
    friendly_coord = friendly_locations[0]

    enemy_locations = zip(*np.where(grid == 2))
    distances = (wrapped_distance(friendly_coord, enemy, grid.shape)
                for enemy in enemy_locations)
    return min(distances, default = 0)


Prime less than N that is a sum of the most consecutive other primes

Multiples of 2 cannot be prime and primes greater than 2 are odd. This means that the sum to be found must be the sum of an odd number of primes if 2 is not in the window. This lets you skip half the work.

You can update a sliding sum by subtracting the outgoing number and adding the incoming one. Perhaps this could be the basis of a window that moves forward as it expands and contracts, much like a caterpillar moves... The idea is to avoid redoing lots of sums without having to store lots of intermediary results. The basic sliding sum should already save quite a bit of work, though.

This can give you a quick exploratory run with sequences (sums) of maximum possible length, if you expand two sums from 2 and 5 respectively - skipping every other prime - and start sliding once the sums exceed the maximum prime. The disadvantage is that you do not gain information for bounding future searches, as in the bottom-up case where you never have to consider sequences shorter than the longest you've found so far. Perhaps it is better to caterpillar right from the start, to quickly collect growing lower bounds on sequence length.

Growing pair of snakes: slide two sums forward, offset by one prime, that are one double step longer than the longest sequence found so far. Expand as you find longer and longer sequences. That should give you some decent results in one stereo slither through the range, which can help bound future searches. (hindsight: one snake, single steps; it's only the growing that can be double-stepped)

UPDATE

I did a bit of snake charming and it didn't pan out - snakes grow very slowly and they have to move around a lot in order to do so. By and large there is little that can be done in the way of improving/refining bounds for the search, apart from using the length of the best sequence found so far (plus two) as a lower bound for future searches.

A lot of re-computation can be avoided by computing cumulative sums for the primes and storing them in a table; that way the sum from prime i to prime k is available as p_sums[k] - p_sums[i - 1] for i greater than zero.

Also, searches go faster if all possible sequence lengths are tried for a given starting point before moving to the next starting point, rather than fixing the sequence length for a given round and then trying all starting points. However, I haven't studied this point thoroughly; the success of this strategy may depend on the fact that a lot of winning sequences happen to begin at very low primes for the small range I tested (232).

'Brute force with superior firepower' is several orders of magnitude faster than the plain brute-force algorithm:

*** g++ 4.8.1 64 ***

v0:          10       0.000 ms          5 = {2} @ 2
v1:          10       0.000 ms          5 = {2} @ 2
v0:         100       0.001 ms         41 = {6} @ 2
v1:         100       0.000 ms         41 = {6} @ 2
v0:        1000       0.010 ms        953 = {21} @ 7
v1:        1000       0.001 ms        953 = {21} @ 7
v0:       10000       0.122 ms       9521 = {65} @ 3
v1:       10000       0.002 ms       9521 = {65} @ 3
v0:      100000       1.505 ms      92951 = {183} @ 3
v1:      100000       0.013 ms      92951 = {183} @ 3
v0:     1000000      19.793 ms     997651 = {543} @ 7
v1:     1000000       0.104 ms     997651 = {543} @ 7
v0:    10000000     254.493 ms    9951191 = {1587} @ 5
v1:    10000000       0.782 ms    9951191 = {1587} @ 5
v0:   100000000    4485.791 ms   99819619 = {4685} @ 7
v1:   100000000       6.226 ms   99819619 = {4685} @ 7
v0:  1000000000   68065.223 ms  999715711 = {13935} @ 11
v1:  1000000000      52.905 ms  999715711 = {13935} @ 11
v0: 10000000000 1359343.949 ms 9999419621 = {41708} @ 2
v1: 10000000000     485.861 ms 9999419621 = {41708} @ 2

The last round used more than 7 GB of core for the two tables, which means this is pretty much the end of the line for this simple algorithm even though the actual search took only half a second. The time for sieving the primes - about one second per 2^31 numbers for my simple code - is not included.

I'm showing the routine as C++ since my Python-fu is not sufficient for doing either python or the algorithm justice. At least that way you have an accurate description for the algorithm, and can ponder about devious ways of having Python do all the hard work:

typedef uint32_t num_t;
typedef uint64_t sum_t;

std::vector<num_t> primes;
std::vector<sum_t> p_sums;    // sum(primes[0] .. primes[i]) for i < primes.size()

void prepare_prime_tables_for_limit (num_t n);
bool is_prime (num_t n);      // uses std::lower_bound() on primes[], i.e. binary search

num_t brute_force_v1 (unsigned n = 1000000000)
{
   assert( n >= 10 );

   prepare_prime_tables_for_limit(n);

   num_t prime_count = num_t(primes.size());
   num_t max_prime = primes.back();
   num_t best_len = 1;
   num_t best_idx = 0;
   sum_t best_sum = 0;

   // separate pass for the prime that is so odd because it's even

   for (num_t i = 1; ; i += 2)
   {
      sum_t sum = p_sums[i];

      if (sum <= max_prime)
      {
         if (is_prime(num_t(sum)))
         {
            best_len = i + 1;
            best_sum = sum;
         }
      }
      else break;
   }

   --best_len;  // adjust for the evenness of 2

   for (num_t i = 1; i + best_len + 1 < prime_count; ++i)
   {
      for (num_t k = i + best_len + 1; ; k += 2)
      {
         sum_t sum = p_sums[k] - p_sums[i - 1];

         if (sum <= max_prime)
         {
            if (is_prime(num_t(sum)))
            {
               best_len = k - i + 1;
               best_idx = i;
               best_sum = sum;
            }
         }
         else break;
      }
   }

   best_len += best_idx == 0;  // restore the stolen bit if 2 is still best

   // ... print stuff ...

   return num_t(best_sum);
}

I left index math etc. unoptimised in order to make the code easier to understand. For the same reasons I didn't harden it by adding the complications needed for handling boundary cases (n < 8 etc.). My intent was to make the basic algorithm as clear as possible.

Sums need a bigger type than indexes and numbers, hence the occasional cast to num_t when it is safe (and necessary) to do so.


Don't care about that. Unless you can prove that it creates a bottleneck, just stick with whatever seems the most readable and maintainable option.
 prefer the latter.

I'd also rename the methods. onEarth is too generic. What exactly on onEarth? Weeks? Months? Years? If it's years, call it getYearsOnEarth or something like this.


The only problem with this approach is that as you add more methods, you are going to end up with an awful lot of repeated if (Request::ajax()) ... blocks all over your code.

Here's what I do for my sites:

<?php
class ApiController extends Controller {
    protected function makeResponse($data, $isError = false, $redirectToIfNotAjax = '/') {
        if (Request::ajax()) {
            if ($isError) {
                return $this->jsonFailure(array(
                    'errors' => $data
                ));
            } else {
                return $this->jsonSuccess($data);
            }
        } else {
            if ($isError) {
                return Redirect::route($redirectToIfNotAjax)
                    ->withInput()
                    ->withErrors($data);
            } else {
                Redirect::route($redirectToIfNotAjax);
            }
        }
    }
}

(This is not exactly the same as what I am using, but it's pretty close.)

Then, inherit your controllers from ApiController instead of just Controller.

Here is what your example would look like:

public function store()
{
    $input = Input::all();

    if(!$this->settings->fill($input)->isValid())
    {
        return makeResponse($this->settings->errors, true, 'admin.settings.create')
    }

    $this->settings->save();

    return makeResponse('success', false, 'admin.settings.index')
}

Much cleaner!


These comments apply to your question, not your answer.

Using strings as arguments seem unnecessary, it would be better to use bools or enums, that way if you one day change strings (e.g. another language) it does not affect the print function.

void Triangle::Print(Direction direction, bool fill)

There are magic numbers in your code 2,3 etc. try using constants for those
values with descriptive names.

The function is arguably a bit long and has quite a few if-statement levels, better to split into several functions that you can parameterize.

You may also want to present public functions to the user that do not have all the arguments then leave the original Print protected e.g.

PrintVertical(bool fill)
PrintInverted(bool fill);
...

that may make its use less confusing than keeping track of all possible argument combinations.

You may also want to include the stream to print to as an argument to Print, that way if you can alternatively print to a file instead of cout.


Extracting lower and upper limit of a range of values based on a multiplier

Function Arguments
def get_lower_upper_limits(inps):
    ranges, multipliers = inps
    ...

This is a curious choice for declaring arguments to the function.  You must package two arguments together as a tuple for the inps argument, without any clear indication to the caller of the requirement.
Why not declare the function as:
def get_lower_upper_limits(ranges, multipliers):
    ...

The caller then has a clue that the function takes two arguments, a ranges and a multipliers.
A """docstring""" could go a long way towards helping the caller understand the requirements for calling the function.  Type-hints would go even further.  I recommend researching both subjects.
Wrapper
With the above change to the function arguments, your wrapped function will need a new definition:
wrapped = wrapper(get_lower_upper_limits, (ranges, multiplier))

This presently provides 1 argument (the tuple created with (ranges, multiplier)) to be passed to the function being wrapped.  With the above change, the function now needs the ranges and multiplier passed as individual arguments:
wrapped = wrapper(get_lower_upper_limits, ranges, multiplier)

Wrapper-free packaging
The wrapper function is not needed.
First, the partial function from functools will perform the wrapping for you (and provides additional capabilities, which are not needed here).  Remove the wrapper function, and replace it with an import:
from functools import partial

wrapped = partial(get_lower_upper_limits, ranges, multiplier)

This may be faster than your hand-written wrapper function, as built-ins can be implemented directly in C.
Again, as this is not using the full capabilities of partial, a simpler alternative exists:
wrapped = lambda: get_lower_upper_limits(ranges, multiplier)

Don't index
In Python, indexing is relatively slow.  If you do not need idx, except for use in variable[idx], it is best to loop over variable directly.
Since in this case, you need to loop over two lists ranges and multipliers simultaneously, you'll need to zip them together first (zip as in zipper, not as in compression).
    for values, multiplier in zip(ranges, multipliers):
        min_l += multiplier * (min(values) if multiplier > 0 else max(values))
        ...

Improved code
import timeit

def get_lower_upper_limits(ranges, multipliers):
    min_l = 0
    max_l = 0
    for values, multiplier in zip(ranges, multipliers):
        min_l += multiplier * (min(values) if multiplier > 0 else max(values))
        max_l += multiplier * (max(values) if multiplier > 0 else min(values))
    return min_l, max_l

ranges = [[1000, 1400, 1800], [2200, 2400, 2600], [3000, 3100, 3200]]
multiplier = [-1, 2, 3]
assert len(ranges) == len(multiplier)
func = lambda: get_lower_upper_limits(ranges, multiplier)

print('get_lower_upper_limits: {}'.format(timeit.timeit(func, number=500000)))

Approximately 5% faster


You have the right idea, but you didn't quite know how to get there.  You don't need that traverse function to operate on the left or right lists.  Just bind them to separate variables through a simple let in expression and you can add the items to each of the lists.

let rec unzip = function
    | (x, y)::t -> let l, r = unzip t in (x::l, y::r)
    | []        -> ([], [])


Calculator for magic item creation in RPG

I see a few problems with this, most notably, you have a plethora of magic numbers.

let baseDC casterLevel =
    5 + casterLevel

let rush dc =
    dc + 5

let ignoreRequirements requirements dc =
    dc + (5 * requirements)

let getBuildPrice basePrice =
    basePrice * 0.5

let getTime basePrice =
    floor (8.0 * basePrice / 1000.0)

let getMinBonusForNoCursed dc =
    dc - 6

let buildDaysWhileAdventuring isRushed buildTime =
    let adventuringBuildTime = buildTime / 4.0
    floor (if isRushed then adventuringBuildTime else adventuringBuildTime * 2.0)

In order, I see:

5 + casterLevel: what is 5?
dc + 5: what is 5? Is it the same as #1?
5 * requirements: what is 5? Is it the same as #1 or #2?
basePrice * 0.5: what is 0.5? Is it 1 / 2 or something different?
8.0 * basePrice: what is 8.0?
#5 / 1000.0: what is 1000.0?
dc - 6: what is 6?
buildTime / 4.0: what is 4.0?
adventuringBuildTime * 2.0: what is 2.0, is it 4.0 / 2, is it the 4.0 from #8 / 2?

For a functional program, it's not too bad. I don't like how many times you use if (I always prefer match), but when dealing with boolean types it does quite fine.


Filter one array based on values of another, is this the best way?

Normally there are a lot of categories, so I'd go through the voucher.categories array:

const filterCategories = (voucher, categories) => (
  Array.isArray(voucher.categories) ?
    voucher.categories
      .map(categoryId => {
        const categoryFound = categories.find(c => c.id === categoryId);
        return categoryFound ? categoryFound.name : null;
      })
      .filter(categoryName => categoryName !== null)
      .sort()
      .join() :
    ""
);

This way you don't have to go through the entire list of 'master' categories (which in practice may be very long) doing a search on the voucher categories in each iteration.

Note: it would be much faster if you could have the categories as an object with the id as index:

categories = {
  ["761601bc-4daf-4db2-a0cf-fe7f443fcb94"]: {name: "Shoes"},
  ["601ebcfe-fcbd-4075-a4b4-a42e356c5747"]: {name: "Hats"},
  ["238933cf-77a5-4443-b290-7d7c836f80ff"]: {name: "Eyewear"}
};

const filterCategories = (voucher, categories) => (
      Array.isArray(voucher.categories) ?
        voucher.categories
          .map(categoryId => {
            const categoryFound = categories[categoryId];
            return categoryFound ? categoryFound.name : null;
          })
          .filter(categoryName => categoryName !== null)
          .sort()
          .join() :
        ""
    );


At least for the PHP part:
You should make it into a function where you return status instead of going over every possibility even if you have a fail.
function validate_post() {
   if ( ... )
      return "no";
   if ( ... )
      return "yes";
}

$array['reponse'] = validate_post();

By this you would eliminate the last // Si tout est ok part as well, as by the response would be OK.

If you truly want to eliminate possible steps, you could also negate the isset() checks and use OR instead of AND, as it then will stop on first false.
if (!isset($_POST['Email']) || !isset($_POST['Password']) ... )
   return "Une erreur s'est produite.";

The length check for password require less resources and as such could be moved above the email check. (Which would be the most expensive.)

For the Javascript part
it becomes a question on what and if you need to optimize.
It is likely a process rarely taken. Manual action by user (hopefully) not in a loop ;). When it get submitted you are to have a rather big form for it to have a noticeable effect.
That said jQuery gives you a overhead, but you might/likely do not want to use pure Javascript.

Edit:
Had another look at this, and also had to check if I was missing something regards to your variables in the Javascript. But, unless you have some omitted code within the "submit" function – you have some unused variables:
var Email = $('#Email').val();
var Password = $('#Password').val();
var PasswordRepeat = $('#PasswordRepeat').val();

As you use:
data : $(this).serialize(),

Which in effect serializes all form fields with a name attribute, and not something like:
data : $.param({
          Email : Email,
          Password : Email,
          PasswordRepeat : PasswordRepeat
       }),

By which you could also use:
data : $.param({
    Email : $('#Email').val(),
    Password : $('#Password').val(),
    PasswordRepeat : $('#PasswordRepeat').val()
}),

It depends on use. If for some reason your form has lot of fields that you do not want to post the latter would be to prefer, though that would also bind it much tighter together and make it a possible spot for bugs in future changes to the code.

As a side-note you also should most likely have this:
$('#form').on('submit', function(event) {
    event.preventDefault();  // Prevent form submit.
    ...


Javascript Object of Arrays manipulation

May i suggest a shorter code?

var data = {
  dataGroup: {
    count: [4, 4, 2, 1],
      dataOne: [1, 3, 2, 1],
      dataTwo: [7, -1, 9, 0],
      dataThree: [3, 8, 1, 2]
  }
}

var processedData = Object.keys(data.dataGroup).filter(key => key != 'count').reduce((acc, key) => {
  acc.groupName[key] = [];
  data.dataGroup.count.forEach((amount, index) => {
    for (let i = 0; i < amount; i++) {
      acc.groupName[key].push(data.dataGroup[key][index]);
    }
  });
  return acc;
}, { groupName: {}});
console.log(processedData);


Simplify get

You can simplify the get method like this:

public TreeNode get(int element) {
    TreeNode runner = root;
    while (runner != null) {
        if (runner.data > element) {
            runner = runner.leftNode;
        } else if (runner.data < element) {
            runner = runner.rightNode;
        } else {
            return runner;
        }
    }
    return null;
}

(Thanks @david-harkness for pointing out the extra shortcut!)

Breadth-first search

It's called breadth-first, not "breath-first".

Also, this initialization is pointless, as you overwrite the value of runner immediately in the loop:

Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
TreeNode runner = root;
while (!queue.isEmpty()) {
    runner = (TreeNode) queue.remove();

And, the cast is also pointless, because the Queue is correctly declared with TreeNode type.

Depth-first search

The depthFirstSearch method will set all node.visited = true, so you won't be able to call it twice. Actually it's really bad to have side effects like this. It would be better if TreeNode didn't have the visited field at all. It's polluting the class with data only used by one specific purpose, the depth-first search. It doesn't belong there. You could track what was visited using a Set, used only in depthFirstSearch.

TreeNode

I would rename leftNode to left and rightNode to right. It's simpler and everybody understands what they are.

Since you never need to change data, it can be final.

The current implementation is limited to int values. It would be better if the BST could store anything comparable.

Change the class declaration to this:

public class BST<T extends Comparable<T>> {

Likewise for TreeNode
Replace all comparison operations like x.data < value with x.compareTo(value) < 0, likewise for >

Unit testing

Your basic test could easily become more useful (and less basic) if you do a get not only for one random element, but for all elements you inserted, since you have the array of values ready anyway:

@Test
public void basicTest() {
    BST tree = new BST();
    int[] data = {9, 5, 3, 1, 4, 8, 15, 11, 21, 20, 29};
    for (int i : data) {
        tree.insert(i);
    }
    for (int i : data) {
        assertEquals(i, tree.get(i).data);
    }
}

A single test case named basicTest is not going to make this class "properly tested". At the very least you could add a few more test cases that are obviously necessary when talking about a binary search tree.

For example, what happens if you try to get non-existent elements?

@Test
public void testNoSuchElement() {
    BST tree = new BST();
    assertNull(tree.get(3));
    assertNull(tree.get(31));
}

The BST should not allow duplicate values:

@Test
public void testNoDuplicateVaues() {
    BST tree = new BST();
    int val = 3;
    tree.insert(val);
    tree.insert(val);
    tree.insert(val);
    assertEquals(1, tree.size());
}

Of course this requires a .size method, so implement one, and a test case with it too:

public int size() {
    int count = 0;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    TreeNode runner;
    while (!queue.isEmpty()) {
        runner = queue.remove();
        if (runner != null) {
            ++count;
            queue.add(runner.leftNode);
            queue.add(runner.rightNode);
        }
    }
    return count;
}

@Test
public void testSize() {
    assertEquals(0, new BST().size());
    BST tree = new BST();
    int[] data = {9, 5, 3, 1, 4, 8, 15, 11, 21, 20, 29};
    for (int i : data) {
        tree.insert(i);
    }
    assertEquals(data.length, tree.size());
}

Formatting

The formatting is messy:

the indentation is broken in breathFirstSearch and in basicTest
you should put a space before and after parentheses, for example:

while(!stack.empty()){ should be formatted as while (!stack.empty()) {
if(root == null){ should be formatted as if (root == null) {

Basically, use your IDE to format code correctly. It also makes it easier to review. (For yourself too!)


Extract data from a DBMS, create a CSV dump and transfer it to an FTP server

Class members

Don't use class members if local variables are enough. For example here:

def execute_sql(self, file):
    self.f = open(file)
    self.sql_statement = self.f.read()
    self.cursor.execute(self.sql_statement)

The variables f and sql_statement are used only in this function, so they should be local variables (drop the .self).

As a general rule, it's good to limit the scope of variables, to minimize the chance of accidental modification somewhere else. This is good encapsulation and information hiding.

Review the other functions too, similarly.

Use context managers whenever possible

The function in the previous example should be rewritten using a context manager:

def execute_sql(self, file):
    with open(file) as fh:
        self.cursor.execute(fh.read())

Encapsulation

Looking at this sequence of statements:

ext = Extractor(plist[0], plist[1])
ext.execute_sql(ext.sql_file)
ext.extract_from_db()
ext.cursor.close()
ext.connection.close()
ext.transfer_file()

This code knows too much about the implementation of Extractor: it knows that the class has a cursor member and a connection member. It also knows that these members need to be closed after using, and in a specific order. That's really too intimate knowledge about the implementation. It's also hard to remember these steps, every time you might use this class.

The purpose of encapsulation and information hiding is to free users from knowing too much details. The problem with "knowing" is that it means that if you change the implementation later, all callers must change too. I suggest to reorganize the code, so that the usage looks more like this:

ext = Extractor(plist[0], plist[1])
ext.execute_sql_from_file()
ext.extract_from_db_to_file()
ext.transfer_file()

Inside the implementation of these functions, feel free to do whatever is necessary, such as opening database connection, running query, closing cursor and connection. Users don't need to know these details. This way, you will be able to change the implantation details later, and users of the class don't have to notice anything.


Simple CodeReview Questions Notifications for OSX

Nitpicks

Maximum line length should be 72 characters for docstrings.
For your old variable, you may wan to use a set instead of a list to check for existence (not in) as it will be \$O(1)\$ instead of \$O(n)\$.

Reusability

As it stand, I can't use this script because it is too much tied to your OSX only notifier. I'd rather yield questions from get_notifications (which will not be greatly named after that) and format them elsewhere, letting other users handle it with other notifications systems (or even email, for that matter).

Something like:

import stackexchange
import time

def pync_notify(question):
    from pync import Notifier
    Notifier.notify('Votes: {0} | Answers: {1} | Views: {2}'.format(
        question.score, len(question.answers), question.view_count),
        title='CodeReview: {0}'.format(question.title),
        subtitle='Tags: {0}'.format(', '.join(question.tags)),
        sound='default', open=question.url)

def gtk_notify(question):
    from gi.repository import Notify
    Notify.init('stackexchange')
    notification = Notify.Notification.new(
        'CodeReview: {}'.format(question.title),
        'Votes: {} | Answers: {} | Views: {}'.format(
            question.score, len(question.answers), question.view_count),
        'dialog-information')
    notification.show()

def get_questions():
    """Fetch recent questions from CodeReview

    This function uses the SE API and yield each
    new question that is asked on CR.
    """

    cr = stackexchange.Site(stackexchange.CodeReview)

    old = {}
    while True:
        questions = cr.recent_questions(filter='_b')
        for question in questions[:1]:
            if question.title not in old:
                old.add(question.title)
                yield question

        time.sleep(2)

if __name__ == '__main__':
    for question in get_questions():
         pync_notify(question)

Should be enough. Note that I import modules each time a new question appears, which is not ideal, but at least it let you easily deal with modules that are not present on the system. And the few extra time spent realizing the module is already loaded is negligible compared to your time.sleep(2) anyway. You may want to use classes with a __call__ method if you really want to import and initialize only once.

On the reusability side, it could also be good to be able to parametrize the generator with the site the user whish to fetch:

def get_questions(site=stackexchange.CodeReview):
    se = stackexchange.Site(site)
    …

Better usage of the stackexchange API

The stackexchange module let you directly query information using "site classes" (such as stackexchange.CodeReview) without necessarily relying on a stackexchange.Site object. So:

CR = stackexchange.CodeReview()
CR.questions()

will be a direct call to the SE API on questions.

From there, two things worth noting:

The sort method;
The fromdate parameter.

Sorting results

The advantage of using sort='creation' in the query parameters is that you only need to store the last asked question in your old variable. You can then iterate over the result of the query and stop when q.title == old.title without storing previous questions anymore.

Asking for questions asked after a given date

The fromdate parameter takes a timestamp and make the query returns only questions asked after that point in time. There is no real need for sorting anymore, all you need to remember is the date at when the last query was made.

Proposed improvements

import stackexchange
import datetime
import time

def pync_notify(question):
    from pync import Notifier
    Notifier.notify('Votes: {0} | Answers: {1} | Views: {2}'.format(
        question.score, len(question.answers), question.view_count),
        title='CodeReview: {0}'.format(question.title),
        subtitle='Tags: {0}'.format(', '.join(question.tags)),
        sound='default', open=question.url)

def gtk_notify(question):
    from gi.repository import Notify
    Notify.init('stackexchange')
    notification = Notify.Notification.new(
        'CodeReview: {}'.format(question.title),
        'Votes: {} | Answers: {} | Views: {}'.format(
            question.score, len(question.answers), question.view_count),
        'dialog-information')
    notification.show()

def now():
    """Return the current timestamp"""
    date = datetime.datetime.now()
    return int(date.timestamp())

def get_questions(site=stackexchange.CodeReview, query_delay=2):
    """Fetch recent questions from the Stack Exchange network

    This function uses the SE API and yield each
    new question that is asked on the given site.
    """

    se = site()
    last_query = now()

    while True:
        fromdate, last_query = last_query, now()
        questions = se.questions(fromdate=fromdate, sort='creation')
        yield from questions
        time.sleep(query_delay)

if __name__ == '__main__':
    for question in get_questions():
         pync_notify(question)

Last minute reading

On the discussion about throttles of the StackExchange API, one can read:

  While not strictly a throttle, the Stack Exchange API employs heavy caching and as such no application should make semantically identical requests more than once a minute. This is generally a waste of bandwidth as, more often than not, the exact same result will be returned.

This means that you probably want to increase your time.sleep delay from 2 to at least 60.


As for the code:

The property getter and setter should probably throw an exception if the check against the caller failed.  If you attempt to set it from any function besides one defined on the prototype, you don't want it to silently fail -- if it does, you'll be wasting lots of time trying to figure out why your changes aren't sticking.  (Particularly in light of other issues below.)
If you're going to assign a different key to each member function, you might consider making validFns[key] be the function with that key, rather than just '1', so you can check it against the caller.  (Ensures the key doesn't ever accidentally match.)
You're setting keys on each thing you copy from the prototype, regardless of whether it's a function.  Only functions need keys; other stuff (well, anything really, but particularly non-function members) might have its own purpose for key.
The way the access checks are now, only member functions can use them.  Though that may be the intent, it is way more crippling than it sounds.

Observe:

foo.prototype.doStuff = function() {
    var self = this;
    $('input.some_selector').each(function() {
        self.foo += parseInt(this.value);
    });
};

We're in a private function, which should have access to foo.  But since the actual access is within an anonymous function, and not doStuff, it's not allowed.  In order to fix this (and fix it you should), your access check would need to go down the call stack (check the caller, then the caller's caller, and so on) til it finds a function with a key.  Recursive functions seem to cause such a search massive amounts of trouble, though; a depth limit might help with that.

definePrivateProperties can be run a second time.  And a third, fourth, etc.  And each time you call it, it obliterates the previous property's value in order to add the new one.  Read: external code can mess up your private variables.

Say:

foo.prototype.mangleFoo = function() { this.foo = 100; };
x.definePrivateProperties('foo');
delete foo.prototype.mangleFoo;
x.mangleFoo();

(BTW, see what we just did there?  We can add a function and give it access to the "private" properties pretty much at will.)  In order to prevent that...i dunno.  redefine definePrivateProperties after it's run once?

In contrast, the standard method (hiding the variable away in a closure) is not prone to such hackery.


You should investigate whether GNU Make (or whichever Make implementation your users are supposed to use) has a special variable for all dependencies of the current rule, so that you don't need to list the source files twice.
The command line for gcc is missing the -Wall -Wextra -O2 options to catch common mistakes and to make the program run faster.
If you want the Makefile to be portable to systems other than GNU Linux on x86_64, you should switch to GNU autoconf, but that's a lot of work. If your project is just a toy project, it's fine as it is.


MS Fakes Shims. Assert "was called" (by closures)

Generally, I see no problem with using closures with unit testing, as long as the intent is clear and concise. Functional programming style can be difficult for others to grasp if they're not familiar with it. So, best practices here may vary from person to person and company to company. I use the pattern a lot for testing if my events are firing correctly.

bool eventCalled = false;
obj.PropertyChanged += (sender,args)=>
 {
      Assert.IsTrue(args.PropertyName.Equals("Change");
      eventCalled=true;
 };
obj.Change = true;

Assert::IsTrue(eventCalled, "PropertyChanged was not called");


DRY cursors: preventing T-SQL's FETCH statement from being repeated

The infinite loop idiom in languages that have boolean literals is while ( true ) but it seems the boolean type and its literals (e.g., TRUE/FALSE) have gone the way of the DO ... WHILE as far as T-SQL is concerned. This means you're stuck with true-evaluating expressions of which 1=1 is the simplest.

In your case I'd replace the start of the loop with WHILE (1=1) -- Loop until BREAK..


Periodically sending data from database to an API

If Dowork takes longer than 15 seconds to execute, it will be called a second time.  Will this cause issues?  One way around that would be to disable the timer while you're doing work, then start it up again when the work is done, or add an appropriately typed and thread safe "busy" member to the class so that you can skip starting any new work if work is currently being done.


Windows forms set saved groupbox location settings

Parsing the settings strings character by character is troublesome and can be hard to get it right.

It would be better to use a regex to match the string and extract the relevant parts using capture groups, for example:

\[(\d+):\{X=(\d+),Y=(\d+)\}\]

Debuggex Demo

I know too little of C# to give a sample implementation,
in case it helps, here it is in Java:

Pattern pattern = Pattern.compile("\\[(\\d+):\\{X=(\\d+),Y=(\\d+)\\}\\]");
String sample = "[1:{X=7,Y=29}][2:{X=52,Y=433}]";

Matcher matcher = pattern.matcher(sample);
while (matcher.find()) {
    int id = Integer.parseInt(matcher.group(1)),
    int x = Integer.parseInt(matcher.group(2)),
    int y = Integer.parseInt(matcher.group(3))
    // do what you need with id, x, y
}


Is my DSL good idea to replace builder pattern?

A few, rather subjective thoughts:

Decision #1:

Here you have a flight builder. Which group of sentences looks more natural from the following?

a flight builder with origin
a flight builder with destination

or

a flight builder from
a flight builder to

The first two looks better for me.

Furthermore, if origin and destination are in your domain you should use them. Using synonyms could be confusing.

Decision #2:

I may be worth to note that if you have more than one field with the same type (strings and ints are common) it would not work. Having builders in the same application and one half of them is using with() while the other half is using withX() is also confusing.

Decision #3:

The passenger().withName("KENNEDDY") statements make me think about where the passenger instance comes from. A database or maybe a cache? I think a create word somewhere would make it obvious that it's a new instance and it would be helpful for readers although renaming passenger() to createPassenger() does not seem natural in this code too.


Solving maze problem with backtracking solution using stack

Your solution looks correct. Your don't need to find a similar implementation to validate yours. You just need to verify yours works correctly, by stepping through the logic as if with a debugger, and verifying all execution paths, and considering all possible corner cases.

By the way, recursive solutions use a stack too, just implicitly. They take advantage of the function call stack, which stores the program state every time you step into a function, and pops it when leaving a function, returning to the caller. Manually implementing a stack based solution is typically less convenient, but more powerful and efficient, because you have full control over the stack and its entries, which can be perfectly sized.

Although your solution works, I would write it slightly differently:

The logic would be slightly easier to understand if all the conditions of the movement were organized in the same if-else chain inside the loop
Instead of adding the next position to the stack, it's more conventional to add the current one
The Stack class is no longer recommended in Java, use Deque and ArrayDeque instead
Instead of int[] end = new int[]{maxY, maxX};, a shorter more convenient form exists: int[] end = {maxY, maxX};. (Unfortunately this form works only at initialization, it doesn't work for assignment in general.)
It's more natural to store coordinates as (x, y) pair instead of (y, x) pair

Like this:

public static boolean solve(boolean[][] maze) {
    int maxY = maze.length - 1;
    int maxX = maze[0].length - 1;

    Deque<int[]> stack = new ArrayDeque<>();
    int x = 0;
    int y = 0;

    while (true) {
        if (x == maxX && y == maxY) {
            // Found the exit!
            return true;
        } else if (x + 1 <= maxX && maze[y][x + 1]) {
            // Try moving right
            stack.push(new int[]{x + 1, y});
            x++;
        } else if (y + 1 <= maxY && maze[y + 1][x]) {
            // Try moving down
            stack.push(new int[]{x, y + 1});
            y++;
        } else if (!stack.isEmpty()) {
            // Mark as dead end (so we will not try to reach here again)
            maze[y][x] = false;
            int[] current = stack.pop();
            x = current[0];
            y = current[1];
        } else {
            // No way to go -> impossible to reach the exit
            return false;
        }
    }
}


Looks good!

I would say maybe the following styles would be just a bit more readable, easier to follow.

We can also alter l1 and l2 with more descriptive variable names.

Line Counting Fallacy:

Sometimes, Line/character countings are helpful for command line languages/scripts (awk, grep, sed, regex, etc.) or maybe Code Golfing, is not a JavaScript practice though.

Iterative using a Sentinel Node
const mergeTwoLists = function(l1, l2) {
    const sentinel = {
        val: -1,
        next: null
    }

    let head = sentinel
    while (l1 && l2) {
        if (l1.val > l2.val) {
            head.next = l2
            l2 = l2.next
        } else {
            head.next = l1
            l1 = l1.next
        }

        head = head.next
    }

    head.next = l1 || l2

    return sentinel.next
}

Recursive
const mergeTwoLists = function(l1, l2) {
    if (l1 === null) {
        return l2
    }

    if (l2 === null) {
        return l1
    }

    if (l1.val < l2.val) {
        l1.next = mergeTwoLists(l1.next, l2)
        return l1

    } else {
        l2.next = mergeTwoLists(l1, l2.next)
        return l2
    }
}

Or even better that those:
const mergeTwoLists = function(l1, l2) {
    if (l1 === null) {
        return l2;
    }

    if (l2 === null) {
        return l1;
    }

    if (l1.val < l2.val) {
        l1.next = mergeTwoLists(l1.next, l2)
        return l1;

    } else {
        l2.next = mergeTwoLists(l1, l2.next)
        return l2;
    }
}

const mergeTwoLists = function(l1, l2) {
    const sentinel = {
        val: -1,
        next: null
    };

    let head = sentinel;
    while (l1 && l2) {
        if (l1.val > l2.val) {
            head.next = l2;
            l2 = l2.next;
        } else {
            head.next = l1;
            l1 = l1.next;
        }

        head = head.next;
    }

    head.next = l1 || l2;

    return sentinel.next;
}


Updated: Questions on implementing Builder design pattern

Question 1: If the parameters are mandatory anyway you might as well enforce this through your API. This reads just fine:

Connector con = new Connector.Builder(mandatoryURL)
                    .setAccessKey(key)
                    .build();

Question 2: Either place, since you contained the checks entirely in the Connector class (because of the private constructor) you have full control anyway.

Since either one of them is mandatory and you I'm assuming you won't use both of them, you might also provide 2 separate "build" methods that take one of those parameters as input.

public static class Builder {
    String appUrl = null;

    public Builder(String appUrl) {
        this.appUrl = appUrl;
    }

    public Connector withAccessKey(String accessKey) {
        Connector result = new Connector(appUrl);
        connector.accessKey = accessKey;
        return connector;
    }

    public Connector withOneTimePwd(String oneTimePwd) {
        Connector result = new Connector(appUrl);
        connector.oneTimePwd = oneTimePwd;
        return connector;
    }
}

Quick note that I changed the Connector constructor to also take the URL parameter instead of the builder. Your way works just fine in this case, I just prefer to have the builder be responsible for setting the correct fields instead of making the Connector "know" about the Builder class.

Alternative solution to using a Builder is to use factory methods. Your Connector class could then look something like this:

public class Connector {

    String appUrl = null;
    String oneTimePwd = null;
    String accessKey = null;

    private Connector(String appUrl) {
        this.appUrl = appUrl;
    }

    public static Connector createWithAccessKey(String appUrl, String accessKey) {
        Connector result = new Connector(appUrl);
        connector.accessKey = accessKey;
        return connector;
    }

    public static Connector createWithOneTimePwd(String appUrl, String oneTimePwd) {
        Connector result = new Connector(appUrl);
        connector.oneTimePwd = oneTimePwd;
        return connector;
    }

    //... rest of the class
}

You can now use it as follows:

Connector con = Connector.createWithAccessKey(someUrl, myKey);

This has about the same effect as your Builder idea but with a lot less boilerplate code to reach it.


Byte array to floating point such as FPE2 in Java

Documentation

I took me a while to understand and research the algorithm and the purpose of the function parameters. It would be better to write some Javadoc for reviewers and future readers (which may include yourself).

Identifiers

You should use variable and function identifiers that explain their purpose (barring obvious cases like i for a loop iterator).

strtof is a function defined since C89 and does something very different from your function; that's not a good name here. What about FPxToFloat because the function converts data in a variant of the FP* formats (x instead of *) to a float?
e is the number of bits in the integral part of the number. How about integerBits instead?
total – My first thought was “total of what?”. I usually go for a name like result in these cases since it holds the function result (or an intermediate result on the way to the final result) which should be well documented somewhere nearby.

Limitations

Why is size restricted to ≤ 4 bytes and integerBits restricted to ≤ 8. You say you want a more generic solution. I don't see a reason why size can't be 17 and integerBits 49.
Currently the encoded number needs to start at offset 0 inside the bytes array. Since Java doesn't have C's pointer arithmetic it would be useful to offer an offset parameter like the read and write functions in java.io.

You can still offer a convenience function with less boiler plate:

public static float FPxToFloat(byte[] bytes, int integerBits) {
    return FPxToFloat(bytes, 0, bytes.length, integerBits);
}

Complexity

Your implementation seems overly complicated and suffers from a number of unnecessary limitations (see first point in the section above). What about this:

double result = 0;
int exponent = integerBits - Byte.SIZE;
for (; offset < size; offset++, exponent -= Byte.SIZE) {
    result += Math.scalb(bytes[offset] & 0xFF, exponent);
}
return result;

scalb avoids multiplicative floating-point operations and overflow of integers that shall later be converted to floating-point. The only optimization I can think of is to work on long instead of byte if possible to use the available processor word size better (to achieve that one can wrap byte[] inside a java.nio.ByteBuffer and use a LongBuffer view onto it).

Full program (Ideone is currently acting up here so a Gist it has to be for now.)


Naming: Hungarian Notation is the DEVIL.
It makes the reader want to see your code burn in eternal flames.

https://simpsonswiki.com/wiki/Flanders_the_Devil

objExcel would be better off as xlApp or excelApp
objUser is dying to call itself something like adUser
intRow wants to be called xlRow or just row
intUAC is silently begging for a more descriptive name
objOU wants to shoot whoever named it that

Now, whether your code is correct or not is off-topic for this site; since this question hasn't been closed as off-topic yet, I'm going to assume you've got working code.
Do Until objExcel.Cells(intRow,1).Value = ""

I'd use vbNullString here instead of "". It makes the intent clearer, and the non-string takes up 0 bytes. "" eats 6 bytes for no reason - StrPtr(vbNullString) is 0; StrPtr("") is a non-zero memory address.
The repeated assignments on objUser are a missed opportunity of using a With block:
With objOU.Create("User", "cn=" & objExcel.Cells(intRow, 3).Value, _
                          objExcel.Cells(intRow, 2).Value, _
                          objExcel.Cells(intRow, 19).Value)

    .SAMAccountName = objExcel.Cells(intRow, 19).Value & ".sat"
    .GivenName = objExcel.Cells(intRow, 3).Value
    .SN = objExcel.Cells(intRow, 2).Value
    .AccountDisabled = False
    .AccountExpirationDate = Date + 365
    '...

End With

Your usage of line continuation characters is... well, you use it in weird places. Actually, everywhere you've used it, I wouldn't have. Notice in the above snippet, how I used it to line up the parameters.


Streamlined for-loop for comparing two lists

Your solution's time complexity is O(n2), which is far from optimal. Your lists contain 19 elements - so your solution performs an order of 361 operations.
In order to get a linear solution, you can simulate a "c-style" for loop using range:

for i in range(len(list1)): # assuming the lists are of the same length
    if list1[i]==list2[i]:
                do x

Now the loop runs exactly 19 times - much better!

Another thing: your code checks if binary==1. Is it what you want? If so, Python's equal operator can operate on three arguments, making it more readable:

for i in range(len(list1)): # assuming the lists are of the same length
    if list1[i]==list2[i]==1:
                do x

Lastly, you may want to represent a binary number using the most natural way - as a number. Aside from space consideration, most languages (including Python) have standard binary (often called bitwise) operations.


A wounded Zombie finder, or: how to find the almost dead undead?

Not utterly wrong, but

q.PostTypeId = 1

and

AND a.PostTypeId = 2

are superfluous. The only post types with a non-null value in ParentId are answers (see the Database schema documentation), and their values are the ids of questions, so the join already takes care of this.

I'd slightly misunderstood the objective of the query at first, because questions with answers with negative scores, like this one also appear on /unanswered. But you want to review the answers to see if they're worthy of an upvote. Then, you might as well drop the second column (MAX(a.Score) AS [Best answer score]) because you know it's going to be zero.


About aesthetics

  I used the "long" form of all math statements, avoided the use of pointers, and used only while loops for aesthetic purposes (simply put, I think the code is prettier when it is written like that.)

While making the code look aesthetically pleasing can be beneficial (especially if it makes it more readable), you should not give that a higher priority than writing maintainable code. The "short" form of modifying variables has the advantage that you don't have to repeat the variable name. This might make the code easier to read, but the big advantage is that it reduces potential errors: for example, it's impossible to accidentily put the wrong variable name on the right hand side if there is none to begin with. So if you'd write:

CurrentIndex[0]++;

You can't accidentily misspell the variable name, you can't accidentily use [1] on the right hand side, and you can't accidentily write + 2 instead of + 1.

Another benefit is that incrementing a counter using ++ is more ideomatic, which means that there is a big chance that other programmers that are used to C will find the short form more natural.

Toby Speight already mentioned why for-loops can improve clarity over while-loops with separate initialization and incrementing statements.

The use of arrays instead of pointers is perfectly fine here, since you are indeed manipulating arrays.

Variable names

Descriptive variable names help understand code, but having too long variable names can start to hinder readability. Also, some one-letter variable names are justified, for example it is idiomatic to use i and j as loop counters.

Also, when you write CurrentIndex in BubbleSort(), it makes me wonder: is there also PreviousIndex or a NextIndex? If not, just Index would be better (or even just i). In SelectionSort() it makes more sense.

CPU efficiency

Your bubblesort implementation might have the advantage of quiting early if the input array was already sorted, but if it was not, then it takes twice as long as necessary. Instead of comparing two consecutive elements at a time, sort by first comparing the first element to all other elements, and swapping when necessary. After that first pass, you know that the first element is the lowest, so you don't have to consider it in the next pass anymore, and so on.

If you want to sort arrays of integers in the most efficient way, you probably want to implement radix sort.

Make sure you handle corner cases

In BubbleSort(), if the length of the input array is zero, then your code will go into an infinite loop and read out of bounds. Always check that you handle corner cases like arrays of length 0 and 1.

Another issue is that since Length is an int, someone could pass a negative value. To avoid that, use size_t Length instead (and change the type of the indices to match), or at least add in a check that Length is not negative. It still make sense to allow a length of 0 or 1.


Since the goal is the best possible implementation of this algorithm, I'd suggest the following. However, faster algorithms do exist.

To conform to PEP8 make sure you have two blank lines after your imports and surrounding function definitions.
Since, you aren't editing each item, but rather adding and removing items until the list is sorted, I'd use the while keyword.
The builtin min function is faster than looping through yourself. If you want to make your own minimum function as an exercise you can always do that and replace min with your own my_min say

My Code:

def my_sort2(my_list):
    unsorted_list = [*my_list]
    sorted_list = []
    while len(unsorted_list) > 0:
        shortest_num = min(unsorted_list)
        sorted_list.append(shortest_num)
        unsorted_list.remove(shortest_num)
    return sorted_list

When timing mysort2 vs your mysort, I get a 12% improvement on my machine.

Timing code: (Not the nicest but it does the job)

t1 = inf
t2 = inf
for _ in range(1000):
    t1 = min(t1, timeit.timeit(
        stmt=f'my_sort(random_list)',
        setup=f'from __main__ import my_sort, random_list',
        number=100))
    t2 = min(t2, timeit.timeit(
        stmt=f'my_sort2(random_list)',
        setup=f'from __main__ import my_sort2, random_list',
        number=100))


Pausing and resuming a concurrent database update queue

Why are all your variables static? You shouldn't use them.
You don't need that many locks. Actually, you need only 1 and a AtomicBoolean (locked).
I can't understand why you add "SELECT 1" if the queue is empty. That'll  waste some precious time.
I think as long as there's only 1 QueueExecutor you don't need to make the queue thread-safe.
You could execute your statements in batches but I'm not sure of the pros and cons.
Unless you 100% trust the user you should use PreparedStatements but even if you do trust the user you still should use it as it will give you a speed (i.e. query execution) boost.
Wouldn't it be better to pass Statements to queue instead of String? It would allow you to easily allow the user to use PreparedStatements

Example implementation (not tested):

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.atomic.AtomicBoolean;

public class DatabaseQueue {

    private final Deque<PreparedStatement> queue = new ArrayDeque<>();
    private final QueueExecutor executor = new QueueExecutor();
    private final AtomicBoolean paused = new AtomicBoolean(false);
    private final Object object = new Object();

    public DatabaseQueue() {
        executor.start();
    }

    public void start() {
        if (!paused.compareAndSet(true, false)) {
            throw new IllegalStateException("DatabaseQueue wasn't paused");
        }

        executor.notify();
    }

    public void pause() {
        if (!paused.compareAndSet(false, true)) {
            throw new IllegalStateException("DatabaseQueue is already paused");
        }
    }

    public void close() {
        executor.shutdown();

        paused.set(false); // we want to execute all the statements before closing
        executor.notify();
    }

    public void queue(PreparedStatement statement) {
        queue.addLast(statement);

        if (!paused.get())
            executor.notify();
    }

    public PreparedStatement createStatement(String sql) throws SQLException {
        return Database.getConnection().prepareStatement(sql);
    }

    class QueueExecutor extends Thread {
        private boolean shutdown = false;

        QueueExecutor() {
            setName("Database Queue Executor");
            setDaemon(true);
        }

        void shutdown() {
            shutdown = true;
        }

        @Override
        public void run() {
            // even if we should shutdown we first should execute all the statements
            do {
                if (paused.get() || queue.isEmpty()) {

                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                try {
                    PreparedStatement statement = queue.removeFirst();

                    if (!paused.get())
                        statement.execute();
                    else
                        queue.addFirst(statement);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } while (!shutdown || !queue.isEmpty());
        }
    }
}


For small lists of enemies, linearly scanning all of them and computing the distance to the character is sufficient. However, if you have many enemies, a more efficient data structure is needed.

If your list of enemies does not change (or changes less often than you need to find the closest enemy), I would use scipy.spatial.cKDTree. kd-trees take \$\mathcal{O}(n\log n)\$ time to build, but afterwards each query only takes \$\mathcal{O}(\log n)\$.

from scipy.spatial import cKDTree as KDTree

def find_closest_kdtree(character: tuple, enemies: KDTree) -> (int, int):
    """
    Finds the closest enemy in enemies

    :param character: An (x, y) representing the position of the character\n
    :param enemies: A KDTree that represent enemies

    :return: A tuple (x, y) of the closest enemy
    """
    _, i = enemies.query([character], 1)
    return i[0]

if __name__ == "__main__":

    # Test Case #

    character = (5, 6)
    enemies = [(1, 2), (3, 4), (7, 6), (11, 4)]
    enemies_tree = KDTree(enemies)
    closest = enemies[find_closest_kdtree(character, enemies_tree)]
    print(closest)

If you do regularly need to update the list of enemies (because they are spawned, get killed, move off-screen, etc), you might be able to use a R* tree instead:

from rtree.index import Rtree

def find_closest_rtree(character: tuple, enemies) -> (int, int):
    """
    Finds the closest enemy in enemies

    :param character: An (x, y) representing the position of the character\n
    :param enemies: A KDTree that represent enemies

    :return: A tuple (x, y) of the closest enemy
    """
    return next(enemies.nearest(character, 1, objects='raw'))

if __name__ == "__main__":

    # Test Case #

    character = (5, 6)
    enemies = [(1, 2), (3, 4), (7, 6), (11, 4)]
    enemies_tree = Rtree()
    for i, p in enumerate(enemies):
        enemies_tree.insert(i, p+p, p)

    closest = find_closest_rtree(character, enemies_tree)
    print(closest)

Here is how the different methods compare performance wise, including the implementation using min and your original implementation:

Note that building all the R* trees for this took multiple minutes, while building all the KDTrees took only a couple of seconds. So you would probably have to rebuild the KDTree quite often for it to be worth it to switch to the R* tree.

In case you are interested, this is how I generated that graph:

import numpy as np
import pandas as pd
from functools import partial
import timeit
from scipy.spatial import cKDTree as KDTree
from rtree.index import Rtree

def get_time(func, *x):
    timer = timeit.Timer(partial(func, *x))
    t = timer.repeat(repeat=5, number=1)
    return np.min(t), np.std(t) / np.sqrt(len(t))

def get_times(func, inputs):
    return np.array(list(map(partial(get_time, func), inputs))

def find_closest(character: tuple, enemies: list) -> (int, int):
    closest_enemy = None
    smallest_distance = 100_000_000 # Set to large number to ensure values can be less #
    for enemy in enemies:
        distance = math.sqrt(math.pow(character[0] - enemy[0], 2) + (math.pow(character[1] - enemy[1], 2)))
        if distance < smallest_distance:
            closest_enemy = (enemy[0], enemy[1])
            smallest_distance = distance
    return closest_enemy

def find_closest_min(character: tuple, enemies: list) -> (int, int):
    def find_enemy_distance(enemy):
        return math.hypot((character[0] - enemy[0]), (character[1] - enemy[1]))
    return min(enemies, key=find_enemy_distance)

def find_closest_kdtree(character: tuple, enemies: KDTree) -> (int, int):
    _, i = enemies.query([character], 1)
    return i[0]

def find_closest_rtree(character: tuple, enemies) -> (int, int):
    return next(enemies.nearest(character, 1, objects='raw'))

def find_closest_kdtree_with_build(character: tuple, enemies) -> (int, int):
    enemies_tree = KDTree(enemies)
    _, i = enemies_tree.query([character], 1)
    return enemies[i[0]]

if __name__ == "__main__":
    character = 5, 6
    x = [list(map(tuple, np.random.randint(-n, n, (n, 2))))
         for n in np.logspace(1, 6, dtype=int)]
    kdtrees = [KDTree(v) for v in x]
    rtrees = []
    for y in x:
        rtrees.append(Rtree())
        for i, v in enumerate(y):
            rtrees[-1].insert(i, v+v, v)

    df = pd.DataFrame(list(map(len, x)), columns=["x"])
    df["find_closest"], df["find_closest_err"] = get_times(partial(find_closest, character), x).T
    df["find_closest_min"], df["find_closest_min_err"] = get_times(partial(find_closest_min, character), x).T
    df["find_closest_kdtree"], df["find_closest_kdtree_err"] = get_times(partial(find_closest_kdtree, character), kdtrees).T
    df["find_closest_rtree"], df["find_closest_rtree_err"] = get_times(partial(find_closest_rtree, character), rtrees).T
    df["find_closest_kdtree_with_build"], df["find_closest_kdtree_with_build_err"] = get_times(partial(find_closest_kdtree_with_build, character), x).T

    for label in df.columns[1::2]:
        plt.errorbar(df["x"], df[label], yerr=df[label + "_err"], fmt='o-', label=label)
    plt.xlabel("Number of enemies")
    plt.ylabel("Time [s]")
    plt.xscale("log")
    plt.yscale("log")
    plt.legend()
    plt.show()


Processing an input image using probability

I'm not familiar with the algorithm, so I can't say whether there is a radically different approach which will improve performance. That said:

With such short variable names it's hard to know what things are. What is c0 actually? What does the "t" in rt and ct mean? Also, the structure and semantics of prob is completely opaque. I can guess that it's related to probability in some way, but why do you only care about the third index of its shape and what is prob[r0, c0, c]?
Try compressing the calculation into a single expression to avoid reassigning so many times. This should be optimised away, but see point 4.
Instead of converting the height and width indexes into floating point numbers, can you use an integer scaling factor to avoid floating point math?
This sort of performance problem really should be profiled, but without the full context and realistic images it would amount to nothing more than guesses.


You might be confusing from lxml import etree that is a legitimate (even preferred) form of an absolute import with relative imports for intra-package imports that are discouraged: http://www.python.org/dev/peps/pep-0008/ (see "Imports" section)


characters should be named Character
Add some type hints
Use f-strings
Use int or float for power score, not str
Use a @property where appropriate
As-is, there isn't a lot of advantage to separating your prompt strings into variables
For the data method, don't force a print - just return a string and print at the outer level
Add a main
Square brackets around an input choice implies that it is the default to be selected on 'enter'
Simplify your yes/no check to only care about the first letter; anything more complicated isn't all that useful
Add an input validation loop

Suggested:
class Character:
    def __init__(
        self,
        title: str,
        name: str,
        power_score: int,
        biography: str = 'Not much is known about this character',
    ):
        self.title = title
        self.name = name
        self.power_score = power_score
        self.biography = biography

    @property
    def full_name(self) -> str:
        return f'{self.title} {self.name}'

    @property
    def data(self) -> str:
        return (
            f'{self.title} {self.name} | Power score - {self.power_score} -\n'
            f'{self.biography}'
        )

def ascii_art():
    # Y(Height) of ascii-art
    z = 12
    for x in range(z):
        hyphens = "-" * (z-x)
        print(hyphens + "*" * x + " " * x + hyphens)

def input_yesno(prompt: str) -> bool:
    full_prompt = f'{prompt} ([Yes]/No): '
    while True:
        answer = input(full_prompt).strip()
        if answer == '':
            return True

        answer = answer[0].lower()
        if answer == 'y':
            return True
        if answer == 'n':
            return False
        print('ERROR')

def main():
    ascii_art()
    if not input_yesno('Are you ready to play'):
        return

    is_hero = input_yesno('Do you want to be a Hero')
    print('\nYou have selected', end=' ')
    if is_hero:
        print('to be a hero')
        character = Character('Barbarian', 'Cider', 4854)
    else:
        print('not to be a hero')
        character = Character('Lord', 'Cido', 7910)

    print("\nYour character's profile:")
    print(character.data)

if __name__ == '__main__':
    main()


Here's mine, done basically without consulting yours.

v    >          0v    >              v >\#v_:.v
0>:3%|           >\:5%|              >:|  >   v
>    >"zziF",,,,1^    >"zzuB",,,,\1+\^ >\"!",$v
 ^+1 _@#-**455: ,*25                          <

My strategy for writing it was just to write the very simplest code possible — the body of the main loop is just

if (i divisible by 3) "Fizz"
if (i divisible by 5) "Buzz"
if (i equals 0) "!"

and then throw a loop around that. So I started by writing just

     >          v   >          v >    v
0>:3%|          >:5%|          >:|    v
>    >"zziF",,,,^   >"zzuB",,,,^ >"!",v
 ^+1 _@#-**455:                       <

But this is missing three pieces: (1) there should be a newline after each line; (2) there should be a :. to print i whenever we don't print Fizz or Buzz; and (3) we need to avoid printing i whenever we did print Fizz or Buzz.

(1) is easy to fix; we just add ,*25 to the "carriage return" code along the bottom of the loop.

(3) is awkward. I made an abortive attempt to squeeze a recomputation of something like ::3%!\5%!+#v_:. (read left-to-right) into the "carriage return" line before realizing that computing logical AND ("i mod 3 AND i mod 5") is awkward in Befunge, and I would have to add a fifth line if I wanted to branch again here with #v_. So it makes sense to do what you did and keep track of whether we've printed "Fizz" or "Buzz" as we print them. This lengthens the loop body by a few characters (most of which are \).

With (3) out of the way, (2) is easy to squeeze into the blank rectangle in the upper right. As a bonus, if we just printed "!", then we know we don't need to test for :.!

As for your code: It's definitely more convoluted than mine! :D  But in Befunge, this is not necessarily a bad thing.

There are some infelicities; for example you use *2*5*52:+1,*52,*84 where I would have used **455:+1,*52 — I don't understand why you bother printing that space character with *84 since it comes at the end of a line. Possibly a vestige of an earlier version of the code?

On the right-hand side you have a # jumping over a 5. If you were trying to be obfuscated, then you could replace this with a codepath that just runs straight through the 5 and then corrects with a $ further up. You have plenty of white space where a $ could fit in.

Rather than always using

 >A
>|
 >B

consider using

  >A
>#^_B

where it saves you a line. In my long-rusted experience, Befunge idiom still values "small number of lines" over "small number of columns" — the language may be 2D but it's still written by line-oriented chauvinists. :)

Can they be reworked into functions? — No. :) Befunge-93 has no concept of the (non-#) GOTO, and as a corollary it has no GOSUB and no RETURN. I can imagine a programming idiom that applies a binary search tree of "line numbers" down the left side of the program and can "GOTO" a line whose number is specified on the stack; but this would be way overengineered for FizzBuzz.

Can this be condensed? — Yes. :)

Do other people understand the steps I've taken? — Yes. It's pretty straightforward. :)


From a once over:

You could have used a loop instead of .each(), it would be marginally faster
Your indenting is off, I assume you had trouble pasting the code
.9 and .7 are magic constants, you should declare these with var and a good name
I would use a ternary for this:

if {
    var newWidth= ;
    $('#navUl').css({"maxWidth":newWidth});
} else {
    $('#navUl').css({"maxWidth":});
}

could be

var navWidth = ( menuLength > windowWidth *.9 ) ? menuLength *.7 : windowWidth;
$('#navUl').css({"maxWidth":navWidth});

of course with properly named constants this might stretch too much to be easily readable, up to you.
With jQuery, the most common way to trigger on ready is

$( function(){
  //Do Something
  menuBreak();
});

now, since $() expects a function, we might as well pass menuBreak immediately:

$( menuBreak );

The same things goes for resize:

$(window).resize( menuBreak );


Insert a Node at the Tail of a Linked List

Memory Leak
These lines here create a memory leak, because you allocate a node and never free it:

    // creates a temp node and sets it to head
    Node *temp = new Node;
    temp = head;

You don't need to allocate another node there, because you aren't actually ever using it.  You can just set the temp pointer directly to head:
    Node *temp = head;


Reduce an X/Y Value to an Index In a 1D array and Return the Array Value

From a short review;

the tilescale is 16 which is a great value to multiply or divide with, so
x = x/tilescale;
z = z/tilescale;

can become
x = x >> 4; //Divide by 16 (tilescale)
z = z >> 4; //Divide by 16 (tilescale)

this does mean that changing the tilescale can become a performance drag (like in real games)

So are 256 and 4, so
return(mapcol[(x+z*mapscalex)]*tilescaley);

could be
return(mapcol[(x+z<<8)]<<2); //Nice comment here

~~ is faster than Math.floor() but for negative values it does return ~~-6.3 -> 6

Don't count on Math to be fast, I dont think I've ever seen Math be faster in anything, even an if statement is faster than Math.max(0,Math.floor(x))

When you know that x or z are either negative or greater than 255, why not just exit with a fixed value?

Check out 8 bit arrays, they might reduce the need for clamping in your code


A string is not a comment

A comment in the code starts with #. Even thought the strings you write seems to have no effect in the code, they are evaluated and created in memory (and thrown away right after) each time. Especially in the while loop.

Do not confuse yourself between docstrings and comments.

l is a really bad variable name.

I truly thought l/rho was 1/rho at first and had a hard time mapping your code to the maths.

Given that:

You don't seem to use the returned value for rho and l;
You “only” need rho and the quotient l/rho;
You don't need to recompute l/rho at each iterations.

I suggest you precompute using:

#Calculate regression co-efficient and stepsize
r = np.amax(np.absolute(w))
l_over_rho = sqrt(2*log(n, 10)) * r
rho = 1/r

and call Sthresh(xhat + u, l_over_rho) latter on. You also only need to return zhat.

Besides, you are dividing l_over_rho by 2.0 in Sthresh; on top of not seeing that anywhere in the maths, you should also incorporate it in the precomputation for a faster loop.

A for loop is more pythonic

Since you don't need the value of i in your while loop, it is best to write:

for _ in xrange(MAX_ITER):
    #x minimisation step via posterier OLS
    xhat = Q.dot(Aty + rho*(zhat - u))
    #z minimisation via soft-thresholding
    zhat = Sthresh(xhat + u, l_over_rho)
    #mulitplier update
    u = u + xhat - zhat

to better emphasize the fact that you won't use the iteration value.

Separate computation and presentation

I'd recommend creating a function for plotting the results and a function for your tests. That way, it would be easier to jump into an interactive session and test your function with alternatives input values:

def test():
    A = np.random.randn(50, 200)

    num_non_zeros = 10
    positions = np.random.randint(0, 200, num_non_zeros)
    amplitudes = 100*np.random.randn(num_non_zeros, 1)
    x = np.zeros((200, 1))
    x[positions] = amplitudes

    y = A.dot(x) + np.random.randn(50, 1)

    plot(x, ADMM(A,y)) #given that ADMM only 'return zhat' now

def plot(original, computed):
    plt.plot(original, label='Original')
    plt.plot(computed, label = 'Estimate')

    plt.legend(loc = 'upper right')

    plt.show()

if __name__ == "__main__":
    test()

[Optimization] Method lookups are faster with local variables

The Sthresh call incur overheads that you can easily remove since it is a one liner. In the same vein Q.dot, np.sign, np.maximum, and np.absolute have to be resolved at each loop iteration. You will save some time using local variable as alias to these functions:

Q_dot = Q.dot
sign = np.sign
maximum = np.maximum
absolute = np.absolute

for _ in xrange(MAX_ITER):
    #x minimisation step via posterier OLS
    xhat = Q_dot(Aty + rho*(zhat - u))
    #z minimisation via soft-thresholding
    u = xhat + u
    zhat = sign(u)*maximum(0, absolute(u)-l_over_rho/2.0) # do we even need the '/2.0' part ? see comment on 'l'
    #mulitplier update
    u = u - zhat

Full modifications (with a tiny bit of variable renaming)

import numpy as np
import matplotlib.pyplot as plt
from math import sqrt, log

def ADMM(A, y):
    """Alternating Direction Method of Multipliers

    This is a python implementation of the Alternating Direction
    Method of Multipliers - a method of constrained optimisation
    that is used widely in statistics (http://stanford.edu/~boyd/admm.html).

    This is simplified version, specifically for the LASSO
    """

    m, n = A.shape
    A_t_A = A.T.dot(A)
    w, v = np.linalg.eig(A_t_A)
    MAX_ITER = 10000

    #Function to caluculate min 1/2(y - Ax) + l||x||
    #via alternating direction methods
    x_hat = np.zeros([n, 1])
    z_hat = np.zeros([n, 1])
    u = np.zeros([n, 1])

    #Calculate regression co-efficient and stepsize
    r = np.amax(np.absolute(w))
    l_over_rho = sqrt(2*log(n, 10)) * r / 2.0 # I might be wrong here
    rho = 1/r

    #Pre-compute to save some multiplications
    A_t_y = A.T.dot(y)
    Q = A_t_A + rho * np.identity(n)
    Q = np.linalg.inv(Q)
    Q_dot = Q.dot
    sign = np.sign
    maximum = np.maximum
    absolute = np.absolute

    for _ in xrange(MAX_ITER):
        #x minimisation step via posterier OLS
        x_hat = Q_dot(A_t_y + rho*(z_hat - u))
        #z minimisation via soft-thresholding
        u = x_hat + u
        z_hat = sign(u) * maximum(0, absolute(u)-l_over_rho)
        #mulitplier update
        u = u - z_hat

    return z_hat

def test(m=50, n=200):
    """Test the ADMM method with randomly generated matrices and vectors"""
    A = np.random.randn(m, n)

    num_non_zeros = 10
    positions = np.random.randint(0, n, num_non_zeros)
    amplitudes = 100*np.random.randn(num_non_zeros, 1)
    x = np.zeros((n, 1))
    x[positions] = amplitudes

    y = A.dot(x) + np.random.randn(m, 1)

    plot(x, ADMM(A,y))

def plot(original, computed):
    """Plot two vectors to compare their values"""
    plt.plot(original, label='Original')
    plt.plot(computed, label='Estimate')

    plt.legend(loc='upper right')

    plt.show()

if __name__ == "__main__":
    test()


Python's sorted() uses an adaptive sorting algorithm called "timsort" (from its author name Tim Peters), which has worst case complexity of \$O(n log n)\$.

Bubble Sort on the other hand has best, worst and average time complexity of \$O(n ^ 2)\$ which is much worse than \$O(n log n)\$ with growing \$n\$:

In other words, the Bubble Sort sorting algorithm is inefficient by definition.

We can though still apply some optimizations - adjust the end of the working range - skipping every last item on each iteration since it is already in place:

def bubble_sort_new(iterable):
    swapped = True
    while swapped:
        swapped = False
        end = len(iterable) - 1

        for item in range(0, end):
            if iterable[item] > iterable[item + 1]:
                iterable[item], iterable[item + 1] = iterable[item + 1], iterable[item]
                swapped = True

        end -= 1

    return iterable

My timeit results:

In [1]: import random

In [2]: random_list = [randint(0, 100) for _ in range(3000)]

In [3]: %timeit -r 100 bubble_sort(random_list)
1000 loops, best of 100: 402 µs per loop

In [4]: %timeit -r 100 bubble_sort_new(random_list)
1000 loops, best of 100: 382 µs per loop


Groupby, apply custom function to data, return results in new columns

I tried a few variations on your code. I was surprised at how performant the groupby approach really was!

I changed your test data to use more values -- this amortizes the overhead a bit more. Surprisingly, the overhead is a lot of the difference. When I pushed the array length too high, the differences got very small for the groupby-based alternatives.

That said, there are some things you can do to speed things up:

original:        18.022180362
org_prefill:     14.969489811999996
unique_keys:     23.526526202000007
groupby_return:  15.557421341999998
groupby_prefill: 15.846651952999991
shifty:           9.605120361000004

I tried moving away from groupby by iterating over the distinct key values, but that didn't pay off: the performance got worse (unique_keys). I tried playing games with the return value from groupby, hoping to eliminate some duplicated effort. I eventually got that in groupby_return. For small sizes, where the overhead is more of a factor, I got a tiny speed boost by pre-filling the result column before running the groupby. That's groupby_prefill and then org_prefill where I back-ported it. You can see that it pays off versus the original code, but not against the groupby_return code.

Finally, I eliminated the groupby entirely, by figuring out how to detect the start of a group using .shift(). Then I computed a shifted-by-one series and did the subtract operation as a single expression. That's shifty and it's the most performant by a bunch. W00t!

import sys
import timeit

import numpy as np
import pandas as pd

def make_df():
    n = 10_000
    df = pd.DataFrame({'id': ['a']*(n//2) + ['b']*(n//2),
                    'x': np.random.randn(n)})
    return df

def original(df):
    def my_func(group):
        group['diff'] = (group['x'] - group['x'].shift(
            1, fill_value=group['x'].iat[0]))
        return group

    df.groupby('id').apply(my_func)

def org_prefill(df):
    def my_func(group):
        group['diff'] = (group['x'] - group['x'].shift(
            1, fill_value=group['x'].iat[0]))
        return group

    df['diff'] = df['x']
    df.groupby('id').apply(my_func)

def unique_keys(df):
    #print("DF:\n", df)
    df['diff'] = 0
    for key in df.id.unique():
        matches = (df.id == key)
        #df.loc[matches, 'diff'] = df.loc[matches, 'x'] - df.loc[matches, 'x'].shift(1, fill_value=df.loc[matches, 'x'].iat[0])
        df_lmx = df.loc[matches, 'x']
        df.loc[matches, 'diff'] = df_lmx - df_lmx.shift(1, fill_value=df_lmx.iat[0])

def groupby_iter(df):
    for key, subset in df.groupby('id'):
        subset['diff'] = subset.x - subset.x.shift(1,
                fill_value=subset.x.iat[0])

def groupby_return(df):
    def my_func2(group):
        gx = group['x']
        result = gx - gx.shift(1, fill_value=gx.iat[0])
        return result

    res = df.groupby('id').apply(my_func2)
    df['diff'] = res.values

def groupby_prefill(df):
    def my_func2(group):
        gx = group['x']
        result = gx - gx.shift(1, fill_value=gx.iat[0])
        return result

    df['diff'] = df['x']
    res = df.groupby('id').apply(my_func2)
    df['diff'] = res.values

def shifty(df):
    shifted = df['x'].shift(fill_value=df['x'].iat[0])
    shifted.loc[(df.id != df.id.shift())] = df['x']
    df['diff'] = df['x'] - shifted

if __name__ == '__main__':
    kwargs = {
        'globals': globals(),
        'number': 1000,
        'setup': 'df = make_df()',
    }

    print("original:", timeit.timeit('original(df)', **kwargs))
    print("org_prefill:", timeit.timeit('org_prefill(df)', **kwargs))

    print("unique_keys:", timeit.timeit('unique_keys(df)', **kwargs))
    #print("groupby_iter:", timeit.timeit('groupby_iter(df)', **kwargs))
    print("groupby_return:", timeit.timeit('groupby_return(df)', **kwargs))
    print("groupby_prefill:", timeit.timeit('groupby_prefill(df)', **kwargs))
    print("shifty:", timeit.timeit('shifty(df)', **kwargs))


Notice how the square of a number 15 or greater exceeds 200? What you can do, is set the interval from 1 to 14.
There is no advantage in evaluating the same combination over and over again. Realize that the most efficient way is to structure your for loops such that

$$ a  \leq b  \leq c  \leq d $$

In your attempt, you are iterating 38,416 times!

By limiting the interval, you iterate just 2380 times!

One more thing you can do: check and break when \$a^{2} + b^{2} + c^{2} + d^{2} > 200 \$

for(int a = 1; a<=14; a++)
    for(int b = a; b<=14; b++)
        for(int c = b; c<=14; c++)
            for(int d = c; d<=14; d++){
                if(a*a + b*b + c*c + d*d == 200)
                    cout << "a: " << a << " b: " << b << " c: " << c << " d: " << d << endl;
                else if(a*a + b*b + c*c + d*d > 200)
                    break;
            }

Now you iterate only 1,214 times! This is way more efficient.


Parenting

A node in a tree either has a parent or does not have a parent. It is never its own parent. You default your values to:

node_parent[child] = child

But it would be cleaner to keep them as None. That way, your iteration on parents() would've just been:

def parents(ar, idx):
    while ar[idx] is not None:
        yield ar[idx]
        idx = ar[idx]

Children

You use child and parent in a lot of places where neither makes sense. For example:

for child, parent in enumerate(node_count):

There is no child/parent relationship in that loop. That's confusing. Furthermore, you don't even use the parent part since what you're doing is just iterating over the nodes:

for node in xrange(N):
    if node_count[node] % 2 = 0 and node_parent[node] is not None:
        res += 1

But, more generally...

Global Variables and Data Storage

This solution half-relies on global variables (update_child_count) and half on passing around arguments (parents). It also involves keeping two separate arrays (node_parent and node_count) when there really should be just the one array of both items. It'd be better to better to group these into a class: Node. A Node has two things: a size and a parent:

class Node(object):
    def __init__(self):
        self.parent = None
        self.size = 1 #itself

And it has a way to set its parent - copying the loop I indicated above:

    def add_parent(self, p):
        self.parent = p
        while p is not None:
            p.size += 1
            p = p.parent

This simplifies your algorithm drastically. Now instead of keeping two lists, we just have to keep one:

nodes = [Node() for _ in xrange(N)]

And when we input the child and parent†, we just assign as appropriate:

nodes[child-1].add_parent(nodes[parent-1])

This is more direct than having two functions to do the updating. Then, all we need to do is find all the non-root nodes that have an even size, as you did before. Full solution using your same algo:

class Node(object):
    def __init__(self):
        self.parent = None
        self.size = 1

    def add_parent(self, p):
        self.parent = p
        while p is not None:
            p.size += 1
            p = p.parent

if __name__ == '__main__':
    N, E = map(int, raw_input().split())

    nodes = [Node() for _ in xrange(N)]
    for _ in xrange(E):
        child, parent = map(int, raw_input().split())
        nodes[child-1].add_parent(nodes[parent-1])

    print sum(1 for node in nodes
              if node.size % 2 == 0 and node.parent is not None)

† I'm not convinced that you can necessarily be sure that the child goes first in the inputs. It's not stipulated in the problem and this approach does require that to be true.


Perform a predetermined set of operations on a large sequence

Now that that pesky "Not looking for the review of my code" is gone...

Step 1: White space

Follow the PEP 8 guidelines, specifically (but not limited to) put a space around operators and after commas:

n, k = map(int, input().split())
arr = list(map(int, input().split()))   # read input sequence and store it as list type
for i in range(k):                      # iterate over 0 to (k-1)
    t = i % n                           # module of i wrt n
    arr[t] = arr[t] ^ arr[n - (t) - 1]  # xor between two list elements and then set result to the ith list element
for i in arr:
    print(i, end=" ")                   # print the final sequence

Much easier to read.

Step 2: Avoid multiple lookups

Python is an interpreted language, and the meaning of a line of code -- or even a fragment of code -- can change by the time the interpreter returns to execute the code as second time.  This means the interpreter cannot truly compile the code; unless something is a well defined short-circuiting operation, every operation must be executed.

Consider:

arr[t] = arr[t] ^ arr[n - (t) - 1]

The interpreter must compute the address of arr[t] twice; once to fetch the value, and a second time to store the new value, because some side-effect which occurs during the execution of arr[n - (t) - 1] may change the meaning of arr[t].  In your case, arr is a list, and n and t are simple integers, but with user-defined types, anything can happen.  As such, the Python interpreter can never make the following optimization:

arr[t] ^= arr[n - (t) - 1]

It is a tiny speed-up, but considering the code may execute \$10^{12}\$ times, it can add up.

Step 3: Avoid calculations

Speaking of avoiding work: because we know the length of the array is fixed, arr[n - 1] is the same as arr[-1].  So we can further speed up the line of code as follows:

arr[t] ^= arr[-1 - t]

Instead of two subtractions, we now have only one.  Yes, Python has to index from the back of the array, which internally is going to involve a subtraction, BUT that will be an optimized, C-coded subtraction operation on ssize_t values, instead of subtraction on variable byte length integers, which must be allocated and deallocated from the heap.

Step 4: Printing space-separated lists

The following is slow:

for i in arr:
    print(i, end=" ")

This is faster:

print(*arr)

And for long lists, this may be fastest:

print(" ".join(map(str, arr)))

For a detail discussion, including timing charts, see my answer and this answer on another question.

Step 5: The Algorithm

Consider the list [A, B, C, D, E].

After applying a single pass of the operation on it (ie, k = n), you'll get:

[A^E, B^D, C^C, D^(B^D), E^(A^E)]

which simplifies to:

[A^E, B^D, 0, B, A]

If we apply a second pass (ie, k = 2*n), you'll get:

[(A^E)^A, (B^D)^B, 0^0, B^((B^D)^B), A^((A^E)^A)]

which simplifies to:

[E, D, 0, B^D, A^E]

A third pass, (ie, k = 3*n) gives:

[E^(A^E), D^(B^D), 0^0, (B^D)^(D^(B^D)), (A^E)^(E^(A^E))]

or:

[A, B, 0, D, E]

Now k does not need to be an exact multiple of n, so you'll have to figure out what to do in the general cases, but you should be able to use the above observation to eliminate a lot of unnecessary calculations.

Implementation left to student.


Type checking to perform a variation of the strategy pattern

I don't know if it will be useful for you, but here is one variant:
Add to your Entity base class a method called GetWriter. This method should return IEntityWriter.
This IEntityWriter should have method Write() without parameters.

Then an implementation of an Entity would be something like:

class XXXEntity: Entity
{
   public override IEntityWriter GetWriter()
   {
      return new XXXEntityWriter(this);
   }
}

And then the method WriteEntities in your example would be

public void WriteEntities(IEnumerable<Entity> entities)
{
   foreach(Entity entity in entities)
      entity.GetWriter().Write();
}

The 'mappings' approach (no matter if it is in the code or in the xml file) have a couple of problems:
1. It's easy to do wrong configuration of mappings. You can map a XXXEntity to YYYEntityWriter.
2. It's easy to forget to add an EntityWriter when you add new Entity or you can forget to add the mapping. And this is a real problem.

By the way. Judging from the description of the task, a concrete EntityWriter have to know about a concrete Entity.
So mapping is not as flexible as it seems, because of this explicit connection between EntityWriter and Entity.
It's not a problem to use GetType(). The problem here is to separate (hide) connections between classes that should work together.


First off this is a C solution there is nothing inherently C++ about this code. You just seem to be using the output stream. We refer to this as kind of code (in the C++ community) as C with classes. Note this is not a good designation.

As C and C++ are completely different languages with different styles and idioms you should not write a piece of code for one and expect it to be good code in the other language. The fact that the compiler may compile it is just a historical artifact. You should remove one of the tags from question (Since it will not compile as C I suggest you remove the C tag).

Since the question is tagged C++ I will review your code as a C++ program and point out why it is badly designed.

Never do this:

using namespace std;

See: Why is “using namespace std;” considered bad practice?

Useless comments are worse then no comments.

/* C++ Function to print leaders in an array */
void printLeaders(int arr[], int size)

I don't need a comment to tell me this. The name of the function and its parameters are actually very well named. Restrict your comments to a description of why (the code describes how) and well named functions and variables describe what is happening.

C++ code prefers to use iterators it situations like this.

void printLeaders(int arr[], int size)

The problem here is that it is so easy to use this incorrectly. Arrays decay into pointers way to easily. If you use the iterator interface this will prevent this happening accidentally.

template<typename I>
void printLeaders(I begin, I end) {
    // Code
}

// Calling:
int arr[] = {16, 17, 4, 3, 5, 2};
printLeaders(std::begin(arr), std::end(arr));
// If you change the code now and accidentally cause the array to decay into a
// pointer then the compiler will generate a compile time error. The current
// code is way to susceptible to refactoring mistakes.

// Also it allows you to use any container that supports the iterator
// interface (which is all of them including built in array).

You have forgotten to validate your input.

    int max_from_right =  arr[size-1];

If the size is zero. Then this is undefined behavior.

I know you are printing here.
But that looks like for de-bugging.

        if (max_from_right < arr[i])
        {
            max_from_right = arr[i];
            cout << max_from_right << " ";
        }

You could just use std::max() to simplify the code.

You should basically never use the built in array.

    int arr[] = {16, 17, 4, 3, 5, 2};

The container library contains several classes for storing a set of obejcts that are better. std::vector<int> for dynamically sized objects or std::array<int,size> for fixed size containers.

Built in arrays are hard to use correctly. Passing them by reference the syntax is non-trivial. They decay into pointers way to easily. Getting the size of an array is obnoxious as you have to remember to plant the correct division that is easy to mistype (with no compiler checking).

No need to return 0 at the end of main (its special).

    return 0;

Normally in C++ you leave out the return value to indicate that main can never fail. If you explicitly plant return 0 here it is an indication that it succeeds but also a hint there are other return paths that will fail (so I start looking for other return statements in main())