Suggestion for improving this code to be more readable and easy for beginners?

Some suggestions:

Since you never reassign animals, better to declare it with const. (On a similar note, don't mix let and var - var has too many gotchas, and let permits reassignment, which is more difficult for a reader of the code to parse than const. Always prefer const.)

You never declare the people variable. This will throw an error in strict mode, and in sloppy mode, will implicitly create a variable on the global object, even if the whole script is inside its own function. Best to always declare variables before using them. Since the kokoarray is the same as people, it'll be easier to just use one of those variables, no need for two identical ones which refer to the same array.

Regarding your myFunction, don't use inline handlers, they have way too many problems to be worth using in modern scripts; use addEventListener instead:

document.querySelector('button').addEventListener('click', () => {
  paivitys(animals, animalCols)
});

Rather than selecting elements over and over, it would be more elegant to select the elements you need once, then reference those variables rather than calling querySelector again. It's less repetitive and less expensive.

Numeric-indexed IDs are a code smell. IDs should be reserved for elements which are completely unique in the document. If you want to indicate that an element fulfills a particular role that other elements have as well, use a class or a data attribute instead.

Your
 is missing a child
 - both s and s should only be children of
s. Also, s should be reserved for table headers. For plain data (like in your body), it'd be more semantically appropriate to use tds. If you want to make them bold, use CSS for that.

Rather than having animal and animal2 and person and person2, it'd be a lot simpler to combine all of those properties into a single array property, perhaps call it names. Rather than having multiple entirely separate data structures, it'll be far easier to parse it if they have the same format. One option is:

const animalData = {
  cols: ['Animal', 'Animal 2'],
  items: [{
    names: ['tiger', 'lion'],
    id: "54321",
  }]
};
const people = {
  cols: ['Person', 'Person 2'],
  items: [{
      names: ['kaka', 'julle'],
      id: "9874",
    },
    {
      names: ['Ronaldo', 'jussi'],
      id: "65555",
    }
  ]
};

This way, to reference the first (only) animal, use animalData.items[0]. To reference the ith person, reference people.items[i]. Populating the table gets much easier now:

const headTR = document.querySelector('thead tr');
const bodyTR = document.querySelector('tbody tr');
function display(cols, item) {
  headTR.children[0].textContent = cols[0];
  headTR.children[1].textContent = cols[1];
  bodyTR.children[0].textContent = item.names[0];
  bodyTR.children[1].textContent = item.names[1];
  bodyTR.children[2].textContent = item.id;
}

Remember to use textContent when inserting text - using innerHTML when you're not deliberately inserting HTML markup makes things slower and can be a security hazard if the input isn't trustworthy.

To identify which person item should be displayed when the select changes, you can set the value of each <option> to its current index, eg:

<select>
  <option value="0">kaka 9874</option>
  <option value="1">Ronaldo 65555</option>
</select>

Then, when the select changes, just pass people.items[select.value] to the function that populates the table, rather than having to .find.

You can construct the options much more concisely, like the following:

people.items.forEach((item, i) => {
  const option = select.appendChild(document.createElement('option'));
  option.textContent = `${item.names[0]} ${item.id}`;
  option.value = i;
});

Put all these together, and you get:

const animalData = {
  cols: ['Animal', 'Animal 2'],
  items: [{
    names: ['tiger', 'lion'],
    id: "54321",
  }]
};
const people = {
  cols: ['Person', 'Person 2'],
  items: [{
      names: ['kaka', 'julle'],
      id: "9874",
    },
    {
      names: ['Ronaldo', 'jussi'],
      id: "65555",
    }
  ]
};

const headTR = document.querySelector('thead tr');
const bodyTR = document.querySelector('tbody tr');
function display(cols, item) {
  headTR.children[0].textContent = cols[0];
  headTR.children[1].textContent = cols[1];
  bodyTR.children[0].textContent = item.names[0];
  bodyTR.children[1].textContent = item.names[1];
  bodyTR.children[2].textContent = item.id;
}

display(animalData.cols, animalData.items[0]);
document.querySelector('button').addEventListener('click', () => {
  display(animalData.cols, animalData.items[0])
});

const select = document.querySelector("select");
select.addEventListener("change", function(event) {
  display(people.cols, people.items[select.value]);
});
people.items.forEach((item, i) => {
  const option = select.appendChild(document.createElement('option'));
  option.textContent = `${item.names[0]} ${item.id}`;
  option.value = i;
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

        Animal
        Animal
        id

  <select></select>
  <button>backtozero</button>


Your code is pretty good as-is. There are other ways to do the same thing, but yours is fine.

One thing I noticed is that you've skipped braces on the if...else in reverseFromMap. My advice is to always use braces, even for one-line expressions.

However, you could also do

reversedMap[value] || (reversedMap[value] = []);
reversedMap[value].push(key);

You can collapse that into 1 line, although it's a little too terse if you ask me

(reversedMap[value] || (reversedMap[value] = [])).push(key);
// or
(reversedMap[value] = reversedMap[value] || []).push(key);

Or just reduce it to a ternary

reversedMap[value] ? reversedMap[value].push(key) : reversedMap[value] = [key];

The _.isUndefined check isn't really required, since reversedMap[key] is either a non-empty array, or it's false'y.

Other small stuff:

I'd prefer the name iterator instead of callback, but lo-dash uses callback in similar situations, so sticking with that convention is fine.
You don't necessarily need the identity function, as you could also do

x = callback ? callback(x) : x;

and just not bother with the identity function. It may or may not be faster - I haven't benchmarked it. In any event, both approaches work just fine, so there's no need to change anything.
If you do need an identity function, lo-dash has one built-in (_.identity). Saves you having to type it out.
Lastly, if you want to be stringent, you might want to check whether callback is a function, instead of just doing "default if false'y". E.g.

callback = _.isFunction(callback) ? callback : _.identity;
// or just plain JS
callback = typeof callback === 'function' ? callback : _.identity;

Personally, I'd skip this, though. If people pass in something that's not a function, it's their bug to deal with. Besides, I'd rather have the code fail loudly than having it silently ignore my (faulty) callback argument and default to something else without telling me. Still, type-checking is an option, so I thought I'd mention it.

As for alternatives to the overall approach, I'd use _.transform (which is basically the same as reduce/foldl but aimed at objects)

var reverseMapFromMap = function(map, callback) {
  callback = callback || _.identity;
  return _.transform(map, function (memo, value, key) {
    key = callback(key);
    memo[value] || (memo[value] = []);
    memo[value].push(key);
  }, {});
}

And again for mapFromReverseMap

var mapFromReverseMap = function(reverseMap, callback) {
  callback = callback || _.identity;
  return _.transform(reverseMap, function (memo, keys, value) {
    _.forEach(keys, function (key) {
      memo[callback(key)] = value;
    });
  }, {});
};


SQL Query to display minimum prices per country

try {
            Connection con = Mycon.getConnection();

This probably could be

    try (Connection con = Mycon.getConnection()) {

Assuming that this is the Java.sql.Connection interface.

Then the try-with-resources would be able to close the connection for you--exception or no exception.

But that won't help with your speed issues.

You need to determine where the problem lies.  Is it the query at the end?  Is it the population of the table?  The creation of the jTable?  Where?

Are there any conid values in venprices that aren't in country?  It would seem that there would have to be, as there are only 30,000 records in country and 180,000 in tempcalcplan.  Both have conid as their primary key, so no duplicates.

Is there an index on conid and rate in venprices?


I think you are putting way too much logic in your constructor. The other problem is that you do not want to create dummy files, if so, are there are real files you can make a copy of and test on? If there are no real files either you might actually have to create some real/dummy files.

And if I understand your question you want to test "the logic" of the Player class, which is basically invoking and creating a new URLClassLoader, but since this class takes a File as argument you can't invoke it. In that case you could change the argument from a File to a String so the invoke would look something like

public Player(String filePath) {
    this(new URLClassLoader(new URL[] { filePath }), "test");
}


I don't believe your depth-first approach is incorrect, as far as I can tell your visited variable does its job. However, there is room for improvement.

General improvents to readability
Firstly, this game's board can be represented by a linear tape of cells, rather than a two-dimensional grid. Using a one-dimensional array greatly simplifies the code. Only one position variable will be passed around instead of two. Additionally, the translation steps between coordinate systems that you're currently making (e.g.: int pos = i*a[0].length + j;) are eliminated.

Likely bugs
The aim is to count the minimum number of dice rolls, but you're also incrementing min when you use a snake or ladder. I think you should remove the + 1 in the else branch.

You're currently using the magic number 100, here: Integer.MAX_VALUE-100. There is no explanation as to where this 100 comes from, why it needs to be exactly that number. I assume it's to prevent interger wrapping when taking a sum. However, this exposes you to bugs. What if you use this program on a larger board that has paths longer than a 100 rolls? Your program now thinks the most optimum route is done in negative two billion rolls.

The current implementation assigns a special meaning to the value zero (no snake or ladder). However, position zero is a valid cell. This means that there is no way for a snake to point towards the cell at zero! One workaround would be to change the default value to -1.

Nitpicks
I recommend always using brackets with conditional blocks, even if there's just one line. Read this for more information.


Fixed size value in binary file

It is not a problem if you have binary file with fixed size data.

In this case all you need is to copy your input file into output (or any other way of allocation equal amount of data) and then make file.seek to next value you need to write.

Maybe it will be faster to change reading curstor instead of writing cursor, it this case you have no need to preallocate large sized file, just add to the end off file.

Varies size value in text file

Have no idea how to implement than in memory and perfomance efficient way.

So if you can make some restrictions on input data, let it be binary file, in other case try to find out some other restrictions that, perheps, give you some advatages.

BTW: if it wont be critical you can try converting file from text to binary for transposing and back to text after that.

Explaining

Lets look at the followig matrix

$$
A = \left[ \begin{array}{ll}
a_{11} & a_{12} \\
a_{21} & a_{22}
\end{array}\right] $$

$$
A^T = \left[ \begin{array}{ll}
a_{11} & a_{21} \\
a_{12} & a_{22}
\end{array}\right]
$$

Your source file contain matrix \$A\$, while your destination file should contain \$A^T\$.

To write data into destination file in direct order you should jump over source file to read each element from current column.

# ROW_OFFSET length of row in binary file
# NUMBER_OF_ROWS in source file
# DATA_TYPE_SIZE
# current_column while looping all columns
for current_line in range(NUMBER_OF_ROWS):
    sourceFile.seek(current_column * DATA_TYPE_SIZE + ROW_OFFSET * current_line)
    destinationFile.write(sourceFile.read(DATA_TYPE_SIZE))


Presumably you could pull those sections out into a generic method.

private ArrayBufferObject CreateArrayBuffer<T>(ColladaArray colladaArray)
{
     uint cursorOffset = Offset;

     ArrayBufferObject<T> arrayBufferObject = new ArrayBufferObject<T>(BufferObject.Hint.StaticCpuDraw);

     for (uint i = 0; i < Count; i++)
     {
         foreach (ColladaParam param in Params)
         {
             if (param.Name != null)
                 arrayBufferObject[cursorOffset - Offset] = (T)Convert.ChangeType(colladaArray[cursorOffset], typeof(T));
             cursorOffset++;
         }
         cursorOffset += Stride - (uint)Params.Count;
     }

     return arrayBufferObject;
}

And then replace those sections with a call to that method.

if (simpleParamsType == ArrayTypeFloat)
    return CreateArrayBuffer<float>(colladaArray);
else if (simpleParamsType == ArrayTypeInt)
    return CreateArrayBuffer<int>(colladaArray);
else
    throw new NotSupportedException(String.Format("simple accessor params type {0} not supported", simpleParamsType));

Depending on the types that you're converting to and from, the call to Convert.ChangeType() may have to be changed to something else, but it should be sufficient for the standard numeric types. For more information on type conversion, see this.


Controling Document and Window events via array

The code below is very stable and surprisingly fast, but am I headed in a strange direction?

I would say, it's a good first step to bring the code base into some kind of controlled state. It's also a good way of understanding the application and going through all the source files.

  It truly looks like dozens of different developers over many years just sticking whatever code in whatever file.

Actually most of old applications out there looks like this, some CMS driven backend, where people are trying to fix the DOM after its rendered.

However, I would make a HOF to generate the functions:

function createStackCaller(array) {
  return function() {
    for (var i = 0; i < array.length; i++) {
      if (typeof array[i] === 'function')
        array[i]();
    }
  }
}

$(window).on({
    load: createStackCaller(myObj.win.load),
    scroll: createStackCaller(myObj.win.scroll),
    resize: createStackCaller(myObj.win.resize),
    resizestop: createStackCaller(myObj.win.resizestop),
});


Names

What should your code do? Neither your code (by good names) nor your documentation inside the code (docstrings) nor your question does state the task in detail. So I cannot tell if your code is delivering the right results (but I don't think it does). So fix your names, there is no need to save characters. The bigger the scope the better the names have to be. Also add some docstring with a more detailed description of the task the function tries to solve.

Correctness of the results

>>> _ = eg_fr(7, 133)
7/133 = 1/19
>>> _ = eg_fr(7, 132)
7/132 = 1/19

That surprises at least me. At least the print statement lies to me. there is no equality in the second expression

Functions returning values vs. I/O

>>> eg_fr(7, 133)
7/133 = 1/19
['1/19']

Functions usually should either return values and have no other side effects like print or they should do tasks with side effect and return nothing (None) or success/error codes only. Your function does both. Either call the function print_egypti... and remove the return value or do remove the print from inside the function.

I strongly suggest to do printing outside the algorithm to have a testable function that is not cluttering the output.

Printing

A single test is no test.

If you did

if __name__ == '__main__':
    eg_fr(7, 133)
    eg_fr(7, 132)

you would have noticed not only the interesting results but also that you missed a line feed.

Looping

In Python you never do

for i in range(len(something)):
    do(something[i])

You always do

for element in something:
    do(element)

in your case

for element in ls_str[:-1]:
    print('', element, '+ ', end='')

that is less error prone.

String concatenation

You do concatenate the string output via printing in a loop. Use join() here. Instead of

for element in ls_str[:-1]:
    print('', element, '+ ', end='')
print(ls_str[-1])

you do

print(' + '.join(ls_str))

Testability

As mentioned before we split algorithm from I/O to get a nice and testable function

def egyptian_fractions(nominator, denominator):
    # [...]

def print_egyptian_fractions(nominator, denominator):
    print('{}/{} = '.format(nominator, denominator), end='')
    print(' + '.join(egyptian_fractions(nominator, denominator)))

Go for purity

We squeeze out all stuff from the algorithm that does not belong there. That is the string representation and also the nominator which is always 1. The final algorithm shall return only a list of denominators.

The remaining algorithm is

def egyptian_fractions_(nominator, denominator):
    denominators = []
    fraction = nominator / denominator
    total = 0
    for i in range(1, 1000):
        while 1/i + total <= fraction:
            denominators.append(i)
            total += 1/i
            if total >= fraction:
                break
    return denominators

The fitting print function is

def print_egyptian_fractions(nominator, denominator):
    ls_str = ['1/' + str(e) for e in egyptian_fractions(nominator, denominator)]
    print('{}/{} = '.format(nominator, denominator), end='')
    print(' + '.join(ls_str))

Algorithm

Depending on your task, I cannot know for sure, your algorithm is erroneous and inefficient.

You do prepare a lengthy fractions for a later test where you could calculate straightforward.
you do prepare string representations where you could leave this to the output functions
You limited yourself to a smallest fraction of 1/1000. Why?
You use float numbers for calculation and testing inside your algorithm and will get precision errors

I should mention there is the module fractions that is providing fractional math. As this is an exercise we will try to do it by hand.

First we try to lay out the algorithm

We try to find the biggest fraction f that is smaller or equal to the given fraction g
We keep the denominator from the fraction f

3a. we subtract fraction f from the given fraction g to get the remainder

So far this is what you did, now the change

3b. we try to find a fractional expression for the remainder (nominator, denominator)

we repeat from step 1

For step 1 you did a simple loop testing to find the biggest fraction. We do it a little more advanced, we divide the given denominator by the given nominator to find the new egyptian denominator. We use integer division for that step to work without precision loss. If the remainder of this division is 0 we are done, if not we have to increment the new denominator.

For step 3 we do some basic math to do the subtraction with the help of a common denominator to avoid precision loss and stick to a nominator/denominator fraction format.

What do we do for step 4? the task is the very same - solve the same problem for a new pair of nominator/denominator. We do a simple recursion and call the same function again appending that result to that from the current recursion depth.

def egyptian_fractions(nominator, denominator):
    if nominator == 1:
        return [denominator]    # exactly fitting fraction (was normalized)
    else:
        d = denominator // nominator
        r = denominator % nominator
        if r == 0:
            return [d]          # exactly fitting fraction (wasn't normalized)
        else:
            d += 1              # increment to get the biggest fitting fraction
                                # keep the result and add the result of the subproblem
            return [d] + egyptian_fractions(nominator*d-denominator, denominator*d)


You don't want Int b, you just want Int:

Ord a => [a] -> a -> Int -> Int -> Maybe Int


I came up with this:

for key in bcolors:
    locals().update({key: lambda string: bcolors[key] + string + bcolors["ENDC"]})

which is almost equivalent to your code (except the function names are uppercase). There is still a function being created for every colour but it's more concise in writing.

It works for me but apparently changing locals() is a bad idea:

  Others have suggested assigning to locals(). This won't work inside a function,  where locals are accessed using the LOAD_FAST opcode, unless you have an exec statement somewhere in the function.

https://stackoverflow.com/questions/8028708/dynamically-set-local-variable-in-python

  Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

https://docs.python.org/2/library/functions.html#locals

Another way I see is to write a function like so:

def _(color):
    return lambda string: bcolors[color] + string + bcolors[color]

but you'd have to call it like this:

_("BLUE")("hello")

That's the closest I can come up with.


Efficient method to look for an instance of an object in a collection

I think good coding practices should prioritize efficiency before code brevity.  It is important to not ask for unnecessary work to be done (this is part of the artistry of being a clever coder).  Implementing an early exit, in my opinion is a non-negotiable factor in selecting the "best" code design.

Using a function like array_walk_recursive() is handy for its leafnode traversal, but I agree that the syntax of making an early exit is a little unsightly.  For this reason, I recommend a language construct as part of the recursive design.  The conditional logic is the only part that can be condensed, so I've tried to boil it down as much as possible.

Code: (Demo)

function anyFish(array $collection)
{
    foreach ($collection as $item)
    {
        if((is_array($item) && anyFish($item)) || $item instanceof Fish)
        {
            return true;
        }
    }
    return false;
}

I don't think it is horrible to look at, but everybody loves their own babies.  I'm not sure that I can make it any more readable.


class TextBoxNum

Abbreviation should be avoided when naming a class: Num -> Numeric
The descriptive adjective should also be in front of the noun. It is a numerical textbox, and not a textbox number: NumericTextBoxBase
TextBoxNum and Update should be marked as abstract, unless a generic way of updating the value is provided in TextBoxNum. And by changing it to a abstract class, we should append Base to the end of the class name : NumericTextBoxBase, and its concrete classes can be named as FloatTextBox, DoubleTextBox...

class Value<T>

Without the definition of this class, I can only make some guess about it. We can observe that the value is assigned by a parameter from the constructor. The class itself seems to serve no other purpose than holding the value via void Value<T>.Set(T) and T Value.Get(). I would suggest you to replace them by T or T?, depending on whether or not if you want to enforce valid value is required.

Misc

Avoid try-catch as control-structure much as possible, unless that is your last resort.
Your Clamp method is comparing the value against the same upper boundary, max, twice.

Code:

public class NumericTextBox<T> : TextBox where T : IComparable<T>
{
    protected T min;
    protected T max;
    protected T value;

    public NumericTextBox(T value, T min, T max)
    {
        this.min = min;
        this.max = max;

        // ensure the value is with in valid range
        this.value = Clamp(value);
        // actually you should implement a full property for value and update the Text property in the setter
        this.Text = value.ToString();

        LostFocus += new EventHandler(Update);
    }

    protected virtual void Update(object sender, EventArgs e)
    {
        var type = typeof(T);
        var tryParse = type.GetMethod("TryParse", new[]
        {
            typeof(string), type.MakeByRefType()
        });
        var args = new object[] { Text, null };
        var result = (bool)tryParse.Invoke(null, args);

        if (result)
        {
            value = Clamp((T)args[1]);
            Text = value.ToString();
        }
        else
        {
            Text = value.ToString();
            Focus();
        }
    }
    protected T Clamp(T input)
    {
        if (input.CompareTo(max) > 0)
        {
            return max;
        }

        if (input.CompareTo(min) < 0)
        {
            return min;
        }

        return input;
    }
}


Finding the longest palindrome from the given string

You will hit a 64MB memory restriction regardless of how you allocate an array 20+ million entries strong. So you need to revisit an algorithm.

The problem doesn't look like a DP to begin with. Notice that the mere initialization of the array drives the time complexity to be quadratic. If you are happy with the quadratic time, notice that a naive approach requires constant space.

And since the quadratic time complexity will TLE on any decent OJ, you shall check out Manacher's algorithm.


Calculating 24 from 4 numbers (math Poker game)

A few pieces of feedback:

Semi-colons in Python aren't necessary, unless you're trying to issue two commands on one line like a=5;b=6.  I couldn't find a pep style guide that specifically bans them, but most Python code doesn't use them, as they are unnecessary.
You set temp_key to a str, but that is unnecessary.  I'm assuming you added that because you probably had it as a list before and got a "unhashable" error when trying to use a list as a dictionary key.  This is a perfect spot to use a tuple, and your code will work if you just remove the str (leaving the ()), because tuples are hashable and immutable.
Instead of relying on floating point accuracy, which isn't a problem given the magnitude of your examples, an alternative would be to use the fractions class and all your calculations would be exact.
Instead of recursively calling the comp function for your inverse negative and inverse divide, it'd probably be much simpler to just write tmp = nums[j]-nums[i].  I'd suggest it for the inverse divides too.


Javascript Prototypes that represent HTML elements

As dystroy mentioned, the setters and getters are really not JavaScript style, neither are the many try/catch statements in your functions.

However, if you insist on having all these getters and setters, you should create a utility function that generates a getter/setter  for you. Since you have default values for most properties in your LightParticle I was thinking something along the lines of this :

function addGetterSetter( o , property , defaultValue ){
  var postFix = property[0].toUpperCase() + property.slice(1),
      getter  = 'get' + postFix,
      setter  = 'set' + postFix;
  o[getter] = function(){
    return this[property] || defaultValue;
  }
  o[setter] = function( value ){
    this[property] = value;
    return this;
  }
}

And then you would

var LightParticle = function() {},
    prototype = LightParticle.prototype;

addGetterSetter( prototype , width   , 10 );
addGetterSetter( prototype , height  , 10 );
addGetterSetter( prototype , top     , 0 );
addGetterSetter( prototype , left    , 0 );
addGetterSetter( prototype , position, 'absolute' );
addGetterSetter( prototype , background, 'white' );
addGetterSetter( prototype , className , 'LightParticle' );


Functions
Create individual smaller functions doing a single task.
Enumerations
The enumeration for file does not make sense. line_no servers no purpose.
if __name__ block
For scripts, it is a good practice to put your executable feature inside the if __name__ == "__main__" clause.
A rewrite of the same code might look like:
from selenium import webdriver

FILE_NAME = "google-search-terms.adoc"

def search_google(browser, term: str):
    term = term.replace(' ', '+').replace('&', '%26')
    browser.execute_script(f"window.open('https://www.google.com/search?q={term}');")

def process_file(filename: str) -> str:
    with open(filename) as fin:
        for line in fin:
            yield line.strip()

def main():
    browser = webdriver.Chrome()
    browser.get('https://google.com')
    for search_term in process_file(FILE_NAME):
        search_google(browser, search_term)

if __name__ == "__main__":
    main()


A Vote should not have access to the database. It should be a dumb 'entity' with setters, getters and a constructor to make the required object a valid one.

You should take a look at the Repository and Data Mapper patterns. The point is, the object you want to save should not know how it is saved - meaning that you can change where you want to save it's data in the future without touching the underlying entity.

For an example implementation of this, check out Doctrine ORM. The Repository is the the object that uses a data mapper to save data to the relevant data source. Change the data source, the repository object-api (how you save / retrieve data) stays the same, but how the data is saved changes. Pretty basic concept but really powerful, and not just limited to ORMs or PHP, either. Imagine entities in JavaScript with a data mapper for local/session storage, for example. The data mapper would have get, update, delete (etc) methods, and the repository would call the underlying data mapper (relying on an interface) to actually perform the saving / retrieving of data, which you can swap out at any time.

Also, our vote needs to have it's own id (unique, primary key) completely separate from every other attribute so it can be uniquely identified. Aside from that, all lowercase, underscores for spaces and prepared statements is a good thing.

I'm not going to write your code for you, but effectively, you need to take a look at doing the following:

Abstract out the thing that saves, updates and removes data from your persistence. This is your data mapper, it is stand-alone, and just takes data and maps it to your given persistence. This is the object that would have your instance of \PDO dependency injected (yes, typehint for it).
Have a class that takes an instance of your data mapper that is responsible for saving your vote (a VoteRepository). You don't need an ORM, but you can simulate some of it's useful abstraction to help with SoC. This class contains your object-specific stuff which it forwards to it's data mapper, with your methods like userHasVote(User $user, $voteId).
You could probably get away with putting addVote(Vote $vote) and removeVote(Vote $vote) in your repository. This will require you to construct a new Vote object before you save it to the database (a Factory will help here, and your repository will give you a Vote object when you request one from the database. Remember, you're trying to use OOP here: everything is an object with a single responsibility.
The logic to remove / add a vote depending on something I would personally put in a Voting component (name it something better), with this single responsibility within it. Also, read the difference between a component and a service. Responsibility wise, you need to work upwards from the datasource, building a nice object api for each object without having it concern others (so they can work standalone)
Learn how to document your code. Phpdoc is a standard everyone and their dog's framework are employing to help other developers (and automated documentation tools) understand what code does
You're not writing php 4 any more. var has no place in your code. Use the correct access modifier, as in protected $db. The same goes for your functions (methods), make the ones you want others to consume (the public api) public function name instead.

So, all in all, a lot of refactoring to be done here. Well done for using \PDO and prepared statements though.


Excel .find Macro to write data to archive

If I understand correctly what you're doing, then VBA is simply not the right tool for this task. Excel has a built-in VLOOKUP function specifically for this purpose - try something like this in column 80 of the RAW_DATA_ARCHIVE sheet:

=IFERROR(VLOOKUP(A2,'RAW DATA'!E:E,1,FALSE),"")

That said, you did post some VBA code, albeit just a loop. Here are some thoughts, mostly on naming style:

ws1 and ws2 would probably be better off as sourceSheet and targetSheet.
ws1LRow would be more meaningful as simply lastRow
i is usually fine as a loop counter, but here it has a clear meaning: targetRow
aCell is really a searchResult

Using such meaningful names instantly makes it easier to read the code, which makes it easier to maintain/modify without breaking anything.

It also eliminates the need for explanatory comments:

'If match found
If Not aCell Is Nothing Then

vs.

If Not searchResult Is Nothing Then

A number of things explain why your code is slow.

You're using procedural code instead of built-in worksheet functions
You're writing to cells in a loop, presumably with Application.ScreenUpdating = True and Application.Calculation = xlCalculationAutomatic, which means many things happen every time you write a value into a cell.


Reader for graph-file with ugly return and questionable use of streams

Exception Handling

What are you doing in the exceptional case?

Printing an error message (ugly stack trace, actually) and returning null.  Now the caller has to handle the problem of the function returning null.

You've said:

  I don't need error-handling except that I know I provided the wrong path.

Well, want is the caller doing when it gets the null?  Does it say, "I couldn't open that file, please enter a different filename"?  That too is error handling, and you've have it in two places: the try ... catch here, and the if (list == null) by the caller.

Better is to ignore the exception here, and let the caller handle it, or the caller's caller.

public static List<Integer[]> edges_from_path(final String filePath) throws IOException {
    //captures only lines that consist of two positive integer numbers separated by whitespace (each line encodes an edge)
    final String LINE_DATA_FORMAT = "\\d+\\s+\\d+";
    final String SEPARATOR = "\\s+";
    return Files.lines(Paths.get(filePath))
                .filter(str -> str.matches(LINE_DATA_FORMAT))
                .map(str -> Arrays.stream(str.split(SEPARATOR)).map(Integer::parseInt).toArray(Integer[]::new))
                .collect(toList());
}

  My method doesn't return a graph because I want to be able to create graphs from different sources, and a list of integer-pairs is the interface the constructor for graphs is supposed to use.

This is even more reason not to catch the error and return null; the other sources would need to have the same behaviour.  They could fail in different and diverse ways; the exception will provide more details about the failure than null return value will.

List of Integer-Pairs

To say I almost threw-up when I saw List<Integer[]> would be an exaggeration, but only slightly.  Mixing collections and raw arrays is cringe worthy.  But a list of a raw arrays of a boxed type???  Yikes!

The raison d'être for "boxed types" is so they can be placed into the various Collection<E> containers, which require objects instead of raw types.  But here, you're not putting the integers into a Collection<E>; you're putting them into an array ([]), so they don't actually need to be boxed.

To see how wrong this is, each element of the List<> is an object Integer[], which holds two references to two Integer objects.  That is 3 objects allocated in the heap (ignoring interning) for every edge in the list.

If instead you used List<int[]>, then element of the List<> would be an int[] object, which directly contains the two integers, instead of references.  No extra objects need to be allocated.  Less memory is required, and the data is faster to access because an extra level of memory indirection has been removed.

Still, we eschew lists of raw arrays.  They are inconsistent; you need different access methods to get to the data at different levels, such as list.get(idx1)[idx2].  The array of integers doesn't convey any requirement on the number of values; you could be given a lists of lengths other than two.  It would be better to wrap the edge information into a POD (plain old data) object:

class Edge {
    public final int from;
    public final int to;
    Edge(int _from, int _to) {
        from = _from;
        to = _to;
    }
}

And then you could return a List<Edge>.  Change your graph constructor from taking a list of arrays of boxed integers of arbitrary lengths to taking a list of edges.  That is a much clearer interface contract.


Java number formatting in accountant style

If you come back in a few months to that code you will likely have a problem at figuring out what your code is doing. This is due to the abbreviations you used to name your things like

int cnt = 0;

boolean fd = false;
int fCnt = 0;

for e.g you just won't know what fd should represent.

Naming things is very improtant in the programming field on the other side it is pretty hard as well. Try to give your things meaningful names stating its purpose. By reading the name later you will grasp easier what your code is about.

char[] fin = new char[chars.size()];
int cntr = 0;
for (Character ch : chars) {
    fin[cntr++] = ch;
}

It would be better to just use the toArray() method specified by the List<E>.

For reversing the array you could use ArrayUtils.reverse() see also https://stackoverflow.com/a/2138004/2655508 which lives in Commons.Lang

You contains() and reverse() method are publicbut you aren't doing any parameter validation. If the passed in char[] ch would be null you would get an NullPointerException.


Misuse of inheritance

The huge, glaring problem I see with this code can be shown in one line:

class Address_book : public Person

This looks to me like a completely broken architecture. As a rule, public inheritance should follow the Liskov Substitution Principle (LSP), and this isn't even close1.

Before Barbara Liskov formulated the substitution principle, the usual phrasing was that public inheritance should reflect an "Is-a" relationship. The LSP attempts to...tighten that a little to deal with a few odd cases like circles vs. ellipses, where you can say a circle is a specific case of an ellipse, but (since you can't always substitute a circle where an ellipse is required) you shouldn't normally use public inheritance.

In this case, however, we don't need the more careful formulation. An address book isn't a person, and isn't really even anything like a person. We don't need to look much further to see that this is use (abuse?) of inheritance is problematic at best.

Consistent interface

I'd also change the interface a little bit. Right now, you have read and write member functions for Person, and operator<< and operator>> for an address book.

I'd prefer to change this so the public interface is more consistent. Since the (more or less) standard way to do formatted I/O is to use operator<< and operator>>, I'd use those for both classes.

Resizing

Right now, to resize your vector, you have code like:

//sets vector size, creates person elements of vector
void Address_book::num_of_ent(int entries, Address_book& abook) {
    for (int i = 0; i < entries; ++i) {
            Person p;
        abook.add_book.push_back(p);
    }
}

I'm not fond of the name (at first blush, the name sounds more like it should be retrieving the current number of entries). I'd also prefer to use vector's resize() member instead. Finally, a member function that's going to modify an object should normally modify the object of which it's a member, not have some other object passed to it to modify.

void Address_book::resize(int entries) {
    add_book.resize(entries);
}

Size type

That brings us to the next point: the type for the size of a container is preferably container_type::size_type or if that's not easily available, you can usually use size_t as a fair approximation. So that means the resize should really be changed to:

void Address_book::resize(size_type entries) {
    add_book.resize(entries);
}

...where size_type is something like:

typedef vector<Person>::size_type size_type;

...or:

using size_type = vector<Person>::size_type;

formatting of output

A fairly minor point is that by convention writing an object to the stream should only write the content of that object to the stream, not write a delimiter that separates that object from the next. For example, here:

//operator for address book person element
std::ostream& Person::print(std::ostream& os, const Person &p1) {
    os << "Name: " << p1.name << "\nAddress: " << p1.address << "\n\n";
    return os;
}

...we really want to get rid of the trailing new-lines, and leave that to the client code.

std::ostream& Person::print(std::ostream& os, const Person &p1) {
    os << "Name: " << p1.name << "\nAddress: " << p1.address;
    return os;
}

Then we might use it something like this:

std::copy(my_book.begin(), my_book.end(),
          std::ostream_iterator<Person>(std::cout, delimiter));

...and to get the same format, we'd have delimiter = "\n\n";, but if we wanted the output single-spaced, it'd be "\n", and so on.

1. Nor do I see any indication that this might be an exception to the rule.


Best Practices concerning Includes and SQL Connect Strings

1.) What you do here is to extract code used in several locations into a shared file. Instead of describing what do to you refer to a building block to use here (the footer building block). This is a technique commonly used in other engineering areas as well (e.g. construction). This approach greatly boosts re-usability. In my opinion it helps to see software as a set of building blocks to combine (of course those are composed of other smaller building blocks as well). Many software architecture diagrams and techniques use this view.

Other principles this approach relates to are:

Modularity: Decompose your system into modules. Each module represents one functional aspect of your application. Related is the separation of concerns: each building block has one dedicated responsibility., i.e. the rendering of the footer.
Information hiding: Hides the detail how the footer is actually rendered and how the information is retrieved.
Don't repeat yourself: Probably the most generic one applicable for all of real-life as well: Don't repeat the footer, refer to it.

These principles usually are applied at another level of architecture. Yet it really helps to practice them in a smaller scale. These principles (and others not mentioned) are the foundation of software development. They are very generic though and in my opinion you really can't learn them but do experience them by applying them gradually while refining your projects.

2.) For smaller projects it is probably a good idea to keep all configuration in one location. How to actually store passwords and other sensitive information is really up to your use-case: either store it in a file, in environment variables and others. Especially for web-sites it is very common to store all configuration in one file (including passwords). Of course this file should not be accessible by visitors ;).

3.) I won't give a recommendation on any particular framework or language. With experience it mostly doesn't matter. The common principles and patterns are the same for most languages and frameworks. Yet I highly recommend to have a look at other projects and try to understand them. Learn by observing how others solve problems. Start with some smaller projects (can be as simple as a single function or class) and gradually approach more complex frameworks. Among the complex frameworks written in PHP are the big MVC-Frameworks (e.g.. Symphony, Zend Framework... ) or Doctrine. The important thing really is to understand and work with those frameworks, yet abstract their approach and not just learn how this is done in this particular framework. Of course this requires a lot of research and experimentation :).

A final remark: the stackexchange sites works best for one new question per (unrelated) question (e.g. one for each, 1 & 2).


Here's some improvements you can make and some (untested) code with those improvements:

Instead of checking if the argument key contains '__' then splitting it, just split it. If it didn't contain '__' the second part will be an empty string.
Instead of through all the items and each keyword argument each time, loop through the arguments and use list comprehensions to find the matches. This way the matches list is shrinking and you don't need to look at values that matched the previous arguments.
Instead of checking if the type of a value is string, use isinstance(obj, basestring). This will allow unicode strings also.
Instead of catching all exceptions, catch only the exceptions you expect. (others are actually errors and should be propagated to the caller).

...

def find(self, **kwargs):
    matches = self.data

    for key, key_value in kwargs.iteritems():
        # Determine if this query has extra arguments
        key_parts = key.split('__')
        attrib = key_parts[0]

        if (len(parts) > 1):
            arg = key_parts[1]
            if arg not in self.query_types:
                continue

            if arg == 'contains':
                matches = [ item for item in matches if isinstance(getattr(item,arg, None), basestring) and
                            ( key_value.lower() in getattr(item,arg, "").lower() ) ]
            elif arg == 'startswith':
                matches = [ item for item in matches if isinstance(getattr(item, arg, None), basestring) and
                            ( getattr(item,arg, "").lower().startswith(key_value.lower()) ) ]
            elif arg == 'endswith':
                matches = [ item for item in matches if isinstance(getattr(item, arg, None), basestring) and
                            ( getattr(item,arg, "").lower().endswith(key_value.lower()) ) ]
            elif arg == 'gt':
                matches = [ item for item in matches if self._is_int((getattr(item, arg, None)) and
                            ( int(getattr(item, arg, 0)) > int(key_value) ) ]
            elif arg == 'lt':
                matches = [ item for item in matches if self._is_int((getattr(item, arg, None)) and
                            ( int(getattr(item, arg, 0)) < int(key_value) ) ]
        else:
            attr_value = getattr(item, key)
            if isinstance(value, str):
                if key_value.lower() == attr_value.lower():
                    matches = [ item for item in matches if
                                ( isinstance(getattr(item,arg, None), str) and
                                    key_value.lower() == isinstance(getattr(item,arg,"")).lower() )
                                or ( key_value == isinstance(getattr(item,arg,None)) ) ]

    return matches


Invoicing - calling multiple pages of Api and concatinating the results

When you have an assumption of getting a mix of return one or more values. You need to favor collection over single value return; because treating it as a collection would make things easier to deal with.

So, you can get rid of GetAllInvoices and adjust GetAllInvoicesAsync to something like this :

public async Task<IEnumerable<Invoice>> GetAllInvoicesAsync()
{
    const string endPoint = @"foo/{0}/invoices?pageNum={1}&itemsPerPage={2}";
    const int itemsPerPage = xxx;
    int pageNumber = 1;
    int iterationCount = 0;

    var tasks = new List<Task<InvoiceCollection>>();

    var isFirstRound = true;

    do
    {
        var response = await _apiClient.GetAsync<InvoiceCollection>(string.Format(endPoint, _apiClient.OrgId, pageNumber, itemsPerPage));

        if(isFirstRound)
        {
            iterationCount = response?.TotalCount <= itemsPerPage ? response?.TotalCount : (int) Math.Ceiling(totalPageItems / (double)itemsPerPage);
            isFirstRound = false;
        }

        tasks.Add(response);

        pageNumber++;
    }
    while(pageNumber <= iterationCount)

    var invoiceResponseList = new List<InvoiceCollection>(await Task.WhenAll(tasks));

    var invoiceCollection = invoiceResponseList.SelectMany(i => i.Invoices ?? Enumerable.Empty<Invoice>());

    return invoiceCollection?.Invoices;
}


Create an array with at least a given number of bits

Yes, wrap it in a macro:

#ifdef CHAR_BIT
    #define BIT_PER_MIN_IN_DAY ((60 * 24 / CHAR_BIT) + (((60 * 24) % CHAR_BIT) ? 1 : 0))
#else
    #error "Platform not supported"
#endif

UCHAR minutesOfDay[BIT_PER_MIN_IN_DAY];


Generating random sequences while keeping sum fixed

1. Comments on your code

The function stores its results in the global variable rand_list and always returns 0. This is a poor design of interface for two reasons. First, if you call generater_random_list twice, rand_list now contains the concatenation of the first and second lists:

>>> generater_random_list(10)
0
>>> rand_list
[2, 1, 5, 1, 0, 1]
>>> generater_random_list(10)
0
>>> rand_list
[2, 1, 5, 1, 0, 1, 9, 1]

(The caller could set rand_list = [] before the second call to generater_random_list, but it would be really annoying to have to keep remembering to do that.)

And second, what's the point of returning 0? That's no use to anyone. Python allows you just to write return as a shorthand for return None if you really have nothing worth returning, but here you do have something to return, namely the list of random numbers you just constructed.
There's no docstring. What does this function do and how do you call it?
You could choose a better name for the function than generater_random_list. (i) "Generator" is spelled with an "o". (ii) If you're going to name a function after its action, use the imperative form of the verb. (So use sort or multiply, rather than sorter or multiplier.) (iii) "Generator" has a specialized meaning in Python (referring to a generator), so best not to use it unless that's what you mean.
The Python style guide (PEP8) says, "Avoid extraneous whitespace immediately before a comma, semicolon, or colon."
When you're writing a function that produces a sequence of items, it's usually a good idea in Python to make it into a generator function that yields the items one by one (rather than a normal function that builds and returns a list of all the items). It's often convenient to process these items one by one, and a generator function allows you to do this without having to construct an intermediate list in memory. (And if you need a list, it's trivial to build one, by passing your generator to the function list.)

2. Revised code

def random_ints_with_sum(n):
    """
    Generate non-negative random integers summing to `n`.
    """
    while n > 0:
        r = random.randint(0, n)
        yield r
        n -= r

And here are some example calls:

>>> list(random_ints_with_sum(10))
[9, 1]
>>> list(random_ints_with_sum(10))
[10]
>>> list(random_ints_with_sum(10))
[0, 2, 8]

3. Comments on your design

Do you really mean to include 0 among the random integers? This suggests that you would be happy with

>>> list(random_ints_with_sum(1))
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

and similar outputs. You don't say what you are using this function for, so I can't tell if this is right or wrong, but it looks well dodgy to me.
Even with 0 excluded, your implementation samples its range with a lot of bias. For example, the number 4 has eight ordered partitions into positive integers:

4   3, 1   2, 2   2, 1, 1   1, 3   1, 2, 1   1, 1, 2   1, 1, 1, 1

but your algorithm doesn't sample these partitions evenly. Here's a test program that calls random_ints_with_sum(4) a million times, and counts the number of times each result was generated:

>>> from collections import Counter
>>> Counter(tuple(random_ints_with_sum(4)) for _ in xrange(10 ** 6))

Here are the results:

Partition    Count
-----------  ------
4            249997
3, 1         250047
2, 2         124579
2, 1, 1      125113
1, 3          83425
1, 2, 1       83190
1, 1, 2       41875
1, 1, 1, 1    41774

If the partitions had been generated uniformly, each would have appeared about 125,000 times in the results. You can see that shorter partitions are generated more frequently, and longer partitions less frequently than in the uniform distribution.

Again, since you don't explain what your function is for, I can't tell whether this kind of bias is important or not.

4. Sampling partitions uniformly

Supposing that you wanted to sample the space of ordered integer partitions uniformly, how could you implement it?

First we have to know how to count ordered integer partitions. And to do that, there's a neat combinatorial observation. Consider a group of objects waiting to be partitioned:

If there are n objects, there are n − 1 locations where you could insert a partition (indicated by the dotted lines). For example, if we insert partitions at the first and the third locations, we get the partition 1, 2, 1:

Each subset of locations corresponds to a different ordered partition, and each ordered partition corresponds to a different subset of locations. This means that we can choose an ordered partition uniformly by choosing a subset of locations uniformly. There are 2n − 1 subsets of the n − 1 locations (for example, 4 objects have 23 = 8 ordered partitions, as noted above), and we can choose one of these subsets uniformly by putting each location into the subset with probability ½.

Here's a revised function that implements the new algorithm:

def random_ints_with_sum(n):
    """
    Generate positive random integers summing to `n`, sampled
    uniformly from the ordered integer partitions of `n`.
    """
    p = 0
    for _ in xrange(n - 1):
        p += 1
        if random.randrange(2):
            yield p
            p = 0
    yield p + 1

And here's an example distribution after a million calls to the revised function:

Partition    Count
-----------  ------
4,           125042
3, 1         124848
2, 2         125189
2, 1, 1      125126
1, 3         124861
1, 2, 1      125152
1, 1, 2      124248
1, 1, 1, 1   125534

You'll see that this is very close to uniform.

Again, I should emphasize that since I don't know what your function is going to be used for, I don't know whether changing it so that it samples uniformly from the ordered integer partitions is the right thing to do. But if it is, now you know how to do it.

(Who would have thought there would be so much to write about a six-line function?)

5. Chinese restaurant process

You updated your question to say that you are trying to simulate a Chinese restaurant process. I have to say that I can't relate the code in your question to this process, which has nothing to do with numbers that sum to a particular total. So I'm puzzled! Maybe you can say more about how the code you posted relates to this process?

Anyway, if you want to generate a sample from this distribution, the easiest thing to do is to simulate the process directly:

def chinese_restaurant_partition(n):
    """
    Return a random partition of the numbers from 1 to n generated by
    the Chinese restaurant process.
    """
    partition = []  # list of sets
    assignment = [] # set each number is assigned to
    for i in xrange(n):
        r = random.randrange(i + 1)
        if r < i:
            # assign i + 1 to existing block
            block = assignment[r]
        else:
            # create new block
            block = set()
            partition.append(block)
        block.add(i + 1)
        assignment.append(block)
    return partition

For example:

>>> chinese_restaurant_partition(4)
[set([1]), set([2, 4]), set([3])]

This distribution looks like this (again, after generating a million samples):

Partition   Count
----------  ------
1234        249231
134, 2       83453
124, 3       82664
123, 4       83569
1, 234       83161
14, 23       42126
13, 24       41688
12, 34       41726
14, 2, 3     41891
13, 2, 4     41569
12, 3, 4     42022
1, 24, 3     41522
1, 23, 4     41719
1, 2, 34     41867
1, 2, 3, 4   41792


Your vertical separation is good, you've got clear regions in your code for defining the objects you need like sockets, readers and writers, etc. There's one region that needs cleaning, though:

while (p1.isClosed() || p2.isClosed()) { // if one of the players disconnect, the match will end.
    try {
        String p1 = bos1.readLine(); // what p1 says
        String p2 = bos2.readLine(); // what p2 says

        if (!p1.equalsIgnoreCase("")) { // if what p1 says is something
            if(p1.startsWith("my position x=")) {
                p1 = p1.substring(15);
                float x = Float.parseFloat(p1);
                bis2.write("his position x=" + x);
            } else if(p1.startsWith("my position y=")) {
                p1 = p1.substring(15);
                float y = Float.parseFloat(p1);
                bis2.write("his position y=" + y);
            }
        }

        if (!p2.equalsIgnoreCase("")) { // if what p1 says is something
            if(p2.startsWith("my position x=")) {
                p2 = p2.substring(15);
                float x = Float.parseFloat(p2);
                bis1.write("his position x=" + x);
            } else if(p2.startsWith("my position y=")) {
                p2 = p2.substring(15);
                float y = Float.parseFloat(p2);
                bis1.write("his position y=" + y);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

It's filled with duplication. If this game turns into a four-player game, you're gonna have a mess on your hands.

If you could wrap all the processing in a Player object, however, you could extract the relevant parts to functions, drastically simplifying the main loop:

while (!gameEnded(players)) { // check victory conditions or disconnects
    try {
        for(Player p : players){
            handleTickForPlayer(p);//How to handle update x y?
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Okay, that looks rather drastic, but that's because I'm leaving some parts out.

You've combined reading and writing in your own code, and its not very future proof. If you wanted to log matches, you'd have to insert it something in between, and from the way you handle messages, you'd have to do it for every case.

What I think you should do is give your messages some sort of identifier to state the meaning of the message, like id = 0 means it's an update of position x, id = 1 is used for an update for position y, maybe id = 2 is a chat message... you could put the type in the message by doing something like so: "id;message body", so "0;my position x=10.5". Or maybe you'd be better off with well known formats like JSON, but that's a separate point.

Via using these ids, you can then say "well, this is an 'update x' message", and send it off to the "update x" message handler.

I'd propose something like this:

        for(Player p : players){
            Message message = readMessageFromPlayer(p);
            if (message == null) { continue; }

            MessageHandler handler = getHandlerForMessage(message);
            if (handler == null) {
                //error?
                //maybe ignore bad messages
                continue;
            }
            handler.handleMessageFromPlayer(message, p, players);
        }

In readMessageFromPlayer, you check if there is any incoming content, and if there is, you split it up into the body of the message and the identifier. Otherwise return null...

In getHandlerForMessage, you check if you have any handler that can handle said message. There's multiple ways to do that; one way is to have a Map<MessageType, MessageHandler> of sorts (this means max 1 handler per message type), the other is a List<MessageHandler> where each MessageHandler has a boolean canHandle(Message message) (multiple possible handlers, but first come first serve), or it could be a gigantic switch that just makes you a new MessageHandler of the correct subclass (nasty, but could work?). I'd go for the Map because it allows you to instantly see "is there a handler for this messagetype".

Then, once you have the handler, you give it the message, the player who sent the message, and the rest of the players in the game.

(Actually, you might want to wrap the game in a Game object, if games are played ON the server. What you have right now is a relay server; the server doesn't keep track of state. That's okay, if all you want is a relay server, but this does stop you from doing things like server-side anti-cheat, such as checking if players are moving into walls.)

Inside the MessageHandler, you'd go about the thing you're doing now; first, parse the message to get the relevant content, then, send out an update.

You might want to change the messages to a more easily parsable format; if you'd go with the idea that the first number; in a message is the id, why not put the rest in the same shape? Something like 0;10.5; being "update x to 10.5", with the format being id=0;x=10.5;.

You can go really far with this, as you can see. You'll have to decide how far you want to take it, but I think that at the very least, you should come up with a way for handling players one at a time by wrapping them into objects. That way you centralize message handling and reduce reliance on the availability of several variables - directly writing to sockets is low level and you don't want to deal with it next to your game logic, because the two may get mixed up.


Just a couple of things:

With ThisWorkbook.Worksheets(9)
Range(Cells(3, 13), Cells(3, 44)).Select

You miss a . here, should be .Range, without that your With doesn't have any effect.

  Selection.Calculate

Don't need to select before calculate, you could immediately do .Range(..).Calculate
(Is it really necessary in your logic to calculate before copy)

With Range(Cells(i, 13), Cells(i, 44))

Again, . is missing, should be .Range...

For i = 4 To n + 2
With Range(Cells(i, 13), Cells(i, 44))
.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.Calculate
.Value = .Value2
End With
Next i

Do you really need to do this in sequence?? You could just do:

.Range(Cells(3,13),Cells(3,44).Copy
.Range(Cells(4,13),Cells(n+2,44).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False
.Calculate
.Range(Cells(4,13),Cells(n+2,44).Value = .Range(Cells(4,13),Cells(n+2,44).Value2

You can also find some further tips here: https://stackoverflow.com/documentation/excel-vba/1107/vba-best-practices/5925/switch-off-properties-during-macro-execution#t=201706191115061969896


Find the sum of the digits of a given number

A simplified pure numerical function may be:

int digitSum(int input) {
    int n,m,s = input<0 ? -1:1;
    for(n=input*s; n>9; ) {
        for(m=n, n=0; m>0; m/=10)
            n+=m%10;
    }
    return n*s;
}


Finding the two largest three digit numbers missing from a text file

Reading input

In this specific case it doesn't make a difference, but try to break the habit of using code like:

while (!some_file.eof())

Under most circumstances this leads to incorrect behavior--in particular, it will typically result in processing the last item in the file twice. In this code, we're just setting a value in an array to 1, so setting it to 1 again doesn't change anything, and the bug is hidden. Still better to avoid it.

while(in >> data)
{
    if (data >= 100 && data <= 999)
        a[data] = 1;
}

indentation

I'm a lot less than excited about your formatting, putting the first statement in a block on the same line as the block's opening brace:

while(!in.eof())
{   in >> data;

...

for(i=999;i>=100;i--)
    {if(a[i]!=1)

The usual advice is to pick a style and use it consistently. I'd add one item to that though: unless you have a really good reason to do otherwise, pick one of the styles that's already reasonably well know and widely used (e.g., K&R, OTBS, etc.)

Standard containers

Right now, your a is basically acting as a set. That it, it simply records what numbers are present/absent in a range. The standard library already provides std::set (and std::unordered_set, though it's probably not the best choice here) specifically for that purpose. It might be worth at least considering using one of these.

Simplification

Since we care about the numbers that are missing (rather than the ones that are present), we probably want to invert the sense of our set. Rather than inserting numbers as we encounter them, then searching for what's missing, we can start by inserting all the numbers from 100 to 999, then remove the numbers as we read them from the file.

This way, when we're done reading the data from the file, our set contains exactly what we care about: the numbers in the specified range that were not present in the file (if any).

Note that this can be a little bit of a tradeoff. If we expect a lot of numbers to be missing, we could be adding a fair amount of extra work by inserting all the numbers to start with, then removing them as we read. In a case like this, with only ~900 items in the range, that's probably irrelevant though--inserting 900 items in a set is fast enough that it usually won't matter nearly as much as simplifying the code can/does.

Standard algorithms

We can also use standard algorithms to ease the job a bit, such as using std::copy_n to copy the last two items in the set to std::cout, assuming we find two or more missing numbers.

Use of braces

A fair number of people advise using braces around the statement(s) controlled by every if, while, for, etc. Personally I don't like (or usually follow) this advice, but it's pretty widespread, and if you decide to do otherwise, you should (IMO) be consistent about whether to do it or not.

Summary

Code incorporating all these could look something like this:

std::set<int> s;

for (int i = 100; i < 1000; i++)
    s.insert(s.end(), i);

int data;

while (in >> data)
    s.erase(data);

if (s.empty())
    std::cout << "All numbers were present\n";
else if (s.size() == 1)
    std::cout << "The one missing number was: " << *s.begin() << "\n";
else {
    std::cout << "The two largest missing numbers were: ";
    std::copy_n(s.rbegin(), 2, std::ostream_iterator<int>(std::cout, " "));
}


I generally prefer foreach to for, but in the case where you are using the index variable to iterate through two lists at once, for is a pretty good option. I still try to use .Zip() instead, as the other answer demonstrated, but sometimes that can get hairy. Here are some smaller improvements that don't involve changes to the overall structure.

It's always a good idea to use descriptive names

I would rename LstA to DigitsOfA (same for B, and Sum)
I would rename GetDigit to GetDigits

It's usually1 a good idea to delay declaration of a variable until it's used

A related concept is reducing variable scope; not using a global variable if a local variable will do. This doesn't have any technical impact, but it does have a readability impact: If I see you using a variable but have to scroll up to see how that variable was declared, the flow of my reading has been interrupted. We could call this "spatial scope".
Here, this would mean declaring sum and carry just before the for loop, instead of at the top of the function.
You could even declare sum inside the loop. It does seem inefficient to instantiate a new variable every iteration of the loop, but (1) the impact will probably be low, even negligible, (2) you can generally trust the compiler to do something smart (3) if making my program a tiny bit easier to read also makes it a tiny bit slower, that's a trade I'll gladly make every time.

I usually prefer var over explicit types when declaring a variable

This is the subject of a fair amount of debate, but here's my reasoning. It's easier for me to read
var prices = new Dictionary<Fruit, decimal>();
var lemon = new Lemon();
var price = 17.50;
prices.Add(lemon, price);
 than
Dictionary<Fruit, decimal> prices = new Dictionary<Fruit, decimal>();
Lemon lemon = new Lemon();
decimal price = 17.50;
prices.Add(lemon, price);
 In the former, the information I immediately want to know (what are the variables' names? how are they used?) all flows nicely down the left edge.

It's nearly always easier (to write and to read) to use LINQ's .ToList() than to call List.Add() in a loop.

This means you can initialize your lists quite easily as var digitsOfA = GetDigits(a).ToList();

Implicit braces do make your code shorter and prettier, but they are also the source of a very common bug. You write
if (awake)
    GetCoffee();
 then I come along and update your code to
if (awake)
    GetCoffee();
    GetBreakfast();
All of a sudden I'm eating breakfast while I'm still asleep. And if you're thinking I'd have to be a real bonehead to make that mistake, you're right! But it's a mistake I've made before, it's a mistake that will be made again... And it's a mistake that would be impossible if the original code were
if (awake)
{
    GetCoffee();
}
 So consider very carefully how likely it is that others might modify your code in the future, or that you might modify it before you have your coffee... I recommend the braces every time.
You can dodge the whole brace issue, however, by modular arithmetic instead of if:
carry = sum / 10;
sum = sum % 10;

I quite like the GetDigits function as it stands! That's an excellent use of yield return, in my opinion.

1This advice does not apply to Javascript, thanks to variable hoisting


Initiating Child ViewController from UIStoryBoard in iOS

There isn't another way to handle this scenario. Storyboard VC's can't be subclassed without replicating the UI also.
I'm surprised this works at all. object_setClass just changes the isa pointer, so the memory is still set up for the parent class, not the child. It will probably crash if you try to set an instance variable that doesn't exist in the parent.
Refactor the two VC's into one (since the UI is the same after all), and use composition for the differences instead.


LINQ query for a user's submitted time-off requests

Not sure what you mean by a "better" way, but assume it's not having to specify every column. You should be able to do this with an anonymous type, though you'd still have to list navigation properties if you don't lazy load:

var query = [beginning of query] select new { u, us, u.User /* other nav properties */ };

Then you could iterate the results and use a mapping tool (Automapper, FastMapper, ExpressMapper...pick your poison) to map to the VM. Depending on the mapping tool, nav properties may have to be mapped separately:

var userSubmittedRequests = new List<PendingTimeOffViewModel>();

foreach (var request in query.ToList())
{
   userSubmittedRequests.Add(/* Map request to a PendingTimeOffViewModel instance */);
}

BUT, I don't like this approach. It's means you're doing a select * against every table involved: TimeRequests, UserManagers, ApproveDenyReason, etc. Is this for a grid? I've seen too many L2E queries like this start taking forever once the amount of data gets large enough because it's pulling back way more fields than necessary. An approach I've taken for grids is to create a dedicated SQL view that does the joins for me and flattens out the data, then have a DbSet for that view. You can let L2E handle any paging via Take and Skip. And honestly, I'd still rather see every column listed in the L2E select, so SQL is only querying the necessary fields.


Some people say that adding private functions which are only called in one place in a class clutter the "private interface" of the class. However I actually do prefer it in some cases. In your case I think it makes sense as it makes InsertTrack easier to read so I would not merge the two.

As to DoesTrackExist

Check txtEventTracks.Text == "" first - this avoids performing any query at all.
I assume you meant to use the parameter txtValue instead of accessing the textbox directly.
Might not be more efficient but Any() accepts a predicate as well:

private bool DoesTrackExist(string txtValue)
{
    // maybe even consider IsNullOrWhiteSpace?
    if (string.IsNullOrEmpty(txtValue))
       return false;
    using (EMSEntities db = new EMSEntities())
    {
        return db.EventTracks.Any(x => x.TrackName.Contains(txtValue))
    }
}


Creating chat commands properly with Socket.IO

You can gain a lot of readability by formatting the code (every decent editor will do a passable job at this with a single keystroke) and extracting several small functions (refactoring). I'll start with this but only extract the reusable functions.

  Note: I assumed you can emit the initial connection count after binding the commands. If not, move the first call to emitConnectionCount inside setupSocket.

io.on('connection', function (socket) {
    if (socketConnections().length <= 1024) {
        setupSocket();
        emitConnectionCount();
    } else {
        disconnect();
    }

    function setupSocket() {
        socket.username = socket.handshake.query.username;
        socket.toString = function () {
            return this.name
        };
        socket.join(socket.handshake.query.room);
        socket.on('postName', handleUsername);
        socket.on('chat message', handleMessage);
        socket.on('users', emitConnectionCount);
        socket.on('disconnect', emitConnectionCount);
    }

    function disconnect() {
        emitToUser('PM: Sorry, we cannot allow more than 1024 connections in the server');
        emitToUser('PM: Disconnecting! Try again later.');
        emitToUser('You are not connected.', 'connections');
        socket.disconnect();
    }

    function handleUsername(username) {
        socket.username = username;
    }

    function handleMessage(msg) {
        var markedMessage = markdown.renderInline(msg.message);
        var messageDate = moment(msg.date).format("LT, D/M");
        var firstWord = markedMessage.substr(0, markedMessage.indexOf(" "));
        var messageToBeSent;
        var finalMessage;
        if (msg.message === "/help") {
            emitToUser('Montreus Chat - v1.3.3
Available commands:
/help - Display help commands
/bot-say &lt;message&gt; - Give something for the bot to say!
/broadcast &lt;message&gt; - Broadcast a message');
        } else if (firstWord === "/broadcast") {
            finalMessage = markedMessage.substr(markedMessage.indexOf(" ") + 1);
            messageToBeSent = '
 BROADCAST: ' + finalMessage + '

' + messageDate + '
';
        } else if (firstWord === "/bot-say") {
            finalMessage = markedMessage.substr(markedMessage.indexOf(" ") + 1);
            messageToBeSent = '
 Chat bot: ' + finalMessage + '

' + messageDate + '
';
        } else {
            messageToBeSent = '
' + escapeHTML(msg.username) + ': ' + markedMessage + '

' + messageDate + '
';
        }
        if (messageToBeSent.length <= 8192) {
            if (!verifyEmptyness(msg.message)) {
                emitToRoom(messageToBeSent);
            } else {
                emitToUser('PM: Sorry, you cannot send empty messages.');
            }
        } else {
            emitToUser('PM: Oops! You cannot send messages longer than 8192 characters. Sorry!');
        }
    }

    function emitToRoom(message, command) {
        io.to(socket.handshake.query.room).emit(command || 'chat message', message);
    }

    function emitToUser(message, command) {
        socket.emit(command || 'chat message', message);
    }

    function emitConnectionCount() {
        var socketsConnected = socketConnections(socket.handshake.query.room, "/");
        emitToRoom(socketsConnected.length + 1, 'connections');
    }
});

That's much easier to grok already, but let's tackle that complicated handleMessage function next. What are its responsibilities?

Parse the message to extract an optional command (/help, /broadcast, and /bot-say).
Handle the help command.
Fail if the message is empty.
Format the message using Markdown.
Embed it into an HTML snippet.
Fail if the formatted message is too long.
Emit the formatted message.

Wow, that's a lot of work--too much for a single function. Let's simplify it by extracting functions for emitting the help text and formatting the message.

function handleMessage(chat) {
    var message = chat.message;
    if (message === "/help") {
        handleHelp();
    } else {
        var split = message.indexOf(" ");
        var command;
        if (split === -1) {
            command = '/chat';
        } else {
            command = message.substr(0, split);
            message = message.substr(split);
        }
        if (verifyEmptyness(message)) {
            emitToUser('PM: Sorry, you cannot send empty messages.');
        } else {
            var realMessage = formatMessage(command, message, chat.username, moment(chat.date).format("LT, D/M"));
            if (realMessage.length > 8192) {
                emitToUser('PM: Oops! You cannot send messages longer than 8192 characters. Sorry!');
            } else {
                emitToRoom(realMessage);
            }
        }
    }
}

function formatMessage(command, message, user, date) {
    var intro;
    switch (command) {
        case '/broadcast':
            intro = 'BROADCAST';
            break;
        case '/bot-say':
            intro = 'Chat bot';
            break;
        case '/chat':
            intro = escapeHTML(user);
            break;
        default:
            intro = 'UNKNOWN COMMAND';
            message = command;
            break;
    }
    return '
 ' + intro + ': ' + message + '

' + date + '
';
}

function handleHelp() {
    sendToUser(
        'Montreus Chat - v1.3.3'
        + '
Available commands:'
        + '
/help - Display help commands'
        + '
/bot-say &lt;message&gt; - Give something for the bot to say!'
        + '
/broadcast &lt;message&gt; - Broadcast a message'
    );
}

That's better, but handleMessage is still doing too much. I don't like that it has to parse the original message, check for an empty chat message, and send the formatted message if it's not too long. Let's extract the parsing first.

function handleMessage(chat) {
    if (chat.message === '/help') {
        handleHelp();
    } else {
        var parsed = parseMessage(chat.message);
        if (verifyEmptyness(parsed.message)) {
            emitToUser('PM: Sorry, you cannot send empty messages.');
        } else {
            var message = formatMessage(parsed.command, parsed.message, chat.username, moment(chat.date).format("LT, D/M"));
            if (message.length > 8192) {
                emitToUser('PM: Oops! You cannot send messages longer than 8192 characters. Sorry!');
            } else {
                emitToRoom(chat, command, message);
            }
        }
    }
}

function parseMessage(message) {
    var split = message.indexOf(' ');
    if (split === -1 || message.charAt(0) !== '/') {
        return {command: '/chat', message: message};
    } else {
        return {command: message.substr(0, split), message: message.substr(split)};
    }
}

If you don't mind formatting an empty message that won't be sent, you can extract the format/check/send logic to yet another function.

function handleMessage(chat) {
    if (chat.message === '/help') {
        handleHelp();
    } else {
        handleChat(chat);
    }
}

function handleChat(chat) {
    var parsed = parseMessage(chat.message);
    var formatted = formatMessage(parsed.command, parsed.message, chat.username, moment(chat.date).format("LT, D/M"));
    if (verifyEmptyness(parsed.message)) {
        emitToUser('PM: Sorry, you cannot send empty messages.');
    } else if (formatted.length > 8192) {
        emitToUser('PM: Oops! You cannot send messages longer than 8192 characters. Sorry!');
    } else {
        emitToRoom(chat, command, formatted);
    }
}

Here's the final product (after a little reorganization) for ease of understanding and discussion:

io.on('connection', function (socket) {
    if (socketConnections().length > 1024) {
        disconnect();
    } else {
        setupSocket();
        emitConnectionCount();
    }

    function disconnect() {
        emitToUser('PM: Sorry, we cannot allow more than 1024 connections in the server');
        emitToUser('PM: Disconnecting! Try again later.');
        emitToUser('You are not connected.', 'connections');
        socket.disconnect();
    }

    function setupSocket() {
        socket.username = socket.handshake.query.username;
        socket.toString = function () {
            return this.name
        };
        socket.join(socket.handshake.query.room);
        socket.on('postName', handleUsername);
        socket.on('chat message', handleMessage);
        socket.on('users', emitConnectionCount);
        socket.on('disconnect', emitConnectionCount);
    }

    function handleUsername(username) {
        socket.username = username;
    }

    function handleMessage(chat) {
        if (chat.message === '/help') {
            handleHelp();
        } else {
            handleChat(chat);
        }
    }

    function handleHelp() {
        sendToUser(
            'Montreus Chat - v1.3.3'
            + '
Available commands:'
            + '
/help - Display help commands'
            + '
/bot-say &lt;message&gt; - Give something for the bot to say!'
            + '
/broadcast &lt;message&gt; - Broadcast a message'
        );
    }

    function handleChat(chat) {
        var parsed = parseMessage(chat.message);
        var formatted = formatMessage(parsed.command, parsed.message, chat.username, moment(chat.date).format("LT, D/M"));
        if (verifyEmptyness(parsed.message)) {
            emitToUser('PM: Sorry, you cannot send empty messages.');
        } else if (formatted.length > 8192) {
            emitToUser('PM: Oops! You cannot send messages longer than 8192 characters. Sorry!');
        } else {
            emitToRoom(chat, command, formatted);
        }
    }

    function parseMessage(message) {
        var split = message.indexOf(' ');
        if (split === -1 || message.charAt(0) !== '/') {
            return {command: '/chat', message: message};
        } else {
            return {command: message.substr(0, split), message: message.substr(split)};
        }
    }

    function formatMessage(command, message, user, date) {
        var intro;
        switch (command) {
            case '/broadcast':
                intro = 'BROADCAST';
                break;
            case '/bot-say':
                intro = 'Chat bot';
                break;
            case '/chat':
                intro = escapeHTML(user);
                break;
            default:
                intro = 'UNKNOWN COMMAND';
                message = command;
                break;
        }
        return '
 ' + intro + ': ' + message + '

' + date + '
';
    }

    function emitConnectionCount() {
        emitToRoom(socketConnections(socket.handshake.query.room, "/").length + 1, 'connections');
    }

    function emitToRoom(message, command) {
        io.to(socket.handshake.query.room).emit(command || 'chat message', message);
    }

    function emitToUser(message, command) {
        socket.emit(command || 'chat message', message);
    }
});

The main benefits of this version over the original are

Short functions with descriptive names make it easier to understand the program in small pieces and verify its correctness.
Repeated code has been deduplicated with reusable functions with sane defaults.
Separating responsibilities into functions allows each function to live at the same abstraction level. For example, handleMessage is only concerned with detecting /help or passing off to handleChat while the latter is only concerned with checking for a valid message. Likewise for parseMessage and formatMessage: they are both at even lower abstraction levels.
Splitting the functions also allowed reusing variable names across functions to avoid wordy repetition such as markedMessage, finalMessage, and messageToBeSent.

Here are some suggested improvements:

Add JSDoc documentation to each function that requires further explanation, especially those that take parameters. It would also be good to document the chat object passed to handleMessage.
Find better names for handleChat and handleMessage. I would reserve handle for functions bound to commands, though handleHelp does make sense. Naming can be tough at times, but a good name goes a long way. Don't be afraid of longer names like formatAndSendMessage to remove confusion.
Consider extracting sendMessage(original, formatted) from handleChat so the latter doesn't do any parsing, formatting, length-checking, or sending but merely ties those all together.


I see the point of the commenters: why implement this, if it has already been implemented? However, I still see benefit for such a question in an interview process. Given the right analysis, you can see how the developer thinks and what question he asks, which is IMHO more important than the actual code.

Questions could be:

What coding guidelines shall I follow?
Besides that single line description, do you have acceptance criteria?
Which unit test framework shall I use?
...

public class Date : IEquatable<Date>

Such low level classes use to be sealed. Could apply here as well.

public static int MaxDays(int month, int year)

Why make it public? The purpose of the class is to add days. There's nothing in the task that qualifies this method to be part of the API, IMHO. Make it private instead.

The class hardly useful, because one cannot access the properties of the changed date. There are no accessors for _month, _day and _year.

Comments: do you expect XML-doc comments on public (API) methods? You don't have them.

// [...] thinking about using in constructor for validation.

What would you do if it's invalid? Throw an exception? Well, Microsoft does it ...

Magic number:

if (month == 2)

Introduce a constant February to give it semantics.

I write code in some languages and operator precedence is always an issue. The line

if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))

is hard to understand. A method IsLeapYear() might help you out of that:

private static IsLeapYear(int year)
{
    if (year % 400 == 0) return true;
    if (year % 100 == 0) return false;
    if (year % 4 == 0) return true;
    return false;
}

At the same time it gives sematics to the magic numbers.

Why do we have AddDays() but not SubtractDays()? Can I pass a negative number for subtracting, or is subtracting not allowed?

Your code does not seem to support subtraction, but the data type is still int and not uint.

return new Date(day, month, year);

Do you expect immutability? Why? For performance reasons / multi threading? Is this premature optimization? Immutability comes at the cost of garbage collection.

Magic number:

if (month > 12)

What if the interviewed person uses _daysInMonth.Length? Is that better or worse than your implementation?

Hash codes etc.: do you provide an IDE which can generate equality members (like Jetbrains R#), or do you expect the developer to come up with that prime stuff by himself?

I have never written such code myself and actually I don't want to work in a company that expects me to write such code (except I'm applying to some security company which has to deal with hashes and encryption).


Holding server response header data after parsing it

The way I would do it is by simply representing the headers as map of char* to char*. That'll be the most flexible and extensible situation, since HTTP headers are added over time, and custom headers are completely acceptable and allowed for by the standard. Any solution involving struct fields will require updating as the standard expands, and can't handle custom headers easily. (You could handle custom headers the same way as standard ones, but then you'd have the problem that their meaning is not standard, and different clients could use them to represent different things.)

The downside of making the map values be char* is that you'll have to translate into the proper data type wherever you retrieve them from the map, rather than only performing this translation when you read the request headers. This is an acceptable trade-off for the flexibility you gain, and you can find a way to encapsulate it if desired.


Use java.util.Deque

Instead of implementing your own stack,
it's better and easier to use the Deque in the JDK.
(Not Stack, as the JavaDoc explains, Deque is recommended.
Thanks @greybeard for the tip!)

Naming

In this game there are discs and towers (or sticks, rods, pegs).
It would be better to call them that way instead of Node and Stack.

tower is a poor name for moving discs.
In general, verbs are best for method names.
In this example move would be natural.

Alternative implementation

With the above suggestions applied,
the implementation becomes:

import java.util.ArrayDeque;
import java.util.Deque;

public class Hanoi {

    private static class Tower {

        private final String name;
        private final Deque<Integer> stack;

        public Tower(String name) {
            this.name = name;
            this.stack = new ArrayDeque<>();
        }

        public void add(int... discs) {
            for (int disc : discs) {
                stack.push(disc);
            }
        }

        public int size() {
            return stack.size();
        }

        public void moveOneDisc(Tower to) {
            System.out.println("Pushed " + this.stack.peek() + " from " + this.name + " to " + to.name);
            to.stack.push(this.stack.pop());
        }

        private void moveDiscs(int count, Tower mid, Tower to) {
            if (count == 1) {
                moveOneDisc(to);
            } else {
                moveDiscs(count - 1, to, mid);
                moveOneDisc(to);
                mid.moveDiscs(count - 1, this, to);
            }
        }
    }

    public static void main(String[] args) {
        Tower from = new Tower("A");
        from.add(10, 15, 20, 25);
        Tower mid = new Tower("B");
        Tower to = new Tower("C");
        from.moveDiscs(from.size(), mid, to);
    }
}

Some other improvements:

Moved the tower method inside the Tower class and renamed to move
Tower.add accepts varargs, for conveniently adding multiple discs
Tower.size to know the number of discs on a tower
The method names of Tower are all in the language of the problem domain, not the implementation (implementation details are well hidden)


Checking whether a store is open or not by querying over its business hours

Here's your problem:

<%= render @stores %>

<% if store.open? %>

You're rendering multiple stores via partials. When each partial is fully rendered out it looks like this:

<% if store.open? %>

<% if store.open? %>

<% if store.open? %>

<% if store.open? %>

Each call to

<% if store.open? %>

will result in a db query, which is where your n+1 problem is coming from.

You have 2 options:

1. Eager loading

#pseudocode
#controller
@stores = Store.includes(:business_hours).where(some_condition:...)

#partial
<% if store.is_open?(store.business_hours) %>

#model
def is_open?(business_hours)
   open = business_hours.detect {|h| (h.wday == Time.now.wday) && ((h.open_time..h.close_time).cover?(Time.now)) }
   open.present? ? true : false
end

May get very memory intensive if you have thousands of stores and many business_hours for each store.

2. Denormalize your database and cache weekdays and business hours in your table

#pseudocode
#migration
table "stores"
   t.integer wday
   t.string open_time
   t.string close_time

#model
def is_open?
  (self.wday == Time.now.wday) && ((self.open_time.to_time..self.close_time.to_time).cover?(Time.now))
end

The approach you take will depend on how many records you need to deal with at any one time.


I'm not entirely sure how the performance will compare, but the standard way to accomplish this would be the erase-remove idiom:

str.erase(std::remove(str.begin(). str.end(), ch), str.end());

Unless the performance proves to be a bottleneck, it's typically better to stick with the C++ style of doing things.  I can't imagine that this would be significantly less efficient than the other method.  (In fact, I wouldn't be surprised if this is a bit faster for long strings with a high amount of the removed character -- though my assumption of that depends on quite a few non-guaranteed implementation choices, and a rather rough estimation of the cost of different low level operations.)


Abstract Interface for managing Init/Shutdown

I'm afraid to say I don't like this design. You seem to have put quite a lot of thought into it, but you really don't gain much with it.

This is not an interface in the usual sense: it has state. Interfaces are collections of (usually) pure-virtual functions (with perhaps a non-pure virtual destructor) with no non-static data members. Multiple inheritance is tricky, picking up state from multiple bases just makes it trickier.
Implementing your interface forces every user to add a bunch of boiler-plate code for your design to work. That doesn't scale, leads to copy-pasta bugs (or forgetting to copy/paste bugs).
Your goal: "make resetting [the components] easier". Your interface reads like "provide a way of initializing and shutting down things". Minor semantic nitpick but a reset interface should have only one method: reset. This ties into the next point:
"unless I track the [...] state of the object [...], undefined behavior could creep in." - this is not good C++ design. Your objects should be responsible for their invariants, not some third-party addon to their class structure. Constructors should establish the invariants, destructors should to whatever cleanup is required. In between, i.e. when the object is alive, all its public members should maintain a consistent state. That you're worried about undefined behavior if you call a method "out of sequence" seems to indicate that you're not (sure of) following this rule. If that's the case, then you should fix your classes to follow it rather than try to tack on something artificial from outside, with its accompanying boilerplate.

So if you want to stick with this resetting interface, I'd go with something much simpler:

struct Resetable {
  virtual void reset() = 0;
  /* or, if passing in the "new state of the world" is needed */
  virtual void reset(GameState &) = 0;
};

Your classes must know if they need to release resources or not when reset is called (you can't write a correct destructor if they don't). For some of your classes that reset member will be trivial, for some others it might need to call into several helpers to get the job done - that's fine. Its the class's job to know how it needs to be reset, the public interface shouldn't expose that complexity.

You might also want to take a second look at your class hierarchies and figure out whether this actually should be an independent interface or if reset should be directly in the base class(es).

Or you could drop that interface completely and just use the C++ builtin stuff to create shiny fresh objects and get rid of them: constructors and destructors.

Random thoughts:

Your classes, methods and data members all start with capital letters. That seems a bit strange to me. But if you apply it consistently, well, that's your choice.
Init and Shutdown don't return anything, so the only way for them to signal failure is exceptions (or just terminating the program). That's fine if you use (and handle) exceptions, otherwise you should make them return some sort of status or error code (same for reset if you go that route).
Careful if you run multiple threads, the posted code isn't thread-safe.
const bool &IsActive; seems like a pessimisation to me. I don't think compilers will optimize that reference member out, so you're adding something like a pointer on top of the bool overhead to each and every implementer of the interface. bool isActive() const { return IsActive_; } would almost certainly be inlined and has no per-object overhead.