Here is some advice for your code.

General recommendations

1) For readability, I suggest that you change the way that you create your arrays; since the "C-style" array declaration is harder to read and less used in Java, in my opinion.

Before

int y[] = {};

After

int[] y = {};

2) In my opinion, I suggest that you wrap the logic of the condition / loop with braces, even if there's only one line of code; this provide consistency and prevent probable bugs if you want to add code to the condition and forget to add the braces.

Before

if (t[i] == 0)
  c++;

After

if (t[i] == 0) {
  c++;
}

getWinRate method

1)  Since the comb is always the same, I sugest that you extract it in a constant.

public class AI {
   //[...]
   private static final int[][] COMB = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}};
   //[...]
}

2) Instead of using a series of if on a value that can have only one of the values, I suggest that you use the if-else or a switch statement and extract the evaluation of t[d] in a variable.

Before

if (t[d] == 2)
   AIwin++;
if (t[d] == 1)
   oppWin++;
if (t[d] == 0)
   empty++;

if-else

int currentValue = t[d];
if (currentValue == 2)
   AIwin++;
else if (currentValue == 1)
   oppWin++;
else //Zero
   empty++;

or

switch

switch (t[d]) {
   case 2:
      AIwin++;
      break;
   case 1:
      oppWin++;
      break;
   default: //Zero
      empty++;
      break;
}

play method

1) In my opinion, instead of cloning an array, you can use java.util.Arrays#copyOf(int[], int).

   int[] t = Arrays.copyOf(t1, t1.length);

2) The j variable is unused.

3) I suggest that you use better names for your variable, it makes the code harder to read.

4) In my opinion, you can extract some of the logic into sub-methods.

a) Create a method to calculate the number of available moves.

private int calculateNumberOfEmptySpace(int[] game) {
     int nb = 0;

     for (int i = 0; i < 9; i++) {
         if (game[i] == 0) {
             nb++;
         }
     }

     return nb;
 }
 //[...]
void play(int[] t1) {
   int[] copyOfTheGame = Arrays.copyOf(t1, t1.length);
   int numberOfPossibleMoves = calculateNumberOfEmptySpace(t1);
}

5) The index in the last loop is not used, you can use a for-each

Before

for (i = 0; i < moves.length; i++) {
   boardcopy = t.clone();
   boardcopy[moves[i]] = 2;
   rate = getWinRate(boardcopy);
   if (rate > maxRate) {
     maxRate = rate;
     bestMove = moves[i];
  }
}

After

for (int move : moves) {
   boardcopy = t.clone();
   boardcopy[move] = 2;
   rate = getWinRate(boardcopy);
   if (rate > maxRate) {
     maxRate = rate;
     bestMove = move;
  }
}


Guessing Game: computer generated number between 1 and 100 guessed by user

The pythonic way to do count = count + 1 is count += 1
You don't need to repeat the 'guess again' part of the game twice:

if guess > val:
    print("Too high. Try again:", guess)
elif guess < val:
    print("Too low. Try again:", guess)
guess = int(input("\n\t\tEnter a number between 1 and 100: "))
count += 1
if guess == val:
    print("\nCongratulations! You got it in", count, "guesses.")
    break

You don't need to add the extra if statement because if guess != val, then the loop with break anyway:

while guess != val:
    if guess > val:
        print("Too high. Try again:", guess)
    elif guess < val:
        print("Too low. Try again:", guess)
    guess = int(input("\n\t\tEnter a number between 1 and 100: "))
    count += 1
print("Congratulations! You got it in", count, "guesses.")

I think print("randint is", val) was probably for testing purposes, but it's still in your code!
If you execute your program outside the command module (I'm not quite sure what it's called), the program will close immediately after it's finished; it's always best to give the user the choice of when to quit, so insert this at the end of your code:

input("Press enter to quit")

The first section is unneeded:

def main():`, `if __name__ == "__main__":

The first if statement is also unneeded:

if guess == val:

You don't need to define guess = 0 the first time.

So, all in all, my improvement of your code is:

import random
print("Time to play a guessing game.")
val = random.randint(1, 100)
count = 1
guess = int(input("\n\t\tEnter a number between 1 and 100: "))
while(guess != val):
    if guess > val:
        print("Too high. Try again:", guess)
    elif guess < val:
        print("Too low. Try again:", guess)
    guess = int(input("\n\t\tEnter a number between 1 and 100: "))
    count += 1
print("\nCongratulations! You got it in ", count, " guesses.")
input("Press enter to quit.")


Since the split files do not need to be readable text files, I would read & write in chunks of bytes, not in lines. This should be faster than reading and writing line by line. We can go with a chunk size of 4,096 bytes because 4,096 or 8,192 is a typical block size on most file systems.
Although, I should note that when I tested your script on my system with a 9 GB text file which has 81 characters per line, it took about 73 seconds to split it into files of 10,000,000 lines each, or about 772 MB per file. The fact that it takes 12 minutes on your laptop likely confirms @Graipher's suspicion that your disk's write speed is the bottleneck here.
Using a refactored version of your script that reads & writes in byte chunks (provided at the end of this review), when I ran it on the same file with --size 772 (split into files of size 772 MB) it took about 35 seconds. Still a decent improvement, but I'd be curious to know how it runs on your machine.
To implement this, I personally like having a helper method like the following which tells us the chunk sizes to read/write:
from typing import Iterator

def chunk_sizes(total_bytes: int, chunk_size: int) -> Iterator[int]:
    for _ in range(total_bytes // chunk_size):
        yield chunk_size

    if remaining_bytes := total_bytes % chunk_size:
        yield remaining_bytes

For example, list(chunk_sizes(10000, 4096)) which returns [4096, 4096, 1808] would tell us that in order to read 10,000 bytes in 4,096 byte chunks, we should read 4,096 bytes, followed by another 4,096 bytes, followed by 1,808 bytes.
General review

There's no reason to have run() be a staticmethod, and it's weird how FileSplitter creates an instance of itself inside this method.
If you change the top-level invocation to FileSplitter().run() then run() could be simplified to
def run(self):
    self.split()

But if you do that you might as well remove run() and make FileSplitter().split() the top-level call. My recommendation is to move the contents of run() under the __name__ == "__main__" guard and then remove run() entirely as it's no longer needed.

Always open files with a with block to ensure the file is closed properly.

I recommend using argparse because you get a lot of stuff for free (input type validations, help/usage message with -h, etc.).

I would move the command-line argument parsing logic out of FileSplitter, because it should ideally only have one responsibility: splitting files.

Specify the exact exception you want to handle with a try-except. Handling a bare except is considered a bad practice.

I wouldn't use sys.exit inside methods you might want to test, because it exits the Python interpreter.

In Python 3, f-strings are a much more legible way of doing string interpolation.
Before
new_file_name = "%s.%s" % (self.file_base_name, str(file_number))

After
new_file_name = f"{self.file_base_name}.{file_number}"

Refactored version
#!/usr/bin/env python3

import argparse
import gzip
import os
import itertools

from typing import BinaryIO, Iterator

CHUNK_SIZE = 4096  # bytes

def megabytes_to_bytes(megabytes: int) -> int:
    return megabytes * 1024 * 1024

def chunk_sizes(total_bytes: int, chunk_size: int) -> Iterator[int]:
    for _ in range(total_bytes // chunk_size):
        yield chunk_size

    if remaining_bytes := total_bytes % chunk_size:
        yield remaining_bytes

class FileSplitter:
    input_file_path: str
    output_directory: str
    output_file_base_name: str
    split_size: int  # size of each partition, in MB

    def __init__(
        self, input_file_path: str, output_directory: str, split_size: int
    ) -> None:
        self.input_file_path = input_file_path
        self.output_directory = output_directory
        name = os.path.basename(input_file_path)
        name_without_file_extension = os.path.splitext(name)[0]
        self.output_file_base_name = name_without_file_extension
        self.split_size = split_size

    def get_new_file(self, file_number: int) -> BinaryIO:
        new_file_name = f"{self.output_file_base_name}.{file_number}"
        new_file_path = os.path.join(self.output_directory, new_file_name)
        return open(new_file_path, "wb")

    def split(self) -> None:
        bytes_per_file = megabytes_to_bytes(self.split_size)
        os.makedirs(self.output_directory, exist_ok=True)

        with gzip.open(self.input_file_path, mode="rb") as in_file:
            for file_number in itertools.count(start=1, step=1):
                with self.get_new_file(file_number) as out_file:
                    for chunk_size in chunk_sizes(bytes_per_file, CHUNK_SIZE):
                        chunk = in_file.read(chunk_size)
                        # chunk == "" means we finished reading the input file
                        if not chunk:
                            return
                        out_file.write(chunk)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Read a gzip-compressed file "
        "and split its uncompressed contents into separate files."
    )
    parser.add_argument(
        "file_name", help="a gzip-compressed file, e.g. foo.gz"
    )
    parser.add_argument(
        "--size",
        type=int,
        default=500,
        help="desired size of each partition, in MB",
    )
    args = parser.parse_args()

    output_directory = os.path.join(os.getcwd(), "pychunks")
    splitter = FileSplitter(args.file_name, output_directory, args.size)
    splitter.split()


Removal of subtrees in tree on condition optimally

Data Structure

You don't have a Tree of nodes; you have a List of nodes which describes a tree-like structure in a serialized format.  This is fine for storing the tree of nodes in a flat database table, but it is not a Tree.

Traversing a Tree can be done in \$O(N)\$ time.  Your Depth-First-Search traversal of the List of nodes requires searching the list of nodes repeatedly, once for every node in the list.  This makes the algorithm \$O(N^2)\$.

To properly make your tree, you'd need each node to have its own (possibly empty) list of child nodes:

class Node {
    Node parent = null;
    List<Node> children = new ArrayList<>();
}

A depth first search of this tree could then be performed in \$O(N)\$ time.

Code Review

tree1 and newTree don't reflect a consistent naming strategy.  tree1 and tree2, or oldTree and newTree would be better.

You use tree1.get(0) four times, to get the root node of the tree.  Why not store the root node in a variable?

Node root = tree1.get(0);

Is tree1.get(0) the root node?  Always?  It looks like you make no assumptions of the order of the nodes in the List<Node> structure.  You should probably search for the node with the null parent identifier:

Node root = tree1.stream()
                 .filter(node -> node.parentId == null)
                 .findFirst()
                 .get();

Will the tree always have a root node?  If your processing removes all node, and then you call .get(0) on the resulting list, you'll get an IndexOutOfBoundsException.

You repeat this code:

    if(tree1.get(0).rank != 1 || tree1.get(0).getNumberOfValidSubtrees() != 0) {
        newTree.add(tree1.get(0));

here:

        if(child.rank != 1 || child.getNumberOfValidSubtrees() != 0) {
            // ...
            newTree.add(child);

If your traverse() method actually operated on parent instead of the parent's children, you wouldn't need to duplicate code.

Also, if the traverse() method operated on the parent, it could maintain a count of the subtrees, and you wouldn't need to pollute the Node class with numberOfValidSubtrees.

Moving on to class Node:

Why is the numberOfValidateSubtrees member private, but none of the other members (id, parentId, rank) are?

Should id and parentId be final?  How about rank?

Inconsistent this. usage: You do not need it in getNumberOfValidSubtrees() and in incrementValidSubtree() methods.  OR, you should also use it in getId() and toString().

You can remove the this.numberOfValidSubtrees = 0; initialization by providing the initial value in the declaration:

private int numberOfValidSubtrees = 0;

Suggestions

Will it always be rank == 1 nodes with no subtrees that are deleted?  A more elegant solution would be to allow a Predicate<Node> argument which would return true if a node was to be deleted.

static boolean isRank1WithNoSubtree(Node node) {
    return node.rank == 1  &&  node.children.isEmpty();
}

static void removeDFS(Predicate<Node> predicate) {
    // ...
}

public static void main(String[] args) {
    // ...
    removeDFS(Main::isRank1WithNoSubtree);
    // ...
}

But there are multiple ways of traversing a tree.  Perhaps you would be better with defining methods which traverse the tree, each which take a Consumer<Iterator<Node>> action argument, to call on each tree node as it is visited.

static void removeIfRank1(Iterator<Node> iter) {
    Node node = iter.next();
    if (node.rank == 1  &&  node.children.isEmpty())
        iter.remove();
}

static void traverseDFS(Consumer<Iterator<Node>> action) {
    // ...
}

public static void main(String[] args) {
    // ...
    traverseDFS(Main::removeIfRank1);
    // ...
}

Node -vs- Tree

Personally, I like to draw a distinction between a Node and a Tree.  A tree may be a collection of nodes, each node optionally containing more child nodes.  But the root node is NOT the tree.  The Tree itself can contain additional information about itself, such as the number of nodes it contains.  The Tree class would have methods for adding nodes, removing nodes, traversal, filtering, etc., instead of having to tack those methods on to either the Node class or the Main class.  Eg):

class Tree<E> {

    class Node<E> {
        Node<E> parent = null;
        List<E> children = new ArrayList<E>();
        E data;

        Node(E e) {
            data = e;
        }
    }

    Node<E> root = null;
    int numNodes = 0;

    void traverseDFS(Consumer<Iterator<Node>> action) {
        // ...
    }
}


A data structure with push(int x), pop(), min() and max() in O(1)

Your MyDS class has the right idea, in general.

Special values like -1, Integer.MIN_VALUE, and Integer.MAX_VALUE make me suspicious.  All of those special values denote what I consider to be error cases.  Using special cases that might also be valid data is a dangerous habit that can lead to bugs.  Instead of those special numbers, it would be better to throw exceptions — probably NoSuchElementException.  You should also offer a size() and/or an isEmpty() method so that users of your data structure can proactively avoid encountering the exception.

The three instance variables should be private.  The default access is rarely appropriate.  java.util.Stack is to be avoided, due to unfortunate historical design decisions (inappropriately extending java.util.Vector, and being thread-safe by default).  The documentation recommends ArrayDeque instead.

Of the four operations in MyDS, I think pop() could use the most work.    It's weird that pop() doesn't return a value.  The -1 is entirely avoidable: if the main stack is empty, the min and max stacks should surely be empty too.

public int pop() {
    if (s.isEmpty()) {
        throw new NoSuchElementException();
    }
    int popped = s.pop();
    if (popped == min()) {
        minStack.pop();
    }
    if (popped == max()) {
        maxStack.pop();
    }
    return popped;
}


Equated Monthly Installment (EMI) for Home Loan and Amortization Schedule

var
Particularly given that you have accuracy issues, it's important for your own understanding of what the code does to be explicit in the following declarations:
    var monthlyRepaymentAmount = HousingLoanInterest(principal, interestRatePerAnnum, years);
    var tenure = years * 12;
    var principalAndInterest = CompoundInterest(principal, interestRatePerAnnum, 12, years);

From these lines alone, I have no idea if these are supposed to be doubles, integers, decimals, etc. Just spell out the actual type.
In-place operations
        totalRepaymentAmount = totalRepaymentAmount + (decimal)monthlyRepaymentAmount;
        tenure = tenure - 1;

can be
totalRepaymentAmount += monthlyRepaymentAmount;
tenure--;

Formatting
This could benefit from some temporary variables, but even without them,
    return (loanAmount * Math.Pow((interestRate / 12) + 1,
         (years * 12)) * interestRate / 12) / (Math.Pow
         (interestRate / 12 + 1, (years * 12)) - 1);

is more legible as
return (
    loanAmount * Math.Pow(
        interestRate / 12 + 1,
        years * 12
    ) * interestRate / 12
) / (
    Math.Pow(
        interestRate / 12 + 1,
        years * 12
    ) - 1
);

which in turn is equivalent to
double annual = interestRate / 12;
double pow = Math.Pow(
    annual + 1,
    years * 12
);
return loanAmount * pow * annual / (pow - 1);

Simpler yet:
double annual = interestRate / 12,
       pow = Math.Pow(
           annual + 1,
           -12 * years
       );
return loanAmount * annual / (1 - pow);

Please test this for equivalence.


Meta-circular interpreter for lambda calculus in Python

I don't quite know what lambda calculus is (I'm assuming it's a mathematical annotation for what we might call "purely functional programming"?), but I'll give this a quick shot.

First, I'd love to have env populate itself if not provided. You really shouldn't have mutable default values for functions, though; the typical practice is to define:

interp(self, env=None):
    env = env or {}
    # ...

but that's really bloat'y in this case, so let's use a little inheritance:

class Op:
    def interp(self, env=None):
        return self._interp(env if env is not None else {})

    def _interp(self, env):
        raise NotImplementedError()

class Cons(Op):
    def __init__(self, v):
        self.v = int(v)

    def _interp(self, env):  # update name to "_interp"
        return Num(self.v)

# ...

print(expr.interp())  # Yay for no boilerplate arguments!

Now we can just call interp() and the rest handles itself.

The next thing I'd do to make things a bit more concise is to leverage Python 3.7's new dataclass feature; while this doesn't seem to remove any lines of code, it's certainly more concise and descriptive, and adds some useful meta-features like allowing our AST objects to be intelligently compared and printed:

from dataclasses import dataclass

# ...

@dataclass
class App(Op):
    fun: Lam
    param: Op

    def _interp(self, env):
        return self.fun.interp(env)(self.param.interp(env))

@dataclass
class Add(Op):
    a: Op
    b: Op

    def _interp(self, env):
        return add(self.a.interp(env), self.b.interp(env))

# ...

print(expr)
# App(fun=Lam(arg='x', body=Add(a=Var(x='x'), b=Var(x='x'))), param=Add(a=Cons(v=10), b=Cons(v=11)))

Moving beyond Add, we can start using inheritance to make things clearer and more concise:

@dataclass
class BinOp(Op):
    a: Op
    b: Op

    @staticmethod
    def _func(v1, v2):
        raise NotImplementedError()

    def _interp(self, env):
        return self._func(self.a.interp(env), self.b.interp(env))

class Add(BinOp):
    @staticmethod
    def _func(v1, v2):
        return Num(v1.v + v2.v)

class Sub(BinOp):
    @staticmethod
    def _func(v1, v2):
        return Num(v1.v - v2.v)

Some minor nit-pick details to finish off:

4-space indentation is more common than 2-space, which can look a bit cramped.
I'm not sure if it's typically allowed in lambda calculus, but I'd like to see Lam/functions that can take any number of arguments (I have a working implementation that's pretty clean that I'd be happy to share if you're interested).


First, note that with code like this that has to read in external input, and convert it into objects, you typically end up with some sort of factory class that's kind of the border where you often have difficulty applying the open-closed principle very well. That is, it often needs at least a little tweaking when the rest of the system changes--about the best you normally hope for is to restrict your changes to this one area.

So, what I'd probably do in this case is have a single "stack manipulator" interface, and have both an operand and operators that implement that interface.

// Note: this isn't intended to be compilable code, just pseudo code with
// syntax similar to Java/C#/C++/etc.
//
interface stack_manipulator {
    void execute(stack);
};

class operand : implements stack_manipulator {
    void execute(stack s) {
        s.push(this);
    }
};

class add : implements stack_manipulator {
     void execute(Stack s) {
         // skipping error checking and such for clarity
         var a = s.pop();
         var b = s.pop();
         s.push(a + b);
     }
};

class sub : implements stack_manipulator {
    void execute(Stack s) {
        var a = s.pop();
        var b = s.pop();
        s.push(a - b);
    }
};

// ... and so on for other operators

Then your ITerm CalculatePostfixExpression would look something like this:

    var tempResult = new Stack<ITerm>();
    foreach (var term in input) {
        term.execute(tempResult);
    }
    return tempResult.Peek();

...and modifications to the other code won't require changes to this (as long as the other code adheres to the stack_manipulator interface. As hinted at above, however, somewhere you'll need a factory class that knows how to map from input characters to the individual types that implement the stack_manipulator interface.


Problems

There was a bug in Booster.raf in the else block you have this.run().bind(this) and I assume you mean this.run.bind(this)() though the binding is not needed because you are in the context of this so this.run() will do just fine.

You throw in two places yet ignore many problems that can be introduced by not vetting at the interface. There should be more checking when setting the Booster state. Eg amount should be a Number, should not be less than 0. Booster.remove(n) n could be a fraction, you should ignore or truncate floats.

It is possible for a function to execute even after Booster is paused. This will happen if pause() is called after the event is triggered. The run function should make sure that you do not run in paused state.

If any of the given functions throw an error then all remaining function on the fn array will not be executed. Nor do you check if any of the functions given are actually functions. This will also prevent functions after the bad function from being called.

You do not check if Booster.view has the function addEventListener. In Booster.throttle this will result in the Booster object incorrectly setting the active state to true.

It is possible to have more than one event listener if Booster.init is called more than once. Because you only have one Booster.timeout property the Booster.throttle function can overwrite the Booster.debounce timeout property preventing debounce from working correctly (and debounce can stop throttle timeouts breaking throttling)

Design
The logic is not fully thought out. It is always important to test your code for behaviour that are not expected.
I can not tell if you expect init to be called again after construction. The fact that it is outside the constructor suggests so. If this is the case, why are you not providing a way to remove listeners. Calling init will just keep adding listeners and because the added listeners are anonymous there is no way to remove them.
I do not know how many events you are expecting to intercept or delay, but any more than a few and you would be much better of running a continuous rAF loop and handling all the needed events in that one function.
Review by comments.
All comments within /* ... */ are added as I went over the code, and other comments are me modifying your code by removal. The comments are generally unrelated suggestion and were created before I wrote the review above.
export default class Booster {

  constructor(method, type, amount, ...fnArray) {
    this.view = window;
    this.type = type;     /* type of what? bad naming maybe eventType */
    this.amount = amount; /* amount? bad naming maybe bebounceDelay */
    /* fn will always be an array as you have defined it as so in the arguments
       this.fn = fn ? fn : [];  // bad naming use plural or indicate its an array
       Use existing methods */
    // this.fnArray = fnArray;
    this.add(fnArray);
    /* Use existing methods */
    //this.paused = false;
    this.pause();
    this.method = method; /* method? bad naming maybe methodType */
    this.runBound = this.run.bind(this);  /* Only need to bind once */

    /* calling init in the constructor always seams such a silly thing to
        do especially when init does not actually init the class */
    /* Use a setter to set the method */
    // this.init();
  }
  /* Use a setter to set method and remove init as it is not needed */
  set method(type) {
    if      (type === 'throttle') { this.throttle(); }
    else if (type === 'debounce') { this.debounce(); }
    /* Why throw, You are not in control of the calling function so how do you know it
        will be caught. Throwing will stop executing code and in production if
       not caught end up in a non functioning page.
       Degrade gracefully, don't fall in a heap at the slightest fault. */
    else  { console.warn("Invalid Booster method. Must be \"throttle\" or \"debounce\".") }
    //  else { throw new Error('Invalid Booster method. Must be "throttle" or "debounce".'); }
  }
  raf() {
    if (this.view.requestAnimationFrame) {
      this.view.requestAnimationFrame(this.runBound);
    } else {
      /* Run then bind ?????   you had this.run().bind(this);
         maybe you meant this.run.bind(this)(); */
      this.run();
    }
  }

  run() {
     /* Don't need to check if zero. For each will do that for you */
    // if (0 < this.fn.length) {
    /* try to avoid callback iterators as they are slower than for loops */
      //this.fn.forEach(function(fn) {
      //  fn();
      //});
    /* a better way to iterate
    for(const fn of this.fnArray){ fn() }  */
  }

  throttle() {
    this.active = true;
    this.view.addEventListener(this.type, () => {
      if (this.active && !this.paused) {
        this.active = false;
        this.raf();
        this.timeout = setTimeout( () => {
          this.active = true;
        }, this.amount);
      }
    }, false);
  }

  debounce() {
    this.view.addEventListener(this.type, () => {
      if (!this.paused) {
        clearTimeout(this.timeout);
        this.timeout = setTimeout( () => {
          this.raf();
        }, this.amount);
      }
    }, false);
  }

  add(...fnArray) { this.fnArray.push(...fnArray); }
  remove(n) {
    if (n >= 0 && n < this.fn.length) {
      this.fn.splice(n, 1)
    }
    /* Again you are not in control of calling code and can not know
      if this will be caught. I dont think this is even worth a warning  */
  //    else {
  //  throw new Error('There are only ' + this.fn.length + ' functions in this Booster.');
    //}
  }

  pause()    { this.paused = true;}
  resume()   { this.paused = false; }
  toggle()   { this.paused = !this.paused; }

  /* removed as not needed, see setter set method */
  //init() {
  //  if      ('throttle' === this.method) { this.throttle(); }
  //  else if ('debounce' === this.method) { this.debounce(); }
  //  else { throw new Error('Invalid Booster method. Must be "throttle" or "debounce".'); }
  //}
}


This program is really a pleasure to read. It accomplishes the desired outcome neatly and succinctly. The only thing I could think of that might be an improvement is threading. Other than that this program looks fantastic.

I can see where making this program threaded can be a great benefit when dealing with smaller files. I'm not sure, but I fear with larger files or smaller buffering, having this program run copy routines in parallel might bring the system to a halt. I wrote up a minor modification to your excellent source code to illustrate my idea:

""" Simple backup script which just creates the root structure in an other
folder and syncs everything which recursevely lies within one of the source
folders. For files bigger than a threshold they are first gziped."""

import argparse
import gzip
import os
import shutil
import sys
import threading

def parse_input():
    parser = argparse.ArgumentParser()
    parser.add_argument('-target', nargs=1, required=True,
                        help='Target Backup folder')
    parser.add_argument('-source', nargs='+', required=True,
                        help='Source Files to be added')
    parser.add_argument('-compress', nargs=1,  type=int,
                        help='Gzip threshold in bytes', default=[100000])

    # no input means show me the help
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()

    return parser.parse_args()

def size_if_newer(source, target):
    """ If newer it returns size, otherwise it returns False """

    src_stat = os.stat(source)
    try:
        target_ts = os.stat(target).st_mtime
    except FileNotFoundError:
        try:
            target_ts = os.stat(target + '.gz').st_mtime
        except FileNotFoundError:
            target_ts = 0

    # The time difference of one second is necessary since subsecond accuracy
    # of os.st_mtime is striped by copy2
    return src_stat.st_size if (src_stat.st_mtime - target_ts > 1) else False

def threaded_sync_file(source, target, compress):
    size = size_if_newer(source, target)

    if size:
        thread = threading.Thread(target=transfer_file,
                                  args=(source, target, size > compress))
        thread.start()
        return thread

def sync_file(source, target, compress):
    size = size_if_newer(source, target)

    if size:
        transfer_file(source, target, size > compress)

def transfer_file(source, target, compress):
    """ Either copy or compress and copies the file """

    try:
        if compress:
            with gzip.open(target + '.gz', 'wb') as target_fid:
                with open(source, 'rb') as source_fid:
                    target_fid.writelines(source_fid)
            print('Compress {}'.format(source))
        else:
            shutil.copy2(source, target)
            print('Copy {}'.format(source))
    except FileNotFoundError:
        os.makedirs(os.path.dirname(target))
        transfer_file(source, target, compress)

def sync_root(root, arg):
    target = arg.target[0]
    compress = arg.compress[0]
    threads = []

    for path, _, files in os.walk(root):
        for source in files:
            source = path + '/' + source
            threads.append(threaded_sync_file(source,
                           target + source, compress))
#            sync_file(source, target + source, compress)
    for thread in threads:
        thread.join()

if __name__ == '__main__':
    arg = parse_input()
    print('### Start copy ####')
    for root in arg.source:
        sync_root(root, arg)
    print('### Done ###')


If object is either nil or a string, you can just do value = object || "".

If it can be anything and you want to get a string, your second solution doesn't actually do what you want, since it won't turn the object into a string if it's not nil. To fix that your second solution would become value = object.nil? ? object.to_s : "". Of course since now you're calling to_s in both solutions there is no reason to prefer the second over the first, so I'd go with the first.


LeetCode: Divide Array in Sets of K Consecutive Numbers C#

Here's some C# in accordance with my first suggestion of sorting the array and looping.

public bool IsPossibleDivide(int[] nums, int k)
{
    if (nums.Length % k != 0)
    {
        return false;
    }

    var dict = new Dictionary<int, int>();
    foreach (var num in nums)
    {
        if (!dict.TryGetValue(num, out var value))
        {
            value = dict[num] = 0;
        }

        dict[num] = value+1;
    }
    Array.Sort(nums);

    for (int i = 0; i < nums.Length; i++)
    {
        var currVal = nums[i];
        if(dict[currVal] > 0)
        {
            for(int j = 0; j < k; j++)
            {
                if(!dict.ContainsKey(currVal + j))
                {
                    return false;
                }
                dict[currVal + j]--;
            }
        }
    }

    return true;
}

This is significantly faster, and is O(nlogn), as I say I think there's a O(n) solution but I'm not really sure of the exact details and I don't know much C#, probably I could write it in JS if you like.

As I say, this

int start = dict.FirstOrDefault(x=>x.Value >0).Key;

looks bad to me because once you've done a good number of the consecutive numbers, it might start having to look through a lot of the dict.


Find the most frequent integer in an array

Your original Python code translates line-for-line into C++11 as:

#include <iostream>
#include <map>
#include <tuple>
#include <vector>

int main()
{
    std::vector<int> lst = {1,2,4,3,1,3,1,4,5,15,5,2,3,5,4};
    std::map<int, int> mydict = {};
    int cnt = 0;
    int itm = 0;  // in Python you made this a string '', which seems like a bug

    for (auto&& item : lst) {
        mydict[item] = mydict.emplace(item, 0).first->second + 1;
        if (mydict[item] >= cnt) {
            std::tie(cnt, itm) = std::tie(mydict[item], item);
        }
    }

    std::cout << itm << std::endl;
}

The only newly introduced lines here are the #include lines, the lines that define main(), and a couple of closing curly braces.

Your C++ code could definitely be cleaned up by removing a lot of its blank lines and premature declarations; for example, there's no need to put a blank line in between every pair of declarations, and there's no need to pre-declare item outside the for-loop. Just tightening up the style (whitespace and such) will go a long way toward readability.

You have a bug on this line:

it->second = it->second++;

In C++, it->second++ is a side-effecting expression: it means "actually increment it->second, and then return the old value." So (in C++11 and C++14), this statement as a whole has undefined behavior: it's telling the compiler that you want to increment it->second, but also assign a new value to it->second.

In C++17, this statement may or may not have defined behavior; I'll have to read up on it and get back to you. Certainly it->second++ is guaranteed to be evaluated prior to the assignment, but I don't know if that completely solves the problem.

Anyway, what you meant to write was simply

it->second = it->second+1;

or

++it->second;

Stylistically, I advise writing "increment thing" instead of "thing increment", intuitively because that's how English works, but also because it can be an optimization in some cases involving overloaded operator++ (and is never a pessimization).

Your code actually doesn't compile with any C++11 compiler I have access to, because of your misuse of the std::make_pair function template. You wrote

std::make_pair<std::string, int>(item, 0)

but you should have written

std::make_pair(item, 0)

so that the compiler would deduce the types for you. (And in this case it deduces std::make_pair<std::string&, int>; but you as the programmer shouldn't have to care about that. Just let the compiler do its job and you try to stay out of its way as much as possible.)

The function parameters argc and argv are unused, so you should get rid of them. int main() is perfectly fine in both C and C++.

I don't understand why you write using std::cout; but then proceed to use the fully qualified names of std::string, std::make_pair, and so on. I would think that you'd either use the fully qualified names of everything from std:: (my preferred choice), or else go all out and using std::... a ton of things.

Anyway, using std::cout doesn't save you any typing — it actually costs you two lines and about 10 characters — so you'd do well to get rid of it.

As far as improving your C++ skills to the point where you can translate Python line-for-line as I did above, the best advice I can give you is go to cppreference.com and study the standard library! The STL is way better today than it was in 2003, and it takes ideas from many other languages. So for example the C++ equivalent of mydict.get(item, 0) is this humongous ugly expression mydict.emplace(item, 0).first->second (and I'm not actually saying you should write that ugly expression in production code!), but it does exist, and translation from Python to C++ is just a matter of being able to remember vaguely what it's called and look it up. And that just takes a lot of practice.


Find the smallest number of square numbers to create n

Your solution seems to be the most efficient, except for the fact that it doesn't seem to work. You could try finding all possible groups like so:

$$18=4^2+1^2+1^2$$

$$18=3^2+3^2$$

$$18=3^2+2^2+2^2+1^2$$

$$...$$

Then find the smallest group.

Your code would sure like some space. After some nice, wide spacing:

public static int solution(int number) {
    int squareCount = 0;
    while(number > 0){
        int square = (int) Math.sqrt(number);
        squareCount++;
        number -= square * square;
    }
    return squareCount;
}

I will post a possible solution after I figure one out.


When comparing actual values use .equals instead of ==

Pay attention to the == java operator, it compares the value of two object references instead of the actual value.

For example your variables are stored in memory like this:

0x000 "string1" //stored in String operator
0x001 "string2"
0x002 "string3"
0x003 "string1" //stored in String temp
0x004 "string2"
0x005 "string3"

Performing operator == temp translates to "is 0x000 equal to 0x003?", while performing operator.equals(temp) translates to "is 'string1' equal to 'string1' ?"

In other words, use == only if you want to check if two objects are exactly the same objects in the same location in memory


Motorcycle rental station with flyweight pattern

The flyweight pattern exists to minimize memory usage. I don't think it is what you need here. At least, wha you have done looks like strategy.

But because your are asking about the flyweight let me try to explain a good usage of it. The goal of the flyweight is to reduce memory usage. The idea is to have something like a date stamp that you can reuse to print differents dates. You take your stamp, roll the numbers to have the expected date, apply it and then forgot or use the same for another date.

public class DateStamp {
  private int year, month, day;
  // setters
  public void apply() {
    System.out.printf("%1$d/%2$d/%3$d", year, month, day);
  }
}

// ..
DateStamp stamp = new DateStamp();
stamp.set..
stamp.apply();

stamp.set..
stamp.apply();

In many systems today, this pattern is rarely used due to the hughe amount of availables memory. Creating new instances is almost no cost.
But when the creation of a new instance can be costly or when you have hundreds instances of the same type at the same time it can be interesting to use it.

About your code and implementation of the factory, there is nothing wrong with the map. It is the best structure to keep a "relation" between two things.

Another implementation, would be to use an abstract Bike as explained by BKSpurgeon.


First attempt at a pure JavaScript slider

I would suggest wrapping this whole thing in an IIFE such that you can modularize all of your slide show functionality into its own scope.

That might look like this:

(function() {
    // your javascript code
}())

This would prevent you from defining a bunch of variables in global scope which could interact negatively with other javascript on a page where you want to insert the slide show.

I agree with other answer about removing styling for .controls into CSS.  You don't use this DOM collection anywhere else in your code, so why have it in JS at all?

You might consider separating the logic for hiding/showing slides into a separate method from goToSlide(). This allows goToSlide() to just focus on setting current slide index and calling appropriate hide/show methods.

I worry about writing to className as you could clobber any other classes that had been applied to a slide element. Since it seems like your code is really only worried about adding/removing showing, consider accessing classList on the element to add/remove this class only.

I would probably place the logic related to "wrapping" index values into the next/previous convenience function and let goToSlide() do one thing only - show the slide index as given.

Consider throwing an error for an illegal slide index passed to goToSlide(), since this function is exposed publicly.

If you truly want to make this code re-usable, you may want to consider making this functionality into a proper "class" and internalize all references to state and DOM bindings.  This would allow you to place multiple instances of these slide shows onto a page at once.

Putting it all together might yield something like:

// you could have this class defined in an externally included file
function Slider(slideSelector, nextId, prevId, toggleClassName) {
    this.currentIndex = 0;
    this.slides = querySelectorAll(slideSelector);
    this.next = getElementById('#' + nextId);
    this.prev = getElementById('#' + prevId);
    this.toggleClassName = toggleClassName;

    this.next.onclick = function() {
        this.nextSlide();
    }
    this.prev.onclick = function() {
        this.prevSlide();
    }
}

Slider.prototype.goToSlide = function(idx) {
    this.validateIndex(idx);
    this.currentIndex = idx;
    this.hideAllSlides();
    this.showSlide(idx);
}

Slider.prototype.nextSlide = function() {
    var idx = this.currentIndex + 1;
    if (idx === this.slides.length) {
        idx = 0;
    }
    this.goToSlide(idx);
}

Slider.prototype.prevSlide() = function() {
    var idx = this.currentIndex - 1;
    if (idx < 0) {
        idx = this.slides.length - 1;
    }
    this.goToSlide(idx);
}

Slider.prototype.hideAllSlides = function() {
    this.slides.forEach(function(slide) {
        slides.classList.remove(this.toggleClassName);
    });
}

Slider.prototype.showSlide = function(idx) {
    this.validateIndex(idx);
    this.slides.item(idx).classList.add(this.toggleClassName);
}

Slider.prototype.validateIndex = function(idx) {
    if(!Number.isInteger(idx)) {
        throw new TypeError('Non-integer value passed');
    }
    if ((idx > this.slides.length - 1) || idx < 0) {
        throw new RangeError('Out of range index value: ' + idx);
    }
}

// following code could then be in your document ready handler
// you could instantiate any number of sliders
// each which could operate independently of each other
var slider1 = new Slider('#slider1 .slides', 'next1', 'prev1', 'showing');
var slider2 = new Slider('#slider2 .slides', 'next2', 'prev2', 'showing');

Notes:

You could make ES6 class as well, but I did not show this, as I see nothing in your original code to make me think you are working in ES6.
Taking class approach should eliminate need for IIFE around slider code, in that you have already encapsulated your logic/state.
I have added index value validation, as given that the goToIndex() method could theoretically be called form anywhere in code that has access to the object in it's scope, it becomes more important to make sure object can not be put into a bad state.


Retrieve a number in a webpage and store in a SQLite3 db

Code smells

your code is vulnerable to SQL injection attacks because you are using string formatting to put query parameters into a query. You need to proper parameterize your query with the help of the database driver:

query = """
    INSERT INTO {table} (datetime, nb_co)
    VALUES(?, ?)
""".format(table=self.forum)
c.execute(query, (now, nb_co))

Note that this way you also don't need to worry about Python to database type conversions and quotes inside parameters - it will all be handled by the database driver.

Performance

instead of re-connecting to the database multiple times, think about connecting to a database once, processing all the data and then closing the connection afterwards
same idea about the use of requests - you may initialize a Session() and reuse
use lxml instead of html.parser as an underlying parser used by BeautifulSoup
you can use SoupStrainer class to parse only the desired element, which will allow you to then simply get the text and split by space instead of applying a regular expression:

parse_only = SoupStrainer(class_="nb-connect-fofo")
page = BeautifulSoup(page_html, 'lxml', parse_only=parse_only)
return page.get_text().split()[0]


Replacing tokens in a text file with replaced text

Its a little heavy on the code side.

Your definition of a token still leaves possibilities that you have not defined.

$$          :  Replace with $                                         Fine
$(<X>)      :  Replace with the mapped `<X>`                          Fine.

$(<stuff>\n : No closing ')'                                          Error
$()         : What happens with no identifier.                        Error
$<X>        : Some other character after '$' that is not '(' or '$'   Error

Especially your stream handling.
Its usually bad practice to test for .good(), .bad() or .eof() during normal processing. You want to test these after things go wrong to generate the appropriate error message or not. Usually stream code looks like this:

while(std::getline(stream, line))
{
    // correctly read a line
}

// or

while(stream >> value >> value2 >> value3 >> etc)
{
    // correctly read a value from the stream
}

You can use OO to compartmentalize your mapping.
Personally I would combine your mapper and mapped class into a single class.

class Mapper
{
    // Class contains a map from tokens => value
    // used via replace() to replace all tokens $(<X>) in string
    // with the values contained in the map.

    std::map<std::string, std::string>  replaceMap;
    public:
        Mapper(std::string const& fileName)
        {
            // Read all the mapping values from the file.

            std::ifstream   mapFile(fileName.c_str());
            std::string     line;

            while(std::getline(mapFile, line))
            {
                // Each line in the file contains a token/value mapping
                std::stringstream   linestream(line);

                std::string         token;
                std::string         value;

                std::getline(linestream, token, ':');
                std::getline(linestream, value);

                // Save the token and value
                replaceMap[token]  = value;
            }
        }

        std::string replace(std::string const& line)
        {
            std::string result;
            std::size_t last = 0;

            // Search for the '$' char repeatedly.
            for(std::size_t find = line.find('$');find != std::string::npos;last=find, find=line.find('$', find))
            {
                // Copy the inert text from line
                // into the result
                result  += line.substr(last, (find-last));

                // If the next character is a '(' then search for the closing ')'
                //
                // If we don't find a token `$(<X>)` then ignore the '$' and treat
                // it like a normal character. Note If <X> has no mapping then
                // we replace it with the empty string. Note if <X> is empty it is
                // is still value.

                bool hit = false
                if ((find + 1 < line.size()) && line[find + 1] == '(')
                {
                    std::size_t end = line.find(')', find);
                    if (end != std::string::npos)
                    {
                        std::string key = line.substr(find+2, end-find-2);
                        result += replaceMap[key];
                        find = end + 1;
                        hit  = true;
                    }
                }

                if (!hit)
                {
                    // Token was not found.
                    // Put the '$' on the output and move on.
                    result  += '$';
                    find++;
                }
            }
            // Add the rest of the inert string to the output
            result  += line.substr(last);

            return result;
        }
};

This makes it easy to use:

int main(int argc, char* argv[])
{
    Mapper  mapper(argv[1]);

    std::ifstream   input(argv[2]);
    std::string     line;
    while(std::getline(input, line))
    {
        std::string result = mapper.replace(line);
        std::cout << result << "\n";
    }
}


Your marker interface has no added value. In fact, it's an anti-pattern because you provide a generic type parameter on an interface ICommand, only to enforce it on another interface ICommandResult.

public interface ICommand<TResultData>
{ }

public interface ICommandHandler<TCommand, TResultData>
    where TCommand : ICommand<TResultData>
{
    CommandResult<TResultData> Handle(TCommand command);
}

Since specific commands have nothing in common, I would not create an interface for commands. Also, TResultData has nothing to do with a command, and everything with the command result.

The handler could be rewritten as follows:

public interface ICommandHandler<TCommand, TResultData>
{
    CommandResult<TResultData> Handle(TCommand command);
}


Average readouts from multiple IR sensors with Arduino

The code feels overcommented. The only comment I see having some value is

// Dummy sensor read (suggested when switching ADC pin)

but even that shall refer to the proper place in the datasheet.

Everything else could (and should) be taken care of by using proper names. Don't be shy factoring blocks of code into functions, even just for the sake of giving them names.
The code does not know (or care about) the nature of the sensor connected to the pins. Does it matter that it is IR? Would anything be changed if it were RF, or sonar, or anything else? So the ir_ prefix seems like a pure noise. I strongly advise of dropping it.
The code does care on the signal postprocessing (clamping and rescaling). This operation is highly specific on the part used. If by any chance you'd opt for another part, you'd need to fix the heart of the program. I strongly advise to factor this functionality into the function, to be called via a pointer.
I do not endorse variables like ir_avg_is_valid. It is toggled once, but consumes cycles for the entire program lifetime. Consider filling up first IR_WIN_LENGTH samples outside the loop.

All that said, the code should look along the lines of

    void read_new_values(uint32_t (*postproc)(uint32_t raw))
    {
        for (uint8_t sensor_i = 0; sensor_i < IR_NUM_SENSORS; sensor_i++ ) {
            uint32_t raw = read_sensor(sensor_i);
            uint32_t cooked = postproc(raw);
            values[sensor_i][win_ix] = cooked;
            win_ix = (win_ix + 1) % WIN_LENGTH;
       }
    }

    uint32_t read_sensor(uint8_t pin) {
        analogRead(pin); // Dummy read, see datasheet, chapter and verse
        return analogRead(pin);
    }

    uint32_t whatever_part_number_postproc(uint32_t value) {
        // See datasheet, chapter and verse
        clamp
        return rescale
    }

    void prefill_window(uint8_t win_size) {
        for (win_ix = 0; win_ix < win_size; win_ix++) {
            read_new_values(whatever_part_number_postproc);
        }
    }

    void setup() {
        ....
        prefill_window(WIN_LENGTH);
    }

    void loop() {
        ....
        read_new_values(whatever_part_number_postproc);
        ....
    }


Adding events to multiple markers in a Google map

Your code is definitely simpler, though I would not use it myself. There is no good reason to have an anonymous function, and if you have multiple markers, then you will have multiple clones of the same function. I would create a named function and use that function with addListener.

(I am assuming that infowindow is available to this function)

function setPositionAsContent(){
  infoWindow.setContent(this.position.toString());
  infoWindow.open(this.map, this);
}

google.maps.event.addListener(marker, "click", setPositionAsContent);


Extracting and reformatting dates from text

Whenever declaring a function that you only expect to use in the current file, mark it static.

The (anonymous) user in the comments above is correct to indicate that accum is quite large; however, rather than allocating it statically as a global I'd suggest that it be allocated from the heap (malloc).

printf("%s\n", dates) is equivalent to puts(dates), but the latter is more efficient.

Having to predeclare variables in C hasn't been needed since the 90s. Do not predeclare variables. Declare them where they're used; i.e.

for (int i = 0;

That loop doesn't do what you think it does. You're missing braces. The loop will only apply to the first if.

j += 8

Where does 8 come from? Declare this as a constant. Magic numbers are bad.

It's pointless to have a return value for pickDates, so make it void.

date_str in isDate should be a const char * because you shouldn't be modifying it. The same applies to dates in pickDates.

Later, where you have a series of sprintf / strcat, do not use strcat, nor a tmp array. You can write to date_str via a temporary pointer that you increment based on the return value of sprintf.

I suggest inverting this logic:

if (dd < 32 && dd > 0 && mm < 13 && mm > 0 && yy > 0)
{
    // ...
    return 1;
}
else return -1;

to

if (dd < 0 || dd > 31 || mm < 0 || mm > 12 || yy < 0)
    return -1;
// ...
return 1;

Also, if that return value indicates success or failure, you should use a boolean from stdbool.h and use true/false instead of an integer.

This:

int i = 0;
int dd = atoi(&date_str[i+1]);
int mm = atoi(&date_str[i+4]);
int yy = atoi(&date_str[i+7]);

doesn't make a whole lot of sense; i might as well not exist and you might as well do

int dd = atoi(date_str + 1),
    mm = atoi(date_str + 4),
    yy = atoi(date_str + 7);


Sorting is not needed.  A Set may be a better data structure for the task.

const find2Unique2 = a => Array.from( a.reduce(
    (once, x) => (once.delete(x) || once.add(x), once),
    new Set()
))

console.log( find2Unique2( [2, 0, 6, 8, 10, 2, 6, 10] ) );

I"m not sure how to solve this in constant space.  If you xor all of the terms together

arr.reduce( (xor,x) => xor ^ x, 0 )

Then result = a ^ b, where a and b are your two unique terms.  If you can figure out a, then b = result ^ a.  Or you can find some other reduction, you'll have two equations and two unknowns, and an algebraic solution might be possible.

For example, xor of the negated array combines with positive xor to uniquely identify a and b if they are two bits wide:

  xor = arr.reduce( (xor,x) => xor ^ x, 0 )
  neg = arr.reduce( (xor,x) => xor ^ -x, 0 )

 a     b               xor   neg & 0xF (high bits omitted for clarity)
 0     1     =>          1  1111
 0    10     =>         10  1110
 0    11     =>         11  1101
 1    10     =>         11     1
 1    11     =>         10    10
10    11     =>          1    11

But it doesn't work for larger values.  You could do multiple passes, with each pass xor-ing a right-shifted version of elements that could possibly match (if the last two bytes are 11 and 10, you can skip numbers that don't end in those bits).

I didn't implement this because it's pretty complicated and it doesn't seem like the right answer.  But maybe it gives you an idea.


In total, a process in Unix systems can have a limited number of open filehandles. By default this is only say 1024 per process in Linux; all of the open sockets also consume file descriptors. Even if you optimize the system, then reading the file for each request will be costly.

In this case, if you are really concerned about the performance, read the image into memory (as bytes/str), and send it from there instead:

with open('test.png', 'rb') as f:
    image_data = f.read()

...

    return ( image_data, )

However if you have a veery big file, then you could mmap it into memory in the beginning of the process (this consumes just 1 file descriptor) globally and send it from there in each client:

im_file = open('verybigfile.iso', 'rb')
mm = mmap.mmap(im_file, 0)

    ...
    return ( mm, )

Both of these would save you 1 file descriptor per a client requesting the file.

However, if you need to serve lots of files like this, then you might want to increase the limit of open file descriptors per a process, use a front-side cache such as Varnish and/or scale up into multiple processes, or hosts, or even use a CDN to deliver your files.


Another variant of runs

Let us start with the finished product first, and then I will show you how to get there:

runs :: String -> [String]
runs "" = []
runs xs = munched : runs (drop (length munched) xs)
  where munched = munch xs

Use pattern matching

In your extract function, you've checked str's length. However, that is not necessary and is very expensive. If you want to check whether a list is empty either use null or pattern matching. With pattern matching, we end up with

extract []  xs = xs
extract str xs = extract (drop (length (munch str)) str) (xs ++ [(munch str)])

Use bindings to keep repetition low

However, we repeat ourselves here and use munch str twice. Let's get rid of that:

extract []  xs = xs
extract str xs = extract (drop (length munched) str) (xs ++ [munched])
  where
    munched = munch str

Our line got a little bit shorter. Great. Now let us have a look at your accumulator.

Avoid repeated ++

Your results looks like this:

munch str ++ munch str' ++ munch str'' ++ munch str''' …

However, with parentheses, we actually have

(…(((munch str ++ munch str') ++ munch str'') ++ munch str''') …)

Since ++ is linear in its first argument, that is going to be slow. However, we don't need to use ++ at all, since we're constructing a list element-wise from the first to the last. So instead of an accumulator, let us have extract return the list as soon as possible:

extract [] = []
extract str = munched : extract (drop (length munched) str)
  where munched = munch str

At that point extract has exactly the same type as runs, so we can get rid of it. We end up with

runs :: String -> [String]
runs []  = []
runs str = munched : runs (drop (length munched) str)
  where munched = munch str

Replace str with xs and the first [] with "", and you have my first variant. We're done.

Other functions

You could rewrite chomp in a way that returns already groups of characters, e.g.

chomp "aaaaabbbbbccccc" = ["aaaaa","bbbbb","ccccc"]

Then, you could rewrite munch so that it splits a string after 9 characters:

munch "aaaaaaaaaa" = ["aaaaaaaa","aa"]

If you do that, runs gets a lot simpler:

runs = concatMap munch . chomp

However, the types of chomp and munch would differ in that case. By the way, this variant of chomp is in the standard library, and munch is also easy to implement.


The most important difference between your if and your else is this:

self.dx += self.deacc

vs.

self.dx -= self.deacc

The rest can work just fine without being in if or else.

Also, when you copy-paste code, which you apparently did to check the bounds on self.dx, you should change the comments. Both of your comments say "go below zero". It was a bit hard for me to understand the purpose of your if self.dx > (self.deacc * -1):.

If I understand your code correctly, and if my Python syntax skills are correct, I think it should work to do it like this:

self.x += self.dx
self.dx += (self.deacc if self.horzDir == 'l' else -self.deacc)

if Math.abs(self.dx) < self.deacc:
    self.dx = 0

If I understand your code correctly, you are stopping Mario whenever his velocity (self.dx) gets close enough to zero. This can be accomplished by taking the absolute value of self.dx (which will get rid of a possible negative sign) and check if it is below self.deacc. If it is, Mario should stop. I think describing this as "stop Mario if his speed is too slow" is more accurate than "ensure Mario's velocity doesn't go below zero."


Find the most combinations of two numbers that equal third or get close to it

Have you simply tried to split code into smaller functions?

int t = in.nextInt(); //Time available

How about simply naming it timeAvailable instead of t ?

if(m > n) { //I rearrange my input as it doesn't work when m is bigger then n
    int tmp = m;
    m = n;
    n = tmp;
}

Common pattern is something like:

int calculate(int m, int n, int t) {
    if (m > n) {
        return calculate(n, m, t);
    }
    ...
}

Try to declare variables in smallest possible scope - int tmpgap; should be inside the for-loop. The inner for-loop might be replaced by division + Math.floor().


Resizing table widths and making input fields

At first, you code looks good enough for the set of the requrements you specified. The constructions that you use are simple, so here may be place for the improvements, but this requeres developing understanding in the nontrivial subjects: CSS selectors, jQuery selectors and jQuery chaining details. I think that it may be possible to write down all the code in one chain but it may decrease maintainability.

Some recommendations:

Instead of getting element html use .text().trim().
Use width:100% for inputs to let CSS do the work for you, but apply it only for the inputs without size - use combination of :not and [size] for that.
Tables are stretching, so just remove the table size at the end - it should be autosized to the content.
Use find(...)....end() to chain the queries and separate the realizations of the requirements.
Use static code analysis tools, like Jshint, jslint - it is better to add var to not interfere with the global scope and these tools let know about such kind of the errors and more.
It highly unclear what is the nature of the constants (like 35, 11, etc) in the code. It is better to add at least a very small explanation on them. It greatly improves understanding and review.


What I like to do in this sort of complicated conditional situation is to do the comparisons upfront and give them names. This makes it easier to reason about the code, and doesn't have any drawback if the conditional expressions are cheap.

I then go ahead and replace the conditional expressions with the named booleans, and it usually becomes more obvious how to simplify the code. Here's what I ended up with:

private Float applyFactors(Float originalValue, Float localFactor, Float globalFactor) {
    Float result = null;

    boolean hasGlobalFactor = ((globalFactor != null) && (globalFactor != 0));
    boolean hasLocalFactor =  ((localFactor != null) && (localFactor != 0));

    if (hasGlobalFactor && hasLocalFactor) {
        result = localFactor * globalFactor * originalValue;
    }
    else if (hasGlobalFactor) {
        result = globalFactor * originalValue;
    }
    else if (hasLocalFactor) {
        result = localFactor * originalValue;
    }

    return result;
}

This approach also makes the code more readable as well.


namespace std

Others have said this already but it's important enough to be repeated: Don't put your own definitions into namespace std.  It's undefined behavior.

About the only thing I'm aware of that you may put into namespace std are specializations for templates already defined by the standard.  So, for example, if you have

struct MyType
{
  int a;
};

inline constexpr bool
operator==(const MyType& lhs, const MyType& rhs) noexcept
{
  return lhs.a == rhs.a;
}

then you may do

#include <functional>  // std::hash

namespace std
{

  template <>
  struct hash<MyType>
  {
    using argument_type = MyType;
    using result_type = std::size_t;

    result_type
    operator()(const argument_type& mt) const noexcept
    {
      return mt.a;
    }
  };

}

so you can, say, use MyType as key in a std::unordered_map.

The whole point of namespaces is to separate stuff. So put your own stuff into your own namespace. For example, Boost has its stuff in namespace boost and sub-namespaces thereof. You could use namespace ethan_bierlein or something. In other languages, it is common practice to use one's domain as in package com.example.myproduct (assuming you own example.com) but I haven't seen this practice in C++ yet.

Correctness

Consider the following program.

int
main()
{
  const auto age = easy_input<int>("How old are you? ");
  std::cout << "Hello, " << age << " year old!\n";
}

If compiled and run as this

$ ./a.out
How old are you? 17
Hello, 17 year old!

everything seems fine.  However, if the user inputs nonsense,

$ ./a.out
How old are you? don't care
Hello, 0 year old!
$

the result is probably not what you'd expect from a well-designed user interface.  However, it gets worse.

int
main()
{
  const auto ounces = easy_input<int>("How many ounces of beer dou you want? ");
  const auto age = easy_input<int>("How old are you? ");
  //std::cout << "ounces = " << ounces << ", age = " << age << "\n";
  if (age >= 18)
    std::cout << "Here are your " << ounces << " ounces of beer.\n";
  else
    std::cout << "Sorry, you're not old enough.\n";
}

In action:

$ ./a.out
How many ounces of beer dou you want? too many
How old are you? Here are your 0 ounces of beer.
$

Don't worry if you cannot reproduce the results of the above two examples result of the second example. It's undefined behavior so anything (including but not limited to your cat getting pregnant) could happen.

What's the reason for this?

There are two problems.  First, in

TInput user_input_value;        // (1)
std::cout << prompt;            // (2)
std::cin >> user_input_value;   // (3)
return user_input_value;        // (4)

if TInput is a builtin type like int, the variable user_input_value is not initialized on line 1. If the input on line 3 succeeds, the value is set to the input, which is fine. However, if the input is invalid, no value will be assigned and you'll return the uninitialized value. If the stream is good(), the extraction operator on line 3 will either successfully extract and assign the value or, if invalid input is given, set the failbit and assign 0. Therefore, if the first input is invalid, 0 will be returned (for ounces) and the failbit set. Then, on the second entry, nothing is assigned to user_input_value and an uninitialized int returned (for age).  This results in undefined behavior.

Running the above examples second (“too many ounces of beer”) example through a tool like Valgrind can unveil the error. (To my surprise, neither ASan nor UbSan were able to detect the error.)

  I originally thought that if input fails for whatever reason, the destination value would never be changed. This seemed to be the case but apparently was changed in C++11 such that now 0 is assigned for invalid input provided the stream was good() to begin with. Thanks to Mooing Duck for discovering this (see comments).

The seemingly simple fix to this problem is to use value-initialization for user_input_variable.

TInput user_input_value {};

Since your question is tagged with C++14, we can now at least use one C++11 feature (uniform initialization) with pride.

However, while this “solution” fixes the undefined behavior, it still has its issues. If the user enters invalid input, it should probably be yelled at and not 0 (or whatever a default-constructed TInput is) returned silently.  So you should really check the stream after the operation.

TInput user_input_value {};  // value-initialization not strictly needed any more
std::cout << prompt;
if (std::cin >> user_input_value)
  return user_input_value;
throw std::istream::failure {"bad user input"};

You could have the same effect by setting the exceptions mask of std::stdin but this would also affect other uses of std::cin even outside your function so it might surprise users of your function. I'd consider a utility function messing with the mask bad.

Some people will argue that a user inputting invalid data is by no means an “exceptional” event so throwing an exception is inappropriate. If you're like them, you might prefer returning an std::experimental::optional<TInput> result.  Unfortunately, it is not standard yet but many implementations support it and there is a readily available version in Boost.Optional.

But this is still not as useful as it could be.  Consider the “beer” example again.

$ ./a.out
How many ounces of beer dou you want? 4 2
How old are you? Sorry, you're not old enough.
$

The first invocation of your function happily consumes the 4, stops at the white-space and leaves the 2 on the stream. The second invocation then sees the 2 readily available and without waiting for any user input, immediately and equally happily returns 2.

cr_oag has suggested you address this by calling std::cin.ignore.  However, I don't think that this is the ideal solution. If you ask the user how many ounces of beer she wants and she inputs 4 2, it is unlikely she really meant 4.  It would be better to treat this as an error and ask for clarification.

There is another, closely related, problem with your current version. Consider how this seemingly reasonable program…

int
main()
{
  const auto name = easy_input<std::string>("What's your name? ");
  std::cout << "Hello, " << name << "!\n";
}

…behaves not quite as expected.

$ ./a.out
What's your name? Ethan Bierlein
Hello, Ethan!
$

While it might create a warm and cozy feeling to be called with the first name by the program, most of us would probably consider this a bug.

For least surprise, I recommend that you always treat user input line-oriented: Read a single, but complete, line, and treat its entirety as one input. You can easily do this via std::getline. You can then try to convert that string into the target type and see if it has any characters remaining.

std::cout << prompt;
std::string line {};
if (!std::getline(std::cin, line))
  throw std::istream::failure {"I/O error"};
std::istringstream iss {line};
TInput value {};
if (!(iss >> value) || !iss.eof())
  throw std::istream::failure {"bad user input"};
return value;

This is still not ideal. While it behaves as expected for, say, numbers, the example asking for a name would now reject any input longer than one word. Not quite what we want. You would need some template meta-programming to special-case string input. But explaining how that would work is too much to go through in a code review.

As a matter of fact, there is already a function template in Boost.Lexical_Cast that does this (and more) for you (#include <boost/lexical_cast.hpp>).

std::string line {};
std::cout << prompt;
if (!std::getline(std::cin, line))
  throw std::istream::failure {"I/O error"};
return boost::lexical_cast<TInput>(line);

Portability

user86418 has already mentioned that #pragma once is not portable but if you use it, the #include guards become redundant. On the other hand, #pragma once can be more efficient than #include guards because the preprocessor can immediately stop processing the file while with #include guards, it has to process the whole header anyway to find out where the matching #endif is. So if you want the best of both worlds, you could use something like this.

#if HAVE_PRAGMA_ONCE
#pragma once
#endif

#ifndef EASY_INPUT_H
#define EASY_INPUT_H

// ...

#endif

Your users could then compile with -DHAVE_PRAGMA_ONCE to eventually speed up their compilations while still being portable to implementations that don't have #pragma once. If you're used to using GNU Autoconf, you'll be very familiar with those HAVE_${FEATURE} macros.

Another option is to use tricks like

#ifdef __GNUC__
#pragma once
#endif

(GCC defines __GNUC__) but I don't like this kind of being clever very much and prefer having the user have the last word.

As Mooing Duck points out, compilers ought to ignore unknown #pragmas. However, it is still a good idea to make them conditional. For example, if you compile with -Werror=unknown-pragmas (And you should, because it is enabled by -Wall -Werror.), GCC will reject code with unknown #pragmas. This is conforming as in standard configuration, GCC ignores them gracefully as it is supposed to. Your library should not force your users to use less rigorous warning levels. Such “noisy” or “unclean” libraries are very annoying, to say the least.

Genericity

Others have suggested making the stream to read from a parameter or accepting other prompts than strings. I don't think that this would add much value as I've yet to see a program that needs to read interactive user input from anything but standard input. Some lost souls might want to read from std::wcin, though. Those would probably also be interested in a std::wstring prompt that would be streamed to std::wcout. Eventually, there could be good reasons to print the prompt to standard error output (for example if standard output is to be redirected to some file).

Having an overload that uses no (or a default) prompts seems useful but anything else I think is superfluous.  A default parameter comes in handy here.

template <typename TInput>
TInput easy_input(const std::string& prompt = "");

Yes, you'll needlessly construct a temporary std::string if you call the function with a string literal but so what (see next section)?  And I don't think that using, say, an int as prompt would be a very frequent use-case.

Performance

  Is there anything that can be improved performance-wise?

Maybe, but don't worry about it. You are asking for user input. It would take very bad code for an input function that would be slow enough to make any difference compared to how long humans need to read, think and type.

Going Fancy

If you want to make your program fancy, consider adding line-editing support. It is very annoying for a user, having to delete an almost completely typed answer only because you realize that you have a typo in the first few characters. The GNU Readline library provides a de-facto standard mechanism for this. With GNU Readline there also goes GNU History which allows a user to re-fetch a previous answer using the arrow-keys. This is very handy if you have to give the same answer or similar answers many times. Of course, you should make the feature optional because your users might not have installed the library.

Also note the license requirements; quoting the project website:

  Readline is free software, distributed under the terms of the GNU General Public License, version 3. This means that if you want to use Readline in a program that you release or distribute to anyone, the program must be free software and have a GPL-compatible license.

If you don't publish your software at all, you're also fine. So you can always experiment around freely for your personal learning and private usage.

There might be other libraries providing similar line-editing support but I don't know any of them.

Williham Totland commented that there is another free software library for line-editing, Linenoise. While checking its website, I also found the Editline Library (libedit) (also free software). I've never used either of them.

Style

Besides the fact that you shouldn't declare stuff in namespace std, you have put the DocString alongside with the implementation. If you decide to separate declaration and definition, the DocString should go with the declaration because that's what is important for your users.

I assume you wanted to write a DocString that can be processed by Doxygen. If so, note that you should use @tparam to document template arguments.


app.h

#pragma once

This is not portable, and does not work as well as advertised. You should use include guards instead.

#include <iostream>
#include <string>

#include <Python.h>

One of the biggest problems currently in C++ is slow compile times. There are several things you can do to lower compile times, but one of the most important ones is to not include what you don't need to include - especially in headers. Obviously that won't be a problem in this small program, but it doesn't hurt to practice best practices.

This header file doesn't need any of these three includes.

<iostream>: you don't actually use anything from the <iostream> in the header.
<string> : you need this for std::string... but as I'll explain later, you don't actually need any std::string stuff in the header.
<Python.h>: because you only use a PyObject pointer in the header, you don't actually need to include it here.

So you can remove all three of these includes from the header, and move them to app.cc, where they're actually needed.

class App {
public:
  App();
  ~App();

Have you heard of the rule of three/five/zero? Since your class requires you to write a destructor, that means it almost certainly requires you to write a copy constructor, move constructor, copy assignment operator, and move assignment operator. And in fact, your class does need you to do these things.

Now you probably don't want your App class to be copyable... that doesn't really make any sense. So for the copy ops all you need is:

App(App const&) = delete;
App& operator=(App const&) = delete;

All that's left is move ops. Should your class be movable? The answer to this question is almost always "yes", unless you have very complex technical reasons why not... which you don't here.

Unfortunately, as written your class's move ops can't be defaulted. You'll have to handle moving manually. The easiest way to do that is to define _counter to be:

PyObject* _counter = nullptr;

And then your move ops are like:

App(App&& other) noexcept
{
    std::swap(_counter, other._counter);
}

App& operator=(App&& other) noexcept
{
    std::swap(_counter, other._counter);
    return *this;
}

But to avoid cleaning up Python multiple times, you need to add a check that _counter is not nullptr in the destructor:

~App()
{
    if (_counter)
        Py_Finalize();
}

That's all you need to make the class safe according to the rule of five.

static const std::string PY_CLASS_NAME;
static const std::string PY_MODULE_NAME;

These don't really need to be class members. They're only used in app.cc, and don't seem necessary anywhere else.

static std::string _GetString(PyObject* obj);

This also doesn't need to be defined in class. It's only used in app.cc. If you move this and the two static constants into app.cc, you don't need to include <string> in the header.

But the main problem with this function is that _GetString is an illegal identifier. You cannot have an identifier that starts with an underscore and a capital letter anywhere. The rules for identifiers are pretty complex, so when I teach I generally advise these simple rules:

Never start with an underscore.
Never use two underscores together.

(_counter is technically okay because it's an underscore followed by a lowercase letter, and because of its scope. But I generally advise using something like counter_.)

app.cc

const std::string App::PY_CLASS_NAME = "Counter";
const std::string App::PY_MODULE_NAME = "lib";

Strings work here, but this is actually a job that might be better handle by string views. String views are constexpr and no-fail - ideal for constants. And the Python library supports non-null-terminated strings, partially. Instead of PyUnicode_DecodeFSDefault() you'd use PyUnicode_DecodeFSDefaultAndSize(). Unfortunately, there's no equivalent for PyObject_GetAttrString(), so you'll need a string there. But at the very least PY_CLASS_NAME can be:

namespace {

constexpr std::string_view PY_CLASS_NAME = "Counter";

} // anonymous namespace

The anonymous namespace is to make sure PY_CLASS_NAME is only visible in app.cc.

On to the constructor:

Py_SetProgramName(Py_DecodeLocale("App", NULL));

This is an issue generally, but you're not doing any error checking here. Py_DecodeLocale() can return nullptr if it fails for a number of reasons. You should really check for that, and handle it - probably by throwing an exception.

There's another issue here: resource management. You're doing everything the old-fashioned C way... mostly because the Python library is a C API. Generally when you're using a C API, you should make some proper C++ RAII classes for resource management.

For example, the memory allocated by Py_DecodeLocale() needs to be freed by a call to PyMem_RawFree()... but you never do that.

The smart thing to do is to create a PyMem_RawFree() deleter:

struct pymem_rawfree_deleter
{
    auto operator()(void* p) noexcept
    {
        PyMem_RawFree(p);
    }
};

Then you can store the program name in a unique_ptr:

namespace {

std::unique_ptr<wchar_t[], pymem_rawfree_deleter> p_program_name;

} // anonymous namespace

And now the memory will no longer leak, because it will automatically be freed.

Now the code becomes something like:

p_program_name.reset(Py_DecodeLocale("App", nullptr));
if (!p_program_name)
    throw std::runtime_error{"failed decoding program name"};
Py_SetProgramName(p_program_name.get());

Also note: NULL is old-fashioned and problematic. Use nullptr.

Py_Initialize();

Another issue with the constructor is that you don't do any checking to make sure it hasn't been called multiple times. What happens if someone does?:

App a1;
App a2;

One answer is that Py_Initialize() will be called twice. This doesn't seem to be a problem, because calling it a second time is guaranteed to do nothing. However, when one of those is destroyed, it will call Py_Finalize()... and now if you try to do anything with the second one, who knows what will happen - probably a crash.

What you'd need to do is make sure that only a single App object is created at a time. You could use a static flag for that... but you kinda already have one with p_program_name. If p_program_name is not nullptr, it must have been set in the constructor, so you know a second App is being constructed. What you can do is test p_program_name first thing in the constructor, and if it is not nullptr, throw an exception. And then you can set it to nullptr in the destructor after the call to Py_Finalize().

PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");

This might benefit from a raw string constant:

constexpr auto PY_INIT_SYS_PATH_CODE = R"~python~(

import sys

sys.path.append(".")

)~python~";

PyRun_SimpleString(PY_INIT_SYS_PATH_CODE);

Next up is more resource management worries:

PyObject* name = PyUnicode_DecodeFSDefault(PY_MODULE_NAME.data());

// ...

Py_XDECREF(name);

The C++ way of doing this is to define a deleter, and use unique_ptr:

struct pyobject_deleter
{
    auto operator()(PyObject* p) noexcept
    {
        Py_XDECREF(p);
    }
};

using pyobject_ptr = std::unique_ptr<PyObject, pyobject_deleter>;

// ...

auto name = pyobject_ptr{PyUnicode_DecodeFSDefault(PY_MODULE_NAME.data())};

And there's no need for all the calls to Py_XDECREF().

Once again, there's no error checking done.

void App::Run() {
    PyObject* res;

It's generally bad practice to declare variables before they're needed. Now you do this so you can reuse res after the loop is done, but there's no real need for this.

for (auto i=0; i<10; i++) {
    PyObject_CallMethod(_counter, "Inc", NULL);
    res = PyObject_CallMethod(_counter, "GetValue", NULL);
    std::cout << _GetString(res) << "\n";
}

I'm not 100% sure with the Python API, but I believe you are leaking a lot of stuff here. Each time you call PyObject_CallMethod() it's returning a PyObject*, whether you catch it or not. That PyObject* is nullptr on failure (which you might want to check for) but otherwise it's something you need to consider.

This would be really easy with the pyobject_ptr I showed above:

for (auto i = 0; i < 10; ++i)
{
    auto r1 = pyobject_ptr{PyObject_CallMethod(_counter, "Inc", nullptr)};
    auto res = pyobject_ptr{PyObject_CallMethod(_counter, "GetValue", nullptr)};
    // should at least check res for nullptr
    std::cout << _GetString(res.get()) << '\n';
    // cleanup is automatic
}

And of course, all the same for the bit of code after the loop.

std::string App::_GetString(PyObject* obj) {
    PyObject* repr = PyObject_Repr(obj);
    PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~");
    const char* bytes = PyBytes_AS_STRING(str);

    Py_XDECREF(repr);
    Py_XDECREF(str);
    return std::string(bytes);
}

I've already mentioned the problem with the name, but I believe this function has a more serious bug in it. You get the pointer to the string representation of str as bytes, then you decrement the reference count of str... which will probably destroy it. But then you use bytes again... which probably points to freed memory. Normally this would trigger a segmentation fault, but I suspect that Python is managing its memory as a pool, so the OS doesn't detect the use-after-free.

The immediate fix for this is to simply construct the string right away:

std::string App::_GetString(PyObject* obj) {
    PyObject* repr = PyObject_Repr(obj);
    PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~");
    const char* bytes = PyBytes_AS_STRING(str);

    auto res = std::string{bytes};

    Py_XDECREF(repr);
    Py_XDECREF(str);

    return res;
}

This will copy the data from bytes right away, before it's released.

But this becomes so much simpler if you use smart pointers:

std::string App::_GetString(PyObject* obj) {
    // Of course, you should be doing error checking....
    auto repr = pyobject_ptr{PyObject_Repr(obj)};
    auto str = pyobject_ptr{PyUnicode_AsEncodedString(repr.get(), "utf-8", "~E~")};
    const char* bytes = PyBytes_AS_STRING(str.get());

    return std::string{bytes};
}

Summary

Try to keep headers as minimal as possible:

Don't include stuff that isn't necessary.
Try to move as much as possible into implementation files especially stuff that's mostly implementation details.

Always respect the rule of zero/three/five.
Consider reentrancy - what happens when a function is called multiple times or a class is instantiated multiple times.
Error checking!!!
Use RAII, even if you have to roll your own classes to do it (which you often do when working with C APIs).

And lesser points:

Don't use NULL. Use nullptr.
Watch out for illegal identifiers. Simple advice: don't start identifiers with an underscore.


You have the column definitions backwards.  On your header row you have:

Last Updated | Last Hit

but in the actual cf it looks like it's displaying in this order

Last Hit | Last Updated

Other than that it looks great!


Guess how many are in the jar game in Java

Javadoc, Javadoc, Javadoc

import java.io.*;

Wildcard imports are sub-optimal. You never know what exactly is imported and it might conflict with other imports.

Classes should all be declared in their own files, this smells like you have all in one file.

class Test {

The main class should ideally be public. I also prefer to have Main somewhere in the name (or as name).

class Game {
    ....
    private Prompter prompter;

It is declared but never used.

You always create a new instance of Prompter but it only contains static methods. So either you make it a static helper class (and always invoke the methods statically) or you make it an instance class. I'd opt for an instance class.

String line;

do {
    System.out.print("Ready? (press ENTER to start guessing): ");
} while ((line = scanner.nextLine( )).length( ) > 0);

Why you need a line variable at all here?

Your logic is split over all the classes, each class has a little piece of the puzzle and the flow is just as far stretched. It is very hard to follow the actual program flow because you have to piece it together from all over the place.

Ideally, you'd have the main class, a class containing the actual logic and some helper classes. The main class would kick off your logic class, which would contain some setup code and the actual logic for the game logic.

Consider this pseudo-code:

class Main
    static void main()
        new Game().start()

class Game
    void start()
        setupPlayers()
        setupJar()

        do
            echo "Guess! "
        while getAnswer() != jarCount

Something like this. Abstract the details away behind methods but keep the main logic in one place, so that it is easy to follow the program flow.

  Your main method should tell me what your application does, not how it does it.

On a related note, Your classes are encapsulating state that does not need to be in its own class. Jar is only used once, there speaks nothing against having these four variables in your Game class. Same for the Player class, which only contains a method which would be better in the Game class.

You have filleted the code into too many classes, all this could be done in one well organized class.

I have to say, with a few exceptions, your naming is always spot on and awesome! Good job.


Bubble, selection, and insertion sorting

They seem right to me. A few minor comments:

You don't need to construct your lists by adding .add(pos, value). You can build them from an array as:

int[] array = {6,12,9,-14};
List<Integer> list = new ArrayList<>(Arrays.asList(array);

which is more concise and readable.
In your bubblesort, you do:

Integer temp1= unsortedList.get(i + 1);
Integer temp2= unsortedList.get(i);

accessing unsortedList twice. If you assign outside the if, you can recycle it and make it more readable. Also, consider using better names than temp1 and temp2: not much difference here, but it's a good habit to get into, same for insertion.


Options with a "yes" or "no" radio button

This should work:

$('#Option1, #Option2').live('change', function() {
    if ($('input[name=' + $(this).attr('id') + ']:checked').val() == 'False') {
        $('#formDiv').show();
    else {
        $('#formDiv').hide();
    }

    });

Or, if whatever has the id option1 is the same page element as the input with the name option1, you could do:

$('#Option1, #Option2').live('change', function() {
    if ($(this).val() == 'False')
        $('#formDiv').show();
    else {
        $('#formDiv').hide();
    }

    });


Regex detection for Puppet configuration

You're working too hard, trying to distinguish strings from regular expressions.  Rather, you should take advantage of the fact that the === operator for a RegExp and the === operator for a String both express the idea of a "match", which is what you want here.

I don't understand why you need to #intern all the strings.

I don't see why the fval = Facter.value(fact).to_s assignment appears inside an if condition.  The result of the assignment would only be false if Facter.value(fact).to_s is false or nil, which can never happen.  (Even nil.to_s results in an empty string.)

To treat values as an array regardless of whether a scalar or an array was passed in, you can use the [*values] idiom.

def self.fact_match(fact, values)
  fact_val = Facter.value(fact).to_s.downcase
  fact_val != "" and [*values].any? { |v| v === fact_val }
end

In addition to supporting literal case-insensitive matches and regular expression matches, also consider supporting Ranges.


Your code is too complex. With C++17, you can write more complex constexpr functions, so you don't need the variadic template tricks:
template <typename T = std::uintmax_t, std::size_t N>
constexpr T hash(char const(&s)[N]) noexcept
{
  T val{};

  for (size_t i = 0; i < N; ++i)
    val |= s[i] << (i * CHAR_BIT);

  return val;
}

Apart from that, this is a terrible hash function! The output is highly correlated to the input. It will also only hash up to sizeof(T) characters, so long strings with a common prefix might all get the same hash value.


Check if a value exists or catch an exception

I would recommend that you use option 2, especially since you have the ability to avoid the exception (by using the has method).

Exceptions should be used in exceptional circumstances (e.g. You might expect getInt to throw an exception if J_ID_CHUNK_TOTAL exists but does not contain a character which can be parsed to an integer). In which case you would want to wrap the call to that in a catch.

I would also suggest that you do a null check against the jUpdate object before using it.


Concurrent blocking Tasks in a BackgroundWorker

I would go with Task-based method (if you're using .Net 4.5) instead of the BackgroundWorker. That will sort out most of your problems.

Something in the vicinities of

async Task<List<T>> yourJobAsync(...)
{
    var results = await Task.Run ( () =>
    {
        //your job.
        return jobResults
    });
    return  yourJobAsyncResults
}


1, You should create those indexes. Explain shows whether your queries use indexes or not. If you don't have yet maybe you want a cron job which regularly deletes old records from the table. It improves performance too.

2, As others already mentioned on other questions, if possible, use PDO to avoid possible SQL injections.

3, Choose a meaningful names instead of $query1 and $query2 (maybe $remoteAddrQuery and $userIdQuery). It improves code readability a lot. The same is true for $result1 and $result2 ($remoteAddrResults, $userIdResults).

4, Maybe one query would be enough:

$attemptsQuery = "SELECT id FROM history
    WHERE (Time > date_sub(now(), interval 5 minute))
        AND (remote_addr='" . ip2long($_SERVER['REMOTE_ADDR']) . "'
            OR userid='" . $userid . "')
    LIMIT 6";

5, If you don't use the queried records just the count of them use COUNT(*):

$attemptsQuery = "SELECT COUNT(*) as attempts FROM history
    WHERE (Time > date_sub(now(), interval 5 minute))
    ...
    LIMIT 6";

It results a little bit less network traffic between the webserver and the database server and maybe means lower database load.
Of course you have to change mysql_num_rows too.

6, Some comments is unnecessary:

//so we know mysql_num_rows($result2)

7, Instead of commenting create functions whose name say what the comments said. I'd change

$attempts=0; // we want to set up $attempts=maximum of
             // (mysql_num_rows($result1), mysql_num_rows($result2))
if($result1) {
    $attempts=mysql_num_rows($result1);
}
if($result2 && $attempts<mysql_num_rows($result2)) {
    $attempts=mysql_num_rows($result2);
}

to

function getMaxAttempts($result1, $result2) {
    $attempts = 0;
    if ($result1) {
        $attempts = max($attempts, mysql_num_rows($result1));
    }
    if ($result2) {
        $attempts = max($attempts, mysql_num_rows($result2));
    }
    return $attempts;
}

It makes the code more readable.

Note that I've removed the first call of mysql_num_rows($result2) which maybe improves performance a little bit. (Probably PHP caches it.) A vararg function would be better with a loop but I don't know PHP supports it or nor.

8, If there is an error with the queries or with the database server mysql_query will return FALSE. Therefore, there will be no captcha displayed at all:

if ($result1) {
    $attempts = mysql_num_rows($result1);
}

Maybe you want to log and/or show an error message in these cases.


Overall, it's not bad. I only have some minor observations on the code itself:

You're setting, and re-setting @top in both the constructor and reset.
SIZE isn't used for anything.
Why does reset call flood? As far as I can tell, there's no need at all.
Doesn't seem like decreaseLimit has a point.
You could postfix a couple of if/unless statements and cut down on indentation.
in _flood the if i < 0 or j < 0 or i == DIMENSION or j == DIMENSION check could be written as:

return unless 0 <= i < DIMENSION and 0 <= j < DIMENSION

or you could simply skip it in favor of trying the coordinates and checking afterward:

square = @grid[i]?[j]
return unless square?

When looping through the @grid (in reset and hasWon) there's no need to use a [0...DIMENSION] range. You can just use regular CoffeeScript for...in loops:

for row in @grid
  for square in row
    # do something with square...

The IIFE at the end could be written more idiomatically using the do keyword

do ($ = jQuery, Game) ->
  ...

Structurally, I have a few notes:

You inject both the Game object and a td element into Square, so Square doesn't really have that much to do. In fact, the first thing it does is set an event listener on the element that the game object created, and set it to call back to the game object. It just seems a roundabout way to set things up.
I'd probably move the td creation to Square.
You pass a tbody element to the Game constructor, which is nice. But Game also directly accesses #count and #counter-user. So it's not really decoupled from the markup at all.
Somewhat similarly: You pass in jQuery as $ in the IIFE that kicks things off. That's a perfectly good pattern. However, Game just uses $ "raw". So you're sort of half-way following the pattern.

Here's a (simplified) refactored version, just for fun.


PHP error handling: log everything, and redirect critical errors to an "oops" page

A few things jump out at me:

The redirect of $e['type'] == 0:
For exceptions the default code is 0. Another code could be used and if the exception is not catched, it will throw a fatal error. Your handler does watch for fatal errors, so this may be a non-issue. The exception condition will just be logged twice.
For the actual header redirect:
Some browsers are slow on the header redirect (I'm not sure why). If you allow the rest of your code to continue executing, it could cause an ugly screen flicker. Again, since you are only redirecting fatal errors, probably a non-issue.
The logging functionality:
You may want to consider moving this out into another function. Some day you may decide to log the errors to a database, send emails, or even a text message. You could add these to that redirect method, but that would start to get pretty messy. If each piece were a separate method that was called from a generic log method, that would be easier to read and change as needed.


Your code is split into small functions and looks nice.

A few things could be done in a better way.

zip(count(1),sorted(names) can be rewritten with the enumerate builtin : enumerate(sorted(names), start=1).

You can iterate directly over strings so you don't need to use a list in list(name).

You don't need parenthesis in for (ind, name) in.

To answer your question :

FILE could easily be moved behind the main guard so I'd put it there. Had it been the smallest of the issues, I would have left it where it currently is.
for the with, I consider it to be a good habit to put it. Also, this should answer your solution.