The input numbers \$ A, B, N \$ can be as large as \$ 10^{12} \$, which
means that a Java int (which is a 32-bit signed integer) is not large
enough to hold all possible values, you should use long instead.

You also do not reduce the sum modulo 1000000007, as required.

The main function can be simplified by calculating the output for each
input line as it is read, this makes the queries array obsolete.

The function sumBetweenRange does not describe what the function actually does.
Something like sumOfIntiNumbersInRange or – using the mathematical term –
sumOfCoprimeNumbersInRange might be a better choice.

The main function would then look like this:

public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

    Scanner console = new Scanner(System.in);

    int queries = Integer.parseInt(console.nextLine());

    for (int i = 0; i < queries; i++) {
        long N = console.nextLong();
        long A = console.nextLong();
        long B = console.nextLong();

        long result = sumOfCoprimeNumbersInRange(A, B, N);
        System.out.println(result);
    }
}

Your method to determine if two numbers have a common factor is
very slow, it does trial division for all numbers between 2 and
no1/2. That can be improved slightly by using sqrt(no1) as the upper bound,
but one can do much better.

An efficient method is the
Euclidean algorithm
which determines the
greatest common divisor
of two integers. Two integers \$ a, b \$ have no common divisor exactly if \$ \gcd(a, b) = 1 \$.

There are many known Java functions for calculation the
greatest common divisor, see for example https://rosettacode.org/wiki/Greatest_common_divisor#Java.
Here is a simple (tail-recursive) implementation:

public static long gcd(long a, long b) {
    if (b == 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}

Then sumOfCoprimeNumbersInRange() can be implemented as

private static final int MOD = 1000000007;

// Compute the sum (modulo MOD) of all numbers in the range a...b which are coprime to N.
private static long sumOfCoprimeNumbersInRange(long a, long b, long n) {
    long sum = 0;

    for(long i = a; i <= b; i++){
        if (gcd(i, n) == 1) {
            sum = (sum + i) % MOD;
        }
    }
    return sum;
}

This is already much faster than your original implementation:
For \$ N=100000, A=10000, B=90000 \$ I measured on a
1.2 GHz Intel Core m5 MacBook:

Your code: 3 seconds.
GCD-based solution: 0.165 seconds.

But it may be not fast enough for the full range of numbers up to
\$ 10^{12} \$. A very elegant and efficient approach using the
Inclusion-Exclusion Principle is explained in

How to count co-prime to n in a range [1,x] where x can be different from n?

on Stack Overflow.
Let us consider \$ N = 300 = 2^2  \cdot 3 \cdot 5^2 \$ as an example. The distinct prime
factors are \$ 2, 3, 5 \$, and to compute the sum of all numbers in some range which
are coprime to \$ N \$ one proceeds as follows:

Compute the sum of all numbers in the range.
Subtract the sum of all multiples of \$ 2, 3 \$, and \$ 5 \$ in the range.
Add the sum of all multiples of \$ 2 \cdot 3, 2 \cdot 5 \$, and \$ 3 \cdot 5 \$ in the range.
Subtract the sum of all multiples of \$ 2 \cdot 3 \cdot 5  \$ in the range.

Note that apart from the factorization, no trial divisions are required anymore, only
multiplications.

First we need a function to get the distinct prime factors of a given number,
e.g. the function in Finding out the prime factors of a number,
modified slightly to return only distinct prime factors:

// List of all distinct prime factors of n.
static List<Long> primeFactors(long n) {
    List<Long> factors = new ArrayList<Long>();
    long md = 2;
    if (n % md == 0) {
        factors.add(md);
        do {
            n /= md;
        } while (n % md == 0);
    }
    md = 3;
    while (md <= java.lang.Math.sqrt(n) + 1) {
        if (n % md == 0) {
            factors.add(md);
            do {
                n /= md;
            } while (n % md == 0);
        }
        md += 2;
    }
    if (n > 1) {
        factors.add(n);
    }
    return factors;
}

Now the "challenge" is to translate the Inclusion-Exclusion approach to a
recursive function, and that could look as follows:

// Sum of all numbers 1...k, computed modulo MOD.
private static long sumUpTo(long k) {
    k = k % MOD; // Otherwise the following multiplication can overflow.
    let sum = k * (k+1) / 2;
    return sum % MOD;
}

// Sum of all numbers (modulo MOD) in a...b which are divisible by k, but not
// by any multiple of k with factors in the primes list:
private static long inclExcl(long a, long b, long k, List<Long> primes) {

    // Sum of all numbers in 1...b which are divisible by k:
    long s1 = sumUpTo(b / k) * k;
    // Sum of all numbers in 1...(a-1) which are divisible by k:
    long s2 = sumUpTo((a-1) / k) * k;

    long sum = (s1 - s2) % MOD;

    for (int idx = 0; idx < primes.size(); idx++) {
        // The magic recursion!
        sum = (sum - inclExcl(a, b, k * primes.get(idx), primes.subList(idx + 1, primes.size()))) % MOD;
    }

    return sum;
}

private static long sumOfCoprimeNumbersInRange(long a, long b, long n) {

    List<Long> primes = primeFactors(n);

    long sum = inclExcl(a, b, 1, primes) % MOD;
    if (sum < 0) {
        sum += MOD;
    }
    return sum;
}

For a (hopefully) better understanding of the implementation, here is how the
inclExcl function is called recursively if \$ N = 300 = 2^2  \cdot 3 \cdot 5^2 \$
as above (showing only the relevant arguments):

k=1, primes=[2, 3, 5]
    k=2, primes=[3, 5]
        k=6, primes=[5]
            k=30, primes=[]
        k=10, primes=[]
    k=3, primes=[5]
        k=15, primes=[]
    k=5, primes=[]

This is again much faster, because we have to iterate and recurse only over the distinct prime factors of \$ N \$
(and there can be no more than \$ 11 \$ prime factors if \$ N \le 10^{12} \$).
There is no iteration over the range  \$ A \ldots B \$ anymore.

Benchmark: For \$ N=96996900, A=100, B=96996000 \$:

GCD-based solution: 26 seconds.
Inclusion/exclusion-based solution: 0.181 seconds.


C++ password generator with WinAPI clipboard function

Out Of Bounds Problem

const int to = chars.size();
...
std::uniform_int_distribution<int>  distr(from, to);

uniform_int_distribution - Produces random integer values i, uniformly distributed on the closed interval [a, b]

So if chars were "ABC", size is 3, and the range of values returned would be [0,3]
 = 0,1,2 and 3. 3 is an invalid index. Therefore 'to' should be chars.size() - 1.

Error Checking

You should check the return values on system functions like OpenClipboard.

if (!OpenClipboard())
{
    auto lastError = GetLastError();
    // get error message, throw exception?
}

GlobalFree

From MSDN - If SetClipboardData succeeds, the system owns the object identified by the hMem parameter. The application may not write to or free the data once ownership has been transferred to the system

So it looks like a GlobalFree call is not needed. You should free it though if SetClipboardData (or any of the other system calls) fails.


The key to solving this problem (and many others) is using memoization: The numbers of the collatz sequence converge in a kind of tree-like structure. Once you have calculated the value of, say collatz(100) on one path, you do not need to calculate it again when you encounter it again on another path.

One way to do this would be to have (a) a cache and (b) a list of all the numbers on the current path. As soon as you encounter a number that is already in the cache, go your path backwards and add all the numbers to the cache.

cache = {1: 1}
def collatz(n):
    path = [n]
    while n not in cache:
        if n % 2:
            n = 3 * n + 1
        else:
            n = n / 2
        path.append(n)
    for i, m in enumerate(reversed(path)):
        cache[m] = cache[n] + i
    return cache[path[0]]

Another, maybe more elegant way would be using recursion and a decorator function. You can define a @memo decorator and use it again and again for all sorts of function you want to apply memoization to. This decorator automatically replaces your function with a version that looks in the cache, first.

def memo(f):
    f.cache = {}
    def _f(*args):
        if args not in f.cache:
            f.cache[args] = f(*args)
        return f.cache[args]
    return _f

@memo
def collatz(n):
    if n == 1:
        return 1
    if n % 2 == 0:
        return 1 + collatz(n / 2)
    if n % 2 == 1:
        return 1 + collatz(3 * n + 1)

In both cases, call like this and after a few seconds you should get your result.

print(max(range(1, 10**6), key=collatz))


First of and maybe a bit off-topic. The is this feature in all modern browsers now: https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange and the support is good: http://caniuse.com/hashchange

Then the function. Perosnally I would use an anonymous function without storing it in a var first. I would pass in the hs 'unparsed' and simply pass the hash to the function instead of an array. It is snipplet that checks or the hash changes and should thus not be concerned on what the symbols in the hash mean.

Also, instead of using the setTimeOut and calling it allover your code. Simply use the setInterval function.


Missing copy constructor & assignment operator
Because you're handling raw pointers and owning memory through them, you must implement the rule of three. Otherwise you will get double deletes after some one copies your allocator.
Use of reset()
By the looks of it, this class is developed for a very specific purpose. OP hasn't told us what the purpose is unfortunately. And the class is kind of dangerous.
Calling reset() will conceptually invalidate any pointers returned by construct(...) but they will continue to be accessible and eventually overwritten with new data until the ArenaAllocator is destroyed. If some piece of code is wrongly holding a pointer to a data block after the reset this should be a bug but static and dynamic code analysis tools will likely not detect this because the pointer is still valid. Neither will you get a crash, just a quiet possibly wrong result.
Although safe if used correctly in a single threaded environment, I'm afraid that it is easy to make a mistake with this class.
Ewww! Raw new/delete
Instead of having a custom allocator policy (BlockProvider) you could use the standard std::allocator for example. By doing this you can now use std::shared_ptr with the allocator provided and get rid of the usage of raw new/delete which is bad, yet you still have the option of providing your own allocator. Don't worry, the overhead of using std::shared_ptr is minimal in this case because your blocks are large.
Overall
I don't see any obvious bugs besides the missing rule of three.
Although custom memory management has its uses, you really do want profiling data to back up the added complexity and failure points of rolling your own memory management. Unless you have a strong reason for custom management that seriously outweighs the reduction in efficacy of code analysis tools and increase in risk for bugs, I would not recommend rolling your own. You have to be sure the extra headache is worth it.
Also note, that if your type is a POD then operator delete will not call any destructors (there aren't any!). In fact I would expect various standard library functions to not call destructors on trivially destructible types any way. Apparently at least GCC does this.
If you have a piece of code that must rapidly allocate and throw away memory at a pace where the standard allocator isn't fast enough, then you might want to consider changing that code to re-use the same memory area instead. This is even faster than writing a custom allocator, solves the problem at the root and doesn't introduce near as much hair loss as custom memory management.
If you just need a lot of fixed size objects quickly and contiguously, I would consider using a fixed item size memory pool and overloaded new/delete for the class and make it transparent. You can do some very efficient reclamation and allocation when items are of fixed size.


Mini JavaScript thread pool with maximum number of concurrently running tasks

Some suggestions:

It's not entirely clear until getting to the bottom of the class what the queue array holds. Maybe call it something more precise like unstartedTasks or unstartedTasksQueue.

You can return early to avoid nested indentation - cutting down on unnecessary indentation can make it clearer exactly which block a } at the end corresponds to. For example, backgroundRunner could be made to be:
backgroundRunner() {
  if (!this.queue.length) {
    return;
  }
  // lots of code

The scheduled for later section looks superfluous since unstarted tasks will be run immediately upon the completion of a task, due to the
task(id).finally(() => {
  this.runningTasks--;
  this.backgroundRunner();
});

When you want to remove the first element from an array and use it, use shift, not splice. This:
const [[task, id]] = this.queue.splice(index, 1);

can be
const [task, id] = this.queue.shift();

Unless the insertion index of the task needs to be saved, you could simplify the queue by incrementing and using the id not when the task is pushed, but when the task gets executed. This way the queue only needs to be an array of functions, not an array of [task, id]s.

See below for the version I'd prefer, if a class-based implementation is required. I use # to clearly distinguish what's exclusively private methods and properties from a public method:

class TaskPool {
  #unstartedTasksQueue = [];
  #runningTaskCount = 0;
  #id = 0;
  #runningTaskLimit;
  constructor(runningTaskLimit) {
    this.#runningTaskLimit = runningTaskLimit;
  }
  insertTask(fn) {
    if (this.#runningTaskCount === this.#runningTaskLimit) {
      this.#unstartedTasksQueue.push(task);
    } else {
      this.#startTask(fn);
    }
  }
  #startTask(fn) {
    this.#runningTaskCount++;
    fn(this.#id++).finally(() => {
      if (this.#unstartedTasksQueue.length) {
        this.#startTask(this.#unstartedTasksQueue.shift());
      } else {
        this.#runningTaskCount--;
      }
    });
  }
}

function task(id) {
  //create an ID
  return new Promise((resolve) => {
    console.log('running task #', id);
    setTimeout(() => {
      console.log('done running task #', id);
      resolve();
    }, 4000);
  });
}

const pool = new TaskPool(3);
for (let i = 0; i < 5; i++) {
  pool.insertTask(task);
}

But all the private methods and properties, despite making the code's intent a bit clearer, can look a bit ugly. Since the external user of the class is only interfacing with 2 things (the constructor, and the run method), I'd prefer to make a function instead of a class, which returns the run (or, as I've named it, insertTask) method, so as to rely on the closure instead of on #s:

const makeTaskPool = (runningTaskLimit) => {
  const unstartedTasksQueue = [];
  let runningTaskCount = 0;
  let id = 0;
  const startTask = (fn) => {
    runningTaskCount++;
    fn(id++).finally(() => {
      if (unstartedTasksQueue.length) {
        startTask(unstartedTasksQueue.shift());
      } else {
        runningTaskCount--;
      }
    });
  };
  return (fn) => {
    if (runningTaskCount === runningTaskLimit) {
      unstartedTasksQueue.push(task);
    } else {
      startTask(fn);
    }
  };
};

function task(id) {
  //create an ID
  return new Promise((resolve) => {
    console.log('running task #', id);
    setTimeout(() => {
      console.log('done running task #', id);
      resolve();
    }, 4000);
  });
}

const insertTask = makeTaskPool(3);
for (let i = 0; i < 5; i++) {
  insertTask(task);
}


wrapper class for random access iterator to hide template method implementation from header file

I’m going to answer your questions first, then get into the actual code review.
Questions
How can “it” [the code/the design] be improved?
I’ll get into details in the review, but the broad answer to this question is: I don’t know.
The reason I don’t know is two-fold:

you don’t provide even a single comment to explain the logic of what this code is doing; and
you don’t provide even a single example to show what the intended usage is.

Without any clue about what the code is supposed to be doing or how it’s supposed to be used, how can anyone answer the question of whether it can be improved? Maybe it’s absolute perfection; maybe there is no possible way to make this code any better for what it was written for. Or maybe it’s the absolute worst possible solution for what it’s for. All that depends on what it’s for.
Obviously I’m going to try to review the code anyway, but to do so I’ll have to make a lot of assumptions about what you mean in your very brief, wildly unclear description of what the purpose of this wrapper is. I may guess wrong—that’s very likely, in fact—which means a lot of what I say may be incorrect, or even gibberish. For that I apologize, but it can’t be helped; I have to work with what I have.
So I guess one way to answer the question is: documentation… lots of documentation, and some example usage code. For something this small, there’s really no reason one couldn’t provide a complete, compile-able test program (even if you want to keep that algorithm secret; you could just include a stub or dummy implementation just for the purposes of illustration and testing).
Do I have to use the rule of 3 or 5 in such case?
Yes. You always✻ have to. That’s why they call it a “rule”.
✻ (Okay, technically the rule says “almost always”. But that just means that unless you’re 100% sure you don’t need to follow the rule, then the answer is yes.)
The only question is which rule: 3, 5, or 0?
Unfortunately, I can’t really give a coherent answer to that without making some guesses. So… just looking at what you’ve got there, and going by your description, I don’t… think… you need the rule of 3 or 5 (that is, you can use the rule of 0).
BUT…
I suspect that if the intended usage is more than what you explicitly say it is—that is, if I have to guess at practical usage of this wrapper, at least in my imagination—then the answer is that you do need to use the rule of 3 or 5. In fact, I think this wrapper is dangerously broken, and I’ll explain why in the review.
Does it make sense to create a generic iterator wrapper class and a specialization for each iterator type?
Absolutely. It’s not a bad idea at all. In fact, I wouldn’t be surprised if there were already “type-erased iterator” types out there. You could even make an argument for including one in the standard library. It would be hella useful.
Now, does it make sense to do it this way? Mm, maybe? Impossible to say for sure. For the general use case I’d say no, but for the specific use case of random-access iterators only—with some additional caveats on both the iterator and algorithm characteristics—then maybe.
So, onto the code review.
Code review
I’m going to skip the type traits, because I’ll talk about them when we get to the constructor that uses them.
template <typename T>
class WrapperRandomAccessIterator

Okay, so, here’s the first point of confusion. The type is called WrapperRandomAccessIterator… but it doesn’t look like you’re actually wrapping a random-access iterator. It looks like you’re trying to create a random-access iterator (actually, technically a contiguous iterator, but if you’re still stuck with C++11, then you don’t have that concept yet—seriously, though, who’s still using C++11 in 2020… almost 2021!) to a value sequence, and you’re trying to do so by stealing the value out from under a random-access iterator, and creating a pointer directly to it.
The point is… the name is misleading. This is not an iterator wrapper. It does not wrap an iterator. It just transforms an iterator to a pointer.
using this_type = WrapperRandomAccessIterator<T>;

As type aliases go, this is really… kinda useless. So long as you’re inside the class body, you can omit the template arguments. Sure WrapperRandomAccessIterator is a little longer than this_type… but you really shouldn’t need to repeat it so often that it becomes a problem.
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;

These are all okay, but I would suggest defining value_type as:
using value_type = typename std::remove_cv<T>::type;

This is to bring it in line with the way people expect to use value_type. If you have a case like this…:
template <typename Iterator>
void max_value(Iterator first, Iterator last)
{
    using type = typename iterator_traits<Iterator>::value_type;

    type val = *first;

    while (++first != last)
        if (*first > val)
            val = *first;

    return val;
}

// used with:
const vector<string> vec{"string1", "string2", ... };

string v = max_value(vec.begin(), vec.end());

… you would normally expect this to work because val should be a copy of whatever *first references, and that copy is not const. (And that would be true if you’d just used auto instead of type.) But with your WrapperRandomAccessIterator, it won’t work, because value_type will be const string, not string.
(It’s correct to use plain T for pointer and reference, because that makes them const string* and const string&… which is what you want.)
template <typename RandomAccessIter, typename  = typename
        std::enable_if<iter_same_category<this_type, RandomAccessIter>() &&
                iter_same_value_type<this_type, RandomAccessIter>()>::type>
constexpr explicit WrapperRandomAccessIterator(RandomAccessIter iter)
    : ptr_(&*iter)
{}

Now, here’s where the problems start. What exactly is the purpose of iter_same_category and iter_same_value_type? Let’s look at the first one to show you what I mean:
iter_same_category<this_type, RandomAccessIter>

Now, this expands to:
std::is_same<
    typename std::iterator_traits<this_type>::iterator_category,
    typename std::iterator_traits<RandomAccessIter>::iterator_category>

And this_type is just WrapperRandomAcessIterator<T>. But why all the shenanigans going through iterator_traits to get the iterator_category of this_type? There’s no mystery; it’s iterator_category. typename std::iterator_traits<this_type>::iterator_category is always iterator_category.
So you could just do:
std::is_same<
    iterator_category,
    typename std::iterator_traits<RandomAccessIter>::iterator_category>

… and there’s no need for iter_same_category at all.
Same goes for iter_same_value_type.
That gives:
template <
    typename RandomAccessIter,
    typename = typename std::enable_if<
        std::is_same<
            iterator_category,
            typename std::iterator_traits<RandomAccessIter>::iterator_category>()
        && std::is_same<
            value_type,
            typename std::iterator_traits<RandomAccessIter>::value_type>()>::type
>
constexpr explicit WrapperRandomAccessIterator(RandomAccessIter iter)
    : ptr_(&*iter)
{}

Also, iterator_category is always going to be std::random_access_iterator_tag. That’s kinda the point of the class.
To be safe, it might be wise to use remove_cv on the RandomAccessIterator’s value_type. You shouldn’t need to, because most well-behaved containers and iterators will already have removed the const/volatile… but it pays to be safe, just in case. (I think, for example, there was a bug in the standard in C++11 that raw pointers didn’t behave properly.)
There is another nasty little bug lurking here with types that overload the address-of operator (unary operator&). To avoid that, you should use std::address_of(). Note that means you can’t be constexpr anymore in C++11, because address_of() wasn’t constexpr until C++17, but… . Can’t be helped. constexpr wasn’t really well-supported in C++11.
But even in C++11, this can be noexcept, and there’s no reason it shouldn’t be.
operator* is okay, though it too should be noexcept. And it should probably be const. You’re not changing the iterator (wrapper) with this function, or with returned value (which is a pointer to something else entirely, not the iterator). That is why the next function is superfluous.
// Warning says "const has no effect on type reference"
const T& /*reference*/ operator*() const
{
    return *ptr_;
}

Okay, to understand what this warning is telling you, I first have to break your misconception of const. const (and volatile, for that matter), does NOT apply to what’s on its RIGHT; it applies to what’s on its LEFT.
In other words, const T is WRONG. T const is correct. This is the subject of religious fights in the C++ community, but there is an objectively correct answer, and it really matters… as you’ve discovered.
Now, C++ has a silly little loophole that allows you to write const T&, and the compiler will understand that you REALLY mean T const&. Same for const T*; it gets quietly translated to T const*. So most of the time, you don’t notice that you’re using const wrong. But in this case, you’ve hit one of the cases where the mistake actually causes a problem.
reference is T&. When you const reference… or, better, when you write it CORRECTLY as reference const, that expands to T& const… NOT T const& (or const T&).
Now do you understand the warning?
You can’t have a “const reference”, or thing& const. You can have a “reference to a const (thing)”, or thing const&. The thing-being-referenced can be const, but the reference itself cannot. References are always const, because unlike pointers, you can’t change what they are referenced to.
Note that pointers CAN be const. You can have a T const * const, which is a const pointer to a const T (which is basically T const&, except it can be nullptr and you have to use * everywhere). You can have a T const* which is a non-const pointer to a const T. You can have a T* const, which is a const pointer to a non-const T (basically T&). And of course you can have T*, a non-const pointer to a non-const T.
I suggest to people I teach C++ to that they read the type backwards. So T& is a “reference to T”, and T const& is a “reference to const T”. (And T const * const is a const pointer to a const T, and so on.)
So to silence the warning, you have tried to replace reference const with T const&. But that’s wrong. Those are two completely different things. That’s similar to trying to replace a T* const with a T const*. It “works” (without a warning for pointers) only because dropping the const on the pointer doesn’t matter when you’re doing with a copy, and adding the const on the T is always allowed—you’re always allowed to add const. Assigning the former to the latter “works”… but T const* and const T* still are very different things. Assigning T& const to T const& “works” for references too; the only reason you get the warning is because T& const is gibberish.
All this, by the way, is why CONTAINERS have reference (which is usually T&) and const_reference (which is usually T const&). (And pointer and const_pointer.) If reference was just reference const, there wouldn’t be any need for const_reference.

reference is T&
reference const would be T& const (which is gibberish); and
const_reference is T const&.

Similarly, for CONTAINERS:

pointer is T*
pointer const is T* const; and
const_pointer is T const*.

ITERATORS don’t have const_reference or const_pointer because they don’t make any sense for iterators. Instead, there are iterators and const_iterators:

iterator::reference is T&
iterator::pointer is T*
const_iterator::reference is T const&; and
const_iterator::pointer is T const*.

So let’s circle back to the operator functions here:
reference operator*() const // <- I recommend both const (and noexcept)
{
    return *ptr_;
}

// Warning says "const has no effect on type reference"
const T& /*reference*/ operator*() const
{
    return *ptr_;
}

Notice now that the two functions are literally identical? That’s because you don’t need a non-const version, and because the correct return type for the const version is just reference (not reference const or T const&).
So all you need is:
reference operator*() const noexcept
{
    return *ptr_;
}

And maybe constexpr, though I don’t know if C++11’s constexpr rules will allow it. (C++17+ will, though.)
const this_type& operator++()
{
    ptr_ = std::next(ptr_);
    return *this;
}

You mentioned that clang-tidy gave a warning about const for the postfix increment operator… are you sure it wasn’t for this function, the prefix increment operator? Because returning a const reference is wrong here. Try doing ++ ++i for this type; it won’t compile. The correct form for this operator is to return a non-const reference.
As for the postfix increment operator, I don’t really see anything wrong with it.
Now, I’m honestly not sure what you think std::next() is doing here. ptr_ is a T*. std::next() for any pointer p is just ++p. All this function needs to be is:
WrappedRandomAccessIterator operator++() noexcept
{
    ++ptr_;
    return *this;
}

Alright, that’s it for the code as written. Now I’m going to go on to do a design review.
Design review
Ceci n’est pas un iterator
Okay, this first problem here is that you claim this to be a random-access iterator… but it’s not. It’s not even a bidirectional iterator. It can’t possibly be any better than a forward iterator… except it’s not even that! It’s not even a legal iterator at all!
Why? Because an iterator needs more than just operator++ (prefix and postfix) and unary operator*. At the bare minimum, the most basic kinds of iterators—input, output, and forward iterators—also require equality operators… that is, both operator== and operator!=. How can you possibly even implement the simplest algorithms, like std::for_each(), without them?
template <typename Iterator, typename Func>
void example_for_each(Iterator first, Iterator last, Func&& func)
{
    while (first != last) // won't work without operator !=
        func(*first++);
}

I’d have to check, but I’m pretty sure that the most basic iterators also need operator->, too.
A random-access operator also needs operator-- (prefix and postfix). And it needs operator+= and operator-= with difference_type. AND it needs binary operator+ and binary operator- with difference_type (both ways around). AND it ALSO needs operator- between two iterators, returning a difference_type. And I’m probably forgetting a bunch of other stuff, too. There’s actually quite a lot of operations a random-access iterator can do.
You need to add a whole lot of extra operators to this class to make it a random-access iterator.
Random-access ≠ contiguous
Okay, so, here is where I really have to guess at what the real purpose of this class is. I imagine you have some function, call it foo(), that takes a pair of iterators to a sequence—let’s assume it’s a sequence of ints. To actually think this problem concretely through without resorting to vague and nebulous hand-waving, I’m going to assume that foo() actually does something real: I’m going to assume foo() does what std::minmax_element() does.
Now the tricky thing here is that you want foo() to NOT be a function template. You want only the declaration in the header, and the definition in a source file:
// foo.hpp
auto foo(??? first, ??? last) -> std::pair<???, ???>;

// foo.cpp
auto foo(??? first, ??? last) -> std::pair<???, ???>
{
    auto result = std::pair<???, ???>{first, first};

    for (; first != last; ++first)
    {
        if (*first < *(result.first))
            result.first = first;

        if (*(result.second) == *first or *(result.second) < *first)
            result.second = first;
    }

    return result;
}

Now we need to figure out what the type ??? is. This is what I presume you intend WrapperRandomAccessIterator for. You want to do:
// foo.hpp
auto foo(WrapperRandomAccessIterator<int> first, WrapperRandomAccessIterator<int> last)
    -> std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>;

// foo.cpp
auto foo(WrapperRandomAccessIterator<int> first, WrapperRandomAccessIterator<int> last)
    -> std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>
{
    auto result =
        std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>{
            first, first};

    for (; first != last; ++first)
    {
        if (*first < *(result.first))
            result.first = first;

        if (*(result.second) == *first or *(result.second) < *first)
            result.second = first;
    }

    return result;
}

And you want to be able to call it with a vector of ints like this:
auto int_vec = std::vector<int>{};
// ... fill it with ints somehow...

auto result = foo(
    WrapperRandomAccessIterator<int>{int_vec.begin()},
    WrapperRandomAccessIterator<int>{int_vec.end()});

Something like that, right?
So the question is… will this work? Yes. Once you add operator!= to the class, then yes, this will work.
So all good, right?
No. In fact, you have some nasty bugs lurking, which could easily lead to a segfault, but just as easily not while doing catastrophic damage to your machine… almost certainly not for a machine running a modern desktop OS, of course, but who knows? That’s the problem with UB. Anything could happen.
Here’s the problem. You assume that given a pair of random-access iterators to a sequence, you can degrade them to pointers, and then treat them the same as the original iterators. For example:
auto sequence = std::vector<int>{};
// ... fill sequence with a million ints...

// You assume that this...:
auto iter_beg = sequence.begin();
auto iter_end = sequence.end();
std::for_each(iter_beg, iter_end, [](int i) { std::cout << i << ' '; });

// ... is basically the same as this...:
auto ptr_beg = &(*(sequence.begin()));
auto ptr_end = &(*(sequence.end()));
std::for_each(ptr_beg, ptr_end, [](int i) { std::cout << i << ' '; });

For a vector, you’d be right. The two cases above are functionally identical, and your WrapperRandomAccessIterator would work just fine, no problems. It would also work for std::array, std::string, and C arrays (and std::valarray, but who even uses that anymore?).
But you know what? It won’t work for std::deque.
Why not? Because you have confused the concept of “random-access iterator” with the concept of “contiguous iterator”. Not all random-access iterators are contiguous iterators:

Container
Random access?
Contiguous?

std::vector
✓
✓

std::array
✓
✓

std::string
✓
✓

C array
✓
✓

std::deque
✓
✗

Internally, a deque is an vector of pointers to arrays. This structure makes appending to the front and back fast—if there’s no space, just add another array chunk, at either the beginning or the end. It also allows for random access—element N is at position “num_elements_in_first_chunk + ((chunk_number * chunk_size) + n)”, and you just solve for chunk_number and n (which is just subtracting num_elements_in_first_chunk from N, then doing N / chunk_size to get chunk_number and N % chunk_size to get n).
But while random-access is possible in a deque, that doesn’t mean that the elements are contiguous. They are if they all happen to be in the same array chunk. But if the elements are in two different chunks, all bets are off.
So if you did the example above with a deque…:
auto sequence = std::deque<int>{};
// ... fill sequence with a million ints...

// No problems:
auto iter_beg = sequence.begin();
auto iter_end = sequence.end();
std::for_each(iter_beg, iter_end, [](int i) { std::cout << i << ' '; });

// Boom, UB, possible segfault:
auto ptr_beg = &(*(sequence.begin()));
auto ptr_end = &(*(sequence.end()));
std::for_each(ptr_beg, ptr_end, [](int i) { std::cout << i << ' '; });

So you might think that, okay, if random-iterators won’t work, you could just use contiguous iterators instead. Well, sorry. There are no contiguous iterators in C++11. (Well, there are, but the concept wasn’t standardized.) Contiguous iterators didn’t come around until C++17… but you couldn’t actually use them until C++20.
So… what does that mean?
Well, it means your WrapperRandomAccessIterator won’t actually work for all random-access iterators. Sure, it will work for most random-access iterators (if you actually implement all the required functions)… but not all. And there’s no safe way to detect which iterators will cause a crash (not until C++20).
So you have two options:

throw the whole design out; or
accept the limitations, accept that it will only work for some types and maybe add checks to make sure only those types are used, and just live with that.

HOWEVER… if you chose option 2, there is one more thing to consider…
Going contiguous? Don’t over-engineer; just use pointers
Contiguous iterators are really just pointers. Your misnamed WrapperRandomAccessIterator is actually WrapperContiguousIterator, because it only works for contiguous iterators, because it uses pointers internally.
But… here’s the thing… if you’re just going to use pointers internally… why not just use them externally, too?
Let's go back to the foo() function:
// foo.hpp
auto foo(WrapperRandomAccessIterator<int> first, WrapperRandomAccessIterator<int> last)
    -> std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>;

// foo.cpp
auto foo(WrapperRandomAccessIterator<int> first, WrapperRandomAccessIterator<int> last)
    -> std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>
{
    auto result =
        std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>{
            first, first};

    for (; first != last; ++first)
    {
        if (*first < *(result.first))
            result.first = first;

        if (*(result.second) == *first or *(result.second) < *first)
            result.second = first;
    }

    return result;
}

// Usage in other.cpp
auto int_vec = std::vector<int>{};
// ... fill it with ints somehow...

auto result = foo(
    WrapperRandomAccessIterator<int>{int_vec.begin()},
    WrapperRandomAccessIterator<int>{int_vec.end()});

Since WrapperRandomAccessIterator<int> is ultimately just an int*… why not do:
// foo.hpp
auto foo(int* first, int* last) -> std::pair<int*, int*>;

// foo.cpp
auto foo(int* first, int* last) -> std::pair<int*, int*>
{
    auto result = std::pair<int*, int*>{first, first};

    for (; first != last; ++first)
    {
        if (*first < *(result.first))
            result.first = first;

        if (*(result.second) == *first or *(result.second) < *first)
            result.second = first;
    }

    return result;
}

// Usage in other.cpp
auto int_vec = std::vector<int>{};
// ... fill it with ints somehow...

auto result = foo(&(*(int_vec.begin())), &(*(int_vec.end())));
// or:
auto result = foo(int_vec.data(), int_vec.data() + int_vec.size());

Note that if you were going this route, rather than taking a pair of pointers, a safer option might be to take a pointer and a size. It’s easy to mix up pointers, or to one pointer from one sequence and another pointer from another sequence. It’s a lot harder to screw up using a pointer and a size.
Actual type-erased iterators…?
Okay, so pointers work fine for contiguous iterators, but let’s say you really, really want to use random-access iterators. Or maybe even bidirectional or forward iterators. Can it be done? How?
Well, I’m not going to put any real thought into solving this problem right now… but if I had to just barf something up, I might do something like this:
Rather than trying to degrade iterators to pointers, I would ask what are the fundamental operations an iterator needs. A basic iterator—input, output, and forward—needs to be able to do 3 things:

dereferencing (so *i returns a possibly-const reference)
movement (so ++i advances the i); and
equality (so i == j returns true if they reference the same thing).

A bidirectional iterator only adds the ability to do “negative movement”; movement backwards via decrement.
A random-access iterator adds a TON of stuff… but it really boils down to:

really big movement (i += n or i -= n)
distance measuring (i - j); and
comparison (i < j).

“Really big movement” is just movement, as is “negative movement”. And we can join equality and comparison if we keep track of what kind of comparison we’re actually doing.
So we can boil this down to 4 operations. Assuming p and q are type-erased (std::any—I know this requires C++17, but you can always use boost::any) iterators:

deref(std::any p) handles dereferencing (returns a possibly-const reference to whatever the iterator references);
advance(std::any p, std::ptrdiff_t n) handles movement (normally n must be 1, but can be -1 for bidirectional iterators, and any number for random-access iterators);
compare(std::any p, std::any q, bool eq) returns int(i == j) if eq is true using the iterators under p and q, or 1, 0, or −1 if eq is false doing a standard 3-way compare between i and j, handling both equality and comparison; and
distance(std::any p, std::any q) handles distance measurement.

Then we define a class that holds functions:
template <typename T, typename IterCat>
class type_erased_iterator
{
private:
    std::any                                                         _iter;
    std::function<T& (std::any&)>                                    _deref;
    std::function<void (std::any&, std::ptrdiff_t)>                  _advance;
    std::function<int (std::any const&, std::any const&, bool)>      _compare;
    std::function<std::ptrdiff_t (std::any const&, std::any const&)> _distance;

public:
    using difference_type = std::ptrdiff_t;
    using value_type = typename std::decay_cv<T>::type;
    using pointer = T*;
    using reference = T&;
    using iterator_category = IterCat;

    template <typename Iterator>
    explicit type_erased_iterator(Iterator it) :
        _iter{it},
        _deref{[](std::any& p) -> T& { return *std::any_cast<Iterator>(p); }},
        _advance{[](std::any& p, std::ptrdiff_t n) { std::advance(std::any_cast<Iterator>(p), n); }},
        // you get the idea...
    {}

    template <typename Iterator>
    type_erased_iterator(
            Iterator it,
            std::function<T& (std::any&)> deref,
            std::function<void (std::any&, std::ptrdiff_t)> advance,
            std::function<int (std::any const&, std::any const&, bool)> compare,
            std::function<std::ptrdiff_t (std::any const&, std::any const&)> distance
        ) :
        _iter{it},
        _deref{std::move(deref)},
        _advance{std::move(advance)},
        _compare{std::move(compare)},
        _distance{std::move(distance)}
    {}

    // Now just implement the iterator ops in terms of the core functions.

    auto operator++() -> type_erased_iterator&
    {
        _advance(_iter, 1);
        return *this;
    }

    auto operator*() -> T&
    {
        return _deref(_iter);
    }

    // and so on...
};

// usage:
auto int_vec = std::vector<int>{};
// ... fill it with ints somehow...

auto result = foo(
    type_erased_iterator<int, std::random_access_iterator_tag>{int_vec.begin()},
    type_erased_iterator<int, std::random_access_iterator_tag>{int_vec.end()});

As you can see, it’s used pretty much exactly like the way I assumed WrapperRandomAccessIterator would be used. You could even make a helper function to make it simpler:
auto result = foo(
    make_type_erased_iterator(int_vec.begin()),
    make_type_erased_iterator(int_vec.end()));

Given that most iterators are small (often just pointers), and that the functions will probably never be closures, there shouldn’t be any dynamic allocation required. This class won’t be fast, but it will allow you to type-erase ANY iterator. Not just random-access; you can even type erase input or output iterators.
If you really just want to support random-access iterators, that eliminates much of the complexity of SFINAE-ing away illegal iterator operations (like preventing operator-- for forward iterators).
Summary
WrapperRandomAccessIterator is unfortunately named, because it is not a wrapper, and it does not work with random-access iterators.
It does work with contiguous iterators, and ONLY contiguous iterators… or at least it would if you added all the required iterator operations. However, contiguous iterators aren’t really a thing until C++17, and not a practical thing until C++20.
But if you really only want it to work with contiguous iterators, you might as well just use pointers.
If you really need other iterator categories (including actual random-access iterators), you will need a much more advanced type-erasure system.


Authorization using Entity Framework in ASP.NET MVC

You should not instanciate a new DbContext each time your code go throw your ActionFilter.  What you should do is to use dependency injection and to define an execution scope.

Because you are using .net Framework and not .net core, I advise you to look into DI providers such as Autofac or Ninject.

I advise you to look into why to use DI and think about what execution scope you need (probably perScope() in your case).

Hope it helps.


In both nested loops, it seems you really need the values of dictionaries.
You iterate over the keys just to use them to get the values:

for ID in switch:
    for pin in switch[ID]:
        GPIO.setup(switch[ID][pin], GPIO.OUT)

A more direct approach would be to iterate over the values instead of the keys:

for pins in switch.values():
    for pin in pins.values():
        GPIO.setup(pin, GPIO.OUT)

A minor thing, the definition of switch doesn't follow PEP8,
because of the spaces around the = when setting the dictionary keywords.
This is the recommended style:

switch = {
    'A': dict(On=22, Off=12),
    'B': dict(On=19, Off=11),
    'C': dict(On=18, Off=16),
    'D': dict(On=15, Off=13)
}


Such an algorithm is very rarely used, so it is extremely unlikely that its performance matters. So, most chances are you do not need to optimize it at all. But if you insist:
Do not pre-initialize the 'hundred' and 'thousand' StringBuffers. Only initialize them if they are needed. As a matter of fact, it is good practice (though it does not have anything to do with performance) to not even declare them outside of the narrowest possible scope in which they will be used.  By the way, I do not understand why 'hundred' and 'thousand' are StringBuffers instead of Strings.
You do not need HashMaps for this job; just use arrays of String. They will be faster.
It seems like the kind of recursion you are using is tail recursion, so you can trivially convert your function to work iteratively, which will probably yield better performance. I am not saying it will necessarily perform better, so write both versions and benchmark one against the other if you really care about performance. But if you do not, then keep the recursive version, it is way cooler, and even easier to read.
When you append to a StringBuffer, never append multiple strings concatenated with +. Always use a separate call to append() for each string.  Otherwise, the compiler will very likely be creating more temporary StringBuffers behind your back in order to optimize your string append operations.
Considering that any number minus zero is still the same number, you can optimize this:

int temp = num % 1000;
if (temp == 0) {
    numRep.append(representation(num / 1000) + "-" + thousand);
} else {
    numRep.append(representation((num - temp) / 1000) + "-" + thousand
            + "-" + representation(temp));
}

into this:

int temp = num % 1000;
numRep.append( representation( (num - temp) / 1000) );
numRep.append( "-" );
numRep.append( thousand );
if( temp != 0 )
{
    numRep.append( "-" );
    numRep.append( representation( temp ) );
}


You should probably take out the class selectors (.grid-row and .col-1-2) because nth-child doesn't respond to them (i.e. they're not doing anything):

.achievements :nth-child(even) :nth-child(odd) .achievement

In the future, CSS3's toggle() function (which cycles through values) could simplify things:

.achievement {
  background: toggle(#ccc, #5891bc, #96c3e6, #d3dfe7);
}

Sadly this isn't supported by any browsers yet. Also proposed is an :nth-match selector, which would let you do:

:nth-of-type(n4+1 of .achievement) {
  background: #5891bc;
}


To solve the root of your problem, I suggest you actually modify the source of that HTML. Add your scripts and attributes there instead of creating this voodoo with JS.

Now if this is the only way you could do it (sigh)...

First, jQuery cannot parse full HTML and I think you're aware of that. It's also mentioned in the documentation how it creates jQuery objects for complex markup.

  If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new  element and sets the innerHTML property of the element to the HTML snippet that was passed in.

An alternative way to do it is to just skip all this work and just inject an external script instead. You could look for  or some element in the markup that's guaranteed to always be there, and replace it with markup containing your external script.

var htmlWithInjectedScript = html.replace('', '');

This way, you don't have to mangle the markup while having a place to run JavaScript in all its glory. This assumes that the markup is actually executed somewhere, not just for show and tell and that your script is in a location that's always available.


Build a stamp duty calculator for various types of buyers

Hard coded
You have created yourself a future problem by hard coding the data in your code.  When dealing with taxes (or any business logic)  there is one certainty, and that is change.
With the data embedded in the code, making even a minor change will take some effort and will be very prone to error.
You need to create a data structure that allows you to make changes quickly and easily. You should only have to change a value once, in one location, not many times in many places.
Defining the data
The data is defined as an object, with only the data needed, if information can be deduced there is no need to include it.
The example has a helper function rate to reduce the overhead of typing in {level:10000, tax: 0.1} over and over
const rate = (level, tax) => ({level, tax});
const brackets = {
    firstTime: [
        rate(300000, 0),
        rate(925000, 0.05),
        rate(1500000, 0.1),
        rate(Infinity, 0.12),
    ],
    returning: [
        rate(125000, 0),
        rate(250000, 0.02),
        rate(925000, 0.05),
        rate(1500000, 0.1),
        rate(Infinity, 0.12),
    ],
    second: [
        rate(125000, 0.03),
        rate(250000, 0.05),
        rate(925000, 0.08),
        rate(1500000, 0.13),
        rate(Infinity, 0.15),
    ],
};

Applying logic
With the data organised, the code can then just deal with the logic of how the duty is calculated:
function calculateDuty(price, bracket) {
    var duty = 0;
    var prevLevel = 0
    for (const rate of bracket) {
        if (rate.level <= price) {
            duty += (rate.level - prevLevel) * rate.tax;
            prevLevel = rate.level;
        } else {
            return duty + (price - prevLevel) * rate.tax;
        }
    }
}

And now you can get the duty for any bracket: calculateDuty(price, brackets.firstTime)
Rewrite
Thus the whole thing becomes:
const rate = (level, tax) => ({level, tax});
const brackets = {
    firstTime: [rate(300000, 0), rate(925000, 0.05), rate(1500000, 0.1), rate(Infinity, 0.12)],
    returning: [rate(125000, 0), rate(250000, 0.02), rate(925000, 0.05), rate(1500000, 0.1), rate(Infinity, 0.12)],
    second: [rate(125000, 0.03), rate(250000, 0.05), rate(925000, 0.08), rate(1500000, 0.13), rate(Infinity, 0.15)],
};
const stampDutyCalc = price => ({
    ftb: calculateDuty(price, brackets.firstTime),
    rtb: calculateDuty(price, brackets.returning),
    shb: calculateDuty(price, brackets.second),
});

function calculateDuty(price, bracket) {
    var duty = 0, prevLevel = 0
    for (const rate of bracket) {
        if (rate.level <= price) {
            duty += (rate.level - prevLevel) * rate.tax;
            prevLevel = rate.level;
        } else {
            return duty + (price - prevLevel) * rate.tax;
        }
    }
}


Refactoring jQuery slider code suggestions

Some minor improvements you can make:

Cache your DOM lookups (e.g. $('.slider img')) to prevent having to parse the DOM multiple times. That's as simple as making a new variable:

var sliderImages = $('.slider img');

Use a ternary statement for setting your z-index:

$(this).css('z-index', zindex < count ? zindex + 1 : zindex - count - 1);

That'll remove 4 lines and remove unnecessary repetition.
Add the var keyword to your count variable so it's not global (it should remain accessible to all the functions within your function scope anyway).
Add some simple comments to explain why you're changing the z-index in the first place.


Validate your inputs

The current method doesn't check for invalid input:

null array
negative rotation order

I suggest to add this ad the top:

if (arr == null || order < 0) {
    throw new IllegalArgumentException("The array must be non-null and the order must be non-negative");
}

Follow standard formatting

The posted code is messy. Use your IDE to reformat it to the standard:

int[] unOrderedArr = {1, 2, 3, 4, 5, 6, 7, 8};
int orderToRotate = 2;

for (int i = 0; i < orderToRotate; i++) {
    for (int j = unOrderedArr.length - 1; j > 0; j--) {
        int temp = unOrderedArr[j];
        unOrderedArr[j] = unOrderedArr[j - 1];
        unOrderedArr[j - 1] = temp;
    }
}

Now that's a lot easier to read.

On a related note, an easy way to print an array is using Arrays.toString

Optimize

Frist of all,
what will happen if you receive arr to rotate, and the rotate order = arr.length?
The array elements will be rotated pointlessly,
just to return to their original position.
This gets even worse for multiples of arr.length.

Secondly, in this code:

for (int i = 0; i < order; i++) {
    for (int j = arr.length - 1; j > 0; j--) {
        // ...
    }
}

The above code iterates over the entire array order times.

To avoid unnecessary iterations,
you will benefit from using a clone of the original array,
and iterate over the elements only once,
at the expense of using twice as much memory.

Suggested implementation

The above suggestions and some style improvements applied:

private static void rotate(int[] arr, int order) {
    if (arr == null || order < 0) {
        throw new IllegalArgumentException("The array must be non-null and the order must be non-negative");
    }
    int offset = arr.length - order % arr.length;
    if (offset > 0) {
        int[] copy = arr.clone();
        for (int i = 0; i < arr.length; ++i) {
            int j = (i + offset) % arr.length;
            arr[i] = copy[j];
        }
    }
}

Some unit test to verify it works:

@Test
public void testRotateBy2() {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
    int[] expected = {7, 8, 1, 2, 3, 4, 5, 6};
    rotate(arr, 2);
    assertArrayEquals(expected, arr);
}

@Test
public void testRotateBy3() {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
    int[] expected = {6, 7, 8, 1, 2, 3, 4, 5};
    rotate(arr, 3);
    assertArrayEquals(expected, arr);
}

@Test
public void testRotateByLength() {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
    int[] expected = arr.clone();
    rotate(arr, arr.length);
    assertArrayEquals(expected, arr);
    rotate(arr, arr.length * 3);
    assertArrayEquals(expected, arr);
}

@Test
public void testRotateByZero() {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
    int[] expected = arr.clone();
    rotate(arr, 0);
    assertArrayEquals(expected, arr);
}


Mongo command to add a field to all documents in a collection

This is a lot faster:

db. birds.updateMany(
   {},
   { $set:
      {
        hi: true
      }
   }
)


I am looking for code-style advice and maybe a better algorithm suggestion.

As for coding style, first and foremost, please follow PEP8.

Simplify

You could simplify get_starts using product from itertools:

def get_starts(n):
    sqrt, power, fact, gamma = int(n ** 0.5), n ** 2, math.factorial(n), math.factorial(n - 1)
    return product((sqrt, n, power, fact, gamma), repeat=4)

I also dropped the unused lst parameter.
In fact many of the functions have unused parameters,
remove them everywhere.

Use generators, they are awesome

Since you accumulate solutions in an array,
the program seems to freeze for a few seconds while calculating,
rather than printing the solutions that are ready.
You could improve that by using a generator instead, for example:

def solve_44(max_):
    for i in range(max_):
        yield how_to_obtain(i, [concat, op.add, op.mul, op.sub, div, op.pow, op.mod])

def main(max_):
    none_count = 0
    for solution in solve_44(max_):
        print(solution)
        if solution is None:
            none_count += 1
    print("The random search failed to find a solution {}% of the times.".format(
        none_count / max_ * 100))

Another correction here is using is None instead of == None for comparing with None values.


Implementation of a dynamic list-like array

This is an interesting concept, a size-limited "bucket" of not-guaranteed-order items. You are right that the add and remove are O(1) operations, but there are a number of concerns I have.... some of them are severe.

If someone adds a null value, you are broken in the iterator. You need to accommodate null, or throw an exception.
The get(int) and remove(int) methods are useless - how does the user know what int to use? The first item added is placed at index size - 1, and so on, so how does that work?

Then, there's a trick with Collections that have a generic type. The general concensus in Java is that you should pass the class definition in to the constructor. The standard Java collections can't do that for backward compatibility reasons, but, consider this:

public class BagArray<T> implements Iterable<T> {

    private final T[] mItems;
    public BagArray(Class<T> tClass, int size) {
        @SuppressWarnings("unchecked")
        mItems = (T[]) Array.newInstance(tClass, size);

Note two things there...

In Java, by convention, you declare arrays as T[] mItems, and not T mItems[]
The array now has the correct type, and there's only one place you need to cast the values, and that is in the array creation.

One last thing, in Java 8, a nice trick for creating an array populated with sequential numbers is:

int[] values = IntStream.range(startInclusive, endExclusive).toArray();


Here's how you could use a table array for the widths.  I didn't fill in all the character widths (I just did lowercase) because it's tedious to build, but you can extend it to contain all the typeable characters that you want to support.  I also made it a jQuery method that you can call like this:

$("input").autoSize();

Here's the code (also in a jsFiddle):

(function() {
    var widths = [
     // a, b, c, d, e, f, g
        7, 7, 6, 7, 7, 3, 7,
     // h, i, j, k, l, m, n
        7, 3, 3, 6, 3, 11, 7,
     // o, p, q, r, s, t, u
        7, 7, 7, 4, 7, 3, 7,
     // v, w, x, y, z
        5, 9, 5, 5, 5
    ];

    // character code our table starts with
    var lowWidth = 97;

    $.fn.autoSize = function() {
        return this.each(function() {
            var val = this.value;
            var totalWidth = 0, charIndex, ch;
            for (var i = 0, len = val.length; i < len; i++) {
                // get char code and see if it's in our width table
                charIndex = val.charCodeAt(i) - lowWidth;
                ch = val.charAt(i);
                if (charIndex >= 0 && charIndex < widths.length) {
                    totalWidth += widths[charIndex];
                } else if (ch == ' ') {
                    // special case for space char
                    // until the table contains all codes we need
                    totalWidth += 6;
                }
            }
            $(this).css("width", totalWidth + "px");
        });
    }
})();

FYI, jQuery will also measure the natural width of any DOM element for you so you could also have a span that is styled with the right font that you insert this text into and then ask jQuery what it's width is.  jQuery will temporarily make it position absolute (so it will layout to it's natural width) and then let the browser tell you how wide it is.  This would be much, much more accurate than what you are doing.

Letting jQuery measure it for you would look like this:

$.fn.autoSize = function() {
    var testItem = $("#testWidth");
    return this.each(function() {
        // put the text into our test span
        testItem.text(this.value);
        $(this).width(testItem.width());
    });
}

And, you'd have appropriate CSS for a testItem span (see the jsFiddle demo for details):

jsFiddle demo: http://jsfiddle.net/jfriend00/jQ93f/


Algorithm to find pair with max sum from two arrays

We can solve this in \$O(n)\$ time. The best possible sum for a particular index, \$i\$, is \$S[i] = A[i] + \max(B[i+1:])\$ (using the Python notion of slice). We can update both incrementally by counting from the back, so we have to keep track of two things: \$\max(S[i:])\$ and \$\max(B[i+1:])\$.

So for the test arrays:

int[] testArrayA = { 7, 1, 4, 5, 1};
int[] testArrayB = { 3, 2, 1, 5, 3};
                              ↑
                              starting i

At i==3, we start with maxS == 8 and maxB == 3, since those are the only two options. With i==2, we update maxB = max(maxB, B[i+1]) = 5 and maxS = max(maxS, A[i] + maxB) = max(8, 4+5) = 9. etc.

In code:

public static void printMaxIncreasingIndexSum(int[] A, int[] B)
{
    int bIdx = B.length - 1;
    int aIdx = A.length - 2;

    int maxB = bIdx;
    int maxS = A[A.length - 2] + B[maxB];

    for (int i = A.length - 3; i >= 0; --i) {
        if (B[i+1] > B[maxB]) {
            maxB = i+1;
        }

        if (A[i] + B[maxB] > maxS) {
            maxS = A[i] + B[maxB];
            aIdx = i;
            bIdx = maxB;
        }
    }

    System.out.printf("%d %d", aIdx, bIdx);
}


Fetching user details, posts, and comments using promises in ExpressJS

If you use 1 promise, you would encounter a long chain of then method and all of async operations would be executed in sequence style which increases response time.

If you create 3 promises, all of that can be performed in parallel. So the answer is yes, you should implement with 3 promises.

By the way, with help of bluebird library, You can write more readable JS code as I refactored show below, (I will explain more):

const bluebird = require('bluebird')
const User = require('./model/User')
bluebird.promisifyAll(User)

function asyncHandler(fn) {
    const promiseFn = bluebird.method(fn)
    return function(req, res) {
        let resultPromise = promiseFn.call(this, req,res)
        resultPromise.then(function(result) {
            res.json({
                success: true,
                response: result,
            })
        }).catch(function(err) {
            logHlpr.logThisError({stackTrace: err});
            res.json({
                success: false,
            })
        })
    }
}

exports.fetchUserInformation = asyncHandler(function(req, res) {
    if (!req.query.userId) {
        throw new Error("UserId is required")
    }
    let userId = req.query.userId
    let userDetails = User.getUserDetailsAsync({userId: userId})
    let userPosts = userDetails.then(result => User.fetchUserPostsAsync({userId: userId, result: result}))
    let userComments = User.fetchUserCommentsAsync({userId: userId, userType: 'user'})
    return bluebird.props({
        userId: userId,
        userDetails: userDetails,
        userPosts: userPosts,
        userComments: userComments,
    })
})

Most of the time, when you write JavaScript in Node.js, you need to work with callbacks, so convert all callback-style to promise-style by using bluebird.promisifyAll() or bluebird.promisify() will allow you to work with code easier, please see bluebird document.

After that most of handler function you write would deal with promise, so you can create higher-order function, like asyncHandler, which send success response in case that promise is fulfilled. You can also move asyncHandler function to shared-file and require() it later to use at multiple places.

For handler function, fetchUserInformation from your code sample, you want to return result as an object. This object contains result from many promises. You can use bluebird.props() which create a wrapper promise that wait all object's values to be fulfilled.

The last things, I would suggest you find a way to reimplement User.fetchUserPosts() that it wouldn't require userDetails as part of the parameter, so this method can be performed without waiting for User.getUserDetails() result and can make the code more elegant.


Is this C++ program correctly implemented in SSE?

Your SSE code looks like a reasonably accurate translation of your original C, but that C code doesn't immediately jump out as the best way to do things. In particular, I don't see where you gain anything by taking the absolute value before you do your multiplication. Given that your're squaring the value immediately afterwards anyway, it would appear simpler to just leave it negative if that's what it happens to be. Lacking a specific reason to do otherwise, I'd start with something simpler, like this:

double x = x1 - x2;
double y = y1 - y2;

double dist = sqrt(x * x + y * y);

Then I'd convert that to SSE instructions.

Especially if you're concerned with speed, you might want to consider using an alternative to the Pythagorean theorem to compute the hypotenuse though. I posted some C for one possibility in a previous answer.


Write your implementation of Ruby's String#count method

If you can use some ruby String method I would suggest
def custom_count(string, search_char)
  search_char.split("").inject(0) do |count,pattern|
    string.scan(pattern).size + count
  end
end


Vectorization with NumPy
When read with cv2.imread or skimage.io.imread or scipy.misc.imread, you would already have the image data as a NumPy array. Now, NumPy supports various vectorization capabilities, which we can use to speed up things quite a bit.
I. Crop to remove all black rows and columns across entire image
To solve our case, one method would be to look for rows and columns that have at least one pixel along rows and columns that is greater than some lower limit or threshold as a pixel value. So, if you are sure that the black areas are absolutely zeros, you can set that threshold as 0. Thus, if img represents the image data, you would have correspondingly two boolean arrays : (img>tol).any(1) and (img>tol).any(0).
Next up, you can use these boolean arrays to index into the image data for extraction of valid bounding box using broadcasted indexing with np._ix -
np.ix_((img>tol).any(1),(img>tol).any(0))

Finally, we index into image data with it for the final extracted data, which is the required bounding box data.
To sum up, the final implementation would be -
def crop_image(img,tol=0):
    # img is 2D image data
    # tol  is tolerance
    mask = img>tol
    return img[np.ix_(mask.any(1),mask.any(0))]

Sample results
1] With tolerance = 0 :

2] With tolerance = 80 (tighter) :

II. Crop while keeping the inner all black rows or columns
To crop the image while keeping the inner all black rows or columns, the implementation would be close to the previous method. The basic idea here would be getting the start, stop indices along rows and columns that decide the bounding box. We will start off with the same mask of ANY match along rows and columns as used in the previous one. Then, argmax would be useful to get start and stop indices of those matches along rows and cols. We will use these indices to slice the 2D input array, which is the desired cropped image output. The implementation would look something like this -
def crop_image_only_outside(img,tol=0):
    # img is 2D image data
    # tol  is tolerance
    mask = img>tol
    m,n = img.shape
    mask0,mask1 = mask.any(0),mask.any(1)
    col_start,col_end = mask0.argmax(),n-mask0[::-1].argmax()
    row_start,row_end = mask1.argmax(),m-mask1[::-1].argmax()
    return img[row_start:row_end,col_start:col_end]

Sample run -
Input :

Output :

Benchmarking
Since we are talking about performance in this Q&A, let's test out how this method works in comparison to others.
@Gareth Rees's solution is another vectorized one that finds all indices and then slices the input array. Finding all indices could become costly. We will try to time and see how much would that affect the performance. we will use the sample data used in the earlier section -
# @Gareth Rees's solution
def crop_with_argwhere(image):
    # Mask of non-black pixels (assuming image has a single channel).
    mask = image > 0

    # Coordinates of non-black pixels.
    coords = np.argwhere(mask)

    # Bounding box of non-black pixels.
    x0, y0 = coords.min(axis=0)
    x1, y1 = coords.max(axis=0) + 1   # slices are exclusive at the top

    # Get the contents of the bounding box.
    cropped = image[x0:x1, y0:y1]
    return cropped

Timings -
# Import the "4" digit image from previous section
In [50]: from skimage import io
    ...: im = io.imread('https://i.stack.imgur.com/tmdiH.png')

# @Gareth Rees's solution
In [51]: %timeit crop_with_argwhere(im)
1000 loops, best of 3: 1.4 ms per loop

In [52]: %timeit crop_image_only_outside(im,tol=0)
10000 loops, best of 3: 81.8 µs per loop

The memory efficiency with crop_image_only_outside is noticeable on performance.

Extend to generic 2D or 3D image data cases
Assuming we are looking to check for ALL matches across all channels along the last dimension/axis, the extension would be simply performing numpy.all reduction along the last axis. Hence, we would have generic solutions to handle both 2D and 3D image data cases like so -
def crop_image(img,tol=0):
    # img is 2D or 3D image data
    # tol  is tolerance
    mask = img>tol
    if img.ndim==3:
        mask = mask.all(2)
    mask0,mask1 = mask.any(0),mask.any(1)
    return img[np.ix_(mask0,mask1)]

def crop_image_only_outside(img,tol=0):
    # img is 2D or 3D image data
    # tol  is tolerance
    mask = img>tol
    if img.ndim==3:
        mask = mask.all(2)
    m,n = mask.shape
    mask0,mask1 = mask.any(0),mask.any(1)
    col_start,col_end = mask0.argmax(),n-mask0[::-1].argmax()
    row_start,row_end = mask1.argmax(),m-mask1[::-1].argmax()
    return img[row_start:row_end,col_start:col_end]


How should I name a function which shows or hides an element?

Naming

I think togglePassenger is not the only naming problem in your code.

A function parameter should not be a single letter except in a very limited number of cases. But I don't think that this is not one of them; a reader does not automatically understand what i actually does.

I would also rename nbPassengers, because it is unclear what nb means.

What I think your function does is show the first n passengers, and hide the rest. If that is the case, I would not use toggle, because as you said, there really is no toggling going on. You could go with something like updateVisibility to avoid this confusion, although it's a bit unconcrete. Whatever name you do choose, I would add a comment to the function explaining what it does.

Misc

I would use curly brackets even for one line statements to avoid future bugs
your spacing is sometimes inconsistent (eg spacing around variable in function calls)


Using 'switch to choose different rates to calculate net pay

It's not bad. A couple of issues regarding validating input, which you know about, but a few 'style' things, some of which you may not know about yet.

In addition to Ryan's answer, a couple more suggestions:

Only declare one variable per line. Otherwise it becomes harder to see where it comes from.

double totalPayed;
double rateToCalculate;

In general, try to declare variables in the inner-most block in which they're used. In this case, all but rateSelected should be declared inside the while loop. It doesn't matter for this, but in more complex programs restricting where the variables can be used will become more important.
Don't have 'magic numbers', in this case the options themselves. I would suggest setting up an enum (if you know about them?, or a series of #defines), something like:

enum { OPTION_BEGIN = 1, OPTION_RATE_ENTRY = OPTION_BEGIN, OPTION_RATE_MID, OPTION_RATE_SENIOR, OPTION_RATE_MANAGER, OPTION_QUIT, OPTION_END };

Use these in getRate instead of the appropriate numbers.
Separate out the question into a separate function, it's an identifiable single task. And it becomes easier to change if it's one place. I've added another function here for readability:

int is_valid_option( int option )
{
    return ( option >= OPTION_BEGIN ) && ( option < OPTION_END );
}

int ask_for_pay_rate( void )
{
    int option = OPTION_END;
    while ( option == OPTION_END )
    {
        int answer;

        printf("Enter the number corresponding to the desired pay rate or action:\n");
        printf("1) %.2lf$/hr                               2) %.2lf$/hr\n", RATE1, RATE2);
        printf("3) %.2lf$/hr                              4) %.2lf$/hr\n", RATE3, RATE4);
        printf("5) Quit\n");

        /* scanf returns the number of successful inputs, ie 1 number.
           Test for this, rather than eof */
        if ( ( scanf( "%d", &answer ) == 1 ) && is_valid_option( answer ) )
        {
            option = answer;
        }
        else
        {
            printf("please enter a valid number:\n");
        }
    }
    return option;
}

Note by the way, that I've set up a condition at the start of the while loop which forces it to execute at least once. Doing it the way you did means that you have to duplicate code, allowing the possibility that it'll be subtly different.
You may want to validate the value for weeklyHours, should be a number >= 0


Calculate Levenshtein distance between two strings in Python

There is a module available for exactly that calculation, python-Levenshtein. You can install it with pip install python-Levenshtein.

It is implemented in C, so is probably faster than anything you can come up with yourself.

from Levenshtein import distance as levenshtein_distance

According to the docstring conventions, your docstring should look like this, i.e. with the indentation aligned to the """ and the line length curtailed to 80 characters.

def calculate_levenshtein_distance(str_1, str_2):
    """
    The Levenshtein distance is a string metric for measuring the difference
    between two sequences.
    It is calculated as the minimum number of single-character edits necessary to
    transform one string into another.
    """
    ...


I would remove the First and Then methods and just execute actions in the order they are declared.


Telegram Bot that retrieves book information from GoodReads

i = 0
for book in books:
    title = book[i].title
    info_dict['title'] = title

    author = book[i].authors[0]
    info_dict['author'] = author

    rating = book[i].average_rating
    info_dict['rating'] = rating

    review = book[i].description
    info_dict['review'] = review

    cover = book[i].image_url
    info_dict['cover'] = cover

    link = book[i].link
    info_dict['link'] = link
    i += 1
    book_list.append(info_dict)

I don't really get this part, either the books objects got some weird structure, or it seems like (and most likely is) that each object in this collection got also information about the whole collection.
So this might be just replaced with:

for book in books:
    book_list.append({
        'title': book.title,
        'author': book.authors[0],
        'rating': book.rating,
        'review': book.review,
        'cover': book.image_url,
        'link': book.link
    })

which you might want to replace with list comprehession if you want to:

book_list = [{'title': book.title,
              'author': book.authors[0],
              'rating': book.rating,
              'review': book.review,
              'cover': book.image_url,
              'link': book.link
              } for book in books]

But if I'm wrong and this books got really weird structure you can simplify your code as:

for i, book in enumerate(books):
    book_data = book[i]
    book_list.append({
        'title': book_data.title,
        'author': book_data.authors[0],
        'rating': book_data.rating,
        'review': book_data.review,
        'cover': book_data.image_url,
        'link': book_data.link
    })

now your random_book function can be prettified a bit as:

def random_book():
    index = random.randint(1, 1000000)
    book = gc.book(index)

    return {
        'title': book_data.title,
        'author': book_data.authors[0],
        'rating': book_data.rating,
        'review': book_data.review,
        'cover': book_data.image_url,
        'link': book_data.link
    }

Now as we can see, these both two functions are having deal with same structure, so you might want to create a parse function. And in the end your code will be like:

import random
from goodreads import client

client_key = "[redacted]"
client_secret = "[redacted]"

gc = client.GoodreadsClient(client_key, client_secret)

def parse_book(book):
    return {
        'title': book_data.title,
        'author': book_data.authors[0],
        'rating': book_data.rating,
        'review': book_data.review,
        'cover': book_data.image_url,
        'link': book_data.link
    }

def book_info(title):
    books = gc.search_books(str(title), page=1, search_field='all')

    return map(parse_book, books)

def random_book():
    index = random.randint(1, 1000000)
    book = gc.book(index)

    return parse_book(book)

Also in random_book I would replace index = random.randint(1, 1000000) with a call that returns a number of books in goodreads (if there is such) so you wont get an error here.


Standard guarantees sizeof(char) to be 1.
argv[1] is a perfectly good string. There is no need to copy it anywhere, let alone allocate a megabyte for it.
Length of a destination string is strlen(argv[1]) * loop + 1. Do not hardcode a megabyte.
strcat has to find the end of destination string over and over again, making the execution time quadratic. Trace the end of the destination string as you go and strcpy to the right location instead.


Python program to find a word ladder transforming "four" to "five"

By performing recursion, you are performing a depth-first search of four-letter words. However, this task involves finding a shortest path, and shortest-path problems are generally better done using breadth-first search. With BFS, the first solution you encounter will be an optimal solution — which is not the case with DFS.


Declare and initialize variables in one go
You can initialize a value at the same time you declare it. This even works for structs and arrays. For example:
int main() {
    int c = 0;
    int length = 0;
    int hist[MAXLEN+1] = {0}; // Initializes all elements to 0

    while ((c = getchar()) != EOF) {
        ...

Use isspace()
Instead of manually checking against spaces, tabs and newlines, use isspace() from <ctype.h>.
Split your code into multiple functions
Even for a simple program like this, it is a good exercise to split the code into multiple functions, and reduce the responsibility of each function as much as possible. This way for example, main() could be reduced to:
int main() {
    int hist[MAXLEN + 1] = {0};

    build_histogram(hist, MAXLEN);
    print_histogram(hist, MAXLEN);
}

Then build_histogram() could be written like this:
static void build_histogram(int hist[], size_t hist_size) {
    int c;
    int length = 0;

    while ((c=getchar())!=EOF) {
        if (isspace(c)) {
            add_word(hist, hist_size, length);
            length = 0;
        } else {
            length++;
        }
    }

    add_word(hist, hist_size, length);
}

So its main function is to scan for words. Then add_word() does the actual work of recording the length of a word in the histogram:
static void add_word(int hist[], size_t hist_size, size_t length) {
    if (length > hist_size)
        hist[hist_size]++;
    else if (length)
        hist[length - 1]++;
}

You can use a similar approach for print_histogram().


Forgive my ignorance, but isn't ActiveRecord::Base#enum just a method? Therefore, to help reduce duplication (but not eliminate it), you could do something like this:

STATUS_FLAGS = {
  'Pending' => 1,
  'Suspended' => 2,
  'Cancelled' => 3,
  'Pass' => 4,
  'Fail' => 5,
  'DPR' => 6,
  'Unknown' => 7,
  'Enrolled' => 8
}

class Enrolment < ActiveRecord::Base
  has_many :enrolment_presentations
  has_many :presentations, through: :enrolment_presentations

  enum status: STATUS_FLAGS
end

class EnrolmentPresentations < ActiveRecord::Base
  belongs_to :enrolment
  belongs_to :presentation

  enum status: STATUS_FLAGS
end

This, of course, doesn't eliminate duplication. One way around that might be to use a module as a mixin (though I'm not sure how that would work with ActiveRecord) or use singular inheritance to create a class that extends ActiveRecord::Base with the enum status, and then inherit from that - though I have to admit it feels hacky extending Active Records through inheritance.

As a stylistic note, it appears that the convention for #enum is to use lowercase names rather than PascalCase.


Setting global environment vars from Python or Bash

env | grep '^NOM'  would more exactly align with the sed command.

ensure you're exactly matching the variable name:

sudo sed -i "/^$VAR=/d" /etc/environment
# .................^

Use %-formatters for printf:

printf '%s="%s"\n" "$VAR" "$VAL"

In the function, use local to limit the scope of VAR and VAL

had another thought about that function. Change

sudo sed -i "/^$VAR/d" /etc/environment
printf "$VAR=$VAL\n" | sudo tee -a /etc/environment > /dev/null

to

tmpfile=$(mktemp)
grep -v "^$VAR=" /etc/environment > $tmpfile
echo "$VAR=$VAL" >> $tmpfile
sudo mv $tmpfile /etc/environment

That minimized any possibility that the /etc/environment file contains "invalid" data -- it overwrites the previous good file with the new good file all at once.


Your approach is wrong. It creates too complex code for a very simple and common problem. To use a sort of event aggregator to report progress is overkill.
First notice that you generally distinguish between IO bound tasks and CPU bound tasks. CPU bound tasks are executed on a background thread. The performance of CPU bound tasks can be improved by using multi threading. For example calculations are CPU bound.
CPU bound tasks should be executed in parallel using background threads.
Reading from a file or download data are IO bound tasks. The performance of IO bound tasks cannot be improved using multiple threads, but by improving the IO devices. For example a download's performance is not limited by available CPU resources, but transfer rate or other network conditions and hardware. Using a thread for IO bound tasks is a waste of resources, since IO bound operations generally require almost no CPU resources.
IO bound tasks should be executed asynchronously or event-driven.
This means you should check the library you are using to download resources for asynchronous methods and await them e.g. await DownloadAsync(). Alternatively subscribe to corresponding API events e.g. DownloadProgressChanged. Every modern UI related API exposes asynchronous methods.
Since all DispatcherObject objects are associated with a Dispatcher and each thread has its own Dispatcher, you can't use or access a DispatcherObject on a different thread then the thread the DispatcherObject was created on. Except the DispatcherObject derives from Freezable and is in a frozen state.
To access a DispatcherObject from a different thread you must use the associated Dispatcher.
The following examples show how to update e.g., a Progressbar from a background thread:
MainWindow.xaml
<Window>
  <Progressbar x:Name="CompressionProgressbar" />
</Window>

MainWindow.xaml.cs
private async Task CompressData()
{
  // Start a background thread
  await Task.Run(() =>
  {
    // Access the DispatcherObject from a background thread
    // using the associated Dispatcher
    this.Dispatcher.InvokeAsync(() => this.CompressionProgressbar.Value = 33.33);
  });
}

Since .NET 4.5 the recommended approach is to use IProgress<T> to report progress (or delegate data back to the UI thread). The library offers a ready to use implementation, the Progress<T> class. The constructor captures the current SynchronizationContext to post the registered callback to it. Therefore it is important to create the instance on the UI thread and then pass it to the background thread.
private async Task CompressData()
{
  // Create an instance of Progress<T> using the constructor
  // to register the callback which will be executed on the current thread e.g. to report the progress
  var progressReporter = new Progress<double>(progressValue => this.CompressionProgressbar.Value = progressValue);

  // Start a background thread
  await Task.Run(() =>
  {
    // Access the DispatcherObject from a background thread
    // using the IProgress<T> instance
    progressReporter.Report(33.33);
  });
}


Overall, this code looks very good.  Just two nitpicks here:

Give your function definitions lines to themselves:

let openChannelOn (connection:IConnection) = connection.CreateModel()

Use match statements unless you are checking a boolean value directly:

if ea <> null then
    let body = ea.Body
    let message = Encoding.UTF8.GetString(body)
    Some message
else
    None

Becomes:

match ea with
| null -> None
| _ ->
    let body = ea.Body
    let message = Encoding.UTF8.GetString(body)
    Some message


I think you meant to write max(val_1, val_2) instead of max(val_2, val_2).

Long Strings

I personally think the PEP8's 79 characters-per-line requirement is too strict and is not practically optimal. Increase it to, for instance, 100 for this code snippet and you'll get a more readable and concise code with all of the used strings fitting on a single line.

Other Improvements

I would apply an "Extract Variable" refactoring method and define a tuple of report template strings, which would allow to bring the nestedness 1 level down:

is_answer_correct = int(input()) == answer
print(ANSWER_TEMPLATES[is_answer_correct].format(answer))
correct_answers += is_answer_correct

where ANSWER_TEMPLATES is defined as:

ANSWER_TEMPLATES = (
    'No, the correct answer was {:d}',
    'Yes, the answer is {:d}'
)

As far as generating unique random pairs for the problem, there is also this approach involving keeping track of seen pairs and keeping generating a next pair until it has not been seen.


Re-writing rough JS code with loads of jQuery plugins

On the whole, I think you need to work on keeping it simple.

I would not write my own cross-browser event handling function if I use jQuery, I would leverage what jQuery provides.
This:

/* standard JS */
function InitStandard(jQuery) {
    //get device information
    this.device = new Device();

    // initialise jQuery, if device is capable
    if (this.device.quality === 1) {
        this.jqueryPlugins = new InitJquery(jQuery);
    }
}

/* initialise standard JS on load and pass in the jQuery object */
(function init(jQuery) {
    var js = new InitStandard(jQuery);
}(jQuery));

could be

(function InitStandard(jQuery) {
    //get device information
    this.device = new Device();

    // initialise jQuery, if device is capable
    if (this.device.quality === 1) {
        this.jqueryPlugins = new InitJquery(jQuery);
    }
}(jQuery));

Because you are not using var js anywhere.
Also, 1 should be assigned to a properly named constant like ADVANCED_DEVICE
addEvent(window, 'load', init); could be $( init )


There are several possible steps you can take to increase readability to your code, depending on how much control of the code you have and how much implementation details you which to hide.

Separate default values from database loading logic

By initializing setupConfiguration with default values by named properties and moving the database loading logic into a LoadFromDatabase() method you increase readability of the defaults:

var setupConfiguration = Configuracion.LoadFromDatabase(new NRG96.SetupConfiguration
{
    PRIMARY_VOLTAGE = 1,
    SECONDARY_VOLTAGE = 1,
    PRIMARY_CURRENT = 1,
    VOLTAGE_TYPES = "SIMPLES",
    MAIN_DEFAULT_SCREEN = SetupConfiguration.MainDefaultScreens.One,
    ENERGY_DEFAULT_SCREEN = SetupConfiguration.EnergyDefaultScreens.One,
    HARMONIC_CALCULUS = "THD",
    BACKLIGHT_SHUTDOWN_TIME = 1
});

I'm assuming SetupConfiguration can be defined by something like:

public class SetupConfiguration
{
    public int PRIMARY_VOLTAGE { get; set; }
    public ushort SECONDARY_VOLTAGE { get; set; }
    public ushort PRIMARY_CURRENT { get; set; }
    public string VOLTAGE_TYPES { get; set; }
    public MainDefaultScreens MAIN_DEFAULT_SCREEN { get; set; }
    public EnergyDefaultScreens ENERGY_DEFAULT_SCREEN { get; set; }

    public string HARMONIC_CALCULUS { get; set; }
    public byte BACKLIGHT_SHUTDOWN_TIME { get; set; }

    // Doesn't get saved to database because no public setter
    public bool HARMONIC_CALCULUS_IS_THD { get { return (HARMONIC_CALCULUS ?? "").ToUpper() == "THD"; } }

    public enum MainDefaultScreens
    {
        One = 1,
        Two
    }
    public enum EnergyDefaultScreens
    {
        One = 1,
        Second
    }
}

LoadFromDatabase() could then be implemented by:

public static SetupConfiguration LoadFromDatabase(SetupConfiguration defaultValues)
{
    return new SetupConfiguration
    {
        PRIMARY_VOLTAGE = (int)GetDouble("PRIMARY_VOLTAGE", defaultValues.PRIMARY_VOLTAGE, ParamUnidad.SinUnidad),
        SECONDARY_VOLTAGE = (ushort)GetDouble("SECONDARY_VOLTAGE", defaultValues.SECONDARY_VOLTAGE, ParamUnidad.SinUnidad),
        PRIMARY_CURRENT = (ushort)GetDouble("PRIMARY_CURRENT", defaultValues.PRIMARY_CURRENT, ParamUnidad.SinUnidad),
        VOLTAGE_TYPES = GetString("VOLTAGE_TYPES", defaultValues.VOLTAGE_TYPES, ParamUnidad.SinUnidad),
        MAIN_DEFAULT_SCREEN = (SetupConfiguration.MainDefaultScreens)GetDouble("MAIN_DEFAULT_SCREEN", (int)defaultValues.MAIN_DEFAULT_SCREEN, ParamUnidad.SinUnidad),
        ENERGY_DEFAULT_SCREEN = (SetupConfiguration.EnergyDefaultScreens)GetDouble("ENERGY_DEFAULT_SCREEN ", (int)defaultValues.ENERGY_DEFAULT_SCREEN, ParamUnidad.SinUnidad),
        HARMONIC_CALCULUS = GetString("HARMONIC_CALCULUS", defaultValues.HARMONIC_CALCULUS, ParamUnidad.SinUnidad),
        BACKLIGHT_SHUTDOWN_TIME = (byte)GetDouble("BACKLIGHT_SHUTDOWN_TIME", defaultValues.BACKLIGHT_SHUTDOWN_TIME, ParamUnidad.SinUnidad)
    };
}

Cleaning up database loading logic with helper methods

LoadFromDatabase() could be furter cleaned up by creating a couple of helper methods to do the actual loading from database:

static int Get(string name, int defaultValue) { return (int)GetDouble(name, defaultValue, ParamUnidad.SinUnidad); }
static byte Get(string name, byte defaultValue) { return (byte)GetDouble(name, defaultValue, ParamUnidad.SinUnidad); }
static ushort Get(string name, ushort defaultValue) { return (ushort)GetDouble(name, defaultValue, ParamUnidad.SinUnidad); }
static string Get(string name, string defaultValue) { return GetString(name, defaultValue, ParamUnidad.SinUnidad); }

public static SetupConfiguration LoadFromDatabase(SetupConfiguration defaultValues)
{
    return new SetupConfiguration
    {
        PRIMARY_VOLTAGE = Get("PRIMARY_VOLTAGE", defaultValues.PRIMARY_VOLTAGE),
        SECONDARY_VOLTAGE = Get("SECONDARY_VOLTAGE", defaultValues.SECONDARY_VOLTAGE),
        PRIMARY_CURRENT = Get("PRIMARY_CURRENT", defaultValues.PRIMARY_CURRENT),
        VOLTAGE_TYPES = Get("VOLTAGE_TYPES", defaultValues.VOLTAGE_TYPES),
        MAIN_DEFAULT_SCREEN = (SetupConfiguration.MainDefaultScreens)Get("MAIN_DEFAULT_SCREEN", (int)defaultValues.MAIN_DEFAULT_SCREEN),
        ENERGY_DEFAULT_SCREEN = (SetupConfiguration.EnergyDefaultScreens)Get("ENERGY_DEFAULT_SCREEN ", (int)defaultValues.ENERGY_DEFAULT_SCREEN),
        HARMONIC_CALCULUS = Get("HARMONIC_CALCULUS", defaultValues.HARMONIC_CALCULUS),
        BACKLIGHT_SHUTDOWN_TIME = Get("BACKLIGHT_SHUTDOWN_TIME", defaultValues.BACKLIGHT_SHUTDOWN_TIME)
    };
}

Automating database loading logic by reflecting on the configuration objects

Finally, if you want true magic and can make sure the configuration classes properties are named as in the database, you can automate LoadFromDatabase() with something like:

public static T LoadFromDatabase<T>(T defaultValues) where T : class, new()
{
    var result = new T();

    var getters = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
    foreach (var property in getters)
    {
        if (property.GetMethod != null && property.GetMethod.IsPublic
            && property.SetMethod != null && property.SetMethod.IsPublic)
        {
            var defaultValue = property.GetValue(defaultValues);
            if (property.PropertyType.Equals(typeof(int)))
            {
                var value = (int)GetDouble(property.Name, (int)defaultValue, ParamUnidad.SinUnidad);
                property.SetValue(result, value);
            }
            else if (property.PropertyType.Equals(typeof(byte)))
            {
                var value = (byte)GetDouble(property.Name, (byte)defaultValue, ParamUnidad.SinUnidad);
                property.SetValue(result, value);
            }
            else if (property.PropertyType.Equals(typeof(ushort)))
            {
                var value = (ushort)GetDouble(property.Name, (ushort)defaultValue, ParamUnidad.SinUnidad);
                property.SetValue(result, value);
            }
            else if (property.PropertyType.Equals(typeof(string)))
            {
                var value = GetString(property.Name, (string)defaultValue, ParamUnidad.SinUnidad);
                property.SetValue(result, value);
            }
            else if (property.PropertyType.BaseType.Name == "Enum")
            {
                var value = (int)GetDouble(property.Name, (int)defaultValue, ParamUnidad.SinUnidad);
                property.SetValue(result, value);
            }
        }
    }

    return result;
}

... and call the method with:

var setupConfiguration = NRG96.Configuracion.LoadFromDatabase<NRG96.SetupConfiguration>(new NRG96.SetupConfiguration
{
    PRIMARY_VOLTAGE = 1,
    SECONDARY_VOLTAGE = 1,
    PRIMARY_CURRENT = 1,
    VOLTAGE_TYPES = "SIMPLES",
    MAIN_DEFAULT_SCREEN = SetupConfiguration.MainDefaultScreens.One,
    ENERGY_DEFAULT_SCREEN = SetupConfiguration.EnergyDefaultScreens.One,
    HARMONIC_CALCULUS = "THD",
    BACKLIGHT_SHUTDOWN_TIME = 1
});

Loading all different configuration objects from the database could then be achieved without changing LoadFromDatabase<>().


Custom sorting a list of objects efficiently

Note that comparison doesn't have to return 1 or -1. For example returning 123 would have the same effect as returning 1. With this in mind, the firstGreaterCmp function could be somewhat simpler:

def firstGreaterCmp(a, b):
    difference = topicToDistance[a] - topicToDistance[b]
    if abs(difference) <= .001:
        if a.id < b.id:
            return 1
    return int(difference)

On the other hand, the comparison function must return an int, and since your value is a float, I had to cast it. I don't really know if that has a non-negligible cost or not.

UPDATE

Also, as @janne-karila pointed out in a comment,
int(difference) is 0 for a range of values (due to integer truncation),
while your original code never returns 0.
It depends on your use case whether this is acceptable or not.

In the Topic class, I find it somewhat strange that the id parameter comes last in the parameter list.
Normally I would expect an id field to be the first.

Your code doesn't follow PEP8. It would be better this way:

def firstGreaterCmp(a, b):
    if abs(topicToDistance[a] - topicToDistance[b]) <= .001:
        if a.id < b.id:
            return 1
    if topicToDistance[a] > topicToDistance[b]:
        return 1
    return -1

# sorting by key may be faster than using a cmp function
topics.sort(cmp=firstGreaterCmp)


Well, fine for good signals. Good signals means low noise level, absense of features like very slow volume change rates, etc.
Otherwise, you need things like FIR filter(s) to average and diffifentiate signal and use an interpolation to increase precision of the detection.


You tagged c++11, but your code does not look like C++11. You do not implement move construction and move assignment. You should implement them. Here's a sample implementation using the copy-and-swap idiom.

friend void swap(Vector& a, Vector& b)
{
    using std::swap;
    swap(a.capacity, b.capacity);
    swap(a.sizet, b.sizet);
    swap(a.arr, b.arr);
}

Vector(Vector&& v)
    :Vector{}
{
    swap(*this, v);
}

Vector& operator=(Vector v)
{
    swap(*this, v);
    return *this;
}

This way, you don't have to define a separate copy assignment operator.
Your default constructor sets arr to new int. This makes no sense and cannot be handled by the destructor. You should set arr to nullptr.
Use ++i, not i++, in discarded-result expressions. See Difference between i++ and ++i in a loop?.
Consider using standard algorithms instead of hand-crafted loops when plausible. For example:

for (int i = 0; i < sizet; i++)
    arr[i] = v.arr[i];
}

Can be replaced by

std::copy_n(v.arr, sizet, arr);

You will need to #include <algorithm> for this to work.
Your copy constructor uses assignment instead of member initializer clauses. You should use member initializer clauses uniformly. Now your copy constructor should look like this:

Vector(const Vector& v)
    :capacity{v.capacity},
     sizet{v.sizet},
     arr{new int[v.sizet]} // to avoid dependence on member declaration order
{
    std::copy(v.arr, v.arr + sizet, arr);
}

Where is the const overload for operator[], at, front, and back?
Your push_back is incorrect. It does not allocate any memory. You will get an out-of-range error when capacity exceeds the actual capacity. Same applies to resize.
size() should be const.
Your at does the same job as operator[]. at should check for out-of-range errors and raise an exception if index >= sizet.
front and back should return a reference instead of a value.
The implementation of back is wrong. It should return arr[sizet - 1].


CSS3 transitions performance enhancement

I'm pretty new to CSS, but I do have a few notes:

As @Jivings said, the animation worked nicely for me.  No stutter
or anything.
I would use Font Awesome instead of your envelope .png (but keep the PNG as a fallback for cases such as some IE versions not supporting SVG).  Why?  Because now I can scale the envelope infinitely (due to SVG graphics), and customization of the image becomes a whole lot easier (size, color, drop shadow, etc.).
You should give a little bit more space between the envelope picture and the item text.

nav:hover a {
    margin-left: 5%;
    opacity: 1;
}

I think it looks nicer with the picture and text centered.

nav:hover {
    text-align: center;
    width: 40%;
}

JSFiddle with the suggested changes.