Crashing bug

If I call peakfinder([0, 0]), I get an IndexError:

Traceback (most recent call last):
  File "peaks.py", line 32, in <module>
    peakfinder([0, 0])
  File "peaks.py", line 22, in peakfinder
    if arr[left] <= arr[mid] >= arr[right]:
IndexError: list index out of range

(I’m not sure if these are the “size constraints” you allude to in the question, you didn’t provide details.)

If we inspect these, we discover that we have (L, M, R) = (0, 1, 2), but trying to get the element at index 2 will fail. This will fail whenever you have an array of length 2.

One way to handle this would be to add an extra base case for when you have an array of length 2. Alternatively, you could tweak the bounds checking so that it only looks for elements within the bounds of the array.

Let’s suppose we never pass in an array of size 2. But it turns out other arrays will hit the same, if they reduce to an length-2 array at an intermediate step. For example:

>>> peakfinder([0, 1, 0, 0])
Traceback (most recent call last):
  File "peaks.py", line 35, in <module>
    peakfinder([0, 1, 0, 0])
  File "peaks.py", line 29, in peakfinder
    return peakfinder(arr[:mid])
  File "peaks.py", line 31, in peakfinder
    if arr[mid] < arr[right]: # Look to right side of array for peak.
IndexError: list index out of range

Here’s a small test I wrote with Hypothesis to find some counterexamples:

from hypothesis import given, strategies as st

@given(st.lists(st.integers()))
def test_peakfinder_doesnt_crash(xs):
    """Finding the peak of a list doesn't crash."""
    peakfinder(xs)

The peak of an array must be an element of the array

Sounds reasonable enough, right? But your code will return a list of length 1 if any of the intermediate steps reduce to such a list, an element otherwise. For example:

>>> from peaks import peakfinder
>>> peakfinder([1, 0])
[1]
>>> [1] in [1, 0]
False
>>> peakfinder([1, 2, 3])
2
>>> 2 in [1, 2, 3]
True

You should tweak the case when len(arr) == 1 to return the single element:

if len(arr) == 1:
    return arr[0]

Here’s another small test I wrote to find a counterexample:

from hypothesis import assume, given, strategies as st

@given(st.lists(st.integers()))
def test_peak_is_in_original_list(xs):
    """The peak of a list is in the list."""
    assume(len(xs) > 0)
    assert peakfinder(xs) in xs


Skinny model, fat controller in Rails managing user IP addresses

First of all you should look at your controller and see what common functionality you can extract to a private methods and callbacks.

Another fairly large concern with you controller is that you are just assuming that a record is created or deleted without checking the return value. Create / Update / Destroy actions can and will fail.

class IpAddressesController < ApplicationController

    before_filter :set_ip_address, only: [:show, :edit, :update, :destroy]

    def index
        @ip_addresses = IpAddress.all.order(:title) # extract to model default scope?
    end

    def show
    end

    def new
        load_form_resources
        @ip_address = IpAddress.new
    end

    def create
        @ip_address = IpAddress.new(ip_address_params)
        if @ip_address.save
            redirect_to ip_addresses_path
        else
            load_form_resources
            render :new
        end
    end

    def destroy
        # Remember that destroy can actually fail!
        if @ip_address.destroy
            flash.success "Record successfully deleted"
            redirect_to ip_addresses_path
        else
            flash.alert "Record not deleted"
        end
    end

    private

        def set_ip_address
          @ip_address = IpAddress.find(params[:id])
        end

        def load_form_resources
            @ip_address_roles = IpAddressRole.all
            @servers = Server.all
            @ip_address_users = IpAddressUser.all
        end

        def ip_address_params
            params.require(:ip_address).permit(:title, :server, :user, :is_in_use, :role)
        end
end

When it comes to your model, then I usually preach so much against boolean state flags that I feel somewhat like a broken record.

Instead of having a ip_addresses.is_in_use column you could add a ip_addresses.state integer column.

Rails has a really fancy trick called enums.

class IpAddress < ActiveRecord::Base
  enum state: [:available, :in_use]
end

Which gives you:

IpAddress.available # gets all free ip adresses
IpAddress.in_use # gets all in_use ip adresses
@ip_adress.available? # check status
@ip_adress.in_use?
@ip_adress.in_use! # setters


Filtering out the correct car from a list of cars and retrieving only one car

Your solution is inefficient, for two reasons:

If there are multiple matches, the filteredCars lists gets unnecessarily populated.
It iterates over the entire list, even though it could stop immediately when a second match is found.

The appropriate exception type depends on your application and its purpose, for example:

If the caller is wrong to request a brand of which multiple cars exist,
then you could use IllegalArgumentException.
If the cars list is wrong to contain multiple cars of the requested brand, then you could use IllegalStateException.
If you want to give the caller a chance to recover from the bad call, then you should use a checked custom exception type, catch it and handle it.

Btw, it seems you forgot to handle the case of no matching cars,
which would result in an exception when you call .get(0).

As a minor remark, the name isCorrectBrand seems tedious. Simply isBrand would be more natural.

Consider this alternative:

public Car getCar(String brand) {
    return cars.stream()
            .filter(car -> car.isBrand(brand))
            .reduce((a, b) -> {
                throw new IllegalArgumentException("more than one matching cars");
            })
            .orElseThrow(() -> new IllegalArgumentException("no matching cars"));
}


C# - name separation & last name in upper to Camel

Well, I don't know if your code could be better or faster but the code could be a lot shorter by using some Linq-"magic".
Your code could use some level of input-parameter-validation because the methods in question are public which means anybody who uses these methods can pass whatever he/she wants, even null which would blow each method and would expose implementation details.
I don't know if the requirement is meant to be that passing Ronald Chris MAC DONALDS returns as lastname MacDonalds but for me this doesn't sound correct.
Instead of splitting the fullname twice and then splitting the lastname again, you should consider to just pass a string[] to the methods.
You could consider to have one public method where you pass the fullname and get a Tuple<string, string> so you would need only one parameter validation because you can make the other methods private.
Because a lastname contains only UpperCase letters we can take the passed string[] and take each string in this array which contains only upper-case letters, we will leave the first char because it allready is uppercase and take the remaining chars as lower-case chars. Last we join them using a space char like so
private static string GetLastName(string[] nameParts)
{
    return string.Join(" ", nameParts.Where(s => s.All(c => char.IsUpper(c)))
                                     .Select(s => s[0] + s.Substring(1).ToLowerInvariant()));
}

For the firstname we know that not all chars are upper-case chars. So we take each string inside the passed array and check if any char is a lower-case char, and then join the found strings by using a space char like so
private static string GetFirstName(string[] nameParts)
{
    return string.Join(" ", nameParts.Where(s => s.Any(c => char.IsLower(c))));
}

Last but not least we need to call these 2 methods after some proper validation like so
public static Tuple<string, string> GetNormalizedNames(string fullName)
{
    if (fullName == null) { throw new ArgumentNullException(nameof(fullName)); }
    if (string.IsNullOrWhiteSpace(fullName)) { return Tuple.Create("", ""); }

    var nameParts = fullName.Split(' ');

    return Tuple.Create(GetFirstName(nameParts), GetLastName(nameParts));
}

which we then call like so
var firstNameLastNameTuple = GetNormalizedNames(fullName);
Console.WriteLine("Name: " + firstNameLastNameTuple.Item1);
Console.WriteLine("Last name: " + firstNameLastNameTuple.Item2);

The whole code is now easier to read and therefor easier to maintain. Sure linq is only syntactic sugar and won't be faster than iterating over the chars by "hand" but the benefit is less and easier to read code.


This works. State works as well but you don't need it until your app gets more complex.
There are different ways to structure this app, but it doesn't necessarily make them better. I was able to grok this in just a few minutes, which is great. I was able to read it from top to bottom without jumping around the file, which is great. Your style is largely consistent throughout the app, which is great.

Points 3 and 4 are mostly the same as above. You can structure it differently, but it's not necessary for a small app like this. As the app grows you will notice some areas that can easily be refactored into their own pieces, and I think you've mentioned most of them.

Here are some ideas you can use as a learning exercise. Understanding them now will help you reason about larger apps in the future. They're not necessarily the correct way, just learning exercises:

Try using a component for the form and another for the stats. Think about how you would communicate the data between these two components.
Write unit tests to prove that your component(s) are working as expected. Currently you have a lot of logic in your component methods. Is it easy to test this logic with unit tests? Would it be easier to test this logic if it were separated from the controller?
Try extracting the API logic into another class that you can import. Currently your controller has data and methods that can be used by your template, but they are not. Think of these as 'public' properties and methods. Do they need to be public? Why would you not want to make them public?
Currently your methods are fetching data and then mutating the results. Try storing the raw data, and then use computed properties to alter the data for display. Does this approach make it easier or harder to reason about the logic? How does it affect the testability of your component?


Todo-list practice code accepts title and list

Your code looks nice and is properly formatted. Still, a few points could be improved.

Magic methods

As mentionned in ChrisWue's nice answer, the __str__ magic method is supposed to return a string and is not expected to have any side-effects (such as performing some printing). Also, I would not consider it a good idea to change the signature of a usual magic method. Finally, the string returned by the function is empty which does not bring much information to anyone (the string returned by default is somehow more interesting : <__main__.TodoList object at 0x6085be4ce470>).

The best way to improve this is to split your function into 2 functions: one __str__ with a correct behavior and another one. For instance:

def print_list(self, tdl=None):
    if tdl is None:
        tdl=range(len(self.items))

    for i in tdl:
        item = "{0}. {1}".format(i, self.items[i])
        print(item)

def __str__(self, tdl=None):
    return str(self.title)

This also corresponds to a better Separation of Concerns and to the Single Responsibility Principle : each entity should do/be responsible of a single thing.

More about magic methods

Among the methods you've defined, a few of them could be renamed to emulate a container type:

remove corresponds to __delitem__
update corresponds to __setitem__
__len__ is fine.

search

At the moment, search is defined like this (print_list being the function defined above):

def search(self, query):
    result = []
    for k, i in enumerate(self.items):
        if query in i:
            result.append(k)
    return self.print_list(result)

A few improvements could be done.

First, I'd use i as the variable name for the index and not for the item.

Then, the my_list = []; for ...: if ...: my_list.append(...) pattern is usually written using list comprehension which are more concise and clearer once you get used to it. They are also more efficient and considered more pythonic.

def search(self, query):
    result = [i for i, item in enumerate(self.items) if query in item]
    return self.print_list(result)

Finally, I'd consider it poor API to have a search method that doesn't return anything (while performing some printing). I'd like it more if you were to return the results and to have another method to pretty print them if needed.

The final code looks like (I am still not a big fan of print_list):

class TodoList(object):

    def __init__(self, title=None):
        self.title = title
        self.items = list()

    def print_list(self, tdl=None):
        if tdl is None:
            tdl = range(len(self.items))

        for i in tdl:
            item = "{0}. {1}".format(i, self.items[i])
            print(item)

    def __str__(self, tdl=None):
        return str(self.title)

    def __len__(self):
        return len(self.items)

    def add(self, item):
        self.items.append(item)

    def __setitem__(self, key, update):
        self.items[key] = update

    def __delitem__(self, key):
        del self.items[key]

    def search(self, query):
        return [i for i, item in enumerate(self.items) if query in item]

if __name__ == "__main__":
    x = TodoList("Shopping list")
    print(str(x))
    x.add("buy salad")
    x[0] = "buy potato"
    x.add("buy tomato")
    del x[1]
    x.print_list(x.search("potato"))

Going further

If you want to improve your code, you could consider adding documentation with docstrings. The docstring conventions for Python code can be found in a document called PEP 257.


In Go, measure performance. Run benchmarks using the Go testing package.

For example,

$ go test transpose_test.go -bench=. -benchmem
BenchmarkTranspose-4       2471407    473 ns/op    320 B/op    13 allocs/op
BenchmarkTransposeOpt-4    9023720    136 ns/op    224 B/op     2 allocs/op
$

As you can see, minimizing allocations is important. Efficient memory cache usage probably helps too.

transpose_test.go:

package main

import "testing"

func transpose(a [][]int) [][]int {
    newArr := make([][]int, len(a))
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(a[0]); j++ {
            newArr[j] = append(newArr[j], a[i][j])
        }
    }
    return newArr
}

func BenchmarkTranspose(b *testing.B) {
    a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        _ = transpose(a)
    }
}

func NewMatrix(d2, d1 int) [][]int {
    a := make([]int, d2*d1)
    m := make([][]int, d2)
    lo, hi := 0, d1
    for i := range m {
        m[i] = a[lo:hi:hi]
        lo, hi = hi, hi+d1
    }
    return m
}

func transposeOpt(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    for i := 0; i < len(b); i++ {
        c := b[i]
        for j := 0; j < len(c); j++ {
            c[j] = a[j][i]
        }
    }
    return b
}

func BenchmarkTransposeOpt(b *testing.B) {
    a := [][]int{{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        _ = transposeOpt(a)
    }
}

Goroutines have overhead. For a small task (4 x 4 matrix), the overhead may outweigh any gains.

Let's look at a 1920 x 1080 matrix (the size of an FHD display).

For this type of problem, we examine the optimized transpose function (transposeOpt) and see if it can be subdivided into smaller, concurrent pieces. For example, by row (transposeRow), or the number of available CPUs (transposeCPU).

$ go test goroutine_test.go -bench=. -benchmem
BenchmarkTranspose-4       37   31848320 ns/op   63354443 B/op   15121 allocs/op
BenchmarkTransposeOpt-4   202    5921065 ns/op   16616065 B/op       2 allocs/op
BenchmarkTransposeRow-4   229    5307156 ns/op   16616159 B/op       3 allocs/op
BenchmarkTransposeCPU-4   360    3347992 ns/op   16616083 B/op       3 allocs/op
$

A row is still a small task. Twice the number of CPUs amortizes the goroutine overhead over a number of rows.  By any measure -- CPU, memory, allocations -- transposeCPU is considerably more efficient than the original transpose for a 1920 x 1080 matrix.

func NewMatrix(d2, d1 int) [][]int {
    a := make([]int, d2*d1)
    m := make([][]int, d2)
    lo, hi := 0, d1
    for i := range m {
        m[i] = a[lo:hi:hi]
        lo, hi = hi, hi+d1
    }
    return m
}

var numCPU = runtime.NumCPU()

func transposeCPU(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    var wg sync.WaitGroup
    n := 2 * numCPU
    stride := (len(b) + n - 1) / n
    for lo := 0; lo < len(b); lo += stride {
        hi := lo + stride
        if hi > len(b) {
            hi = len(b)
        }
        wg.Add(1)
        go func(b [][]int) {
            defer wg.Done()
            for i := 0; i < len(b); i++ {
                c := b[i]
                for j := 0; j < len(c); j++ {
                    c[j] = a[j][i]
                }
            }
        }(b[lo:hi])
    }
    wg.Wait()
    return b
}

However, for a amall, 4 x 4 matrix, the goroutine overhead outweighs any gains.

BenchmarkTranspose-4      2570755    463 ns/op   320 B/op   13 allocs/op
BenchmarkTransposeOpt-4   8241715    145 ns/op   224 B/op    2 allocs/op
BenchmarkTransposeRow-4    908217   1318 ns/op   240 B/op    3 allocs/op
BenchmarkTransposeCPU-4    881936   1330 ns/op   240 B/op    3 allocs/op

As always, when we are exploiting concurrency, we use the Go race detector to check for data races. The overhead to check for data races is considerable. Therefore, we discard any benchmark results.

$ go test goroutine_test.go -bench=. -benchmem -race

By design, there are no data races.

goroutine_test.go:

package main

import (
    "runtime"
    "sync"
    "testing"
)

func transpose(a [][]int) [][]int {
    newArr := make([][]int, len(a))
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(a[0]); j++ {
            newArr[j] = append(newArr[j], a[i][j])
        }
    }
    return newArr
}

func BenchmarkTranspose(b *testing.B) {
    for N := 0; N < b.N; N++ {
        _ = transpose(a)
    }
}

func NewMatrix(d2, d1 int) [][]int {
    a := make([]int, d2*d1)
    m := make([][]int, d2)
    lo, hi := 0, d1
    for i := range m {
        m[i] = a[lo:hi:hi]
        lo, hi = hi, hi+d1
    }
    return m
}

func transposeOpt(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    for i := 0; i < len(b); i++ {
        c := b[i]
        for j := 0; j < len(c); j++ {
            c[j] = a[j][i]
        }
    }
    return b
}

func BenchmarkTransposeOpt(b *testing.B) {
    for N := 0; N < b.N; N++ {
        _ = transposeOpt(a)
    }
}

func transposeRow(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    var wg sync.WaitGroup
    for i := 0; i < len(b); i++ {
        wg.Add(1)
        c := b[i]
        go func(c []int, i int) {
            defer wg.Done()
            for j := 0; j < len(c); j++ {
                c[j] = a[j][i]
            }
        }(c, i)
    }
    wg.Wait()
    return b
}

func BenchmarkTransposeRow(b *testing.B) {
    for N := 0; N < b.N; N++ {
        _ = transposeRow(a)
    }
}

var numCPU = runtime.NumCPU()

func transposeCPU(a [][]int) [][]int {
    b := NewMatrix(len(a[0]), len(a))
    var wg sync.WaitGroup
    n := 2 * numCPU
    stride := (len(b) + n - 1) / n
    for lo := 0; lo < len(b); lo += stride {
        hi := lo + stride
        if hi > len(b) {
            hi = len(b)
        }
        wg.Add(1)
        go func(b [][]int) {
            defer wg.Done()
            for i := 0; i < len(b); i++ {
                c := b[i]
                for j := 0; j < len(c); j++ {
                    c[j] = a[j][i]
                }
            }
        }(b[lo:hi])
    }
    wg.Wait()
    return b
}

func BenchmarkTransposeCPU(b *testing.B) {
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        _ = transposeCPU(a)
    }
}

var a = func() [][]int {
    b := NewMatrix(1920, 1080)
    for i := range b {
        for j := range b[0] {
            b[i][j] = i<<16 + j
        }
    }
    return b
}()

You might want to look at gonum, the Go numeric module. It's open source.

For matrices:

  package mat

import "gonum.org/v1/gonum/mat"

  Package mat provides implementations of float64 and complex128 matrix
  structures and linear algebra operations on them.


Dynamically set angular directive template

To my opinion your 2nd way which uses ng-include is better because as mentioned in angular doc it says that-

  The $templateRequest service runs security checks then downloads the provided template using $http and, upon success, stores the contents inside of $templateCache. If the HTTP request fails or the response data of the HTTP request is empty, a $compile error will be thrown.

Although $templateRequest factory that was added in v3.0. $templateRequest function checks and saves to the $templateCache.

Another way you can use

templateUrl: function(element, attributes) {
  if (element[0].tagName === 'INPUT') {
    return 'templates/input.html';
  } else {
    return 'templates/default.html';
  }
}


let and const allows us to declare block scoped variable. In your code

if (imperialCountries.indexOf(country) === -1) {
  var units = 'metric';
} else {
  units = 'imperial';
}

when you replace var with let the variable units becomes a block scoped variable and is recognized only inside the if block. You can make the following change in your code to use let:

let units;
if (imperialCountries.indexOf(country) === -1) {
  units = 'metric';
} else {
  units = 'imperial';
}


Dinning Philosophers

How should I improve my solution for Dining Philosopher's problem?

Well first implementing the Dining Philosophers problem would be good. This is an interesting problem you implemented but its not the classic Dinning Philosophers
The issue here is that in your implementation each philosopher tries to grab any two forks. In the classic implementation each philosopher is assigned two specific forks (though each is shared with another philosopher).
The other issue is that you have a single lock for the whole table. In reality you should have a lock on each fork. Just because philosopher one is grabbing fork one does not stop philosopher three grabbing fork three.
Also if a philosopher fails to get either fork, then it must give up all forks and think for a random period.
Code Review
Prefer initializer list. Also you don't need a temporary v in the constructor.
Dining()
{
    vector<int> v = { 1,2,3,4,5 };
    chopsticks = v;
    count = 0;
}

Dining()
    : chopsticks{ 1, 2, 3, 4, 5}
    , count(0)
{}

Use RIAA.
If you have code that looks like
InitSomething

// Stuff

UnitSomething

Then you should have an object that handles the InitSomething in the constructor and UnitSomething in the destructor.
In this:
    arbit.lock();

    // STUFF

    arbit.unlock();

Should look like this:
    std::lock_guard<std::recursive_mutex>   lock(arbit);
    // STUFF

Don't use dynamic allocation when automatic variables will work
Dining* philosophers = new Dining();

This should be:
Dining   philosophers;


Correctness

Input
1 1 1 1 0 0 0

Output
None, None
0, 4

The reason is obvious: the longestSequence does not distinguish between longest sequence of zeroes and longest sequence of ones, so 0 0 0 is not considered long enough.
General

Avoid globals; prefer returning values.
There is no need to pass size; a list already knows its size. For the same reason, size = int(input()) is redundant and reduces usability.


Putting 3 different on click functions into one reusable function

A lot of present code can be made reusable.

I have made the necessary changes and created a single reusable function handleEvent

// Handle next-image click on product single page
var handleEvent = function(e, currentClass, linkClass, method) {
    e.preventDefault();

    var current = $('.' + currentClass + '.first');
    var next;

    // handles click on thumbnail
    if (typeof method == "undefined") {
        next = $(this);
    } else {
        // Handles next-image and prev-image click on product single page
        // Check if thumbnail is last, if it is make first thumbnail next
        if (current.next().hasClass(linkClass)) {
            next = current.next('.' + linkClass);
        } else {
            next = $('.' + linkClass)[method]();
        }
    }

    // Grab image src from data-image attribute
    var image = next.data('image');

    $('.woocommerce-main-image')
        .find('img')
        .animate({
            opacity: 0
        }, 300, function() {
            $(this).attr('src', image);
            $(this).animate({
                opacity: 1
            }, 300);
        });

    current.removeClass('first');
    next.addClass('first');
};

Example of calling this reusable function from three different events is as follows

// Handle next-image click on product single page
$('.images').on('click', '#next-image', function(e) {
    handleEvent(e, 'thumbnail-link', 'thumbnail-link', 'first');
});

// Handle prev-image click on product single page
$('.images').on('click', '#prev-image', function(e) {
    handleEvent(e, 'thumbnails', 'thumbnail-link', 'last');
});

// Handle click on thumbnail
$('.thumbnails').on('click', '.thumbnail-link', function(e) {
    handleEvent(e, 'thumbnail-link');
});


This is copied from my answer to your question "What about my Pong game?".

The Text._size member is only used to create the font, so there is no need to store it in the instance.
Why not make Text a subclass of pygame.sprite.Sprite so that you can draw it using a sprite group?
Lots of code is repeated betwen Text.__init__ and Text.set_value. Why not have the former call the latter?
The Text.__init__ constructor takes many keyword arguments, which you then apply to self.rect like this:

if top: self.rect.top = top
...

The first problem is that the test if top: means that you can't set top to zero. You should write something like this:

if top is not None: self.rect.top = top

But it would be much simpler to use Python's ** keyword argument mechanism to take any number of keyword arguments, and pass them all to Surface.get_rect.

Applying all these improvements yields the following:

class Text(pygame.sprite.Sprite):
    def __init__(self, text, size, color, font=None, **kwargs):
        super(Text, self).__init__()
        self.color = color
        self.font = pygame.font.Font(font, size)
        self.kwargs = kwargs
        self.set(text)

    def set(self, text):
        self.image = self.font.render(str(text), 1, self.color)
        self.rect = self.image.get_rect(**self.kwargs)


Standardizing Controller + Service method signatures

Just create a helper method for executing a query where you wrap the entire try/catch error handling and pass the query via a lambda expression:

private async Task<T> ExecuteAsyc<T>(Func<DbContext, T> query)
{
    try
    {
        using (var db = new DbContext())
        {
            return query(db);
        }
    }
    catch (Exception e)
    {
        HandleServiceLayerException();
        return default(T);
    }
}

Then you call it like this with a lambda:

public async Task<ApiResponseDto> SubmitReportAsync(string username, string ReportDto report)
{
    return ExecuteAsyc(context =>
    {
        // this is where the unique stuff is
    });
}


SQL report of subscribers and their associated revenue

I think this looks very good, but I would make a few small changes:

Instead of getting separate columns for month and day, use one column with date_trunc('day', subscriptions.created_at). Then you still have a timestamp that you can format, sort by, etc. Also you will avoid problems when someone reports on a range crossing New Years.
Be aware that binning timestamps into days involves time zones. Right now you're cutting days using UTC, which may be fine, but just be aware of it if you want to do something else.
You don't seem to be using the users table at all, so you could just leave that out completely.
Watch out for your edge conditions. Your query will include all of 1/1 but only the first instant of 3/4. It is more common and probably better to do >= and <. Otherwise if something happens in that first instant it will be double-counted with the next range (e.g. 3/4 to 6/1).


Comparing values of equal-length tuple and list

If I've understood your code correctly, you can do this trivially with zip:

def _is_valid_combination(combination, path):
    """
    Check if the combination is valid for the path

    Keyword arguments:
    combination -- tuple of pattern combination
    path -- list of the actual path
    """
    return all(part == '*' or part == path_ for part, path_ in zip(combination, path))


Change View visibility programmatically or through XML?

According to View source code setting visibility through xml (line 3450) is cheaper than through setVisibility method (line 5511).

So it is better to change visibility programmatically fewer times.


You're not trying to modify a local environment, you're trying to modify the module's dictionary, which you can access by calling globals().

Note: the dictionary returned by locals() isn't meant to be modified.


Sanitizing and validating a user signup form before submission

Kid Diamond! It's always great to see code improving over time. ☺

On loading, you treat input[name=firstName] and input[name=lastName] specially, due to the need for some specialised logic. Instead of selecting each of them every time, you can assign them to variables. The variables are prefixed with $ to remind you that these are jQuery objects.

var $firstName = $("#signup input[name=firstName]"),
    $lastName  = $("#signup input[name=lastName]");

In the first if block, you could optionally take advantage of method chaining. I get rid of the #signup in the selector: since $firstName is already a descendant of #signup, then its siblings will be too, and so it's unnecessary.

$firstName.select().siblings("div").show();

The else if condition is not immediately obvious. After looking at it more carefully, the logic flow is this:

Consider whether the error is associated with $firstName.

If so, consider whether $firstName is not empty.

If $firstName is not empty, then consider whether it is greater than the max length.

If so, then $firstName is the errant field and should be selected.
Otherwise, $firstName is fine, so $lastName must be errant and selected.

If $firstName is empty, then fall-back to the else (below).

Else, select the input associated with the first error.

This is actually rather complicated. In fact, for this snippet, I prefer your original code. Here is how I would rewrite it:

var $errors = $("#signup .error");
if ($errors.length === 0) {
    $firstName.select().siblings("div").show();
} else {
    var $firstError = $errors.first();
    if ($firstError.closest(".input").has($firstName).length > 0) {
        if (!$firstName.val() || $firstName.val().length > MAX_FIRST_NAME_LENGTH) {
            $firstName.select();
        } else {
            $lastName.select();
        }
    } else {
        $firstError.closest(".input").children("input").select();
    }
}

In the event handler, you can at least do var $div = $("#signup div"). Personally, I'd rather rewrite like the following, just because the logic reads slightly more clearly to me:

$("#signup input").on("focus blur", function(e) {
    var $div = $(this).siblings("#signup div");
    if ($div.has(".error").length > 0) {
        $div.stop();
        if (e.type === "focus") {
            $div.slideDown("fast");
        } else {
            $div.slideUp("fast");
        }
    }
});

Below the comment, the code is pretty good. The one thing I'd change is I wouldn't make a $button variable at all, since it's only used once. I might also reverse the order of the logic to avoid the unnecessary return true;:

if (emptyInputs > 0) {
    return false;
}
// if the form submits successfully, disable the button to prevent accidental double-submits.
$("#signup button").prop("disabled", true);


Finding the weight of the heaviest path in a binary tree

The algorithm looks sound.  It visits every node once, and cannot be more efficient than that.

I find it odd that you split the code into two classes, one of which is non-public.  Since the Node class is non-public, no code in any other package will be able to construct a Node.  The algorithm is therefore "unusable".

There are two ways to model a tree: a "lazy" way (exposing the nodes, and a tree is just referred to by its root node) and a "polished" way (with the tree being an opaque data structure that hides and manages its nodes).  Here, you have an odd hybrid.

If you want to have a BinaryTree class that contains nothing but a static method, then you should suppress the implicit no-argument default BinaryTree() constructor by making it private:

public class BinaryTree {
    // Suppress the default constructor
    private BinaryTree() {}

    public static int getHeaviestPathWeight(…) {
        …
    }
}

Package names are conventionally all lowercase.

Whenever possible, use int instead of Integer.  Using Integer objects is less efficient and usually results in more complicated source code and bytecode.  One reason why you might need an Integer instead of an int would be to store a null — and that sounds more like a liability than an advantage in this case.

To language purists, "data" is plural, and "datum" is singular.  However, I would suggest a different name altogether, such as weight.

Simple solution

package binarytree;

public class BinaryTree {
    private final int weight;
    private final BinaryTree left, right;

    public BinaryTree(int weight, BinaryTree left, BinaryTree right) {
        this.weight = weight;
        this.left = left;
        this.right = right;
    }

    public BinaryTree(int weight) {
        this(weight, null, null);
    }

    /**
     * JavaDoc here
     */
    public int getHeaviestPathWeight() {
        return this.weight + Math.max(
            this.left  == null ? 0 : this.left.getHeaviestPathWeight(),
            this.right == null ? 0 : this.right.getHeaviestPathWeight()
        );
    }
}

Alternate solution

package binarytree;

public class Node {
    public final int datum;
    public final Node left, right;

    public Node(int datum, Node left, Node right) {
        this.datum = datum;
        this.left = left;
        this.right = right;
    }

    public Node(int datum) {
        this(datum, null, null);
    }
}

public class HeaviestPath {
    private HeaviestPath() {}

    /**
     * JavaDoc here
     */
    public static int weight(Node root) {
        if (root == null) {
            return 0;
        } else {
            return root.datum + Math.max(weight(root.left), weight(root.right));
        }
    }
}


Accept either a existing stream or a filename (to be opened) in a constructor

Very close

You're actually one foot off the finish.

Reduce

You could store a pointer to the istream (note that std::ifstream is its child class, so new std::ifstream(file) will automatically be converted to istream*), then store a bool flag if it is owning or not.

Bigger issue

There is yet greater issue here, and it is ownership semantics. When ownership semantics are weird design starts becoming fragile. I'd recommend letting the caller to take ownership of the stream, so that Parser wouldn't mess with it and keep rule of zero. Callers will have much more power that way. Otherwise Parser would also require implementing either of rule of 0/3/5.

Code review

fin.close();

is redundant in the destructor. Invoking it explicitly opens possibilities for exceptions, thus making your fin leak. Just delete it, destructor will take care of closing.

Code never checks if the file is opened. Code could start on non-opened stream, which is, I believe undefined behavior.


Ah, you moved your <h1> into the <body>. Still, what exactly are you looking for? File size (--> code reduction)? Speed optimization?

One simple thing would be using parameters to reduce code duplication:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.rect(0, 0, 200, 300);
ctx.fillStyle = "grey";
ctx.fill();

var colours = ["red", "yellow", "green",  "red yellow"];
var current = colours[0];

function offlight(a1) {
    ctx.beginPath();
    ctx.arc(95, a1, 40, 10, 12 * Math.PI);
    ctx.fillStyle = "black";
    ctx.fill();
    ctx.stroke();
}

function drawLight(a1, fillParam) {
    ctx.beginPath();
    ctx.arc(95, a1, 40, 10, 12 * Math.PI);
    ctx.fillStyle = fillParam;
    ctx.fill();
    ctx.stroke();
}

function changelight() {
    if (current == colours[0]) {
        drawLight(50, "red");
        offlight(150);
        offlight(250);
        current = colours[4]
    } else if (current == colours[4]) {
        drawLight(50, "red");
        drawLight(150, "yellow");
        offlight(250);
        current = colours[2]
    } else if (current == colours[2]) {
        offlight(50);
        offlight(150);
        drawLight(250, "green");
        current = colours[1]
    } else if (current == colours[1]) {
        offlight(50);
        drawLight(150, "yellow");
        offlight(250);
        current = colours[0]
    }

}
setInterval(changelight, 1000);

Do you ever use colours? ("yellow")

You could also remove the whitespaces and shorten variable and function names. Also think about moving your JS into a separate file.

Here is a working fiddle.


Form validation evaluation to avoid exploits

I think it looks ok - though someone might want to add on if they notice any issues I may have missed. However, a bit of cleanup goes a long way:

# Set a 500 (internal server error) response code.
function outputResponse($override = "", $code = 500){
    # http_response_code($code);
    echo $override ?: "Oops! Something went wrong and we couldn't send your message.";
    exit;
}

# Exit early while doing negative checks
if(empty($_SERVER['HTTP_X_REQUESTED_WITH'] ||
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest' ||
    $_SERVER["REQUEST_METHOD"] != "POST"){
    outputResponse();
}

# Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = strip_tags(trim($_POST["message"]));

# Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    # Set a 400 (bad request) response code and exit.
    outputResponse("Oops! There was a problem with your submission. Please complete the form and try again.", 400);
}

# Set the recipient email address.
$recipient = "email_here";

# Set the email subject.
$subject = "New contact from $name";

# Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";

# Build the email headers.
$email_headers = "MIME-Version: 1.0\r\n";
$email_headers .= "Content-type: text/html; charset=utf-8\r\n";
$email_headers .= "From: $name <$email>\r\n";
$email_headers .= "Reply-To: $email\r\n";
$email_headers .= "Return-Path: $email\r\n";
$email_headers .= "Organization: Bilingual Counselling\r\n";

# Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
    # Set a 200 (okay) response code.
    outputResponse("Thank you! Your message has beent sent.", 200)
} else {
    outputResponse();
}


Trie Data Structure Implementation in C++11 using Smart Pointers -- follow-up

Input sanitization

Your functions take a std::string as parameter, as such, they should be "well behaved" for any possible std::string passed to them. Note that well behaved does not mean that it has to "work", just that it should not break anything.

Specifically, what would happen if I passed the string "Hello" to that function? 'H' - 'a' is -25, ruh roh!

There's a few different ways to tackle this.

You could convert all upper-case letters to lower case, but that does not fix punctuation marks, spaces and numbers. I also personally think that wether the trie is case-sensitive or not should be the user's problem, not the trie itself.
You could bail out of the function if a unhandled character is hit.
Just expand children to 256 instead of 26 so that all legal values of char are handled properly. Sure your trie is going to be 5 times as big, but that's a fairly minor detail since it grows logarithmically.

edit: This last approach also makes the trie operate on raw data instead of characters, which makes it encoding-agnostic (which gives you your unicode support)

Avoid using shared_ptr unless absolutely necessary

shared pointers are clunky and heavy affairs. On top of this, using them sends a message to people reading the code: Ownership of the object is potentially shared between multiple owners, which is simply not the case here.

in your case, a std::unique_ptr<> is absolutely fine.

Your root does not need to be dynamically allocated

It's created at construction unconditionally, and destroyed at destruction unconditionally. On top of that, it does not make use of type erasure (polymorphism). As such, there's no reason for it not to be a normal member of trie.

std::shared_ptr<Node> root = std::make_shared<Node>();

becomes:

Node root;

This will require you to change your search and insert functions so that the first line becomes:

const Node* n = &root;

But that's fine because that's preferable once you move to unique_ptr anyways.

Edit: On that note:

Raw pointers are not evil

std::shared_ptr<Node> n = root;

We tend to teach people that "you should never use raw pointers". But I find that extremely naive. The real rule is "You should never have raw pointers with ownership".

There is absolutely nothing wrong with using raw pointers as long as it's understood that:

The pointer only refers to the pointed object without owning it.
The lifetime of the pointer assignment to the object is fully enclosed by the lifetime of whatever DOES own the object.

In your code using shared_ptr, using the following would have been 100% ok, and much better in my opinion:

const Node* n = root.get();

Mark non-mutating functions as const.

Your search() member function should not alter the trie in any way, so you should mark it as const like this:

bool search(const std::string & key) const {

There's a few subtle advantages for the compiler, but the main one is that if you goof up and accidentally do something that changes the trie, the compiler will tell you.

nitpick: private: is redundant here.

The namespace of a class is private by default. Fun fact: that's the only difference between a class and a struct.

nitpick: redundant null-checking

in your search function, when I read the last line:

return n && n->end;

My impression was "Oh! n can be possibly null in certain cases", which led me to search for the scenario where that might be the case. It's misleading to the reader.

Defensive programming can be useful at times, but this is just excessive.


C would have allowed you to just ignore errors and pretend everything was good. A naïve cat would be very short, but rather unreliable also. A well‐written cat will go and use all the error codes that are returned to produce a useful result.
Python and similar languages would raise exceptions in these cases, leading to you getting tracebacks in case of errors on a naïve approach; again, a well‐written cat is going to handle all of these exceptions manually, producing a neater result.
Rust makes error‐handling explicit and makes it harder for you to ignore errors, though you still can ignore them if you want by unwrapping results, which gets you something more like the default arrangement in languages like Python. The explicit nature of error handling can be a pain in places (most notably for simple scripts), but it makes for a much more solid result in general as it scales very well.

One must realise that in these common tasks that people tend to assume must succeed there are actually possibilities of failure.

Writing to stderr and stdout may fail. They might be being piped to a read‐only file, or on a device that is not ready or full. print!, for example, will panic if writing fails.
By using String, you’ve constrained your lolcat to only use UTF‐8; if you pass a non‐UTF‐8 file, it will blow up in your face. You might want to vec![] instead of String::new(), read_to_end instead of read_to_string and stdout().write(&buf) instead of print!("{}", buf).

Macros can be quite good at alleviating these sorts of pains; there is try!, for example, which works well at handling Results; if you refactored your code so that all of the important stuff was inside a function which could then return Result<(), io::Error>, for example, you could use try! on all of the fallible I/O operations. As it is, you can do things like writing a new macro to assist, and also give a more helpful message explaining where the error occurred.

Here’s something more like what I would write; of course, there are various points that are subjective, and I have made some stylistic changes to be in line with what I believe to be more common standard style:

use std::env;
use std::io::{Read, Write, stdout};
use std::fs::File;
use std::path::Path;
use std::process;

macro_rules! println_stderr {
    ($($arg:tt)*) => {
        match writeln!(&mut ::std::io::stderr(), $($arg)*) {
            Err(e) => panic!("Unable to write to stderr: {}", e),
            Ok(_) => (),
        }
    }
}

macro_rules! try_or_die {
    ($e:expr, $err_msg:expr) => {
        match $e {
            Ok(x) => x,
            Err(e) => {
                println_stderr!(concat!($err_msg, ": {}"), e);
                process::exit(1);
            },
        }
    }
}

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() < 2 {
        println_stderr!("Usage: {} GIMME_TEH_FILEZ",
                        Path::new(&args[0]).file_name().unwrap().to_str().unwrap());
        process::exit(1);
    }

    let path = Path::new(&args[1]);
    let mut file = try_or_die!(File::open(path), "failed to open input file");

    let mut buf = vec![];
    try_or_die!(file.read_to_end(&mut buf), "failed to read input file");
    try_or_die!(stdout().write(&buf), "failed to write output");
}

(At first I had try_or_exit, but then try_or_die sounded better.)


Loop each folder and subfolder to get values

As Mathieu Guindon mentioned in the comments, the main slow down is that you are creating a new Excel.Application for each file.   I would personally just use the current Application and turn off Application.ScreenUpdating.

Using an InputBox to prompt an user to enter a folder path is very prone to error. You should test if the folder exists.

FolderName = InputBox("Enter path", "Get File")
Do While Len(Dir(FolderName, vbDirectory)) = 0
    If Len(Dir(FolderName, vbDirectory)) = 0 Then
        If MsgBox("Do you wish to continue?", vbYesNo, "Invalid Folder") <> vbYes Then
            Exit Sub
        Else
            FolderName = InputBox("Enter path", "Get File")
        End If
    End If
Loop

Or better yet just use Application.FileDialog(msoFileDialogFolderPicker) to pick the folder.  It's the right tool for the job.

Using an Array to collect the data and writing it to a range of cells in one operation is much faster the writing each piece of data to an individual cell.

Refactored Code

Here is how I would write the code.  Notice that I created a subroutine to collect the files and another to get the Folder Path.  This allows me to debug each part of the code separately.

Sub LoopFoldersAndXLFiles()
    Dim t As Double: t = Timer
    Const SheetName As Variant = 1
    Dim FileList As Collection
    addExcelFileList FileList
    If FileList.Count = 0 Then Exit Sub

    Dim oFile As Object, xlApp As New Excel.Application
    Dim r As Long
    Dim results() As Variant
    ReDim results(1 To FileList.Count, 1 To 8)
    For r = 1 To FileList.Count
        Set oFile = FileList(r)
        With xlApp.Workbooks.Add(oFile.Path)
            results(r, 1) = oFile.Name
            results(r, 2) = oFile.DateCreated
            results(r, 5) = .Sheets(SheetName).Range("D3").Value
            results(r, 6) = .Sheets(SheetName).Range("G12").Value
            results(r, 7) = .Sheets(SheetName).Range("C9").Value
            results(r, 8) = .Sheets(SheetName).Range("C13").Value
            .Close SaveChanges:=False
        End With
    Next

    xlApp.Quit

    With ActiveSheet
        With .Range("A" & .Rows.Count).End(xlUp).Offset(1)
            .Resize(UBound(results), UBound(results, 2)).Value = results
        End With
    End With
    Debug.Print Round(Timer - t, 2)
End Sub

Sub addExcelFileList(ByRef FileList As Collection, Optional FolderName As String, Optional fso As Object)
    If Len(FolderName) = 0 Then
        FolderName = getFolderPath
        If Len(FolderName) = 0 Then Exit Sub
    End If
    If FileList Is Nothing Then Set FileList = New Collection
    If fso Is Nothing Then Set fso = CreateObject("Scripting.FileSystemObject")

    Dim oFolder As Object, oSubfolder As Object

    Set oFolder = fso.GetFolder(FolderName)

    For Each oSubfolder In oFolder.SubFolders
        If UCase(oSubfolder.Name) <> "DO NOT USE" Then addExcelFileList FileList, oSubfolder.Path, fso
    Next

    Dim oFile As Object
    For Each oFile In oFolder.Files
        If oFile.Type = "Microsoft Excel Worksheet" And Not oFile.Name Like "*~*" Then FileList.Add oFile
    Next
End Sub

Function getFolderPath() As String
    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then Exit Function
        getFolderPath = .SelectedItems(1)
    End With
End Function


Populating a class whose data is stored in an external application

What you have implemented is a sort of Active Record where the record itself knows how to communicate with the storage.

What is bad about your design is that this kind of code will be extremely hard to unit test. Imagine that you need to write a unit test for a class that uses Person objects. How can you prevent it from calling UserService?

The proper solution for your problem depends on use cases.

Will you need to update your entities and propagate those changes back to server?
Can you load several entities at once using methods other than UserService.getPerson(this.id);?
What is the lifetime of the entities loaded?

Generally the most flexible solution (as I see it) would be to implement a repository and unit-of-work pattern (similar to ISession in NHibernate or DbContext in Entity Framework). Basically it's better not to hide communication with 3rd-party but rather expose it in such a way that you have maximum control and flexibility.

Primitive implementation may look like:

public class Person
{
    public string Id { get; set; }

    public string Name { get; set; }
}

public interface ISessionFactory
{
    IUserServiceSession CreateSession();
}

public interface IUserServiceSession
{
    Person GetPerson(string id);
}

public class SessionFactory : ISessionFactory
{
    public IUserServiceSession CreateSession()
    {
        UserService userService = new UserService(); //better use dependency injection, or cache it once if it's thread-safe.
        return new UserServiceSession(userService);
    }
}

public class UserServiceSession : IUserServiceSession
{
    private readonly Dictionary<string, Person> _cache = new Dictionary<string, Person>();
    private readonly UserService _userService;

    public UserServiceSession(UserService userService)
    {
        _userService = userService;
    }

    public Person GetPerson(string id)
    {
        Person result;
        if (!_cache.TryGetValue(id, out result))
            result = _cache[id] = _userService.getPerson(id);

        return result;
    }
}


Getting the url of origin

This is a bit awkward:

remote=$(grep -A 1 "remote \"origin\"" $(pwd)/.git/config | sed -n 2p)

Because:

The grep + sed is a bit hacky
$(pwd) can be replaced with a simple .
It's awkward to rely on .git/config content instead of some git command

Try to look for native Git commands to extract this kind of information, for example:

git remote show -n origin | grep Fetch.URL

The output is not exactly same as the original, but it will work fine with the rest of your script.

Named parameters

In Bash there are no named parameters.
As a consequence, in this function it can be hard to remember what $1 refers to:

open_site() {
  # currently only works for SSH addresses
  if [[ $remote == *@* ]]; then
    name=$(echo $remote | sed  "s/^.*:\(.*\)\.git/\1/g")
    ext=$(get_ext $1)
    open "$1/${name}${ext}"
  fi
}

As a workaround, I recommend assigning the parameter to a well-named local variable, like this:

open_site() {
  local baseurl=$1
  # currently only works for SSH addresses
  if [[ $remote == *@* ]]; then
    name=$(echo $remote | sed  "s/^.*:\(.*\)\.git/\1/g")
    ext=$(get_ext $baseurl)
    open "$baseurl/${name}${ext}"
  fi
}

Pattern replacement

Instead of this:

name=$(echo $remote | sed  "s/^.*:\(.*\)\.git/\1/g")

I recommend simple pattern substitution:

# chop off the start until the last :
remote=${remote##*:}
# chop off .git at the end
remote=${remote%.git}

The benefit of this approach is that it doesn't run extra programs (no sed, no echo, no piping).

A minor note, the original sed didn't need the g flag.

Printing a blank line

You don't need "" to just echo a blank line:

echo ""

This is exactly the same:

echo


Computing sum of elements with mutlithreads

Better algorithm

So the main practical improvement would be to use a roll. Atomics are very slow if multiple threads take turns in accessing it in clockwise/anticlockwise manner, e.g. like a carousel. Let's define the algorithm:

Retrieve number of physical threads, e.g. cores. Sometimes it is not available, so setting it to 4 would be a pretty good guess these days. Number of threads visible to OS would be important if algorithm would have diverse workload, but this is not the case here.
While not reached the end of the vector:

2.1 Allocate all physical threads to sum 1000 numbers in the range. The number might need to be fine tuned, but I believe this already should outweigh the cost of the thread creation.

2.2. Sum the results of each number into result.

The process is actually much harder than it looks like. One has to create a vector of std::promises and get std::futures of them, then create small function that would set the future from outside, then join threads ... Well I guess you got the point. This question should help out with that.

Compute in place

Since the algorithm does read-only access on the container, it could be just passed by reference. The master function could schedule the work and then collect the result.

Iterators

I believe that if the properties of std::vector are not exploited, it doesn't make much sense to hardcode it. Iterators provide powerful abstraction, though they take time to get used to them. Also, they could be used to delegate to std::accumulate, e.g. in the small function it would just call accumulate on range.

More power

I believe the function could be extended without much effort and still retain compatibility and easy of use of original one. Something like this:

template <typename RandomAcessIt,
          typename T = std::iterator_traits<RandomAcessIt>::value_type,
          typename BinaryOp = std::plus<>>
T accumulate(parallel_compute_tag, RandomAcessIt first, RandomAcessIt last, T initvalue = {}, BinaryOp op = {})

So default would still be +, but it could be changed to whatever heart likes. And then instead of using + one could just op(lhs, rhs).

Rolling

Here is a terrible picture (I made my best at it)

As you can see, the scheduled threads "roll into" master thread to provide the result. That is why I said rolling approach. I don't really know the term for this though.


Exception based on std::exception but easy to modify and rethrow

A note on the the link you posted; the OP was asking a hypothetical question in regards to what happens ('under the hood') to the call stack/exception/etc. if the exception that is caught is of a reference type (i.e. catch (std::exception& e) vs catch (const std::exception& e)). As was answered there, yes it is not a good idea to modify the exception within a catch (though completely legal code, still not advised).

Per your code, there are a couple of things worth noting:
changing your err type from a  std::array<char, long_enough> to a std::string would simplify all of your code, also, while you can pass a const char[] into functions, it decays into a pointer (pointing to the first element in the array), so it's similar to just const char*, if you're intent WAS to pass in a reference to a char[], it's recommended you pass a const size, as in template<int N> someFn(const char (&x)[N]), otherwise stack issues can occur. As well, if you're working with C++, unless you have a specific need to use a char[] (which is possible) it's advised to use a std::string over a char[].

Lastly, while having an append function to add aditional information into your exception object could be useful, it's usually better to derive a specific exception from your base exception with specific information in it (or otherwise just put the needed information in your throw exception...). Here's you're exception class with the err variable being a std::string

class my_exception : virtual public std::exception {
private:
    std::string err;
public:
    void append(std::string::iterator first, std::string::iterator last) {
        err.append(first, last);
    }
    void append(const char* msg) {
        err.append(msg);
    }
    my_exception(const char* msg) noexcept : err(msg) {}
    virtual const char* what() const throw() {
        return err.c_str();
    }
};

Use it like such:

try {
    throw my_exception("here's a simple message");
} catch (std::exception e) {
     e.append("...added some text");
     std::cout << "error: " << e.what() << std::endl;
     // or printf("error: %s\n", e.what()) for your C friends
}

As a side note (and for reference), here is the exception code from part of an open source framework I'm working on (just in a single header file exception.hpp):

#include <iostream>
#include <exception>
#include <string>

namespace your_namespace {
    class exception : virtual public std::exception {
        public:
            exception() throw() : m_what("general exception") {}
            exception(const char *reason) throw() : m_what(reason) {}
            exception(const std::string& reason) throw() : m_what(reason) {}
            virtual ~exception() throw() {}
            virtual const char* what() const throw() { return m_what.c_str(); }
            virtual void seterr(const char *err) { this->m_what = std::string(err); }
            virtual void seterr(const std::string &err) { this->m_what = err; }
            friend std::ostream& operator<<(std::ostream& s, const omni::exception& e)
            { s << e.m_what; return s; }
            friend std::basic_ostream<wchar_t>& operator<<(std::basic_ostream<wchar_t>& s, const omni::exception& e) {
                s << e.m_what.c_str();
                return s;
            }
        protected:
            std::string m_what;
    };

    class some_other_exception : public your_namespace::exception {
        public:
            some_other_exception() : exception("some other exception happened") {}

    };
}

To use:

try {
    throw your_namespace::exception();
} catch (std::exception e) { // or const std::exception&
    std::cout << "error: " << e << std::endl;
    // or printf("error: %s\n", e.what()) for your C friends
}

try {
    throw your_namespace::exception("Here's an exception for you");
} catch (std::exception e) {
    std::cout << "error: " << e << std::endl;
}

try {
    throw your_namespace::some_other_exception();
} catch (std::exception e) {
    std::cout << "error: " << e << std::endl;
}

I hope that can help


Optimizing search by id in some data in JSON structure

It looks like this is just a snippet of the code you are using, but if this is the standard structure, you could simplify your search by doing something like:

getById: function(id) {
    function innerGetById(obj, id) {
        var result;
        if (obj.id == id) {
            return obj;
        } else {
            for (var i = 0; i < obj.cnt.length; i++) {
                result = innerGetById(obj.cnt[i], id);
                if (result) {
                   return result;
                }
            }
        }
    }
    return innerGetById(test, id);
}

This will only work if you know the names of the keys you are dealing with, if that is unknown, you will need to do a for in loop like you have. The key here is that you are testing for the id outside of the loop through the array.

I would also define innerGetById outside of your getById function if possible. I just wrote it this way because I don't know the context that you are defining the getById function in and it looks like you may be creating it as part of an object.

To answer your question, I'm not sure that a faster way exists than manually searching through the structure unless you are willing to index the structure before doing the search. If you want to do that, you can use the same sort of recursive method, but create a flat object with the ids as keys and the associated object as the value. This will make lookups very simple.

You can turn your test object into something like this:

lookupTable = {
    0: { id: 0, cnt: [ ... ] },
    1: { id: 1, cnt: [ ... ] },
    2: { id: 2, cnt: [ ... ] },
    etc.
}

By using something like:

var lookupTable = {};
function buildLookupTable(obj) {
    lookupTable[obj.id] = obj;
    for (var i = 0; i < obj.cnt.length; i++) {
         buildLookupTable(obj.cnt[i]);
    }
}
buildLookupTable(test); // Using your original test data

Then your lookup is simply: lookupTable[id]


I agree that the String should be left out of the name, as this is quite obvious in StringUtils. How about this short version?

public static boolean isNullOrWhiteSpace(String value) {
    return value == null || value.trim().isEmpty();
}


I am also a novice in Go, so can't say anything about the idiomatic of this approach, but some improvements can offer.

Makes no sense to return -1 in currentBrightness/0  because panic is panic.
By the way, Go instead of processing the code of the return value is customary to return the error value as, for example, in strconv.Atoi or ioutil.ReadFile.
Instead of replace better to use TrimSpace

strings.TrimSpace(string(buff))

Code duplication

Not necessary 2 times used strconv.Itoa(brightness).

str := fmt.Sprint(brightness)
checkError(ioutil.WriteFile("brightness", []byte(str), os.ModeDevice))
fmt.Fprintf(w, str)

Since the error handling in Go program a common thing, easy to create a special function.

func checkError(err error) {
    if err != nil {
            log.Fatal(err)
        }
    }

3.
In both handlers have a recurring part: update the value stored in the file. This can also be avoided creating a new function.

update := func(w http.ResponseWriter, brightness int) {
    str := fmt.Sprint(brightness)
    checkError(ioutil.WriteFile("brightness", []byte(str), os.ModeDevice))
    fmt.Fprintf(w, str)
}

Then get as result:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "strconv"
    "strings"
)

func main() {

    const BRIGHTNESS_AMOUNT = 25

    maxBrightness := func() int {
        buff, err := ioutil.ReadFile("max_brightness")
        checkError(err)
        buffInt, err := strconv.Atoi(strings.TrimSpace(string(buff)))
        checkError(err)
        return buffInt
    }()

    currentBrightness := func() int {
        buff, err := ioutil.ReadFile("brightness")
        checkError(err)
        buffInt, err := strconv.Atoi(strings.TrimSpace(string(buff)))
        checkError(err)
        return buffInt
    }

    update := func(w http.ResponseWriter, brightness int) {
        str := fmt.Sprint(brightness)
        checkError(ioutil.WriteFile("brightness", []byte(str), os.ModeDevice))
        fmt.Fprintf(w, str)
    }

    http.HandleFunc("/increase", func(w http.ResponseWriter, r *http.Request) {
        if (currentBrightness() + BRIGHTNESS_AMOUNT) < maxBrightness {
            update(w, currentBrightness()+BRIGHTNESS_AMOUNT)
        } else {
            update(w, maxBrightness)
        }
    })

    http.HandleFunc("/decrease", func(w http.ResponseWriter, r *http.Request) {
        if (currentBrightness() - BRIGHTNESS_AMOUNT) > 0 {
            update(w, currentBrightness()-BRIGHTNESS_AMOUNT)
        } else {
            update(w, 0)
        }
    })

    log.Fatal(http.ListenAndServe(":5600", nil))

}

func checkError(err error) {
    if err != nil {
        log.Fatal(err)
    }
}


Your code is not thread-safe. Each of the threads will, in parallel, be accessing both the best, and the bestQuality variables.

Your Lambda is, in essence, modifying external data from the stream, and this is an anti-pattern for streams. It has side-effects.

You should change your code to use the collect mechanism. There are a few ways to do it, but, you should look at this example for guidance: Reduction

Some Notes about my following suggestion:

I converted the method to a static method, and created an inner accumulator class.
you should possibly refine this answer to suit your needs more in the class structure.

Putting these observations together, I would suggest something like:

public class Maxinator {

    @FunctionalInterface
    public interface QualityFunction<V> {
        double computeQuality(V value);
    }

    private Maxinator() {
//        no public instances
    }

    private static final class AccumulateResult<T> {
        T bestItem = null;
        double bestScore = Double.MIN_VALUE;

        public T getBestItem() {
            return bestItem;
        }

        public void accept(QualityFunction<T> function, T item) {
            double score = function.computeQuality(item);
            if (score > bestScore) {
                bestScore = score;
                bestItem = item;
            }
        }

        public AccumulateResult<T> combine(AccumulateResult<T> r) {
            if (r.bestScore > bestScore) {
                bestScore = r.bestScore;
                bestItem = r.bestItem;
            }
            return this;
        }

    }

    public static <T> T getBest(final QualityFunction<T> qualityFunction, final List<T> population) {
        return population.parallelStream().collect(Collector.of(
                    AccumulateResult<T>::new,
                    (a,t) -> a.accept(qualityFunction, t),
                    (a, b) -> a.combine(b))
               ).getBestItem();
    }
}


The first thing that will help is to switch this from a recursive algorithm to an iterative one. This will prevent the stack overflow that prevents you from solving 25x25, and will be a bit faster to boot.

However to speed this up more, you will probably need to use a smarter algorithm. If you track what numbers are possible in each square, you will find that much of the time, there is only 1 possibility. In this case, you know what number goes there. You then can update all of the other squares in the same row, col, or box as the one you just filled in. To implement this efficiently, you would want to define a set (either a bitset or hashset) for what is available in each square, and use a heap to track which squares have the fewest remaining possibilities.


Sed script that removes specific lines in `seq` output

N;/7/!{P;D}

Nice job there, this very concisely (and clearly) allows you to capture both lines \$n\$ and \$n+1\$.

:b N;s/\n/&/3;Tb;d

Now the loop that follows it is mostly redundant. You are essentially appending lines of input until you are left with \$4\$ lines in total. You already have \$2\$ in your pattern space and need \$2\$ more, i.e. lines \$n-1\$ and \$n-2\$, which can simply be expressed in N;N followed by a d.


void main is a really bad habit. It must be int main.

Always check what scanf returns. For example, try to enter a non-numeric input, and see your program entering the infinite loop.

Avoid conio.h (and hence getch). It is very non-portable.


Is my error handling feasible when dealing items not found in an array?

Your error handling looks correct to me as long as your application is catching PdhSwapRateNotFoundException at some point and logging appropriate warning/error to notify user about this.

A slight cosmetic modification to your code could be like:

{
    if (!SwapExists(shiftedCurve, swapToShift))
        throw new PdhSwapRateNotFoundException(swapToShift);

    var rateToShift = shiftedCurve.Swaps.Single(r => r.Description() == swapToShift);
    rateToShift.Rate = rateToShift.Rate + 1 / 10000.0;
    return; // you don't actually need this.
}

And you're correct default value of reference type is null.

Edit:
I assume shiftedCurve.Swaps will not be null, otherwise Find will throw an exception. And if you think it could be the case then you may want to update your code to check for shiftedCurve.Swaps == null and handle it appropriately.


Fastest way to find if a lot numbers are in multiple intervals

Review

Please don't use using namespace; on the gobal scope. It's considered bad practice. Next, try to keep the scope of your variables smaller. Also indent your code properly to make it easier for you (and others) to see the program flow.

Don't include bits/c++. It's not a standard header. It's somewhat OK in programming challenges, but you should use the proper includes in your real/production code.

If you use a smaller scope for your variables, you will also be able to use better names for them, for example lower instead of temp and upper instead of temp1.

If we apply these changes (and translate your names into English), we end up with

#include <iostream>
#include <utility>
#include <vector>

int main()
{
    std::cin.tie(0);
    ios_base::sync_with_stdio(0);
    std::cout.tie(0);

    std::vector<std::pair<int, int>> ranges;
    std::vector<int> numbers;

    int number_count, range_count;

    std::cin >> number_count >> range_count;

    for (int i = 0; i < number_count; i++){
        int number;
        std::cin >> number;
        numbers.push_back(number);
    }

    for (int i = 0; i < range_count; i++){
        int lower, upper;
        std::cin >> lower >> upper;
        ranges.push_back({lower, upper});
    }

    for(int i = 0; i < range_count; i++){
        int count = 0;

        for(int h = 0; h <number_count; h++){
            if(ranges[i].first <= numbers[h] && ranges[i].second >= numbers[h]){
                count++;
            }
        }
        std::cout << count << "\n";
    }
    return 0;
}

It would be even better to use the proper types and more functions for I/O.

Performance

Instead of \$\mathcal O(nm)\$, you can get \$\mathcal O((n+m) \log n)\$ if you std::sort the numbers and then use std::lower_bound and std::upper_bound.


To load data, you can see the gem Cancan. It think it can do something like you do. I find your code very clear.

Instead of this:

if !organisation.nil?

You can do this:

if organisation.present?

Instead of this:

@categories = Category
  .where(organisation_id: organisation.id)
  .order(:name)
  .all

You can do this:

organisation.categories.order(:name)

Instead of using the method find_by_id you can use just the method find.

You did a good job!


I'm not sure this is any simpler but it does use only a single loop:

 const dataset={ ... }
 const names=[], countries=[]
 for (var d of dataset) {
     names.push(d.name);
     countries.push(d.country);
 }

Surprisingly, according to jsben.ch, this approach is about 6 times faster than running map twice.


The fact that mysqli has nothing to do with PDO aside, there are several things about your code at whole:

this "class Database"  from some article is a dummy. It is absolutely useless and there is not a single reason to prefer it over original PDO. Let alone some flaws in the code inside.
under no circumstances you should create a new database connection in the constructors of your classes. A single existing instance should be passed as a constructor parameter instead.
runQuery() function is misplaced, misnamed and useless. It just performs PDO::prepare() which you can always call directly. It makes whole User class a dummy as well, just a useless chunk of code.
some User-related method should be written in this class instead

Given all the above let's rewrite your code

database.config.php will be a code from my article How to connect to MySQL using PDO:

<?php
$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

here it will give you an instance of PDO class.

user.class.php

<?php
class User
{
    private $conn;

    public function __construct(PDO $pdo)
    {
        $this->conn = $pdo;
    }
    public function findTeacher($id)
    {
        $stmt = $this->conn->prepare("SELECT * FROM teacher WHERE id=?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }
}

here you have a findTeacher() method logically placed in the user class.

index.php

<?php
require_once 'database.config.php';
require_once 'user.class.php';

$user = new User($pdo);
$teacher = $user->findTeacher($_SESSION['teacher_id']);
echo $teacher['Name'];

As you can see, this code is much more concise and logical, actually utilizing some basic OOP, as opposed to your current code which could be written (again more concisely) without any classes.

As for your question, in the average PHP script you don't have to close neither the statement nor the connection. PHP will close it for you automatically.


Optimization on Sieve of Eratosthenes using vector

Repeating work already done
The biggest problem with your solution is that for each test case, you start over from scratch.  This causes you to do up to 10x the work that you need to do.  What you should do instead is:

Read all test cases first (into a vector for example).
Find the maximum n of all the test cases.
Use your sieve once to find all primes up to the maximum number.
Using the vector of primes that you produced with the sieve, solve all test cases.

Don't use expensive operations in loop iterator
Depending on your compiler, this line could be costly:

    for (ll i = 2; i <= sqrt(n); ++i) {

You could instead do:
     for (ll i = 2, sqrt_n = sqrt(n); i <= sqrt_n; ++i) {

to make sure that you don't call sqrt() once per loop iteration.
Sieve loop improvements
This sieve loop:

            for (ll j = 2; (i*j) <= n; ++j) {
                primes[i*j] = 1;
            }

Could be written more optimally as:
            for (ll j = i*i, dj = i+i; j <= n; j += dj) {
                primes[j] = 1;
            }

Notice, the loop starts at i*i instead of 2*i, and it iterates by 2*i instead of by i.  It also avoids multiplication within the main loop.  However, this loop assumes that all even numbers have already been marked from the primes array, so you will have to do that separately when you create the primes array.
Printing loop
The printing loop is not optimal because it starts at 2, even though first may be very large:

    for (ll i = 2; i <= n; ++i) {
        if (primes[i] == 0 && i >= first) {
            cout << i << '\n';
        }
    }

You should just start the loop at first:
    for (ll i = first; i <= n; ++i) {
        if (primes[i] == 0) {
            cout << i << '\n';
        }
    }


check_prime.cpp (checks if input is a prime number)

Don't use using namespace std;.

Since is_prime only has two possible return values, and given its name implies a binary result, it should return a bool, not an int.  Then replace the return statements with the proper bool values.

When checking for primes, you only need to go up to the square root of the number to check.  This value can be computed once then used in the loop condition, or you can check for i * i <= num, although this has the potential to overflow with sufficiently large num.

The check for 0 or 1 can be simplified to if (num < 2).

Before the loop, you can check num to see if it is divisible by 2 and return an appropriate value.  Then you loop can start at 3 and increment by 2 (so you only need to check the odd numbers).

You should declare your variables as close to the place you first use them as possible, so your loop could be

for (unsigned long n = 3; ...

(or for (auto n = 3UL;).

When getting input, rather than while (1) with repeated conditions in the loop, you can say while (!cin.fail()) and not check for that within the loop.


Your second function is faster for me when simplifying it like this:

@jit(nopython=True)
def move_to_back_c(a, value):
    mask = a == value
    return np.append(a[~mask], a[mask])

In addition, Python's official style-guide, PEP8, recommends not surrounding a = with spaces if it is used for keyword arguments, like your nopython=True.

Since numba apparently recently gained generator support, this might also be worth checking out:

@jit(nopython=True)
def _move_to_back_d(a, value):
    count = 0
    for x in a:
        if x != value:
            yield x
        else:
            count += 1
    for _ in range(count):
        yield value

@jit(nopython=True)
def move_to_back_d(a, value):
    return list(_move_to_back_d(a, value))

The timings I get on my machine for the given testcase are:

move_to_back_a    1.63 µs ± 14.5 ns
move_to_back_b    2.33 µs ± 21 ns
move_to_back_c    1.92 µs ± 17.5 ns
move_to_back_d    1.66 µs ± 9.69 ns

What is in the end as least as important is the scaling behavior, though. Here are some timings using larger arrays:

np.random.seed(42)
x = [(np.random.randint(0, 100, n), 42) for n in np.logspace(1, 7, dtype=int)]

While slightly slower for small arrays, for larger the mask approach is consistently faster.


JavaScript function to create HTML select option elements

Just a warning: in its current implementation your code works only if countOptionsStart is less than or equal to countOptionsEnd!
So depending on your actual needs you should check this case to exit without generating options, or adapt code to work also in this case.

In the other hand, I suggest you some improvements about process of filling value with zeroes. It dramatically reduces code size, and probably works faster:

// Trying it out.
var selects = document.querySelectorAll('.drop-down');
selects = Array.prototype.slice.call(selects);

createOptions(selects[0], -9, 9, 8);

for (var i = 1; i < selects.length; i++) {
  createOptions( selects[i],
                 i * (-1 * Math.pow(10, i)),
                 i * Math.pow(10, i));
}

function createOptions( selectElement,
                        countOptionsStart,
                        countOptionsEnd,
                        preSelected ) {
  preSelected = preSelected || 0;
  demand = Math.max(
    countOptionsStart.toString().length,
    countOptionsEnd.toString().length);
  for (var i = countOptionsStart; i <= countOptionsEnd; i++) {
    var option = document.createElement('option'),
        strI = Math.abs(i) + '',
        sign = i < 0 ? '-' : '',
        fill = i < 0 ? demand -1 : demand;
    option.setAttribute('value', i);
    if (i === preSelected) option.setAttribute('selected', 'selected');
    option.innerHTML = sign + '0'.repeat(fill - strI.length) + strI;
    selectElement.appendChild(option);
  }
}
<select class="drop-down"></select>
<select class="drop-down"></select>
<select class="drop-down"></select>
<select class="drop-down"></select>


Top users under age 30, sorted by age, with rank

A few things, some nitpicks, some UX, some probably-bugs. What Lyle's Mug has already stated is also part of my answer, but first things first:

UX

This query is quite unwieldy to use, because all the things you might want to play with are hardcoded.
SEDE allows using parameters, with a rather simple syntax:

##name:type[?if optional, default value]##

replacing all your magic numbers gets us to:

SELECT TOP ##x:int?150##
 -- ...
WHERE User.Age IS NOT NULL AND Users.Reputation > ##minrep:int?150## AND User.Age <= ##age:int?30##

Nitpicks:

Note that this already stretches out that single-line WHERE quite much. I really like queries to state WHERE conditions on separate lines, because that makes it easier to process them.

Additionally I strongly recommend a lightly different comma-placement when listing columns, namely the comma before the declaration.
This has the advantage of allowing removals without running into syntax errors each time.

Probably-Bugs:

The ordering you Limit By is ... skewed? strange? ... well you select the youngest users and limit according to age, when the purpose of such a query is most probably reputation based stats.
Off-By-One: WHERE Rep > 150 excludes users with 150 rep!
Then again it seems that the where clause about rep is moot anyways...
If you remove it, there's a way to cut away large parts of "inactive" userbase depending on reputation. Usually when querying that table, I explicitly exclude users with 1 and 101 rep. These two values are a strong indicator for non-activity.

My final version:

SELECT TOP ##x:int?150##
  ROW_NUMBER() OVER (ORDER BY Users.Reputation DESC) AS Rank
  , Users.Id as [User Link]
  , Users.Age
  , Users.Reputation as Rep
FROM Users
WHERE Users.Age <= ##age:int?30##
ORDER BY Rank ASC;

(also available on SEDE)


Given set of cubes can we get a given word?

Verify complexity to be O(n!), where n is the number of alphabets in the word.

Indeed.
    private CubeFind() {}

You don't need this to get a default constructor.

Premature optimization: read that they were bad practices. they look good in my code, should i keep them ?
If not checked now, then NPE would result after hashMap is computed. on line 46

if (cubeMatrix == null) { throw new NullPointerException("The input cube matrix should not be null");

if (word == null {throw new NullPointerException("The input word should not be null"); }

Please don't do that! You're not gaining anything, the first reason being that it's going to fail very quickly if you really get null or word. The second reason is that there's no reason to get null here, why would that happen? You're simply calling this function from main, it cannot be null. When not for useless optimizations, this practice is called defensive programming and is only useful in a few specific scenarios.
 if (cubeMatrix.length != word.length()) return false;

This one can also be seen as a way to eliminate cases you don't want to reason about later on. That is, you know after this line that you will have the correct number of cubes, and it simplifies the reasoning and the code. You should keep it.
if (cubeNumber == cubeMatrix.length) {

This one wasn't obvious at first, and could deserve a comment, eg. "If we chose a letter for all cubes, check that no letter is left", maybe.
charFreq.put(cubeMatrix[cubeNumber][i], frequency - 1);
if (findWordExists(cubeMatrix, charFreq, cubeNumber + 1)) {
    return true;
}
charFreq.put(cubeMatrix[cubeNumber][i], frequency);

Nice trick. Another way to do it is to give a copy of cubeMatrix. You would then avoid the second put, but it could be very costly here due to the number of copies you would have to do: don't do it.
I would define premature optimization as "a change made for performance reasons that brings no benefit or degrades readability, and has not been proved to actually improve performance".
Last, your tests are okay for this usage, but consider using an unit test library like JUnit to manage tests, this will help you later on.


Find all numbers that are factors of one array and factor into the second array, then print their count

Redundant calculations
You calculate mult1 * mult2 three times. Instead, do this once, assign it to a variable, and use that.

Since you want to never want to calculate when a value is 0, you can set the start of range to 1.
range(1, 101) # 1 -> 100, since (inclusive, exclusive)

Now you can remove that (product != 0) check.
Type hints
At first, it looks like the function accepts two integers. In reality, it accepts two tuples of integers. Consider doing the following:
from typing import Tuple

def get_total_x(input_factors: Tuple[int], test_numbers: Tuple[int]) -> int:

This makes it clear that you want tuples of integers as parameters, instead of a single integer.
Using sets
You use a set, but you don't actually use the set. You're trying to add values to the set that aren't already there, or that you can add to the set. Instead of having that list comprehension, simply cast fact into a set. Does the exact same thing.
fact = set(fact)

Magic numbers
What is the significance of 100? I see in your question you explain, but not in the code. I would assign this to a variable to make it more clear.


Starting with asynchronous JS and promises

There is a problem regarding error handling: in callDB() you catch all exceptions and log them in the console without passing them on to the caller. Either you should rethrow the exception (or a modified version that is more helpful for the caller) or not catch it at all. Since the MongoClient.connect() can also fail, I would move it into the try/catch as well:
async function getDataFromMongoDB() {  // renamed so you don't need the comment
    try{
        const connection = await MongoClient.connect( uri, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        });
        return await connection
            .db("todos")
            .collection("items")
            .find({})
            .toArray();
    } catch(e) {
        console.log(e);
        throw e; // or throw something else
    }
}

This would be even more concise if you would extract the creation of the connection into its own function. However, I think you would like to write the whole function in one expression after the return, you would have to write it like this:
return await (await getConnection()).db("todos")...

The first await is required to keep error handling in this function.
The request handler can also make use of async/await:
app.get("/todos", cors(), async (req, res)=> {
    try {
        const response = await callDB();
        res.json(response);
    }
    catch (e) {
        console.log(e);
    }
});


There are some things to consider:

You already have using std::cout, however you use printf

for (int i = 0; i < Width * SquareSize + 2; i++) {
    std::cout << "*";
}

Edit: See that std::cout takes a std::string, so you should include that header.
C++ mainly works with std::string rather than plain char arrays. Now if you look at std::string there is this constructor string (size_t n, char c) So what you can do now is replace the loop by a constructor:

std::cout << std::string(Width * SquareSize + 2, "*");

You are passing the result of a boolean comparison as a boolean:

for (int i = 0; i < SquareSize; i++) {
    (j % 2 == 0 ? printSmallSquares(SquareSize, Width, true) : printSmallSquares(SquareSize, Width, false));
}

Just pass the comparison directly:

for (int i = 0; i < SquareSize; i++) {
    printSmallSquares(SquareSize, Width, j % 2 == 0);
}

Obviously you should use a appropriate class for your task:

class DrawCheckedGrid {

    DrawCheckedGrid(const int heigth, const int width const int size)
        : Height(height)
        , Width(width)
        , SquareSize(size)
    {}
private:
    int Height;
    int Width;
    int SquareSize;
}

Now that you have a class, you can preallocate all you need

std::string stars = std::string(SquareSize, "*");
std::string spaces = std::string(SquareSize, " ");
std::string separator = std::string(Width * SquareSize + 2, "#") + "\n";

Also you can simply create some helper methods that draw the grid rather than plumbing everything into main():

void drawLines(bool starsFirst) const {
    for (int line = 0; line < Width; ++line) {
        drawLine(starsFirst);
    }
    std::cout << separator;
}

void drawLine(bool starsFirst) const {
    const int offset = starsFirst ? 0 : 1;
    for (int square= offset; square < Width + offset; ++square) {
         std::cout << (square % 2 == 0 ? stars : spaces);
    }
    std::cout << "\n";
}

void drawGrid() const {
    std::cout << separator;
    for (int i = 0; i < Height; ++i) {
        drawLines(i%2 == 0);
    }
}

See that I have created multiple small helpers that do one thing at at a time, rather than one big function.

class DrawCheckedGrid {
    DrawCheckedGrid(const int heigth, const int width const int size)
        : Height(height)
        , Width(width)
        , SquareSize(size)
    {
        stars = std::string(SquareSize, "*");
        spaces = std::string(SquareSize, " ");
        separator = std::string(Width * SquareSize + 2, "#") + "\n";
    }

    void drawGrid() const {
        std::cout << separator;
        for (int i = 0; i < Height; ++i) {
            drawLines(i%2 == 0);
        }
    }
private:

    void drawLines(bool starsFirst) const {
        for (int line = 0; line < Width; ++line) {
            drawLine(starsFirst);
        }
        std::cout << separator;
    }

    void drawLine(bool starsFirst) const {
        const int offset = starsFirst ? 0 : 1;
        for (int square= offset; square < Width + offset; ++square) {
             std::cout << (square % 2 == 0 ? stars : spaces);
        }
        std::cout << "\n";
    }
    int Height;
    int Width;
    int SquareSize;
    std::string stars;
    std::string spaces;
    std::string separator;
}

Here you can also see that all internal functions are private, so we do not leak our internals. You can also add functions that allow you to change the parameters of the grid and pass something to drawGrid().


def get_LOS(headway = None, frequency = None, veh_per_hr = None):

You have no docstring. That would helpful in explaining what the parameters are doing.

  if frequency != None and headway = veh_per_hr == None:

When checking wheter something is none it is best to use  is None or is not None

    headway = 1 / frequency

The problem is that if someone passes frequency along with one of the other parameters, this function will go merrily onwards and probably not even produce an error. I recommend having a get_LOS_from_frequency function which takes the frequency and then calls this function.

  if headway!= None or veh_per_hr != None:
    if headway 10 < or veh_per_hr > 6:

I'm pretty sure that won't compile

       return 'A'
    elif 10 <= headway < 15 or 5 < veh_per_hr <= 6:
      return 'B'
    elif 15 <= headway < 20 or 3 < veh_per_hr <= 5:
      return 'C'
    elif 20 <= headway < 31 or 2 < veh_per_hr <= 3:
      return 'D'
    elif 31 <= headway < 60 or 1 <= veh_per_hr < 2:
      return 'E'
    elif headway >= 60 or veh_per_hr < 1:
      return 'F'

I'd store these values in a list which makes it easy to pull them from configuration at a later date if neccesary.

    else:
      return 'Error'

Don't report error by returning strings. Throw an exception, or at least assert False.

How I'd do this:

import bisect
def get_los_from_frequency(frequency):
    return get_los(1 / frequency)

HEADWAY_LIMITS = [10, 15, 20, 31, 60]
VEH_PER_HR_LIMITS = [1,2,3,5,6]
GRADES = "ABCDEF"

def get_los(headway = None, veh_per_hr = None):
    if headway is None:
        headway_score = len(GRADES)
    else:
        headway_score = bisect.bisect_left(HEADWAY_LIMITS, headway)

    if veh_pr_hr is None:
        veh_pr_hr_score = len(GRADES)
    else:
        veh_pr_hr_score = len(GRADES) - bisect.bisect_left(VEH_PR_HR_LIMITS, veh_pr_hr)

    return GRADES[min(headway_score, veh_pr_hr_score)]


trying out possible combinations of varying formula with recursion

Can be done without recursion
You can do the same thing without recursion, by simply adding one to the rightmost dimension, and then "carrying over" when that number exceeds the one to its left.
Here is a sample implementation:
void loop()
{
    int i = 0;

    for (i = 0; i < dim; i++) {
        number[i] = 1;
    }
    do {
        do_sth();
        for (i = dim - 1; i > 0; i--) {
            if (number[i] < number[i-1]) {
                number[i]++;
                break;
            }
            number[i] = 1;
        }
        if (i == 0) {
            if (number[0] < max) {
                number[i]++;
            } else {
                return;
            }
        }
    } while (1);
}


Your first example looks much nicer, so I'll focus on that.

First, let's remove the tail recursion in the most obvious way possible:

public static boolean isEven(int[] arr, int index, int leftSum, int rightSum) {
    while (true) {
        int i = index-1;
        int j = index+1;

        while(i > -1) {
            leftSum += arr[i--];
        }

        while(j < arr.length) {
            rightSum += arr[j++];
        }

        if (leftSum == rightSum) {
            return true;
        }
        if (index == arr.length-1) {
            return false
        }

        index += 1;
        leftSum = 0;
        rightSum = 0;
    }
}

Now let's clean it up:

public static boolean isEven(int[] arr) {
    for (int index = 0; index < arr.length; index++) {
        int leftSum = 0;
        for (int i = index -  1; i > -1; i--) {
            leftSum += arr[i];
        }

        int rightSum = 0;
        for (int i = index+1; i < arr.length; i++) {
            rightSum += arr[i];
        }

        if (leftSum == rightSum) {
            return true;
        }
    }

    return false;
}

We can combine the sum variables:

public static boolean isEven(int[] arr) {
    for (int index = 0; index < arr.length; index++) {
        int difference = 0;

        for (int i = index -  1; i > -1; i--) {
            difference += arr[i];
        }
        for (int i = index+1; i < arr.length; i++) {
            difference -= arr[i];
        }

        if (difference == 0) {
            return true;
        }
    }

    return false;
}

Now consider that we don't need to recalculate difference each time. If one iteration we have

|-A-| * |--B--|
1 2 3 4 5 6 7 8

The next we have

|-A-|++ --|-B--|
1 2 3 4 5 6 7 8

Namely, we add 4 to A and subtract 5 from B, which means we add 4 and 5 to the difference. We should also check for empty arrays.

public static boolean isEven(int[] arr) {
    if (arr.length == 0) {
        // Alternatively, return false since there
        // is no element that satisfies the condition.
        throw new IllegalArgumentException();
    }

    int difference = arr[0] - Arrays.stream(arr).sum();
    if (difference == 0) {
        return true;
    }

    for (int i = 1; i < arr.length; i++) {
        difference += arr[i-1];
        difference += arr[i];

        if (difference == 0) {
            return true;
        }
    }

    return false;
}


More elegant way to round decimals in Python?

I was actually unaware of the decimal module -- I've +1 your question just for that.

Taking a quick look at the docs, Decimal is specifically designed to avoid artifacts of binary floats and work like "people" math. Because of that I would be suspicious of the conversion to float, no matter how brief. Can you use the quantize() function instead of round()? The quantize method "rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places" and sounds well suited to your application.


Using set for unordered, unique list of elements

My questions are:
There are any potentially problems that could arise from using this construct?

Its not valid.
The code will not work as expected as the std::set requires the comparator type to generate a strict weak ordering between elements.

What other alternatives I have to achieve the same thing in a more readable form? I do not plan to write my own unordered set just for this scenario and can't really use any external libraries. Only standard library available in C++03.

You can use std::set as an unordered container as is. If you have an unordered container it does not matter to you what order the elements are in. If they just happen to be ordered does that matter?
The reason for using std::unordred_set is that it provides faster access to the elements. You give up an ordered property to get better performance.
Container:           Insert     find
std::set             O(ln(n))  O(ln(n))
std::unordered_Set   O(1)      O(1)