java.util.Observable but with generics to avoid casts

Pick a convention for your curly brackets/indentation and stick with it. You code has all of the following:

Brackets included, one-lined statement
Brackets omitted, one-lined statement
New line after opening bracket, closing bracket on same line.
New line after opening bracket, closing bracket on different line.
Un-indented code inside brackets.
Padding spaces to vertically aligning opening brackets (with multiple different vertical lines being padded to).
Single space padding opening brackets.
Blank line before closing bracket.

The Java convention is:

public synchronized boolean add(final Observer<? super T> o) {
   return !this.observers.contains(o) && observers.add(o);
}

It is best to always include curly brackets even when they could be omitted. If you start with an if that does not include brackets and then need to add a second line, forgetting to would have the second line execute unconditionally.

It is safer to synchronize on a private instance variable than on the class instance. You have no control over what someone does with the instance of your class. Maybe they think it would be a good idea to use it to synchronize some other code. Now you have two different pieces of code using the same lock instance that might be result in a deadlock because they are not coordinated properly. A private lock variable guarantees that this can't happen.

You have to synchronize all accesses to observers. countObservers() could be called while you are adding or removing an observer.

Don't create aliases for your methods. It will only lead to confusion if there are multiple ways to do the same things.

observersSet is not a Set Don't make the argument name appear as if it is expecting one. If you do want it to be a set (you might since you are checking for duplicates in add()), then change the type from Collection to Set. If you need observers to be called in the order in which they were added, LinkedHashSet satisfies this requirement. If you accept any Collection when creating the instance, there is nothing to prevent the collection from already containing a duplicate.


Simple react app to fetch and display data

Requests could be handled better by first fetching planets and then fetching films, instead of waiting for all data to fetched before render. I would prefer to make a service call to get planets and then fetch films asynchronously after that.
As I mentioned above, I think it's better to get planets and then fetch films asynchronously.
Since you're looping through all planets and films, I expect it to take long time. In addition, you're waiting for films to be fetched all and then you display planet information. Also, this approach would not be working correct if there was more than one page of films response.
You can fetch planet and keep a current index value to show current planet information. And you can fetch featured films of that planet after planet info is rendered. To implement a better structured code, you can also use reducers.

I've implemented two versions, first version is without reducers and second one is with reducers. You can take a look at to get some idea and compare both solutions.

Without reducer: https://codesandbox.io/embed/swapiplanetsfilms-simple-wdtoh

With reducer: https://codesandbox.io/embed/swapiplanetsfilms-reducer-yg44l


Minimize array and output the remainder with respect to 1 second time limit

One easy way is to use numpy, which is implemented in C (if it is available on the machine your online judge is running on). It provides fast ways to do numerical calculations. In this case, you can use numpy.diff, which calculates the difference between elements. It even has a n argument, so it applies it n times. We also know how often we need to apply it to get only a single element, len(seq) - 1 times:

import numpy as np

n = int(raw_input())
seq = map(int, raw_input().split())
print np.diff(seq, len(seq) -1)[0]

If you need to stick to built-in methods, you could at least make the minimize_list method a bit shorter using a list comprehension (and maybe rename it to diff):

def diff(x):
    return [b - a for a, b in zip(x, x[1:])]

def reduce_diff(seq):
    while len(seq) > 1:
        seq = diff(seq)
    return seq[0]

if __name__ == "__main__":
    n = int(raw_input())
    seq = map(int, raw_input().split())
    print reduce_diff(seq)

I also removed the redundant copying from seq to final_list and instead of the for loop to convert all values to integers I used map.

Be aware that if you want to use this with Python 3 (as you should, since Python 2 will be obsolete soon), you need to surround that map call with a call to list and replace raw_input with input.

In addition I added a if __name__ == "__main__": guard to allow importing from this script from another script.

And finally, one can notice that this approach is \$\mathcal{O}(n^2)\$. When looking at a simple example of successive application of diff, a pattern becomes obvious:

\$
a, b, c, d, e\\
b-a, c-b, d-c, e-d\\
c-2b+a,d-2c+b, e-2d+c\\
d-3c+3b-a, e-3d+3c-b\\
e-4d+6c-4b+a
\$

The coefficients are the ones from Pascals triangle, together with an alternating sign:

\$
\begin{pmatrix}
 & & & & 1 & & & &\\
 & & & 1 & & 1 & & & \\
 & & 1 & & 2 & & 1 & & \\
 & 1 & & 3 & & 3 & & 1 & \\
1 & & 4 & & 6 & & 4 & & 1
\end{pmatrix}
\$

So, if you find a fast way to calculate the n-th row of Pascal's triangle, you can solve this problem in \$\mathcal{O}(n)\$, by adding the terms with a plus, modulo p and the ones with a minus, modulo p and then subtract them:

from itertools import cycle

def pascal_line(n):
    line = [1]
    mid, even = divmod(n, 2)
    line_append = line.append
    for k in xrange(1, mid + 1):
        num = line[k-1]*(n + 1 - k)//(k)
        line_append(num)
    reverse_it = reversed(line)
    if not even:
        next(reverse_it)
    line.extend(reverse_it)
    return line

def reduce_pascal(seq):
    return sum(sign * c * x
               for sign, c, x in zip(cycle([1, -1]),
                                     pascal_line(len(seq)-1),
                                     reversed(seq)))

if __name__ == "__main__":
    n = int(raw_input())
    seq = map(int, raw_input().split())
    p = 1000000000+7
    print reduce_pascal(seq) % p

One could make this also modular p at each step by doing the sum manually and enforcing the mod p.

Beware: This seems to break down for large sequences (since the terms in the triangle get big).


While you don't want alternative solutions, you should take a look at the data in your specific usecase. As an example, for some randomly generated input (both lists of length ~600) on my machine (Python 3.6.9, GCC 8.3.0), your function takes

In [18]: %timeit sorted_lists_intersection(a, b)
179 µs ± 1.19 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

The function defined in the answer by @alexyorke, while more readable IMO, takes a bit longer:

In [16]: %timeit list(intersect(a, b))
249 µs ± 4.67 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In contrast, this highly readable and short implementation using set and sorted, that completely disregards the fact that the lists are already sorted (which means that it also works with unsorted lists):

def intersect_set(a, b):
    return sorted(set(a) & set(b))

is about twice as fast:

In [29]: %timeit intersect_set(a, b)
77 µs ± 1.44 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Of course, in order to properly compare them, here are more data points:

import numpy as np

np.random.seed(42)

ns = np.logspace(1, 6, dtype=int)
inputs = [[sorted(set(np.random.randint(1, n * 10, n))) for _ in range(2)] for n in ns]

The set based function wins in all of these test cases:

It looks like for lists with lengths of the order of more than 10M your function might eventually win, due to the \$\mathcal{O}(n\log n)\$ nature of sorted.

I think the greater speed (for a wide range of list sizes), coupled with the higher readability, maintainability and versatility makes this approach superior. Of course it requires objects to be hashable, not just orderable.

Whether or not this data is similar enough to yours, or whether or not you get the same timings, performing them to see which one is the best solution in your particular usecase is my actual recommendation.


Since pthread_create() returns an error number on failure, you can put ret into strerror() to get the associated error message instead of just printing the number:

fprintf(stderr, "Thread 1 creation failed: %s\n", strerror(ret));

Notice that I'm calling fprintf() instead of printf().  Since you're printing an error, it must be sent to stderr, not stdin (used by default with printf()).

Also, while you'd normally not need all this code for printing an error, it's necessary since pthread_create() doesn't set errno (which is why ret is useful here).

For code that does set errno (which would be stated on man pages), you'd only need to call perror() to print the corresponding error message:

perror("<insert source of failure here>");

This would also eliminate the need for variables like ret in such code.  However, with pthread_create() and related functions, you could probably just put errno in its place and then use perror().
The functions called by pthread_create() should still return something.  Since the return value won't be useful here, you can just return NULL.
There's no need to call exit() right at the end of main().  You're preventing it from returning a value, and it'll always return 0 at this point anyway.
This isn't a criticism, but a tip: make sure you're running this through valgrind to check for any memory leaks along the way.

Actually, this may already cause a leak, but I haven't checked to make sure.  If it does, then you may need to call both pthread_mutex_destroy() and pthread_cond_destroy() before exiting the program at any point.


Iterating backwards was smart, but, yes, there is a much simpler way to do this using a list comprehension – this is how one typically filters a list in Python.

filtered_words = [word for word in word_list if word != user_input]

Note that this creates a new list object rather than altering the original word list in place.

Your current code isn't terribly inefficient – it iterates over the list twice rather than once, but both are asymptotically linear.

If you were to keep that structure, there are a number of small things that could be done to make the code more Pythonic. Compare the following loops to your own code:

for i, word in enumerate(word_list):
    if word == user_input:
        remove_queue.append(i)

for i in remove_queue[::-1]:
    del word_list[i]

These do the same thing, but are much more readable once one knows that enumerate can be used to iterate over both the index and element at once and that list[::-1] is a common method to iterate over a list backwards (albeit, slightly inefficient).

A final note is that I have updated all two-word names to use snake-case.


Racket isn't my Lisp of choice, but here's some general advice.

You're calling the function guess multiple times with the same arguments. The code would be much more readable (and slightly more efficient) if you bind the result to a local variable:

(define (game-iter number)
  (define (iter number count lower-boundary upper-boundary accu)
    (let ((guess (guess lower-boundary upper-boundary)))
      (cond ((= guess number) (values count guess))
            ((> guess number)
             (iter  number
                    (add1 count)
                    lower-boundary
                    (sub1 guess)
                    guess))
            (else (iter number
                        (add1 count)
                        (add1 guess)
                        upper-boundary
                        guess)))))
  (trace iter)
  (iter number 0 1 100 (guess 1 100)))

I'm not sure if the racket custom is to abbreviate variable names to avoid shadowing the function. Using the same name for the variable and the function shouldn't cause any problems in this case, so I'll just use guess here. Feel free to change it.

Your iter function has number as a parameter, but it never changes. It's unnecessary to pass it down, since it's already available from the outer scope. You also have a parameter called accu, which is never used. Unless you intend to use it later, it should be removed.

(define (game-iter number)
  (define (iter count lower-boundary upper-boundary)
    (let ((guess (guess lower-boundary upper-boundary)))
      (cond ((= guess number) (values count guess))
            ((> guess number)
             (iter (add1 count)
                   lower-boundary
                   (sub1 guess)))
            (else (iter (add1 count)
                        (add1 guess)
                        upper-boundary)))))
  (trace iter)
  (iter 0 1 100))

You coud collapse the two calls to iter into one by using if inside the call.

(define (game-iter number)
  (define (iter count lower-boundary upper-boundary)
    (let ((guess (guess lower-boundary upper-boundary)))
      (if (= guess number)
          (values count guess)
          (iter (add1 count)
                (if (< guess number)
                    (add1 guess)
                    lower-boundary)
                (if (> guess number)
                    (sub1 guess)
                    upper-boundary)))))
  (trace iter)
  (iter 0 1 100))

Notice also that you start counting guesses from zero. So if the number is 50, which is the first guess, the program will consider that to be zero guesses. It would make more sense to start from 1.

As pointed out by Renzo, you should also make sure that the number is in the range from 1 to 100:

(define (game-iter number)
  (define (iter count lower-boundary upper-boundary)
    (let ((guess (guess lower-boundary upper-boundary)))
      (if (= guess number)
          (values count guess)
          (iter (add1 count)
                (if (< guess number)
                    (add1 guess)
                    lower-boundary)
                (if (> guess number)
                    (sub1 guess)
                    upper-boundary)))))
  (trace iter)
  (if (< 0 number 101)
      (iter 1 1 100)
      ;; Raise an error or return something suitable
      #f))


Your comments should actually give you a hint.

' Getting data from DB:
' ...
' Populate retValue list with project names:

These sound like the beginnings of good function names to me.

Private Function GetAutocompleteItems(reader as DbDataReader) as List(Of AutocompleteItem)
    If reader.HasRows Then
        retValue = New List(Of AutocompleteItem)
        ' Populate retValue list with project names:
        Dim item As AutocompleteItem = Nothing
        While reader.Read()
            item = New AutocompleteItem()
            item.Value = reader.GetString("Location")
            item.Label = item.Value
            retValue.Add(item)
        End While
    End If

    Return retValue
End Function

Which would then be called like this.

        ' Getting data from DB:
        Using cmd As DbCommand = DbProvider.GetDbCommand(SQL, conn)
            cmd.Parameters.Add("@ClientID", DbType.Int32).Value = userData.ClientID
            cmd.Parameters.Add("@Filter", DbType.String).Value = String.Format("%{0}%", prefix)
            Using reader As DbDataReader = cmd.ExecuteReader()
                retValue = GetAutocompleteItems(reader)
            End Using
        End Using

As you can see, just extracting this one function out considerably reduced the nesting.

I don't see much else to pick on other than this.

    Finally
        conn.Close()
        conn.Dispose()
        Logger.WriteConnectionInfo("SearchDataAccess.GetLocationsAutocomplete", Logger.ConnectionActionType.Closed)
    End Try

DbConnection obviously implements IDisposable, so why not use another Using block?


The following line is incorrect:

return x + 1/6. * (k1 + k2 + k3 + k4)

Should be:

return x + 1/6. * (k1 + 2*k2 + 2*k3 + k4)

Cross reference:
This code


Excessive Memory Use

The first thing you do is read every line into memory:

while (std::getline(in, lineBuff)) // write multiline text to vector of strings
{
    vec.push_back(lineBuff);
}

Why? Do you need to have every line in memory? No. You're just trying to count the words. What if the file was 100TB worth of "all work and no play makes Jack a dull boy"?

Poor Memory Use

std::vector<StringOccurrence*> strOc;

That should yell antipattern to you. You're not holding pointers to existing objects, this is strOc actually owning that memory. You use new to add to it. I don't see any deletes. So you're leaking memory. Doesn't matter so much in this case, but this is exactly what RAII is for. Prefer:

std::vector<std::unique_ptr<StringOccurrence>> strOc;

Though, regardless, don't use a vector to begin with because...

Data Container Choice

You are holding a vector of StringOccurrences. That means that on each new word, you have to walk through the whole vector doing string comparisons. That is O(N). Everything about this is bad. To start with:

goto end; //skip next step (need fix?)

Yes, this needs a fix. Never use goto. The way to search for things is to use the <algorithm> library, specifically std::find_if:

auto it = std::find_if(strOc.begin(), strOc.end(), [&](StringOccurence* so){
    return so->m_str == stringBuff;
});
if (it != strOc.end()) {
    // success case
}
else {
    // new word case
}

That'll make your code easier to understand by far and drop the goto. But it won't handle the O(N) problem. For that, we just need to use an entirely new data structure. We need to map a word to a number, and we don't care about word ordering. Thus, std::unordered_map. This will have O(1) lookup. And we don't even need to do all that work ourselves!

std::unordered_map<std::string, int> strOc;
// for each word
++strOc[stringBuff]; // this will insert new elements as necessary

Cool.

Read the words directly

You are walking through a line character by character. That is error-prone at best, hard to follow at worst. But there's already support for this in C++. Use a std::stringstream. You could have just done:

while (std::getline(in, lineBuff)) {
    std::string word;
    std::istringstream iss(lineBuff);
    while (iss >> word) {
        ...
    }
}

Then again, operator>> is defined on any istream, not just istringstream. So we can use that on the ifstream directly:

std::string word;
while (in >> word) {
    ...
}

Use the right loops

Don't use auto with iterators - just use a range-based for-expression. It'll save on the typing and add to clarity.

Improved solution

std::unordered_map<std::string, int> wordCounts;
std::string word;
while (in >> word) {
    ++wordCounts[word];
}

std::ofstream out("test2.out");
for (auto const& wc : wordCounts) {
    out << wc.first << ' ' << wc.second << '\n';
}


how to pass a block to a function as a parameter

In order to pass a block to a function, you need to prefix it with an ampersand.

block_or_string = case @request.path
  when '/'    then Proc.new { |response| do_stuff }
  when '/env' then @end.to_html
end

response = if block_or_string.is_a?(Proc)
  Rack::Response.new(&block_or_string)
else
  Rack::Response.new(block_or_string)
end

This is pretty ugly. It might be an improvement to wrap the strings in simple procs.

block = case @request.path
  when '/'    then Proc.new { |response| do_stuff }
  when '/env' then Proc.new { @end.to_html }
end

Rack::Response.new(&block)


Advent of Code #4 in Haskell - Ascending digits with double digit

Disclaimer: I don't know Haskell and I have never used it before.

solve low hi = length . takeWhile (<= hi) . dropWhile (< low) . map read .
  filter (allF [hasDouble, noLeadingZeros]) $ combinations 6 ['0'..'9']
  where hasDouble = any ((== 2) . length) . group
        noLeadingZeros = (/= '0') . head

Instead of running combinations 6 ['0'..'9'] and then chopping off everything which has a zero at the start, generate numbers from 100000..999999 and then convert it to a string. This would eliminate the combinations method.

I was able to make the following conclusions about the algorithm:

if the numbers are sorted from smallest to largest, then it should equal the original number (i.e. they are already sorted from smallest to greatest)
if the numbers with no duplicates does not equal the original number, then it means that there is at least two which were "de-duped", therefore it has two duplicates

I was able to produce the following code:

import Data.List

checkNum num = do return ((sort(show num) == (show num) && (nub (show num)) /= (show num)))
main = do checkNum 4222211

This checks if the sorted number (as a string) is equal to itself (which means that it is increasing correctly), and nub removes all duplicate digits.


Use of scoped objects in a JavaScript Tic-tac-toe implementation

You're on the right track. Now a few things before stuff gets out of hand:

Not all your functions need to be on the literal. What return {} is doing is exposing stuff in the literal as t3Game in the global scope for other code to interact with your code. If you have functions that need not be exposed, define then in the closure. It will only be accessible by code within the closure, but not outside.

var t3Game = (function(){

  function myHiddenFunctionThatNeedsNotExposed(){...}

  return {...}

})();

} // end return

If you do proper indentation, then you don't need such markers. If you use an IDE, proper indentation will allow you to collapse blocks of code as well as show indent guide lines as long as you indent properly.

An alternate way to define a global namespace is the following:

;(function(ns){

  var sameVars = []

  function theHiddenFunction(){...}

  ns.myExposedFunction = function(){...}

}(this.t3Game = this.t3Game || {});

t3Game.myExposedFunction (...);

What this does is check if t3Game already exists. If it exists, it uses the existing one, and if not, uses a new literal. This way you don't accidentally destroy an existing object of the same name in the global scope.

for(i=1; i<=9; i++){
  squares[i] = "empty";
}

Arrays zero-indexed so it's best if you start with 0. Also, 9 is very ambiguous. We don't know what 9 is. Best if you put constant values in a variable with an appropriate name.

getImgFileName: function(playerOrComp){
    if(playerOrComp ==="player"){
        return playerImg;
    }
    else {
        return compImg;
    }
},

can be shortened to:

getImgFileName: function(playerOrComp){
  return playerOrComp ==="player" ? playerImg : compImg;
}

setImgFileName: function(choice){
    if(choice === "X"){
        playerImg = "images/X.gif";
        compImg = "images/O.gif";
    }
    else {
        playerImg = "images/O.gif";
        compImg = "images/X.gif";
    }
},

can be shortened to:

const X_IMAGE = "images/X.gif";
const O_IMAGE = "images/O.gif"

setImgFileName: function(choice){
  const isX = choice === "X";
  playerImg = isX ? X_IMAGE : O_IMAGE;
  compImg   = isX ? O_IMAGE : X_IMAGE;
}

Again, any constant value must be defined in a variable with a good name.

Lastly, code is for humans. Write verbose names for functions and variables so that the code is understandable.


The code mostly follows usual coding style and reads good. I would just change secondlow to second_low and avoid using abreviations in variable names.

Now for the improvements:

Print vs return

Do not code too much behaviour into your functions. Let them compute their stuff and return the result so the caller can do whatever they want with it. It doesn't add much here, but it is a good habit to have.

Getting the value you are looking for

seclow_stud = []
for student in students:
    if student[1] == seclow_grade:
        seclow_stud.append(student[0])

You do not need to store the only value you are looking for into a list. Especialy when using a for loop after that to extract the element out of the list:

for student in students:
    if student[1] == seclow_grade:
        return student[0]

Sorted

sort_grades = sorted(grades)
seclow_grade = sort_grades[0]
for grade in sort_grades:
    if grade != seclow_grade:
        seclow_grade = grade
        break

The sorted builtin returns a list of values in increasing order. What is important to note here is that sort_grades is a list. So sort_grade[0] is the lowest grade and sort_grade[1] is the second lowest. No need to search for the value yourself, sorted already did the work for you.

seclow_grade = sorted(grades)[1]

List-comprehensions

grades = []
for student in students:
    grades.append(student[1])

Python have these construct to easily build lists out of other iterables:

grades = [student[1] for student in students]

You can also use the same construct when building lists out of the input. Overall code would look like:

def secondlow(students):
    grades = [student[1] for student in students]
    seclow_grade = sorted(grades)[1]
    for student in students:
        if student[1] == seclow_grade:
            return student[0]

students = [[input(), float(input())] for _ in range(int(input()))]
print(secondlow(students))

Dictionaries

I know that the challenge explicitly mentionned lists of lists, but Python have dictionaries that can map a value to another. You can use them as a replacement:

def secondlow(students):
    seclow_grade = sorted(students.values())[1]
    for student in students.items():
        if student[1] == seclow_grade:
            return student[0]

students = {}
for _ in range(int(input())):
    name = input()
    grade = float(input())
    students[name] = value
print(secondlow(students))

Or you can take advantage of the way you can retrieve items associated to others by switching the way you store your data:

def secondlow(students):
    second_low = sorted(students)[1]
    return students[second_low]

students = {}
for _ in range(int(input())):
    name = input()
    grade = float(input())
    students[value] = name  # Note the switch here
print(secondlow(students))

Edit

After reading the challenge description again, I realised that there can be multiple students with the second lowest grade. And in fact, there might be cases where there are multiple student with the lowest grade. Making my point about having the second lowest grade as sorted(grades)[1] irrelevant… Unless you remove duplicates using a set:

def second_low(students):
    second_low_grade = sorted(set(students.values()))[1]
    for student in students.items():
        if student[1] == second_low_grade:
            yield student[0]

students = {}
for _ in range(int(input())):
    name = input()
    grade = float(input())
    students[name] = value

for second_lowest_student in second_low(students):
    print(second_lowest_student)

Here I used the yield keyword to avoid building a list in second_low. What it does is allowing the function to return several results: one each time there is a match (if student[1] == second_low_grade). Here is the version using list of lists:

def second_low(students):
    grades = set(student[1] for student in students)
    seclow_grade = sorted(grades)[1]
    for student in students:
        if student[1] == seclow_grade:
            yield student[0]

students = [[input(), float(input())] for _ in range(int(input()))]
for second_lowest_student in second_low(students):
    print(second_lowest_student)

Unfortunately, such requirements prevent you from using dictionaries the other way around.


Making this password search more intelligent

There's no real way to speed up the brute-force enumeration of all possible 3-letter passwords.

Perhaps you could use the dictionary.  There's a finite list of 3-letter English words.    They may be slightly more common.

Also, if you google for  "most common passwords", some kind of 3-letter version of that list could be tried before anything else.


boost::unordered_set intersection using templates

SetUtilites is misspelled; it should be SetUtilities.
For better readability, consider doing something about this long line:

static boost::unordered_set<Type> intersection(const boost::unordered_set<Type> &set1, const boost::unordered_set<Type> &set2)

You could shorten the types as such via typedef, but it may not help very much, or it may even make things uglier.  You could also wrap the line in some way.  Choose whichever works best.
Do you even need a class for this?  It just contains one function and no data members, so it's not really doing anything relevant as one.  Instead, just make this a free function (non-member function) and put it into a namespace with a similar name as the class.
The name iSet sort of sounds like Hungarian notation, although it appears to be a shortened form of intersectionSet.  If you still don't want to call it something that lengthy, you could rename it to something like finalSet, indicating that it will be returned from the function.


Reading two csv files as dictionaries with differing key definitions

Higher order functions

You should define a more general function and then use higher order functions to costumize behaviour:

def csv_dict(filename, key_func, value_func):
    final_dict = {}
    with open(filename, 'r') as f:
        csvReader = csv.reader(f)
        next(csvReader, None) # skip the header
        for row in csvReader:
            key = key_func(row)
            final_dict[key] = value_func(row)
    return final_dict

def dict_one(filename):
    return csv_dict(filename,
                    lambda row: row[0],
                    lambda row: row[1])

def dict_two(filename):
    return csv_dict(filename,
                    lambda row: " ".join(row[:3]).replace("  "," "),
                    lambda row: row[4])

Naming is more important than you think

Names like first_dict = {} and second_dict = {} are ugly and should be avoided even in throw-away code.

Enumerating

You can use enumerate to reduce verbosity:

def csv_dict(filename, key_func, value_func):
    with open(first_file, 'r') as f:
        for row_number, row enumerate(csv.reader(f)):
            if row_number == 0: # Skip header
                continue
            key = key_func(row)
            first_dict[key] = value_func(row)

Only write sensible comments

# Second dictionary gives no information and is just noise.


Shell POSIX OpenSSL file decryption script follow-up #1

Although print_error_and_exit correctly sends output to standard error and exits with a non-zero status, print_usage_and_exit outputs to standard out.  I recommend explicitly accepting -h (as your case implies, but getopts hasn't been instructed to do), and if the user asks for help, then writing to standard out and returning success, but if the help is provided due to error, then writing to standard error and returning failure:

print_usage()
{
    echo "Usage: $0 [-o output_directory] filename_to_decrypt"
}

while getopts ":ho:" option
do
    case "${option}" in
        o)
            given_output_directory=${OPTARG}
            ;;
        h)
            print_usage
            exit 0
            ;;
        '?')
            print_usage >&2
            exit 1
            ;;
    esac
done

shift $((OPTIND - 1))

[ "$#" -eq 0 ] &&
    print_usage && exit 1

While we're on error reporting, you might want to consider making the exit code be the first argument to print_error_and_exit rather than the last.  That can make the code easier to read, and it also allows you to pass multiple arguments, just like echo which it wraps:

print_error_and_exit()
{
    value=$1; shift
    echo "${bold_red}$* Exit code = $value.${nocolor}" 1>&2
    exit "$value"
}

It's good to see that you use tput to produce the terminal-specific escape codes (if they exist) for highlighting.  But it's probably not worth putting them into variables for a single use each.  I'd get rid of the variables and just write something like

print_error_and_exit()
{
    value=$1; shift
    exec >&2
    tput bold
    tput setaf 1   # red
    echo "$* Exit code = $value."
    tput sgr0
    exit "$value"
}

and (in the success branch)

else
    tput bold
    tput setaf 3   # yellow
    echo "Decryption successful."
    tput sgr0

    exit 0
fi

These tests are probably over-doing it:

[ ! -f "$1" ] &&
print_error_and_exit 3 "The given argument is not an existing file."

input_filename="$1"

[ ! -r "$input_filename" ] &&
print_error_and_exit 4 "Input file is not readable by you."

Unless there's a good reason we can't accept input from a pipe or other non-regular file, just skip the -f test: -r will fail if its argument doesn't exist.  It's also worth including the filename in the message - this is really useful when the user expands a variable into the call, and it doesn't expand to what she expects:

[ -r "$1" ] ||
    print_error_and_exit 3 "$1: not a readable file."

If you really feel you need different exit status for non-existent and existing-but-unreadable files (why?), then consider -e as an alternative to -f.

We should check whether the supplied output directory is actually a directory, before trying to use it:

[ -d "$output_directory" ] ||
    print_error_and_exit 4 "$output_directory: not a directory."
[ -w "$output_directory" ] ||
    print_error_and_exit 5 "Destination directory is not writeable by you."

A shorter way to write this:

if [ -z ${given_output_directory} ]
then
    output_directory="$input_filepath"
else
    output_directory="$given_output_directory"
fi

is to use parameter substitution with - modifier:

output_directory="${given_output_directory:-$input_filepath}"

I think a case helps with matching filename patterns here:

if [ "$filename_extracted_from_path" = "$filename_without_enc_extension" ]
then

I'd write that block as:

filename_extracted_from_path=$(basename "$input_filename")

# Strip .enc suffix from name if it has one, else add .dec suffix
case "$filename_extracted_from_path" in
    *.enc)
        output_filename="${filename_extracted_from_path%.enc}"
        ;;
    *)
        output_filename="$filename_extracted_from_path".dec
        ;;
esac
output_filename="$output_directory/$output_filename"

Note that there's no longer a need for $filename_without_enc_extension.

You definitely need to replace this -f with -e:

[ -f "$output_filename" ] &&
print_error_and_exit 6 "Destination file exists."


Get bibtex entries from metadata of PDF files

Always double-quote variables if they might contain spaces

These commands will fail if the variables contain spaces:

cd $FOLDER

# ...

echo >> $BIBTEX_FILE

Even if you never intend to use your script with paths containing spaces,
it's good to make it a habit to double-quote variables that might contain spaces:

cd "$FOLDER"

# ...

echo >> "$BIBTEX_FILE"

Error checking

What will happen if this command fails?

cd $FOLDER

If this fails, the program will happily continue,
download a likely invalid url with curl,
and create a bogus $BIBTEX_FILE,
essentially putting garbage in the current directory.

Look for possible points of failure where the program should abort.
If something goes wrong with this cd command you definitely don't want execution to continue.
Here's a simple way to abort:

cd "$FOLDER" || exit 1

Here's a more user-friendly way:

if ! cd "$FOLDER"; then
    echo "error: could not cd into $FOLDER"
    exit 1
fi

Use the modern $(...) instead of the obsolete `...`

For example:

TITLE=$(pdfinfo "$f" | grep Title | cut -c17-)

Notice that I double-quoted $f, as it should be.

Bogus pipeline

This is strange:

pdftotext $f /tmp/pdf | cat /tmp/pdf | ...

In a pipeline, usually the output of one command is passed as input to the next through stdout and stdin file handles. That's not what happens here, data is passed through a file. This is unusual and confusing.
Also confusing is to name a text file /tmp/pdf.

You don't need a temporary file here,
pdftotext can produce output on stdout,
and then you don't need cat either:

pdftotext $f - | ...

Removing double-quotes from the output of jq

Instead of this:

curl -s $URL | jq '.message.items[].DOI' | sed 's/"//g'

You can remove the double-quotes by using the --raw-output flag:

curl -s "$URL" | jq -r '.message.items[].DOI'

-r is a shortcut for --raw-output.
Notice also, once again, that I added the necessary double-quotes around $URL.

Redirecting multiple statements

This kind of repetition quickly becomes annoying:

curl -s $URL >> $BIBTEX_FILE
echo >> $BIBTEX_FILE
echo >> $BIBTEX_FILE

You can dispense with that using grouping:

{
    curl -s "$URL"
    echo
    echo
} >> "$BIBTEX_FILE"


Should a User class only contain attributes and no methods apart from getters/setters?

If you have the feeling your classes are too big, you are usually right. Of course there are always different approaches how you could split classes and your idea seems to be reasonable.

So you will have some plain Value Objects (the User), some UserRepository class for getting/updating the data in the database and some kind of UserAccessCheck/PermissionManager/... class for checking the actual user rights.

In case you store your permission also in the database, you can of course extract a PermissionRepository to collect all the SQL statements in one location and don't mix your level of abstractions.

To sum this up, the decision is up to you. A class with 4 properties, some Getters and 4 can...()-methods might be suitable in one scenario and splitting it up into 5 classes might be suitable in an other scenario. In general "good" (tm) developer tend to make there code more general/abstract than necessary and wasting there time or there clients money in premature optimization. "Bad" (tm) developer will never feel the need to split a class. Find the right way in between.


Simple blog using react redux react-router

Looks good after a quick skim. Just one point. I think this project could benefit from following the Container Component pattern so that the markup components don't directly depend on redux and are reusable.

Read more at https://medium.com/@learnreact/container-components-c0e67432e005


Compare Collection with the information in DB using EF and LINQ

Several points:

Write your code against abstractions. Collection is a specific implementation.

You don't need newThisWeekContracts to be specifically a Collection. I'd take in any IEnumerable<Contract> instead.
By returning a Collection, the caller can add to it, or remove from it, which probably isn't the intended behavior. I'd return an IEnumerable<Contract>, or, if adding/removing is ok, I'd return an IList<Contract> or <ICollection<Contract> (i.e. an abstraction, not a specific implementation).

I like the descriptive naming, casing is correct and all, but the names read a little bit awkward still.

It looks like the number of queries can be reduced, haven't profiled this but I would think it consumes fewer resources; the main thing is combining .Where() with .Any() and !.Any() as needed:

public IEnumerable<Contract> GiveContractsThatWereNotSent(IEnumerable<Contract> newContracts)
{
    using (var entities = new AccountingEntities())
    {
        var sentContracts =
                   entities.Tbl_SentProtocol
                           .Where(sent =>
                                  newContracts.Any(contract =>
                                                   sent.CONTRACT_NO == contract.ContractNo
                                                && sent.CONTRACT_NO_ALT == contract.ContractNoAlt))
                           .ToList();

    }

    // ...
}

That gives you sent contracts (/ contractsWereSent), but that's not what you're after. Now you need to return the contracts in newContracts (/ newThisWeekContracts) that are not in sentContacts.

What you have here:

foreach (Contract contract in contractsWereSent)
{
    newThisWeekContracts.Remove(contract);
}

Involves calling EqualityComparer<T>.Default on each contract, which verifies whether Contract implements IEquatable<T>, otherwise uses overrides of .Equals and .GetHashCode if Contract overrides them, otherwise uses reference equality... which doesn't sound very neat, since if a contract is "equal" when its ContractNo and ContractNoAlt exists in sendContracts when comparing in Tbl_SentProtocol, then I'd use the same equality comparison when I want to "remove" items from the newContracts.

In fact, I wouldn't remove anything from newContracts. Keep inputs for inputs!

How about this?

IEnumerable<Contract> sentContracts;
using (var entities = new AccountingEntities())
{
    sentContracts = // trying to prevent horizontal scrolling...
        entities.Tbl_SentProtocol
                .Where(sent =>
                       newContracts.Any(contract =>
                                        sent.CONTRACT_NO == contract.ContractNo
                                     && sent.CONTRACT_NO_ALT == contract.ContractNoAlt))
                .ToList();
}

return newContracts.Where(contract => !sentContracts.Any(sent =>
                                        sent.CONTRACT_NO == contract.ContractNo
                                     && sent.CONTRACT_NO_ALT == contract.ContractNoAlt))
                   .ToList();

One more thing, the entities should be named so as to read like normal code - entity type SentContract can be mapped to table tbl_SentProtocol, and properties ContractNumber and ContractAltNumber can map to columns CONTRACT_NO and CONTRACT_NO_ALT ;)


Looping over a bidimensional array and extract data to a new one

You can compact a lot into a single line, but that is most times not the best thing to do in both source code quality and execution efficiency.

const bArray = [['Hello World', 'Hi everybody', 'How are you?'], [{ text: 'Hola Mundo', from: [Object],  raw: '' }, { text: 'Hola a todos',   from: [Object], raw: '' }, { text: 'Cómo estás?',  from: [Object],  raw: '' },]];

const resultArray = bArray[0].reduce((arr, item, i) => (arr.push({en : item, es : bArray[1][i].text}), arr), []);
console.log(resultArray);

However I would do it as follows.

const bArray = [['Hello World', 'Hi everybody', 'How are you?'], [{ text: 'Hola Mundo', from: [Object],  raw: '' }, { text: 'Hola a todos',   from: [Object], raw: '' }, { text: 'Cómo estás?',  from: [Object],  raw: '' },] ];

const result = [], aArr = bArray[0];
var i = 0;
for (const item of bArray[1]) { result.push({es : item.text, en : aArr[i++]}) }

console.log(result);

Which is easier to read and quicker when run.

Expanding it to idiomatic JS style.

const result = [];
let i = 0;
for (const en of bArray[0]) {
    result.push({
        en,
        es : bArray[1][i++].text
    });
}

// or
const result = [];
let i = 0;
for (const item of bArray[1]) {
    result.push({
        es : item.text,
        en : bArray[0][i++]
    });
}


Search string by regex in files and write line of found string

These parameter names are confusing: param and ext.

The step() function suffers from excessive nesting.  I would further subdivide your step() function to create a search_path() function that deals with each candidate file.  Since both of these helper functions aren't really that useful on their own, I would define them both within the main search() function.

You've hard-coded "search-result.txt" twice.  Ideally, it should be parameterized rather than hard-coded at all.  Furthermore, you're reopening it for appending each time you enter a directory, which is problematic because…

Reopening the file handle is wasteful.
You might not even have any search results for that directory.
If you opened it just once in 'w' mode instead of many times in 'a' mode, you wouldn't have to remove the file at all. (Note that removing the file does make a difference, if the file exists and has a second hard-link.)

Also, if all(not filter in path for filter in filters) is inefficient.  As explained in the documentation for [os.path.walk()], you can avoid entering directories in which you have no interest:

  The visit function may modify names to influence the set of directories visited below dirname, e.g. to avoid visiting certain parts of the tree. (The object referred to by names must be modified in place, using del or slice assignment.)

To analyze file extensions, use os.path.splitext().

Idiomatic Python loops rarely need statements like i += 1.  What you want to use is enumerate().

The format string for output.write() is easier to read if spread out into several lines.

import os.path
import re

EXCLUDE_DIRS = ['bin', 'build', 'logback', 'test', 'target']

def search(directory, output_filename='search-result.txt'):
    def search_path(output, path):
        """Output search results for one file"""
        with open(path) as lines:
            print "Read: {}".format(path)
            for i, line in enumerate(lines, 1):
                if re.search(r"(!|$|RUP)\{[^:]*:[^\}]*\}", line):
                    output.write("Path: {0}; \n"
                                 "    Line number: {1}; \n"
                                 "        {2}\n".format(path, i, line))

    def step(output, dirname, names):
        """Filesystem traversal excluding certain directory names,
           calling search_path() for candidate files"""
        names[:] = [entry for entry in names if entry not in EXCLUDE_DIRS]
        for name in names:
            _, ext = os.path.splitext(name)
            if ext.lower() in ('.xml', '.properties', '.java'):
                search_path(output, os.path.join(dirname, name))

    with open(output_filename, 'w') as output:
        os.path.walk(directory, step, output)


Using recursion is generally advised against, as it takes longer that iterating, and can run into what you ran into, a RuntimeError: maximum recursion depth exceeded. Note you can change the maximum recursion depth, but it is generally advised against, and can lead to stack or memory overflows. In this case, you should iterate.

def triangular_number(n):
    i = n
    while True:
        if i == 1:
            return n
        i -= 1
        n += i

(This keeps running in the same function call, reducing the addition factor by one each time.)

Or better yet, use a range (or xrange for Python 2):

def triangular_number(n):
    for i in range(n):  # range(3) is a generator for [0, 1, 2]
        n += i
    return n

Or better yet, use sum:

def triangular_number(n):
    return sum(range(n + 1))

Or, even better, use the formula for triangle numbers.

def triangular_number(n):
    return n * (n + 1) // 2  # Convert to int for Python 2


Integer Log2 implemented using binary search

I was initially skeptical of your benchmarking results because of your testing methodology:

  I test both of the method by sending 1 << n, n from 0 to 31 to them, and repeat for 1000000 times, and count the time separately.

When you're benchmarking code that contains conditional branches, it is generally not a good idea to use a predictable sequence of inputs, since this tends to ensure that branch prediction will be successful, mitigating something that is potentially one of the most significant costs in performance-sensitive code. Unless you're actually going to be using this function in a setting where the inputs (and thus the direction of the branches) are predictable, you run the risk of skewing the benchmark results. And even if the real-world inputs aren't purely random, you're testing here in a tight loop, which improves branch prediction even more.

To verify for myself, I used the outstanding Google Benchmark library. This automates most of the dirty work of creating a good benchmark. In my test harness, I just defined the necessary functions and prepared some arrays of randomly-generated numbers. The random number generation is done "off the clock" so it won't affect the measurement. Despite my earlier admonitions, though, it appears that your findings were valid; here are the results from my machine, using inputs randomly selected from a large array of randomly-generated values:

Benchmark                     Time           CPU Iterations
-----------------------------------------------------------
Log2                         21 ns         21 ns   29866667
Log2New                      10 ns         10 ns   74666667
Log2NewUnrolled               6 ns          6 ns  112000000

(As you can see from my function names, the word you were trying to think of when composing the question is "unroll". You've unrolled (or unwound) the while loop, which attempts to gain execution speed in exchange for code size, primarily by reducing the overhead of the loop itself. In this case, you've completely unwound the loop, allowing it to be eliminated entirely. This is a very common low-level optimization, although the customary caveat is that it significantly bloats the size of the code. That is true here as well, so it rarely makes sense to go to this extreme when optimizing unless the code is going to be called in a tight loop.)

I see essentially the same thing when compiling for 64-bit. Each improvement roughly corresponds to a doubling in overall performance, which is actually pretty impressive. Although it is almost certainly possible to squeeze more speed out of your code by iterative improvements, it will become increasingly difficult to do so. The magnitude of improvement will become a lot less significant, and you'll very quickly hit up against the limitations of writing code in a compiled language, where you can't manually tweak the generated assembly.

I would also advise you to consider whether it is really necessary. The benchmarks above suggest that on a mobile Haswell processor, you can compute the base-2 logarithm of in ~6 nanoseconds. Do you really need an implementation that is faster than that? Is it really worth the time it takes to develop one, test it, and maintain it?

Well, let's suppose either that you do need something faster, or perhaps that it's worth the time simply because it's fun. One possible tack is to seek out a way to completely eliminate branches. Rather than doing the shift-and-test-and-maybe-add dance each time, we'll simply do all of the shifts and bitwise-OR the results together. Then, the final answer is obtained by doing a population count (i.e., computing the Hamming weight). The code looks like this:

unsigned int Log2Fast(unsigned int N)
{
   N |= (N >> 1);
   N |= (N >> 2);
   N |= (N >> 4);
   N |= (N >> 8);
   N |= (N >> 16);
   return (PopCount(N) - 1);
}

The nice thing about a population count is that there are several highly-efficient ways to do it. The accepted answer to the linked question shows one possibility, a clever bit-twiddling trick that counts in parallel, also shown on Sean Eron Anderson's Bit-Twiddling Hacks page. This is a good general-purpose implementation. If you have a processor that supports it, you can use the POPCNT instruction (available on Intel Nehalem, AMD Barcelona, and later generations). On MSVC, the __popcnt intrinsic allows you to force this instruction to be emitted.

This gets compiled to beautiful, efficient, completely branchless code:

Log2Fast PROC
    mov ecx, DWORD PTR [N]

    mov    eax, ecx       // N |= (N >> 1)
    shr    eax, 1
    or     ecx, eax

    mov    eax, ecx       // N |= (N >> 2)
    shr    eax, 2
    or     ecx, eax

    mov    eax, ecx       // N |= (N >> 4)
    shr    eax, 4
    or     ecx, eax

    mov    eax, ecx       // N |= (N >> 8)
    shr    eax, 8
    or     ecx, eax

    mov    eax, ecx       // N |= (N >> 16)
    shr    eax, 16
    or     eax, ecx

    popcnt eax, eax       // return (PopCount(N) - 1)
    dec    eax
    ret    4
Log2Fast ENDP

Benchmark                            Time           CPU Iterations
------------------------------------------------------------------
Log2                                21 ns         20 ns   34461538
Log2New                             10 ns         10 ns   64000000
Log2NewUnrolled                      6 ns          6 ns  112000000
Log2Fast                             5 ns          5 ns   89600000
Log2Fast_Intrinsic                   4 ns          4 ns  179200000

Notice that the POPCNT instruction (the _Intrinsic variant shown here) is slightly faster than the hand-optimized bit-twiddling code. In fact, this single snapshot of the results is a bit of a lie. Log2Fast takes anywhere from 5–8 ns, varying slightly each time I run the benchmark. The version that uses the POPCNT instruction is consistently fast. If you can't guarantee that your target system supports this instruction, this implementation may not be any better than what you already have. It almost certainly would not be worth it except in a tight loop, when all of the required code is guaranteed to be hot in the cache. The POPCNT version, on the other hand, is actually shorter than your previous implementation, and that, combined with its lack of conditional branches, would make it a better general-case algorithm and possibly faster.

Can we do even better? Maybe. It's extremely hard to tell at this point, because our performance is already so good that the benchmark has virtually reached its limits. The performance differences we'll see will be almost exclusively due to noise. You'd say we need to improve our benchmark, but I'd say that we need to stop optimizing because we're done!

Some people have proposed an approach that uses a look-up table. The look-up table is implemented as an array, filled statically and compiled directly into the executable, with the intention of saving us from having to do expensive computations at runtime, since we can just index into the array and retrieve the precomputed value. The same solution also appears on the previously-linked Bit Twiddling Hacks page. What you'll notice, though, is that the look-up table is only being used to do the population count. Specifically, the look-up table contains a DeBruijn sequence, which is a well-known way to speed up various bit-counting operations, including finding the MSB, finding the LSB, and, of course, finding the total number of set bits.

We cannot reasonably use a look-up table for the shifting operations, because it would be ginormous. And, unfortunately, the population-count code we have is already so fast that it cannot be sped up with a look-up table. This is actually so interesting (and counter-intuitive) that it warrants a bit of further commentary. I tested this extensively a while back when I needed to find the position of the least-significant set bit (as part of an optimized implementation for strlen). I assumed that a look-up table would be the fastest solution, but it wasn't. Even as far back as a Pentium III, it turned out to be faster (or at least equally as fast) to simply compute the value at runtime. Sometimes, modern processors are like this—they are so fast, that it can be faster to recompute something than to store it and/or look it up. It is also a good demonstration of the fact that (micro-)optimization is often counter-intuitive, and can only be done correctly with the aid of a good benchmark test case!

I know I already said that we're pushing the limits of performance and that the code is already fast enough, but maybe there is a way to push it just a little bit faster? Or at least, maybe we can gain some style points for a truly efficient algorithm!

Let's stop and think for a moment about what we're actually trying to do. What is the log base-2 of a number? Well, it is the binary logarithm—the power to which you must raise 2 in order to obtain that number. The lightbulb might have already flashed on here, after seeing that word "binary". Computers work in binary. More specifically, numbers are stored using a binary representation. That's why your bit-shifting algorithm worked. Since binary is fundamentally based on log2, it turns out that the position of the most-significant set bit is the same as the binary logarithm of the represented value. For example, consider the number 21658123. Its binary logarithm is 24, and its binary representation is:

0001 0100 1010 0111 1010 0000 1011
↑  ↑                             ↑
|  └————— bit 24                 |
bit 31                           bit 0

The index of the first set bit, when searching from most-significant bit (MSB) to least-significant bit (LSB), is 24—exactly the same as the binary logarithm. This hints at an exceptionally simple algorithm (at least conceptually): scan through the binary representation of the number looking for the most significant set bit! As luck would have it, there is an instruction on x86 to do precisely what we want to do, and it's been available since the 386 way back in 1986. That is the BSR instruction (Bit Scan Reverse), usable in MSVC via the _BitScanReverse intrinsic and on Gnu compilers (i.e., GCC and Clang) via the __builtin_clz intrinsic (although you'll need to XOR the result with 32). And even if you're not targeting the x86, the intrinsic will likely still work for you, causing the compiler to use an architecture-provided instruction if available, or emit code to generate the equivalent result.

Here's our updated function:

unsigned int Log2_ViaBSR(unsigned int value)
{
    unsigned long result;
    _BitScanReverse(&result, static_cast<unsigned long>(value));
    return result;
}

(Yes, code that should be a single line looks a little bit bloated here because MSVC's _BitScanReverse intrinsic works only with DWORD values, which is a typedef for unsigned long, not unsigned int, so although on Windows they are both 32-bit types, they are nevertheless different types according to the language standard, so you need to declare and use an additional temporary for the output, instead of simply reusing the input parameter. Fortunately, this does not affect the object code generated by the compiler. Note, also, that the intrinsic returns a Boolean value indicating whether it was successful. This allows you to handle the case where the input is 0 and the result is undefined—see "caveats" below.)

And the updated leaderboard:

Benchmark                            Time           CPU Iterations
------------------------------------------------------------------
Log2                                22 ns         21 ns   32000000
Log2New                             10 ns         10 ns   64000000
Log2NewUnrolled                      6 ns          6 ns  112000000
Log2Fast                             7 ns          6 ns   89600000
Log2Fast_Intrinsic                   4 ns          4 ns  186666667
Log2_ViaBSR                          2 ns          2 ns  298666667

Stop and think about this for a second. We went from an O(log n) algorithm to what is effectively an O(1) algorithm, just by thinking about the problem in a different way, and figuring out how we can leverage the computer's internal binary representation to our advantage. It reminds me of a lesson straight out of Michael Abrash's Zen of Assembly Language. We now have the most efficient algorithm and have earned those style points!

Now, there are a couple of caveats. First off, log2(0) is mathematically undefined, so you have to decide how you want to handle that. I've simply ignored it in all of the code I've written, making it undefined there as well. The BSR instruction and its corresponding intrinsics take the same tack, formally defining the result as "undefined" when the input is 0. And although there is actually a lot more that I could say about this (including possible workarounds for "undefined" inputs, inefficient code generation when this intrinsic is used in MSVC, the similar LZCNT instruction introduced on Intel Haswell, etc.), I probably shouldn't make this answer any longer. Instead, I'll refer you to Peter Cordes's recent answer on the subject, and my comments below it.


Getting angle between all points in array

Mathematically, if you have the angle between \$ A(x_1, y_1) \$ and \$ B(x_2, y_2) \$, given as:

$$ \theta = \tan^{-1}{\dfrac{y_2 - y_1}{x_2 - x_1}} \tag{in degrees} $$

then, the angle between \$ B \$ and \$ A \$ would be:

$$ \phi = 180° + \theta \mod {360°} $$

The \$ \mod{360} \$ is simply there if you want results in the interval \$ [0, 360) \$.

With the above, you'll only need to calculate angles between 2 points once, halving the number of calculations performed.


Getting data from the server via JSON callback and parsing the data to HTML

The code isn't bad. I think your taking the wrong approach though. Rendering HTML from JavaScript is ugly and as you mentioned, hard to maintain. I'd recommend looking into a client side templating solution such as Handlebars, Mustache, Dust, etc..

This will allow you to write templates rather than appending html to a variable. For example, in handlebars you could do something like:

<table class="table text-left" width="100">
    {{#each eventsData}}
       <tr....
    {{/each}}
</table>

Handlebars will then take the template and data and give you your HTML, which you can then insert into another element.


Use an Executor
Maintaining a work queue and a thread pool are problems that an executor tackles:

This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads.

The use of Futures also helps you impose time constraints and handle exceptions thrown during execution.
(Note that you'll typically want to use ExecutorService or CompletionService as Executor is a minimalistic interface.)
To paraphrase your example:
class IncrediblyLongRunningTask implements Callable<Long> {
  @Override
  public Long call() throws Exception {
    // ...
  }
}

public void compute() throws InterruptedException {
  final ExecutorService service = Executors.newFixedThreadPool(50);
  final List<IncrediblyLongRunningTask> tasks = new ArrayList<>();
  for ( int i = 0; i < /*...*/; i++ ) {
    task.add(new IncrediblyLongRunningTask());
  }
  final List<Future<Long>> futures = service.invokeAll(tasks); // returns when all done
  service.shutdown();
  for ( final Future<Long> future : futures ) {
    // ...
  }
}


Is this a good way for Controller to interact with Model ? (MVC)

A lot of MVC frameworks do the datamapping in the same class (usually with static methods).  I would also avoid creating hard links between controllers and models (like having each model property as a parameter in the class constructor).  Something like this is a little more elegant, IMO:

<?php

// Model
class Member
{
    public static function forge(array $data = array())
    {
        return new static($data);
    }

    public function __construct(array $data = array())
    {
        foreach ($data as $k => $v)
        {
            // consider checking here for expected properties,
            // sanitizing input, etc.
            $this->$k = $v;
        }
    }

    public function save()
    {
        // If primary key exists, run DB update query
        // Otherwise, run insert query

        // Return success/failure information (and/or throw exceptions)
    }
}

// Controller action
$member = Member::forge($form->get_sanitized_postdata());
$member->save();


You may not define a free message, but I think this may be a solution:

module LogAround
  # log at begin and end of a given block
  # with a mesage and the given params
  def log_around( method_to_log )
    alias_method "_orig_#{method_to_log}".to_sym, method_to_log

    define_method(method_to_log ){ | *args, &blck |
      start_time = Time.now

      puts "call  #{method_to_log} with args #{args.inspect} #{'and a block' if blck} "
      result = send "_orig_#{method_to_log}".to_sym, *args, &blck

    end_time = Time.now - start_time
    puts "called  #{method_to_log} with args #{args.inspect} - (#{end_time}s)"
    result
    }
  end #self.log_around( method_to_log )
end

class Wrapper

  def test
    puts 'in test'
    sleep 1.2
  end

  def test_with_block
    puts 'in test_with_block'
    yield
  end

  extend LogAround
  log_around :test
  log_around :test_with_block
end

Wrapper.new.test
Wrapper.new.test_with_block { puts 'inside block' }

Remarks:

Rails.logger.info is replaced by puts
I extended, not included LogAround (log_around should be a class method, not an instance method).
not well tested ;)


Your program is quite static,
and as you probably know that's not good.

First I would recommend changing the entire throws, ones, twos, etc logic to a list.

# Lazily initialise it with 6 zeros
throws = [0] * 6

This will now be where we hold ones, twos, etc but not throws or total.

The way you should use it is by indexing it.

if roll == 6:
    throws[5] += 1
elif roll == 5:
    throws[4] += 1
# etc

As you can probably guess, you can just index it with roll - 1.
And that is right! Below is most of your old code in a few lines.

total = 0
throws = [0] * 6
while score < limit and play:
    roll = random.randint(1, 6)
    throws[roll - 1] += 1
    total += roll

Now all there is to look at is your prints.
You can use str() to convert a number to a string.
And so you can automate most of your prints.

for side, amount = enumerate(throws, 1):
    print('Total ' + str(side) + "'s:", amount)

First enumerate will loop through the list, giving you the index and item.
Or in our case side and amount.
The above print looks kinda ugly, and so you can change the print to use str.format.

print('Total {}\'s: {}'.format(side, amount))

This replaces the first {} with the value of side, and the second {} with amount. So if side was 1, and amount was 2 it would display Total 1's: 2.

In summery, your code will look something like this:

import random

if input("Do you want to play, 'Y' or 'N'").upper() == "Y" :
    play = True
else :
    play = False

limit = 50

total = 0
throws = [0] * 6
while score < limit and play:
    roll = random.randint(1, 6)
    throws[roll - 1] += 1
    total += roll

if play :
    print("Total throws : ", sum(throws))
    print("Total : ", total)
    for side, amount in enumerate(throws, 1):
        print('Total {}\'s: {}'.format(side, amount))
else:
    print("Yr los")

To further improve your program I would recommend that you put all the 'play' functionality into a function and make your program work with any sized dice.

def play(limit, size):
    total = 0
    throws = [0] * size
    while score < limit:
        roll = random.randint(1, size)
        throws[roll - 1] += 1
        total += roll

    print("Total throws : ", sum(throws))
    print("Total : ", total)
    for side, amount in enumerate(throws, 1):
        print('Total {}\'s: {}'.format(side, amount))

if input("Do you want to play, 'Y' or 'N'").upper() == "Y" :
    play(50, 6)
    play(500, 20) # Limit = 500, dice size = 20
else:
    print("Yr los")


As @Graipher suggested, why bother do this yourself when Python's builtins could give you the answer on a golden plate?

from collections import Counter

def are_anagrams(str1, str2):
    """Return True if str1 and str2 are anagrams and False otherwise."""
    return Counter(str1) == Counter(str2)

Some examples:

are_anagrams('123', '321')
True
are_anagrams('', '')
True
are_anagrams('aabbcc', 'bacac')
False

And that's it. Furthermore it's \$O(n)\$ as you wanted.

And don't think it's something hard to grasp underneath, it's basically just a dictionary with its items as keys and counts as values.

Regarding your code, there are a few style issues that I'd like to point out:

avoid useless/obvious comments like # automatic failure
use 4 spaces per indentation level. (always - not two, not one, not 10. Always 4)
there should be one space after the comma (def are_anagrams(s1, s2):)
don't forget the dot at the end of the docstring (OCD, sorry)
you should always put a space after #

Instead of doing this:

for key in d:
    if d[key]:
        ...

You can do (look also for iteritems() for other python versions):

for key, value in d.items():
    if value:
        ...

To iterate over a string's chars it's recommended to use Python's builtin enumerate (instead of that while) like this:

for index, char in enumerate('test'):
    print('char: {}; index: {}'.format(char, index))

char: t; index: 0
char: e; index: 1
char: s; index: 2
char: t; index: 3


Multiple object instantiation prevention

Using the check if (!$this->SessionCustomer) is not unusual even if a bit clunky. I would still be more explicit about it and use if ($this->SessionCustomer === null). The private $SessionCustomer; member will be initiated to null.

More generally however, what you are using here is called an anti-pattern. PHP Singletons are almost universally considered an anti-pattern. Singleton really is not something you should be using, as it's really unnecessary, what you really want is Dependency Injection.

When you want to use a single class instance during the lifetime of an object, you simply request the \Session\Customer type in your object's constructor, and use a Dependency Injection Container to make sure that the same instance is passed to all the instances of the JobController class:

class JobController
{
    private $sessionCustomer;
    public function __construct(\Session\Customer $sessionCustomer)
    {
        $this->sessionCustomer = $sessionCustomer;
    }
    public function saveJobAction()
    {
        // just use the private property
        if (empty($this->sessionCustomer->offsetGet('customer_id'))) {
            // do stuff
        }
    }
}

At this point, I would just like to comment that otherwise, there is really no reason to use OOP if you are not using constructor injection and just globally access things with a service locator (which is also a very bad pattern of its own, but that's for another topic). That code could be procedural.

Back to the topic: defining your requirements in the constructor allows for the calling code to decide that instance to pass to the JobController's constructor, reuse that instance, pass in a mock instance (because hopefully, you would be testing that class, which may necessitate for you to mock instances).

I generally use Auryn as a Dependency Injection Container, but the usage generally consists on instructing a container to share an instance of a class:

$injector = new \Auryn\Injector;
// this is how you actually use a single instance of a class, through sharing it with a container
$injector->share($sessionCustomer);
$jobController = $injector->make('JobController'); // uses the shared instance


Exception handling and releasing of OracleDB connection

There really isn't too much to say about your posted code.

Answering your specific question:

Yes, the connection will always be released as either your then or your catch method will always run. However, if res.json({data: result.rows}); (or more complex code once you have developed further) throws, your code will try to release the connection twice. This will likely result in an uncaught promise rejection. You can solve this problem a couple different ways.

Use the second callback parameter of the .then method.

con.execute('SELECT * FROM BTO_MDS.AlARMS', {}, { maxRows: 22000 })
    .then(result => {
        con.release();
        res.json({data: result.rows});
    }, ex => {
        con.release();
        res.status(500).json({message: ex.message});
    })

Use async / await and take advantage of the finally in try..catch..finally chain. This solution also has the benefit of avoiding the duplicate code sending error messages. I like this solution the best, but it would probably be even better to have an execute method on your Database class that handles releasing the connection for you.

export let getTest = async (req: Request, res: Response, next: NextFunction) => {
    const db = new Database();

    try {
        const con = await db.getConnection();
        try {
            const result = await con.execute('SELECT * FROM BTO_MDS.AlARMS', {}, { maxRows: 22000 });
            res.json({ data: result.rows });
        } finally {
            con.release();
        }
    } catch (ex) {
        res.status(500).json({ message: ex.message });
    }
};

For the future: Promise.prototype.finally is coming, currently a stage 3 proposal. Proposal. I wouldn't use this just yet.

db.getConnection()
    .then(con => {
        return con.execute('SELECT * FROM BTO_MDS.AlARMS', {}, { maxRows: 22000 })
            .then(result => {
                res.json({ data: result.rows });
            })
            .finally(() => {
                con.release();
            })
    })
    .catch(ex => {
        res.status(500).json({ message: ex.message });
    });

The trick to using promises effectively is to return them whenever possible. The original function can be somewhat simplified by re-throwing the error and returning the connection promise. This doesn't help a ton but it does remove the duplicate res.status(500) line, making it easier to change in the future if necessary.

db.getConnection()
    .then(con => {
        return con.execute('SELECT * FROM BTO_MDS.AlARMS', {}, { maxRows: 22000 })
            .then(result => {
                con.release();
                res.json({ data: result.rows });
            }, ex => {
                con.release();
                throw ex;
            })
    })
    .catch(ex => {
        res.status(500).json({ message: ex.message });
    });


Time calculator for a given speed and file size

It's a very simple little program, however, there's a few comments to make:

All of the code is in main. Of course, for a program of this size, that doesn't really matter too much, however, you should prefer to break things up into self-contained functions where possible. For example, there should be a separate function here to actually do the calculations.
Use the correct data type for what you need. Can time ever be negative here? The answer is no, so I'd prefer to use unsigned over int.
You should be somewhat careful about overflow. Any filesize over 2048MB (2GB) will overflow the size of an int (assuming a 4 byte int - in actuality, an int is only technically required to be at least 2 bytes). Using an unsigned will change this to 4GB, however, if you expect any filesizes larger than that, you should look at another datatype (std::uint64_t perhaps).
Magic numbers. It's not so bad when dealing with time, because it's generally fairly obvious here, but numbers like 86400 shouldn't be shown as-is. They should be a named constant, such as const unsigned seconds_in_day = 86400.

I'd suggest breaking this up into a main function and a required_time(unsigned transmission_rate, unsigned file_size) function.


Euler Project #3 Largest prime factor timeout

It seems to me your second code example is wrong. You divide out only one prime factor and moving on testing for divisibility. If you enter, say: 8, it finds 2, divides it out, which gives 4, and will find 4 as largest prime that divides 8.

You have a lot of redundant tests, stepping b by one.

Consider this:
Write any positive number n as n = m + 6*q (q may be 0). Except for the prime numbers 2 and 3: If m is divisible by 2, then so is n (because 6 is divisible by 2). If m is divisible by 3, then so is n (again, because 6 is divisible by 3). The only chances for n to be prime is, if m is 1 or 5. Not all of those numbers are prime, but if it is prime, it will be 1 or 5 modulo 6.

That will add a few lines of code, to explicitly test for primes 2 and 3. But after that, it should speed up your algorithm. Just remember to divide out all powers of a prime before moving on. A single test could look like this:

n = int(input())
num = n
max = 1

if n % 2 == 0:
    max = 2
    while n % 2 == 0:
        n //= 2

if n % 3 == 0:
    max = 3
    while n % 3 == 0:
        n //= 3

b = 5
inc = 2

while n != 1:
    if n % b==0:
        max = b
        while n % b == 0:
            n //= b

    b += inc
    if inc == 2:
        inc = 4
    else:
        inc = 2


Is this use of ConcurrentDictionary truly thread safe?

If you just used your original code (TryGetValue followed by an indexer set) with ConcurrentDictionary, then that wouldn't be thread-safe.

But you're using the AddOrUpdate method instead, which is guaranteed to be thread-safe (i.e. atomic), so this use is thread-safe.

One other nitpick:

Directory.EnumerateFiles(dirPath, wildCard)
|> Array.ofSeq

If you don't actually want seq, but an array, Directory has a method just for that: Directory.GetFiles.


Inheritance and small number of parameters

So Uncle Bob suggests that no more than 3 arguments should a function get, right?

No. The guy you're referring to suggests that more than two arguments to a function which takes "variable arguments" is bad.

The key to understanding lies in distinguishing between a single argument (int count) and argument pack (Integer ... args). The function which takes the latter is what is called variable number arguments function, compared to fixed number argument function. The three dots here are actually part of the C++ syntax going back to C called ellipsis. Google variadic to impress people)

So if Student ctor takes 4 args (or 10 args) its ok. But if amongst the args Student Ctor takes is an argument pack, then don't overcomplicate things, by passing too many single arguments. Separate the handling of the argument packs (yes, there can be more than one pack) from the rest of them.


Simple Deferred / Promise pattern in JavaScript

A few things caught my eye:

You can call resolve and later call reject too - or the other way around, or call either one multiple times. It should only allow the first resolve/reject call to have an effect.
status might as well be a string (pending, resolved, rejected) which obviate the need for a comment explaining the integer values, and would improve readability
The if(f) check in execute should probably be a full if(typeof f === 'function') check; lots of values are truthy without being functions. You could also do this check in done/fail and simply ignore/complain about non-function arguments.
There's some duplication between done/fail and resolve/reject.

For that last one, if the status becomes a string, it's also relative easy use that as a key for organizing the callbacks and arguments.

function defer() {
  var currentState = 'pending',
      callbacks    = { resolved: [], rejected: [] },
      args         = []; // only need 1 args array

  function execute(state) {
    var cb;
    while(callbacks[state].length) {
      cb = callbacks[state].shift();
      if( typeof cb === 'function' ) cb.apply(this, args);
    }
  }

  // generic function factory for done/fail functions
  function hook(state) {
    return function (cb) {
      callbacks[state].push(cb);
      if(currentState === state) execute(state);
    }
  }

  // generic function factory for resolve/reject functions
  function complete(state) {
    return function () {
      if(currentState !== 'pending') return;
      args = Array.prototype.slice.call(arguments, 0);
      currentState = state;
      execute(state);
    }
  }

  return {
    promise: function () {
      return { done: hook('resolved'), fail: hook('rejected') };
    },
    resolve: complete('resolved'),
    reject:  complete('rejected')
  };
}

You may want to add then, always and isPending (or just state) functions. And once you've resolved or rejected, you might as well get rid of the callbacks you're not going to ever use (i.e. if resolved, clear out the reject-callbacks,and vice-versa).

Lastly, if you want to emulate jQuery, make it chainable, so you can call x.done(...).fail(...).fail(...).always(...) etc.


Conditional aggregate whilst constructing array

First of all you can simplify your Code to:

vm.GroupedData =
   times.Select(time =>
      new { Ticks = time.Start.ToInstant().Ticks,
            Aggregate = results.Data
             .Where(data => time.Intersects(data.Date))
             .Select(data => data == null ? 0m : decimal.Parse(data.Value))
             .DefaultIfEmpty()
             .Max()
             //.Min()
             //.Average()
   });

1.) Remove the Select(v => v)

The Select doesn't actually do anythin in your case, you will get the same result without it. Select is used to project the single elements in your result into another format. E.g. get only a list of the Values insted of the whole object.

2.) Remove the DefaultIfEmpty()

With the DefaultIfEmpty you get a List containing only one "null" element. which would produce the same result as calling Max, Min or Average on an empty list.

3.) Transform the Results before using aggregates

Transform your result list to a list of all the values as decimal with a Select instead of doing this in each of the subfunctions.

4.) Give x and i meaningful Names

5.) Use annonymous Type instead of object array or even better create own type for the tick-aggregate pair

To your actual question: Instead of calculating the Aggregate  you could store the IEnumerable in your result object and then do a second select on that result with your desired aggregate function. As long as you store the query as IEnumerable the query shouldn't be executed until you want to access the actual values of the result.

var myDataRowsPerTime = times.Select(time =>
      new { Tick = time.Start.ToInstant().Ticks,
            DataRow = results.Data
             .Where(data => time.Intersects(data.Date))
             .Select(data => data == null ? 0m : decimal.Parse(data.Value))
             .DefaultIfEmpty()
   });

switch(aggregationMethod)
{
    case AggregationMethod.Avg:
        vm.Groupdata = myDataRowsPerTime.Select(item =>
             new { Tick = item.Tick, Aggregate = item.DataRow.Avg() });
        break;
   case AggregationMethod.Max:
         ...

You should define a own class for the last result, there maybe a problem with accessing the Data of the annonymous Type in the viewmodel. The viewmodel doesn't know the structure of this annonymous type.


Reading and writing an unknown character into an appropriately named file

This is only partly an answer, intended more as a thought exercise about what you might do. I provide a couple examples that you might want to pick and choose parts of, but you probably will not want to just grab the whole. So let's dive in.

What would benefit from this being more general? This seems like a fairly small and specific task. I could imagine parameterizing the input, the list of tags, the mapping from tag name to file name, or the handling once a matched tag is found. Let's examine doing all at once:

import urlparse
def parse_queries(input, get_filename, handle, tags={'blog', 'p', ...}):
    for line in input:
        qsl = urlparse.parse_qsl(urlparse.urlparse(line).query)
        if not qsl:
            print repr(line), "does not yield query"
            continue
        for key, value in qsl:
            if key in tags:
                handle(get_filename(tag), value)
            else:
                print key, "not in tags."

def dot_text(tag):
    return tag + '_file.txt'

def append_to_file(filename, value):
    with open(filename, 'a') as output_file:
        output_file.write(value)

with open("filename") as input:
    parse_queries(input, get_filename=dot_text, handle=append_to_file)

Do any of these help more than they harm readability? Does extracting the small methods like dot_text and append_to_file offer useful chunks of reusable code? I'm not sure myself. It certainly makes the call harder, but providing defaults is easy enough. Thinking it through should raise other questions, such as whether get_filename should be part of parse_queries, or part of handler.

Perhaps it's the line processing which could be parameterized:

def parse_file(input_file, parse):
    ...
    for line in input:
        for key, value in parse(line):
            if key in tags:
                ...

def extract_query_params(line):
    qsl = urlparse.parse_qsl(urlparse.urlparse(line).query)
    if not qsl:
        print repr(line), "does not yield query"
    return parsed_url

parse_file("filename", extract_query_params)

But again ask whether this helps generality more than it harms readability. I'd address other small issues first:

comparing a list to 0 (parsed_url > 0) doesn't have much meaning.
output_file.write(value) seems unlikely to insert newlines, so your values will blur together.
the name tags has a lot of implied meaning in an HTML context, so your use here in an HTTP context could be confusing.
indentation, at least here, your with statement is at the same level as its contained for loop.
unit tests; how better to verify whether this does what you want? Of course if you do want to test this, you may find that parameterizing things makes this measurably easier. Or maybe you really need to look at the resulting files.


Multi producer/consumer queue (without Boost) in C++11

Your size is not mutating. So should declare it const.
std::size_t size() const
     //            ^^^^^

Still in the size() I don't see any in point in lock on such short term. As soon as the function exits the value can be mutated and will thus be out of date (so if you get a value as another thread is mutating it you will be in no better state).
// There is no point in this function.
// It has no intrinsic value alone but can only be used within a set of commands.
// But since you lock per call, if you make multiple calls another thread can
// mutate the object and make this value stale.
{
    std::lock_guard<std::mutex> lock(_mutex);
    return _q.size();
}

Not sure your timed push will work as expected:
if (_item_popped_cond.wait_for(ul, timeout) == std::cv_status::timeout || _q.size() >= _max_size)

Say you set a timeout of 10 seconds. Now another threads pops at 1 second and signals the condition variable. This can potentially release this thread (this does not guarantee your thread will require the lock before another third thread manages to call push). This means that your size would still be max (when you eventually reacquire the lock) and thus you exit with false after only one second.
You need to use the other version of wait_for() that has a test function.
if (!_item_popped_cond.wait_for(ul, timeout, [&q,&_max_size](){return _q.size() < _max_size;})) {
    return false;
}

Or put it inside a loop:
while(_q.size() >= _max_size) {
    if (_item_popped_cond.wait_for(ul, timeout) == std::cv_status::timeout) {
        return false;
    }
    // probably need to adjust timeout here.
}

Don't see the need to test before notifying after a push. Also why are you notifying all threads, why not just notify one (there is only one new item available).
if (_q.size() <= 1)                 // Why test. Always notify
    _item_pushed_cond.notify_all(); // notify_one();

All the same comments apply to pop.
I don't like the name of your identifier names. Technically nothing wrong with them. But there are so many situations where identifiers with an initial underscore is incorrect that I avoid them. And most C++ code follows the same rules. What are the rules about using an underscore in a C++ identifier?
Note: The std lib with the compiler usually uses underscores but they are specifically allowed to (as they are part of the implementation). This is where most beginners pick up this hobbit; But as you are writing code that is not part of the implementation the same rules do not appy and thus this is not a reason to follow that convention.
Expansion of my point on locking above
The only way to use the lock is:
std::size_t  count = que.size();   // locks getting size.
for(int loop = 0;loop < count; ++loop)
{
    que.pop();                     // locks while popping.
}

I see very little use for the size() method in this context. Between the call to the size() method and other methods your object could have been mutated thus making your results stale. Any function that queries state like this is not returning you anything useful because it can immediately by out of date as soon as the lock is released.
So what should you do?
Where you have operations that can be combined together into a larger piece of work. What you normally do is not provide the interface directly. You provide a way to lock the object that returns an interface that you can use (because while you hold the interface object you hold the lock).
class blocking_queue
{
      friend class blocking_queue_interface;
      // Private interface can not be used directly.
      std::size_t p_size() const;
      bool p_push(T& item, const std::chrono::milliseconds& timeout, std::lock_guard<std::mutex>& lock);
      bool p_pop(T& item, const std::chrono::milliseconds& timeout, std::lock_guard<std::mutex>& lock);

      ......
      public:
          // Public interface
          // Just gets lock and calls private interface.
          // Should only be used as a last resort.
          // Personally I would not provide this interface at all.
          std::size_t size() const
          {
              std::lock_guard<std::mutex> lock(_mutex);
              return p_size();
          }
          bool p_push(T& item, const std::chrono::milliseconds& timeout)
          {
              std::lock_guard<std::mutex> lock(_mutex);
              return p_push(item, timeout, lock);
          }
          bool p_pop(T& item, const std::chrono::milliseconds& timeout)
          {
              std::lock_guard<std::mutex> lock(_mutex);
              return p_pop(item, timeout, lock);
          }
 };

 // A locked interface.
 // You can acquire the lock and make multiple calls without
 // the data becoming stale between calls.
 class blocking_queue_interface
 {
     blocking_queue              queue;
     std::lock_guard<std::mutex> lock;

     blocking_queue_interface(blocking_queue& q): queue(q), lock(queue._mutex) {}
     ~blocking_queue_interface()                                               {}
     // delete remove all copy and assignment operators.

      // Calls the private version of these methods
      // as it has already aquired the lock
      std::size_t size() const                                     {return queue.p_size());
      bool push(T& item, const std::chrono::milliseconds& timeout) {return queue.p_push(item, timeout, lock);}
      bool pop(T& item, const std::chrono::milliseconds& timeout)  {return queue.p_pop(item, timeout, lock);}
 };


A fixed max size container class containing unique elements with functions like push_back and pop_back and is iterate-able

Duplicate value storage:

One disadvantage of your approach is that it stores a duplicate of each value inserted. The cost can become prohibitive for large objects, such as class instances stored by value.

A possible approach to avoid the duplicate would be just doing a linear search over the vector every time a new insertion takes place. For small arrays, this is usually quite fast.

Another possible implementation would be to keep the vector always sorted, then a fast binary search could be performed before insertions to ensure uniqueness.

Proper way of testing set/map insertion:

This code doesn't seem correct:

    bool success = true;
    if(m_uset.insert(x)) m_vec.push_back(x);
    else success = false;
    return success;

The insert method of sets and maps of the Standard Library will return you a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place (from here).

So the correct way to test if the insertion was successful would be:

if (m_uset.insert(value).second == true)
{
    ...
}

max_size is never checked:

You've stated in the title that the container should have a fixed maximum size, however, you never check to see if the limit size was reached. push_back in a vector will resize the container if its initial capacity is exceeded. Same is true for set::insert.

push() is taking a mutable reference, which can cause confusion:

The signature of bool push(T& x), taking a mutable reference to T, shows the called that this method has the intention or possibility of altering the input parameter. That would be a pretty strange behaviour for a container. When storing some data, you don't want it to be changed by the container. The proper signature here would be to pass the value by const reference:

bool push(const T& x);

That will prevent a copy and will pass a clear message to the caller that the input value is not changed, only stored.

As you polish this interface, you should consider move semantics (C++11), and add a move reference (T&&) overload for push().

empty() is a more idiomatic way of checking for empty containers:

The traditional way of testing if a Standard container is empty is by calling the empty() method, as opposed to if (c.size() > 0).


Global site settings middleware for Slim Framework 3

A couple of general comments:

Please follow the PSR coding standards whenever possible
Add type-hints for all arguments, especially constructor arguments. You're clearly expecting $app to be an object. Add the type-hint
Predeclare properties, because: what PHP calls object overloading (dynamic properties) are all public, and are slower. Relying on them makes it easy to remove/reassign core properties and makes your code buggy the moment you have typos, which you will. Inevitably.
Avoid one-line loops without brackets (foreach ( $this->getSettings()  as $row )). I know they're technically not needed there, but add them. It's a good habit that avoids awful bugs (think: goto fail;)
You're using PDO, which is good. You're using prepared statements, which is excellent, but the way you're using them doesn't really make sense
Your use of PDO is made worse by the fact that you're repeatedly calling getSettings. Each call will query the DB for the same data. Don't do that

So Let's start by looking at the constructor, how I'd rewrite it:

//add use Slim\App;
/**
 * @var PDO
 */
protected $pdo = null;

/**
 * You're not using this, but just in case:
 * @var App
 */
 protected $app = null;
public function __construct(App $app)
{//<-- PSR coding style
    $this->app = $app;
    $this->pdo = $app->getContainer()['pdo'];
    if (!$this->pdo instanceof PDO) {
        throw new \RuntimeException(
            sprintf(
                '%s requires a PDO instance, app did not contain "pdo" key',
                __CLASS__
            )
        );
    }
}

Avoid querying too many times

Your __invoke method calls getSettings several times. Each time, you'll be querying for the exact same data as the last time. I'd rewrite that ASAP:

public function __invoke( $request, $response, $next )
{
    $settings = $this->getSettings();//assign!
    if( $settings ) {
        foreach ($settings as $row) {
            //set all attributes first
            $request->withAttribute(
                $row['setting'],
                $row['value']
            );
        }
        $response = $next($request, $response);//only call next once
    }

    return $response;
  }

Because your class is doubling as a callable instance (hence the __invoke), you might want to try adding type-hints to the __invoke method, too.

About your use of prepared statements:

Prepared statements are what you use when you're going to query the DB, and you want to use values that might be used for injection attacks, or values that, because they contain quotes might simply break the query.
You might also choose to use prepared statements for queries that you're running mutliple times, because prepared statements can be reused.

You're doing neither: you're creating a prepared statement resource, execute it and forget about it. The query you want to execute in fact is hard coded, so there's no risk of injection whatsoever. What I'd do is this:

$stmt = $this->pdo->query('SELECT setting, value, description FROM site_settings');
return $stmt->fetchAll(PDO::FETCH_ASSOC);

Nothing more. If an exception is thrown here, that should cause the app to grind to a halt: The query to fetch the site settings failed. There's nothing your app can do that would be even remotely sensible. It's a fatal error, so let the exception propagate until a global handler catches it and renders an error page. Don't hush the exception up.

Right now, you're returning false both if a PDOException was thrown, or if there aren't any settings. That's madness. An EXCEPTION signals something EXCEPTIONAL has happened in a bad way. Don't hush it up, sound the alarms! Your app is on fire!

Final nit-pick

Going by the Slim documentation, and because they say their container component is based on pimple, I'd probably use this to get the PDO instance from the container:

$this->pdo = $app->getContainer()->get('pdo');

You could write $app->getContainer()->pdo, too, but I have a profound aversion for the magic __get and __set methods. So much so, then I often implement them to throw exceptions with the sole purpose to disable overloading (dynamic properties):

public function __get($name)
{
    throw new \RuntimeException(
        sprintf(
            'tried to access property non-%s "%s" as public on %s',
            property_exists($this, $name) ? 'public' : 'existent',
            $name,
            get_class($this)
        )
    );
}

public function __set($name, $value)
{
    throw new \RuntimeException(
        sprintf(
            'tried to set property non-%s "%s" to "%s" on %s',
            property_exists($this, $name) ? 'public' : 'existent',
            $name,
            serialize($value),
            get_class($this)
        )
    );
}


How to properly get values from multidimensional object

Minor Changes

Method name reduce suggests a generic API method that would take a predicate and accumulator. Instead, it's very specific in returning a custom array and mapping a string to Date. I would call it getCalendarByMinimumRecommendedTime instead.
Prefer the use of const over let for immutable data: const providerCalendars and const providerRecommended.
The unused index parameter i can be omitted: return data.reduce((acc, cur) => {.