This code is not complete so difficult to give a full review, but here are my thoughts.

Student

Put public methods first

This point is debatable, but I generally think it's better to have public methods before private variables. This is the only thing users of your class should care about, so make it easier to find.

Use variable name forename

forename is a better variable name than firstName, and fits better with surname (as apposed to lastName).

Type alias std::string

I think it would be clearer to type alias std::string for the names, if you make this public, the database class can use this alias to make the map definition clearer too:

using NameType = std::string;

Add missing constructors

Not sure if these were left out intentionally, but a simple forwarding constructor here will suffice:

template <typename T1, typename T2>
Student(T1&& forename, T2&& surname, long studentNumber);

Make fullName a non-member

It's generally preferable to make your class interface as minimal as possible, and you really gain nothing here by having this as a member method, so make it a non-member:

Student::NameType getFullName(const Student& student);

Return fields by const &

You are making a copy on every call to getFirstName and getSurname, better to return a const reference - the caller can always make a copy if needed.

Database

Don't make Database responsible for reading user input

Your remove functions should not read anything from the user, it obscures the interface and purpose of the class. If you need this functionality, put it into a non-member method:

long getStudentNumberToRemoveFromUser();

Consider a better design

I'd say your design is flawed; you shouldn't be removing Student objects by name (not even full name), as you could have duplicates. Presumably the student number is unique, so this should be the only identifier used for removal. Instead you could offer a public method to gain access for student numbers. So you just have:

std::vector<Student> getMatchingStudents(Student::NameType surname forename, Student::NameType surname) const;
bool remove(const Student& student);

Where the return bool indicates if the record was removed.

Consider Boost.Bimap

Boost.Bimap already solves the two way access problem you are having.

Remove shared_ptr

Assuming you don't want to use Boost.Bimap.

There's really no need to use shared_ptr here; Database has complete control over the lifetime of the Student objects. Introducing the shared_ptr only adds code complexity, additional memory consumption, and confusion. Instead you can either store everything by value (completely feasible for just 2000 records), or store values in mapByStudentNumber and store a raw pointer, or std::reference_wrapper<const Student::NameType in mapByName.

Use better variable names

There's some debate about how to best name maps (xToY, ys, xToYMap etc), but I don't like mapByName and mapByStudentNumber. I'd probably go with namesToNumbers and numbersToNames.


1. Style guides

leave two empty lines before each function (when you're not inside of a class)
Python is not C; don't use ;
put a space before and after operands. i>=0 will become i >= 0, s[i]=='.' will become s[i] == '.' and so on.
use the snake_case notation for function names: currencyInIndiaFormat(..) will become currency_in_indian_format(..)
use format() instead of + notation: e.g: print "INR " + currencyInIndiaFormat(n) might be print "INR {}".format(currencyInIndiaFormat(n))
also, I'd recommend you use print('w/e you want here') so that your code can be python 3 compatible.
use 4 spaces for indentation instead of 2.
use augmented assignments where you can: res = res + s[i] can be written as res += s[i]
add docstrings to your functions to describe what their purpose are

If you want to read more about Python style guide, you should start from here.
Preview:
import decimal

def currency_in_indian_format(n):
    """ Convert a number (int / float) into indian formatting style """
    d = decimal.Decimal(str(n))

    if d.as_tuple().exponent < -2:
        s = str(n)
    else:
        s = '{0:.2f}'.format(n)

    l = len(s)
    i = l - 1

    res, flag, k = '', 0, 0
    while i >= 0:
        if flag == 0:
            res += s[i]
            if s[i] == '.':
                flag = 1
        elif flag == 1:
            k += 1
            res += s[i]
            if k == 3 and i - 1 >= 0:
                res += ','
                flag = 2
                k = 0
        else:
            k += 1
            res += s[i]
            if k == 2 and i - 1 >= 0:
                res += ','
                flag = 2
                k = 0
        i -= 1

    return res[::-1]

def main():
    n = 100.52
    print("INR {}".format(currency_in_indian_format(n)))  # INR 100.52
    n = 1000.108
    print("INR {}".format(currency_in_indian_format(n)))  # INR 1,000.108
    n = 1200000
    print("INR {}".format(currency_in_indian_format(n)))  # INR 12,00,000.00

if __name__ == '__main__':
    main()

NOTE: I've also added if __name__ == '__main__'. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
2. Algorithm
As I said in the comments, I would strongly recommend using the existing builtin module locale, which is doing exactly what you want:
Example code (it's working if you have the locale set on your machine - so that would be an ugly constraint):
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_IN.utf8')  # if this doesn't work, you might try as well: locale.setlocale(locale.LC_ALL, '')
'en_IN'
>>> locale.format("%d", 1255000, grouping=True)
'12,55,000'

I'll let others to comment on your code regarding the efficiency of the algorithm you implemented and methods to make it shorter / better.


To-do app, as one monster function and as several smaller functions

Please don't use nt and t as variable names. If you were using them in a small limited context then it wouldn't be much of an issue, but repeatedly using them across multiple lines is going to get confusing. What's wrong with newTask and task?

In the case of var nt = new Task(toDo.value, "No note yet"); it's pretty clear what nt is there, but I'm not even sure if t is a task, or a note on the task, or user input. A clear name makes code more readable, and leaves people guessing at your intentions less.

x in displayArray is even worse. Though it is a limited context, you make it seem as though it accepts arbitrary input (x doesn't specify anything) when it clearly needs something that can have a child appended.

That said I personally like the split up functions a lot more. With individual functions, it's easier to read them and see what the functions do. It's easy for steps to get lost in a big megafunction, but when each step is it's own function you can make everything more explanatory.

However the readability principle applies again. I'm not very familiar with JS, so maybe displayArray makes sense for that, but to me I can't see why a display function is appending something to the HTML. Surely it should be another append function?


Trying to use "this" to refer to a class's instance variable inside a function within the class's method in JavaScript

The "that" solution works well, but you can also bind your function to this :

function UserGoogleMap($mapElement) {
  this.$mapElement = $mapElement;
  this.map = {};
  this.marker = null;
  this.coords = new google.maps.LatLng(25.2697, 55.3095)

  this.initMap = function () {
    google.maps.event.addListener(this.marker, 'dragend', function() {
      console.log(this.marker);
      pos = this.marker.getPosition();
      $('#google-map-info').html("Latitude:" + pos.lat() + " Longitude: " +  pos.lng());
    }.bind(this));
  }
}

There is a way to execute initMap directly :

this.initMap = function () {
  google.maps.event.addListener(this.marker, 'dragend', function() {
    pos = this.marker.getPosition();
      $('#google-map-info').html("Latitude:" + pos.lat() + " Longitude: " +  pos.lng());
    }.bind(this));
    return arguments.callee;
 }();

But arguments.callee is deprecated (due to performance issues), so calling initMap manually is better.


First comment - "Import Statements" - is unnecessary.

I would add few empty lines to make code more readable - ie. before return, for

Document PEP 8 -- Style Guide for Python Code suggest to use UPPER_CASE_NAMES for constant values - WORDS and CHARS you can treat as constant values but ROTATIONS, ENCODED, DECODED, GUESS,GUESSES` are not constant values.

Instead of range(len(..)) in

for index in range(len(text)):
    new_position = ord(text[index]) - (rotations % 26)

you can iterate list

for char in text:
    new_position = ord(char) - (rotations % 26)

There is similar situation in other loop.

for i in range(len(guess)):
    if guess[i] == DECODED[i]:
        response += guess[i]

But here you need i to get DECODED so you can use enumerate()

 for i, char in enumerate(guess):
    if char == DECODED[i]:
        response += char
    else:
        response += " "

You can calculate rotations % 26 only once - before for loop.


With an arrow function I can avoid the var self = this;

mine(input = '') {
    const translatedAnswers = this.constructor._translate(this._defaultAnswers);
    return translatedAnswers.filter(answer => this.constructor._match(input, answer));
}


CarTalk's Homophones Puzzler: A Programmatic Solution

There's an efficiency improvement you could make to are_homophones: As is, you check that all three words are in pron_dict before checking that they're the same. However, it's better practice to catch errors using try blocks rather than trying to prevent them from happening (see this Stack Overflow post). A cleaner/faster way way to write this would be

def are_homophones(pron_dict, word1, word2, word3):
    try:
        return pron_dict[word1] == pron_dict[word2] == pron_dict[word3]
    except KeyError:
        return False

It's also good practice to use with blocks to open files so that Python automatically handles closing the file. With this change, read_dict becomes

def read_dict(file_path):
    pron_dict = {}

    with open(file_path) as fin:
        for line in fin:
            index = line.find(' ')  # e.g. "AA  EY2 EY1"
            word = line[:index]
            pron = line[index+2:]
            pron_dict[word] = pron

    return pron_dict


Project Euler # 74 Digit factorial chains in Python

A few comments.

First, your algorithm for computing the length of a chain is quadratic, because you convert your list to a set at each iteration. Second, there's a lot going on in get_factorial_sequence_length. I'd break the function up. You essentially have three parts: 1. Generate the elements of the sequence; 2: determine when to stop generating the sequence; 3. Determine the length of the non-repeating section (and memoize the length for all the seen numbers). The first part should be its own generator.

def generate_sequence(factorials, num):
    while True:
        yield num
        num = sum(factorials[digit] for digit in str(num)

Now get_factorial_sequence_length can look like:

def get_factorial_sequence_length(number, factorials, lengths):
    chain = []
    seen = set()
    for num in generate_sequence(factorials, number):
        if num in lengths:
            memoize_lengths_found(chain, num, lengths)
            return lengths[num] + len(chain)
        if num in seen:
            memoize_lengths_new(chain, num, lengths)
            return lengths[num]
        chain.append(num)
        seen.add(num)

memoize_lengths_found and memoize_lengths_new could use some work on the names, and I leave the implementations as an exercise to the reader.


Defining an OOP structure for a Student class in NodeJS

In modern versions of node.js (v6.0 or v4.x in strict mode) or when using an ES6 transpiler, you can use the ES6 class keyword:

class Student {
    constructor(name, age, id) {
        // always initialize all instance properties
        this.name = name;
        this.age = age;
        this.id = id;
    }
    getStudentName() {
        return this.name;
    }
    getStudentAge() {
        return this.age;
    }
    getStudentId() {
        return this.id;
    }
}

This creates the same underlying .prototype methods as your original code, but is obviously a bit cleaner syntax.  Usage of the Student constructor and methods is identical.

Note: You don't need accessor methods for these properties.  They are directly accessible as properties of the object.

If you don't want them directly accessible as properties (e.g. you only want methods to be able to access them), you can do this:

function Student(name, age, id) {
   this.getStudentName = function() {
       return name;
   }
   this.getStudentAge = function() {
       return age;
   }
   this.getStudentID = function() {
       return id;
   }
}

This "hides" the name, age and id instance variables in a constructor closure so they are only accessible to methods defined within the constructor.  This does not use the prototype for methods and may (depending upon JS implementation) consume a bit more memory per object, but does give you property privacy.


Classic "100 doors" simulation in Clojure

My philosophy is "A fundamentally mutable problem requires a fundamentally mutable solution":

(def N 100)
(def bound (inc N))

(defn calc-doors []
  (verify (pos? N))
  (let [bound (inc N)
        doors (long-array bound 0) ]
    (doseq [step (range 1 bound)
            idx (range 0 bound step)]
      (aset-long doors idx
        (inc (aget doors idx))) )
     (vec doors)))

(dotest
  (let [doors (time (calc-doors))]
    (dotimes [i bound]
      (println (format "%5d %5d" i (nth doors i))))))

with result:

----------------------------------
   Clojure 1.9.0    Java 10.0.1
----------------------------------

Testing tst.demo.core
"Elapsed time: 0.498 msecs"

    0   100
    1     1
    2     2
    3     2
    4     3
    5     2
    6     4
    7     2
    8     4
    9     3
   10     4
   11     2
   12     6
   13     2
   14     4
   15     4
   16     5
   17     2
   18     6
   19     2
   20     6
   21     4
   22     4
   23     2
   24     8
   25     3
   26     4
   27     4
   28     6
   29     2
   30     8

Just noticed that you want the first N open doors:

(defn door-open?
  "Returns true if `door-idx` is open"
  [door-idx]
  (assert (pos? door-idx))
  (let [hits (atom 0)]
    (doseq [step (range 1 (inc door-idx))]
      (when (zero? (rem door-idx step))
        (swap! hits inc)))
    (odd? @hits)))

(defn first-n-open-doors
  "Return a vector of the first N open doors"
  [doors-wanted]
  (assert (pos? doors-wanted))
  (loop [idx       1
         open-idxs []]
    (let [next-idx       (inc idx)
          next-open-idxs (if (door-open? idx)
                           (conj open-idxs idx)
                           open-idxs)]
      (if (= doors-wanted (count next-open-idxs))
        next-open-idxs
        (recur next-idx next-open-idxs)))))

with result:

(first-n-open-doors 100) => [1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500 2601 2704 2809 2916 3025 3136 3249 3364 3481 3600 3721 3844 3969 4096 4225 4356 4489 4624 4761 4900 5041 5184 5329 5476 5625 5776 5929 6084 6241 6400 6561 6724 6889 7056 7225 7396 7569 7744 7921 8100 8281 8464 8649 8836 9025 9216 9409 9604 9801 10000]
"Elapsed time: 1279.926319 msecs"


1. Quick review:

The collections.Counter class has an update method that adds counts for items in an iterable. So instead of:

words = nltk.word_tokenize(sentence)
words = [word.lower() for word in words]
for word in words:
    f[word] += 1

you could write:

f.update(word.lower() for word in nltk.word_tokenize(sentence))

There's no need to call sent_tokenize if you are then going to call word_tokenize on the results — if you look at the implementation of word_tokenize you'll see that it calls sent_tokenize, so by calling it yourself you're doubling the amount of work here.

Revised code:

def freq2(string):
    return Counter(word.lower() for word in nltk.word_tokenize(string))

This is about 35% faster than the original code, mostly due to avoiding the duplicate sentence processing. But can we make further progress?

2. Profiling

When you have to improve the speed of some piece of code, there is a standard approach that works like this:

Prepare a repeatable and representative test case whose execution time you can measure.
Profile the execution of the code on the test case you prepared in step 1.
The profiling results will usually show that a small fraction of the code is responsible for a large fraction of the runtime. (If this is not the case, you've reached the limits of what can be achieved by this approach, so stop here.)
Investigate the code you identified in step 3 and make it faster.
Go to step 2.

So let's try this. Here's the test case:

TEST_FILE = 'nltk_data/corpora/gutenberg/melville-moby_dick.txt'
TEST_TEXT = open(TEST_FILE).read()
TEST_CASE = lambda:freq2(TEST_TEXT)

We can time the execution using the timeit module:

>>> from timeit import timeit
>>> timeit(TEST_CASE, number=1)
1.699578917992767

And profile the execution using the cProfile module:

>>> cProfile.run('TEST_CASE()', sort='time')
         2201133 function calls (2158188 primitive calls) in 2.127 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   281219    1.100    0.000    1.303    0.000 {method 'sub' of '_sre.SRE_Pattern' objects}
     9853    0.165    0.000    0.573    0.000 punkt.py:1287(_slices_from_text)
   216744    0.082    0.000    0.129    0.000 re.py:323(_subx)
     9852    0.064    0.000    1.366    0.000 treebank.py:96(tokenize)
   254990    0.060    0.000    0.084    0.000 cr153873.py:16(<genexpr>)
        1    0.058    0.058    0.142    0.142 {built-in method _collections._count_elements}
    25066    0.054    0.000    0.120    0.000 punkt.py:388(__init__)
    35055    0.052    0.000    0.225    0.000 punkt.py:533(_tokenize_words)
   216744    0.047    0.000    0.047    0.000 re.py:306(_compile_repl)
    37938    0.042    0.000    0.056    0.000 sre_parse.py:931(expand_template)
    12491    0.033    0.000    0.033    0.000 {method 'findall' of '_sre.SRE_Pattern' objects}
    25066    0.031    0.000    0.056    0.000 punkt.py:581(_first_pass_annotation)
   294926    0.029    0.000    0.029    0.000 {method 'lower' of 'str' objects}
[... and so on ...]

It takes a bit of practice to read this. Each row of the table gives statistics for a single function. The "tottime" column gives the total time spent running code in that function (but only in that function, not in any functions called by it). The "cumtime" column gives the cumulative time spent in that function (including time spent in functions called by it).

The profiling results satisfy the condition in step (3) — that is, a large fraction of the runtime (more than half) is spent in a single function, the sub method on regular expression objects. Why is so much time being spent here? In order to find out who is calling this method, we can use the print_callers method from the pstats module, like this:

>>> cProfile.run('TEST_CASE()', 'cr153873.profile')
>>> import pstats
>>> pstats.Stats('cr153873.profile').print_callers("method 'sub'")
   Random listing order was used
   List reduced from 83 to 1 due to restriction <"method 'sub'">

Function        was called by...
                    ncalls  tottime  cumtime
{method 'sub'}  <-       1    0.000    0.000  re.py:175(sub)
                     25066    0.022    0.022  nltk/tokenize/punkt.py:411(_get_type)
                    256152    1.078    1.282  nltk/tokenize/treebank.py:96(tokenize)

So the caller that's responsible is the tokenize method of the TreebankWordTokenizer class, which is called by nltk.word_tokenize. Looking at the implementation, you can see that it works by making many regular expression substitutions to the text being tokenized. Each substitution requires a pass over the text and then making a copy of the text. This is wasteful: it would be more efficient to pass once over the text being tokenized, and yield the tokens as they are found.

3. A faster word tokenizer

So it looks as if one way to significantly improve the performance of the code would be to write your own word tokenizer with the same (or similar enough) behaviour as TreebankWordTokenizer, but improved performance, and use that instead.

Here's a very rough sketch of how to do this:

import re
from nltk.tokenize.api import TokenizerI

class FasterTreebankishWordTokenizer(TokenizerI):
    """Word tokenizer that behaves similarly to TreebankWordTokenizer, but
    runs faster.

    """

    # Words that are tokenized as compounds.
    COMPOUND_WORDS = """
        can/not d/'ye gim/me gon/na got/ta lem/me mor/'n wan/na
    """

    # Dictionary mapping a compound word to a tuple of its tokens.
    COMPOUND = {
        a + b: (a, b) for a, b in (w.split('/') for w in COMPOUND_WORDS.split())
    }

    # Regular expression matching a token or a compound word.
    TOKEN_RE = re.compile(
        r'''
        '(?:[msd]|(?:ll|re|ve|tis|twas))\b
        |\b(?:[a-z]+n't|{})\b
        |--
        |\.\.\.
        |[^\s.\[\](){{}}<>;@#$%&:,?!"']+
        |\S
        '''.format('|'.join(COMPOUND)),
        re.VERBOSE | re.IGNORECASE)

    def tokenize(self, text):
        _compound = self.COMPOUND
        for token in self.TOKEN_RE.findall(text):
            if token.endswith("n't"):
                yield token[:-3]
                yield "n't"
            elif token in _compound:
                yield from _compound[token]
            else:
                yield token

Note that this is only a rough sketch to help illustrate the approach: it's untested, and I know that it doesn't have the same behaviour as TreebankWordTokenizer in lots of cases. If you end up going down this road, then there will lots of work ahead getting the details right.

But just for illustration, here's the new implementation of freq using the faster tokenizer:

def freq3(string):
    word_tokenizer = FasterTreebankishWordTokenizer().tokenize
    result = Counter()
    for sentence in nltk.tokenize.sent_tokenize(string):
        result.update(word_tokenizer(sentence.lower()))
    return result

and this is about twice as fast as freq2 (three times as fast as the original freq):

>>> timeit(lambda:freq3(TEST_TEXT), number=1)
0.8160900929942727


EF6 Code First unit of work pattern with IoC/DI

Unit of work

There are some issues of mechanics here. Normally with a generic repository, you want to be able to extend it, so you'd write:

public interface IOrderRepository : IGenericRepository<Order>
{
    //Some Order-specific queries here
}

But this would mean updating your IUnitOfWork every time too.

You're also having to add lots of annoying boilerplate code to your EfUnitOfWork to make it conform to the interface. The question here has a much nicer way of achieving the same thing.

However, my actual suggestion would be to remove IUnitOfWork altogeter, and simply add a Save (or, if you prefer, Commit) method to your repositories. Then any code which needs data access should be passed the repositories it needs directly, rather than ever being passed the DbContext.

The Generic Repository

I think the first hint that you're putting the cart before the horse here is the name you picked: IGenericRepository. The fact that it's generic absolutely does not need to be in the name. For one thing, it's already implied by the generic parameter. But more importantly, the fact that you're using the generic repository pattern, as opposed to just the repository pattern, is an unimportant detail.

The generic repository is simply a base class for your repositories. The only reason it's there is that there will be some methods you'll want on all of your actual repositories, and you don't want to have to repeat them.

Mat's Mug already gave the reasons in his answer not to expose IQueryable or take Expression or Func arguments in your repository, and I'd strongly echo those.

How to write your repositories

So given that, here's what I think a generic repository should look like to start out:

public interface IRepository<T> { }

Why is it empty? Because you don't know what methods you're going to need yet.

As soon as you need data access in one of your classes, write a repository for it:

public interface IOrderRepository : IRepository<T>
{
    IEnumerable<Order> GetAllPendingOrders(DateTime endDate);

    void Add(Order order);
}

(GetAllPendingOrders and Add being made up example data access methods that you might find yourself needing to use in some service class)

Note how these methods are defined by what the repository's consumer needs, they're not just aimed to exactly match what IDbSet already gives you.

After you have a few repositories, you'll find you have quite a bit of repetition. For example, Add would probably be on most or all of them. (GetAllPending... would not!) So then, you simply refactor by removing those methods and creating a generic version on the Repository<T>. This is just plain old vanilla extracting of a base class that you see all over the place, there's nothing magic about it just because it's relating to repositories.

Guessing

If you really don't like the idea of starting with an empty generic repository, there are some methods which using educated guesswork, you can be almost sure you'll need. So a starting point for your generic repository might be the following cut-down version of the one you posted:

public interface IGenericRepository<T> : where T : class
{
    IEnumerable<T> GetAll();
    T GetById(int id);
    void Add(T entity);
    void Save();
}

But to emphasise: don't just copy this without understanding why! Generic repositories are horribly badly explained in dozens of articles and blog posts across the internet, and it's really worth clearing up in your mind what they're actually for before using them.


Translation function - one word set to another

Best approach
If your vocabulary library is very large you need to implement another data structure and sorting algorithm for your vocabulary. I would go with Bucket Sort. You need to partition your strings into separate buckets of characters
to optimize. Comparing entire strings is not efficient.
Alternative approach
If you are lazy or prefer a different approach, utilize Microsoft Query (ACE.OLEDB - SQL) which is much more efficient than any VBA code. Dump your vocabulary to a single worksheet and execute an SQL to find your matches like so (for each sentence separately):

Split string to tokens and dump it to another worksheet DumpedTokens

Execute a query like this:

Find all matches in the Vocab worksheet. Keep tokens that don't have translations:
SELECT Iif(Vocab.Word = NULL, Dumped.Token, Vocab.TranslatedWord) FROM [DumpedTokens$] as Dumped
LEFT OUTER JOIN [VocabularySheet$] as Vocab
ON UCase(Vocab.Word) = UCase(Dumped.Token)

Join the strings back into sentences

This will probably run a couple of seconds.
If you want you can use my SQL AddIn to Excel which makes it easier to write SQL queries in Excel: http://www.analystcave.com/excel-tools/excel-sql-add-in-free/


Parsing a sequence of bits out of a bit field

This is not the kind of thing you should loop for. Just calculate a mask:

def parse_out_bits(bit_field: int, start_index: int, end_index: int) -> int:
    mask = (1 << (end_index - start_index + 1)) - 1
    return (bit_field >> start_index) & mask

In English:

If you're getting bits 5-7, that's 3 bits
2^3 == 8, - 1 = 7 (or 111 in binary - that is your mask)
Shift the field right by 5 to put the bits of interest in the least-significant position
And-mask them to get the result.


Welcome to Code Review.  Not too bad but I would suggest a few things.

_failureCount is only used in ExecuteAction so I would only define it locally to ExecuteAction and renamed it simply failureCount.

You may want to expose threshold publicly as a property since different instances could have differing thresholds.  Suggest:

public int Threshold { get; }

Consider having a ToString() override.

CircuitState enum is okay where its at, but if it were me, I usually define it external to the class.

You may consider having the State be gettable publicly.  Suggest:

public CircuitState State { get; private set; }

I see no reason for Invoke().  Just call ExecuteAction(_currentAction) directly.

The constructor has a timeout parameter.  I would encourage clarity in the name with millisecondsTimeout.

And finally, the biggest issue I see is that you really should get into the practice of use { } with if.  I know C++ was okay with this, and C# allows it, but here at CR we strongly discourage it because it could lead to nefarious hard-to-find bugs. There are lots of places where you would change this; here is but one example:

if (State != CircuitState.Open)
{
    ChangeState(CircuitState.Open);
}


I'm not really sure if this question is on topic, but I just started using SQL myself, so here's a chance for me to apply what I've learned. The following is using PDO.

//unspecified placeholder
$sql = "SELECT * FROM item_entries WHERE item_id=?";
$sth = $dbh->prepare( $sql );
$sth->execute( array( $id ) );

//specific placeholder
$sql = "SELECT * FROM item_entries WHERE item_id=:id";
$sth = $dbh->prepare( $sql );
$sth->execute( array( ':id' => $id ) );

The idea being that the SQL statements don't have values directly injected into them by using placeholders. In the first example that placeholder was unspecified ?. You can use any number of unspecified placeholders, but then the array you pass in to the execute() function has to be in the same order. While this may not be a big deal for one input, it could quickly become tedious trying to keep track of multiples. Which is where the second example comes in. It uses specific placeholders :id to define keys in the execution array. This means these elements can be in any order so long as the correct key is associated with the correct input.

As for if this is only necessary for user data? I don't know, but I'm just as prone to make mistakes as users, so it couldn't hurt. I'm quite interested to here if I got this right as well.


Calling a function when all asynchronous calls complete

The approach itself (i.e. using a counter) is reasonable, but the hard-coded 2 and DoStuff limits its use.

You could do something like this, to derive more generic implementation:

function createCounter(count, callback) {
  count || (count = 1); // default to 1
  (typeof callback === 'function') || (callback = function () {}); // default to no-op
  return function () {
    --count || callback();
  };
}

Now you have a function that returns a specialized "done" function. Use like so:

var done = createCounter(2, DoStuff);

elem1.executeAsync(function () {
  done();
});

elem2.executeAsync(function () {
  done();
});

Incidentally, this can be shortened to:

var done = createCounter(2, DoStuff);

elem1.executeAsync(done);
elem2.executeAsync(done);

(of course, your actual code is likely more complex)

However, I'd say you should also look into the Promise/Deferred patterns.
For instance, using jQuery's implementation (and assuming executeAsync returns a promise) you can do this

$.when(elem1.executeAsync(), elem2.executeAsync()).then(DoStuff);


const fs = require('fs');
// Read data from JSON file and parse it as a JSON object
const dataFromFile = JSON.parse(fs.readFileSync('./Data.json', 'utf8'));

const data = {
  'A0_Water': 'c_inh2o_A0',
  'A1_Water': 'c_inh2o_A1',
  'A2_Water': 'c_inh2o_A2',
  'A3_Water': 'c_inh2o_A3',
  'Barometer': 'b_mbar_corrected',
  'Temp': 'b_temp'
};

// Now for every 'property' in your 'data' object here,
// you need to update the 'dataFromFile' object

for(let property in data) {
  if(data.hasOwnProperty(property)) {
    dataFromFile[property] = data[property];
  }
}

// Write the updated data in the JSON file
fs.writeFileSync('./Data.json', JSON.stringify(dataFromFile));

NOTE: The above code will add a new value in the JSON file if a corresponding key is not found in your data object. You may want to add a check as:

for(let property in data) {
  if(data.hasOwnProperty(property)) {
    if(dataFromFile[property]) {
      dataFromFile[property] = data[property];
    }
  }
}

Now, the update will be preformed only when a corresponding key has been found.


Method

The fastest way to check if an item into a MongoDB is unique (and if it isn't, not insert it) is to create a unique index on the related columns and catch the error upon insertion time.

Watch more here.

MongoDB - Features

Maybe this would be OT, but I would like to let you know all this:

MongoDB is inconsistent by default. The documentation claims "strong consistency," but the default implementation considers an operation "complete" as soon as it is queued in the send buffer of a client, even before it has been seen by any node. There is a big discrepancy between the discussion in Mongo blogs and the default implementation in the code. You have to take extra measures to ensure that an update has propagated to all replicas.

I'll list you the advantages and the disadvantages, just to let you make an idea, I don't like so much MongoDB.

Advantages

Lightning fast.
You can perform rich queries, can create on the fly indexes with a single command.
Lightning fast.
Replication is very easy.

Disadvantages

Indexes take up a lot of RAM. They are B-tree indexes and if you have many, you can run out of system resources really fast.
Very unreliable. No single server durability. If something crashes while it's updating 'table-contents' - you lose all you data. Repair takes a lot of time, but usually ends up in 50-90% data loss if you aren't lucky. So only way to be fully secure is to have 2 replicas in different datacentres.

Obviously, there could be some alternative to MongoDB.


Just some stylistic things that stick out to me:

I think it's a bit cumbersome to have all of this:

using std::cout ; using std::cin; using std::endl;
using std::mutex; using std::atomic;
using std::array; using std::function;

You're also still prefixing std:: in places, which defeats the purpose of having this.  Since you could always end up using something not already in this list, you might as well keep prefixing std:: as you're doing already, and remove all of that above.
Some of your indentation and semicolon placing are inconsistent.  In some places you indent or not, and in some places you have a space before the ending semicolon.  Keep the indentation consistent (you should utilize it) and choose what to do with all of your semicolons.
It would be more readable and maintainable to place the template statements on separate lines from the class or function, especially if either statement is lengthy:

template <typename T>
class Class
{
};

template <typename T>
void function()
{
}


Java Pub Sub implementation using broker

First of all, mutex should be final, since you are synchronizing on it. In the current state of your code, it wouldn't make much difference, since it is private anyway and never exposed outside the class, but still, if you make it final, then the field mutex is protected against modification by the compiler, reducing the risk of bugs.

If you don't ever intend to change brokerInstance, i.e. if Broker is intended to be a singleton, you can also make brokerInstance final and initialize it immediately with its declaration. This would eliminate the need for the if construct in the method getInstance(). After googling about this, I found out that the purpose of what you are doing is probably lazy initialization. However, in this question on stackoverflow, some points are made in favor of the approach with the final variable (especially the point about thread safety might be interesting to you).

You might consider taking advantage of the class ConcurrentHashMap for your synchronization purposes. A ConcurrentHashMap is optimized for synchronized access in that it is not locked entirely during an operation, so that operations that do not conflict with each other can be performed simultaneously (you might want to take a look at this).
For example, you could make each Set<Subscriber> in Broker.subscribers a ConcurrentHashMap.KeySetView (which serves as the Set equivalent of a ConcurrentHashMap, because there is no class ConcurrentHashSet) instead of a regular HashMap. This would at least make the synchronized block in Broker.deregister(String, Subscriber) unnecessary. Making Broker.subscribers itself a ConcurrentHashMap might also help, but you still have to be careful, for example in the method Broker.register(String, Subscriber), because, without any other synchronization, the first call to subscribers.containsKey(topic) might yield false, so the else block is entered, but before the call subscribers.put(topic, sub) is reached, subscribers might have been changed and could now already contain a mapping for topic which would then be overwritten. There seem to be special methods in the class ConcurrentHashMap for such cases (like the compute methods), but since this is merely a general suggestion, I won't go into detail about it.

Your code lacks handling of exceptional cases, for instance, if the methods deregister(String, Subscriber) or sendMessage(String, Map) are called with a topic that is not contained in the key set of subscribers.

As I already hinted at in a comment, using raw types is a dangerous undertaking. It is not wrong per se, but the risk of bugs is higher because generics provide compile-time type-safety which you are not taking advantage of if you use raw types. I don't know what your code might do with the map, so maybe it won't be a problem, but you might still take a look at this or this.

Also note that the map that is being passed to Broker.sendMessage(String, Map) will be accessed concurrently in sub.parallelStream().forEach(subscriber -> subscriber.update(map)), which might not be desirable if the map can be modified by the subscribers.


Feedback

Use JSDoc comment style for the function, this style is widely used and most developers understand it.
Add comments inside your function to describe what every variable is used for and what every section is doing.
Do all the validations before starting to compute the result. So instead of checking if the elements are numbers while constructing the result; you should check them before.
Whenever you find yourself doing something twice, extract it to a separate function.
Throwing an error when it happens is more useful then returning null, it will give the user of your code a hint about what is going wrong and stops the execution of the code instead of using null as an array or checking the result every time your function is called.

Refactored code

/**
 * Checks if the given argument is an integer or not.
 * @param  {Mixed}   n the argument to check
 * @return {Boolean}   TRUE if n is an integer; FALSE otherwise.
 */
function isInteger (n) {
    return !isNaN(n) && typeof n === 'number' && n % 1 === 0;
}

/**
 * Checks if the given argument is an array of integers.
 * @param  {Mixed}  array the argument to check.
 * @return {Boolean} TRUE if the given array is an array of integers
 *                   (or an empty array); FALSE otherwise.
 */
function isArrayOfIntegers (array) {
    return Array.isArray(array) && array.length == array.filter(isInteger).length;
}

/**
 * Gets an object in which the keys are the items of the given array
 * and the values are TRUE.
 * @param  {Array} array Array of simple elemets (numbers or strings)
 * @return {Object}
 */
function toIndex (array) {
    return array.reduce(function(index, value) {
        index[value] = true;
        return index;
    }, {});
}

/**
 * Gets the array of elemets which are present exclusively in one of the arrays.
 * @param  {Array} array1 First array of integers.
 * @param  {Array} array2 Second array of integers.
 * @return {Array} Array of the integers which are present
 *                 exclusively in one of the two arrays.
 * @throws {Error} If one of the two arguments is not an array of integers.
 */
function getArrayDiff (array1, array2) {
    // Validating the arrays
    if (!isArrayOfIntegers(array1) || !isArrayOfIntegers(array2)) {
        throw Error('One of the given parameters is not an array of integers');
    }

    // Making objects from the arrays. Objects in which the keys
    // are the values of the arrays which will allow to search
    // the elements in logarithmic time
    var index1 = toIndex(array1);
    var index2 = toIndex(array2);

    // Computing the union of the arrays
    var result = array1.concat(array2);

    // Removing elements which are present in the two arrays
    result = result.filter(function(item){
        return index1[item] === undefined || index2[item] === undefined;
    });

    return result;
}

Hope this will help you and waiting for other members to give their suggestions and improve this code.


Including a page specified in query string

Common practice is to check all GET/POST/SERVER/ENV parameter values against a whitelist or regex before using it for any purpose. You are checking it with a list derived from scandir, but that makes the assumption that the modules directory hasn't been compromised.
Running scandir on every request is a likely performance bottleneck. One possible solution is to cache the results of the scandir and subsequent filtering to a file above the document root and only re-run the scan if the mod time of the modules directory is more recent than the mod time of the cache file (check out the filemtime() docs).
You have some duplicate code for handling 404s. This could be combined into one method if you want to adhere to DRY principles.
A more widely accepted way to prevent a file from being executed is to compare the __FILE__ constant to the SCRIPT_FILENAME which has been set by the server (if available in the $_SERVER global). It's not fool proof, but more portable than your solution.


Your building pattern is just right. But the situation (as elsewehere mentioned) to use the building pattern is not. Imagine a situation where there is a (in your case) celldata base class:

 class CellData {
 }

This class is the base of other, more specific, celldata class:

 class CellData_2  extends CellData {
 }

etc.

Now imagine the choice of which specific celldata you are requiring, depending on the given URL your builder method starts to look something like this:

 public CellData build (String URL) {
     if (URL complies to case 1) {
          return new CellData_1;
     ...
 }

That's where the builder pattern should be used.


Number Of Matching Elements In Two Lists

As you have updated your examples, you can write some code to ensure the code we are about to write works properly :

def main():
    """Main function"""
    assert Score('aaabb', 'bbaaa') == 5
    assert Score('aabbb', 'bbbaa') == 5
    assert Score('aaabb', 'aabbb') == 4
    assert Score('aaabb', 'ccaaa') == 3
    assert Score('aaaaa', 'bbbbb') == 0
    assert Score('ababa', 'babab') == 4
    assert Score('aabcc', 'babaf') == 3
    assert Score('abcde', 'abfgh') == 2
    assert Score('bacde', 'abdgh') == 3

Now, the main issue in your code is that we are performing complicated (dirty?) string logic and checking many times if some letter is in a list. The real solution is to count letters in both string. Each letter will count for n points where n is the minimum between the number of times it appears in string 1 and the number of times it appears in string 2.

Using Counter, you can write this :

from collections import Counter

def Score(guess, solution):
    g = Counter(guess)
    s = Counter(solution)
    n = 0
    for l,c in g.iteritems():
        n+=min(c, s[l])
    return n

Abusing generator expressions, you can also write this :

def Score(s1, s2):
    c = Counter(s2)
    return sum(min(n, c[l]) for l,n in Counter(s1).iteritems())


It's a good attempt, it reads easily and I like that you nested the FizzBuzz check within Fizz branch.

This doesn't look like most of the code you see in the wild, though, so a good exercise would be to extract a function for the FizzBuzz logic that is independent from the loop over numbers.

def get_fizzbuzz(num:int) -> str:
    result = ""
    # fizzbuzz logic
    if num % 3 == 0:
        if num % 5 == 0:
            result = "FizzBuzz"
        # ...
    return result

You could even make it more flexible by optionally allowing different numbers to be entered instead of 3 and 5, while still using 3 and 5 as default values, like so:

 def get_fizzbuzz(num:int, fizz:int = 3, buzz:int = 5) -> str:
    result = ""
    # fizzbuzz logic
    if num % fizz == 0:
        if num % buzz == 0:
            result = "FizzBuzz"
        # ...
    return result

Then you can just call the function in a loop using the default values:

for num in range(1, 101):
    print(get_fizzbuzz(num))

Or alternatively with different values for fizz and buzz:

for num in range(1, 101):
    print(get_fizzbuzz(num, 5, 7))

That will help you make your code more modular.

Note that I used Python 3's type hints in the function definition, which are completely optional but can make the code more clear, as well as provide static code analysis with certain tools.


the other lines are of different length and are presented randomly

I understand this as that all lines have different length. As such, I would make a different choice of data structure. Namely, a TreeSet<String>.

A TreeSet can be constructed with a Comparator, so I would use your existing comparator as the constructor for this TreeSet. Then I would use the descendingIterator() method to iterate x times over your elements in descending order.

Note: Even if there would be lines of the same length, you could still use a TreeSet but then you'd need to compare on both the length and the String itself, to avoid ignoring the insertion of an element that has the same length as a previous existing element. (If elements can be exactly identical, then TreeSet will not work well)

This will allow us to get rid of your insertSorted method and get rid of the potentially slow ArrayList.add(index, object) call which is \$O(n - index)\$


Extracting the location for a page with fewer conditionals

In advance sorry for the formatting but I code in C# so the it's probably slightly different than you're used to:

Using else if

Although this doesn't actually improve number of if statements, why are you using else if? If the previous if statement is satisfied you're returning a value anyway, so the code won't execute the next if statement anyway. This also renders your else keyword pointless too because of the same reasons

Combining conditionals

You are returning aPage.getSiteDetail() in two places, you can combine these if statements together:

if (aPage.getSiteDetail() != null &&
    (aPage.getLocationDescription() == null || aPage.getLocationDescription().getLocationLevel() == null))
{
    return aPage.getSiteDetail();
}

After this there's no point in checking if aPage.getLocationDescription() == null || aPage.getLocationDescription().getLocationLevel() == null because if aPage.getLocationDescription() then aPage.getLocationDescription().getLocationLevel() has to be null:

Repeated method calls

You can really improve the readability of your code and minimise the number of external method calls your making by assigning the return value of your method calls to a variable:

string siteDetails = aPage.getSiteDetail();
// Here you need to replace var with whatever the return value of aPage.getLocationDescription() is
var locationDescription = aPage.getLocationDescription();
string locationLevel = locationDescription != null ? locationDescription.getLocationLevel() : null;

Pointless Conditionals

If aPage.getSiteDetail() != null || aPage.getLocationDescription() != null but none of the rest of your conditionals are satisfied you return "N/A" but you also do this if both are null anyway. So your first conditional is pointless, because you continuously evaluate those values later on making a final code looking something like this:

public String getLocationToString()
{
    string siteDetails = aPage.getSiteDetail();
// Here you need to replace var with whatever the return value of aPage.getLocationDescription() is
    var locationDescription = aPage.getLocationDescription();
    string locationLevel = locationDescription != null ? locationDescription.getLocationLevel() : null;

    if (siteDetails != null))
    {
        if (locationDescription == null)
        {
            return siteDetails;
        }
        if (locationLevel != null)
        {
            return siteDetails.trim() + "-" + locationLevel;
        }
    }

    return "N/A";
}

Ternary Operators

I already used these when assigning a value to locationLevel but you could also do it for the following two if statements which means you'd only have one if in your whole function:

if (locationDescription == null)
{
    return siteDetails;
}
if (locationLevel != null)
{
    return siteDetails.trim() + "-" + locationLevel;
}

Becomes:

return locationDescription == null ? siteDetails : siteDetails.trim() + "-" + location.level;

Could even become:

return siteDetails.trim() + (locationDescription == null ? "" : location.level);


From a once over:

You are using lowerCamelCase, that is good
Variables like ans and prob deserve to be written out to answer and problem
You are using functions, but I think it can be split up a bit more from a best practices. I would go for something like this:

while( stillPlaying ){
  problem = generateNewProblem();
  answer = getAnswer( problem );
  processAnswer( answer );
}

['+', '\u2212', '\xD7', '\xF7'][randInt(4)]; I wonder why you could not simply use ['+','-','*','/']. Regardless you should have 4 constants for those values since you use those values repeatedly in other places

var plusSign = '+',
  minusSign = '-',
  timesSign = '*,
  divideSign = '/',
  signs = [plusSign , minusSign, timesSign, divideSign];

  if (sign == divideSign) num1 *= num2;

This seems funny: num1 = randInt(maxNum + 1);, if you were trying to avoid zero, you really need num1 = randInt(maxNum) + 1;
Avoid dropping the curly braces and newlines, even when if statements are short like here: if (sign == '\u2212') num1 += num2;

Here's my attempt for fun and giggles.

var maxNum = 12,
    signWidt = 12,
    question = document.getElementById( 'question' ),
    input = document.getElementById( 'input' ),
    errorMessage = document.getElementById( 'errorMessage' ),
    greatMessage = document.getElementById( 'greatMessage' ),
    answer;
//Some of these signs are closer to what children use in school
var plusSign = '+',
    minusSign = '\u2212',
    timesSign = '\u2212',
    divideSign = '\xF7',
    signs = [plusSign , minusSign, timesSign, divideSign];

function randInt(max) {
  return Math.floor(Math.random() * max);
}

function calculateAnswer(n1, sign, n2) {
  switch (sign) {
    case plusSign:
      return n1 + n2;
    case minusSign:
      return n1 - n2;
    case timesSign:
      return n1 * n2;
    case divideSign:
      return n1 / n2;
    default:
      return false;
  }
}

function displayQuestion( s ){
  //We know the question will never surpass 12 chars..
  var extraneousSpace = 12 - s.length, spaceLeft, spaceRight;
  //Compare last bit to 1, if that bit is 1, the number is odd
  //So we subtract 1 before we evenly divide by 2 and 1 space on the right
  if( extraneousSpace & 1 ){
    extraneousSpace--;
    spaceLeft = extraneousSpace / 2;
    spaceRight = spaceLeft + 1;
  } else {
    spaceLeft = spaceRight = extraneousSpace / 2;
  }
  //Mildly evil re-use of variable and magical space repeating routine
  //http://stackoverflow.com/questions/202605/repeat-string-javascript
  spaceLeft = new Array( spaceLeft + 1 ).join( ' ' );
  spaceRight = new Array( spaceRight + 1 ).join( ' ' );
  question.innerText = spaceLeft + s + spaceRight;
}

function generateQuestion(){
  var sign = signs[randInt(4)],
      num1 = randInt(maxNum + 1),
      num2 = randInt(maxNum + 1);

  if (sign == minusSign){
    num1 += num2;
  }
  if (sign == divideSign) {
    num2 = randInt(maxNum) + 1;
    num1 *= num2;
  }
  answer = calculateAnswer( num1 , sign, num2 );
  displayQuestion( num1 + ' ' + sign + ' ' + num2 )
}

generateQuestion();
input.focus();

input.addEventListener( 'keypress' , function(e){
  console.log( this );
  if( e.which == 13 || e.keyCode == 13 ){
    if( input.value != answer ){
      errorMessage.innerText = 'Wrong, ' + question.innerText.trim() + ' = ' + answer;
      greatMessage.innerText = '';
    }else {
      errorMessage.innerText = '';
      greatMessage.innerText = 'That is right, here\'s another question';
    }
    input.value = '';
    generateQuestion();
  }
});
#errorMessage { color: red }
#greatMessage { color: green }

|￣￣￣￣￣￣ |
|   What is  |
|            |
|      ?     |
| ＿＿＿＿＿__|
(\__/) ||
(•ㅅ•) ||
/ 　 づ

<input type='text' id='input'>


Walking and comparing contents of binary trees

In my opinion, you haven't completed the exercise properly, since you have hard-coded the termination after reading 10 values. If a rogue tree.New() produces a larger tree, you should be able to detect it.


Quadratic "Complete the Square" Solver in Python 3

There is a library to help with this! Check out sympy, particularly sympify and parse_expr.


There is a much better solution to your problem. Some mistakes you could have avoided -

• You use 2 loops. One would also do it.

• You iterate all the elements in the nested array. You do not need to include the element itself (as indirectly mentioned in the question). Therefore, you can iterate only a[i]/2 elements.

You can optimize this further also. Here is my code but unfortunately it is in Python. Hope you can at least understand that. It is an easy language.

for i in range(int(input())):
    x = int(input())
    sum=0
    for j in range(x/2):
        if(x%j==0):
            sum += j
    print(sum)


Find and print all prime numbers (less than 10000)

This is a very nice start! It is clear that you have put some effort into making your code clear and easy to read - it paid off. That said, there are a few things I would recommend changing.

Don't take input as a float. This opens up the possibility for confusion without providing any benefit to the user.
Include USER_INPUT in the range tested for primes. If I input 5 using the form I only get 2 and 3, while I expected 2, 3, and 5.
Why do you cache PRIMES only to reset it every time findPrimes is called? If you are going to spend the memory to save a list of primes, you might as well make use of it.
I see you have started to optimize your solution by only going up to Math.sqrt(n), but you are still using an inefficient algorithm. I would encourage you to look into the Sieve of Eratosthenes as your input is bounded.
Don't mix your logic and display code. While for a small project like this it isn't much of an issue, if you want to use PrimeFinder somewhere else in your application you would have to rewrite it to strip out all of the page specific code.

With this in mind, here is how I would write PrimeFinder as a module without handling DOM manipulations.

const PrimeFinder = (function() {
    let PRIMES = [];
    const MAX_RANGE = 10000;

    function _generatePrimes() {
        // Computing 10000 is not much different than computing 500, so fill the entire array.
        let marks = Array(MAX_RANGE + 1).fill(false)
        for (let i = 2; i <= MAX_RANGE; i++) {
            // Already marked as non-prime?
            if (marks[i]) continue;
            // Mark all multiples
            for (let j = i * 2; j <= MAX_RANGE; j += i) {
                marks[j] = true;
            }
            // This number hasn't been marked, and therefore is prime
            PRIMES.push(i);
        }
    }

    function isPrime(n) {
        if (Number.isNaN(n)) throw Error('n must be a number');
        if (n > MAX_RANGE || n < 0) throw Error('n is out of range.');
        if (!PRIMES.length) _generatePrimes();
        // Could be sped up with a binary search.
        return PRIMES.includes(n);
    }

    function findPrimes(upperBound) {
        if (Number.isNaN(upperBound)) throw Error('upperBound must be a number');
        if (upperBound > MAX_RANGE) throw Error(`upperBound must be less than ${MAX_RANGE}`);
        if (upperBound < 0) throw Error('upperBound must be at least 0');

        if (!PRIMES.length) _generatePrimes();

        let index = PRIMES.findIndex(n => n > upperBound);
        // Return a copy of the array so users can't mess with the module
        return index == -1 ? [...PRIMES] : PRIMES.slice(0, index);
    }

    return { isPrime, findPrimes };
}());

function displayArray(parent, items) {
  parent.innerHTML = '';
  items.forEach(value => {
    let el = document.createElement('li');
    el.textContent = value;
    parent.appendChild(el);
  });
}

document.querySelector('input').addEventListener('input', event => {
  let num = parseInt(event.target.value, 10);
  if (num > 10000) event.target.value = num = 10000;
  if (num < 0 || Number.isNaN(num)) event.target.value = num = 0;
  displayArray(
    document.querySelector('ul'),
    PrimeFinder.findPrimes(num)
  );
});
<input type="number" />

The snippet behaves similarly to the provided snippet without mixing DOM logic into the PrimeFinder functionality - this makes it possible to easily pull out PrimeFinder for use in other projects (even those where the DOM might not exist).


Stripping time information in a DateTime object

Simple Google Search rendered this link DateTime.Date

this Returns only the date

DateTime now = DateTime.Now;
Console.WriteLine(now.Date.ToString("d"));


I can't test this code, so I will only make a few general remarks for the time being.
I was curious, since I actually started working on the Prometheus API yesterday, because I was asked to design a monitoring dashboard.

This code is un-Pythonic:
    global ENDPOINT
    ENDPOINT = endpoint
    global ENDPOINT_NAME
    ENDPOINT_NAME = endpoint_name
    global INTERVAL
    INTERVAL = interval

Assigning a variable to another variable like this: ENDPOINT = endpoint has no added value and is even confusing. All this is redundant.
Global variables are frowned upon, because they are seldom necessary in fact. There usually is a better way. Just pass the variables along to your functions and retrieve resulting values as necessary.
If you have constants, define them at the top of your code (if you have just one file), or put them in a separate config file.
I suggest that you create a config.py file, and move all your constants there. Then you import the file:
import config

And you can refer to your constants like this all across your code:
config.ENDPOINT

Source and there are more useful tips too. This is recommended reading for beginners and more experienced programmers as well.

You have this code:
        if family.type == 'summary':
            #print(family.type)
            pass
        elif family.type == 'histogram':
            #print(family.type)
            pass
        else:

pass is no operation (NOP). So you have code that does strictly nothing and should be removed. What you want is probably something like this:
if family.type not in ('summary', 'histogram'):

You have 3 functions: config_func, parse_func, read_func. It's obvious they are functions, so the _func suffix is superfluous. But the names are not descriptive enough. It doesn't tell me what you are reading or parsing. So I think your naming conventions should be revisited.
In a way I think the order of things is logical: configuration, reading results, parsing results. Gotta make it more obvious.

Something that is lacking badly: comments. They are not just for external reviewers but for your benefit too. After a while you will forget stuff and you will have to re-analyze your own code to figure out the flow and what kind of data is returned by a given function. I would recommended that you document each function with a docstring. 2-3 lines will do.
Document your functions, and describe what kind of data you are manipulating. When you have some ifs and are testing for a specific condition, it does not hurt to explain why in a comment, unless the purpose of the test is very obvious.
Since you put your code on Github there is an expectation that somebody else might want to download it, use it, possibly fork it. But then it is important to provide enough documentation. Lack of documentation can be forgiven for software that works straight out of the box without any configuration, but this is rare.

Quality control: in config_func (at the top of your code) you have repeated code:
endpoint_set = False
endpoint_set = False

A good IDE would help you spot those mistakes and also enforce PEP8 rules. In a job interview this would qualify as lack of attention to detail, just by proof-reading your code carefully you should have noticed :)

In a Python program it is customary to have a main method and use __main__ like this:
if __name__ == '__main__':
    collectd.register_config(config_func)
    collectd.register_read(read_func, INTERVAL)

Or better yet:
if __name__ == '__main__':
    main()

And put your launcher code in the main function. The benefit of doing so is that you can import your package (to reuse some functions) without actually launching it.

Now that I am reading what I wrote so far I realize that it's not very helpful. I only gave you general suggestions but I think they are still useful though. But I am kinda frustrated because you have not described what the finished product does look like. After reading your code I can't really figure it out. I don't have a Prometheus box handy so I can't run your code and pull out some data.
The code is quite short (< 100 lines) and yet it is obscure to me. I don't think it's only because I am Prometheus newbie. The code does not speak for itself. Comments would help make more sense of the overall approach.
I am not familiar with collectd so I can't comment much on that. I understand you are scraping metrics but what is the ultimate goal, how will the data be used, that's what is interesting.


Counting pairs of integers which have a predefined difference

Style

1-letter variable names doesn't have meaning. It is acceptable for i, j or k as loop indexes but other than that it mostly harms readability;
Same for temp or abreviations (ar, cnt, diff): give these variables some real names;
functions names should be snake_case instead of camelCase;
iterating over the values of a sequence is more easily done using a for loop:

for value in ar:
    # do something with `value` instead of `ar[i]`

Since you’re not modifying it, you can remove temp and access ar[j] directly.
You don't need to strip() before a split() without arguments, it will be done automatically.
You correctly used if __name__ == '__main__', that's a good habit to keep.

After that, the code could look like:

def count_pairs(data, length, delta):
    data.sort()
    i = length - 1
    num_pairs = 0
    for value in data:
        while abs(value - data[i]) > delta and i > 0:
            i -= 1
        if abs(value - data[i]) == delta:
            num_pairs += 1
        i = length - 1
    return num_pairs

if __name__ =='__main__':
    N, K = map(int, raw_input().split())
    data = map(int, raw_input().split())
    print count_pairs(data, N, K)

Complexity

For now, you’re iterating over the same list several times to find the pairs and you need to sort the list beforehand for an efficient computation. But you could compute, for each element, the element that need to be present to form a pair (\$O(n)\$) and then, for each initial element (\$O(n)\$), check if it exists in the array of computed "need-to-be-there" elements.

Luckyly, Python's sets can provide such checks with an \$O(1)\$ performace, for an overall \$O(n)\$ time complexity:

def count pairs(data, delta):
    needed_values = set(value + delta for value in data)
    return sum(value in needed_values for value in data)

Here I abuse the fact that booleans are integers after all, but you could write it in a more proper way using:

def count_pairs(data, delta):
    needed_values = set(value + delta for value in data)
    exist_in_pair = [value for value in data if value in needed_values]
    return len(exist_in_pair)


This looks like nice Haskell to me! I'm not an expert, but I could make a few remarks:

args !! 0 could be simplified to head args. It's just more idiomatic.
maximumBeautyInner could be renamed to maximumStringBeauty'. That's what I see most of the time, anyway, in this pattern (having an outer "starter" function and an inner "real recursive" function).
I would write:

countSort = reverse . sortOn length . group . sort

because it reads nicer, but I'm not sure how expensive the reverse will be afterwards.
maximumBeautyInner can be written much more concisely when using the builtins sum, zipWith and map. When writing recursive functions, try to see if you can use these and maybe fold or another of their family.

  where maximumBeautyInner = sum . zipWith (*) [26, 25..1] . map length

Step by step:

The map length returns only the lengths of the groups (from countSort).
The zipWith combines that list with the list [26, 25..1] to form pairs, and applies * to each pair of values. So the first (highest) length gets multiplied by 26, the next one by 25, etcetera.
sum, finally, sums them all up (you'd probably guessed).

You would only pass the result of the countSort to this function, as it is now [[Char]] -> Int.

By using these list functions, you can reduce the need for your own recursive functions, which increases readability.

All in all, well-factored code, and a good way to solve this problem!

EDIT: instead of using countSort = reverse . sortOn length . group . sort, use countSort = sortOn (negate . length) . group . sort. That removes the need for reverseing the list.


Repeat actions

Look at the bottom of your code. This is the layout:

do something with user1
do the same thing with user2

do something with user1
do the same thing with user2

...

You have a lot of repeated code down there. To reduce this repetition, you should store the two players in an array, and then each time loop through the array an do what you need to do with each player.

To make it cleaner, you could use comprehensions:

user.receive_cards(5)    for user in users
user.place_first_cards() for user in users
user.receive_cards(3)    for user in users
...

This clearly illustrates each step of the game play, and doesn't have a repetitive line right after each one.

In fact, you could simplify this even further. If you keep a list of lambdas that show/do each of the different game moves (receive_cards, play_first_cards, etc.), then you easily loop through the list, calling each lambda.

Here's what the list might look like:

game_moves = [lambda user: user.receive_cards(5), lambda user: user.place_first_cards(), ...]

Then:

for game_move in game_moves:
    game_move(for user in users)

Note: I didn't have time to test this out, so this may not work. Leave a comment if there is an issue; I'll fix it later.

Now, with the list, each part of the game item by item is easy visible just a glance at the list.

If this, return true. Else that, return false.

I came across this in your code, inside your board_limit method:

if len(self.board[board_number - 1]) < 3:
    return True
else:
    return False

This is unnecessary. If the condition in the if statement evaluates to true, why don't you just return the conditional itself?

return len(self.board[board_number - 1]) < 3

Refactor methods

Look at your place_first_cards and place_cards methods. Then, put them in a diff tool. What's the different? Here:

while len(self.hand) != 0:

and:

self.hand.pop(0)

These are the only two lines that are different among these two methods. Everything else is exactly the same.

You should refactor this into one method that takes a parameter that tells if the cards are the first cards or not. Then, your new method would look like this:

def place_cards(self, is_first):
    print "Your time to play %s. Here is your hand. Pick a card and choose a row to place it" % self.name
    while len(self.hand) != (0 if is_first else 1): <--------
        print '-'.join(self.hand)
        for i in self.board:
            print i
        card_placed = int(raw_input("Choose a card (1 - %d): " % len(self.hand)))
        chosen_board = int(raw_input("Choose a board (1-3): "))
        if self.board_limit(chosen_board):
            self.board[chosen_board - 1].append(self.hand[card_placed - 1])
            self.hand.pop(card_placed - 1)
        else:
            print "The board is full. Choose another one."
    if not is_first:
        self.hand.pop(0) <------

This single method does exactly what those other two methods did, except for two small sections that can be "turned on or off" with a simple argument.

Now, your code would look like this for placing first cards:

user.place_cards(is_first=True)

Note: the is_first= is not necessary, but it increases readability, I think.

Now your code is simpler.


Get rows from a table and add rows to google charts

Is the javascript part of the same file as the PHP?  If so, you should show them together as a single file, not as separate pieces of code.

Typically, you should have already made a call to the DB to get records before you ever begin rendering things to the browser like you are doing for your javascript.  Keep these pieces of logic separated.  Your page might look more like:

<?php
// not-shown: file bootstrapping logic, if any
$rows = [];
// not shown: your DB logic to retrieve records

if(empty($rows)) {
    // you have no results to work with so perhaps handle this as error condition and exit/redirect.
}
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    // use json_encode to pass data from PHP to javascript literal
    var rows = <?php echo json_encode($rows); ?>;

    //Google Stuff
    google.charts.load('current', {packages: ['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        // Define the chart to be drawn.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Element');
        data.addColumn('number', 'Percentage');
        data.addRows(rows);

        // Set chart options
        var options = {
            title:'Sales',
            titleTextStyle: {color: 'white', bold: true},
            height:300,
            backgroundColor: '#3a3939',
            color: '#fff',
            legend: {textStyle: {color: 'white'}},
            hAxis: {gridlines: {color: 'black'}}
        };

        // Instantiate and draw the chart.
        var chart = new google.visualization.PieChart(document.getElementById('SalesChar'));
        chart.draw(data, options );
    }
</script>

Note my use of json_encode() to serialize the PHP data structure into javascript in the code above. This is the #1 most useful way to interchange data between PHP and javascript. Embrace the power of JSON serialization to simplify data transfer. Dynamically building javascript data structures via PHP string concatenation is a really bad approach.

I would encourage to look at working with mysqli in an object-oriented manner.  There are a lot of legacy procedural PHP code examples out there, and while it is good to understand procedural style, I would venture to guess that you will likely fall into good development habits more easily if you bias yourself towards object-oriented programming for PHP.

Your SQL has some problems:

Don't use SELECT *. It is lazy and a potential point for application fragility.  Why make a developer go look at a database table in order to understand what fields are available to a particular section of code?  Why waste extra bandwidth sending across fields that are not needed in a certain area of code?
You have fallen into a querying-in-a-loop anti-pattern. Almost always, when you see code like this, it should be a red flag to you that perhaps a join is a better option than sending a bunch of individual queries against a database.
You may have a schema problem.  Why work with Sales/Products as a comma-separated list?  Should this be normalized into its own table (potentially with aggregation into comma-separated values if needed for purposes of a given query)?


Validate that a given email address has a whitelisted domain and the address has not already been registered

There are a few things that jump out at me in your code:

public async Task<JsonResult> CheckEmail(string Email)

Email should be email because it is conventional for parameters to be camelCase in C#.

Why are you making a copy of the email address?

string s = Email;

Strings are immutable, you can just use your parameter directly.

This line:

Console.WriteLine(s.Substring(0, idx)); //local half (not needed) e.g myname

First, you should never be using Console.WriteLine in a action method of a controller. Generally, you shouldn't be using it in a web app at all. If you want to debug it, add a log or just step through with an actual debugger using breakpoints.

Second, if you don't need the local half, why do you compute it at all?

Third, you haven't validated that the email address even contains an @. If it doesn't, this line will throw an exception.

Validate your index:

var atCharPosition = email.LastIndexOf('@');
if (atCharPosition == -1)
{
   return Json(data: "Invalid email address");
}

This line is the most worrying:

IEnumerable<Organisation> organisations =  _context.Organisations.ToList();

Is that _context an Entity Framework Data Context? If it is, you're getting all of the organisations back from the database to see whether the domain exists. Let the database do it:

// requires a using System.Linq;
var isValidDomain =  _context.Organisations.Any(o => o.EmailDomain == domain);

Finally, why are you returning a closing anchor tag in this line?

return Json(data: $"Email address already registered</a>");

I can't see any reason why you'd want to return malformed html here.


Hibernate MassIndexer using chained invocation for building a batch job

Make a second level Builder class

long executionId = new MassIndexer()
        .addRootEntities(Company.class, Employee.class)
        .javaSE()
        .entityManagerFactory(emf)
        .jobOperator(jobOperator)
        .start();

long executionId = new MassIndexer()
        .addRootEntities(Company.class, Employee.class)
        .javaEE()
        .start();

class MassIndexer
    MassIndexer addRootEntities(Class<?>...)
    SEBuilder javaSE()
    EEBuilder javaEE()

class MassIndexer.SEBuilder
    long start()
    SEBuilder entityManagerFactory(EntityManagerFactory)
...

I am not that happy with the name and using a constructor for MassIndexer
addRootEntities might go in the "constructor"
javaSE/EE maybe standalone/server or container?


Nested loop with synchronous and asynchronous behavior

First you can make the database container more precise and accessible if you define it like this:

var dbs = [
    { id: 'db1', docs: ['doc1', 'doc2', 'doc3'] },
    { id: 'db2', docs: ['doc4', 'doc5', 'doc6'] },
];

So you can access the database id via db.id and don't need to calculate it with dbId = Object.keys(dbObj)[0]

Second the function's names aren't so good. The names dbIterator, docIterator and merchantIterator tell about HOW they do their work, but they should better tell WHAT they do as it is the case with getDocument.

Third in docIterator you are nesting promises but they are meant for chaining.

Fourth in docIterator the checks if (++docsProcessed >= docsToBeProcessed) are needless because forEach makes sure that all documents will be processed and it will stop if there are no more.

When you are dealing with loops and asynchronous functions you should have a look at the Promise.all method. Provided that merchantIterator does realy nothing more than triggering the next iteration (as you suggested) I think the processing of all databases and documents may look like this:

function processDatabases(dbs) {
    Promise.all(dbs.map(db => {
        var connection = // some config for connection to **db.id**
        return Promise.all(db.docs.map(doc => {
            return getDocument(doc, connection)
                .then(doc => processDoc(doc, connection))
                .catch(err => logger.error(err.message));
        }));
    }))
    .then(() => logger.info('all done'));
}

In this case getDocument and processDoc should reject or throw an Error with an appropriate message.


There are a number of things that I see that may help you improve your code.

Fix typos

There were so many typos in this code that I had to do quite a number of fixes before the code would even compile.  I'd recommend composing the question offline, using a text editor that changes tabs to spaces. Then cut and paste the whole thing into CodeReview.  It will save many people lots of time, including and especially you!

Don't put everything into the constructor

The MeadowGiant class has all of its code in the constructor.  That's not very good design.  Instead, it would be better to instantiate one or more of them and then use member functions to manipulate the object.

Use only necessary #includes

The #include <stdio.h> line is not necessary and can be safely removed.

Don't reseed the random number generator more than once

The program currently calls srand after every call to rand().  This is really neither necessary nor advisable.  Instead, just call it once when the program begins and then continue to use rand() to get random numbers.  Better yet, see the next suggestion.

Consider using a better random number generator

If you are using a compiler that supports at least C++11, consider using a better random number generator.  In particular, instead of rand, you might want to look at std::uniform_real_distribution and friends in the <random> header.

Use constant string concatenation

This code currently has a number of instances that look like this (or would if the typos were fixed):

std::cout << "You have slain the goblin!\n"
    << "You head towards the chest and take the spoils\n"
    << "of battle!\n";

This calls the << operator three times.  Instead, you could write this:

std::cout << "You have slain the goblin!\n"
    "You head towards the chest and take the spoils\n"
    "of battle!\n";

This only calls << once.  The compiler automatically concatenates the string literals together.

Avoid using goto

Having a proliferation of goto statements is usually a sign of bad design.  Better would be to eliminate them entirely -- it makes the code easier to follow and less error-prone.  In this code, it's probable that you could use a loop instead:

for (goblinHP = 10; goblinHP > 0; ) {
    // code to implement goblin attack goes here
}

Use C++-style includes

Instead of including stdlib.h you should instead use #include <cstdlib>.  The difference is in namespaces as you can read about in this question.

Eliminate unused variables

Unused variables are a sign of poor quality code, and you don't want to write poor quality code. In this code, ability is unused.  Your compiler is smart enough to tell you about this if you ask it nicely.


Argggh, my eyes burn!

SQL Injections

You should understand SQL injections.  This code is likely to promote SQL injections.  Read up about prepared statements.  It looks like you are probably passing in a mysql_* function as a string.  This stops you from using prepared statements.

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

One Size Fits None

Your function is overly complex.  It should be broken into methods for each action.  This will remove the need for the big switch and if statements and make it more readable.  Your code will be easier to test.

This also causes you to have a variable function call $Db_Function($sql, 0, 0, 0);.  It is easy to have errors by calling non-existent functions with this.

Response To Edit: It looks better with separate functions now.

Method Naming

You really have an awful naming scheme.  Is this dictated to you by your bosses?  Personally I already think they are silly for wanting a class like this that would promote SQL Injections.  You have a mixed pascal case name aaaa_Bbbb_Cccc?  Sane choices are camelCase, UpperCamelCase, Pascal_Case, lower_pascal_case.

The methods should not have sql_ preceding them.  Their usage should be like this:

$sql = new sql; // Or whatever your class is called.
$sql->insert(/* params go here */);

It should be obvious from the object that you create that you have an sql type object.  The sql_ in front of the method names then just gets in the way.

Unused Parameter

The sql_delete method does not use the $Fields parameter and it should therefore be removed.

Magic Numbers

Magic 0's and 1's are a sign of poor design.

Consistency

Please find a consistent way to name variables.  $sql, $fields, $value are in the minority.  I dislike Pascal_Case for variables in PHP, but inconsistency is even worse.


1) I believe it is not a good practice to give variables one-letter names. Storyboard story = ...
2) I believe you can specify Duration in ColorAnimation only. And do not set it for Storyboard.
3) I would introduce variable for ColorAnimation because s.Children[0] looks weird to me when I know that it is ColorAnimation.
4) Strangely you are using 0.1f where parameter is double anyway.
5) I would consider using object and collection initializers for Storyboard.Children.
6) Optionally I would think on removing storyboard variable and start it immediatly after constructing.

Result: my code looks differently, but readability changes are subjective:

Line TargetLine = line;

var duration = new Duration(TimeSpan.FromSeconds(0.1));
var colorAnimation = new ColorAnimation(Colors.LightGreen, duration);
Storyboard.SetTarget(colorAnimation, TargetLine);
Storyboard.SetTargetProperty(colorAnimation, new PropertyPath("Stroke.Color"));

new Storyboard {Children = {colorAnimation}}.Begin();


Duplicating Excel-workbook, and transferring data

Since you use continue in the if clause, you can get rid of the else part and save a level of indentation.
You can use a list-comprehension to build the list of r_value: [worksheet.cell_value(row + 1, 1) for row in range(3)].
You can iterate directly over the content of r_value to set it back:

for row, value in enumerate(r_value, 3):
    s.write(row, 1, value)

I don't think you need to copy the template first and modify it after. You may be able to open the template and then save it using the new filename.
You can use a second parameter with a default value to hold the name of the template.

Proposed improvements:

import os

from xlrd import open_workbook
from xlutils.copy import copy

def duplicate_and_transfer(path, template_name='Template.xlsx'):
    template = os.path.join(path, template_name)

    for filename in os.listdir(path):
        if filename == template_name:
            continue

        filepath = os.path.join(path, filename)
        excel_file = open_workbook(filepath)
        worksheet = excel_file.sheet_by_index(0)
        new_filename = worksheet.cell_value(5,2)
        new_filepath = os.path.join(path, new_filename + '.xls')
        values = [worksheet.cell_value(row + 1, 1) for row in range(3)]

        rb = open_workbook(template)
        workbook = copy(rb)
        worksheet = workbook.get_sheet(0)
        worksheet.write(7, 2, new_filename)
        for row, value in enumerate(values, 3):
            worksheet.write(row, 1, value)

        workbook.save(new_filepath)

if __name__ == '__main__':
    duplicate_and_transfer(r'C:\Users\Stewie\Documents\excel_folder')

You may as well be able to open the template once and save it several times.

Lastly, if you have troubles working with XLSX files, you may want to try openpyxl instead:

import os

from openpyxl import load_workbook

def duplicate_and_transfer(path, template_name='Template.xlsx'):
    template = load_workbook(os.path.join(path, template_name))

    for filename in os.listdir(path):
        if filename == template_name:
            continue

        workbook = load_workbook(os.path.join(path, filename))
        worksheet = workbook.worksheets[0]

        new_filename = worksheet['C6'].value
        template['B8'] = new_filename
        new_filepath = os.path.join(path, new_filename + '.xlsx')

        # Using double unpacking as the ranges will return a 3-tuple of 1-tuple
        for (src,), (dest,) in zip(worksheet['B2:B4'], template['B4:B6']):
            dest.value = src.value

        template.save(new_filepath)

if __name__ == '__main__':
    duplicate_and_transfer(r'C:\Users\Stewie\Documents\excel_folder')


Find intersections of overlapping intervals

Because the intervals are already sorted by start time, you can begin the inner loop at j = i + 1 and simplify the if test and drop the call to max:

if (intervalj.getStart() < intervali.getEnd()) {
    hashSet.add(new OverlapCoord(intervalj.getStart(),
                                 Math.min(intervali.getEnd(), intervalj.getEnd())));
}

However, is it possible for three intervals to overlap?

[===============]
        [=============]
             [=============]

If so, this will produce three overlaps:

        [=======]
             [==]
             [========]

Is this desired? What about if the first and third intervals above butted up against each other rather than overlapping themselves?

        [=======]
                 [====]

Should all these cases be merged into the same single overlap?

        [=============]

Here are some better variable names to consider:

intervalList -> intervals
hashSet -> overlaps
intervali -> leftInterval or lowerInterval
intervalj -> rightInterval or upperInterval

I find it's best to leave the type of collection out of the name. First, it makes it easier to change later. And second, you can see it and in any IDE hover over the method to see the required type. I might even drop the Interval suffix from the last two above since this method only deals with intervals.

Finally, there's no reason this method couldn't accept a null list. It should respond just as it does when the list is empty: return an empty set.

if (intervals == null || intervals.isEmpty()) {
    return Collections.<OverlapCoord>emptySet();
}


A more efficient way (in terms of lines of code) of doing the same thing would be to use this code. The code declares a new dictionary countMap and then loops over the items in aDict. The first loop increases the entry in countMap that corresponds to the current value of aDict which is being evaluated and then increases the value in countMap if it's already been found but if it hasn't then it sets the corresponding value in countMap to 0 and then increments the value (initially setting every value to 1 or if it's already been found then incrementing it). The second loop only adds values within countMap to the list uni if there values equal 1 (if the current entry is unique).

Taken from here:

aDict = {
        0: 1,
        1: 2,
        2: 2,
        4: 2,
        5: 2,
        6: 3,
        7: 2}

countMap = {}
for v in aDict.values():
    countMap[v] = countMap.get(v,0) + 1
uni = [ k for k, v in aDict.items() if countMap[v] == 1]
print(uni)


Automatically generate a thunderbird importable contacts file for all employees

Variables

I like that you're using Option Explicit. It helps prevents "easy" mistakes from typos. I don't like that you declare all your variables in a block and I somewhat dislike the naming scheme you use:

I also used to declare all variables in a block at the start of a procedure. It's significantly easier to declare them as close as possible to their usage, though. It especially allows you to limit their scope (preventing name-conflicts and inappropriate reuse), and it lowers the "cognitive load" because you don't need to keep in mind which variables exist and which type they have.

Another thing I noticed is that you're (possibly unintentionally) mix German into your variable names: tel and telMobi would probably be declared as phone and mobilePhone by a native speaker.

Additionally the casing is inconsistent. SQL could be sqlQuery, Email should just be email and Name is an array, which should accordingly be names.

Furthermore you use some hungarian notation (oFile), but don't do that consistently (as for oFso, oRs, oDb). Since you specifically mark objects (that need to be assigned to with Set), you should mark all objects the same way. Alternatively you can grab the Rubberduck VBE Addin (which I am involved in maintaining), that has an inspection warning you when you assign to an Object-typed variable without the Set keyword making the hungarian notation useless.

Last but not least as far as I can tell bigDelim will never change. I suggest you move it from a Sub-scoped variable into a module-scoped constant.

Responsibilities

Currently this sub does a few things:

Prompt the user for confirmation
Validate the provided input (namely the output path)
Run a SQL-Query against a database
Write the Query results into a file
(output a success message)

Each of these steps could probably be extracted into it's own method. This allows us to break down the procedure into "manageable" steps, reducing cognitive load and simplifying maintenance.

Semantics:

Some minor semantic issues I think are worth fixing:

You're late-binding the Scripting.FileSystemObject. I think that is a bad decision, because it means you can only declare fso as Object and accordingly lose all the help that the VBE can provide you with (autocomplete). That type should be available on all systems that this code will ever run on. No need to late-bind this.
the Name() you're using is a little bit messy. I'd prefer to have a firstName and a lastName to clarify usage. It should be possible to assign them as follows:

Dim split() As String
firstName = split(1)
lastName = split(2)

Setting objects to Nothing after usage is the same as setting Objects in java to null after usage. In my experience it's more of a hassle than the benefits you gain from it. When the object references go out of scope they're collected away anyways. I'd leave that part out :)


It can also be written in "one line" using regular expression:

window.location = window.location.hostname.replace(
    /^(.*)\.school\.edu$/,
    "ftp://ftp.school.edu/public/$1"
);

I believe in this case regular expression expresses the intent more clearly than using indexOf and string slicing, though tastes may vary.


Code:

// CTors / DTor: This comment doesn't add anything that we can't see from the code.

Sometimes comments like this denote sections or regions of code in a file, but without consistently doing this for all the code, we don't know where the "constructor / destructor" section ends. I'd suggest just removing the comment.
Sequencer(std::string const first_frame_in): There's little benefit to making function arguments that are passed by value const. It doesn't affect the caller, and makes the function signature harder to read.

Perhaps this should be a const& though?
When we have lots of member variables in a class, adding an m_ prefix on the names (e.g. m_current_frame) helps to distinguish them from local variables or function arguments.
first_frame_name, match_pattern, and first_frame_regex_results are all unused after the constructor, so they could just be local variables rather than members.
tmp_num and tmpname are not informative names. They should also be local variables since they are each used in only one function.
Presumably negative frame numbers can't exist. If this is the case we should be using an unsigned integer type, not a signed one.
We should check the result of the regex search and handle an error (since presumably this is going to be a user specified string).
The regex captures "zero or more" digits, but we don't check that we got a match before trying to convert the frame number. Perhaps we should require "one or more" digits / letters when matching.
Perhaps the regex pattern should use the specified file_delim too.
Using a chain of + operators for std::strings tends to create a lot of temporary strings. Using std::string::append is likely to be faster, especially if we reserve() the memory we need first.
We can add the padding digits in one operation by using std::string::insert.

Design:

I'd suggest grouping the information extracted from the first frame filename into a struct. We can then put the regex search and data extraction into a separate function, and more easily use the constructor initializer list.
Unless there's a particular reason for it, I wouldn't try finding the last frame inside the Sequencer class. It's probably simpler to restrict the "sequencer" to only generating filenames, and leave checking if the file exists for code that does actual processing.
Perhaps something like FrameFilenameGenerator might be a more accurate name than Sequencer?
We can effectively use the same code to generate the input and output filenames.
If we let the user keep track of the current frame, our generator can generate the filename for any requested frame, and doesn't have to keep track of the frame itself.

So applying the above points, we might get something like:

#include <regex>
#include <string>
#include <experimental/filesystem>

class FrameFilenameGenerator
{
public:

    // note:
    // `first_frame_filename` isn't copied, so we only need a const&
    // `file_delim` is a "sink argument" (i.e. we store a copy in the class), so we take the argument by value and move it into place.
    FrameFilenameGenerator(std::string const& first_frame_filename, std::string file_delim = "."):
        m_file_delim(std::move(file_delim)),
        m_info(get_first_filename_info(first_frame_filename))
    {

    }

    // note: we should probably be more careful with the frame offset!
    // first_frame_number + frame_offset could overflow!
    std::string make_filename(std::uint32_t frame_offset, std::string const& output_suffix = "") const
    {
        auto result_size =
            m_info.prefix.size() +
            output_suffix.size() +
            m_file_delim.size() +
            m_info.digit_padding +
            m_file_delim.size() +
            m_info.extension.size();

        auto result = std::string();
        result.reserve(result_size);

        result.append(m_info.prefix);
        result.append(output_suffix);
        result.append(m_file_delim);
        result.append(frame_number_to_string(m_info.first_frame_number + frame_offset, m_info.digit_padding));
        result.append(m_file_delim);
        result.append(m_info.extension);

        return result;
    }

private:

    struct FirstFilenameInfo
    {
        std::string prefix;
        std::uint32_t first_frame_number;
        std::size_t digit_padding;
        std::string extension;
    };

    static FirstFilenameInfo get_first_filename_info(std::string const& first_frame_filename)
    {
        auto result = FirstFilenameInfo();

        const auto match_pattern = std::regex("([a-zA-Z]*).([0-9]*).(\\w{3})");
        std::smatch regex_results;

        if (!std::regex_search(first_frame_filename, regex_results, match_pattern))
            throw std::runtime_error("First frame filename does not meet the required format!");

        result.prefix = regex_results[1];

        if (regex_results[2].length())
        {
            result.first_frame_number = std::uint32_t{ std::stoul(regex_results[2]) };
            result.digit_padding = regex_results[2].length();
        }

        result.extension = regex_results[3];

        return result;
    }

    static std::string frame_number_to_string(std::uint32_t frame_number, std::size_t digit_padding)
    {
        auto result = std::to_string(frame_number);

        if (result.size() >= digit_padding)
            return result;

        auto const zeros_needed = (digit_padding - result.size());
        result.insert(result.begin(), zeros_needed, '0');

        return result;
    }

    std::string m_file_delim;
    FirstFilenameInfo m_info;
};

#include <iostream>

int main()
{
    std::string image_filename = "prefix.00030.ext";
    auto generator = FrameFilenameGenerator(image_filename);

    for (auto i = 0u; i != 20u; ++i)
    {
        auto in = generator.make_filename(i);
        auto out = generator.make_filename(i, "_signature");

        //if (!std::experimental::filesystem::exists(in))
        //  break;

        std::cout << in << " -> " << out << "\n";
    }

    return EXIT_SUCCESS;
}


Here's what I came up with:

var addNestedPropToObj = function (obj, name, value) {
    var path = name.split('.'),
    current = obj,
    len = path.length - 1,
    i = 0;
    for (; i < len; i++) {
        current[path[i]] = current[path[i]] || {};
        current = current[path[i]];
    }
    if ( 0 < path[i].indexOf( "[]" ) ) {
        name = path[i].replace('[]', '');
        current[name] = current[name] || [];
        current[name].push(value);
    } else {
        current[path[i]] = value;
    }
    return obj;
};
jQuery.fn.serializeObject = function () {
    var o = {},
    a = this.serializeArray(),
    i = 0,
    len = a.length;
    for (; i < len; i++) {
        o = addNestedPropToObj(o, a[i].name, a[i].value);
    }
    return o;
};

Demo and test cases

Tips:

Always try to separate most of the logic from the plugin into small testable functions.
Use a regular loop instead of the $.each().
String.prototype.split() returns an array of the entire string if a match isn't found. So the else condition isn't required.

// not needed
else {
    o[this.name] = this.value;
}

Instead of checking to see if you're at the end of the loop, iterate to path.length - 1 then afterwards perform the statement, current[path[i]] = this.value;.

As for the array format contained within the name property, for simplicity I suggest that the array notation should be an endpoint where the value is the push to the current property. So for a value to a added to an array, then [] must be at the end of the name.

Here's an example:

var func = function( str ){
    return JSON.stringify( addNestedPropToObj( {}, str, 1));
};
func("a[].b") === '{"a[]":{"b":1}}';
func("a.b[]") ===  '{"a":{"b":[1]}}';

Seen as an array: a[] or a.b[]

Seen as a string: a[b], a[b.c]


addition of two list elementwise with abortion if condition satisfied python

Does it make sense (in the context of your program execution) to split your task into two stages?
Check for the presence of (1, 1) in zip(lis1, lis2), and if False, then pass the generator to the array: array('H', (i + j for i, j in zip(lis1, lis2))).