Repeating code infinitely

Right now, in order to have QuadSolver repeat forever, you're calling it recursively, by calling QuadSolver again inside of itself. Unlike functional languages, which are optimized for tail-call recursion, Python isn't. Once you've recursed in the same function 1000 times, Python will raise an error. You can technically set the recursion limit using sys.setrecursionlimit, but this is a very "hacky" way to do things.

The proper way to make any piece of code repeat for a variable amount is to use a while loop. This means that the body of your QuadSolver function should be wrapped in a while loop, like this:

def QuadSolver():
    while True:
        # Original code goes here.

By doing this your code gains a few good things:

It will properly execute forever.
It's faster.
It's more readable, e.g, it's clear to the reader that you're executing a chunk of code forever.

Integer input validation

Never trust the user to enter the correct input. For example, what if I ran your program and entered asghiopisdfiojgpfdj for the variable a? Your program would raise a ValueError and crash. You need to use a try/except block to catch a ValueError in case the user enters the wrong input. This means that this section of code here:

a = int(input(" What is the value of a? ---> "))
b = int(input(" What is the value of b? ---> "))
c = int(input(" What is the value of c? ---> "))

Should be wrapped in a try/except block, like this:

try:
    a = int(input(" What is the value of a? ---> "))
    b = int(input(" What is the value of b? ---> "))
    c = int(input(" What is the value of c? ---> "))

    # Original code below the above section goes here.
except ValueError:
    print("Please enter a valid integer.")

Now, if a user enters incorrect input, the program will alert them to this, and start over.

Proper string formatting

The % operator is deprecated as of Python 2.6. Instead, you should be using the str.format function instead. For example, this line:

print("         X=%d  OR  X=%d ") % (X, X2)

Would become this:

print("         X={x1}  OR  X={x2}".format(x1=X, x2=X2))

str.format supports the following styles:

Normal parameters:

"{} {}".format("Hello", "world")

Positional parameters:

"{1} {0}".format("world", "Hello")

Named parameters:

"{word1} {word2}".format(word1="Hello", word2="world")

You can do a great deal more with str.format, but I'll leave it up to you to figure that out, as there's too much for this one post.

Getting rid of the system calls

I find all of these lines of code to be absolutely horrid:

os.system('cls')
os.system('')
os.system('color a')
os.system('title Quadratic Equation Solver')
os.system('pause >nul')

Especially this one in particular:

os.system('pause >nul')

There are many things wrong here. For starters, the call to os.system has a long startup and "cooldown" period, e.g, it takes a fair amount of time. Secondly, all the commands you're running, like cls, color, or pause are very Windows-specific. What happens if someone wants to run this on a Linux-based system? Most of these system calls are purely stylistic, and unnecessary anyways.

On the matter of this line:

os.system('pause >nul')

I find it awful that bad C++ practices are leaking into Python. The method above is slow, insecure, and unreadable. If you want to pause until user input, just use the standard input operations of your language. In the case of Python, that would just look like this:

input()

If you're still using Python 2.x for some reason, it would look like this:

raw_input()

Proper style

Unlike many languages, Python has an official style guide, PEP8, and you're violating a fair amount of the guidelines set there.

Variable names should be in snake_case, and UPPER_SNAKE_CASE if they're constants.
Function names should only be in snake_case.
Classes should be in PascalCase.
You should have two spaces between top-level code/functions/classes.

While the following items aren't actually in PEP8, they're kind of a code smell, and should be removed.

Separator comments, like the one below this should be removed. They're useless and look bad in your code.

#------------------------------------------------

Inline comments on the end of code lines should be removed. If you're having to put comments on the end of lines of code, then you probably aren't writing the code in a clear enough way. If you feel the need to put comments at the end of lines of code, then chances are, those lines should be re-written.

It's also worth mentioning docstrings as well. Docstrings are a convenient way to describe your functions and classes in Python, much like XML documentation in Visual Studio. A typical function docstring generally looks something like this:

def my_function( ... ):
    """Brief description of the function.

    Detailed description of the function.

    argument_name -- Argument description.
    """

If we take this and apply it to your QuadSolver function, we get something like this:

def quad_solver():
    """Solve the quadratic equation.

    This function takes user input, a, b, and c, and
    runs it through the quadratic equation to "solve"
    it.
    """
    ...


Object literals
By the looks this is client side UI only and the actual results are stored in the database.
Your concern is not that of the data structure, but rather one of representation.
The task is defined by what you have in createAnswerSelect(validAnswers) {
Your code is attempting to imitate a higher level abstraction unrelated to the task you need to complete. This has forced you to presented 4 additional interfaces to the scope you are working in  Answer, UnansweredState, ValidAnswerState, InvalidAnswerState that you are unsure of.
Javascript lets you define objects as literals, you can side step the noise related to defining named Objects, Prototypes, functions, calls to super etc, yet still keep the same underlying relationship of shared and unique state.
Example
The best code is that which does it quickly and as simply as possible. Creating an inherited structure just to hold some shared and unique states is too complex.
This example is an alternative (based on the information you have provided)
It defines the 3 states as named constants that access state information via a Map of named states, rather than the 3 objects you defined UnansweredState, ValidAnswerState, InvalidAnswerState
const UNANSWERED = 1;
const INVALID = 2;
const VALID = 3;

const createElement = (type, opts = {}) => Object.assign(document.createElement(type), opts);
const common = (icon, color) => ({icon, color});
const states = new Map([
  [UNANSWERED, {...common("remove", "grey"), data: {unanswered: ""}}],
  [INVALID, {...common("clear", "red"), data: {valid: "", icon: "icons/round-done-24px.svg"}}],
  [VALID, {...common("done", "green"), data: {invalid: "", icon: "icons/round-clear-24px.svg"}}],
]);
const option = (answer, stateId) => {
  const state = states.get(stateId);
  const option = createElement("option", {value: answer, textContent: answer });
  Object.assign(option.dataset, state.data);
  option.dataset.validationIcon = state.icon;
  option.dataset.validationColor = state.color;
  return option;
}

function createAnswerSelect(answers) {
  const select = createElement('select');
  select.add(option("Unanswered", UNANSWERED));
  answers.forEach(answer => select.add(option(answer.answer, VALID)) );
  select.add(option("Incorrect response", INVALID));
  return select;
}
export { createAnswerSelect };


Welcome to SO and glad you are learning Ruby.
You know there are easy ways in Ruby to do convertions between numbers ?
If not take a look at this blog http://rubyquicktips.com/post/18935873770/convert-between-number-bases-easily

Answering your question: you have a lot of boiler code which you could cut by taking the exponent of each digit like here under. While I still could do this shorter by injecting an object instead of declaring the dec = 0 I won't do so for readability.

I use the method each_char on the string to split into a character array and daisychain this result to another method with_index that adds... yes an index.
Then I use the formula below to add the exponent of that char multiplied by 2 (the base) converted to an integer taking into account the position in the string.
This is not the best algorithm by far to do this, just an example how to use these methods to shorten your code and make it more 'Rubylike'.
If you search for good exercises which you can test and compare your results with others solutions taka a look at https://www.codewars.com

Happy code learning !

bin_input = "1111"
puts bin_input.to_i(2)  #=> 15 this is the normal Ruby way

# This is our educational way
dec = 0
print dec
bin_input.to_s.each_char.with_index do |char, index|
  dec += (char.to_i*2)**(bin_input.length-(index+1))
  puts "+(#{char.to_i*2})**(#{bin_input.length-(index+1)})"
end
puts dec # 15

Which gives

15
0+(2)**(3)
+(2)**(2)
+(2)**(1)
+(2)**(0)
15


Before entering into the meat of the answer, let's talk about time accuracy for a bit.

For starter, time.sleep is not extremely accurate as it can be (a little bit) longer than the requested sleeping time. And even if it was, you’re performing work inbetween the repeated sleep calls, which take time and add up. So each cycle in the while loop of countdown_timer take more than a single second. Let's evaluate how much by using the following file:

import time
import datetime
import timeit

def countdown_timer(x):
    while x >= 0 :
        x -= 1
        print("{} remaining".format(str(datetime.timedelta(seconds=x))))
        print("\n")
        time.sleep(1)

if __name__ == '__main__':
    print(timeit.timeit(lambda:countdown_timer(120), number=1))

And the output is:

0:01:59 remaining

0:01:58 remaining

[Snip for readability]

0:00:01 remaining

0:00:00 remaining

-1 day, 23:59:59 remaining

121.14761522800109

Wow… That remaining time at the end… That's unexpected. Thing is that the way your while loop is setup, you are performing x + 1 iterations; which explains the 121 seconds your countdown take as well as that last remaining time. Just change the condition to while x > 0: and you’re good. But do you see that your counter drift of about 150ms over the course of two minutes? That will be 1 second and a half after 20 minutes, between 4 and 5 seconds on a 1 hour timer and several minutes for a 1 day timer…

You need to account for that drift. And the easiest way to do it is to maintain an ideal time to sleep up to which is 1 second in the future, and then compute the difference between the current time and this ideal time to try and sleep this exact amount of time. Luckily, this difference is easily computed using timedelta.total_seconds:

import time
import datetime
import timeit

def countdown_timer(x, now=datetime.datetime.now):
    target = now()
    one_second_later = datetime.timedelta(seconds=1)
    for remaining in range(x, 0, -1):
        target += one_second_later
        print(datetime.timedelta(seconds=remaining), 'remaining', end='\r')
        time.sleep((target - now()).total_seconds())
    print('\nTIMER ended')

if __name__ == '__main__':
    print(timeit.timeit(lambda:countdown_timer(120), number=1))

And the timing is way better:

0:00:00 remaining
TIMER ended
120.00124583899742

Just a single millisecond of drift. In fact, this drift is always compensated for and never accumulate. A run for 1200 seconds outputs:

0:00:00 remaining
TIMER ended
1200.0010585399978

Now for the rest of the code. Did you note how the calling code was under an if __name__ == '__main__': clause? You should get into this habit as it allows to more easily import and test the code you are developping. This will also hopefully force you to gather your code into functions and to make better usage of parameters and return values.

A coarse rewrite could look like:

import time
import datetime

def countdown_timer(x, now=datetime.datetime.now):
    target = now()
    one_second_later = datetime.timedelta(seconds=1)
    for remaining in range(x, 0, -1):
        target += one_second_later
        print(datetime.timedelta(seconds=remaining), 'remaining', end='\r')
        time.sleep((target - now()).total_seconds())
    print('\nTIMER ended')

def get_input_format(supported_formats=('hrs', 'min', 'sec')):
    while True:
        units = input('Enter the format in which you want to time yourself {}: '.format(supported_formats))
        if units in supported_formats:
            return units
        print('Invalid input. Please re-enter your desired format')
        print('The input is case sensitive')

def IOTimer(unit_input):
    while True:
        try:
            if unit_input == "hrs":
                hours = int(input("Enter the number of hours: "))
                print("\n")
                minutes = int(input("Enter the number of minutes: "))
                print("\n")
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
            elif unit_input == "min":
                hours = 0
                minutes = int(input("Enter the number of minutes: "))
                print("\n")
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
            elif unit_input == "sec":
                hours = 0
                minutes = 0
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
        except:
            print("Invalid Input. Re-enter the values")
            print("\n")
    hours_in_sec = hours*3600
    minutes_in_sec = minutes*60
    total_seconds = hours_in_sec + minutes_in_sec + seconds
    print("Starting countdown for {}".format(str(datetime.timedelta(seconds=total_seconds))))
    print("\n")
    time.sleep(2)
    countdown_timer(total_seconds)

if __name__ == '__main__':
    IOTimer(get_input_format())

But there is still improvement for the IOTimer function:

the name looks like it is a class as per PEP8, the official Python style guide, function names should be lower_snake_case;
I already removed the recursive call as it is already handled by the while True: loop;
there is a lot of repetitions in the various if statements;
you should not use a bare except statement, always specify the exceptions you’re expecting, otherwise it may create hard-to-diagnose bugs;
I hardly see a valid reason to sleep 2 seconds before starting the timer.

Revised version look like:

import time
import datetime

def countdown_timer(x, now=datetime.datetime.now):
    target = now()
    one_second_later = datetime.timedelta(seconds=1)
    for remaining in range(x, 0, -1):
        target += one_second_later
        print(datetime.timedelta(seconds=remaining), 'remaining', end='\r')
        time.sleep((target - now()).total_seconds())
    print('\nTIMER ended')

def get_input_format(supported_formats=('hrs', 'min', 'sec')):
    while True:
        units = input('Enter the format in which you want to time yourself {}: '.format(supported_formats))
        if units in supported_formats:
            return units
        print('Invalid input. Please re-enter your desired format')
        print('The input is case sensitive')

def main(unit_input):
    hours = minutes = seconds = 0
    while True:
        try:
            if unit_input == 'hrs':
                hours = int(input('Enter the number of hours: '))
            if unit_input != 'sec':
                minutes = int(input('Enter the number of minutes: '))
            seconds = int(input('Enter the number of seconds: '))
        except ValueError:
            print('Invalid Input. Re-enter the values')
        else:
            break
    delay = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
    print('Starting countdown for {}'.format(delay))
    countdown_timer(int(delay.total_seconds()))

if __name__ == '__main__':
    main(get_input_format())

But the whole point of these two extra functions is to only gather parameters for the script from the user. Let specialized modules do the work for you. Let me introduce you to argparse:

import time
import datetime
import argparse

def countdown_timer(x, now=datetime.datetime.now):
    target = now()
    one_second_later = datetime.timedelta(seconds=1)
    for remaining in range(x, 0, -1):
        target += one_second_later
        print(datetime.timedelta(seconds=remaining), 'remaining', end='\r')
        time.sleep((target - now()).total_seconds())
    print('\nTIMER ended')

def command_line_parser():
    parser = argparse.ArgumentParser(description='Simple countdown timer', conflict_handler='resolve')
    parser.add_argument('seconds', type=int, help='amount of seconds to wait for')
    parser.add_argument('-m', '--minutes', '--min', type=int, help='additional amount of minutes to wait for')
    parser.add_argument('-h', '--hours', type=int, help='additional amount of hours to wait for')
    return parser

if __name__ == '__main__':
    args = command_line_parser().parse_args()
    delay = datetime.timedelta(**vars(args))
    print('Starting countdown for', delay)
    countdown_timer(int(delay.total_seconds()))

Usage being:

$ python simple_timer.py -h 1 -m 23 45


Changing attributes in different objects

First, to answer your question on passing by value/reference, Python doesn't pass mutable (e.g. list, dict) and immutable (e.g. str, tuple) objects any differently - the difference appears because they are[n't] mutable, i.e. can[not] be changed in-place. Names in Python are just references to objects.

When you pass an immutable object:

def calling():
    foo = "bar" # bind str object to name 'foo' in scope of 'calling'
    called(foo) # pass reference to str object to 'called'
    print(foo) # still "bar"

def called(baz): # first arg object will be bound to name 'baz' in scope of 'called'
    baz = "{0}!".format(baz) # rebinds name 'baz' to **new str object**
    print(baz)

In this case, the string is immutable, it can't be changed in-place, so changes in called won't be reflected in calling, as calling still references the original object.

By contrast, with a mutable type:

def calling():
    foo = [] # bind list object to name 'foo' in scope of calling function
    called(foo) # pass reference to list object to 'called'
    print(foo) # see change from 'called'

def called(baz): # first arg object will be bound to name 'baz' in scope of 'called'
    baz.append("hello, world") # object bound to name 'baz' (and 'foo') **is changed**
    print(baz)

You should read and consider following the Python Style Guide, PEP-0008 - class names should be CapitalizedWords and variable, function and method names should be lowercase_with_underscores.

optionsClass can be streamlined. At the very least, note that

if self.Option1 == True:
    self.Option1 = False
else:
    self.Option1 = True

can be simplified to:

self.Option1 = not self.Option1

Dictionaries would allow you to simplify further:

class OptionsClass():

    id_map = {'Option1': 1, 'Option2': 2}

    def __init__(self, options=None):
        if options is None:
            options = {1: True, 2: False}
        self.options = options

    def change(self, option_id):
        self.options[option_id] = not self.options[option_id]

    def __getattr__(self, attr_name):
        return self.options[id_map[attr_name]]

Now you can use it:

>>> o = OptionsClass()
>>> o.Option1
True
>>> o.Option2
False
>>> o.change(1)
>>> o.Option1
False


Many thing can be improved to make your code faster and clearer:

Multiple useless calls to str

You keep calling str on ter which is a string already. You can replace every occurence of "str(ter)" by "ter".

The 2 loops with (apparently) different loop indices can be written in a single loop

Unless I am missing something, the 2 loops could be written with a single loop.

Loop like a native

I highly recommend watching Ned Batchelder's excellent talk "Loop like a native". In a nutshell, any time you use range and len together, there is a better way to do it.

In your case, after taking the comment above, the code becomes :

for c in ter:
    if c == '0':
        wordx = wordx + x1
    if c == '1':
        wordx = wordx + x2
    if c == '2':
        wordx = wordx + x3
    if c == '0':
        wordy = wordy + y1
    if c == '1':
        wordy = wordy + y2
    if c == '2':
        wordy = wordy + y3

Similar conditions

You have the same conditions evaluated twice. You could group them together.

elif

You could use elif between your mutually exclusive cases.

+=

You could use a += b instead of a = a+b.

Then your code becomes:

for c in ter:
    if c == '0':
        wordx += x1
        wordy += y1
    elif c == '1':
        wordx += x2
        wordy += y2
    elif c == '2':
        wordx += x3
        wordy += y3

Single value provided to %

Instead of builting a tuple with a single value via "%01d" % (float(ter),), you could directly write "%01d" % float(ter).

Loop like a native again

Instead of writing a while True to loop over integers, you could use itertools.count.

import itertools
for x in itertools.count(1):
    ter = "%01d" % float(ternary(x))

divmod

A builtin called divmod does exactly what your are doing in your ternary function.

Final code

Many things can still be improved but here is my current version of the code:

import sys
import itertools

x1 = "aba"
x2 = "a"
x3 = "bab"
y1 = "a"
y2 = "ab"
y3 = "abaa"

def ternary(n):
    if n == 0:
        return ''
    else:
        e, q = divmod(n, 3)
        return ternary(e) + str(q)

for x in itertools.count(1):
    ter = "%01d" % float(ternary(x))
    #print("ter = " + ter)
    wordx = ""
    wordy = ""
    for c in ter:
        if c == '0':
            wordx += x1
            wordy += y1
        elif c == '1':
            wordx += x2
            wordy += y2
        elif c == '2':
            wordx += x3
            wordy += y3

    if wordx == wordy:
        print("Wordx = " + wordx + " and wordy = " + wordy + " and the decimal number is = " + str(x) + " and the ternary number is = " + ter)
        sys.exit("Yes!")


Click-through rate calculator using jQuery

I think this style is what causes a lot of the "jquery mess" you hear people talk about. Let me try to explain why.

What's going on is that the code tries to handle every possible view state change.
For example, when you want to highlight a certain input, you also need to consider that one or both of the other inputs are highlighted already and so you need to hide them.
What you can do instead is to "reset" the view state before every run and in that way only have to consider the one case.
This is called declarative programming, since you basically declare what your view will look like given a certain state, but you don't care about moving from one state to another.

In your case, you would "reset" your view state like so:

$('#v1,#v2,#v3').css('background-color', 'transparent')

Adding this simple line at the start of your click-handler removes a ton of noise from the rest of the code.

Here's a couple of other things that can be improved:

Only use ', not " as well
Don't duplicate jquery selectors
Use better names than v1,v2,v3
If you only care that the user inputs two values, check that (as opposed to checking exact combinations)

Here's one attempt at a refactoring (not tested):

$(document).ready(() => {
    $('#btn').on('click', () => {
        let $impressions = $('#v1')
        let $clicks = $('#v2')
        let $ctr = $('#v3')
        let inputs = [$impressions, $clicks, $ctr]

        inputs.forEach($input => $input.css('background-color', 'transparent'))

        let nFilled = inputs.filter($input => $input.val() !== '').length
        if(nFilled !== 2){
            alert('Please enter exactly 2 values!')
            return
        }

        let setCalculatedInput = ($input, value) => {
            $input.val(value)
            $input.css('background-color', 'beige')
        }

        if($impressions.val() === ''){
            setCalculatedInput($impressions, (parseInt($clicks.val()) / parseInt($ctr.val())) * 100)
        }else if($clicks.val() === ''){
            setCalculatedInput($clicks, (parseInt($impressions.val()) * parseInt($ctr.val())) / 100)
        }else if($ctr.val() === ''){
            setCalculatedInput($ctr, (parseInt($clicks.val()) / parseInt($impressions.val())) * 100)
        }
    })
})


Is this a good way of handling item reservations?

Placing locks is inherently fragile, especially on a website.  HTTP is stateless, and a user could walk away or close the browser at any time, leaving a lock in place forever.

I would create a table of Lock objects, where each Lock refers to an item, states the quantity, and most importantly has a creation timestamp.  Locks that are too old can easily be purged or ignored.


An elegant way to find diff of two list of objects in Java

I would create this method:

private MyObject findMatch(List<MyObject> objsFromDB, MyObjRequest req_obj){
    for(MyObject db_obj : objsFromDB){
        if(isSameObj(db_obj, req_obj)){
            return db_obj;
        }
    }
    return null;
}

and refactor accordingly.

Beyond that the only suggestion I would have is perhaps some better variable names (at least use a single naming style; if you don't already have one, use this: http://www.oracle.com/technetwork/java/codeconventions-135099.html#367).


In addition to Reinderien's answer, may I suggest:
Yes, Use Memoryviews to speed up access
In addition to the code you have, I would also type the a_mat and b_mat matrixes as double[:,::1] following the Typed Memoryviews guide. (the "1" means contiguous and is allows for slightly faster access). You are right in that you can not cdef declare variables in a loop, but you can cdef declare variables at the top of the function, and reassign within the loop.

    ...
    cdef list Estimate_1_list = []
    cdef list Estimate_2_list = []
    cdef int l,i,t,j
    cdef double[:, ::1] a_mat # declare here
    cdef double[:, ::1] b_mat
    for l in my_list:

        # Resizable matrices (could I use memory view?)
        a_mat = np.zeros((l,n+1),float) # assign in loop
        b_mat = np.zeros((l,n+1),float)
    ...

Turn off Boundscheck And Wrap Around check
Once you are sure that code is bug free. You can locally turn off bounds and wraparound checks using the decorators or with statements for additional speed up. (Compiler Directives, Local Directives)


Create static functions findById and findByUsername and clean-up User constructor or modify it to accept $id and $udata; you can also make it private, if you don't need it outside.

class User {
    // ...

    public static function findById (id) {
        // TODO
    }

    public static function findByName (name) {
        // TODO
    }
}

$user = User::findById(51)
$user2 = User::findByName("JohnDoe")


TTT is not a clear name, TicTacToe is only 6 characters more, and much clearer.

You should have winning_matrix be a constant, defined just inside the class declaration:

class TicTacToe:
    WINNING_MATRIX = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))

Indexing a literal is odd to see, you should declare the constant ICONS and index that.

ICONS = ['.', 'O', 'X']

...

print ICONS[grid[square]],

I personally prefer using print('\n') to make it more clear what's happening as it can look funny to see just a print. You also shouldn't use an inline if as they're very easy to misread.

if square % 3 == 0: print
print ['.', 'O', 'X'][grid[square]],

The above looks like the if is meant to apply to the print call beneath it, but has an indentation error. Even when you spot the print, it seems like that was put there accidentally because it doesn't seem to print anything.

if square % 3 == 0:
    print('\n')
print(ICONS[grid[square]])

Also, instead of iterating over numbers and using those to index you should iterate over grid itself. You need the index of the values to detect when to print a new line, but you can still do this using enumerate.

for index, square in enumerate(grid):
    if index % 3 == 0:
        print('\n')
    print(ICONS[square])

This is much simpler than a double index. Plus, if you were to change the size of grid for any reason, you'd then be able to handle it just fine. The one last change, particularly in that case, could be to replace the 3 with a constant like ROW_WIDTH.

You could also make functions a lot clearer, like this:

def winner_is(self, total):
    '''Establishes which player wins in current node'''
    return total/3 if abs(total)==3 else 0

Your docstring is vague, and more abstract than it should be. Tell me what the function does, not what it's for.

def winner_is(self, total):
    '''Returns -1 or 1 to indicate which player won, or 0 for a tie.'''

However what's odd is that you're doubling down on your check for if the total is 3? You're calling self.winner_is when you've already determined that the total is three, or when it's definitely a tie. I'd combine the functions into one:

def check_game(self, grid):
    '''Returns -1 or 1 to indicate which player won, or 0 for a tie.'''

    for row in self.winning_matrix:
        total = sum([grid[x] for x in row])
        if abs(total) == 3:
            return total / 3
    return 0

Now it's much simpler and contained, but still does exactly the same. I'd also consider renaming this, as it's unclear what a check would do, or what aspect of the game it applies to. eval_winner could improve the clarity.


This question is more than a year old, so a few things have changed in Swift since. Most notably, SequenceOf and GeneratorOf have been renamed to AnySequence and AnyGenerator respectively.

I'd rename gen to generator so that in the while loop, you can do:
while let gen = generator {
    ...
}

That way, you don't have to force unwrap gen.

You need to declare generator and the elements of queueas AnyGenerators for this to work. That way they are ensured to be reference types and gen and generator refer to the same instance.
// Current generator, or `nil` if all sequences are exhausted:
var generator: AnyGenerator<S.Generator.Element>? = AnyGenerator(seq.generate())
// Queue of generators for sequences which still have to be enumerated:
var queue: [AnyGenerator<S.Generator.Element>] = []

The four lines where you try to dequeue the first generator could be written in one line if Arrays had a popFirst function. (Which it should but weirdly doesn't.) So we can define that ourselves in an extension. (though this really is a matter of preference)
extension Array {
    mutating func popFirst() -> Generator.Element? {
         if let elem = first {
            removeAtIndex(0)
            return elem
        }
        return nil
    }
}

Now we can write:
generator = queue.popFirst()

This one might be going a bit far because we're extending Array just to get rid of 3 lines, but I really think it improves readability. In the end it's your call.

Put together, that gives us:
func sequentialFlatten<S : SequenceType>(seq : S, children : (S.Generator.Element) -> S) -> AnySequence<S.Generator.Element> {
    return AnySequence {
        () -> AnyGenerator<S.Generator.Element> in

        // Current generator, or `nil` if all sequences are exhausted:
        var generator: AnyGenerator<S.Generator.Element>? = AnyGenerator(seq.generate())
        // Queue of generators for sequences which still have to be enumerated:
        var queue: [AnyGenerator<S.Generator.Element>] = []

        return AnyGenerator {

            while let gen = generator {
                if let next = gen.next() {
                    queue.append(AnyGenerator(children(next).generate()))
                    return next
                }
                // Current generator is empty, try to deque next one:
                generator = queue.popFirst() // `nil` if queue is empty
            }
            return nil
        }
    }
}

This version works exactly As your old version, which is breadth-first. This less than ideal, since a breadth first search takes more memory. Additionally, you asked:

Can sequentialFlatten() be implemented in a way that it calls itself recursively?

Let's see if we can't kill two birds with one stone.
SequentialFlatten(), a recursive approach
Here's my thinking, if we want to go depth first, we must explore the subtree attached to an element before visiting its siblings. We can solve this problem recursively, by maintaining two generators at each level. one for the sequence that was passed in, and another one for the children of the top level element we last generated:
var mainGen = seq.generate()
// Current generator, or `nil` if all sequences are exhausted:
var generator: AnyGenerator<S.Generator.Element>?

Initially, generator is nil, so we'll definitely use a guard to unwrap it and return the first element of the main generator if it's nil:
guard let gen = generator else {
    if let elem = mainGen.next() {
        generator = // get the generator for elem's children
        return elem
    }
    return nil
}

This is where recursion comes in:
generator = sequentialFlatten(children(elem), children: children).generate()

It might have been better to define a local function that return a Generator and make that recursive instead of wrapping the Generator up in a Sequence only to then get the Generator again, but I think either way works.

Now all that's left to do is return the right element if generator is not nil and create a new generator when our current one is empty. This can all be solved in one go:
guard let gen = generator, let elem = gen.next() else {
    if let elem = mainGen.next() {
        generator = sequentialFlatten(children(elem), children: children).generate()
            return elem
        }
        return nil
    }
    return elem

We now have the next element of the generator and the generator being nil or empty can be treated the same.

Putting this all together gives us:
func sequentialFlatten<S : SequenceType>(seq : S, children : (S.Generator.Element) -> S) -> AnySequence<S.Generator.Element> {
    return AnySequence {
        () -> AnyGenerator<S.Generator.Element> in

        var mainGen = seq.generate()
        // Current generator, or `nil` if all sequences are exhausted:
        var generator: AnyGenerator<S.Generator.Element>?

        return AnyGenerator {

            guard let gen = generator, let elem = gen.next() else {
                if let elem = mainGen.next() {
                    generator = sequentialFlatten(children(elem), children: children).generate()
                    return elem
                }
                return nil
            }
            return elem
        }
    }
}

which is 5 lines of code shorter and requires O(log n) storage instead of O(n).


Parsing numbers and ranges from a string in Javascript

On modern environments that support it (which is pretty much all of them except Safari), you can make it a bit nicer by using matchAll instead of match, and use capture groups to capture the digits immediately, rather than having to use an .includes check and split afterwards:

function parse(string) {
    const numbers = [];
    for (const [, beginStr, endStr] of string.matchAll(/(\d+)(?:-(\d+))?/g)) {
        const [begin, end] = [beginStr, endStr].map(Number);
        numbers.push(begin);
        if (endStr !== undefined) {
            for (let num = begin + 1; num <= end; num++) {
              numbers.push(num);
          }
        }
    }
    return numbers;
}

console.log(parse('11 14-16 18-20'));

(For older environments, you'll need a polyfill)

Also note that you should always use const to declare variables whenever possible - only use let when you need to warn readers of the code that you may have to reassign the variable in the future.


Payment function with too many parameters

I'd group the parameters:

doDirectPayment(CreditCard $card, User $user, array $options = array())

But this doesn't solve all problems.

To mark something required you'd use interface, but the interface can only force the existence of the methods, not the properties.

So the best option seems to be forcing the params in the constructor:

class CreditCard {
     public function __construct($required1, $required2 /*, etc*/);
}

But this way you can't instantiate the object without providing options (no fluent interface).

You may mark the params optional and provide some validation method. The problem is, how to automatically call this method. Maybe some SPL interface may help here.

From Fowler's Refactoring:

  Long Parameter Lists

  Too many parameters. Functionality is wrong, or not enough use of
  fields

  Hinders: comprehension, use, adding parameters

  Main Refactoring: Replace Parameter with Method, Preserve Whole Object, Introduce Parameter Object

Looks like most of those params will come from the user filled form, so you could simply do:

doDirectPayment(PaymentForm $form, array $otherOptions = array()) {
    // ...
    foreach ($form->getValues() as $name => $value) {
        $client->setParameterGet(strtoupper($name), urlencode($value));
    }
    // ...
}


I took an object-oriented approach here, and below you can find what I ended up with. Why do I think it's better? Well, basically, because you should need the ability to control how each one of the number parts is processed: whether it's plural, whether it should be changed according to previous (or following) number parts. The latter one does not really apply to english, but it applies to some other languages. If you did all that in one function, you would end up with having a bunch of code, which performs different kinds of tasks (1. retrieve string value 2. apply plural/singular 3. apply gender 4. Apply "forth"/"four" formatting rules). But taking the object oriented approach you now have a standalone part which does thing 1. When you need to think about 2-4, you can integrate other parsers into your code.

// This is what your initial function looks like
public static string NumberToEnglish(long n) {
    StringBuilder builder = new StringBuilder();
    var steps = new INumberPart[] {
        new SimpleNumberPart{Step = 1000000000000}, //trillion
        new SimpleNumberPart{Step = 1000000000}, //billion
        new SimpleNumberPart{Step = 1000000}, //million
        new SimpleNumberPart{Step = 1000}, //thousand
        new SimpleNumberPart{Step = 100}, //hundred
        new DecimalNumberPart(),
        new TeenNumberPart()
    };
    while (n != 0) {
        var firstAvailable = steps.First(s => s.CanBeFormatted(n));
        n = firstAvailable.Format(n, builder);
    }
    return builder.ToString();
}

public interface INumberPart {
    bool CanBeFormatted(long n);
    long Format(long n, StringBuilder s);
}

public class SimpleNumberPart : INumberPart {
    public long Step { get; set; }

    public bool CanBeFormatted(long n) {
        return n >= Step;
    }

    public long Format(long n, StringBuilder s) {
        return ProcessNum(n, Step, s);
    }

    private static long ProcessNum(long n, long step, StringBuilder builder) {
        var stepValue = n / step;
        builder.AppendFormat("{0}", NumberToEnglish(stepValue));
        builder.AppendFormat("{0} ", numerals[step]);
        return n - stepValue * step;
    }
}

public class DecimalNumberPart : INumberPart {
    public bool CanBeFormatted(long n) {
        return n >= 20;
    }

    public long Format(long n, StringBuilder s) {
        s.AppendFormat("{0} ", numerals[(n / 10) * 10]);
        return n - (n/10)*10;
    }
}

public class TeenNumberPart : INumberPart {
    public bool CanBeFormatted(long n) {
        return 0 <= n && n < 20;
    }

    public long Format(long n, StringBuilder s) {
        s.AppendFormat("{0} ", numerals[n]);
        return 0;
    }
}


Format python data structures in HTML no dependencies

The better way to do this would be to use  html_lib, but short of that, here are a few suggestions.

not_singleton is useless. Just use not singleton.

Use kw.items instead of  zip(kw.keys(), kw.values()).

Don't use SP, use '  '.


You have just added an unneeded layer of complexity to the problem.

You can just create the factory as an Object

const factory = {
    select(opts, text) { return (<select options={opts} labelText={text} />) },
    input(opts, text) { return (<input labelText={text} />) },
    default() { return new Error("Value Not Found") }
};

Then call the function with

(factory[value] || factory.default)(opts, text);


Use a constructor to initialize class variables

Your function buildMenu() looks like it is just initializing all the members of a class menu. That is normally the task of a constructor. So why not write:

class menu
{
    public:
    ...
    menu(std::string name, menu *prev, menu* up, menu* down, menu* right):
            name(name), prev(prev), right(right), down(down), up(up) {}
};

Note that since this is a simple POD class, you can also use brace initialization without having to write a constructor yourself, like so:

menu m = {"foo", nullptr, nullptr, nullptr, nullptr};

However, there is an even better way:

You only need to link menu items to their parent

Manually specifying all four pointers is cumbersome, and it is easy to confuse the four directions. It is also not necessary to store four pointers, there is quite a bit of redundancy in them. It is better to write a constructor that just takes one pointer called parent, and have the class menu have a vector of pointers to child menus, like so:

class menu {
    std::vector<menu *> children;

    public:
    const string name;

    menu(const std::string &name, menu *parent = nullptr): name(name) {
        if (parent) {
            parent->children.push_back(this);
        }
    }

    menu *getChild(int i) {
        return children[i];
    }
};

This makes constructing a menu hierarchy much easier:

menu mainMenu("Main");
menu   toolMenu("Tools", &mainMenu);
menu   notesMenu("Notes", &mainMenu);
menu     subjectsMenu("Subjects", &notesMenu);
menu       mathMenu("Math", &subjectsMenu);
menu       sciencesMenu("Sciences", &subjectsMenu);
menu       humanMenu("Humanities", &subjectsMenu);
menu   flashCardsMenu("Flash Cards", &mainMenu);

Of course, now navigating the menu becomes more tricky, but you should just need two variables:

std::stack<menu *> menuStack;
int menuItem;

The menuStack is to keep track of which (sub)menu you are in, and menuItem tells you which item in the current menu is selected. Navigating them becomes a matter of incrementing/decrementing menuItem to go up and down the currently selected menu, and pushing/popping menus to the stack to go deeper or going out of menus.

(Instead of storing a vector of children, you can still use four pointers. Your constructor still only needs to take a pointer to the parent menu, but now you need to spend more effort in the constructor to derive the four direction pointers based on the parent pointer.)

Further improvements

With the above, you still need to manually specify parent pointers.
You could instead add a member function to the class that creates a submenu:

class menu {
    ...
    private:
    menu(const std::string &name, menu *parent): name(name) {
            parent->children.push_back(this);
    }

    public:
    menu(const std::string &name): name(name) {}
    menu subMenu(const std::string &name) {
        return menu(name, this);
    }
};

This way, you can create your menu hierarchy like this:

menu mainMenu("Main");
menu   toolMenu = mainMenu.subMenu("Tools");
menu   notesMenu = mainMenu.subMenu("Notes");
menu     subjectsMenu = notesMenu.subMenu("Subjects");
menu       mathMenu = subjectsMenu.subMenu("Math");
menu       sciencesMenu = subjectsMenu.subMenu("Sciences");
menu       humanMenu = subjectsMenu.subMenu("Humanities");
menu   flashCardsMenu = mainMenu.subMenu("Flash Cards");

Now your main() function doesn't have to deal with pointers anymore.

Start thinking about ownership

Currently, you are creating a number of menu variables, and they are linked together using pointers. Regardless of how nice you make the interface of linking them together, this can still create a problem if there is the possibility for some of the menu variables to go out of scope, and you get dangling pointers. There are several solutions:

Create a destructor that removes itself from its parent's children vector. To do this, you will also need to store a menu *parent pointer.
Use std::shared_ptr<> to manage links between menu items. This requires that you remove the public constructors, and add a static member function that will do new menu(...) and returns the result as a shared_ptr<menu>.
Store submenus directly inside a regular menu. For example:

class menu {
    vector<menu> children;
    ...
    public:
    menu &subMenu(const std::string &name) {
        return children.emplace_back(name);
    }
};

Create a cursor class for navigating the menu

Think of a cursor as a more advanced iterator. In this case, it's an iterator that can move both up and down inside a menu, and left and right to different menus. It should look like:

class menuCursor {
    menu &rootMenu;
    ...

    public:
    menuCursor(menu &rootMenu): rootMenu(rootMenu) {
        ...
    }

    bool prev();
    bool next();
    bool up();
    bool down();

    menu &operator *() {
        // return a reference to currently selected item
    }

    menu *operator ->() {
        // return a pointer to the currently selected item
    }
};

The functions prev(), next() and so on handle navigating the menu. Each should also check wether the action is correct, and return an error if not (here I recommend using a bool to signal success). Like a regular iterator, you can overload operator * to return the current menu item the cursor points to. The implementation depends on how you implement your menu class: if you have four pointers, then follow those. If you use my suggested method, then keep a stack and an int around to keep track of where you are. Then in your main(), you can do:

menu mainMenu("Main");
menuCursor cursor(mainMenu);
...

while(...get input...) {
    cursor->displayMenu();

    switch(input) {
        case '0':
            cursor.prev();
            break;
        case '1':
            cursor.up();
            break;
        ...
    }
}

Move displayMenu() out of class menu

The function displayMenu() is displaying the possible options for navigating the menu. It makes more sense to have it be a member function of class menuCursor, since the latter should know more about which navigation options are valid.

Use const where appropriate

When passing pointers or references to variables to a function that should not modify those variables, you should make those parameters const. It is quite common to pass strings as const references, like so:

menu(const std::string &name, ...);

This avoids the caller having to make a copy of the string.

Class member variables that are only set at initialization time, and will never change, can also be made const. In your case, if you know you will never change the name of a menu entry after having created it, make it const:

class menu {
    ...
    const std::string name;
    ...
};

Consider a different way of navigating the menus

Instead of offering four options (prev, next, up, down), you could instead show all possible options in the current menu, plus an option to exit the current (sub)menu. Something like:

std::stack<menu *> menuStack;
menuStack.push(&mainMenu);

while (!menuStack.empty()) {
    menu *currentMenu = menuStack.top();

    // Print current menu
    std::cout << currentMenu->name << ":\n";
    int i = 0;
    for (auto &submenu: currentMenu->children) {
         std::cout << i++ << ". " << submenu.name << "\n";
    }
    std::cout << "X. Exit current menu\n";

    // Get input
    std::string input;
    std::cin >> input;

    // Navigate based on the input
    if (input == "X") {
        menuStack.pop();
        continue;
    } else {
        int item = std::stoi(input);
        // Add error checking here to ensure item is valid
        menuStack.push(&currentMenu->children[item]);
    }
}

This should show you something like:

Main:
0. Tools
1. Notes
2. Subjects
X. Exit current menu

And when you enter 2, it should show:

Subjects:
0. Math
1. Sciences
2. Humanities
X. Exit current menu


private static readonly Regex _numericRegex = new Regex(@"\s", RegexOptions.Compiled);

That should be \d, not \s.

Instead of

_specialChars.Add(
    item.Key.ToString().ToUpper()[0],
    item.Value.ToString().ToUpper()[0]);

You can write

_specialChars.Add(
    Char.ToUpperInvariant(item.Key),
    Char.ToUpperInvariant(item.Value));

I find it a bit cleaner, and there is less work involved.

If the text is potentially very long, you may be better off doing just one pass of the string. You would need to profile against the sort of data you have, but it could look something like this

var spaces = normaliar.HasFlag(CharType.Spaces);
var numerics = normaliar.HasFlag(CharType.Numerics);
var uppercase = normaliar.HasFlag(CharType.UpperCase);
var special = normaliar.HasFlag(CharType.Special);

var sb = new StringBuilder(str.Length);

for (var i = 0; i < str.Length; i++)
{
    var c = str[i];
    if (spaces && Char.IsWhiteSpace(c))
    {
        continue;
    }

    if (numerics && Char.IsNumber(c))
    {
        continue;
    }

    if (uppercase)
    {
        c = Char.ToLowerInvariant(c);
    }

    if (special)
    {
        char replacement;
        if (_specialChars.TryGetValue(c, out replacement))
        {
            c = replacement;
        }
    }

    sb.Append(c);
}

return sb.ToString();


I wouldn't search for a "rule", just store the "truncate points"

private final static int[] truncateSizes = {10,7,5,3,1,0};

public int generateListSize(int listSize) {
   for(int truncateSize  : truncateSizes) {
      if (listSize >= truncateSize) {
        return truncateSize;
      }
   }
   throw new IllegalArgumentException("Negative list size");
}


From looking at your database description . . .

No unique constraint on Users.username. You can have 1000 users named "Fred".
No unique constraint on Groups.groupname. You can have 1000 groups named "Hamburger". You probably don't want to allow that.
If you intend to build Membership like UserID integer not null unique references Users (userID), and GroupID integer not null unique references Groups (GroupID) then each user and each group can appear in that table only once. That means that if I have membership in the group Hamburger, you cannot also have membership in the group Hamburger. I think you probably want to drop the UNIQUE constraint from both those clauses, and add PRIMARY KEY (UserID, GroupID).
It's not clear what the difference is between the two tables Membership and Group.

From looking at your code . . .

db.QueryValue("SELECT user_id FROM users WHERE username = name"); You're selecting user identifiers given the users' names. But names aren't unique in your database. If I select one "Fred", and there are 1000 Freds in your database, I'm going to end up with 1000 different user identifiers. You probably don't want to do this.
db.Execute("INSERT INTO group(groupName) There's no column named "groupname" in that table.
int groupID = db.QueryValue("SELECT groupid from group where groupname = You're selecting group identifiers given the group's name. Same problem as with selecting user identifiers above.

Unless I misunderstand you, and that's always possible, you should be able to insert existing users and existing groups into Memberships with a single INSERT statement.


Comparing triangles using Java 8 streams

Since (as mentioned in my comment) the question is very tightly scoped, this review will be mostly style-focused:
Names
Some of your names are good. Some of your names are bad. I didn't see anything really ugly though, so you got that going for you ;)
Some examples of the good names include:

original, permutation, bestDeviation, trial

These names are speaking for themselves, it's almost instantly clear what they  mean.
On the other hand there's things like:

t1, t2, v, v2

These names are completely meaningless. I can't tell what they stand for, I have no idea (not in the slightest) what is in the variables with these names. It would tremendously help to understand your code's purpose, if I (or Mr. Maintainer) knew what the smallest units the code works with are.
I'd guesstimate you're operating on Vectors in a graphical representation of bodies, but I simply cannot be sure.
Anyways, from naming to:
Spacing and Linebreaks:
Thge code could use some additional linebreaks here and there, if only just to reduce the "verical complexity" of your code.
Normally I try to portion my code so you can read it one line at a time, and almost instantly understand what happens on it.
That's extremely hard when I need to scroll and there's multiple (low-level) transformations and operations. Try to write code, which doesn't take long to skim over and get the gist of.

points1.stream().map(v -> v.extend(1)).map(trial::multiply).forEach(v -> sum[0] += points2.stream().mapToDouble(v2 -> distanceCheated(v, v2)).min().orElse(0));

then becomes:
points1.stream().map(v -> v.extend(1))
        .map(trial::multiply)
        .forEach(v -> sum[0] += points2.stream()
                .mapToDouble(v2 -> distanceCheated(v, v2))
                .min().orElse(0)
        );

On the other hand there's one place where I feel you left too much space:

t2.forEach(transformed ->
{

    for (int[] permutation : permutations) {

I'd write it like this:
t2.forEach(transformed -> {
    for (int[] permutation : permutations) {

Other than this, there's no stylistic points to make here, and as mentioned I don't want to review the functionality without more information and context.


Partition a singly linked list using Java

The only suggestions I have are:

make the implementation look as "obvious,"
guarantee stability: the elements belonging in one of the sublists will preserve their relative order.

And this is what I had in mind:

public class MyList {

    private static final class MyListNode {
        int value;
        MyListNode next;

        MyListNode(int value) {
            this.value = value;
        }
    }

    private MyListNode head;
    private MyListNode tail;

    public void add(int value) {
        MyListNode newnode = new MyListNode(value);

        if (tail == null) {
            head = newnode;
        } else {
            tail.next = newnode;
        }

        tail = newnode;
    }

    public void partition(int pivot) {
        MyListNode smallListHead = null;
        MyListNode smallListTail = null;
        MyListNode largeListHead = null;
        MyListNode largeListTail = null;

        while (head != null) {
            // Remove the head node H:
            MyListNode currentNode = head;
            head = head.next;

            // Decide to which of the two lists to append the node H:
            if (currentNode.value < pivot) {
                if (smallListTail == null) {
                    smallListHead = currentNode;
                } else {
                    smallListTail.next = currentNode;
                }

                smallListTail = currentNode;
            } else {
                if (largeListTail == null) {
                    largeListHead = currentNode;
                } else {
                    largeListTail.next = currentNode;
                }

                largeListTail = currentNode;
            }
        }

        if (smallListHead == null) {
            head = largeListHead;
        } else if (largeListHead == null) {
            head = smallListHead;
        } else {
            head = smallListHead;
            smallListTail.next = largeListHead;
            tail = largeListTail;
            // Marks the end of the list, otherwise might be a cycle:
            largeListTail.next = null;
        }
    }

    public String toString() {
        StringBuilder sb = new StringBuilder().append('[');
        String separator = "";

        for (MyListNode node = head; node != null; node = node.next) {
            sb.append(separator).append(node.value);
            separator = ", ";
        }

        return sb.append(']').toString();
    }

    public static void main(final String... args) {
        MyList list = new MyList();

        list.add(3);
        list.add(5);
        list.add(8);
        list.add(5);
        list.add(10);
        list.add(2);
        list.add(1);

        System.out.println(list);
        list.partition(5);
        System.out.println(list);
        list.partition(0);
        System.out.println(list);
        list.partition(100);
        System.out.println(list);

        list = new MyList();
        list.partition(1);
        System.out.println(list);
    }
}

What comes to the complexity of my alternative, it is, at least, not worse than yours. As an additional fun, you could consider implementing quicksort for linked lists using the partition procedure you have.

Hope that helps.


Generating HTML code dynamically with jQuery

I suggest you put the template html in an invisible div in the page html.
Then reference and clone it from javascript.
Then replace "tags" with data from the json request and insert the new html in the page at the appropriate place.

You can then redesign the page without touching the javascript code.


VBA script too slow - Checks for duplicate school enrollments and keeps more recent enrollment

I had some difficulty in getting your code to run. There are a few variables that weren't defined (see comment #1 below). Additionally, you're working With Worksheets(1), but there are places where you're referencing Cells instead of .Cells. The former references whatever sheet is currently active, whereas the latter directly references Worksheets(1). This can be a subtle source of many problems, and it's something to watch out for.

Your current solution using Find , CountIf, and Max relies heavily on Excel worksheet functions and interactions with the data directly on the worksheet. With larger data sets, this can be a big source of the slowness in your code.

I'm suggesting a different approach which converts the entire student data range to a memory-based array and works from there. Working completely out of memory is much quicker and side-steps the need for Excel access individual cells and ranges.

So, a few comments on your code and implementation:

Please use Option Explicit in all your VBA code. It will help keep your sanity longer.
Declare your variables close to where you're first using them. It's easier to see exactly what you intend by the variable at that point.
Read up on using memory-based arrays in VBA.

I've split the solution into two parts: setup and execution. The setup routine determines the area of data to be used -- in this case it's the range studentData.

 Option Explicit

Sub ProcessStudentRecords()
    Dim studentWS As Worksheet
    Set studentWS = ThisWorkbook.Sheets("Sheet1")

    Dim lastRow As Long
    Dim lastCol As Long
    With studentWS
        lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    End With
    Dim studentData As Range
    Set studentData = studentWS.Range("A2").Resize(lastRow - 1, lastCol)

    Dim filteredStudents As Variant
    filteredStudents = FilterForRecentEnrollment(studentData)

    '--- now set our destination...
    Dim destinationWS As Worksheet
    Set destinationWS = ThisWorkbook.Sheets("Filtered")

    '--- ... and define the range where it's going to the correct size
    Dim destRange As Range
    Set destRange = destinationWS.Range("A2").Resize(UBound(filteredStudents, 1), UBound(filteredStudents, 2))

    '--- copy the filtered results to the range and we're done
    destRange = filteredStudents
End Sub

You can see that after the student data is filtered, the function returns a memory-based array. It's a simple couple of steps to write that data back to a worksheet range.

The function FilterForRecentEnrollment does all the heavy lifting by copying your original data into the memory-based array. Your data is large (at 260,000+ rows), but this should still be quicker than relying on Excel moving data directly in and out of the cells.

Moving the data into a memory-based array is quick and easy:

    '--- work with the student data in a memory array for speed
    Dim studentData As Variant
    studentData = studentRange

A Dictionary in VBA is an object that actively manages large amounts of data and you to very quickly access any item in the collection with a unique Key. A key is simply a string. You create the key by using information from your data either a single unique field or a combination of fields that will be unique. As best as I could tell, a "unique" identifier for your data is a combination of the Student ID and the Student Name. Using a key made from these fields, you can test if that entry already exists (and then test the dates).

So, in order to save data in the dictionary, we'll create a simple data-only class called StudentInfo. In your VBA Editor, right-click in the VBA Project "tree" where you see the Microsoft Excel Objects and Modules, then select "Insert-->Class Module". In the Properties window, name the class StudentInfo. This class looks like this:

'--- Class Module:  StudentInfo
Option Explicit

'--- ideally, these should be properties
Public SchoolName As String
Public StudentID As String
Public IDWithSchool As String
Public Student As String
Public IDWithName As String
Public Level As String
Public Grade As String
Public Status As String
Public Exited As Date

Public Property Get NumberOfFields() As Long
    NumberOfFields = 9
End Property

So what we'll do in the Filter routine is to scan a row of your student data, capture all the information into an StudentInfo object, and store it in the Dictionary. Of course, we'll only store the latest exit date of info in the dictionary. It looks like this:

Set rowInfo = New StudentInfo
rowInfo.SchoolName = studentData(i, 1)
rowInfo.StudentID = studentData(i, 2)
rowInfo.IDWithSchool = studentData(i, 3)
rowInfo.Student = studentData(i, 4)
rowInfo.IDWithName = studentData(i, 5)
rowInfo.Level = studentData(i, 6)
rowInfo.Grade = studentData(i, 7)
rowInfo.Status = studentData(i, 8)
rowInfo.Exited = studentData(i, 9)

'--- create a key value that is a unique combination of values that defines
'    a single (non-duplicate) entry
Dim dictionaryKey As String
dictionaryKey = rowInfo.StudentID & rowInfo.Student
If Not students.Exists(dictionaryKey) Then
    students.Add dictionaryKey, rowInfo
Else
    '--- this entry exists, but which has a later exit date?
    Dim existingInfo As StudentInfo
    Set existingInfo = students(dictionaryKey)
    If rowInfo.Exited > existingInfo.Exited Then
        '--- the new row's exit date is later than the existing row,
        '    so replace it
        Set students(dictionaryKey) = rowInfo
    Else
        '--- keep the existing info and ignore the current row
    End If
End If

All that code is inside a loop to catch all the student information and filter it.

Now that we have a collection (Dictionary) of filtered student data, we know exactly how many rows and columns in the data. So we can create a memory-based array and copy the data into that. Again, we're working directly in memory, so it's much faster than working with the sheet for large amounts of data.

'--- now that we have the filtered student data, we'll create an array
'    to return the data
Dim filteredData() As Variant
ReDim filteredData(1 To students.Count, 1 To rowInfo.NumberOfFields)

'--- now populate!
Dim key As Variant
i = 1
For Each key In students.Keys
    Set rowInfo = students(key)
    filteredData(i, 1) = rowInfo.SchoolName
    filteredData(i, 2) = rowInfo.StudentID
    filteredData(i, 3) = rowInfo.IDWithSchool
    filteredData(i, 4) = rowInfo.Student
    filteredData(i, 5) = rowInfo.IDWithName
    filteredData(i, 6) = rowInfo.Level
    filteredData(i, 7) = rowInfo.Grade
    filteredData(i, 8) = rowInfo.Status
    filteredData(i, 9) = rowInfo.Exited
    i = i + 1
Next key

I tested this on the limited sample data you posted and the filtering works. Some decisions you can make would be to adjust the student information you're actually saving in the class and then transferring to the destination. You'll also possibly decide that a different combination of fields is necessary for a unique key. You'll have to determine this based on your real data set.

Here's the full code for the module (don't forget to create the class, as above):

Option Explicit

Sub ProcessStudentRecords()
    Dim studentWS As Worksheet
    Set studentWS = ThisWorkbook.Sheets("Sheet1")

    Dim lastRow As Long
    Dim lastCol As Long
    With studentWS
        lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    End With
    Dim studentData As Range
    Set studentData = studentWS.Range("A2").Resize(lastRow - 1, lastCol)

    Dim filteredStudents As Variant
    filteredStudents = FilterForRecentEnrollment(studentData)

    '--- now set our destination...
    Dim destinationWS As Worksheet
    Set destinationWS = ThisWorkbook.Sheets("Filtered")

    '--- ... and define the range where it's going to the correct size
    Dim destRange As Range
    Set destRange = destinationWS.Range("A2").Resize(UBound(filteredStudents, 1), UBound(filteredStudents, 2))

    '--- copy the filtered results to the range and we're done
    destRange = filteredStudents
End Sub

Public Function FilterForRecentEnrollment(ByRef studentRange As Range) As Variant
    '--- works through each row in the data range and captures a new
    '    dictionary entry for each new student/school combination.
    '    the value in the dictionary is the information from that row

    '--- work with the student data in a memory array for speed
    Dim studentData As Variant
    studentData = studentRange

    '--- create a dictionary that will help determine if there are duplicates
    Dim students As Scripting.Dictionary
    Set students = New Scripting.Dictionary

    Dim rowInfo As StudentInfo
    Dim i As Long
    For i = LBound(studentData, 1) To UBound(studentData, 1)
        Set rowInfo = New StudentInfo
        rowInfo.SchoolName = studentData(i, 1)
        rowInfo.StudentID = studentData(i, 2)
        rowInfo.IDWithSchool = studentData(i, 3)
        rowInfo.Student = studentData(i, 4)
        rowInfo.IDWithName = studentData(i, 5)
        rowInfo.Level = studentData(i, 6)
        rowInfo.Grade = studentData(i, 7)
        rowInfo.Status = studentData(i, 8)
        rowInfo.Exited = studentData(i, 9)

        '--- create a key value that is a unique combination of values that defines
        '    a single (non-duplicate) entry
        Dim dictionaryKey As String
        dictionaryKey = rowInfo.StudentID & rowInfo.Student
        If Not students.Exists(dictionaryKey) Then
            students.Add dictionaryKey, rowInfo
        Else
            '--- this entry exists, but which has a later exit date?
            Dim existingInfo As StudentInfo
            Set existingInfo = students(dictionaryKey)
            If rowInfo.Exited > existingInfo.Exited Then
                '--- the new row's exit date is later than the existing row,
                '    so replace it
                Set students(dictionaryKey) = rowInfo
            Else
                '--- keep the existing info and ignore the current row
            End If
        End If
    Next i

    '--- now that we have the filtered student data, we'll create an array
    '    to return the data
    Dim filteredData() As Variant
    ReDim filteredData(1 To students.Count, 1 To rowInfo.NumberOfFields)

    '--- now populate!
    Dim numFields As Long
    numFields = rowInfo.NumberOfFields

    Dim key As Variant
    i = 1
    For Each key In students.Keys
        Set rowInfo = students(key)
        filteredData(i, 1) = rowInfo.SchoolName
        filteredData(i, 2) = rowInfo.StudentID
        filteredData(i, 3) = rowInfo.IDWithSchool
        filteredData(i, 4) = rowInfo.Student
        filteredData(i, 5) = rowInfo.IDWithName
        filteredData(i, 6) = rowInfo.Level
        filteredData(i, 7) = rowInfo.Grade
        filteredData(i, 8) = rowInfo.Status
        filteredData(i, 9) = rowInfo.Exited
        i = i + 1
    Next key
    FilterForRecentEnrollment = filteredData
End Function


Phone number format and data entry restriction

Here are some points regarding your code:

Decide on a style regarding the if-statements, and stick to it. Don't collapse else statements like the } else { return false; }
Avoid multiple statements on one line, like the var formatted = ...
When both branches does the same, extract the return outside of it
You can inline regexp's when they are simple, (see Detect numbers or letters with jquery/javascript)
Additionaly when using regexp against a single key you don't need to use anchors or multiple match options. Instead of ^[0-9]+$, simply use [0-9]
When replacing text you can enter the replacement text directly, instead of using a function. And the function you use is somewhat complicated
Edit: Switched to a simpler letterToNumber() using the lowercase character code (with the code of a subtracted) to index into a numbered variant of the alphabet.

In this jsfiddle I've corrected for my comments:

$(".PhoneSelection").keypress(function (e) {
    // Only allow number entry
    var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);

    if (!/[0-9]/.test(key)) {
        // If not a number, is it a letter?
        if (/[A-za-z]/.test(key)) {
            // Convert the letter typed to the number on the phone keypad
            $(this).val($(this).val() + letterToNumber(key));
        }
        return false;
    }
});

$(".PhoneNum").text(function (i, text) {
    // returns (999) 555-1234 from 9995551234
    return text.replace(/(\d{3})?(\d{3})(\d{4})$/, "($1) $2-$3")
        .replace(/\(\) /, "");
});

function letterToNumber(val) {
   charIndex = val.toLowerCase().charCodeAt(0) - 97;
   return "22233344455566677778889999"[charIndex];
}

However there are still some comments to be made:

To remove illegal characters, i.e. non-letters, and transforming letters to numbers, whilst you are typing is frowned upon in some camps. It would be better to present a normalised number next to the input field, or after it has been submitted
The transformation of the input also removes the visual feedback of whether the user has entered the correct telephone number
Your code as it stands does not connect the input field and the output field, which might be by design, but it threw me of whilst testing it for a while
You are bypassing backspacing and/or movement of cursor. As an example start entering a number using letters, i.e. xxjjjmmmm, and then you realise that you forgot the first x, so you move the cursor over there and enter it x. Now the code will add that at the end, bummer...

Edit: In original research I found Code golf: Letters in phone numbers and How to convert an alphanumeric phone number to digits), where the shortest, not very readable version of alternateLetterToNumber() is (with addition of lowercasing the character):

function alternateLetterToNumber(y) {
    y = y.toLowerCase().charCodeAt(0) - 91;
    return y > 27 ? 9 : y > 24 ? 8 : y > 20 ? 7 : ~~ (y / 3);
}


A more optimized way of finding prime factors

Format Your Code

It's extremely difficult to follow your logic with inconsistent indenting. 4-spaces after each brace please.

Stop When You Know The Answer

Here is your function to find out if a number is prime. Which you don't actually need for this problem (more on that in a bit), but I wanted to talk about it anyway:

static boolean checkPrime(long num){
    boolean toret = true;
    long sq = (long) Math.sqrt(num);
    for(long i=2; i<=sq; i++){
        if(num%i ==0)
            toret = false;
    }
    return toret;
}

So it is indeed true that you only have to go up to the square root of num. However, let's say we want to find out if 1 trillion is prime. We check 2, and 2 is indeed a divisor. And then we check 3, and 4, and ... and we still check another million numbers. That is hugely inefficient. If you found a divisor, it's already not prime, so just stop:

static boolean checkPrime(long num){
    long sq = (long) Math.sqrt(num);
    for(long i=2; i<=sq; i++){
        if(num%i ==0)
            return false; // we know it's not prime!
    }
    return true;
}

The Algorithm

We want the largest prime factor. We don't care about any other factors, so all the logic around keeping a list (and then going through it again? I don't know what that's about) is unnecessary extra work. Furthermore, you're checking if the number is prime and then going through all the rigmarole of checking all the divisors again. You definitely want to check every divisor at most one time. And even better, divide num as you go:

long largest = 1;
for (long i=2; i*i<=num; ++i) {
    while (num % i == 0) {
        largest = i;
        num /= i;
    }
}

return num > 1 ? num : largest;

So from the Euler example, we start with num == 13195 and i == 2. That doesn't divide, neither does 3 or 4. We get to 5, set largest to 5, and reduce num to 2639. That is no longer divisible by 5. Then we get to 7, largest is now 7 and num is reduced to 377. Then we get to 13, and num is reduced to 29.

At this point we're done, since 14*14 > 29. We know that the remainder must be prime (otherwise we would've found a smaller factor already), so we return 29.

Note that the square root of 13195 is 114, but we didn't even go as high as 14. Your original solution would've have gone up to 114, then gone up to 6597. I just saved you something like 6700 mod operations. And mod operations are not cheap!

Optimization Potential

Once we check for 2, we don't have to check any more even numbers. Once we check for 3, we don't have to check any more multiples of 3. So a simple optimization would be to loop over the factors 5, 7, 11, 13, 17, 19, ... by alternating adding 2 and 4. This is going to be a relatively minor improvement compared to the algorithm improvement I just suggested.


More idiomatic way to handle simple file writing in C#?

I think this is more idiomatic but I think this style does not really add much benefit over calling File.WriteAllText directly. Consider what your client code will need to do to handle a single bool result with no other information as to why it failed.

private static bool CreateImportFile(string path, string content)
{
    try
    {
        File.WriteAllText(path, content);
    }
    catch (IOException e)
    {
        Console.WriteLine("Failed to write import file due to IOException. " + e.Message);
        return false;
    }

    return true;
}


Moving character in given direction C++ SFML

FunctionPointerWrapper_t seems unnecessary; we can store a std::function<void()> in the map directly. To create this function, we can either use std::bind:

auto player = std::make_shared<Player>(*this);
inputControl.addKeyToCheck( sf::Keyboard::H, std::bind(&Player::sayHello, player) );

or a lambda function:

auto player = std::make_shared<Player>(*this);
inputControl.addKeyToCheck( sf::Keyboard::H, [=] () { player->sayHello(); } );

Note that both of these examples internally create a copy of the shared_ptr.

For cutting down on the number of named functions in the player class, we can route the functionality to a single move function, something like:

void Player::move(Vector2f const& speed) { getComponent<Velocity>() += speed * mv::constants::mob::DEFAULT_SPEED; }

We can then use std::bind, or lambda functions as above:

inputControl.addKeyToCheck( sf::Keyboard::W, std::bind(&Player::move, player, Vector2f(0.f, -1.f)) );
inputControl.addKeyToCheck( sf::Keyboard::W, [=] () { player->move(Vector2f(0.f, -1.f)); });

Where Vector2f(0.f, -1.f) can be replaced by whatever the actual desired type / value is. (We could also do the multiplication outside of the move function, if it's not common between the functions).

We still need to define 4 functions, but there's less overhead in the Player class.

To simplify it further, we'd probably want to define some sort of axis mapping, so we could do something like:

inputControl.addAxis(Axis(sf::Keyboard::W, sf::Keyboard::S, maxSpeed, minSpeed), [=] (float axisValue) { player->moveVertically(axisValue); });

(and perhaps even allow a 2d-axis to be defined mapping 4 keys to one function call) but that might be a fair amount of extra work.

General comments:

InputManager::addKeyToCheck and InputManager::eraseKey should probably not return a fixed true / false without checking if they actually succeeded.


Implementing Division of Streams (where it's a stream of polynomial coefficients)

There are a couple of cases where using where isn't gaining us anything. For instance, combineStreams can just be written as

combineStreams :: (a -> b -> c) -> Stream a -> Stream b -> Stream c
combineStreams f (Cons x xs) (Cons y ys) = Cons (f x y) (combineStreams f xs ys)

Same goes for streamMap.

If you're not using combineStreams anywhere else, we can just write

instance Num (Stream Integer) where
    (Cons x xs) + (Cons y ys) = Cons (x + y) (xs + ys)

I just want to repeat the definition given in the homework, for clarity:

  If \$A = a_0 + x A'\$ and \$B = b_0 + x B'\$, then \$A / B = Q\$,
  where \$Q\$ is defined as

  \begin{align} Q = (a_0 / b_0) + x((1 / b_0)(A' - QB')). \end{align}

Your definition of divStreams is very close to this, but we can use the following trick where q refers to itself, just as in the formula above:

divStreams :: Stream Integer -> Stream Integer -> Stream Integer
divStreams (Cons x xs) (Cons y ys) =
    let q = Cons (x `div` y) (streamMap ((1 `div` y) *) (xs - q * ys)) in q

assuming you have defined * to be multStreams.


What if I add a class Kelvin without modifying the other classes? When I convert Celsius to Kelvin then, your code says that 20 °C = 20 K, which is simply wrong.

Your whole approach is doomed to fail. What you should do instead is to define one reference temperature scale. I would take Kelvin for that. Then, for every other temperature scale, have methods fromKelvin and toKelvin. That's all. This approach is well-known from constructing compilers, which has the same problem of several similar source languages and several different target machines.

For converting between arbitrary temperature scales you can have a helper method in the Temperature class like this:

public static Temperature convert(Temperature from, TemperatureScale to) {
    double kelvin = from.toKelvin();
    return to.fromKelvin(kelvin);
}

You can see that there are two completely different classes involved:

A temperature scale, like Kelvin or Fahrenheit
A specific temperature, consisting of a temperature scale and a value, like 293 Kelvin

Regarding the exception class: There is no good reason to give it a String parameter. The name of the class is already expressive enough. Therefore you should remove that parameter and just throw new AbsoluteZeroException(). You should probably rename it to BelowAbsoluteZeroException. Or you should just take the predefined IllegalArgumentException and be fine. In many cases you don't need to invent your own exception classes.


Python program to convert a 24 hour format to 12 hour format

To help with readability, I'd just import datetime.datetime and then alias it, that way you aren't typing datetime.datetime all over the place:

from datetime import datetime as dt

def time_converter(time):
    midday_dt = dt.strptime('12:00','%H:%M')
    time_dt = dt.strptime(time, '%H:%M')

    if time_dt >= midday_dt:
        if time_dt >= dt.strptime('13:00','%H:%M'):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes}'
        time += ' p.m.'
    else:
        if time_dt < dt.strptime('10:00','%H:%M'):
            time = time[1:]
        if is_midnight(time_dt):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes:02d}'
        time += ' a.m.'
    return time

def clamp_to_twelve(time_dt, midday_dt):
    clamp_dt = time_dt - midday_dt
    minutes, seconds = divmod(clamp_dt.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return [hours, minutes]

def is_midnight(time_dt):
    return (time_dt >= dt.strptime('00:00','%H:%M') and
        time_dt <= dt.strptime('00:59','%H:%M'))

if __name__ == '__main__':
    assert time_converter('12:30') == '12:30 p.m.'
    assert time_converter('09:00') == '9:00 a.m.'
    assert time_converter('23:15') == '11:15 p.m.'

Next, if you are just unpacking the list returned from clamp_to_twelve, I would just return a tuple:

def clamp_to_twelve(time_dt, midday_dt):
    clamp_dt = time_dt - midday_dt
    minutes, seconds = divmod(clamp_dt.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return hours, minutes

This saves you from having to construct the list, as well as the additional overhead of over-allocating memory to take into account the mutable list.

As a last optimization, you could refactor your if statements to not be nested. Because you are using if if rather than if elif, all of your statements are executed within the nested blocks:

def time_converter(time):
    midday_dt = dt.strptime('12:00','%H:%M')
    time_dt = dt.strptime(time, '%H:%M')

    if time_dt >= dt.strptime('13:00', '%H:%M'):
        hours, minutes = clamp_to_twelve(time_dt, midday_dt)
        time = f'{hours}:{minutes} p.m.'

    elif time_dt > midday_dt:
        time += ' p.m.'

    elif time_dt < dt.strptime('10:00', '%H:%M'):
        time = f'{time[1:]} a.m.'

    elif is_midnight(time_dt):
        hours, minutes = clamp_to_twelve(time_dt, midday_dt)
        time = f'{hours}:{minutes} a.m.'

    else:
        time += ' a.m.'

    return time

The only issue being that the order is quite important, since time_dt > midday_dt and time_dt >= dt.strptime('13:00', '%H:%M') are not mutually exclusive. However, you do get a slight time bump because of the separation of blocks of code:

python -m timeit -s "from file import time_converter, time_converter_2; times = ['12:30', '09:00', '11:15']" '(time_converter(t) for t in times)'
1000000 loops, best of 3: 0.275 usec per loop

python -m timeit -s "from file import time_converter, time_converter_2; times = ['12:30', '09:00', '11:15']" '(time_converter_2(t) for t in times)'
1000000 loops, best of 3: 0.277 usec per loop

Emphasis on slight. Depends on what you find more readable.


Major

Overall, it seems good.

I would not check for a base case as your code can deal with empty strings. It adds complexity and clutter.

Additionally,

if(parenthesisStack[parenthesisStack.length-1] === '['){
    parenthesisStack.pop();
} else {
    parenthesisStack.push(']');
}

is repeated for each closing option. This violates the Don't Repeat Yourself principle strongly. Encapsulating it into a function would be a great idea.

The same goes to the opening values, they are always handled the same way, why not check if the input is one of them and give that the same treatment. You would only simplify code and ease future maintenance this way. Be aware that I am not really a fan of switches anywhere, except for enumerated types. But my advice is unbiased, as far as I feel it. You'd be better without a switch here, in my opinion.

Minor

You have a // remove comment. It is quite pointless but it is too small to be an issue.

Lastly, it seems that the inline comment before the loop is misaligned. It would be nice to fix that.

Algorithm-wise

Your algorithm only fails on the end. So if I start with } and follow it by () repeated a million times it will take a reasonable amount of time to terminate even though the string cannot possibly be valid.


Making currency rate requests in Java with CompletableFuture

Thread-safety

  I'm worried about thread-safety !! :x

I don't see any shared data anywhere,
and as such there are no visible thread-safety issues.

If you called CurrencyLayer.lookUpRates from multiple threads,
then CurrencyLayer.client would be shared and so it would need to be thread-safe.

The current program as it is,
fetches and processes exchange rates practically sequentially,
so there's no visible need for multi-threading,
and doesn't really benefit at all from CompletableFuture.
There is no visible reason for CurrencyLayer.lookUpRates to return CompletableFuture<List<ForexRate>>,
it could as well return a simple List<ForexRate>.

Unused method parameter

private CompletableFuture<Response> makeRequest(List<CurrencyPair> pairs) {
    final String url = "http://www.apilayer.net/api/live?access_key=[my key ^^]&format=1";
    return CompletableFuture.supplyAsync(() -> client.target(url).request().get());
}

The pairs parameter is not used in this method.

Exception handling in main

In this code,
it would be better to remove the try-catch.
The outcome will look the same in case of failure,
but the exit code will be correctly non-zero,
which is currently not the case.

static public void main(String[] args) {
    CurrencyLayer c = new CurrencyLayer();
    try {
        // ...
    } catch (Exception e) {
        e.printStackTrace();
    }
}


Nagios check to see if a certain IP appears in a trace route

Your use of $locate as a regular expression for grep is sloppy.  If $locate is 2.3.45.25, for example, a hop through 70.233.45.251 would be considered successful.

I suggest using grep -F " $locate " — with -F to interpret the argument as a fixed string rather than as a regex, and with spaces before and after the IP address.


There are a few things I see with your code that I would change:

Node API

First, I would make the members of class Node public. As it stands now, you only have one setter function to the prev member and that's it. This kind of defeats the purpose of making the entire class private to the DoublyLinkedList. Note that setting these members to be public doesn't break good encapsulation practice since the only class able to access and modify those members is the DoublyLinkedList. Moreover, why doesn't your constructor initialize prev? I would also add one or two more constructors that would allow me to construct a Node and assign the values of the next and prev references. This is how I'd revise class Node:

private class Node{
    public Node next;
    public Node prev;
    public String name;

    public Node(String s)
    {
        name = s;
        next = null;
        prev = null;
    }
    public Node(String s, Node n, Node p)
    {
        name = s;
        next = n;
        prev = p;
    }
    public String toString(){
        return this.name;
    }
}

LinkedList API

Instead of providing traverseBackward() and traverseForward(), you may want to have your class implement Iterable and/or Iterator and provide an iterator interface to the user. Also, I would provide a size() or length() member function to return the size of the list. Otherwise, why bother having or keeping track of its size? I'd also throw in an insert(), is_empty(), clear(), and remove() function to the API. Moreover, this is very unnecessary:

private Node current;
private Node first;
private Node traverse;

All you need to keep track of in the list is the head of the list (and maybe the tail if you want O(1) insertion at the end of the list instead of O(n):

private Node head, tail;


Sorting a 2-dimensional array with counting sort

Algorithm is ok, and there is nothing faster than counting sort. You just need to use single System.out.print:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
    sb.append(result[i]).append(" ");
}
System.out.print(sb.toString());

It is faster than many separate calls;


I think this is primarily opinion based, but in the AngularJS docs, there is the following:

  Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the <body> or <html> tags.

Also, note that is not possible to have nested ng-app, so, merging the group related controllers into one unique module is a good thing.


PHP Pagination for 1,2,3... vs 1,2,3,4,5,etc

Do you just mean the links at the bottom of your page? If so you have this code:

// Display page links.
$numOfPages = ceil($rowsReturned/$rowsPerPage);
for($i = 1; $i<=$numOfPages; $i++)
{
    $pageLink = "?pageNum=$i";
    print("$i&nbsp;&nbsp;");
}

Modify this to render just  the first three links, then your ellipses (...) separator and then the final page number.

EDIT to add pseudo code
This is messy but hopefully gives you the idea, create your function, make it work and then post a new question asking how to make it prettier (for example tidy up the ifs, add logic to only render a single set of ellipses, don't repeat any rendering code).

$numOfPages = ceil($rowsReturned/$rowsPerPage);
$renderedEllipses = false;
for($i = 1; $i<=$numOfPages; $i++)
{
    //If you always want to render pages 1 - 3
    if($i < 4) {
        //render link
    }

    //If you always want to render current page number
    else if($i == $pageNum) {
        //render link
        //reset ellipses
        $renderedEllipses = false;
    }

    //if you always want the last page number
    else if ($i == $numOfPages - 1) {
        //render link
    }

    //make sure you only do this once per ellipses group
    else {
      if (!$renderedEllipses){
          print("...");
          $renderedEllipses = true;
      }
    }
}

EDIT added ellipses test
The $renderedEllipses flag will stop hundreds of ellipses being rendered.


So it seems that the issue was with the mapping.  Using this answer, I created an extension to handle mapping the object after calling it.  I changed this code

var employees =
      _service
          .GetEmployeesByOffice(region, area, office)
          .OrderBy(e => e.FullName);
var model =
      Mapper.Map<IEnumerable<Employee>, IEnumerable<EmployeesViewModel>>(employees)
      .ToPagedList(page, 20);

to this

var model =
    _service
        .GetEmployeesByOffice(region, sArea, sOffice)
        .OrderBy(e => e.FullName)
        .ToPagedList(page, 20)
        .ToMappedPagedList<Employee, EmployeesViewModel>();


Detecting the presence of multiple URL segments

Throwing custom exception

I find the second version is cleaner as it clearly communicates which condition caused the exception. With the first one, you need to know it's about Single which you need to read the documentation for.

Implemention

However, as far as the implementation logic is concerned this is doing a lot of querying and the source baseFilters will be queried 3 times!

I'd be a good idea to call ToList on this to make it a one-time operation:

baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign).ToList()

Alternative

I have an extension to deal with such cases. I call it SingleOrThrow. It lets you to define two exceptions. One for when there are no elements and one for when there are too many. Otherwise it uses default ones.

    [CanBeNull]
    public static T SingleOrThrow<T>([NotNull] this IEnumerable<T> source, Func<T, bool> predicate, Func<Exception> onEmpty = null, Func<Exception> onMultiple = null)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));

        var result = default(T);
        var count = 0;

        using (var enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                if (predicate(enumerator.Current))
                {
                    if (++count > 1)
                    {
                        throw onMultiple?.Invoke() ?? DynamicException.Create
                              (
                                  $"{source.GetType().ToPrettyString()}ContainsMoreThanOneElement",
                                  $"There is more than one element that matches the specified predicate."
                              );
                    }

                    result = enumerator.Current;
                }
            }
        }

        if (count == 0)
        {
            throw onEmpty?.Invoke() ?? DynamicException.Create
                  (
                      $"{source.GetType().ToPrettyString()}Empty",
                      $"There is no element that matches the specified predicate."
                  );
        }

        return result;
    }

With it you could do just that:

baseFilters.SingleOrThrow(
    x => x.SegmentType == UrlSegmentType.Campaign,
    onMultiple: () => new InvalidDuplicateUrlSegmentException("Multiple Campaign Url Segments Found", ex));


Before looking at the code, I have a comment on the overall functionality of it. The idea is nice, but it commits a cardinal sin: It messes with files that do not belong to it.

This is A Very Bad Idea™.

Say you want to write the file "log.txt", but it already exists. Your code will rename the existing file, but that file may be in use. Some other process might expect it to be there, and fail when it gets renamed. Or your process will fail if the existing file is owned by another user or is locked. Or the other process will just start overwriting your file, since, hey, that's the one with the correct name. Or you get weird race conditions where you rename a file, and immediately after that, another process - finding the file gone - creates a new one, after which you overwrite the other process' new file; exactly what you're trying not to do. (see user50399's answer for more)

In other words, I wouldn't use this, regardless of the code itself.

But speaking of code, let's look at that.

You've certainly been diligent in dividing everything into methods - kudos. But, as ckuhn203 notes, a method with and in it indicates that the method is in fact doing several things.

I have to wonder why you're using a two-stage method of resolving file name conflicts: One is to append "_old", and the other is to also append a number. Just appending "_old" may not be enough, whereas numbers can simply increment forever (more or less). So you have one way of renaming that may or may not work, and one which will always work. So why use both? It just complicates the code.

Besides, maybe you don't want "_old" in the filename. Maybe you want "-backup" or just nothing. Right now the string is hard coded in a method body, so it's not exactly configurable.

I don't see any handling of file extensions, or anything to indicate that it's been considered. Though not required, it could be nice to rename "file.txt" to "file_old4.txt" instead of "file.txt_old4". Especially since you're using an underscore, meaning that the renamed file's extension is suddenly ".txt_old4", which isn't a real extension.
However, dealing with file extensions is a huge hassle, so if you look at something like the logrotate *nix utility, it just appends a dot and a number, instead of trying to parse file extensions, so you get files like "log.txt.3". Note that it's not using an underscore; it's simply adding an entirely new extension that's all-numeric. While not perfect, it's less likely to confuse anyone.

There's also the question of why this is a class. All its methods are class methods, and it has no state. Yet making it a class implies you can instantiate it - but that doesn't really do anything. You basically just get an instance of Object with no discernible functionality. I'd probably prefer to write it as a module instead (here are a number of ways to do that).

On a micro-level, I noticed this:

until File.exists?(append_old_to(filename) + number.to_s) == false

Saying "until something's not true" is the same as just saying "while something's true". It's cool that Ruby has the until keyword, but in this case you want a good old-fashioned while loop.
You could also avoid calling append_old_to again and again, since its return value isn't going to change. And personally, I'd use string interpolation here

number = 0
base_filename = append_old_to(filename)
while File.exists?("#{base_filename}#{number}")
  ...

Incidentally, this single method may be the most useful, if you "flip it" to produce a new filename you can use instead. I.e. don't try to rename existing files: Make sure that you have a non-conflicting filename before you write anything. Again, there's a risk of race conditions, if you get the file name before writing, but it's less risky than renaming existing files.

You might simply monkey patch the IO class with an open_uniq (or some such) method, which you pass the usual name, mode and block, but which - instead of returning the number of bytes written - returns whatever filename it actually ended up writing. So you give it "log.txt" and some data to write, and it might return "log.4.txt" because there happened to be a few of log*.txt files already.


Java util to compare if time beyond cutoff

You can shorten this:

if(avlDate.before(currentDateWithCutoffTime)){
    return true;
} else{
    return false;
}

to this:

return avlDate.before(currentDateWithCutoffTime);

It'll automatically return whichever conditional is returned by the method.


I'd make heavier use of xpath:

$xml = simplexml_load_string($x); // assume XML in $x
$class = $xml->xpath("//type[@extension = 'doc']/../../@class")[0];
$icon = $xml->xpath("//type[@extension = 'doc']/../@icon")[0];
$description = $xml->xpath("//type[@extension = 'doc']/@description")[0];

echo "$class | $icon | $description";

My code requires PHP >= 5.4, for older versions, do:

$class = $xml->xpath("//type[@extension = 'doc']/../../@class");
$class = $class[0];

or...

list($class,) = $xml->xpath("//type[@extension = 'doc']/../../@class");


PHP Iterate over Child's Child Efficiently

You can do it recursively. Create a function (let's say, iterateChildren(array)) that iterates over the given array and when the children key is found you call iterateChildren(item['children']).

This way you can have as many levels as you'd like, since the function calls itself at each level.

Be cautious, though, because with too many levels you may run out of memory.