Number of prime numbers in a given range

What is the purpose of shortening the term "Prime(s)" to Prim in your method names? IMO numberOfPrimes and checkIfPrime are more readable. The same is true for primAmount etc.
if(checkIfPrim(i) == true) can simply be if (checkIfPrim(i))
Your spacing is inconsistent. Generally, it is recommended to leave a space between a control structure (for, if, while etc.) and its following open paren, which you adhere to exactly once in checkIfPrim, but not elsewhere. The same applies to operators: Write up <= 0 instead of up<=0.
Your checkIfPrim method is grossly overcomplicated. First of all, you check every number up to number for divisibility, while it should be obvious that there can be no divisor greater than number / 2. Still, if you think about the problem, you will soon arrive at another conclusion, which is that you only need to check numbers up to sqrt(number), because you can write a * b = number (with a and b being positive integers), which is to say that a and b are divisors of number. Now, letting sqrt(number) = c * c, and by thinking about how multiplication behaves, we can conclude that either a or b must always be lesser or equal to  while the other must be greater or equal to c, because when either a or b is smaller than c the total product would shrink unless the other one grows to counteract this fact.
The next problem is your use of a boolean array, which is completely redundant. You do not need to store the result of the division test for each number separately, but you only have to keep track of whether you have found a divisor for number (=> number is not prime) or not (=> number is prime). All in all, I would rewrite the method to something like this:

public static boolean checkIfPrime(int number) {
    if (number < 2) {
        return false;
    }

    if (number == 2) {
        return true;
    }

    int root = (int) Math.sqrt(number);
    for (int i = 2; i <= root; i++) {
        if (number % i == 0) {
            return false;
        }
    }

    return true;
}

Although this code should be reasonably efficient for relatively small numbers, there are faster algorithms to solve this problem. However, most of these are not as easy to implement, and if you are not planning on doing this for very large integers, then you should be fine with the changes I suggested. If you are still interested in improving effiency, I point you to the Wikipedia article about the prime-counting function for a start.


Your current implementation is somewhat flawed as relying on ToString to get the type name is dangerous. ToString is meant largely to yield or short meaningful description of the object for debugging, logging etc.
typeof(T) already yields a Type - it is totally unnecessary to convert it to a string just to then turn it back into a type again.
If your repositories all have a parameterless default constructor you can avoid calling CreateInstance entirely.

Your current implementation can be shortened to:

public T GetRepository<T>()
{
    object repoInstance = Activator.CreateInstance(typeof(T));
    return (T)(object)repoInstance;
}

or possibly even to:

public T GetRepository<T>() where T : new()
{
    return new T();
}

In addition to that your GenericRepository seems more like a repository factory than a repository in itself hence you should possibly rename it to RepositoryFactory and the method to CreateRepository.


Follow up to Top Active Answerers on Stack Exchange site

This is a substantial improvement over the previous version. The code is consistent, I do not see any bugs, it's generally good.

There are two further opportunities for improvement that I can see.

I can tell you do this to get an accurate average, and round it to 2 decimal places. The concept is good:

CAST(AVG(CAST(Score AS float)) AS NUMERIC(6,2))

but, there's a trick with float that simplifies things a bit. Consider:

CAST(AVG(Score * 1.0) AS NUMERIC(6,2))

I know it is small, but the implicit cast makes things easier to read.
You duplicate calculations once for the base value, then again for the rank, and again in the having clause. These complex aggregates can be simplified by using a CTE. Calculate the raw data in one CTE and do the calculations in that, then, use that raw data as part of the outer select. Describing it is harder than just doing it. Consider the following query which produces the same results as yours:

WITH RawData AS (

    SELECT
        Users.Id AS UserId,
        Users.DisplayName AS UserName,
        COUNT(Posts.Id) AS AnswerCount,
        CAST(AVG(1.0 * Score) AS NUMERIC(6,2)) AS AvgScore
    FROM
        Posts
      INNER JOIN
        Users ON Users.Id = OwnerUserId
    WHERE
        PostTypeId = 2
        AND CommunityOwnedDate IS NULL
        AND ClosedDate IS NULL
        AND Users.LastAccessDate > DATEADD(DAY, -##DaysSinceActivity:int?31##, GETDATE())
    GROUP BY
        Users.Id, Users.DisplayName

)
SELECT
    TOP ##NumberOfUsers:int?1000##
    UserId AS [User Link],
    UserName AS [UserName],
    AnswerCount AS [Total Answers],
    RANK() OVER (ORDER BY AnswerCount DESC) AS [Total Answer Rank],
    AvgScore AS [Average Answer Score],
    RANK() OVER (ORDER BY AvgScore DESC) AS [Avg Score Ranking]
FROM
    RawData
WHERE
    AnswerCount > 10
ORDER BY
    AvgScore DESC

Note how the complex aggregates happen in just one place.


Implementing my own Integer.toBinaryString(int n) method

The exercise calls for bit shifting. Only bit shifting, nothing else, really. Your main tools are:

checking if the last bit is 0 or 1 with: num & 1
then shift by one bit to the right: num >> 1

A naive implementation could go like this:
    String result = "";
    while (num > 0) {
        result = (num & 1) + result;
        num >>= 1;
    }
    return result;

But that won't work for negative numbers. A simple tweak can fix that:
    String result = "";
    while (num != 0) {
        result = (num & 1) + result;
        num >>>= 1;
    }
    return result;

Instead of the signed bit shift operator >>, we need to use the unsigned bit shift operator >>>, to shift the negative bit just like all the others. And we changed the condition to != 0 instead of > 0.
But this won't work for 0. But only for 0. So you can add a simple condition to handle that.
Lastly, string concatenation is inefficient. We can do better using a StringBuilder.
But a StringBuilder only has an append method, doesn't have prepend. It has an insert method, but that won't be efficient.
A simple solution is to append the bits and reverse at the end.
String toBinaryString(int num) {
    if (num == 0) {
        return "0";
    }

    StringBuilder builder = new StringBuilder(32);
    while (num != 0) {
        builder.append(num & 1);
        num >>>= 1;
    }
    return builder.reverse().toString();
}

In any case, the StringBuilder is not a critical piece here.
You could use a char[] with 32 elements to store the digits,
and transform that to a string to return.


Extracting meta data from nupkg file with F# looks like C# Linq

Without being able to actually test (I can only guess what getDependencies, nugetPackagesFile, !! and filename are), something along the following should produce your desired set of dependencies:

getDependencies nugetPackagesFile
|> Seq.collect (fun (name, ver) ->
       !! (sprintf "./src/packages/*/%s.%s.nupkg" name ver)
       |> Seq.collect (fun pkg -> NuGet.ZipPackage(pkg).GetFiles())
       |> Seq.map (fun f -> filename f.Path))
|> Set.ofSeq

or, depending on your taste (kind of DFS vs. BFS)

getDependencies nugetPackagesFile
|> Seq.collect (fun (name, ver) -> !! (sprintf "./src/packages/*/%s.%s.nupkg" name ver))
|> Seq.collect (fun pkg -> NuGet.ZipPackage(pkg).GetFiles())
|> Seq.map (fun f -> filename f.Path)
|> Set.ofSeq

where Seq.collect and map correspond to IEnumerable.SelectMany respectively Select in C#


Only a couple of beautifying changes i would make. I hate giant app.modules so i like to reorginize all core imports into core.module and import that into app.module, like described here.

under "core feature module"

I do now know what the recent angular-cli generates but i like to think ahead about which modules what my application will include. If it will be many components and you can comfortably group some of them, think about creating more modules(lazy-loading)

Also, consider  where you will put all your constructs (datepicker, timepicker, alert) components and export them. Read more about the shared module on the link above, you have a good setup  for that already. BUT shared module should then not be included into the app.module, only in the functionality modules(if you decide to go that way)


This code is not safe, and exhibits undefined behavior. I don't think you've actually tested it.

           char safe_filename[256];
           if (strlen(filename) > 256) {
               memcpy(safe_filename, filename, 256);
           }
           sprintf(error_msg, "Unable to read file : %s", safe_filename);

Let's see what happens if filename is short. The test is false, so execution proceeds to the sprintf. It is constructing a string and is supposed to interpolate safe_filename... but that hasn't been initialized yet. Whatever garbage is in safe_filename will be copied into error_msg until it happens to hit a '\0', unless it gets a segfault first. It might even overflow the bounds of error_msg.

And what happens if filename is long? The test is true, so 256 characters of filename get copied into safe_filename. No terminating '\0' because memcpy() doesn't do that (and there wouldn't be room if it did). Execution proceeds to the sprintf. Again, it starts interpolating from safe_filename into the string, but the copying continues without stopping until it happens to hit a '\0' or segfaults. Same risk to error_msg.

How did this problem arise? You wrote code without testing it. Let me take a minute to pontificate about testing. You need to test your code. You need to test all your code. You need to be able to do the tests in an automated manner. That means your automatic testing harness needs to be able to cause each branch to be either taken or not taken.


Is there any way to make this shorter or more efficient?

Yes, we can do some things.

for(int i = 0; i < Math.pow(2,n); i++)

You calculate the pow for every iteration. The pow call takes some time (compared to basic things like multiplication or addition), you should do it only once.

B = "";
B = '1'+B;
B = '0'+B;

You will create a lot of string copies for every string concatenation. This costs a lot of perfomance. In general, you should use a StringBuilder.
In this special case, we could even use a char array.

for(int i = 0; i < Math.pow(2,n); i++)
if (temp%2 == 1)
temp = temp/2;

You could use bit manipulations. But depending on the jvm or hotspot compiler, this will be done anyway.

void printB(int n)
        B = "";
        int temp = i;

Overall point: avoid abbreviations.

All together, it could be like this:

void printAllBinaryUpToLength(final int length) {
    if (length >= 63)
        throw new IllegalArgumentException("Current implementation supports only a length < 63. Given: " + length);
    final long max = 1 << length;
    for (long i = 0; i < max; i++) {
        long currentNumber = i;
        final char[] buffer = new char[length];
        int bufferPosition = buffer.length;
        while (bufferPosition > 0) {
            buffer[--bufferPosition] = (char) (48 + (currentNumber & 1));
            currentNumber >>>= 1;
        }
        System.out.println(buffer);
    }
}

Calculates (without printing, printing takes the great majority of every loop) results up to 25 (2^25 = ~33*10^6) in less than a second. Should be enough.


Find the most frequent character in a string

Instead of reversing the input string you could foldRight over it, and instead of updating mutable variables let the fold accumulator carry the current data forward. As an Array is mutable by default there's no point in having the fold accumulator make copies in order to carry it forward.

def findMaxFunctional(word: String): Char = {
  val arr = new Array[Int](128)
  word.foldRight((' ', 0)){
    case (c, (mxChr, mxCnt)) =>
      arr(c) += 1
      if (arr(c) >= mxCnt) (c, arr(c))
      else (mxChr, mxCnt)
  }._1
}


Finding nth Prime using Python and Sieve of Eratosthenes

Upper bound for p_n

There is a known upper bound for the n-th prime.

It means that you don't need any loop inside find_n_prime, and you don't need to check if len(primes) >= n either.

import pytest
from math import log, ceil

def find_primes(limit):
    nums = [True] * (limit + 1)
    nums[0] = nums[1] = False

    for (i, is_prime) in enumerate(nums):
        if is_prime:
            yield i
            for n in range(i * i, limit + 1, i):
                nums[n] = False

def upper_bound_for_p_n(n):
    if n < 6:
        return 100
    return ceil(n * (log(n) + log(log(n))))

def find_n_prime(n):
    primes = list(find_primes(upper_bound_for_p_n(n)))
    return primes[n - 1]

It calculates the 100000th prime in less than 230ms on my computer, compared to 1.5s for your code.

itertools.islice

Another possible optimization would be to use itertools.isclice to get the n-th prime out of the find_primes generator, without converting it to a list.

from itertools import islice

def find_n_prime(n):
    primes = find_primes(upper_bound_for_p_n(n))
    return next(islice(primes, n - 1, n))


var elements = [
      reporter_wrapper                = document.createElement('div'),
      reporter_close                  = document.createElement('button'),
      reporter_title                  = document.createElement('h1'),
      reporter_title_label            = document.createElement('label'),
      reporter_bug_title              = document.createElement('input'),
      reporter_priority_label         = document.createElement('label'),
      reporter_bug_priority           = document.createElement('select'),
      reporter_details_label          = document.createElement('label'),
      reporter_bug_details            = document.createElement('textarea'),
      reporter_user_label             = document.createElement('label'),
      reporter_user                   = document.createElement('input'),
      reporter_submit                 = document.createElement('button')];

Hmm. An array that has variables that each are assigned a value. Hmm. Oh wait; that sounds like an object!

Instead of reinventing the wheel and creating this array thing that's values are assigned to variables too, you should just create an object.

Here is what that would look like:

var reporter = {
    wrapper: document.createElement("div"),
    ...
};

I removed the part reporter_ from the key names because, now that they are in an object, you need not to worry about conflicting with other variable names.

There is practically no difference.

Let's take the last tip to the next level.

This time, let's create a map of names of the keys of the object, and then the type of HTML element to instantiate.

Here is what I mean:

var namesAndElements = {
    "wrapper": "div",
    "close": "button",
    ...
}

Excuse the poor variable name.

See the pattern? The keys are simply the part after reporter_ in the original array, and the values are the parameter passed into document.createElement.

Now, to create the object/map of elements, we simply need to create a loop that stores these keys and values into a new object/map.

Here is what I came up with:

var reporter = {};
for(var name in namesAndElements) {
    elements[name] = document.createElement(namesAndElements[name]);
}

Now, in order to access something from this object, you could write:

elements.details_label

As an example.

And you will get the element assigned to it.

reporter_wrapper.className          = 'buggr__reporter';
reporter_close.className            = 'buggr__reporter-close';
reporter_title.className            = 'buggr__reporter-title';
reporter_bug_title.className        = 'buggr__reporter-input';
reporter_bug_priority.className     = 'buggr__reporter-select';
reporter_bug_details.className      = 'buggr__reporter-textarea';
reporter_user.className             = 'buggr__reporter-input';
reporter_submit.className           = 'buggr__reporter-submit';

See something similar in the value that these classes are being assigned? If not, they are start with this:

"buggr__reporter"

Therefore, we can simplify this by creating a map (like above) of the elements whose classes need to be changed, and the value to change it to.

Here is what I came up with:

var newClasses = {
    "wrapper": "",
    "close", "-close",
    "title", "-title",
    "bug_title", "input",
    ...
}

Excuse the poor variable name.

Notice anything familiar about this object? The keys are keys of the first map we created, and the values are the extra part of the string that is not in the pattern I mentioned.

Now all we have to do is create a loop for setting these class names:

for(var element in newClasses) {
    reporter[element] = ("buggr__reporter" + newClasses[element]);
}


You will likely be rotating many vectors by the same angle.  Therefore, it would be wasteful to compute \$\cos \theta\$ and \$\sin \theta\$ repeatedly.

The typical way to think of linear transformations is as matrix multiplication:

$$
\left[ \begin{array}{c} x' \\ y' \end{array} \right] =
\left[ \begin{array}{rr}
  \cos \theta  & -\sin \theta \\
  \sin \theta & \cos \theta
\end{array}\ \right]
\left[ \begin{array}{c} x \\ y \end{array} \right]
$$

So, define a make_rotation_transformation(angle, origin) function that returns a closure that holds the transformation matrix and origin vector.

from math import cos, sin

def make_rotation_transformation(angle, origin=(0, 0)):
    cos_theta, sin_theta = cos(angle), sin(angle)
    x0, y0 = origin
    def xform(point):
        x, y = point[0] - x0, point[1] - y0
        return (x * cos_theta - y * sin_theta + x0,
                x * sin_theta + y * cos_theta + y0)
    return xform

def rotate(self, angle, anchor=(0, 0)):
    xform = make_rotation_transformation(angle, anchor)
    self._offsets = [xform(v) for v in self._offsets]


Priority Queue (Binary Search Tree) Implementation

Handling booleans

Computation of isEmpty is anti-idiomatic. Consider

    isEmpty = (root == NULL);

Now it is easy to see that isEmpty is not needed at all. The whole method can be shortened to

bool PQ::IsEmpty()
{
    return root == NULL;
}

Pop return on failure

Returning -1 on failure means that the tree cannot have nodes with  -1 as a value (a caller cannot tell such node from a failure). Consider throwing an exception instead.
Recursive Push

Push doesn't need to be recursive:

void PQ::Push(int value, Node * node)
{
    while (1) {
        if (value < node->value) {
            if (node->left) {
                node = node->left;
            } else {
                node->left = new Node(value);
                return;
            }
        } else {
            if (node->right) {
                node = node->right;
            } else {
                node->right = new Node(value);
                return;
            }
        }
    }
}

Recursive Pop

Pop needs not to be recursive either:

int PQ::Pop(Node * node, Node * parent)
{
    while (node->right) {
        parent = node;
        node = node->right;
    }
    do_actual_deletion
}

Edit: as requested, no multiple returns, no infinite loops. I am not sure it is cleaner than the original.

    void PQ::Push(int value, Node * node)
    {
        Node ** insertionPoint = 0;
        while (insertionPoint == 0) {
            if (value < node->value) {
                if (node->left) {
                    node = node->left;
                } else {
                    insertionPoint = &node->left;
                }
            } else {
                if (node->right) {
                    node = node->right;
                } else {
                    insertionPoint = &node->right;
                }
            }
        }
        *insertionPoint = new Node(value);
    }


Here are some changes that you could make to your code. I'll explain various parts of the script below.

import sys

mode = input("E to encrypt, D to decrypt: ").upper()

if mode == 'E':
    string = input("Input your message to encrypt : ").upper()
    def op(x, y): return x + y
elif mode == 'D':
    string = input("Input your message to decrypt : ").upper()
    def op(x, y): return x - y
else:
    print "Please enter either D or E for mode option. Terminating script!"
    sys.exit()

key = int(input("Create your encryption key (remember this): "))

ord_space = ord(' ')
ord_A = ord('A')
ord_Z = ord('Z')
alpha_num = 26

def inner_func(value):
    newvalue = op(value, key) if value != ord_space else value
    return newvalue

def outer_func(value):
    newvalue = (value - alpha_num) if value > ord_Z else ( value + alpha_num if value < ord_A else value)
    return newvalue

text = [chr(outer_func(inner_func(ord(char)))) for char in string]

Checking User Input

The first thing I do is import the Python module sys. At the
beginning of your program you ask the user to enter E or D
depending on whether they want to encrypt or decrypt their string. In
your programs current form it isn't robust to the case where the user
inputs some symbol(s) that isn't equivalent to E or D. So after
taking the users mode input I check that it is either E or D
and if it isn't I exit the program by calling sys.exit().
The next way I help the user (and in turn help our program) is to automatically transform their input to upper case charachters by calling .upper() in every place where you take user input.
Question: Are there any other user inputs we should check? (Hint: Key)

Taking Advantage of Object Scope

Notice that I'm defining string and the function op within the first if-elif statement. I'm then reusing these objects inside of functions later on without having to pass them in as parameters. Within each function Python will search 1st for a local object (in this case op) and then if there is no object with the given name inside of the function it will search the global namespace of the program. In this case because op is defined outside of a function, it belongs to the global namespace. The above also applies to ord_space, ord_A, etc, which again are also used inside the functions inner_func and outer_func. A more detailed description of Python scoping rules can be found here.

Conditional Expressions

Within inner_func and outer_func I'm using what is known in Python as a conditional expression. In other programming languages such as C++ they are also called ternary operators. As explanation consider: x = a if foo else b. The variable x will be assigned the value of a if the statement foo evaluates to true. If foo is false then x will be assigned the value of b. Conditional expressions often lead to more concise code which in the end will lead to less bugs and easier maintenance. Admittedly in outer_func I went a bit overboard and chained two of them together, e.g. x = a if foo else ( b if bar else c ). I wouldn't recommend doing this generally but I thought I'd demonstrate the possibility just for fun.

Tying it all together: List Comprehensions

Finally, on the last line of the code I've demonstrated one of the cornerstones of Python, list comprehensions. All a list comprehension does is build a list by looping over the elements of another container and applying some operator to them. For example if we had a list x = [1, 2, 3] and we wanted to add 1 to each element in x while at the same time creating a new list y we could do it like so:

y = [i + 1 for i in x]

This code has the same effect as the following:

    y = [0] * len(x)
    counter = 0
    for i in x:
        y[counter] = i + 1
        counter = counter + 1


A piece of Python code to compute a frequency table of a list of values

You may want to try 2.5.6, a security fix to 2.5.4.
Alternately either 2.7 or, preferably, 3 would be a better upgrade.
They may be unfeasible, but you should upgrade, you're 7 years behind!

First things first, don't do hacky stuff that give incorrect bounds.

  lowest = min(list) - 10**(-max(count)-1)

The correct bounds are not the ones you are using!
They are:

[0.1, 0.4)
[0.4, 0.7)
[0.7, 1.0]

All bar the last 1 inclusive is easy, just remove that hack you are using.
If we put the bound creator in a function then we can create the bounds and re-use them in a future function.
To handle the 1 inclusive you can change it to a 2, (1 + 1).

I would also use comprehensions, they are quite simple, but extremely useful.
For example creating count would be:

count = [num_after_point(list[i]) for i in range(len(list))]

This can be improved by not indexing list and not using len and range.

count = [num_after_point(i) for i in list]

As most of your function is creating the bounds I'll go through it first.
You want to keep most of your code the same. But:

Remove num_after_point, count and all that mess.
Remove all the bucketCountList stuff.
Change the while loop to a for loop for _ in range(numBuckets - 1):.
Yes you want the -1.
After changing low and high, yield them. (yield low, high).
After the for loop yield high, highest + 1, this is the only edge case we will be using.

This should get you:

def bounds(list_, numBuckets):
    lowest = min(list_)
    highest = max(list_)
    bucket_size = (highest - lowest) / numBuckets
    upper_bound = lowest
    for _ in range(numBuckets - 1):
        lower_bound, upper_bound = upper_bound, upper_bound + bucket_size
        yield lower_bound, upper_bound
    yield upper_bound, highest + 1

Now to use it is very easy:

You want to go through all the lower and upper bounds of the bounds function.
simply for l, u in bounds(...):.
Generate the sum in the bounds.
Display everything.

To get:

def histogram(list_, num_buckets):
    for lower_bound, upper_bound in bounds(list_, num_buckets):
        data = sum(lower_bound <= i < upper_bound for i in list_)
        print "From", lower_bound, "to", upper_bound, ":", data

The only down-side is the one hack we used to include the upper bound.
This has a small impact on the display, but ultimately it's a much nicer solution.

The bounds are easier to read.
You can use every number in the range. You couldn't use 0.0999999999 for example.

Finally, not knowing the numbers in the range is a bit... odd.
You should probably allow that, which is using a comprehensions if.

def histogram(list_, num_buckets):
    for lower_bound, upper_bound in bounds(list_, num_buckets):
        data = [i for i in list_ if lower_bound <= i < upper_bound]
        print "From", lower_bound, "to", upper_bound, ":", len(data)
        print data


My personal preference would be the second option:

$lastSpacePosition = strrpos($text, ' ');
$textWithoutLastWord = substr($text, 0, $lastSpacePosition);

It's more obvious what's happening. The fact that str_word_count returns an array because you feed it a 1, is not obvious.
The code is shorter, in this case I feel that makes it easier to read, rather than obfuscated.
It is by far the fastest. In my text of 110 words copied from a wikipedia article, with 1e6 iterations

str_word_count version took 17.952 milliseconds.
strrpos took 0.597 milliseconds.
preg_replace (By Oscar M) took 71.189 milliseconds.

In my test text the are letters outside of a-z. The str_word_count solution breaks these letters as if spaces. Whether this is, or is not, the intended behaviour of the function, I would stay away from such behaviour.


Shifting the origin of a large list of coordinates

The only thing I can see that will speed stuff up is this part:

string line;
while (getline(infile, line))
{
    std::istringstream iss(line);
    int vertex_source, vertex_destination;
    if (!(iss >> vertex_source >> vertex_destination)) {

There is a lot of copying from line to iss. This provides some good error checking and correction ability. But does slow the code down.

Replacing the above with

while (iss >> vertex_source >> vertex_destination)
{

results in a 10% speed improvement in my code (though I took out the vectors; I did not need them).


From a once over

Indentation is terrible, consider using a tool like jsbeautifier.org, it works for ActionScript as well
Keep working with Event.ENTER_FRAME <- It is the better approach in my mind
Always be on the look out for copy pasted code, this:

if (sprint) {
  timerStart = false;
  condition1 = false;
  condition2 = false;
  sprint = false;
  timer = 7;
}

if (timer <= 0) {
  timerStart = false;
  condition1 = false;
  condition2 = false;
  sprint = false;
  timer = 7;
}

could be

    if (sprint || timer <= 0) {
      timerStart = false;
      condition1 = false;
      condition2 = false;
      sprint = false;
      timer = 7;
    }

Do not track keyDown, you do not use it, and it's value is always the opposite of keyUp
condition1 and condition2 are very unfortunate names, you should try to be more descriptive
This code could use some well named constants and indenting:

if (sprint) {
player.x += 7;
} else player.x += 2;

I would rather see

var FAST_SPEED = 7,
    NORMAL_SPEED = 2;
if (isSprinting) {
    player.x += FAST_SPEED;
} else {
    player.x += NORMAL_SPEED;
}

or if I wanted to be fancy

player.x += isSprinting ? FAST_SPEED : NORMAL_SPEED;


Adding values from DictReader to empty dictionary

Some suggestions:

Pass the code through at least one linter such as pycodestyle or flake8 to get more idiomatic Python.
Don't use global. Returning two values, while ugly, is preferable to having global state.
You can add \n to the end of a string to print a newline, avoiding empty print()s.
Use argparse to rather than input() to make the script … well, scriptable.
Each route should probably be an object rather than a disparate set of just stuff, even though these objects will have no methods for now.
Using a main method as the entry point for the functionality would make the script usable by other scripts.


Search for everything at a tile in Minesweeper

A few things:

I'd suggest that get-by-key can more clearly be defined as an inline lambda using get-in instead of implicitly calling the keys. You can also inline the construction of the flag?-bomb?-hint? vector to cut down on definitions.

I wouldn't worry about the filter immediately going into a set. Sets do one thing and filter does another; the laziness doesn't need to come into play.

Also, this:

(if (g :flags) :flag nil)

is more idiomatic as

(when (g :flags) :flag)

and

#(not (nil? %))

is

some?

Here is a shorter version of your function, taking those into account and not declaring temporary bindings for flag?, bomb?, hint?. I think in this fairly simple scope, that's fine.

(defn all-at
  "Returns a set of everything at the position.
  Possible contents are :bomb, :flag, or a number representing a hint."
  [field x y]
  (let [get-at #(get-in field [% [x y]])]
    (->> [(when (get-at :flags) :flag)
          (when (get-at :bombs) :bomb)
          (get-at :hints)]
         (filter some?)
         (into #{}))))


I would add "data-api" as an attribute to the buttons

<input type='button' data-api='Home/HtmlControlTest' />

Then you could do this with the js

$('input[data-api]').click(function () {

            $.ajax({
                url: $(this).attr('data-api'),
                type: 'POST',
                contentType: 'application/html',
                //data: JSON.stringify(model),
                success: function (content) {
                    $('#divPartialViewContainer').append(content);
                },
                error: function (e) { }
            });
        });


Makefile that places object files into an alternate directory (bin/)

You are not using the make system properly.  As a result, it will always relink the executable, even when everything is already up to date.  On the other hand, it might fail to recompile some source files into object files.

When you run make…

It will try to create the build target.  No file named build exists, so…

It will try to create the prerequisites of build, namely create_directories and create_executable, neither of which are names of existing files.

In an attempt to create a file called create_directories, it runs mkdir -p $(OBJ).
For create_executable, it needs to rebuild create_objects.

For create_objects, it just verifies that all of the source files are present.

For any of the $(SOURCE_FILES) that is missing, it "creates" it using the %.cpp: rule, which actually tries to compile the missing .cpp into a .o.
Once all of the $(SOURCE_FILES) are present, it echoes "Created objects.".  That's a false claim due to the error above.

Having thus falsely satisfied the prerequisites for create_executable, it proceeds to attempt to link the executable, even if any of the $(OBJECT_FILES) is missing.

The main remedy is to specify real targets and real dependencies, rather than phony labels like create_executable.

Here is how I would write it.  Other than the major problems cited above, I have also noted many minor issues in the comments.

#########################################################
# Replacing everything that you told me not to touch... #
#########################################################
EXECUTABLE_FILES = $(EXECUTABLE_NAME:%=$(BIN)/%)
OBJECT_FILES     = $(SOURCE_FILES:%.cpp=$(OBJ)/%.o)
# ^^^ A more succinct expression for $(OBJECT_FILES), using
#     http://www.gnu.org/software/make/manual/make.html#Substitution-Refs

build: $(EXECUTABLE_FILES)

clean:
    rm -r -f $(BIN)
    @# ^^^ I don't recommend suppressing the echoing of the command using @

# http://www.gnu.org/software/make/manual/make.html#Phony-Targets
.PHONY: build clean

$(EXECUTABLE_FILES): $(OBJECT_FILES)
    @$(CC) $(LDFLAGS) -o $@ $^
    @# ^^^ http://www.gnu.org/software/make/manual/make.html#Automatic-Variables
    @echo "Build successful!"

# http://www.gnu.org/software/make/manual/make.html#Static-Pattern
$(OBJECT_FILES): $(OBJ)/%.o: %.cpp
    @echo Compiling $<
    @# ^^^ Your terminology is weird: you "compile a .cpp file" to create a .o file.
    @mkdir -p $(@D)
    @# ^^^ http://www.gnu.org/software/make/manual/make.html#index-_0024_0028_0040D_0029
    @$(CC) $(CFLAGS) -o $@ $<
    @# ^^^ Use $(CFLAGS), not $(LDFLAGS), when compiling.


Advent of Code 2016 Day 1 "No Time for a Taxicab"

Generative approach
The idea of functionally generating the next value from the current value rather than mutating a location is consistent with good Racket practice.
Naming

Instead of 0 1 2 3 using the symbols 'north...it's not obvious what comes next without taking notes and working through the code and figuring out the implementation details...'south 'east 'west is more typical of Racket and other Lisps. The reason is that it aligns the level of abstraction in the program with the abstractions in the problem domain.

When I see the parameter dir in the procedure get-heading my first thought is that it's type is a directory. The code base starting with low level string parsing probably sets me up. The extra characters of directory are worth the added clarity.

Abstractions
As with Naming 1. the abstractions in the code don't closely follow the business logic of the problem statement. There's no reference to Easter Bunny Headquarters or Taxicab Distance in the code. If the specification changed from taxicab to crowflight distance, it's not immediately obvious how to change the code.
  (define (distance-to-easterbunny-headquarters x y)
    (+ (abs x) (abs y))

Makes the code more modular and expresses the 'business logic' in the underlying problem explicitly. Because Racket treats functions as data, higher order functions allow further expression of the business logic and decoupling within the implementation.
  (define (taxicab-distance x y)
    (+ (abs x) (abs y))
  (define (distance-to-easterbunny-headquarters x y distance-function)
    (distance-function x y)

Even in the absence of change, the code will be more readable. And by extension a reviewer will spend less time trying to map the problem statement into the code.
In Racket, unlike many other languages, the idiom is to err on the side of verbosity and explanation. The guiding document is How to Design Programs (first edition, second edition) often referred to as HtDP. The methodology includes lots and lots of comments...even for someone who thinks the Easter Bunny and self-documenting code share some common features. Code golf the method is not.
Data Structures
HtDP methodology starts with data structures. The data structures should reflect the problem domain / business logic. Conversely as a general rule, working with values is a often code smell in Racket. There are a few corner cases where it is necessary and perhaps a few existing code bases where doing so maintains consistency. Otherwise it is likely that data structures will produce more modular and easier to read code.
Being only parameters passed to procedures, the review code's data structures are ad hoc and diffuse. Programmer defined data types are an idiomatic alternative.
(struct position (x y orientation))
(struct instruction (rotation distance))

These programmer defined data types automatically provide functions like position-x and instruction-rotation that align with the business logic and require. During debugging, a programmer defined data type provides something explicit to inspect. As the code evolves it provides a single place to implement changes, a known type to pass among procedures, semantics for creating a list of easter bunny headquarters locations, or hash table to memoize intermediate locations.
Formatting
Racket also has a style guide. It is typical to limit line length to 102 characters. For example:
(define input "R3, L5, R1, R2, L5, R2, R3, L2, L5, R5, L4, L3, R5, L1, R3,
               R4, R1, L3, R3, L2, L5, L2, R4, R5, R5, L4, L3, L3, R4, R4,
               R5, L5, L3, R2, R2, L3, L4, L5, R1, R3, L3, R2, L3, R5")

is a typical way to handle long lists for improved readability.
The style guide also favors define over let and it's related forms. The advantages beyond readability include not having to debug against the differences between let let* let-rec.
Proximity
Explicitly naming is good. Limiting the scope of symbols lexically can avoid subtle bugs. The first definition in the code is parse it is not used until the last definition and it is only used there.
Nesting the definitions is probably appropriate here. It might also have made my confusion in Naming 2. less likely.
(define steps

  ; convert "L1" to '(#\L 1)
  (define (parse step)
    (let ([dir (string-ref step 0)]
          [distance (string->number (substring step 1))])
      (list dir distance)))

  (map parse
    (string-split input ", ")))


SwingWorker comes with all the control features you try to emulate here. It already uses an ExecutorService under the hood. I'm not sure why you want to increase the maximum pool size, but given that the code does not compile as given, makes me suspect you did not decide this, based on performance measuring.

So here's what I did :

Launching the workers is lightweight enough to not need
to be run in a separate thread, so I inlined Starter.
Keeping tabs on task progression is done through the Future that you get from
an ExecutorService. SwingWorker exposes this by implementing Future
itself. Waiting until a SwingWorker is done is as simple as calling its
get() method, which will block until the task is done.
You don't need the low level constructs wait() and notifyAll().
Properly handle InterruptedException : put it in your throws clause, or if you catch
it, reset the Thread's interrupted flag by calling
Thread.currentThread().interrupt(); so clients of your code know the thread has been
interrupted, and they can do their own cleanup.
SwingWorker uses generics to know the type of the result. Typically when no result is
given, Void is chosen as a return type. (this makes a comment about not caring about
the return value superfluous).
I've spent attention to the visibility modifiers, tightening it wherever possible,
exposing only as much as is strictly needed.
Future.get() throws an ExecutionException if the underlying task execution
threw an exception. Your code had no means of dealing with those.

Here's my refactoring of your code :

public class ImproveMe {
    private final List<SwingWorker> workers;

    public ImproveMe(Task[] tasks) {
        workers = new ArrayList<>(tasks.length);
        for (Task task : tasks) {
            workers.add(new TaskWorker(task));
        }
    }

    /* User will call this to start the loading */
    public void startLoading() {
        for (SwingWorker worker : workers) {
            worker.execute();
        }
    }

    /* User will call this to ensure that everything has complete before continuing */
    public void blockUntilDone() throws InterruptedException {
        for (SwingWorker worker : workers) {
            waitForWorker(worker);
        }
    }

    private void waitForWorker(SwingWorker worker) throws InterruptedException {
        try {
            worker.get(); // will block until the worker's task is done
        } catch (ExecutionException e) {
            throw new RuntimeException(e); // more appropriate exception handling here
        }
    }

    private static class TaskWorker extends SwingWorker<Void, Void> {
        private final Task t;

        TaskWorker( Task t ) {
            this.t = t;
        }

        public Void doInBackground() {
            if ( t != null ) {
                //do stuff with 't'
            }
            return null;
        }
    }
}


Very nifty-looking code right there. However, you should declare table as private final. Also, you don't need to initialize each array component of table to null, Java already does this for you. What comes to insert, you could write simply

table[index] = new HashEntry(key, value);

omitting the return statement. Point is to write only necessary statements. In getValue, you might want to check whether table[index] is null, since if that is the case, your implementation will throw NullPointerException.


This "new String()" is unnecessary:

String inputMonth = new String();

I would leave it out completely:

String inputMonth;


htaccess for URL remapping, caching, and compression

Leverage browser caching is designed to prevent browsers from using a cache for too long. If your website is dynamic, this is necessary to prevent users' browsers from storing your website for too long.

The way your file does this is by checking the type of file, and making a browser's cache of it expire after a specified amount of time. Images the other files you listed generally change little, so that part of you code is good unless you create dynamic images often. Your XML and TXT file deadline is okay unless you have XML news feeds or similar. HTML expiration date is also good as those files are usually the most often edited.

Overall, your file structure is good. I am sorry if this did not answer your question.

Edit:
Note that a browser doesn't have to obey you request to revalidate the page.


Prompt

The most obvious bad practice here is the use of a global variable.  Instead of setting num as a side-effect, your function should return the result.

getNum() is not such a good name for the function.  PEP 8, the official style guide for Python, says that function names should be lower_case_with_underscores.  Furthermore, "get" implies that the function is retrieving a piece of data that is already stored somewhere, which is not the case here.  Finally, "Num" should be more specific.

The use of recursion is not appropriate.  If you want a loop, write a loop.

def ask_integer():
    """
    Return an integer entered by the user (repeatedly prompting if
    the input is not a valid integer).
    """
    while True:
        try:
            return int(input("> "))
        except ValueError:
            print("Please enter an integer")

num = ask_integer()

collatz function

Strictly speaking, you didn't follow the instructions.  Your solution isn't wrong or bad — you just didn't implement the collatz function according to the specification that was given, which says that you should print and return one single number.

def collatz(num):
    """
    Given a number, print and return its successor in the Collatz sequence.
    """
    next = num // 2 if num % 2 == 0 else 3 * num + 1
    print(next)
    return next

num = ask_integer()
while num > 1:
    num = collatz(num)


SQL Query over ODBC is slow with DISTINCT

This is a messy query, I personally don't like nesting a select statement in my joins, I would rather use a Common Table Expression like this

WITH csmax AS (
    SELECT CustomerID, MAX(CreateDate) AS MaxDate
        FROM PUB.CustomerSalesperson
        GROUP BY CustomerID
)
SELECT DISTINCT cs.CustomerID, cs.SalespersonID
    FROM PUB.CustomerSalesperson cs
    INNER JOIN csmax ON cs.CustomerID = csmax.CustomerID
    WHERE csmax.MaxDate = cs.CreateDate

This should help the DB run the query more efficiently as well.  using the with statement should allow the SQL Engine to create a table and then compare the tables the way they were meant to be compared.  The CTE actually prepares the table before the outer query is run, so we aren't doing this on the fly.

Sounds like you can't run this through the ODBC connection, I looked at the documentation that you linked me to and found a CREATE VIEW command that would probably have similar efficiency to using a CTE.

CREATE VIEW csmax (CustomerID, CreateDate) AS
    SELECT CustomerID, MAX(CreateDate) AS MaxDate
        FROM PUB.CustomerSalesperson
        GROUP BY CustomerID ;

SELECT DISTINCT cs.CustomerID, cs.SalespersonID
    FROM PUB.CustomerSalesperson cs
    INNER JOIN csmax ON cs.CustomerID = csmax.CustomerID
    WHERE csmax.MaxDate = cs.CreateDate

DROP VIEW csmax

This code is more readable than the code that you wrote, it is easier to follow.

First thing you want to do is get a list of all the customers and the most recent date they did whatever.

Then, you want to know which Sales Person is associated with the "whatever" that customer did at their most recent visit.


I thought it would make sense if you created a function alive, which would take care of bounds checking for you. And also simplify the the final expression by using a single sequence expression instead of two like you do.

But I'm not sure it's actually much better than your version:

let amount_neighbours (board: Cell[,]) (pos: int * int) =
    let alive board pos =
        let (x, y) = pos
        if x < 0 || x >= Array2D.length1 board ||
           y < 0 || y >= Array2D.length2 board then
            false
        else
            board.[x, y] = Alive

    let vicinity x = seq { x - 1 .. x + 1 }

    seq {
        for x in vicinity (fst pos) do
        for y in vicinity (snd pos) do
        if (x, y) <> pos && alive board (x, y) then
            yield true
    } |> Seq.length


Getting the index (x,y) of a char in a "2D" list in Haskell

Disclaimer: I'm rusty with Haskell, there may be a cleaner way to do this.

Code review: your code looks fine to my eyes, it's just that circuitFind is overly complex, as you suspected. Also note that findIndex (==t) can be written as elemIndex t (source).

  "Let us see whether we could, by chance, conceive some other general
  problem that contains the original problem and is easier to solve." –
  Leibnitz.

We start by solving the more general problem of finding all indices of t in c.

Let's look at the skeleton of our solution.

[ (x,y) | ??? ]

We can get y using zip [0..] as you have done.

[ (x,y) | (y,line) <- zip [0..] c, ??? ]

Now we can find x using elemIndices.

[ (x,y) | (y,line) <- zip [0..] c, x <- elemIndices t line ]

Thanks to lazy evaluation, and Data.Maybe, we get our solution

circuitFind :: Circuit -> Tile -> Maybe Position
circuitFind c t = listToMaybe [ (x,y) | (y,line) <- zip [0..] c, x <- elemIndices t line ]


Adding fade to jquery background position animate

I wanted to know if there's firstly a better way to write the following

Well, not much to be improved but you can simplify things a little bit using hover()

$('#facebook')
.css('background-position', '0 0')
.hover(function () {
    $(this).stop().animate({
        'background-position' : '(-63px 0px)'
    }, 150);
}, function () {
    $(this).stop().animate({
        'background-position' : '(0 0)'
    }, 150);
});

  implement a fade so as the background animates it's also fading in on hover

Your best bet is to implement it with two separate images instead of a sprite. You absolute position each image on top of each other, animate their top for the moving effect, and then fadeIn()|fadeOut().


Since your question is about coding style, consider to adhere to PSR-2.

Your color comparision function is bloated. 'If the expression is true, then return true, else, if the expression is false, then return false.' Just return the expression.

return ($color >= $c-2 && $color <= $c+2);

Next, I'd make the literal '2' variable, and add some DocBlock documentation:

/**
 * Check if two color components are similar
 *
 * @param  int  $color  The first color component's value
 * @param  int  $c      The second color component's value
 * @param  int  $dist   The maximum difference for two values to be considered equal
 *
 * @return boolean  True, if the color components are similar.
 */
function colorComp($color, $c, $dist)
{
    return ($color >= $c-$dist && $color <= $c+$dist);
}


Statistical function which computes the average work time in different months

Rubocop Report

Rubocop was able to solve minor layout issues regarding the use of white spaces. One note-worthy change it proposed is:

[Corrected] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.

days_aggregate.each do | key, task |
  parts = key.split("-")

 parts = key.split('-')

A bigger complexity issue it found was:

Metrics/AbcSize: Assignment Branch Condition size for work_per_month is too high. [33/15]
Metrics/MethodLength: Method has too many lines. [30/10]

This means your method work_per_month is doing way too much. It has more than double the AbcSize than the suggested threshold [33/15]. You should split this method in sub-routines.


I would modify a bit logic regarding spacing between words in lines. With your solution you might end up with unnecessary spaces on line ends.

Additionally using Array.reduce instead of for loop is more JS-way to join array.

const formatTextWrap = (text, maxLineLength) => {
  const words = text.replace(/[\r\n]+/g, ' ').split(' ');
  let lineLength = 0;

  // use functional reduce, instead of for loop
  return words.reduce((result, word) => {
    if (lineLength + word.length >= maxLineLength) {
      lineLength = word.length;
      return result + `\n${word}`; // don't add spaces upfront
    } else {
      lineLength += word.length + (result ? 1 : 0);
      return result ? result + ` ${word}` : `${word}`; // add space only when needed
    }
  }, '');
}

let testingText = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam blandit mauris id venenatis tincidunt. Vestibulum at gravida sapien. Mauris tellus augue, aliquet sed laoreet blandit, pulvinar sed felis. Phasellus nec est vitae enim blandit facilisis.
Vestibulum fermentum ligula sit amet volutpat fermentum. Sed in faucibus orci. Pellentesque a dui ex. Curabitur sollicitudin, nulla id dignissim lacinia, odio mauris blandit nisi, eget auctor arcu odio nec est.`;
console.log(formatTextWrap(testingText, 20));


I have made some changes and added comments for each change.
// add the default array here ------------↓
const validateAndFormatdata = (questions = []) => {
  let errorsExist = false, // <- typo in exist
      // in case you want to add new types
      optionTypes = new Set(["multiple_answer", "single_answer"]);

  // no need to check for || [] because default is added
  // remove the errors property here itself by using destructuring
  const formattedData = questions.map(({ errors, question_options, ...question }, index) => {
    // because of the destructuring, question is a new object.
    // So, will not mutate the original object
    question.order = index;

    const newErrors = []

    // checks if label exists and if it is an empty string
    if (!question.label) {
      newErrors.push(errorReasons.missingLabel)
    }

    if (optionTypes.has(question.question_type)) {
      const questionOptions = question_options
                                    .filter(q => q.label)
                                    .map((option, order) => ({ ...option, order }));

      // === 0 is much more clearer to read
      if (questionOptions.length === 0) {
        newErrors.push(errorReasons.noOption)
      } else {
        // no need for [...]. It's a new array
        question.question_options = questionOptions
      }
    }
    // no need for delete question.question_options because it is destructured

    if (newErrors.length > 0) {
      errorsExist = true
      question.errors = newErrors
    }

    return question;
  })

  return {
    errorsExist,
    data: formattedData
  }
}


You have a couple of memory leaks.

First, the DeallocateMemory() will only delete the object's memory block if the size is greater than 0:

void Array :: DeallocateMemory()
{
    if(this->GetSize() > 0)  // GetSize() will return zero at this point
    {
        delete [] this->m_ArrayContainer;
        this->SetSize(0);
    }
}

However, in C++ it's legal to allocate a memory block with 0 size. (See the Q&A C++ new int[0] -- will it allocate memory? on Stack Overflow for more information.) When you allocate memory, you actually get two things: the memory that you asked for, and some data that the C++ runtime uses to keep track of that memory block.

If you have a sequence of code like:

Array a(0);
a.Resize(1);

the constructor will allocate a 0-sized block of memory and the extra data for the C++ runtime. When Resize() calls DeallocateMemory(), it'll see that your data block is 0-sized, won't invoke delete[], and leak that memory when AllocateMemoryOfSize() overwrites the object's m_ArrayContainer pointer:

void Array :: AllocateMemoryOfSize(int size)
{
    this->m_ArrayContainer = new int[size]; // Memory leak!
    this->SetSize(size);
}

Second, in your assignment operator, the first thing you do is to set the size of this to zero:

void Array :: operator = (Array & arr)
{
    this->SetSize(0);
    int size = arr.GetSize();
    this->Resize(size);
    /// [stuff elided].
}

Next, you call Resize with the size of the other object:

void Array :: Resize(int newSize)
{
    int oldSize = this->GetSize();

    for(int i=0 ; i<oldSize ; i++)
    {
        this->SetItem(i, NULL);
    }
    this->DeallocateMemory();

    this->AllocateMemoryOfSize(newSize);
    this->SetSize(newSize);
}

Note that the for-loop at the start doesn't actually do anything because the size of this has been set to zero by the time you get here. Even if it didn't, it would be unnecessary because the intent is to delete[] that memory soon afterwards, and once it has been returned to the heap, the contents of memory are irrelevant.

Then you call DeallocateMemory(), which won't delete any memory because the size field in this has already been set to zero. Finally, you call AllocateMemoryOfSize() which unconditionally overwrites the pointer to the array, leaking memory the same way as in my first point above.

To fix these bugs, I would:

Check if m_ArrayContainer is a null pointer to decide if I need to delete[] it.

void Array :: DeallocateMemory()
{
    if(this->m_ArrayContainer != NULL)
    {
        delete [] this->m_ArrayContainer;
        this->m_ArrayContainer = NULL;
        this->SetSize(0);
    }
}

Don't zero out the memory in this just before deleting it; your Resize() method then becomes:

void Array :: Resize(int newSize)
{
    this->DeallocateMemory();

    this->AllocateMemoryOfSize(newSize);
    this->SetSize(newSize);
}

Don't set the size field independently of the allocation or deallocation of memory. You have calls to SetSize() in several places in your code: remove all except the ones in AllocateMemoryOfSize() and DeallocateMemory().

In the context of your assignment operator, this becomes:

void Array :: operator = (Array & arr)
{
    int size = arr.GetSize();

    this->Resize(size);

    for(int i=0 ; i<size ; i++)
    {
        this->SetItem(i, arr.GetItem(i));
    }
}

Note that there are still other ways that this class could fail, for example if an exception is thrown during allocation. I recommend reading about exception guarantees: in a nutshell, do the memory allocation and copying of the other instance into temporary memory first, then if that succeeds, free up the resources in this instance and assign the temporary values to them. Scott Meyers covers it well in his book, Effective C++.

Speaking of the assignment operator, it's customary to have it return a reference to this:

Array &Array::operator= (Array & arr)
{
    // [rest of the assignment operator elided]
    return *this;
}

This will allow you to chain together assignments like:

Array a, b, c;
// ... stuff ...
a = b = c;


Since you are asking what are the cases to consider, I'll give you a very simple one. Following that, there is a further refinement to achieve a final solution as well as a few comments to consider.

Trading space for speed using memoization

Definition: https://en.wikipedia.org/wiki/Memoization

Basically, we want to keep a look-up table of Fibonacci numbers that we've already computed in order to avoid computing them again. We can also obtain newer Fibonacci numbers by simply using the pre-computed values that we've already evaluated.

package codereview;

import java.util.HashMap;

public final class FibonacciNumber {
    /**
     * A O(1) look-up table to store Fibonacci numbers
     */
    private static HashMap<Integer, Integer> computedFibonacciNumbers = new HashMap<>();

    /**
     * Calculates the n-th Fibonacci number by using memoization
     *
     * @param n
     *            n-th Fibonacci number to calculate
     * @return n-th Fibonacci number
     */
    public static int getFibonacci( final int n ) {
        // check for Fibonacci numbers that have already been computed
        if ( computedFibonacciNumbers.containsKey( n ) ) {
            return computedFibonacciNumbers.get( n ).intValue();
        }

        if ( n == 0 || n == 1 ) {
            return 1;
        } else {
            // calculate it
            Integer nFibonacciNumber = getFibonacci( n - 2 ) + getFibonacci( n - 1 );

            // insert it into our look-up table
            computedFibonacciNumbers.put( n, nFibonacciNumber );

            return nFibonacciNumber.intValue();
        }
    }
}

For example, this will greatly increase the speed of computing successive Fibonacci numbers.

Here is a timed test that should show you the difference:

package codereview;

import java.lang.Runnable;

public class Main {
    public static void main( String[] args ) {
        int loops = 40;

        Runnable memoizationCompute = () -> {
            int last = 0;
            for ( int i = 0; i < loops; ++i )
                last = FibonacciNumber.getFibonacci( i );
            System.out.println( "fibonacci = " + last );
        };

        Runnable alwaysCompute = () -> {
            int last = 0;
            for ( int i = 0; i < loops; ++i )
                last = getFibonacci( i );
            System.out.println( "fibonacci = " + last );
        };

        System.out.println( timeExecutionMilliseconds( memoizationCompute ) );
        System.out.println( timeExecutionMilliseconds( alwaysCompute ) );
    }

    public static long timeExecutionMilliseconds( Runnable r ) {
        long timeBegin = System.nanoTime();
        r.run();
        long timeEnd = System.nanoTime();
        return ( timeEnd - timeBegin ) / 1000000;
    }

    public static int getFibonacci( int n ) {
        if ( n == 0 || n == 1 )
            return 1;
        else
            return getFibonacci( n - 2 ) + getFibonacci( n - 1 );
    }
}

The problems of recursiveness

However, while this highlights an optimization to your current solution, there are better alternatives. You should usually consider implementing recursive algorithms as non-recursive because this will result in better speed and will also allow for higher values of n, since you will get a java.lang.StackOverflowError when you try to compute it recursively for modest values of n.

A final solution?

Knowing all this, we can combine both approaches in order to get the benefits of the iterative solution and the benefits of storing precomputed values. This is good if you will be constantly accessing Fibonacci numbers in a range.

Source of iterative algorithm: http://en.literateprograms.org/Fibonacci_numbers_(Java)#Iteration

package codereview;

import java.util.HashMap;

public final class FibonacciNumber {
    /**
     * A O(1) look-up table to store Fibonacci numbers
     */
    private static HashMap<Integer, Integer> computedFibonacciNumbers = new HashMap<>();

    /**
     * Calculates the n-th Fibonacci number by using memoization
     *
     * @param n
     *            n-th Fibonacci number to calculate
     * @return n-th Fibonacci number
     */
    public static int getFibonacci( final int n ) {
        // check for Fibonacci numbers that have already been computed
        if ( computedFibonacciNumbers.containsKey( n ) ) {
            return computedFibonacciNumbers.get( n ).intValue();
        }

        int prev1 = 0, prev2 = 1;
        for ( int i = 0, hi = n + 1; i < hi; i++ ) {
            int savePrev1 = prev1;
            prev1 = prev2;
            prev2 = savePrev1 + prev2;
        }
        computedFibonacciNumbers.put( n, prev1 );
        return prev1;
    }
}

Implementation remarks

While this is working code, there is still work to be done in order to make this more efficient. I'll leave the implementation of most comments in the following section to you.

Other comments

Can you get even better performance by using a simpler data structure? See this comment for a suggestion. It entails using n as the index of the array.
Is the int type really sufficient for computing Fibonacci numbers? We note that it starts to overflow for n >= 46 (See this comment in another answer). You might want to use BigInteger.
What happens with invalid values of n (negative values)? Do you assume users are responsible enough to use the method correctly (I would, but this is subjective).
Mark constant variables as final. n is never modified it should thus be marked as final to indicate so to users. It is clearer and less error-prone in the sense that you won't modify it by mistake.
You will most definitely want to provide Javadoc in production code. You should also do it for your own code, as it can clearly define what the operation does without having you read through the code. You can look at my Javadoc for a very basic documentation of the method.
Is there a more efficient way of doing the calculation? See this answer for a way and this comment for possibilities.


As your code goes everything i believe is fine. Define the template, define overloads and combine. Some things i've noticed that might be arguable:

Is it possible that your script will have zero arguments? For example a script with id = N denotes print last command or show commands history. If yes, your code wont compile since

template<typename T>
void push(T && arg) {
   _push(std::forward<T>(arg));
}

doesnt accept zero arguments. Perhaps replace it with zero arg overload?

template<typename T>
void push() {
    // cout << "All parameters passed to Lua! [Empty args case]\n";
}

Also as Args && ... other can actually be zero length there's a question of which will be called template<typename T> void push(T && arg) or template<typename T, typename ... Args> void push(T && arg, Args && ... other). Since push(std::forward<Args>(other)...) can not compile with 0 args, then the first overload will get called. I'd call that a bit misleading if somebody else has to work with your code.
The run_script func is packed with expressions which could potentially fail. So i'd probably try to encapsulate each step into its own method and move the _run() to the zero template push.

template<typename T>
void push() {
    // cout << "All parameters passed to Lua! [Empty args case]\n";
    _run(params);
}

That way if push<T>() gets called you're sure all the parameters were passed to interpreter.
Question arises here is how do you pass params to zero arg push? The topic says C++ way and that means OOP. Imo if you're asking about the C++ style then perhaps you should encapsulate your logic and provide an interface to the user. So go for a class which would hold the arg number as a private member and handle the actual processing of different types. Perhaps two classes one for command and one for processing it. That way it will be easier to scale.
And before doing that i'd think about the actual use of your application:

Will somebody else will be using it?
Will it be used in a multithreaded environment?
What guarantees for the user do you want to provide?

Your entry function bool run_script is supposed to return true or false i guess depending on how the execution of the script went. Does it really boil down to two outcomes? Are you giving a guarantee that the code would execute no matter what? Perhaps a enum class would suit better.
Your lua_pushstring(L, arg) and lua_pushinteger(L, arg) all hold some L - so seems only fair to hide it somewhere in the class as a private member as well as arg num.
Are you sure that you'll know all your types at compile time? What if somebody passes a double? There are more elegant ways to check the type being passed but this will do:

template <class A, class B>
struct eq {
   static const bool result = false;
};

template<class A> struct eq<A, A> {
    static const bool result = true;
};

and use

if (!eq<int, A>::result) {
    //...unsupported type error
}

p.s. great project btw. A while a go I've used sockets in Lua and C++ to communicate. So if your code is online I'd love to check it out.


I assume you're working with a 40MB file instead of a 40GB file. The performance will vary greatly depending upon:

the length of each line in the file
the number of lines in the file
the number of uniquely keyed-lines in the file

I've worked with a contrived data-file that is 5.127MB in size and has 250,000 data rows like:

a   b   c   d   e   f   g   h   i   j
b   c   d   e   f   g   h   i   j   k
a   b   c   d   e   f   g   h   i   j

The file has nearly all duplicated records, so I'm pushing the limits on the unique key approach. A file with all unique values will perform differently.

Using your code against the 5MB file, it runs in 6.18s. If I only read the file, it reads in 0.11s. If I only read the file, split each line and build a key, it runs in 0.76s. So approximately 5.42s, or 88% of the duration is related to dictionary manipulation.

So, what can we do in VBA, to improve your code

Option Explicit
You haven't included it in your code, so I assume it isn't declared.

Declare filename As String
The filename variable isn't declared, although you may have declared it at global scope. Option Explicit shows e this right away.

Dim filename As String

Declare tmp as a String Array
tmp is assigned with the Split function, which returns a String array, so declare tmp accordingly and you'll use a great deal less memory.

Dim tmp() As String

Early Binding
You're using CreateObject("Scripting.Dictionary"), so your code will fail anyway, if Microsoft Scripting Runtime isn't available. But more importantly, by using late-binding, COM has to work harder to find the methods you're using. It's much better to early-bind by adding a reference to Microsoft Scripting Runtime.:

Dictionary variable names
You've used ambiguous names: Dict and duplicatecount. You'd be better off with more meaningful names (I don't know what your data is, so I'm using less un-meaningful names) like:

Dim allRecords As Scripting.Dictionary
Dim uniqueKeyCounts As Scripting.Dictionary

Set allRecords = New Scripting.Dictionary
Set uniqueKeyCounts = New Scripting.Dictionary

Avoid using magic function/literal values
You're referring to the Tab character Chr(9) which incurs time on every line. VBA has a built-in constant for Tab: vbTab, which makes it more efficient and easier to read.

tmp = Split(DataLine, vbTab)

Unique keys and Dictionary usage
The code to build a unique key and populate the dictionaries is the most expensive, so let's be careful about checking the smallest dictionary more frequently than the large dictionary.

Also, there's no need to Remove and then Add back, when we can just increment the count of the existing entry.

If uniqueKeyCounts.Exists(key) Then
  'Retrieve the current count once
  Dim currentCount As Long
  currentCount = uniqueKeyCounts.Item(key)
  allRecords.Add key & ">" & currentCount, DataLine
  'Don't remove and re-add, just increment the counter
  uniqueKeyCounts(key) = currentCount + 1
Else
  uniqueKeyCounts.Add key, 1
  allRecords.Add key, tmp
End If

Close the file
You've opened the file and read it all, but you've forgotten to close the file:

Close #FileNum

Timing events
Using Now() offers very limited granularity. Timer gives you improved granularity but also a few problems when timed-code runs through midnight, but it avoids the need for win32 functions. If you want better timing see GetTickCount, or better still, QueryPerformanceCounter.
I've used Timer for the sake of simplicity.

Dim start As Double
start = Timer
'...Do stuff...
Debug.Print Timer - start

So, when I put it altogether, the file is read in 4.85s, or about 22% faster.

Sub ScriptDic()

  'Declare fileName
  Dim filename As String

  Dim FileNum As Integer
  Dim DataLine As String
  'Declare tmp as a string array
  Dim tmp() As String
  'Declare as Scripting.Dictionary to get early-binding benefits
  Dim allRecords As Scripting.Dictionary
  Dim uniqueKeyCounts As Scripting.Dictionary
  Dim key As String
  Dim count As Long

  'USe early binding
  Set allRecords = New Scripting.Dictionary
  Set uniqueKeyCounts = New Scripting.Dictionary

  Sheets("Control").Cells(5, 3).Value2 = Now
  filename = "C:\Temp\test100k.txt"
  FileNum = FreeFile()

  Dim start As Double
  start = Timer
  Open filename For Input As #FileNum
  Do While Not EOF(FileNum)
      Line Input #FileNum, DataLine ' read in data 1 line at a time
      'USe the vbTab constant
      tmp = Split(DataLine, vbTab)
      key = tmp(7) & "-" & tmp(8)
      'Check the unique dictionary - it's almost always smaller
      If uniqueKeyCounts.Exists(key) Then
        'Retrieve the current count once
        Dim currentCount As Long
        currentCount = uniqueKeyCounts.Item(key)
        allRecords.Add key & ">" & currentCount, DataLine
        'Don't remove and re-add, just increment the counter
        uniqueKeyCounts(key) = currentCount + 1
      Else
        uniqueKeyCounts.Add key, 1
        allRecords.Add key, tmp
      End If
  Loop

  'Close the file
  Close #FileNum

  Debug.Print Timer - start
  Sheets("Control").Cells(6, 3).Value2 = Now
End Sub

But do you really want a Dictionary?
Using the existing and optimized approach, you'll end up with a dictionary that is keyed by what seems to be an arbitrary index. You may have your reasons, but if you're not going to use the features of a dictionary, you might be better off with an array:

This code runs in just 1.56s.

Sub ScriptDic1()

  'Declare fileName
  Dim filename As String

  Dim FileNum As Integer
  Dim DataLine As String
  'Declare tmp as a string array
  Dim tmp() As String
  'Declare as Scripting.Dictionary to get early-binding benefits
  Dim uniqueKeyCounts As Scripting.Dictionary
  Dim key As String
  Dim count As Long

  Dim lineNumber As Long

  'Create an array that is larger than our needs, we'll resize it when we're done.
  ReDim allRecords(1, 500000) As Variant

  'USe early binding
  Set uniqueKeyCounts = New Scripting.Dictionary

  Sheets("Control").Cells(5, 3).Value2 = Now
  filename = "C:\Temp\test100k.txt"
  FileNum = FreeFile()

  Dim start As Double
  start = Timer
  Open filename For Input As #FileNum
  Do While Not EOF(FileNum)
      Line Input #FileNum, DataLine ' read in data 1 line at a time
      'USe the vbTab constant
      tmp = Split(DataLine, vbTab)
      key = tmp(7) & "-" & tmp(8)
      'Check the unique dictionary - it's going to be smaller
      If uniqueKeyCounts.Exists(key) Then
        'Retrieve the current count once
        Dim currentCount As Long
        currentCount = uniqueKeyCounts.Item(key)
        allRecords(0, lineNumber) = key & ">" & currentCount
        allRecords(1, lineNumber) = tmp
        'Don't remove and re-add, just increment the counter
        uniqueKeyCounts(key) = currentCount + 1
      Else
        uniqueKeyCounts.Add key, 1
        allRecords(0, lineNumber) = key
        allRecords(1, lineNumber) = tmp
      End If
      lineNumber = lineNumber + 1
  Loop

  ReDim Preserve allRecords(1, lineNumber - 1) As Variant
  'Close the file
  Close #FileNum

  Debug.Print Timer - start
  Sheets("Control").Cells(6, 3).Value2 = Now
End Sub


A global flag would be clear and simple:

_LOGGED_DRIVER = False

def init_chromedriver(path, timeout=30):
    driver = webdriver.Chrome(executable_path=path)
    driver.set_page_load_timeout(timeout)
    global _LOGGED_DRIVER
    if not _LOGGED_DRIVER:
        _LOGGED_DRIVER = True
        logger = logging.getLogger('driver')
        for k, v in driver.capabilities.items():
            logger.log(logging.INFO, f"{k}: {v}")
    return driver

Alternatively, you could replace the function after it has been called for the first time:

def _init_chromedriver(path, timeout=30):
    driver = webdriver.Chrome(executable_path=path)
    driver.set_page_load_timeout(timeout)
    return driver

def init_chromedriver(path, timeout=30):
    driver = _init_chromedriver(path, timeout)
    logger = logging.getLogger('driver')
    for k, v in driver.capabilities.items():
        logger.log(logging.INFO, f"{k}: {v}")
    global init_chromedriver
    init_chromedriver = _init_chromedriver
    return driver

But I think the global flag would be clearer.


refactoring common behavior to js object

I would recommend using a constructor function to create the objects:

function FolderData() {

    this.allAttachments_vector_counter = 0;
    this.allAttachments_vector = [];
    this.attachment_position_dict = {};
    this.extraDetails_dict = {};

}

FolderData.prototype = {

    constructor: FolderData,

    getAttachmentsPerPage: function (pageNum) {
        var result = this.allAttachments_vector.slice(
            global_vars.NUM_OF_ATTACH_PER_PAGE * (pageNum - 1),
            global_vars.NUM_OF_ATTACH_PER_PAGE * (pageNum)
        );
        return result.length == 0 ? null : result;
    },

    getAttachmentsMarkupPerPage: function (pageNum) {
        var attachmentsMarkup = "";
        var attachments = this.getAttachmentsPerPage(pageNum);
        for (key in attachments) {
            attachmentsMarkup += attachments[key].attachment_markup + " ";
        }
        return (attachmentsMarkup == "") ? "No attachments to display" : attachmentsMarkup;
    },

    pushAttachment: function (attachment, position) {
        //not in dict yet
        if (this.attachment_position_dict[attachment.attachmentId] == undefined) {
            if (position ==  null) {
              position = this.allAttachments_vector_counter;
            }
            this.allAttachments_vector[position] = attachment;
            this.allAttachments_vector_counter++;
            this.attachment_position_dict[attachment.attachmentId] = position;
            //this.extraDetails_dict[attachment.attachmentId] = {};
        }
    }

};

...

DS.data_per_folder[CurrentContextMgr.current.folder.attr('id')] = new FolderData();

The benefit of this, other than readability, is that you don't create a separate copy of every function property for each object. The functions are instead attached to the constructor's prototype, so there is only one instance of each function, and functions are shared by each constructed object instance.


It seems like overkill to implement a class to represent the proxy pattern. Design patterns are patterns, not classes. What do you gain from your implementation compared to a simple approach like the one shown below?

class Image(object):
    def __init__(self, filename):
        self._filename = filename
        self._loaded = False

    def load(self):
        print("loading {}".format(self._filename))
        self._loaded = True

    def display(self):
        if not self._loaded:
            self.load()
        print("displaying {}".format(self._filename))

Some other notes on your code:

It doesn't follow PEP8. In particular, "Avoid extraneous whitespace [...] immediately inside parentheses."
No docstrings.
It makes more sense to use True and False for a binary condition than to use None and 1.
It's not necessary to append the class name to all the methods. In a class called Image, the methods should just be called load and display, not load_image and display_image.
You should use new-style classes (inheriting from object) to make your code portable between Python 2 and 3.


Standard way of reading file contents to a buffer

A few things stand out...

Function declarations

I'm not a huge fan of specify return type on previous line style:

void
die( int error_code, char* message )

However, if you're going to use it, be consistent (your main is defined differently).

should work in all cases

You're assuming that the file you're reading does't contain any nulls.  This may be OK, as you're not opening the file in binary mode, however if you decide to reuse the code for binary files, returning a null terminated buffer without a size field is going to cause issues.

Main is leaking

I know your main is just a test harness to demonstrate the code, however it's best to always use appropriate memory management.  Your function is allocating a buffer using malloc, you should be freeing it in your main.  By including this in your example it demonstrates that you recognise responsibility for the returned buffer is sitting with the caller.


Codility Fish (queue) programming challenge

I have some suggestions.

When declaring variable that has inheritance, uses the interface in the left declaration part; this will make the code easier to refactor.

Before

ArrayDeque<Fish> safetyPool = new ArrayDeque<Fish>();
ArrayDeque<Fish> activePool = new ArrayDeque<Fish>();

After

Deque<Fish> safetyPool = new ArrayDeque<Fish>();
Deque<Fish> activePool = new ArrayDeque<Fish>();

When using the diamond operators with variables, declared the type in the left side, the right one will become optional; since it's declared in the variable side.

Deque<Fish> safetyPool = new ArrayDeque<>();
Deque<Fish> activePool = new ArrayDeque<>();

To remove the Arrow Code in the while, I suggest that you read the blog post made by Jeff Atwood Flattening Arrow Code. In my opinion, it's the best way to get rid this kind of code.

The logic contained in the while can be refactored.

while (!activePool.isEmpty()) {
   Fish safeFish = safetyPool.peekLast();
   Fish swimmingFish = activePool.peekFirst();

   if (safeFish == null || safeFish.dir != 1 || safeFish.dir == swimmingFish.dir) {
      safetyPool.offer(activePool.pollFirst());
      continue;
   }

   if (safeFish.att > swimmingFish.att) {
      activePool.removeFirst();
   } else {
      safetyPool.removeLast();
   }
}


Reverse int within the 32-bit signed integer range: \$[−2^{31}, 2^{31} − 1]\$ Optimized

Unused header
We use nothing from <cmath>, so it need not be included.
This should be a function, not a class
Putting all code into a class suggests you have a background in Java or similar.
In C++, we can (and should) use ordinary functions for operations that are mathematically functions.  In this case, we have a pure function: it has no state, and should always give the same result for any given input.
If it's part of your program requirements that it must provide this (unhelpfully-named) class, then comment that.  I'd recommend that you still write a plain function, and simply provide an adapter to conform to the requirements:
int reverse_decimal_digits(int i);

class Solution
{
    public:
        int reverse(int i) { return reverse_decimal_digits(i); }
}

Choice of data type
If we're processing a 32-bit integer, then we should be using std::int32_t.  Plain int isn't necessarily large enough (it can be any size from 16 bits upwards).
Incorrect test
Given int i, then i > INT_MAX || i < INT_MIN is false by definition.  The requirement you quote is (my emphasis):

When the reversed integer overflows, return 0.

Not all integers have a negative
Beware of overflow here:

        if(i < 0) {
            sign = -1;
            i = i*sign;
        }

On 2s-complement systems, -1 * INT_MIN is undefined.
It turns out that we don't need this step, as in modern C++, the % operator can be used predictably with negative numbers to our advantage (see my modified code, below).
Don't do I/O from a pure function
I guess this is some leftover debugging that should have been removed:

        std::cout << reversed << '\n';

Additional tests
It's good that you've included some unit tests - I wish more people would do that!
Do think about which values to test.  Your choice agrees with mine somewhat, but diverges later:

0, 1 and -1 for the three simplest cases.
positive and negative two-digit numbers (e.g. 12 and -23).
smallest and largest allowable input (INT32_MIN and INT32_MAX).
smallest and largest allowable result, and the first overflow in each direction in first and last digits (±1463847412, ±1463847413,  ±1563847412).

Don't be tempted to over-test.  Tests need to be maintained, too, so try to limit the tests to those that exercise the limits within the implementation.
Minor improvements
The scope of pop can be reduced to within the loop.  And perhaps a better name would be digit?
noexcept and constexpr
Can we annotate the function with noexcept and constexpr?
Future
Should the number base be hard-coded to 10?  Perhaps there's a use for a reverser that works in arbitrary bases.  Certainly, base-16 is convenient for testing.

Modified code
I've used GoogleTest rather than plain C assert(), so as to get better messages when a test fails, but any testing method is fine.
#include <cstdint>

constexpr std::int32_t
reverse_digits(std::int32_t i, int base = 10) noexcept
{
    std::int32_t reversed = 0;
    const bool negative = i < 0;

    while (negative ? i <= -base : i >= base) {
        auto const digit = i % base; // negative if i < 0
        reversed = reversed * base + digit;
        i /= base;
    }

    // final digit may cause overflow
    const bool overflow =
        negative
        ? (reversed < (INT32_MIN - i) / base)
        : (reversed > (INT32_MAX - i) / base);
    if (overflow) {
        return 0;
    }

    return reversed * base + i;
}

#include <gtest/gtest.h>

TEST(Reverse, decimal)
{
    EXPECT_EQ(0, reverse_digits(0));
    EXPECT_EQ(1, reverse_digits(1));
    EXPECT_EQ(-1, reverse_digits(-1));

    EXPECT_EQ(21, reverse_digits(12));
    EXPECT_EQ(-32, reverse_digits(-23));

    EXPECT_EQ(0, reverse_digits(INT32_MIN));
    EXPECT_EQ(0, reverse_digits(INT32_MAX));

    EXPECT_EQ(2147483641, reverse_digits(1463847412));
    EXPECT_EQ(0, reverse_digits(1463847413));
    EXPECT_EQ(0, reverse_digits(1563847412));

    EXPECT_EQ(-2147483641, reverse_digits(-1463847412));
    EXPECT_EQ(0, reverse_digits(-1463847413));
    EXPECT_EQ(0, reverse_digits(-1563847412));
}

TEST(Reverse, hexadecimal)
{
    EXPECT_EQ(0x7ffffff7, reverse_digits(0x7ffffff7, 16));
    EXPECT_EQ(0, reverse_digits(0x10000008, 16));

    EXPECT_EQ(-0x7ffffff7, reverse_digits(-0x7ffffff7, 16));
    EXPECT_EQ(0, reverse_digits(-0x10000008, 16));
}


One note: You create extra work and time for the program by including all of the even numbers in the initial List creation.

You can do something similar to this to eliminate the even numbers:

var upperLimit = 9999;
List<Int64> primes = new List<Int64>();
for (int x = 2; x <= (upperLimit+1)/2; x++)
    primes.Add(2*x-1);

That should give you a much reduced list to have to run through. Other than that, it's a very nice and simple solution.


Well I learned a lot today, specifically that writing to UDP is on average faster than writing to a file on my local machine and on my servers.  My implementation on the UDP client was off.

If you look at this code:

require 'socket'
s = UDPSocket.new
before_time = Time.now
100_000.times do |i|
  s.send("#{i}", 0, 'localhost', 1234)
end
puts "Time elapsed was #{Time.now - before_time}"

There's something sneaky in there that I didn't catch with this line:

s.send("#{i}", 0, 'localhost', 1234)

When you pass in host and port into the send method it DNS resolves before each send, which has major overhead.  If instead I change the code to connect ahead of time like so:

require 'socket'
s = UDPSocket.new
before_time = Time.now
s.connect('127.0.0.1', 1234)
100_000.times do |i|
  s.send("#{i}", 0)
end
puts "Time elapsed was #{Time.now - before_time}"

I get benchmarks that beat File IO.  Boom.


Here are a few things:

The loop only handles one connection at a time, which could cause some issues for other clients connecting in the future. If returnResultsForTCP_O is slow and blocking, that could even prevent other clients from working.

Two possible solutions include:

Use http://reactphp.org/ to handle the connections

Or if you would still like to handle the connections manually, you can accept many connections at the same time by adding them all to an array and using socket_select to get arrays of all the sockets ready to read from or write to:

http://php.net/manual/en/function.socket-select.php

You would still need to make the database calls non-blocking. Again, reactphp has some database connection libraries available for it. Otherwise you will have to find another way to access the database in a non-blocking way. Although it isn't nonblocking, you can make a secondary php process you open with proc_open and pass the request into. Then just set stream_set_blocking on the proc_open pipe file handles, and read from it in your main loop.


I don't like how you use static field to indicate level of indentation, I think it would be better if you passed it down the recursion in parameters of the methods.

And while you're at it, you should probably separate your concerns: don't have everything in your Program class, but have one class that recurses directories, and one that writes them out. That way, you can reuse them if you want to write the output in a different way (say in a GUI app) or if you want to recurse through something else than files (say, registry entries).

Also, there is no need to check whether a collection is empty before iterating it, it just unnecessarily clutters the code.

And you should think about handling exceptions: there might be directories you don't have access to. And there's also a chance that a directory was deleted while you were iterating its siblings, so you should handle that too.


If someone searches for "Firstname Lastname" (with a space) it won't find it, even if it exists. I would suggest removing spaces from the search string with search.replace(/ /g, '')

You are not doing anything for special characters like apostrophe. Should searching for "OConner" not return "O'Connor"?

The sort function you have is almost the same as the default sort, except yours doesn't return 0 if they are equal. But you shouldn't use that anyway, since they are case sensitive. You can use .localeCompare instead.

Also note the IE doesn't support .includes. If this is running in a browser and you're not already using a polyfill or transpiler, you should do that, or find another way if you want to support IE.


Spacing For reasonably professional Python code (or for any Python code you or others may have to look at later - ideally, all code you ever write), it would be a good idea to follow the standard PEP 8 style guide, to improve readability. To start with, it recommends putting spaces between arguments and operators, and using 4 spaces for indentation:
pattern = re.compile('<title>RPi Cam Web Interface - Page \d*')
for i in os.listdir():
    parser = open(i, 'r', encoding='utf-8')
    m = pattern.search(parser.read())
    parser.close()
    os.rename(i, m.group()[35:] + 'html')

Raw string It's a good idea to use raw strings when creating Python patterns so that escape sequences aren't interpreted, and instead the backslashes are treated as regular characters inside the pattern. For this particular pattern you're using, it happens to not be necessary, but if you ever had to change it and match a newline \n or a word boundary \b etc, not having used a raw string would result in the script not running as expected.
In other words, you'd want to do something like:
pattern = re.compile(r'<title>RPi Cam Web Interface - Page \d*')
#                    ^

Pattern I see 2 issues with the pattern:

The page number is optional because you're matching with \d* instead of \d+. Using \d+ to match one or more digits would make the intent of the pattern clearer. (\d* matches "zero or more digits")
You're manually extracting the page number from the match with m.group()[35:]. Use a capturing group in the pattern instead of having to manually count up indicies:

pattern = re.compile(r'<title>RPi Cam Web Interface - Page( \d+)')
#                                                         ^^^^^^
# ...
    page_number = m.group(1)


I see what you are trying to achieve, while your question does not fully meet the Code Review rules, but I guess some inputs won't hurt specially in my free time ;).

In my opinion,

You should use DateTime instead of string and int.
You should combine Talk and Slot, as it should be only one class that hold the meeting details (subject, time, and place ..etc).
You can use DurationInMin, but I would rather use DateTime and based on the business requirements, I would make a way to make the user input only integer while using DateTime in the back-end, (e.g. in the front-end, I make a field that only accepts int, and in the back-end, I call DateTime.AddMinutes()) this way, if the business logic required (in the future) to add meetings for future reference (such as making a meeting schedule for the next day or week ..etc), it'll be easy to adjust without being a break change.
Dictionary<Slot, string> should be Dictionary<int, Slot> the int will represent the TrackNumber, which will remove the need of TrackNumber.
GetScheduledTalk takes List<string> and return List<Track>, doesn't make any sense to me! using string list in this situation will be a real pain. Even if is it an input that you get from another resource (such as CVS). if there is any serialization process in this part, I would suggest moving it to a handler class, and create a model for it, then change the string to that model.

Finally, Naming Convention, you should keep your objects names clearer by naming each object to its rule. if the object is related to another object, then include the name of that object as well.

Here is a proposal that might help you in your implementation.

public enum ScheduleSessionName
{
    Python,
    Java,
    Blender
}

public class ScheduleSessionSlot
{
    public ScheduleSessionName SessionName { get; set; }

    public DateTime SessionTimeStart { get; set; }

    public DateTime SessionTimeEnd { get; set; }

    //you can use this method if you want to make SessionTimeEnd readonly property, so it will be automatically set with def
    public DateTime SetDefaultSessionTime(DateTime sessionTimeStart)
    {
        switch (SessionName)
        {
            case ScheduleSessionName.Python:
                return sessionTimeStart.AddMinutes(90);
            case ScheduleSessionName.Java:
                return sessionTimeStart.AddMinutes(75);
            case ScheduleSessionName.Blender:
                return sessionTimeStart.AddMinutes(120);
            default:
                return sessionTimeStart.AddMinutes(60);
        }

    }

}

public interface ISchedule : IEnumerable
{
    int Count { get; }

    void Add(int trackNumber, ScheduleSessionSlot sessionSlot);

    void Remove(int trackNumber);

    void Clear();

    new IEnumerator GetEnumerator();

}

public class Schedule : ISchedule
{

    private readonly Dictionary<int, ScheduleSessionSlot> _schedulesStore = new Dictionary<int, ScheduleSessionSlot>();

    public int Count => _schedulesStore.Count;

    public ICollection<int> TrackNumbers => _schedulesStore.Keys;

    public ICollection<ScheduleSessionSlot> SessionSlots => _schedulesStore.Values;

    public ScheduleSessionSlot this[int trackNumber]
    {
        get => _schedulesStore.ContainsKey(trackNumber) ? _schedulesStore[trackNumber] : null;
        set => _schedulesStore[trackNumber] = value;
    }

    public void Add(int trackNumber, ScheduleSessionSlot sessionSlot) => _schedulesStore.Add(trackNumber, sessionSlot);

    public void Remove(int trackNumber) => _schedulesStore.Remove(trackNumber);

    public bool Contains(int trackNumber) => _schedulesStore.ContainsKey(trackNumber);

    public bool Contains(ScheduleSessionSlot sessionSlot) => _schedulesStore.ContainsValue(sessionSlot);

    public bool Contains(KeyValuePair<int, ScheduleSessionSlot> schedule) => _schedulesStore.Contains(schedule);

    public void Clear() => _schedulesStore.Clear();

    public IEnumerator GetEnumerator() => _schedulesStore.GetEnumerator();

}

The rest, will require your action ;).


Rotating lists in linear time and constant space (Java) - follow-up

Input validation

If the list is empty, there will be division by zero.
Since you check for null input list,
it would make sense to do likewise for empty list as well.

Type parameter

The <T> is not needed in the Collections.<T>reverse statements,
this works just fine:

Collections.reverse(list);
Collections.reverse(list.subList(0, rotationCount));
Collections.reverse(list.subList(rotationCount, list.size()));


Basic Nginx server environment creation script

Error handling

The script misses error handling at several places.
The downloads could fail or be corrupt,
but the script will continue until the end,
and finding the failure point can be difficult.
Worse, if a failure is quiet enough,
it might not even get noticed.

Checking the exit code of every single command can be tedious.
An alternative is to add this near the top of the script:

set -euo pipefail

This will cause the script abort on the first failure,
and also treat suspicious operations as failure.

Long lines

Long lines are harder to read.
Instead of this:

cd /usr/local/src && wget http://www.rfxn.com/downloads/maldetect-current.tar.gz && tar -xzf maldetect-current.tar.gz

It would be easier to read with one line per command:

cd /usr/local/src \
  && wget http://www.rfxn.com/downloads/maldetect-current.tar.gz \
  && tar -xzf maldetect-current.tar.gz

Changing directories in scripts

Be careful with changing directories in scripts.
If an error happens in the middle of the operation,
the next operation may find itself in an unexpected directory (in the absence of adequate error handling).

Changing directories can become safer using (...) sub-shells.
For example instead of this, with a cd ~ at the end:

cd /usr/local/src && wget http://www.rfxn.com/downloads/maldetect-current.tar.gz && tar -xzf maldetect-current.tar.gz
cd maldetect-* && bash ./install.sh && cd ~

You could do this, without the need for the cd ~ at the end:

(
    cd /usr/local/src && wget http://www.rfxn.com/downloads/maldetect-current.tar.gz && tar -xzf maldetect-current.tar.gz
    cd maldetect-* && bash ./install.sh
)

Function declaration style

This is the recommended writing style:

nginx() {
    # ...
}

That is, no function keyword, and () after the name.

I would also give this function a more descriptive name.

Tips

Instead of:

mkdir /root/backups /root/backups/db /root/backups/dirs

You could write more compactly as:

mkdir -p /root/backups/{db,dirs}

Instead of cd ~, you could write simply cd.