Very suspicious approach

Lifetime of elements in std::vector is manager by the vector. I doubt that std::shared_ptr can intervene here at all. The idea is both hard to understand and hard to prove its correctness. Though, even if std::shared_ptr would be able to intervene...

Reference invalidation

Imagine the container already gave out some pointers, then someone puts more elements into the container and it reallocates elements into new location. The handed out pointers will not be able to get lock()ed, and the whole thing will fall. Even if nobody puts elements into it, problem description mentions deletion. On deletion pointers will get invalidated too.

Solution

I see two ways of solving this problem:

Use std::list. The problem requires references that are not invalidated in case of deletion. If you're not traversing the list a lot, and doing some heavy computation on it, probably cost of segmented memory layout will be negligible/affordable.
Block the thread that does deletion/resizing of the vector when you're performing some operations on already existing ones. This is the hard way, but arguably can be win-win situation if thread synchronization is done correctly.

Code Review

Initialize members on construction where possible

It is possible to pass this, &null_deleter to thisPtr in member initialization list:

Object3d::Object3d():
                   thisPtr(this, &null_deleter)
{}

Redundant destructor.

If it is empty and is not virtual, just don't declare/define it. If it is virtual, you can just = default it.
Double copy.

void World3d::SetCamera(std::shared_ptr<Camera> pCamera)
{
    m_pCamera = pCamera;
}

Copies pCamera twice. Pass by const reference to avoid second copy. May be compiler will figure it out, but in more complex case it might not be able to.

Testing

Testing is important.

Build script with testing.

There should be some script (CMake, make, python, whatever is available) to build the project and test it. It will provide confidence in claims.
It is better in the long run

Tests are like an investment. The time spend will come back when changes are made to the code.

Conclusion

Usually code has some places where it is slower, and some places that are optimized well. You could trade performance of some components for the other, or for easier implementation and correctness.


Gallery of employees with dynamic filtering

Make a lookup table. Then access by index:

var expertises = ["asset", "insurance", "wealth"];
expertise = expertises[$(this).index()];
showConsultant();

If you're worried about going out of bounds, add a range check:

var expertises = ["asset", "insurance", "wealth"];
var index = $(this).index();
if (0 <= index && index < expertises.length) {
    expertise = expertises[index];
    showConsultant();
}

You could even globally define these lists somewhere, so you could write enums.getExpertise(index).


Calculating difference statistics over a moving window

You've already made the key observation here, which is that most of the work is redone. Each time you pick a window, most of the calculations are the same as the previous window.

In fact it's much faster to do all the calculations ahead of time into one big ndarray, and then for each window, pick out the calculations that are relevant. So we don't need the temporary a and b lists.

How many dimensions do we need? Just starting point and length. It's going to be a triangular array, so we'll waste some space.

precomputed_results = np.zeros(l_win+1, l_data), dtype = int)
# First pass
for interval in range(1, l_win):
    for first_point_index in range(l_data-interval):
        # compute diff relative to elements [first_point_index] and [first_point_index+interval]
        # line will be similar to precomputed_results[...] = ...

# Second pass
for interval in range(1, l_win):
    for first_point_index in range(l_data-interval):
        # use slicing on precomputed_results


ViewConnection class looks cool, I think that's a clever use of tasks. But frankly I don't see why you can't have a

public string State { get {...} set {...}}

property on both view and viewmodel and solve your problem with two-way databinding. You can set this property on your viewmodel when you load your layout. If view is there - fine, it will be notified that the property has changed and you can handle this change on the view side (i.e. update datagrid with new state). If the view is not there - also fine, it will fetch the property from viewmodel as soon as you set its DataContext. In similar fashion you can save datagrid state on view side, set View.State and handle the new state in ViewModel.State property (i.e save it to file). You do not show your view class, but I don't see any problems with this approach off the bat, and I think that's how those things should be done normally.


This is something I always get confused with as well!!

I would probably think it's fine where it is but if you were considering moving it I might suggest using an interface and injecting that into the controller.  That way it doesn't matter where the latest friend information is persisted and the controller remains separate from this concern.

Although this might be overkill for your situation and example of this in use might be:

public interface IFriendProvider
{
   Friend GetLatest();
   void SaveLatest(Friend friend);
}

Your controller action might then become:

public ActionResult AddFriend(FriendsContext viewModel)
  {
        if (!ModelState.IsValid)
        {
            return View(viewModel);
        }

        // where _friendProvider has been supplied through the controller constructor
        // using DI  (See Ninject or Unity for example)
        _friendProvider.SaveLatest(new Friend()
        {
           FirstName = viewModel.FirstName;
           LastName = viewModel.LastName;
           Email = viewModel.UserEmail;
        });
}

Your implementation of the friendProvider would be something like:

public class SessionFriendProvider : IFriendProvider
{
   private readonly HttpContext __httpContext;

   // or instead of Context maybe the session object itself?
   public SessionFriendProvider(HttpContextBase context)
   {
      __httpContext = context;
   }

   public void SaveLatest(Friend friend)
   {
       _httpContext.Session["latest-friend"] = friend;
   }

   public Friend GetLatest()
   {
      return _httpContext.Session["latest-friend"] ?? new Friend();
   }
}


Improving a priority queue sketch in Racket/Scheme

Here are some general points before I start on more specific points:

I don't see any unit tests. Racket programmers often write many unit tests for each function. You can use the module+ construct and rackunit to easily write internal unit tests.
Indentation is important for clarity. I couldn't tell that everything was internal to heap at first because of the lack of indentation. Also, you can replace some of the lets with internal defines and make some of the internal functions into top-level functions to reduce right-ward drift.

More specific points:

It looks like you're using a dispatch function with internal state to keep track of the priority queue state. The more natural thing to do in Racket would be to create a new datatype using struct. This way, your implementation details don't leak through.
You use a dispatch function as the entry point to your simulated object. Simulating OO style in this fashion is not a very natural thing to do in Racket. Racket programmers tend to either use (1) the built-in classes & objects or (2) have a functional API with a function for each operation.
You use begin to sequence multiple effecting operations inside functions. These are actually unnecessary since Racket functions can have as many expressions in the body as you like.

Hope that helps. Cheers.


Is there a better way to implement this Huffman Algorithm in Python?

Really does belong on codereview.

Use four space indentation. This is the Python standard, and will make any code more "Pythonic". Edit: You're following PEP-8 in all other respects as far as I can tell, so if you like two space indentation, it's not a big deal. Your code is very easy to read.
You don't need to sort every time; you don't even need a fully sorted list. Python has a datatype for this -- it's called heapq. Use it's heappush and heappop methods, so you don't have to sort every time. You can actually write a single line loop to do the tree building. Read what that page says about priority queues -- it's what you're using.
You don't need anything like

return dict(map(lambda p: (p[0], p[1]), table[0].pairs))

just

return dict(table[0].pairs)

does exactly the same thing.
If you really want to minimize lines, everything before the while can be written as one line:

table = sorted((Node([[p[0], ""]], p[1]) for p in Counter(s).iteritems()), key = lambda n : n.frequency)


You could get rid of the code duplication by making use of the fact, that arel expressions are lazily evaluated:

def index
  @program = Program.approved.find(params[:program_id]) if params[:program_id]

  sites =
    if @program
      Site.where(program_id: @program)
    else
      Site.joins(program: :user)
    end
  if params[:tags]
    tags = params[:tags].split(" ")
    sites = sites.tagged_with(tags)
  end
  @sites = sites.page(params[:page])

  respond_to do |format|
    format.html
    format.json { render json: @sites }
  end
end

Because you're using ruby 1.9 hash syntax in the render expression I also adapted the other hashes. That seems more consistent for me.


Sure, you can play with the default argument value:

class AB:
    def __init__(self, data=None):
        self.data = data if data is not None else []

    def __add__(self, other):
        return AB(self.data + [other.arg])

Other notes:

list is a bad variable name as it is shadowing the built-in list keyword
remove redundant parentheses after the class name

Demo:

In [1]: ab = AB()

In [2]: ab += A(1)

In [3]: ab += A(2)

In [4]: print(ab.data)
[<__main__.A instance at 0x10afb14d0>, <__main__.A instance at 0x10afa0998>]


Java game that generates and compares random numbers, looking for matches

Besides minor improvements like consistent formatting and proper indentation I would like to target your random number generation:

int guess1 = 0;
int guess2 = 0;
int guess3 = 0;
int guess4 = 0;

guess1 = rand.nextInt(10);
guess2 = rand.nextInt(10);
guess3 = rand.nextInt(10);
guess4 = rand.nextInt(10);

do {

    guess1 = rand.nextInt(10);
    guess2 = rand.nextInt(10);
    guess3 = rand.nextInt(10);
    guess4 = rand.nextInt(10);

if ( guess1 == guess2 || guess1 == guess3 || guess1 == guess4 ) {
    guess1 = rand.nextInt(10);
}
if ( guess2 == guess3 || guess2 == guess4 ) {
    guess2 = rand.nextInt(10);
}
if ( guess3 == guess4 ) {
    guess3 = rand.nextInt(10);
}

} while (guess1 == guess2 || guess2 == guess3 || guess3 == guess4 || guess4 == ball1);

While not incorrect, that certainly looks a bit clumsy.

Since you want four unique random numbers, a better choice would be to create a list of numbers from 0-9, shuffle it and then simply take the first four elements. And while you're at it, convert your four individual variables guess1 to guess4 to a single int[] array of guesses.

This allows you to replace the above code with simply:

List<Integer> numbers = IntStream.range(0, 9).boxed()
        .collect(Collectors.toList());
Collections.shuffle(numbers);
int[] guesses = new int[4];
for (int i = 0; i < 4; i++) {
    guesses[i] = numbers.get(i);
}

(Refactor that into a separate method and you can re-use it for your balls generation as well.)

When guesses and balls are both arrays, the comparison could also be simplified to:

Arrays.equals(guesses, balls);

Arrays.equals:

  Returns true if the two specified arrays of ints are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.

(Emphasis by me)


What are the expensive operations you do?

Allocating memory for the copy of a std::string passed into splitString().
This can be fixed by accepting a std::string_view instead, or at least a constant reference instead of a copy.
See How exactly is std::string_view faster than const std::string&? and What is string_view? for details.

Allocating memory for the std::strings stored in the result-vector.
Those might be replacable with std::string_view if the argument is changed, but no guarantees. This would be a significant usage change.

Repeatedly shuffling all the rest of the string to the front when removing a match.
Just find the target and copy / reference from there.

Constructing the result-elements in-place using .emplace_back() can also save some effort.

Adding the option to not remove the separator would only really make sense if you allow multiple separators.
Regarding your code, I'm not sure whether you use the dreaded using namespace std;, or the far more benign using std::string; using std::vector;.
If the former, see Why is “using namespace std;” considered bad practice?.
One behavioral point I changed: You ignore the last entry if empty. I decided to preserve it always, thus even an empty string gets at least one result.
auto splitString(std::string_view in, char sep) {
    std::vector<std::string_view> r;
    r.reserve(std::count(in.begin(), in.end(), sep) + 1); // optional
    for (auto p = in.begin();; ++p) {
        auto q = p;
        p = std::find(p, in.end(), sep);
        r.emplace_back(q, p);
        if (p == in.end())
            return r;
    }
}


It is rather difficult to provide a complete review of the code without having access to it as a whole. For instance, the global name line in both functions is rather bad. Firstly because you're not modifying but just accessing name's value so you don't need it. Secondly because using this kind of global variables is bad anyway, and this might have different ways of solving depending on what you're doing with name in other parts of your code (to which OOP might be a way, but not necessarily the way).

Abstract the problem

Do not repeat yourself, it is bad practice and impair maintainability. Instead try to extract a pattern and parametrize it with the different values you need. Not accounting for the if a > b test in the substraction for now, the only thing that differ between the two functions is:

The operation to perform (both taking two arguments);
The representation of this operation.

You can thus define

def problems_1(operation, symbol):
    score = 0

    while score < 30:
        a = randint(1,10)
        b = randint(1,10)
        result = operation(a, b)

        answer = int(raw_input("%i %s %i = " % (a, symbol, b)))

        if answer == result:
            score = score + 1
            print "Good job. Current score is %d" % score

        elif answer != result:
            print "Oops, the correct answer is %i. Try another one." % result

    print "Good job, %s. You passed this course!" % name
    enter_lobby()

And call it using one of three ways:

def add(a,b):
    return a + b
def sub(a,b):
    return a - b
...
problems_1(add, '+')
problems_1(sub, '-')

problems_1(lambda a,b: a+b, '+')
problems_1(lambda a,b: a-b, '-')

import operator

problems_1(operator.add, '+')
problems_2(operator.sub, '-')

Using the operator module is neater since it allows you to reuse existing code.

Account for sorting operands

We left aside the problem of sorting the operands for the substraction problem. This can be incorporated back using a third parameter to tell the function whether or not we should try to sort the operands:

def problems_1(operation, symbol, sort=False):
    score = 0

    while score < 30:
        a = randint(1,10)
        b = randint(1,10)

        if sort and a < b:
           a, b = b, a   # Swap variables using tuple unpacking

        result = operation(a, b)

        answer = int(raw_input("%i %s %i = " % (a, symbol, b)))

        if answer == result:
            score = score + 1
            print "Good job. Current score is %d" % score

        elif answer != result:
            print "Oops, the correct answer is %i. Try another one." % result

    print "Good job, %s. You passed this course!" % name
    enter_lobby()

You can then call your function using

import operator

problems_1(operator.add, '+')
problems_1(operator.sub, '-', True)

You can also choose to sort unconditionally, it won't change the expected output for + or *; and it will force results to be greater than 1 for / (asuming your “divisions” functions ask for integral division). But having this optional parameter can come in handy when dealing with more difficult problems that can potentially benefit from having substraction produce negative results.

Expand on greater difficulty

I guess that the _1 at the end of the function name is for “easy” and that you have _2 and _3 types of functions which all look the same.

Again, don't repeat yourself¹. Parametrize your function instead. If all you need to change is the range of the randint calls, then you should use:

def problems(operation, symbol, min_op, max_op, sort=False):
    score = 0

    while score < 30:
        a = randint(min_op, max_op)
        b = randint(min_op, max_op)

        if sort and a < b:
           a, b = b, a   # Swap variables using tuple unpacking

        result = operation(a, b)

        answer = int(raw_input("%i %s %i = " % (a, symbol, b)))

        if answer == result:
            score = score + 1
            print "Good job. Current score is %d" % score

        elif answer != result:
            print "Oops, the correct answer is %i. Try another one." % result

    print "Good job, %s. You passed this course!" % name
    enter_lobby()

And that's it. This single tiny change allows you to remove at least 8, all look-alike, functions.

The call then becomes:

import operator

problems(operator.sub, '-', 1, 10, True) # easy
problems(operator.sub, '-', 10, 100, True) # medium
problems(operator.sub, '-', 100, 1000) # hard

Coding standards

Now that we removed a whole bunch of your code at once, let's write it properly. For starter, you should have noticed that I changed your sum variable into result. This is both because it better express the intent and because sum is a builtin function in Python that you are shadowing. Try to avoid using builtin functions names for your variables, it makes the code less understandable.

Second, the use of % format specifiers is to be replaced with the format string syntax. It is pretty simple for basic use (you don't even need to handle types yourself) and can be much more expressive it need be. For instance "%i %s %i = " % (a, symbol, b) becomes "{} {} {}".format(a, symbol, b).

Next, answer == sum and answer != sum are already complementary clauses. There is no third (or fourth, or whatever) choice. Thus you can use an else instead of your elif.

Last, your code will fail if the user enters something that fails to be an integer. int(raw_input(...)) will raise ValueError in such cases. You could account for that using a try .. except clause and providing a default value to answer (such as None) if the user inputs something unparsable.

The code thus become:

def problems(operation, symbol, min_op, max_op, sort=False):
    score = 0

    while score < 30:
        a = randint(min_op, max_op)
        b = randint(min_op, max_op)

        if sort and a < b:
           a, b = b, a   # Swap variables using tuple unpacking

        result = operation(a, b)

        try:
            answer = int(raw_input("{} {} {} = ".format(a, symbol, b)))
        except ValueError:
            answer = None

        if answer == result:
            score += 1
            print "Good job. Current score is {}".format(score)
        else:
            print "Oops, the correct answer is {}. Try another one.".format(result)

    print "Good job, {}. You passed this course!".format(name)
    enter_lobby()

Rest of the code

In addition to the speech about using global at the beginning of this post, the call enter_lobby() at the end of the function seems suspicious. What I imagine is that this enter_lobby() function calls one of the various “problems” once, and that's it. Making each problem responsible of returning to it.

This is wrong because it is an implicit recursion. And potentially an infinite one. The lobby calls a problem, which calls a lobby, which calls an other problem, which calls a third lobby… See what I mean? The control flow never return to the first lobby, thus consumming memory to manage the call stack and potentially turning into a RuntimeError: maximum recursion depth exceeded.

This also impairs reusability of your code. Each problem should only be responsible of it's own duty and shouldn't have to know about the rest of the code. If you want to make sure that you stay in the lobby at the end of each problem, you should probably put your enter_lobby code into some kind of infinite loop.

This loop being either within enter_lobby or in the caller body does depend on your intent and the rest of your code, though.

¹ Oh, snap!


I can't fault the code (assuming it works). Looks good.

But what I would point is that to improve flexibility you should probably use numbered replacement sites.

The problem with format strings is that for I18N and L10N the format strings will be pulled out of the source code and placed in a separate resource file for translation. Unfortunately not all languages use the same noun verb ordering so for I18N to work efficiently you need a flexible placement strategy (so that you only need to change the string resource not the code).

English:

// "The disk named MyDisk contains 300 files."
"The disk named %1 contains %2 files" % DiskName % FileCount;

Basque:

// "300 fitxategi ditu, izendatutako MyDisk diskoa."
"%2 fitxategi ditu, izendatutako %1 diskoa." % DiskName % FileCount;

Or in your code:

std::cout << Format(stringresource.get("DiskString"), DiskName, FileCount) << std::endl;


Use a BufferedInputStream to speed up the disk access. If that's not enough, you can read the file line-by-line and use split() to break it into individual numbers.


Euclidian distance - optimization and casting

dstances[i]=(int)sqrt((dx*dx)+(dy*dy));

This only converts to double once. it will do all the math integer style and and then convert it to a double just before calling sqrt.

    distances[i]=(int)sqrt((double)(dx*dx)+(dy*dy));

This is actually the same as:

    distances[i]=(int)sqrt(  ((double)(dx*dx))   + (dy*dy));

not:

    distances[i]=(int)sqrt((double)(  (dx*dx)) + (dy*dy)  );

As a result it will convert dx*dx to double, then convert dy*dy to double then add them and the pass it off to sqrt.

In modern computers floating point numbers are really fast, in some cases even faster then integers. As a result, you well be much better off to use double throughout rather then converting from ints to doubles and back again. The conversion between int and double is expensive so avoiding it may actually be your best bet.

A common trick used in algorithms which need to work with distances is to rework the algorithm so that you can use the square of the distance. That way you can avoid the expensive sqrt call. This works because x*x < y*y iff x < y. Be careful though, whether or not you can do this depends on what you are doing with that distance.


Custom error/fatal error and exception handler in PHP

The first thing which comes to my mind when reading your code is how concurrent requests with errors can tamper with the written data. You can aqquire an exclusive lock on the file for the duration of the writing with the flag LOCK_EX (see file_put_contents documentation).

I would also make sure the file 500.php actually exists. You could also avoid using require_once since the script is terminated afterwards and the possibility for another include is non-existent.

I assume the comments are because the code is posted here, since none of them provide extra information your code doesn't provide. Otherwise I think your code look fine. The variables have meaningful names and the indentation is good.

Happy coding!


The fastest way to find one unique value when all other values are the same

Benchmarks!
Benchmarks for lists with a thousand or a million elements, with the unique element in the middle of the array to reflect the "typical"/"average" case. The results are times, so lower=faster.
n=1000
0.90 find_uniq_Jacques
1.18 find_uniq_tinstaafl_1
0.59 find_uniq_tinstaafl_2
0.88 find_uniq_GZ0_1
0.14 find_uniq_GZ0_2
0.88 find_uniq_Peilonrayz
0.22 find_uniq_RootTwo
0.26 find_uniq_HeapOverflow_1
0.28 find_uniq_HeapOverflow_2
0.26 find_uniq_HeapOverflow_3
0.09 find_uniq_HeapOverFlow_Codewars
0.06 find_uniq_HeapOverflow_GZ0
0.57 unique_different_ethiy
0.28 find_uniq_KyleG_1
0.25 find_uniq_KyleG_2

n=1000000
0.94 find_uniq_Jacques
1.36 find_uniq_tinstaafl_1
0.68 find_uniq_tinstaafl_2
0.99 find_uniq_GZ0_1
0.19 find_uniq_GZ0_2
0.98 find_uniq_Peilonrayz
0.19 find_uniq_RootTwo
0.23 find_uniq_HeapOverflow_1
0.26 find_uniq_HeapOverflow_2
0.25 find_uniq_HeapOverflow_3
0.09 find_uniq_HeapOverFlow_Codewars
0.04 find_uniq_HeapOverflow_GZ0
0.57 unique_different_ethiy
0.28 find_uniq_KyleG_1
0.22 find_uniq_KyleG_2

Done with Python 3.8.1 32 bit on Windows 10 64 bit.
Benchmark code:
from timeit import timeit
from collections import Counter
from itertools import groupby

solutions = []
def register(solution):
    solutions.append(solution)
    return solution

@register
def find_uniq_Jacques(arr):
    nums = list(Counter(arr).items())
    data = [i for i in nums if i[1] == 1]
    return data[0][0]

@register
def find_uniq_tinstaafl_1(arr):
    for i in range(len(arr)-1):
        if arr[i] != arr[i+1]:
            if i == 0 and arr[i] != arr[i + 2]:
                return arr[i]
            return arr[i + 1]

@register
def find_uniq_tinstaafl_2(arr):
    for i in range(0,len(arr) - 1, 2):
        if arr[i] != arr[i+1]:
            if i == 0:
                if arr[i] != arr[i + 2]:
                    return arr[i]
                return arr[i + 1]
            else:
                if arr[i] != arr[i-1]:
                    return arr[i]
                return arr[i + 1]
    return arr[-1]

@register
def find_uniq_GZ0_1(arr):
    return next(k for k, freq in Counter(arr).items() if freq == 1)

@register
def find_uniq_GZ0_2(arr):
    group_iter = groupby(arr)
    k1, g1 = next(group_iter)
    c1 = len(list(g1))
    k2, g2 = next(group_iter)
    if c1 > 1:
       # Group g1 has more than one element
       return k2
    try:
       # Group g2 has more than one element
       next(g2)
       next(g2)
       return k1
    except StopIteration:
       # Both g1 and g2 has one element
       return k2 if next(group_iter)[0] == k1 else k1

@register
def find_uniq_Peilonrayz(arr):
    return Counter(arr).most_common()[-1][0]

@register
def find_uniq_RootTwo(arr):
    a, b = set(arr)
    return a if arr[:3].count(a) < 2 else b

@register
def find_uniq_HeapOverflow_1(arr):
    a = arr[0]
    if a not in arr[1:3]:
        return a
    for b in arr:
        if b != a:
            return b

@register
def find_uniq_HeapOverflow_2(arr):
    dupe = sorted(arr[:3])[1]
    for x in arr:
        if x != dupe:
            return x

@register
def find_uniq_HeapOverflow_3(arr):
    a = arr[0]
    for b in arr:
        if b != a:
            return b if a in arr[1:3] else a

@register
def find_uniq_HeapOverFlow_Codewars(arr):
    arr.sort()
    return arr[-(arr[0] == arr[1])]

@register
def find_uniq_HeapOverflow_GZ0(arr):
    group_iter = groupby(arr)
    k1, _ = next(group_iter)
    k2, g2 = next(group_iter)
    next(g2)
    return k1 if k2 in g2 else k2

@register
def unique_different_ethiy(iterable):
    # assert isinstance(iterable, Iterable)
    # assert len(iterable) > 2
    if iterable[0] != iterable[1]:
        return iterable[0] if iterable[1] == iterable[2] else iterable[1]
    else:
        for element in iterable[2:]:
            if element != iterable[1]:
                return element

@register
def find_uniq_KyleG_1(arr):
    common = arr[0]
    if common not in arr[1:3]:
        return common
    for a, b in zip(arr[1::2], arr[2::2]):
        if a != b:
            if a == common:
                return b
            else:
                return a
    return arr[-1]

@register
def find_uniq_KyleG_2(arr):
    iterator = iter(arr)
    common = next(iterator)
    if common not in arr[1:3]:
        return common
    for a, b in zip(iterator, iterator):
        if a != b:
            if a == common:
                return b
            else:
                return a
    return arr[-1]

# Run the benchmarks
for e in 3, 6:
    n = 10**e
    number = 10**(7 - e)  # fewer number of runs for larger n
    print(f'{n=}')
    arr = [0] * n
    arr[n // 2] = 1

    # Repeat round-robin to reduce effects of CPU speed changes etc
    timeses = [[] for _ in solutions]
    for i in range(20):
        for solution, times in zip(solutions, timeses):
            arrs = iter([arr[:] for _ in range(number)])
            t = timeit(lambda: solution(next(arrs)), number=number)
            times.append(t)
        print(i, end=' ')
    print()
    for solution, times in zip(solutions, timeses):
        print('%.2f' % min(times), solution.__name__)
    print()


Smallest element in an array that is repeated exactly ‘k’ times

Interface

There's no point in limiting your function inputs to a vector. You can take two input iterators instead. It'll make your function more flexible and more "standard library-like".
One function should do one focused thing. Your function finds such an element  and  prints it as the same time. These concerns are unrelated. You can return std::optional<T> instead to represent either such an element or its absence. Note: it works for C++17 only. You can use boost::optional or return a smart pointer if it's not available.

Modern C++

There's no need for things like this anymore:

typename std::map<T, int>::iterator itr;
for(itr = count.begin(); itr != count.end(); itr++)

for (const auto& kv : count) is much better, isn't it?
You can also use initialization list to create a vector with the elements you need: std::vector<char> v({'r', 't',..., 's'})

Performance

for (T x : vec) creates an unnecessary copy. Use for (const T& x : vec) or for (const auto& T : vec) instead.
You can also use std::unordered_map to do the counting and then choose the smallest element (it's more efficient because one can find the minimum in O(n). It's "easier" than sorting the input). One caveat: you need a hash function for T in this case. You can pass it as another template parameter, defaulted to std::hash.


I would re-structure code to improve on readability and avoiding code duplication while decreasing the nestedness depth level - remember that "Flat is better than nested".

I would probably first fail fast if date value is given and has an invalid format. Then, I would define a queryset variable which will help us keep the common parts of the query while building it.

Also, you may pre-compile the regular expression and define it as a proper Python constant - in upper case with underscores.

Something along these lines:

# fail fast if the date value is invalid
if date_value and not DATE_FILTER_PATTERN.match(date_value):
    log.error('Invalid date value parameter: %r', date_value)
    return None

queryset = Model.Bits.query.filter(Model.Bits.bit_type == bit_type)
if not date_value or date_value.lower() == 'latest':
    queryset = queryset.order_by(Model.Bits.published.desc())
else:
    queryset = queryset.filter(Model.Bits.published == date_value)

return queryset.limit(settings.max_bits).all()

where DATE_FILTER_PATTERN is defined as:

DATE_FILTER_PATTERN = re.compile(r'\d{4}-((1[0-2]|[1-9])|0[1-9])-((3[01]|[12][0-9]|[1-9])|0[1-9])')


Random thoughts

In this scenario, there's few implementation details making me ask "why"?

In ApprovalRoute what benefits LinkedList<T> gives over any other IEnumerable<T> ?
In ApprovalStep and ItemToApprove classes is it necessary to make Approved property    nullable ?
Won't it, at least, hurt coder's eyes if bool type is compared using equality operator == instead of someBool or !someBool ?

And to anwer myself right-away

I think it could be e.g. Queue<T> since

  ItemToApprove goes sequentially through all steps until gets status
  Approved

No, because default value will always be false, it is never checked if property  HasValue and there's no separate logic for nulls.
Yes, it hurts the eyes and makes you say nonconstructive things like "WTF dude". Just don't do it.

On the higher level then

  I think this design has some smell because calling Approve delegates further down to
  ApprovalStep.
  itemToApprove.Approve(new Approver(approverName));

You are right. Now it feels like the ItemToApprove is actually approving something. This method shouldn't exist.

  The second smell I feel more naturally call Approve on Approver passing ItemToApprove
  approver.Approve(itemToApprove);

Again you are right. But in this case it would seem than approver is approving the item itself, not a step along the route.

Suggestions

I'd remove the Approve method from ItemToApprove and ApproveStep classes and make it ApprovalRoute's responsibility to dequeue ApprovalSteps as they are approved. Dequeued step is the current step and when queue is empty, item is fully approved.

Better yet I'd pass the ItemToApprove along the ApprovalRoute, not the other way around. You could also have multiple items going down the same route at the same time, all having their own "states".

Something like below.

Related dotnet Fiddle can be found here https://dotnetfiddle.net/6BlA30 (web page "console" seems little buggy though).

public class Program
{
    // console app for testing
    public static void Main()
    {
        // some items
        var item1 = new ItemToApprove("item1");
        var item2 = new ItemToApprove("item2");

        // approvers
        var approver1 = new Approver("app1");
        var approver2 = new Approver("app2");

        // steps w/ authorized approvers
        var step1 = new ApprovalStep("step1", approver1);
        var step2 = new ApprovalStep("step2", approver1, approver2);

        // create route
        var route = new ApprovalRoute("route1", new[] { step1, step2 });
        // add items to current route
        route.AddItems(item1, item2);

        // start manual testing
        Console.WriteLine("** {0} has {1} items **", route.Name, route.Items.Count());
        while (route.Items.Any())
        {
            Console.Write("> ");
            string input = Console.ReadLine() ?? string.Empty;
            var parts = input.Split(' ');

            if (parts.Length == 2)
                route.ApproveStep(new ItemToApprove(parts[0]), new Approver(parts[1]));
            else if (input.Equals("?"))
                route.Status();
        }
        Console.WriteLine("No more items in route");
        Console.ReadLine();
    }
}

Implementation

For examples sake all classes are simplistic and inherit abstract ModelBase.

public abstract class ModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string Name { get; set; }

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        return (Name == ((ModelBase)obj).Name);
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }
}

Actual "business objects" below

public class ItemToApprove : ModelBase
{
    private bool _isApproved;

    public ItemToApprove(string name)
    {
        Name = name;
    }

    public bool IsApproved
    {
        get { return _isApproved; }
        set { _isApproved = value; OnPropertyChanged(); }
    }
}

public class Approver : ModelBase
{
    public Approver(string name)
    {
        Name = name;
    }
}

public class ApprovalStep : ModelBase
{
    public ApprovalStep(string name, params Approver[] approvers)
    {
        Name = name;
        Approvers = approvers;
    }

    public IEnumerable<Approver> Approvers { get; private set; }
}

public class ApprovalRoute : ModelBase
{
    // sequential steps in this route
    private readonly List<ApprovalStep> _steps;
    // items and step indexes
    private readonly Dictionary<ItemToApprove,int> _itemsInRoute =
        new Dictionary<ItemToApprove,int>();

    public ApprovalRoute(string name, params ApprovalStep[] steps)
    {
        Name = name;
        _steps = new List<ApprovalStep>(steps);
    }

    public void AddItems(params ItemToApprove[] items)
    {
        foreach (var item in items)
        {
            item.PropertyChanged += (sender, args) =>
                {
                    if (item.IsApproved)
                        Console.WriteLine("Item '{0}' fully approved", item.Name);
                };
            _itemsInRoute.Add(item, 0);
        }
    }

    public IEnumerable<ItemToApprove> Items { get { return _itemsInRoute.Keys; } }

    public void ApproveStep(ItemToApprove item, Approver approver)
    {
        if (!_itemsInRoute.ContainsKey(item))
        {
            Console.WriteLine("There is no '{0}' on '{1}'", item.Name, Name);
            return;
        }

        int index = _itemsInRoute[item];
        var step = _steps[index];

        if (step.Approvers.Contains(approver))
        {
            Console.WriteLine("{0} for {1} approved by {2}",
                step.Name, item.Name, approver.Name);

            index++;
            if (index > _steps.Count - 1)
            {
                _itemsInRoute.Single(i => i.Key.Equals(item)).Key.IsApproved = true;
                _itemsInRoute.Remove(item);
            }
            else
            {
                _itemsInRoute[item] = index;
            }
        }
        else
        {
            Console.WriteLine("{0} for {1} can only be approved by {2}",
                step.Name, item.Name, string.Join(",", step.Approvers.Select(a => a.Name)));
        }
    }

    public void Status()
    {
        foreach (var entry in _itemsInRoute)
            Console.WriteLine("{0} at {1}", entry.Key.Name, _steps[entry.Value].Name);
    }
}

Hope this made any sense.


Recursive function with Promise and setTimeout to ping DOM

This function will certainly do the job. Couple of nitpicks:

You might consider replacing el !== null && el.length !== 0 with el && "nodeType" in el
Every time the elementFinder is called, you are defining a new function in memory called checkerFn, instead you can reuse it, but probably you'll have to pass interval and maxTries as a parameter to it:

const finder = function(){
   function elementFinder (..){
      ...
   }
   function checkerFn (..) {
      ...
   }
   return elementFinder;
}();

Consider switching to requestAnimationFrame (rAF); for tasks/animations that does not have to be executed with sub-millisecond precision can be handled by rAF. The good thing with rAF is that if the tab is out of focus, it won't run.
If you are simultaneously searching for several elements at the same time, multiple setTimeout/rAF calls will have to be executed. For a couple of elements/tasks this is not an overhead, but if you have many, it makes sense to execute 1 setTimeout/rAF per 'tick' and process the tasks in there. For this you will need to modify your code to store tasks in some sort of ledger.
I see that you are using Promises, which is a great idea, perhaps to return a thenable from your function which you can execute other tasks once the element is available. The problem with Promises is that you cannot 'break' out of it, you'll have to add some sort of breaking mechanism to your code. Also if you want to seamlessly support evergreen and older browsers, you'll need a Promise polyfill.
Although Promises bring a lot of convenience, they certainly bring an overhead (see perf differences between Native Promises and Bluebird's version). If the sole purpose is to return a thenable for constructing chains, this can certainly be implemented using only setTimeout/rAF. This alleviates the need for polyfill for olderbrowsers.


Is this the wrong way to handle AggregateException with Tasks

You are quite right. These exception handling blocks will never catch any task exceptions. The code should be modified to check the Task.IsFaulted flag in the continuation and check the Task.Exception property for the actual exception.

In fact, should an exception occur it will remain unhandled and your application will crash unless you attach an exception handler to TaskScheduler.UnobservedTaskException.

You should definitely check the "Exception Handling (Task Parallel Library)" article in MSDN for the proper ways to handle Task exceptions.

You should also take a look at the Async CTP for C#. It has a production license even though it is technically a CTP and it will make coding with Tasks a lot easier and safer, as you can see from the snippet I found here:

private async void FetchData()
{
    using (var wc = new WebClient())
    {
        try
        {
            string content = await wc.DownloadStringTaskAsync(
                new Uri("http://www.interact-sw.co.uk/oops/"));

            textBox1.Text = content;
        }
        catch (WebException x)
        {
            textBox1.Text = "Error: " + x.Message;
        }
    }
}

You can use the CTP just by adding a reference to the appropriate DLL. The resulting code will certainly be safer that what you posted here, CTP or not.


DateTime Extensions StartOfWeek, StartOfMonth and WorkingDays

First I'd like to pinpoint few details about methods' interface. You have an overloaded WorkingDays method, what I'd change:

Name does not explain what this functions does, I have to check its signature. Does it count the number of working days? Does it return a list of those days? For which period? Let's call it CountWorkingDaysInMonth() and there will be no need to guess.
Both freeDays and bankHolidays are not working days. There may be more: days company is closed, paid holidays and so on. Surely do not want to add a list for each one. Just take one changing signature to accept IEnumerable<DateTime> (and caller may easily use Enumerable.Concat() to build the right list.
Validate your inputs.

Inside the function I'd try to help the reader using the methods you already defined:

var beginningOfCurrentMonth = dt.StartOfMonth();
var beginningOfNextMonth = beginningOfCurrentMonth.AddMonths(1);

Note the explicative names and the fact that I'm reusing StartOfMonth() instead of duplicating its code (you'll see later why).

Let's introduce a generator (useful if you're working with consecutive dates):

IEnumerable<DateTime> AllDaysInInterval(DateTime start, DateTime end)
{
    Debug.Assert(end > start);

    for (var current = start; current < end; current = current.AddDays(1))
        yield return current;
}

Declare a local function to determine if a day is a working day or not:

bool IsWorkingDay(DateTime day)
    => !freeDays.Contains(day.DayofWeek) && !notWorkingDays.Contains(day);

Now you can count them:

return AllDaysInInterval(beginningOfCurrentMonth, beginningOfNextMonth)
    .Count(IsWorkingDay);

Short, easy to understand and you now created few reusable functions you may need elsewhere. Putting things all together:

public static int CountWorkingDaysInMonth(this DateTime dt,
    IEnumerable<DayOfWeek> freeDays,
    IEnumerable<DateTime> notWorkingDays)
{
    if (freeDays == null)
        throw new ArgumentNullException(freeDays);

    if (notWorkingDays == null)
        throw new ArgumentNullException(notWorkingDays);

    var beginningOfCurrentMonth = dt.StartOfMonth();
    var beginningOfNextMonth = beginningOfCurrentMonth.AddMonths(1);

    return AllDaysInInterval(beginningOfCurrentMonth, beginningOfNextMonth)
        .Count(IsWorkingDay);

    bool IsWorkingDay(DateTime day)
        => !freeDays.Contains(day.DayofWeek) && !notWorkingDays.Contains(day);
}

Now it's time to go back to StartOfMonth(). Is it always 1st the first day of the month? No. Not every date is a valid date in every calendar. You may, or may not, need to care about this but you should clearly document it (and be aware of).

In StartOfWeek() you can make your code easier to read.

int diff = ((dt.DayOfWeek - startOfWeek)) % 7; has unnecessary parenthesis and diff does not say anything about its content. Also it's not used if startOfWeek is Sunday.
-1 * diff should simply be -diff.
IMO (7+(startOfWeek - dt.DayOfWeek)) % 7 is clearer if moved outside, to a local variable.

What to do? Just (temporary!) introduce a local function to calculate the number of days from the beginning of the week:

int NumberOfDaysFromBeginningOfWeek()
{
    if (startOfWeek == DayOfWeek.Sunday)
        return (7 + (startOfWeek - dt.DayOfWeek)) % 7;

    return (dt.DayOfWeek - startOfWeek) % 7;
}

Is it what we want? Doesn't it look too complicate? It does then it's probably wrong. Algorithm must be much simpler than that. Let's first calculate the number of days elapsed from the beginning of the week without any special case:

int daysFromBeginningOfWeek = dt.DayOfWeek - startOfWeek;

What's wrong with that? Well, we're relying with enumeration values but week may begin any day (it depends on the culture). What may happen if our day is before the beginning of the week? Number goes negative. Let's add the number of days in a week and it will be right:

int NumberOfDaysFromBeginningOfWeek()
{
    int count = dt.DayOfWeek - startOfWeek;
    if (count < 0)
        return count + 7;

    return count;
}

Note that I'm simplifying this code with a huge assumption: there are always seven days in a week. It's not true and you should read the value from the calendar. Final code will be slightly more complicate than this but I guess you've got the idea. Putting things together:

public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
    return dt.AddDays(-NumberOfDaysFromBeginningOfWeek());

    int NumberOfDaysFromBeginningOfWeek()
    {
        int count = dt.DayOfWeek - startOfWeek;
        if (count < 0)
            return count + 7;

        return count;
    }
}

In this last case local function is more educational than useful, reader should absolutely feel free (!) to replace it with a local variable (with a proper descriptive name.)

Please note: I wrote all this code here without any testing. Do not underestimate date/time handling and write your own huge, big, extensive unit testing to include all corner cases, calendars and cultures you may think of and, most importantly, never ever make any assumption about dates. If there is a property somewhere (Calendar, Culture or DateTime) then use it.


Extension method to run any async method synchronously

Per the comment by @t3chb0t, all I needed was this:

task.GetAwaiter().GetResult()

In context:

bool MySyncMethod (bool throwException)
{
    return MyAsyncMethod(throwException).GetAwaiter().GetResult(); //this is the only line that's changed
}
async Task<bool> MyAsyncMethod (bool throwException)
{
    if (throwException)
        throw new ArgumentException(nameof(throwException));
    return await Task.Run(() => true);
}


My implementation of the Union-Find data structure in MATLAB

I made a scrip that executes your data structure to test it. It doesn't verify correctness, it's just for timing purposes.

tic
uf = UnionFind;
uf.addItem(1);
for ii = 2:10000
    uf.addItem(ii);
    n = randi(4);
    if n == 4 % happens in 25% of cases
        uf.Union(ii, uf.Find(randi(ii-1)));
    end
    if n ~= 1 % happens in 75% of cases
        uf.Union(uf.Find(ii), uf.Find(randi(ii-1))); % ii is no longer necessarily the root
    end
end
toc

Basically, it adds 10,000 elements to the data structure, taking the union of the new element with a randomly selected prior element in 50% of the cases, and with two prior elements in an additional 25% of cases. This does not exactly match how the data structure will be used in a connected components labeling algorithm (Find would be called much more frequently), but it gets close.

This script takes about 1.7 s to run using MATLAB Online (R2019b). Making the simple change of replacing the containers.Map with a normal numeric array:

   properties
       %PARENT = containers.Map('KeyType', 'double', 'ValueType','any');
       PARENT = [];
   end

changes the execution time to 0.097 s. containers.Map is not a very efficient data structure (it's a custom class, much like any user can write, which is obviously going to be more expensive to access than a native type). Assuming that the elements are consecutive integers (as should be the case in the connected component labeling algorithm and any other image processing algorithm that uses Union-Find), there is no advantage whatsoever to using a map, a simple array can be indexed using the element's value.

A second improvement that can be made to the code is in usability: the Union operation should always be made on two roots. It is convenient to have the Union function find the roots of its two input arguments, and it prevents wrong use (taking the union with a non-root element would produce wrong results in any algorithm using this data structure):

       function Union(obj, setOne, setTwo)
          %obj.PARENT(setOne) = setTwo;
          obj.PARENT(obj.Find(setOne)) = obj.Find(setTwo);
       end

We can now simplify our test code to not call Find at all. An additional improvement is to return the new root. This is quite common as well, and will also improve our test code:

       function root = Union(obj, setOne, setTwo)
          root = obj.Find(setTwo);
          obj.PARENT(obj.Find(setOne)) = root;
       end

Typically the Union operation selects the smaller of the two trees to become the child of the other. It is however not directly clear if the additional storage space and logic required to maintain the tree sizes is worth it, one would have to implement this and compare to be sure. A simple alternative is to always make the root with the smaller index the parent of the other tree. This ensures that, more often than not, it is the larger tree that will be the parent. It could look like this:

       function root = Union(obj, setOne, setTwo)
          roots = sort([obj.Find(setOne), obj.Find(setTwo)]);
          obj.PARENT(roots(1)) = roots(2);
          root = roots(1);

This increases runtime by about 40%, so it's not a good change.

Our test code is now simplified to:

tic
uf = UnionFind;
uf.addItem(1);
for ii = 2:10000
    root = ii;
    uf.addItem(root);
    n = randi(4);
    if n == 4 % happens in 25% of cases
        root = uf.Union(root, randi(ii-1));
    end
    if n ~= 1 % happens in 75% of cases
        root = uf.Union(root, randi(ii-1));
    end
end
toc

Regarding the use of handle as a base class: this converts the class into a "handle class", objects of this type cannot be copied, all "copies" refer to the same underlying data. This leads at times to unexpected behavior in MATLAB, where typically b=a, b(1)=0 does not not change a. However I think in this case it is reasonable to use a handle class for this data structure, for the same reasons that MATLAB's containers.Map is a handle class.

Path compression. Union-Find data structures do not become truly efficient until one implements path compression. This means that trees remain totally flat, with all leaves pointing directly at the root. Find in this case is usually an O(1) operation, rather than O(log n), converting the CLL algorithm that uses this data structure from O(n log n) to something that is nearly O(n).

Path compression is typically implemented using recursion. Implementing it without recursion is quite awkward. But MATLAB's function calls are still quite expensive, so it is not directly clear that this would be an improvement. Again, one would need to implement it and compare to know for sure.

The code in the OP uses tree halving instead. This is a reasonable compromise because it can be implemented without recursion.

Path compression would look like this:

       function root = Find(obj, item)
          root = obj.PARENT(item);
          if root ~= item
              root = obj.Find(root);
              obj.PARENT(item) = root;
          end
       end

This increases the test code running time by about 15%, so it is not a good change.

Finally:

A variable name in all caps (PARENT) looks strange to me, using all lowercase letters would be more in line with customary MATLAB style.
The constructor is commented out. You don't need this constructor in most cases, you could either delete it altogether, or uncomment it. A block of commented out code can be confusing.
There is no help text. A comment block at the top of the file should explain the purpose of the class and how to use it. Typing help UnionFind in MATLAB will show this comment block. Likewise, each function should have some documentation as a comment block either just above or just below the function line.


Parsing input in form of 'CMD NUM NUM' (num could be special char '%')

Overall Impression

The code is pretty good. The structure of the code is good, good use of typedef. The code uses that safe version of string comparison strncmp(string1, string2, maxLength). Each Variable is declared on a separate line.

One overall observation is the code is not very extendable.

The program might be more understandable to the user if = is used to get the result rather than %. This would also possibly allow the addition of a modulus operation.

Error Checking

There are at least 2 places in the code where error checking should be performed, the first is always check the return value of malloc(size_t size). If malloc() fails for some reason, it returns NULL access through a null pointer results in UB (Unknown Behavior). Quite often it terminates the program in some nasty manner.

It's always best to check user input for errors so that they can be reported and the user can correct their error.

Magic Numbers

There are Magic Numbers in the main() function (9, 4 and 3), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.

Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.

In the case of the array of Operations called ops you don't need to specify 4 in the array definition, and you can get the size after the creation of the array using this formula: sizeof(ops)/sizeof(*ops);

In the cases of using 9 and 3 define a constant values that can change the value throughout the program:

At the top of the file:

#define INPUT_COMMAND_SIZE 9
#define OPERATION_SIZE 3

Complexity

The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

Declare Variables When Needed

The original version of the C programming language did require variables to be defined at the top of the function, however, this hasn't been true since 1989. It is better to declare the variables when they are necessary to reduce the scope of the variables and make the code easier to understand and maintain.

Initialize Local Variables

The C programming language does not automatically initialize variables. Uninitialized variables can sometimes be the cause of UB. It is generally a best practice to always initialize variables when they are declared.

Horizontal Spacing

Code is much more readable when there is a space separating operators and operands in an expression: return a - b;.

System Macros for Exit Status

The code already includes stdlib.h for the definitions of malloc() and free(). Since stdlib.h is already included it would be better to use the system constants EXIT_SUCCESS and EXIT_FAILURE which can make the code more portable. These constants are defined in stdlib.h.

Example Using Suggestions

Note error checking on user input hasn't been added.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INPUT_COMMAND_SIZE 9
#define OPERATION_SIZE 3

typedef int (*calc_function)(int, int);

typedef struct operation {
    char *name;
    calc_function calculate;

} Operation;

int add(int a, int b)
{
    return a + b;
}

int sub(int a, int b)
{
    return a - b;
}
int mul(int a, int b)
{
    return a * b;
}

int divi(int a, int b)
{
    return a / b;
}

int programLoop(Operation *ops, int opsCount)
{
    int programStatus = EXIT_SUCCESS;
    char *command = malloc(INPUT_COMMAND_SIZE);
    if (command != NULL){
        while((command = fgets(command, INPUT_COMMAND_SIZE, stdin)) != NULL) {

            for(int i = 0; i < opsCount; ++i) {
                int result = 0;
                int a = 0;
                int b = 0;
                if (0 == strncmp(ops[i].name, command, OPERATION_SIZE)) {
                    command = strchr(command, ' ');
                    command++;
                    if (*command == '%') {
                        a = result;
                    } else {
                        sscanf(command, "%d", &a);
                    }
                    command = strchr(command, ' ');
                    command++;
                    if (*command == '%') {
                        b = result;
                    } else {
                        sscanf(command, "%d", &b);
                    }
                    result = ops[i].calculate(a, b);
                    printf("%d\n", result);
                }
            }
        }
        free(command);
    }
    else
    {
        fprintf(stderr, "Malloc returned NULL\n");
        programStatus = EXIT_FAILURE;
    }

    return programStatus;
}

int main() {
    Operation ADD = {"ADD", add};
    Operation SUB = {"SUB", sub};
    Operation MUL = {"MUL", mul};
    Operation DIV = {"DIV", divi};

    Operation ops[] = {ADD, SUB, MUL, DIV};

    int opsCount = sizeof(ops)/sizeof(*ops);

    return programLoop(ops, opsCount);
}


Iterate through slicer settings and print to PDF

Variables
Let's discuss variables a bit.

Always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.

When you don't define your variable, VBA will declare it as a Variant type that can hold any type of data. While this may be more flexible, it adds processing time to your macro as VBA decides or tests for the type. Additionally, since a Variant can be any type of data, you may miss out on valuable troubleshooting information on Type Mismatch

Variable names - give your variables meaningful names.

Personal preference - I avoid variables like i and j because they aren't descriptive. But, there's technically nothing wrong with using them as it's standard practice to iterate with i.

Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names.

That being said -
You don't declare x or i. But those aren't vary descriptive are they? Try:
Dim slicerButtonNumber As Long
Dim tableNumber As Long

You don't have great names for the variables you do declare -
wb - targetWorkbook
sc - targetSlicerCache
si - targetSlicerItem

Extending the names using descriptive words costs you nothing and saves you headaches!
Also, here:
Set targetSlicerCache = targetBook.SlicerCaches("tbl_" & tableNumber)

You're using a constant - "tbl_", so
Const TABLE_PREFIX as String = "tbl_"
Set targetSlicerCache = targetBook.SlicerCaches(TABLE_PREFIX & tableNumber)

It may not seem like much, but by declaring that at top, if it ever changes, you only need to change it in one place.
Same goes for PDFCreate:
Const SHEET_NAME As String = "Detail"
Const POPULATION_SHEET_NAME As String = "Population Detail"
Const SEPARATOR As String = " - "
Dim detailSheet As Worksheet
Set detailSheet = ThisWorkbook.Sheets(SHEET_NAME)
Dim populationSheet As Worksheet
Set populationSheet = ThisWorkbook.Sheets(POPULATION_SHEET_NAME)
Dim file_Name As String
Dim file_Path As String
Dim aPathValue As String

file_Path = "S:\MyFilefilePath\"
aPathValue = detailSheet.Range("T1").Value & SEPARATOR
file_Path = file_Path & aPathValue
file_Name = filePath & [TEXT(populationsheet.range("B1"),"mmm, yyyy")] & ".pdf"

detailSheet.ExportAsFixedFormat Type:=xlTypePDF, _
    filename:=file_Name, Quality:=xlQualityStandard, IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, OpenAfterPublish:=False

You don't need to Call subs, it's obsolete. Instead just use Sub argument, argument

Speed
Your set here is redundant
        For Each targetSlicerItem In sc.VisibleSlicerItems
            Set targetSlicerItem = targetSlicerCache.SlicerItems(targetSlicerItem.Name)

The For sets the items.
This is also unnecessary:
If Not targetSlicerItem Is Nothing Then

It won't be Nothing since you're only addressing the items that exist in the cache.
You can condense down
For slicerButtonNumber = 1 To 6
    For tableNumber = 1 To 7
    Set targetSlicerCache = targetBook.SlicerCaches(TABLE_PREFIX & tableNumber)
        targetSlicerCache.ClearAllFilters
        For Each targetSlicerItem In targetSlicerCache.VisibleSlicerItems
            If targetSlicerItem.Name = slicerButtonNumber * 10 Then
                targetSlicerItem.Selected = True
            Else
                targetSlicerItem.Selected = False
        End If
        Next targetSlicerItem
    Next i

You can however, remove one of your loops, the slicerButtonNumber loop
Const BUTTON_NUMBERS As String = "10,20,30,40,50,60"
Const DELIMITER As String = ","
Dim slicerButtonNumbers As Variant
slicerButtonNumbers = Split(BUTTON_NUMBERS, DELIMITER)

 For tableNumber = 1 To 7
    Set targetSlicerCache = targetBook.SlicerCaches(TABLE_PREFIX & tableNumber)
        targetSlicerCache.ClearAllFilters
        For Each targetSlicerItem In targetSlicerCache.VisibleSlicerItems
            If UBound(Filter(slicerButtonNumbers, targetSlicerItem.Name)) > -1 Then
               targetSlicerItem.Selected = True
            Else
                targetSlicerItem.Selected = False
            End If
        Next targetSlicerItem
    Next tableNumber


I have a big concern with this code. It uses local static variables, so this will result in race conditions if used in a multithreaded program.

I assume you did that to improve performance? Constructing the std::stringstream could potentially incur some overhead. So having that variable as a static would be understandable if you are sure no race conditions apply. But the str string certainly doesn't have to be a local static. Actually, it is not needed at all, since stringstream::str() exists.

I think you have two options here:

Make it thread-safe and cleaner at the cost of some extra object construction every call, which is probably not a big deal:

std::string to_string(int val) {
    std::stringstream ss;
    ss << val;
    return ss.str();
}

Or, if you need ultimate performance and cannot afford the chance of a memory allocation by std::stringstream, then you could use sprintf, snprintf or itoa. This is a possible implementation, also thread safe, with no statics:

std::string to_string(int val) {
    // Buffer size is arbitrary in this example. Could be smaller.
    // 128 is more than enough for any integer number.
    char buffer[128];
    std::snprintf(buffer, sizeof(buffer), "%i", val);
    return buffer;
}

I suggest going with the first one, but if you have a justifiable performance concern, then the second one should perform slightly better.


FizzBuzz with Lambda Expressions in Java

You used a HashMap, where the iteration order is arbitrary. There is no guarantee whether you'll get "fizz buzz" or "buzz fizz"!


Better card validity check in JS card game

This is my new attempt

Game.prototype.isCardLegal = function(card,player){

    var requirements = this.getRequirements();

    if(this.cardsToDraw() > 0 && card.value !== '7'){
        player.setTask('forced draw');
        return false;
    }

    if (card.color !== requirements.color && card.value !== requirements.value && card.value !== 'J') {
        player.setTask('invalid card');
        return false;
    }

    return true;

};

When a card is played the game state will be updated with the required color / value. When the played card is a jack or a 7, the respective requirements are set accordingly. So I don't have to distinguish between the color of the last card palyed and a possible forced color any more, as in both cases the game state property will be updated.

I'm still looking for ideas, though.


I added the following test code to investigate. It does an exhaustive check from 1 to 999 and then a few more cases.

import Data.Monoid
import Control.Monad
import Test.Hspec

specTest n w = it ("converts " <> show n) $ convert n `shouldBe` w

oneToNine = words "One Two Three Four Five Six Seven Eight Nine"
zeroToNineEndings = "" : map ("-"<>) oneToNine
oneToNinetyNine = oneToNine
    <> words "Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen"
    <> [decade <> ending | decade <- words "Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety", ending <- zeroToNineEndings]

main = hspec $ do
  zipWithM_ specTest [1..]
    $ oneToNinetyNine
    <> mconcat
      [[d <> " Hundred"] <> map ((d <> " Hundred ") <>) oneToNinetyNine
      | d <- oneToNine
      ]

  specTest 1000 "One Thousand and "
  specTest 1001 "One Thousand and One"
  specTest 1234 "One Thousand and Two Hundred Thirty-Four"
  specTest 1234567 "One Million, Two Hundred Thirty-Four Thousand and Five Hundred Sixty-Seven"

Note that 1000 converts to 'One Thousand and ' which is probably wrong. Also, your original question claims 1234 converts to 'One Thousand, Two Hundred Thirty Four' but in fact it comes out as 'One Thousand and Two Hundred Thirty-Four'.

I am not sure your rules for adding 'and' and commas in are correct, however I'm from the UK where we typically put an 'and' between the hundreds and tens (e.g. 'two hundred and thirty-four') and I'm aware that this isn't how things are done in the US. I'd recommend adding some more test cases as I've shown above to make sure you're getting things as you expect.

The code seems idiomatically ok, although the mixture of CamelCase and use_of_underscores is a little jarring. hlint offers some good advice on the use of idiom and reports this, a few unnecessary parentheses and $s and identifies that concat . intersperse can be written as intercalate. Nothing major.


Ok, here is a solution with no additional modules, moving eval out of the loop, and with few additional checks.

use strict;
use warnings;

$^I = '.bak';
my $re = shift @ARGV or die "Nothing to do..";
$re = eval "sub{ $re }" or die "Incorrect expression..";

chomp(@ARGV  = <STDIN>) if !@ARGV;
@ARGV = grep {
  warn "[Warning] Backup file already exists and is been used by pie"
    if -f "$_$^I";
  -f $_;
}
@ARGV;

my @bak = map "$_$^I", @ARGV;
while (<>) {
  $re->();
  print;
}
unlink(@bak);


General: Do not use int for float values.
Either use float and float functions like sqrtf() or use double.
When fabs(b) is close to sqrt(discriminant), OP's approach suffers severe loss of precision due to the + or -.  More numerically stable code posted.  Still needs some divide by 0.0 checks.

//x1=(-b + sqrt(discriminant)) / (2*a);
//x2=(-b - sqrt(discriminant)) / (2*a);
float s = sqrtf(discriminant);
if (b < 0) {
  x1 = (-b + s)/(2*a);
  x2 = c/x1;
} else if (b > 0) {
  x2 = (-b - s)/(2*a);
  x1 = c/x2;
} else {
  x1 = s/(2*a);
  x2 = -x1;
}

pow(b, 2) - 4 * a * c; also suffers from severe loss of precession when b*b is about 4*a*c.  If OP is interested there are method to better calculate that too.  It comes down to how quick you want to write/execute the code versus the need for correctness on edge conditions.
Unclear format usage.  About 45% of all float numbers will print as 0.00 with "%.2f".  Suggest a more meaningful format

   // printf("Vertex: V(%.2f,%.2f)\n", vx, vy);
   printf("Vertex: V(%e,%e)\n", vx, vy);

Dangerous code.  Nothing stop code from incrementing into la-la land.  If this A() and B() are only used in this controlled environment, make them static, else they should robustly handle all sorts of string inputs.

float A(const char* in) {
  ...
  while(in[i] != 'x'){ /* until x in found */
    i++; /* increment i */
  }

More weak code.  Nothing insures that c will be a string after the strncpy call.  Just use strtol() or strtof().

strncpy(c, in, i); /* copy first i characters of in to c */
return atoi(c);

Unclear why code is using atoi(), yet returning float.
Corner case: With b = atoi(c);, should c have the textual value of -INT_MIN, then assignment to b is UB.
Consider printing something when sign=='n'
Make a clean separation of parsing form quadratic calculation.  (2 functions)


Saving and loading parts of configuration

How about storing your data in sqlite database? All of your operations can be implemented as relational database queries/commands.

Your table will have columns:

FIRST
SECOND
FIRST_ID
SECOND_ID

To perform updates on the second_id based on an object, just use (this is pseudo-code):

for (second in input_json) {
  ...run UPDATE CONFIGS SET SECOND_ID = {input_json[second]} WHERE SECOND = {second} ...

You can make this run efficiently by creating an index on the SECOND column.

Lookup are just SELECT * FROM CONFIGS WHERE ...

For instance, to select only those configs which have second id:

SELECT * FROM CONFIGS WHERE SECOND_ID <> ""

It all depends on how many configs you have. For a large number using a sqlite database could be a win.


Note that Endpoints.Contains(endpoint) will never be true, because you create a new IPEndPoint, and it does not implement IEquatable interface.

In addition to @mjolka's description why you have a 50% CPU load, I would like to suggest how you can avoid it.

Currently you have a central place that manages all sockets in one place. I suggest to do it differently - have each endpoint handle the data on its own, and manage all sockets only as a collection of ongoing processing (tasks) like this:

public async Task RunListenerAsync(int port)
{
    var endpoint = new IPEndPoint(IPAddress.Any, port);
    using (var client = new UdpClient(endpoint))
    {
        while (true)
        {
            try
            {
                var result = await client.ReceiveAsync().ConfigureAwait(false);
                ProcessEndpointData(client, result);
            }
            catch (Exception exc)
            {
                logger.Error("Error receiving from channel: " + exc.Message, exc);
                return;
            }
        }
    }
}

private void ProcessEndpointData(UdpClient client, UdpReceiveResult result)
{
    var localEndPoint = (IPEndPoint)client.Client.LocalEndPoint;
    var device = (from d in Ports
                    where d.Key == localEndPoint.Port
                    select d.Value).FirstOrDefault();

    var data = new UdpData
    {
        Client = client,
        Data = result.Buffer,
        LocalPort = localEndPoint.Port,
        LocalIP = localEndPoint.Address,
        RemoteEndpoint = result.RemoteEndPoint,
        Device = device
    };
    Flow.bufferBlock.Post(data);
}

Note that in this implementation the only way to stop listening the port is to get an exception on await client.ReceiveAsync(). You might want to introduce the CancellationToken to have a control when to stop this process.

With this approach registering and listening for all ports will be as simple as:

public Task ListenPortsAsync(IEnumerable<int> ports)
{
    return Task.WhenAll(ports.Select(RunListenerAsync));
}


Finding the total time elapsed in the union of time intervals

You can make your current \$O(n^2)\$ algorithm run in \$O(n \log n)\$ time by first sorting the input intervals by interval start time, then do a linear scan of the sorted array:

public static int answer(int[][] intervals) {
    if (intervals.length() < 1) {
        return 0;
    }
    java.util.Arrays.sort(
        intervals,
        new java.util.Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                return Integer.compare(a[0], b[0]);
            }
        });
    int totalTime = 0;
    int currentIntervalEnd = intervals[0][0];
    for (int[] interval : intervals) {
        int intervalStart = interval[0];
        int intervalEnd = interval[1];
        if (intervalEnd > currentIntervalEnd) {
            totalTime +=
                intervalEnd - Math.max(intervalStart, currentIntervalEnd);
            currentIntervalEnd = intervalEnd;
        }
    }
    return totalTime;
}


It looks quite good.  Perldoc, use strict, use warnings are all good practices.  The formatting is good, and the code is readable.

I don't recommend hard-coding the name of the data file in your program.  That turns it from a general-purpose program into throwaway code.  If you use the default filehandle <>, then Perl will do the "right thing": if a filename is specified as a command-line parameter, it will read from that file; if not, it will read from STDIN.  As a bonus, it saves you the trouble of having to call open().  (You neglected to explicitly close(STUDENTS), by the way.)

The CSV-parsing code is repeated for the header row and for the body.  It should be made into a subroutine.

(my $id, my $name) could be written more idiomatically as my ($id, $name).

I find it annoying to use string interpolation like print "$something\n" just because you need a newline.  I suggest taking advantage of the newish say feature.

The facts that you want the second column, and that the columns are the $id and $name, are both hard-coded.  Perhaps you should add an assertion.

Suggested implementation

use strict;
use warnings;
use feature qw(say);

sub columns {
    my $line = shift;
    return unless defined $line;
    chomp($line);
    split ',', $line;
}

my @column_names = columns(scalar <>);

die unless $column_names[1] eq 'Name';
say "Printing Student ${column_names[1]}s...";
while (my ($id, $name) = columns(scalar <>)) {
    say $name;
}


Scoring solution for Farkle (dice game)?

"Pythonic" programming

Code is "pythonic" when it expresses its intention clearly, is easy to read or even looks like pseudo-code, and uses as little low-level garbage as possible. Let's take a look at a couple examples of low-level work in your code:

dice_array = [0] * sides
score = 0
for dice in my_roll:
    dice_array[dice-1] += 1
# as an aside, this isn't an array, it's a list.

This is wonky because it buids a fixed-size list, then plays with values-as-list-indexes to get a count. That might be fast, but it's certainly ugly. Let's not do that.

import collections

counts = collections.Counter(my_roll)

This is much better. It builds a dict-like object, a collections.Counter that has the counts for any dice present in the roll. counts[non_rolled_die] will throw a KeyError while counts.get(non_rolled_die, 0) will act like your current code does.

Your counting loop isn't a whole lot better. Let's look:

for i, count in enumerate(dice_array):
    dice = i + 1

We'll stop here for just long enough to mention that enumerate takes a keyword argument start that lets you tell it where to start counting from. This should be:

for die, count in enumerate(dice_array, start=1):

But since I switched to using a collections.Counter, we can just do:

for die, count in counts.items():
    if die == 1:
        if count == 6: score += 2200
        if count == 5: score += 2100
        if count == 4: score += 2000
        if count == 3: score += 1000
        if count in [1, 2]: score += (count * 100)
    else:
        if count >= 4: score += (dice * 200)
        if count >= 3: score += (dice * 100)
        if (die == 5 and count != 3): score += (count * 50)

First of all, avoid these repeated if statements. Try instead:

    if die == 1:
        if count == 3: score += 1000
        elif count == 4: score += 2000
        elif count > 4:
            score += 2000 + (count - 4) * 100

However there's a better approach. We already know that the triple value for each number is 100 * number, except for 1 which is 100 * 10 * number. Let's use that!

for die, count in counts.items():
    die_score = 0
    if count == 4:
        die_score += die * 2000 if die == 1 else die * 200
        count -= 4
    elif count == 3:
        die_score += die * 1000 if die == 1 else die * 100
        count -= 3

This should handle triplets and quadruplets of any value, and removes from count the number of dice consumed by the grouping. Now let's look at single dice values.

    if die in [1, 5]:
        single_value = 100 if die==1 else 50
        die_score += single_value * count

In fact we can factor some of that out to drop the if block.

    # somewhere earlier in the function
    single_values = {1: 100, 5:50}

    # then inside the loop we're looking at here....
    die_score += single_values.get(die, 0) * count

Finally at the end of our loop (just before exiting it), we add the single die_score to the roll-wide score.

    score += die_score

Testing

I'm a big fan of the unittest module for writing tests. In your case doctest may work better (since you've written examples already that only have to be tweaked slightly to use doctest), but if you start writing more intense functions, it's important to be able to grow your testing suite appropriately. Let's write some tests!

# ./test_farkle.py

import unittest
import farkle

class FarkleTests(unittest.TestCase):
    cases = [([1,1,1,5,5,5], 1500),
             ([1,1,1,1,6,6], 2000),
             ([5,3,6,5,3,3], 400),
             ([1,2,2,3,3,5], 150)]

    def testRolls(self):
        for got, want in self.cases:
            self.assertEqual(farkle.score(got), want)
            # fails test if `farkle.score(got) != want`

A change in data structure

It should occur to you that for every (die, count) pair, score increases by a given amount. This means we can hardcode that data in something like a dict.

# {die: {count: value, ... }, ... }
valuedict = {1: {1: 100,
                 2: 200,
                 3: 1000,
                 4: 2000,
                 5: 2100,
                 6: 2200},
             2: {3: 200,
                 4: 400},
             3: {3: 300,
                 4: 600},
             4: {3: 400,
                 4: 800},
             5: {1: 50,
                 2: 100,
                 3: 500,
                 4: 1000,
                 5: 1050,
                 6: 1100},
             6: {3: 600,
                 4: 1200}}

Now your function becomes pretty simple!

def score(my_roll, sides=6):
    valuedict = ...  # the whole deal above
    counts = collections.Counter(my_roll)
    score = 0
    for die, count in counts.items():
        score += valuedict[die][count]
    return score

Or even more simply:

def score(my_roll, sides=6):
    valuedict = ...
    counts = collections.Counter(my_roll)
    return sum(valuedict[die][count] for die,count in counts.items())


Reduce duplicated logic by using helper methods

Instead of repeating this condition:

if (file.getName().endsWith(mime)) {

Use a helper method:

private static boolean isValidFile(File file) {
    return file.getName().endsWith(mime);
}

The advantage is that this hides the implementation details of what is a valid file to you. Without this, all you methods need to be aware that the file name should end with mime, which is too much detail and duplicated logic. With the isValidFile helper, if you need to change something about the condition on the File object, you will be able to make the change in one place, inside isValidFile, without having to touch the rest of the program.

Bugs and improvements in containsObject

You don't exit the loop even after you found a match, iterating until the end of the file, which is a waste:

while (br.ready()) {
    String line = br.readLine();
    if (line.trim().equals(object.toString())) {
        IsGood = true;
    }
}

After you set IsGood = true, add a break;

IsGood is a bad name for 2 reasons:

Variables should be camelCase
It doesn't explain it self

foundMatch would make more sense.

Simplify and clean up removeObject

The "file clearer" is completely pointless. Instead of this:

BufferedWriter fileclearer = new BufferedWriter(new FileWriter(file));
fileclearer.write("");
fileclearer.close();
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));

You can write simply this for the same effect:

PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));

Notice that I dropped the second true parameter from the the FileWriter when creating pw. This makes the writer truncate the file.

Instead of this:

ArrayList<String> linestoadd = new ArrayList<String>();

You should declare variables with interface types, in this case a List:

List<String> linestoadd = new ArrayList<String>();

And instead of linestoadd, I would name the variable content, or contentLines, but that may be a matter of taste.

Again, IsGood doesn't tell what it's about. If you rename to foundMatch, its purpose becomes much clearer.

Improve getContents

As I noted earlier about linestoadd in removeObject, you should declare variables, and also methods, using interface types. So instead of:

public static ArrayList<String> getContents(File file) throws IOException {
    ArrayList<String> contents = new ArrayList<String>();

This would be better:

public static List<String> getContents(File file) throws IOException {
    List<String> contents = new ArrayList<String>();

Inverting the if-else branches

All your methods have this pattern:

if (isValidFile(file)) {
    // ... (the main code)
} else {
    return false;
}

In cases, the main code is relatively long. As such, when you look at the else block, it's not visible what it is "the else of", I have to scroll up to see. In such situations, it would make the code more readable to invert the logic in the if-else: bring the much shorter block up, like this:

if (!isValidFile(file)) {
    return false;
} else {
    // ...
}

In fact, since in this case the block is a return statement, you can even eliminate the else block, reducing the nesting level, which is usually easier to read:

if (!isValidFile(file)) {
    return false;
}
// ...


Stopwatch exception implementation in C#

You have the beginning of a stopwatch representation—you have its data. You still need to add its behavior.

Approach your design of the class as if the class should stand on its own. Input/output will be handled by something else, like the console, but the stopwatch should be the authority on its internal state.

The simplest stopwatch has a start/stop button and a display. We'll interpret "having a display" to mean "a way to get the stored elapsed time".

This means we'll need to provide three methods:

Start: Sets the stopwatch in a running state.
Stop: Sets the stopwatch in an idle state.
TimeElapsed: Reads out the currently elapsed time.

Additionally, Start and Stop have the requirement that they should throw InvalidOperationException when the stopwatch is not a compatible state. Our stopwatch will need a notion of running to do this.

Let's look how we can modify the stopwatch class to adopt this behavior. I've annotated some below:

    public class Stopwatch
    {
        private DateTime _startTime; // we need this
        private DateTime _stopTime; // ? either this or duration
        private TimeSpan _duration;
        public DateTime StartTime() // why do we return a value here?

        {
            // we still need to check whether we are already running
            _startTime = DateTime.Now;
            return _startTime;
        }

        public DateTime Stoptime() // why do we return a value here?

        {
            // we still need to check whether we are still running
            _stopTime = DateTime.Now;
            return _stopTime;
        }

        // We still need the notion of 'currently running'
    }

    // First attempt
    public class Stopwatch
    {
        private DateTime _startTime;
        private DateTime _stopTime;
        private Boolean _running;

        public void StartTime()
        {
            if ( _running )
            {
                throw new InvalidOperationException("Cannot start: already running");
            }
            _startTime = DateTime.Now;
            _running = true;
        }

        public void Stoptime()
        {
            if ( !_running )
            {
                throw new InvalidOperationException("Cannot stop: not running");
            }

            _stopTime = DateTime.Now;
            _running = false;
        }

        public TimeSpan ElapsedTime()
        {
            if ( _running )
            {
                return DateTime.Now - _startTime;
            }
            else
            {
                return _stopTime - _startTime;
            }
        }
    }

Note that we check if the stopwatch is currently running when asking for elapsed time: otherwise, we're going to get a very strange reading.

Now we can 'clean up' a little bit to follow conventions:

Class members are implicitly private, so we don't need to add the private modifier.
Members should start with a capital letter.

Which gives us:

    public class Stopwatch
    {
        DateTime StartTime;
        Boolean IsRunning;
        DateTime StopTime;

        public void Start()
        {
            if (IsRunning)
            {
                throw new InvalidOperationException("Cannot start: already running");
            }
            StartTime = DateTime.Now;
            IsRunning = true;
        }

        public void Stop()
        {
            if (!IsRunning)
            {
                throw new InvalidOperationException("Cannot stop: not running");
            }
            IsRunning = false;
            StopTime = DateTime.Now;
        }

        public TimeSpan ElaspedTime()
        {
            if (IsRunning)
            {
                return DateTime.Now - StartTime;
            }
            else
            {
                return StopTime - StartTime;
            }
        }
    }

And a quick Main to play around with it:

    static void Main(string[] args)
    {
        var stopwatch = new Stopwatch();
        int choice;

        do
        {
            Console.Write("1-Start Timer\n2-Stop Timer\n3-Read Timer\n0-Quit\n");
            choice = Convert.ToInt32(Console.ReadLine());
            switch (choice)
            {
                case 1: stopwatch.Start(); break;
                case 2: stopwatch.Stop(); break;
                case 3: Console.WriteLine(stopwatch.ElaspedTime()); break;
            }
        } while (choice != 0);
    }


You use a lot of jQuery, where plain javascript will suffice and is actually more efficient. A small example: el.attr('id') loops through the available attributes until it finds ID1. you can simply do el[0].id and select it without anything complex. The same fors for .src and some other values. I will add comment to the coding below to guide you through it:

1 This isnt 100% true, they've improved but you get the gist of it

Round 1:

$(function () {
    var lastImageIdClicked = "";
    var timer;

    $('.imgX').on('click', function () {
        // Was: el = $(this);
        // - Placed [var] before it to make it local scope
        // - We dont yet need it als a jQuery element
        // - el is very short and not descriptive. [elem] is more common:
        var elem = this ;
        // Was: el.attr('id');
        // - update to [elem] -> elem.id
        // - removed variable because we no longer use it (see a few lines below)
        //~ elId =  elem.id
        // Was: el.attr('src');
        // - update to [elem] -> elem.id
        // - removed variable because we no longer use it (see a few lines below)
        //~ elSrc = elem.scr
        var clicks = 0;

        // Was: if (elId === lastImageIdClicked) {
        // - just use elem.id here. It's not more complex and actually tells me more
        if (elem.id === lastImageIdClicked) {
            clicks++;
            clearTimeout(timer);
        }
        // This whole else is irrelevant as you set [var clicks = 0;] a few lines higher
        // else {
        //      clicks = 0;
        //}

        // Was: var fileName = elSrc;
        // - Simply use elem.src
        // We use this only once a few lines below, just use [elem.src] there, no need to use a variable for that

        // Was: lastImageIdClicked = elId;
        // - Simply use elem.id
        lastImageIdClicked = elem.id;

        var re = /(pic)(.*)(.png)/;
        var imgNumber = elem.src.match(re)[2]; // todo: why array
        clicks = Number(imgNumber) + 1;

        // Was: if (clicks > 3) clicks = 0;
        // IMO you should _always_ use brackets: if (clicks > 3){ clicks = 0;}
        if (clicks > 3){ clicks = 0; }

        // Was: var eleImage = $(this).attr('src', 'pic{0}.png'.replace('{0}', clicks));
        // - we now just use this.src = /* ... */
        // - You place {0} in your string, then replace it? Just concat it directly: ['pic'+click+'.png']
        var eleImage = this.src = 'pic'+clicks+'.png';

        //Save image if 5 seconds have passed
        timer = setTimeout(function () {
            alert('saved');
        }, 5000);
    });
});

Clean that up:

$(function () {
    var lastImageIdClicked = "",
        timer;

        $('.imgX').on('click', function () {
            var elem = this ;
            var clicks = 0;

            if (elem.id === lastImageIdClicked) {
                clicks++;
                clearTimeout(timer);
            }
            lastImageIdClicked = elem.id;

            var re = /(pic)(.*)(.png)/;
            var imgNumber = elem.src.match(re)[2]; // todo: why array
            clicks = Number(imgNumber) + 1;

            if (clicks > 3){ clicks = 0; }

            var eleImage = this.src = 'pic'+clicks+'.png';

            //Save image if 5 seconds have passed
            timer = setTimeout(function () {
                alert('saved');
            }, 5000);
    });
});

Round 2

$(function () {
    var lastImageIdClicked = "",
        timer;

        $('.imgX').on('click', function () {
            var elem = this ;
            var clicks = 0;

            if (elem.id === lastImageIdClicked) {
                clicks++;
                clearTimeout(timer);
            }
            lastImageIdClicked = elem.id;

            // Was: var re = /(pic)(.*)(.png)/;
            // Was: var imgNumber = elem.src.match(re)[2]; // todo: why array
            // - This is a simple regex, no need to use a variable for it if you only use it once
            // - you select multiple groups now, you don't want that, only the number
            var imgNumber = elem.src.match(/pic(.*)\.png/)[1]; // todo: why array
            clicks = Number(imgNumber) + 1;

            if (clicks > 3){ clicks = 0; }

            // Was: var eleImage = this.src = 'pic'+clicks+'.png';
            // - Seemingly does nothing, assuming you want to change the src
            this.src = 'pic'+clicks+'.png';

            //Save image if 5 seconds have passed
            timer = setTimeout(function () {
                alert('saved');
            }, 5000);
    });
});

Clean that up

$(function () {
    var lastImageIdClicked = "",
        timer;

        $('.imgX').on('click', function () {
            var elem = this ;
            var clicks = 0;

            if (elem.id === lastImageIdClicked) {
                clicks++;
                clearTimeout(timer);
            }
            lastImageIdClicked = elem.id;

            var imgNumber = elem.src.match(/pic(.*)\.png/)[1]; // todo: why array
            clicks = Number(imgNumber) + 1;

            if (clicks > 3){ clicks = 0; }
            this.src = 'pic'+clicks+'.png';

            //Save image if 5 seconds have passed
            timer = setTimeout(function () {
                alert('saved');
            }, 5000);
    });
});

Round 3

This is for you do to yourself:
- Instead if hardcoding max-images = 3, make an array with images imgs and do imgs.length
- Instead of using a regex, add a data-current_img="1" to your images and use that to count
- If you use the data method, you can update the image to elem.src = imgs[current+1] to move to the next img, instead of the pricy regex

Now you  don't have to manually limit to 3, or rename the images to their number, nor do you need to update our code if an extra state has to be build.


slide out navigation bar seems too simple but it works, is it?

From a once over:

You should put the closing brace at the level of $ for readability:

$(function () {
    $('#menubutton').click(function (e) {
        e.preventDefault();
        e.stopPropagation();
    });

    function handler1() {
        $("#page").animate({
            left: "200px"
        }, 150);
        $("#menu").css("overflow-y", "auto");
        $("#menubutton").one("click", handler2);
    }

    function handler2() {
        $("#page").animate({
            left: "0"
        }, 150);
        $("#menu").css("overflow-y", "hidden");
        $("#menubutton").one("click", handler1);
    }
    $("#menubutton").one("click", handler1);
    $("#page").click(handler2);
    $("#menu").css("visibility", "visible");
});

handler1, handler2 are unfortunate names, these function names should convey what the function does ( perhaps slideRight and slideLeft ? )
You access $('#menubutton') a number of times, you should cache it with var $menuButton = $('#menubutton') and then access $menuButton, you can use the same technique for the other jQuery calls as wel
You are repeating yourself between handler1 and handler2, but it seems that trying to find a common routine would make this code more complex, so I would leave that alone


Decimal to binary conversion in ARM assembly

Here are a number of things that may help you improve your program.
Understand the calling convention
The procedure call standard for ARM says that the registers r0, r1, r2, and r3 can be used and not restored by a called function.  Further, if we don't alter lr, there's no need to preserve and then restore it.  These are all clues for making your program more efficient.
Know your instruction set
The code currently contains these lines:
    movs    r4, r4, lsr #1      @ divide by 2, set carry
    bcs     _odd                @ if carry set, remainder is 1
_even:
    mov     r5, #0              @ remainder of 0
    b       _toString
_odd:
    mov     r5, #1              @ remainder of 1
_toString:
    add     r5, #48             @ convert

That is terribly inefficient.  We can simplify considerably:
    mov     r5, #48             @ start with ASCII '0'
    movs    r4, r4, lsr #1      @ divide by 2, set carry
    adc     r5, #0              @ add zero + carry

Minimize branching
The code ends with this curious combination:
    ble     _endloop
    b       _loop
_endloop:

First, the comment suggests that we're looking for exactly zero and so we should be looking only at the zero flag (beq or bne) rather than doing a signed comparison with ble.  Second, why not simply use a single instruction?
    beq     _loop

However, better, see the next suggestion.
Create reusable code
The code currently exits if the shifted value becomes zero.  That works, but only once.  In other words, if you use the routine to decode 255 and then again to decode the value 3, you will likely be surprised that your routine will falsely give the same binary string for both.  The problem is that it relies on the binStr buffer to always contain a string of zeroes.  A better approach is to explicitly set each byte of the buffer and instead use the counter you already have in r9.  This shortens the code and makes it reusable.
    subs    r9, r9, #1
    bpl     _loop

Move loop invariants outside the loop
Every iteration through the loop we load the r1 register with the address of binStr even though r1 is never changed within the loop.  A more efficient approach would be to load r1 once outside the loop.
Document register usage
One of the keys to being a good assembly language programmer is to carefully manage register use.  The most basic requirement is to keep track of how you're using registers, and a good way to do that, both for yourself and future readers of the code is to document the use.  Based on the observations in the first suggestion above, here's what I used:
@ Register usage:
@   r0 - passed value
@   r1 - pointer to current string digit
@   r2 - decrementing digit offset
@   r3 - the current digit

Results
Using all of these suggestions, the resulting routine is only nine instructions.
decToBin:
    ldr     r1, =binStr         @ output string location
    mov     r2, #7              @ start with the LSB
_loop:
    mov     r3, #48             @ start with ASCII zero
    movs    r0, r0, lsr #1      @ divide by 2, set carry
    adc     r3, #0              @ add the extracted bit
    strb    r3, [r1, r2]        @ store remainder in string at pos in r9
    subs    r2, r2, #1          @ decrement counter
    bpl     _loop               @ end if it has gone negative
    bx      lr

Armed with these suggestions (pun intended!) see if you can perform a similar cleanup on the rest of the code.  In particular, there is a much more efficient way to check if the input value is in the appropriate range (hint: movs r1, r0, lsr #8).
Also, just for fun, this answer was composed and tested entirely on a Raspberry Pi running on battery power.
Other ideas
A more generally useful routine would have the caller pass a buffer pointer and buffer length into which the program would put its result rather than using a fixed location.  See if you can figure out how to modify the code to do that, and don't forget to place the terminating \0 character.