Your code's runtime is \$O(n^3)\$, this is almost definitely not the performance that you want. The simplest way to solve your problem is by, you guessed it, a graph. Take the following directed graph of your selected flights:

Using a graph gives the ability to check only the actual routes. And so it wouldn't check if it is possible to fly from say; FRA -> CPH, and then FRA -> MAD, as the original code does. This benefit is good, however there is a larger benefit when there are say two, or more, flights in each edge. When that is the case, the original would go through roughly \$432\$ different arrangement of flights. Where a graph would only check the four routes to AMS, which would include travelling all \$6\$ edges. The graph could then return the \$1\$, or \$4\$, routes to AMS, and then go on to return all \$8\$, or \$18\$, permutations of those flights. And so the graph would check roughly \$28\$ permutations of these flights, as opposed to \$432\$.

Another example of this is if you wanted to obtain all the routes from from FRA -> MAD. And so you'd return the flights from FRA -> MAD and FRA -> CPH -> MAD. The first algorithm would still visit all \$6\$ airports, as you want to check if there are any three flights that can get to the desired destination. This time the code would return the above \$2\$ routes, which would lead to the graph quickly returning all \$6\$ possible flight combinations. Leading to roughly \$12\$ permutations.

Note: My maths is vague, and rough, it's not scientific, and depending on where it's measure, I'd not be suppressed if you obtained more permutations. It is merely to show the difference in magnitude between the two approaches.

There are two algorithms that I describe above, the first, can be implemented by:

Make an 'array' of the starting airport.
while 'the array' is not empty repeat the following commands:

Pop a route from 'the array'.
Get the last airports name from the route
If the name is the destination yield it.
If the route's length is equal to the depth we limit to, continue.
Extend 'the array' with the last airports possible flights to.

And so could be:

def _routes(self, destination, depth=1):
    depth += 1
    l = [[self.name]]
    while l:
        route = l.pop()
        name = route[-1]
        if name == destination:
            yield route
        if len(route) == depth:
            continue
        l.extend([
            (route + [a])
            for a in self._graph[name]._flights.keys()
        ])

The second algorithm, is much simpler. You want to produce the product of the flights between each airport, for each route.
Which can be:

def routes(self, destination, depth=1):
    root = self._graph
    return chain.from_iterable(
        product(*(
            root[dep].flights(arr)
            for dep, arr in pairwise(route)
        ))
        for route in self._routes(destination, depth)
    )

And so in total I'd use the below code. I added some un-used functions; remove_flight, and flights_to so that if you did want to use it rather than a list, you have a simpler interface.

from collections import defaultdict, namedtuple
from itertools import chain, product, tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

_DEFAULT = object()
class FlightGraph:
    Flight = namedtuple('Flight', 'dep arr dep_dt arr_dt price')
    class Airport:
        __slots__ = ['name', '_graph', '_flights']
        def __init__(self, graph, name):
            self._graph = graph
            self.name = name
            self._flights = defaultdict(set)

        def __getitem__(self, airport):
            if airport not in self._flights:
                raise KeyError('Airport has no flights to {!r}'.format(airport))
            return self._graph[airport]

        def __iter__(self):
            return iter(self._flights.items())

        def add_flight(self, airport, flight):
            # ensure airport exists
            self._graph[airport]
            self._flights[airport].add(flight)

        def remove_flight(self, airport, flight):
            self._flights[airport].remove(flight)

        def flights(self, airport, default=_DEFAULT):
            if airport in self._flights:
                return frozenset(self._flights[airport])
            if default is _DEFAULT:
                raise KeyError('Airport has no flights to {!r}'.format(airport))
            else:
                return default

        def flights_to(self):
            return tuple(self._flights.keys())

        def _routes(self, destination, depth=1):
            depth += 1
            l = [[self.name]]
            while l:
                route = l.pop()
                name = route[-1]
                if name == destination:
                    yield route
                if len(route) == depth:
                    continue
                l.extend([
                    (route + [a])
                    for a in self._graph[name]._flights.keys()
                ])

        def routes(self, destination, depth=1):
            root = self._graph
            return chain.from_iterable(
                product(*(
                    root[dep].flights(arr)
                    for dep, arr in pairwise(route)
                ))
                for route in self._routes(destination, depth)
            )

    def __init__(self, flights=[]):
        self._airports = {}
        for flight in flights:
            flight = self.Flight(**flight)
            self[flight.dep].add_flight(flight.arr, flight)

    def __getitem__(self, key):
        try:
            return self._airports[key]
        except KeyError:
            ret = self._airports[key] = self.Airport(self, key)
            return ret

flights = FlightGraph([
    {'dep': 'FRA', 'arr': 'AMS', 'dep_dt': '2017-05-01 12:00:00', 'arr_dt': '2017-05-01 13:15:00', 'price': 100},
    {'dep': 'FRA', 'arr': 'AMS', 'dep_dt': '2017-05-01 12:00:00', 'arr_dt': '2017-05-01 13:15:00', 'price': 150},
    {'dep': 'FRA', 'arr': 'CPH', 'dep_dt': '2017-05-01 10:00:00', 'arr_dt': '2017-05-01 12:00:00', 'price': 80},
    {'dep': 'FRA', 'arr': 'MAD', 'dep_dt': '2017-05-01 09:00:00', 'arr_dt': '2017-05-01 10:50:00', 'price': 30},
    {'dep': 'CPH', 'arr': 'AMS', 'dep_dt': '2017-05-01 15:00:00', 'arr_dt': '2017-05-01 16:30:00', 'price': 60},
    {'dep': 'CPH', 'arr': 'MAD', 'dep_dt': '2017-05-01 14:15:00', 'arr_dt': '2017-05-01 17:10:00', 'price': 70},
    {'dep': 'MAD', 'arr': 'AMS', 'dep_dt': '2017-05-01 19:00:00', 'arr_dt': '2017-05-01 21:40:00', 'price': 20},
])

for route in flights['FRA'].routes('AMS', 3):
    # TODO: filter if the arr_dt and dep_dt don't allow the route to be possible
    print(', '.join('{0.dep} -> {0.arr} ({0.price})'.format(f) for f in route))


I've been looking at this code for a good long while now, and I must admit I don't have much in terms of a review. It's all nicely done!

What few quibbles I have are minor:

output and output2 aren't really the best names, are they?
Also, basinDepths appears to actually hold basin sizes. The code already deals with "actual" depths, so the name's needlessly confusing.
Speaking of, "depth" is perhaps a slightly confusing term in this case. It's actually altitudes, and the rain flows from high to low. By calling it "depths", one would expect it to be the other way around: Water flowing to greater depth values.
The one-liners aren't all that useful. $ is fine (though maybe using document.querySelector would be nicer, as one might expect $ to behave jQuery-ish), but the rest are really only called once, as far as I can tell. So I would argue that this:

const depths = input.value
  .split('\n')
  .map(line => line.trim().split(' ').map(Number));

would be as clear as using extracted methods. Yes, it's nice to name and encapsulate the operations being performed, and the original line really reads quite well. Still... eh, just seems excessive when there's no re-use of said operations.
Conversely, if you want to go all-in on English-like legibility, a lines function should perhaps take the place of split('\n')?
Your use of whitespace is... eclectic? I'm used to reproaching people for not using enough whitespace, but here it's the opposite. Maybe you're over-correcting after too much code golf? :)
I just find it curious that a line like this:

function markPath( path , basin ){

has tons of space in the argument list, but nothing between ){ (esp. since you do use a space for x => { y } declarations... except in that place where you don't).
Or that your else-if looks like this:

}else if (...){

when most would probably write:

} else if(...) {

instead. Indeed you do write if(...) { in  other places.

Again, it's not a disaster, but it is inconsistent and odd.


Your second code, while might be slightly more efficient than the first due to the avoidance of the second try ... catch inside the first, has two bugs:

First, if str contains a value greater than \$2^{63}-1\$ or less than \$-2^{63}\$, while it is an integer value (d % 1 == 0 will be true), it cannot be expressed as a long, so d.longValue() will discard the upper bits.

Second, if str contains a value which can be parsed as a Long, but has a magnitude greater than \$2^{52}\$, parsing it as a Double will discard some of the low-order bits.

jshell> Double d = Double.parseDouble("10000000000000123");
d ==> 1.0000000000000124E16

jshell> d.longValue()
$2 ==> 10000000000000124

jshell> Long.parseLong("10000000000000123");
$3 ==> 10000000000000123

The statements return Long.parseLong(str) and return Double.parseDouble(str) may be doing more work than necessary.  These methods return a long and a double, respectively, which then need to be auto-boxed into Long and Double.  You should instead use Long.valueOf(str) and Double.valueOf(str) which return already boxed values.

I would write this code like:

private static Object tryParse(String str) {
    try {
        return Long.valueOf(str);
    } catch (NumberFormatException ex) { /* no-op */ }

    try {
        return Double.valueOf(str);
    } catch (NumberFormatException ex) { /* no-op */ }

    return str;
}

... which avoids the nested try-catch blocks, so can easily be extended to several other types, possibly even looping over a collection of parsers:

private static Object tryParse(String str) {
    for (Parser parser : parsers) {
        try {
            return parser.valueOf(str);
        } catch (NumberFormatException ex) {
            /* no-op */
        }
    }

    return str;
}

or even

private static Object tryParse(String str) {
    for (Parser parser : parsers) {
        Optional<Object> value = parser.valueOf(str);
        if (!value.empty()) {
            return value.get();
        }
    }

    return str;
}

Implementation of Parser, and its instances, left as exercise to student.


Optimizing Python code for Project Euler #5 (LCM of all numbers from 1 to 20)

Your intent is to terminate the loop when all entries in table become 1. This

while sum(table) > len(table):

is a rather obscure way of expressing that intent. I suggest instead

while max(table) > 1:

or the more explicit and short-circuiting

while any(x > 1 for x in table):


There doesn't seem much wrong with your code, but it is difficult to judge a small piece of code in isolation.

One thing I must urge you to do is to check the $_POST parameters before you put them into the database. Do not rely solely on the checks you do before the form is submitted. For instance, make sure you've actually got some content, and that the year is really four digits long. This way you can stop rougue data getting into your database.

In some cases you will have to try to prevent robots from posting to your database. This is especially true for registration forms.

See: http://www.ultramegatech.com/2009/08/5-basic-php-security-tips

Or: http://www.dreamhost.com/dreamscape/2013/05/22/php-security-user-validation-and-sanitization-for-the-beginner


I've been waiting for this question to be reopened because the formatting issues here are quite extraordinary! I think I'll keep this post to a clean code/code styling post exclusively, that way others can touch on purpose and implementations.

I think what's required here is a bullet point list, which I know is boring, but it's the easiest way to go line by line! Let's begin :)

Eeek! What in the world is calc_p()!? I immediately know nothing about your code. That's the opposite of what we want. Names should be meaningful and thorough. It looks like you're calculating a price, so a better name might be calculateBookPrice(). Functions are usually expected to be camelCase.
$arg1: bad name. $arg2: bad name. $arg3: bad name. What are these variables? We need description in these names!
I had no idea this function needed variables for func_get_args(). You limit the arguments to three, so I'd say add three parameters to the function. That or have something such as ... $someArguments for a parameter. (Obviously with a name that fits your code)
What is $bp? I immediately have converted this name to "blood pressure". However, that doesn't make sense. Now your reader is confused. See how important useful variable names are?
'ebook', 5, .08: what do all these have in common? I don't know why you chose them. If you need to, create (constants, if you have a class) variables and apply these values to a named variable.
I don't see a default to your switch. I need a default to function! It's best practice to use one anyways.
What in the world is $bp = ($bp + ($bp*$tax));? Hows about $bp *= ++$tax;? It's shorter and takes advantage PHP's combined operators and pre-increment operator. However, even this isn't too pretty. Perhaps refactor the code before it...
//Calclate shipping - this is a useless comment. Comment's should describe why.
It'd be nice to get some place in between statements: if(, '$'.$bp.
The condition for $arg3 == 'California' is empty, why not negate the comparison? ($arg3 != 'California')
$bp = $bp + 1 --> $bp++
Shouldn't you have a switch for the states you check against?
What is $norm? Are you referring to a person named Norman? Spell out a useful variable name!
You may want to look into money_format or formatCurrency... That whole block is hideous!
Some variables are like $final_price and some are like $totalprice! It's vital that you stay consistent!


Dynamically convert property to different data type

I think you kind of reinventing the wheel a bit here. You could use the ValidationAttribute.

Since C# doesn't allow generics in Attribute classes you either have to create an attribute per type or use an enum to specific what type.  I personally prefer an attribute per type.

An Example of use the ValidationAttrubte for DecimalParser

public class DecimalParserAttribute : ValidationAttribute
{
    public DecimalParserAttribute() : base("Cannot convert to decimal")
    {
    }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }

        var stringValue = Convert.ToString(value);

        decimal decimalResult;
        return decimal.TryParse(stringValue, out decimalResult);
    }
}

Now to perform the validation you need to use the Validator Class

var p = new Product() {NoOfItems = "1", GRodes = "4w", Weight = "5", WRodes = "2q3"};
var validationResults = new Collection<ValidationResult>();
if (!Validator.TryValidateObject(p, new ValidationContext(p), validationResults, true))
{
    // If we are here there was validation errors
    var x = string.Join(Environment.NewLine,
        validationResults.SelectMany(r => r.MemberNames.Select(n => n + " " + r.ErrorMessage)));
}

This to me fits more in with what you are doing, validation, with the benefit of using the built in .Net Framework classes.


Calculating sum of certain values in a list

If you add a toString() method inside the client class you could, replace this code:

//in loop so use stringbuilder
            StringBuilder sb = new StringBuilder();
            sb.append(cl.getId());
            sb.append(",");
            sb.append(cl.getFirstName());
            sb.append(" ");
            sb.append(cl.getLastName());
            sb.append(",");
            row = sb.toString();

for just:

row = sb.toString();

Furthermore, you can append the second with the third if condition inside the second loop, this:

if (cl.getId().equals(vl.getClientId())) {
                    if (!done) {
                        row = sb.toString();
                        cash = 0;
                        month = vl.getMonth();
                        done = true;
                    }
                }

can became this:

  if (!done && cl.getId().equals(vl.getClientId()))
    {
                            row = sb.toString();
                            cash = 0;
                            month = vl.getMonth();
                            done = true;
    }

Another thing, in the above code the row = sb.toString instruction should it be remove?
Since you are calculated the row right below the first loop:

row = sb.toString();
for (Valuations vl : valList) {


Generating matrix/image kernel from List

Style

put spaces after comas to improve readability;
remove unnecessary parenthesis;
put spaces around operators;
put two spaces before and one space after the comment sign (#);
remove the 0 in range(0, <whatever>) as it is the default value;
except Exception as e is bad here as you are only actually expecting IndexError; plus the as e part is unnecessary as you don't use e (well, you do in the second snippet, but you could just raise with nothing more, even though the whole except: raise is useless as it adds nothing over the default behaviour);
range(len(<something>)) is often a red flag as it is better to iterate over elements than indices; but here, I don't think you have a choice anyway;
divmod can help you get rid of math.ceil.

In fact, only changing your first snippet to using divmod yield a 5% speedup on my machine:

def get_kernel(pixels, width):
    kernels = []
    pixels = [x for row in pixels for x in row]  # 2D list to 1D
    for i in range(len(pixels)):
        y, x = divmod(i, width)
        try:
            kernel = [
                    pixels[(y-1) * width + x - 1], pixels[(y-1) * width + x], pixels[(y-1) * width + x + 1],
                    pixels[y * width + x - 1], pixels[y * width + x], pixels[y * width + x + 1],
                    pixels[(y+1) * width + x - 1], pixels[(y+1) * width + x], pixels[(y+1) * width + x + 1],
            ]
        except IndexError:
            kernel = [0]
        kernels.append(kernel)  # Add kernel to kernels list
    return kernels

Algorithm

There is one thing that bothers you about this snippet: it is not generic enough to allow for kernels of various radius. There is an other thing that bothers me, it is how it warps around the edges of the image but the bottom. The fact that some_list[-x] will return the \$x^{th}\$ element of some_list starting from the end combined to the flattening of the list will make it so that when at the top row or when reaching a pixel at the right or the left of the image, the coordinates involved will always be a valid index in pixels. But for the last row, (y+1) * width + x will exceed the number of elements in pixels and raise IndexError. This inconsistent behaviour bothers me.

Looking at how you handle your kernels in your other question, we can see that kernels that are not full-sized are discarded. Great, let's generate kernels of lower size for the edges of the image. The key idea here is knowing that slicing a list will always return a list:

>>> a = list(range(20))
>>> a[4:8]
[4, 5, 6, 7]
>>> a[18:50]
[18, 19]
>>> a[-8:5]
[]

Also, slicing a list of lists will not copy inner list but only references to them, so it is rather fast:

def get_kernels(pixels, width, radius=1):
    kernels = []
    for y in range(len(pixels)):
        y_min = y - radius
        y_max = y + radius + 1
        for x in range(width):
            x_min = x - radius
            x_max = x + radius + 1
            kernels.append([
                    pixel for row in pixels[y_min:y_max]
                    for pixel in row[x_min:x_max]])
    return kernels

This version is 5 to 10% slower than your first one but has two advantages:

It is more readable;
It is more generic.

I chose to parametrize it with the kernel radius rather than its diameter to avoid the parity check and simplify the computations.

I also chose to keep the width parameter since you seemed to already have it handy. But if you want to remove it, you can still add:

def get_kernels(pixels, radius=1):
    if not pixels:
        return []
    width = len(pixels[0])

at the beginning of the function.

Going further

Your use case of such function seems only to be able to iterate over the returned value. In such case, you would gain more performances by turning this into a generator instead of building a list element by element.

The code is nearly identical, just remove the kernels list and use the yield keyword instead of the append function. And voilà. What it does is that it will compute the kernels on demand, during the iteration; removing the need for extra storage (and handling of that storage):

def get_kernels(pixels, radius=1):
    if not pixels:
        return

    width = len(pixels[0])
    for y in range(len(pixels)):
        y_min = y - radius
        y_max = y + radius + 1
        for x in range(width):
            x_min = x - radius
            x_max = x + radius + 1
            yield [
                pixel for row in pixels[y_min:y_max]
                for pixel in row[x_min:x_max]]

Oh yes, you might have noticed that I removed the self parameter as it is unused. This might interfere with the fact that you are using this as a method on your class. But I probably should explain what is wrong with that in that other question of yours.


Very quick review.

No docstrings.
The code uses datetime.datetime.combine to make datetime.datetime objects representing the bounds, and then compares these with time_current. But it would be simpler to make datetime.time objects to represent the bounds, and then compare those with time_current.time.
Having done that, it would be simpler still if the function took a datetime.time object as its first argument, leaving it up to the caller to pass time_current.time if that's what's needed.
There's nothing about this code that is specific to alarms (it could be used for appointments, for example), so it would be easier to understand if the functionality were expressed abstractly.

Revised code:

import datetime

def time_in_range(time, start_hour, end_hour):
    """Return True if time (a datetime.time object) lies between
    start_hour and end_hour (inclusive).

    >>> time_in_range(datetime.time(hour=12), 10, 14)
    True

    The range is allowed to span midnight:

    >>> time_in_range(datetime.time(hour=0), 22, 2)
    True

    """
    start = datetime.time(hour=start_hour)
    end = datetime.time(hour=end_hour)
    if end <= start: # Range spans midnight.
        return start <= time or time <= end
    else:
        return start <= time <= end


Python implementation of multidimensional power spectral density with Welch method

For later reference here is the correct code:

from __future__ import division, print_function, absolute_import
from scipy.fftpack import fft,fftfreq
import numpy as np
from math import ceil,floor
import sys
from scipy.signal import get_window,welch,signaltools
from matplotlib import pyplot as plt
import warnings
from scipy.lib.six import string_types

def win_sig(x,nperseg,padded='False'):
    """A function just to cut a multidimensional time series into pieces of specific length (nperseg) """

    #checking whether the size of time series are smaller than the window lenght
    if nperseg>=x.shape[-1]:
        N=nperseg
        win_num=1
    elif int(nperseg/2.)==nperseg/2.:
        N=int(nperseg/2.)
    else:
        N=int(nperseg/2.)+1
    if padded:
        win_num=ceil(x.shape[-1]/float(N))
    elif nperseg<x.shape[-1]:
        win_num=int(x.shape[-1]/float(N))-1

    #index set manipulation for generating the splitted version of the signals faster
    idx_temp=np.indices((win_num,nperseg))
    idx_temp=idx_temp[0]*N+idx_temp[1]

    #padding zeros for the last window when the last window is longer than the remaining of signal
    pad_len=(win_num-1)*N+nperseg-x.shape[-1]
    if padded:
        pad_mat=np.zeros((x.shape[0],pad_len))
        x=np.concatenate((x,pad_mat),axis=-1)

    return x.reshape(-1,x.shape[-1])[:,[idx_temp]].reshape((x.shape[0],win_num,-1))

def ndim_welch(x,nperseg=256,window='hanning',scaling = 'density',detrend='constant',fs=1.0,axis=-1,padded=False):
    """Multidimensional Welch method: Calculating Power Spectral Density for time series of multiple [and one] dimension."""

    ##################################################################
    # checking whether the time series lengths are longer than window
    # length for welch method. If negative the size has been set to time series
    # length. (Taken from original scipy.signal.welch)

    if (not padded) and x.shape[-1] < nperseg:
        warnings.warn('nperseg = %d, is greater than x.shape[%d] = %d, using '
                    'nperseg = x.shape[%d]'
                    % (nperseg, axis, x.shape[axis], axis))
        nperseg = x.shape[-1]

    #########################################################
    # setting the window as is done in original scipy.signal

    if isinstance(window, string_types) or type(window) is tuple:
            win = get_window(window, nperseg)
    else:
        win = np.asarray(window)
        if len(win.shape) != 1:
            raise ValueError('window must be 1-D')
        if win.shape[0] > x.shape[-1]:
            raise ValueError('window is longer than x.')
        nperseg = win.shape[0]

    ######################################################
    #setting the scale as is done in original scipy.signal

    if scaling == 'density':
        scale = 1.0 / (fs * (win*win).sum())
    elif scaling == 'spectrum':
        scale = 1.0 / win.sum()**2
    else:
        raise ValueError('Unknown scaling: %r' % scaling)

    #########################################################
    #  windowing the signal
    # (turning the multidimensional time series into multiple t
    # time series of windowed sections using the function 'win_seg')

    windowed_sig=win_sig(x,nperseg,padded)

    ##################################
    # detrending step

    if not detrend:
        detrend_func = lambda seg: seg
    elif not hasattr(detrend, '__call__'):
        detrend_func = lambda seg: signaltools.detrend(seg, type=detrend)
    elif axis != -1:
        # Wrap this function so that it receives a shape that it could
        # reasonably expect to receive.
        def detrend_func(seg):
            seg = np.rollaxis(seg, -1, axis)
            seg = detrend(seg)
            return np.rollaxis(seg, axis, len(seg.shape))
    else:
        detrend_func = detrend

    windowed_sig=detrend_func(windowed_sig)

    #######################################
    # spectral density estimation

    # multiplying by window
    windowed_sig=np.multiply(win,windowed_sig)

    # calculating the fourier transform
    windowed_seg_fft=fft(windowed_sig)
    windowed_fft=windowed_seg_fft.T

    # returning the spectral density with calcualting outerproducts to get the
    # crossspectrum matrix and also returning the frequency set

    spec_density=np.mean(np.einsum('...i,...j->...ij',windowed_fft,windowed_fft.conjugate())*scale,axis=1)
    spec_freq=fftfreq(nperseg)
    return spec_freq,np.squeeze(spec_density).real


Combining text in an array in JavaScript

perhaps you can try apply(), then you can pass in the image paths as an array:

preLoadIamges.apply(this, absoluteFileNames)

then you can build you array in a the way you like, perhaps looking at this unobtrusive implementation of Array.map:

var directory = "/media/img/elements/frontpage/"
var fileNames = ["1.jpg","...","9.jpg"];
var absoluteFileNames = fileNames.map(function (value) {
    return directory + value;
});


onChange vs onKeyPress for input in React

Don't complicate your code; the first solution is just fine but needs some tweaking:
handleChange(event) {
    this.setState({value: event.target.value});
}

handleEnter(event) {
    if (event.key === 'Enter') {
        this.props.theFunction(this.state.value);
    }
}

Or, you can use what they call a guard clause and make it short and readable:
handleEnter(event) {
    if (event.key !== 'Enter') return;
    this.props.theFunction(this.state.value);
}

And if you're using react hooks:
const handleChange = (e) => {
    setInputValue(e.target.value);
}

const handleEnter = (e) => {
    if (e.key === "Enter") {
        if (value !== "") {
            console.log("Hello", name);
        }
        else {
            alert("can't pass empty string");
        }
        setInputValue("");
    }
}


Your algorithm is selection sort.

Selection sort has a time complexity of \$O(n^2)\$. For sorting algorithms, that's pretty slow.

Consider looking up a sorting algorithm such as quicksort, which, whilst it does have a worst case performance of \$O(n^2)\$, on average, it tends to take \$O(n log n)\$.

Or, as suggested in the comments, make use of the built-in libraries. Use Arrays.sort. Use of library code, especially when part of the language that you're programming in, can save significantly on the work you need to do.

Splitting up your code into several methods can be done.

Take this section, for instance.

        for (int j = i + 1; j <= lastPos; j++)
            if (str[j].compareTo (str[minPos]) < 0)
                minPos = j;

What it does is it looks for the smallest string in the array. So you could turn this into a function, with arguments for the array and the starting position (array.length will get you the end).

The swap,

        if (minPos != i)
        {
            s = str[i];
            str[i] = str[minPos];
            str[minPos] = s;
        }

Could also be a separate method.

If you extract those two sections of code to separate functions, the main sorting function will look like this:

public static void sort (String[] str)
{
    int lastPos = str.length - 1;
    for (int i = 0; i < lastPos; i++)
    {
        swap(str, i, findSmallest(str, i));
    }
}


Consider for a moment, if you will, how we typically handle a user tapping a button.  We typically will do so with an @IBAction method.  What are the Apple suggested defaults when we hook up a button this way?

The default is to give us a method that takes an object of type AnyObject as its only parameter.  We can, of course, change the type to specify UIButton (or whatever UIControl subclass our element actually is).  We can also change the sent arguments.  We can choose between None, Sender, and Sender and Event.

I don't think it's useful to allow objects that aren't of type UIControl as the parameter.  But, I do feel like we're missing methods to accept a handler that just passes the Sender argument.  For me, this is the most common way I hook up methods (mostly because it's the default, but sometimes because I want the sender).  Meanwhile, I don't think I've ever cared about the Event argument.

But moreover, I actually think it'd also be useful if we also had the option of passing a reference to the handler itself (the EventHandlerId returned when the handler is added) so that potentially we could then remove the event conditionally and without having to keep track of the handler reference on our own.  (Although admittedly, I haven't played too terribly much with this aspect of your code, so I'm not sure how possible or manageable that might be.)

I'd change your typealias to this:

typealias EventHandlerRef = UnsafePointer<EventHandler>

and remove the private access modifier from your EventHandler class, and add version of all your methods that take an EventHandler argument.

For starters, I'd do this because even though the version you've implemented is easier, there's not a particularly good reason for this aspect of the implementation to be private.

But moreover, by making the EventHandler class private, you've tricked yourself into writing the off function in a not-so-great way.  The off function takes an EventHandler pointer, finds the event, then removes it as a target of the UI element.  And that's fine for everything you've done... except for your "oneshot" implementation... where the EventHandler object finds its own reference to pass to the control's off method so that method can use the pointer to find the object (which we already knew) and remove it.

Instead, we should have a method that accepts an EventHandler object.  The method that accepts the EventHandlerRef grabs the EventHandler that the reference points to and calls the method that accepts the EventHandler.

The reason, by the way, I prefer EventHandlerRef to EventHandlerId is two-fold.  First of all, the value it holds is hardly an id in the sense that one might think in a database sense, but most importantly, suffixes pointer typedefs with Ref is just how Apple does it throughout their own libraries.  Any other iOS developer will see EventHandlerRef and know that this is a pointer to an EventHandler thing, even if they don't know what sort of thing EventHandler is.  Meanwhile, EventHandlerId seems slightly arbitrary.

Other than these two observations, my main complaint here would be naming.  Large, descriptive variable names don't make your compiled program take up any more space on the disk, or any more RAM, or run any slower.  The only drawback to large, descriptive variable names is that it makes your code more readable.  Wait... that's not a drawback.

Moreover, this isn't Objective-C.  Something declares as private truly is private in Swift.  The underscores just make things look weird here.  So, here's my take on your code, including the name changes I'd make:

Well, I was going to post some sample code... but now I'm going to be distracted with writing a bug report because the compiler keeps crashing trying to figure out the sample I wrote.  And that means there's something wrong with it, but the compiler doesn't feel like telling me, so I can't figure it out...


Input iterator is an abstract concept
I think you are very confused.
“Input iterator” is a concept. A concept is an abstract specification, not a concrete “thing”. You can’t make an “implementation of input iterator”; that’s gibberish. You can implement something that satisfies the input iterator concept, but you can’t implement input iterator itself.
It’s kinda like saying: “I’m making an implementation of container”. The only valid response to that statement is a blank look and the question: “Okay… WHICH container? A linked list? A hash table? A double-ended queue?” You can’t just make ‘container’; it’s an abstract concept. You can implement something that is a container (that is, something that satisfies the abstract specification of “container”), but you can’t actually “implement container”… that’s gibberish.
You say you “need input_iterator for a specific constructor”… I think you mean you need AN input iterator for a specific constructor; you need a type that satisfies the input iterator concept, not specifically a type that “is” input iterator (because that’s gibberish).
If you need an input iterator, you don’t need to make one. It’s a concept. Anything that satisfies the concept will do. For example, in the standard library, std::istream_iterator is an input iterator:
#include <forward_list>
#include <iostream>
#include <iterator>
#include <list>
#include <sstream>
#include <vector>

template <typename T>
void foo(T, T)
{
    std::cout << "foo called with some type\n";
}

template <std::forward_iterator T>
void foo(T, T)
{
    std::cout << "foo called with forward iterators (or better)\n";
}

template <std::input_iterator T>
void foo(T, T)
{
    std::cout << "foo called with input iterators\n";
}

auto main() -> int
{
    auto vec = std::vector<int>{};
    auto list = std::list<int>{};
    auto slist = std::forward_list<int>{};

    auto iss = std::istringstream{};

    foo(0, 1);
    foo(vec.begin(), vec.end());
    foo(list.begin(), list.end());
    foo(slist.begin(), slist.end());
    foo(std::istream_iterator<int>{iss}, std::istream_iterator<int>{});
}

Output:
$ ./a.out
foo called with some type
foo called with forward iterators (or better)
foo called with forward iterators (or better)
foo called with forward iterators (or better)
foo called with input iterators
$

I can’t quite make sense of what you think you mean when you say you “need input_iterator for a specific constructor”, but if you mean you need to test a specific constructor with input iterators, then you can just do:
auto iss = std::istringstream{"5 4 3 2 1"};

auto v = your_vector<int>(std::istream_iterator<int>{iss}, std::istream_iterator<int>{});
// If the above constructor works as expected, v should now contain: 5, 4, 3, 2, 1

If you mean you need to implement a specific constructor with input iterators, then that’s just:
template <typename T>
class your_vector
{
    // ... [snip] ...

    template <typename T>
    constexpr your_vector(T first, T last)
    {
        while (first != last)
            this->push_back(*first++);
    }

    // ... [snip] ...
};

That’s a constructor that takes input iterators.
Of course, before C++20 it’s standard practice to name the type with something more descriptive than T if you’re using a concept, like:
template <typename T>
class your_vector
{
    // ... [snip] ...

    template <typename InputIterator>
    constexpr your_vector(InputIterator first, InputIterator last)
    {
        while (first != last)
            this->push_back(*first++);
    }

    // ... [snip] ...
};

And as of C++20, you can now actually check that the type satisfies the input iterator concept, because the standard library has a std::input_iterator concept defined already:
template <typename T>
class your_vector
{
    // ... [snip] ...

    template <std::input_iterator It>
    constexpr your_vector(It first, It last)
    {
        while (first != last)
            this->push_back(*first++);
    }

    // ... [snip] ...
};

That’s it. That’s all you need. That’s implementing a constructor with input iterators, and above I show you how to test a constructor with input iterators. You don’t need to make an “input iterator” type, because the standard library already has input iterator types (and, as of C++20, a std::input_iterator concept to check them, to make sure they really are valid input iterators).
Your type is dangerous and buggy
So what you’re trying to do is take a plain pointer—which is a contiguous iterator—and strip its power, to reduce its capability until it looks like an input iterator.
In VERY limited circumstances, this isn’t a terrible idea. For example, if you’re making an algorithm that works differently with input iterators than with forward iterators or better, and you want to test that the right implementation is being used, you could use a type like this to take the pointers to an array or vector data, and forcibly pretend they’re only input iterators.
Of course… you could also just use actual input iterators, for example, by creating an istringstream, and then using istream_iterators. That would be less work, and zero chance of bugs and other headaches.
Where this type gets dangerous is that it will only work for very limited circumstances… and where it won’t work, it will silently trigger undefined behaviour.
This is okay:
auto data = std::vector<int>{};
// fill data with values...

auto first = input_iterator<int>(&data.front());
auto last  = input_iterator<int>(&data.front() + data.size());

any_algorithm(first, last);

This is not:
auto data = std::deque<int>{};
// fill data with values...

auto first = input_iterator<int>(&data.front());
auto last  = input_iterator<int>(&data.front() + data.size());

any_algorithm(first, last);

The only thing that changed is the type of the container. But while std::deque is random-access, it is NOT contiguous, so trying to iterate through it using pointer arithmetic (which input_iterator does internally) is a quick path to UB.
(In fact, the code above will not work for any container except std::vector. Trying it with std::list or anything else is asking for UB.)
Iterators are attached to specific container types for a reason; you can’t just make an iterator out of the æther with no associated container. Again, that’s nonsensical. An iterator needs to know the correct way to move from one element to the next… no, simply skipping to the next address in memory is NOT the correct way to do it, usually.
It is possible to implement an iterator adaptor that can take an iterator and fake it as a more restrictive category. But if you’re going to do that, you have to do it carefully. Simply degrading to a pointer is not the right way to do it.
Your type is not an input iterator… or an iterator at all
Okay, so you can’t implement an abstract concept. But you can implement something that models the abstract concept. You can’t “implement input iterator”, but you can implement something that models input iterator. Does your class model input iterator?
No. It’s closer to a forward iterator, but it isn’t even that.
To see what I mean, here’s a simple program that just prints the name of an iterator’s category, tested with simple pointers, std::istream_iterator, and your input_iterator:
#include <iostream>
#include <iterator>
#include <string_view>
#include <type_traits>

#include <your-input-iterator-declaration>

namespace detail_ {

template <typename T, typename = void>
struct iter_cat_impl_2_
{ using type = std::iterator_traits<T>::iterator_category; };
#if defined(__cpp_lib_ranges) and __cpp_lib_ranges >= 201911L
template <typename T>
struct iter_cat_impl_2_<T, std::void_t<typename std::iterator_traits<T>::iterator_concept>>
{ using type = std::iterator_traits<T>::iterator_concept; };
#endif // defined(__cpp_lib_ranges) and __cpp_lib_ranges >= 201911L

struct dummy_t {};

template <typename T, typename = void>
struct iter_cat_impl_1_ { using type = dummy_t; };
template <typename T>
struct iter_cat_impl_1_<T, std::void_t<typename std::iterator_traits<T>::iterator_category>> : iter_cat_impl_2_<T> {};

using namespace std::string_view_literals;

template <typename T>
inline constexpr auto iter_cat_name = "<not an iterator>"sv;
template <>
inline constexpr auto iter_cat_name<std::input_iterator_tag> = "input iterator"sv;
template <>
inline constexpr auto iter_cat_name<std::output_iterator_tag> = "output iterator"sv;
template <>
inline constexpr auto iter_cat_name<std::forward_iterator_tag> = "forward iterator"sv;
template <>
inline constexpr auto iter_cat_name<std::bidirectional_iterator_tag> = "bidirectional iterator"sv;
template <>
inline constexpr auto iter_cat_name<std::random_access_iterator_tag> = "random access iterator"sv;
#if defined(__cpp_lib_ranges) and __cpp_lib_ranges >= 201911L
template <>
inline constexpr auto iter_cat_name<std::contiguous_iterator_tag> = "contiguous iterator"sv;
#endif // defined(__cpp_lib_ranges) and __cpp_lib_ranges >= 201911L

} // namespace detail_

template <typename T>
inline constexpr auto iter_cat_name = detail_::iter_cat_name<typename detail_::iter_cat_impl_1_<T>::type>;

auto main() -> int
{
    std::cout << "int*                  = " << iter_cat_name<int*>                       << '\n';
    std::cout << "istream_iterator<int> = " << iter_cat_name<std::istream_iterator<int>> << '\n';
    std::cout << "input_iterator<int>   = " << iter_cat_name<input_iterator<int>>        << '\n';
}

Output:
$ ./a.out
int*                  = contiguous iterator
istream_iterator<int> = input iterator
input_iterator<int>   = <not an iterator>
$

As you can see, your type is not an iterator.
The reason your type fails to be detected as an iterator is because you are missing some key typedefs. It looks like you have confused the typedefs necessary for a CONTAINER with the typedefs necessary for an ITERATOR. An ITERATOR does not need const_pointer or const_reference… those make no sense for an iterator. It does need difference_type and iterator_category.
Once you define those typedefs, this type will “work” as an input iterator. But it will also “work” as a forward iterator (though, a well-designed algorithm will still treat it as an input iterator).
Okay, let’s dive into the actual code review.
The review
I’ll skip down to the typedefs, because everything prior to that is cool:
using reference = T&;
using const_reference = const T&; // <- nonsense typedef
using value_type = T;
using pointer = T*;
using const_pointer = const T*; // <- nonsense typedef

The two typedefs I’ve marked are nonsense for an iterator. You have confused the typedefs required for a container with the typedefs required for an iterator.
To understand why those typedefs are nonsensical, consider std::vector<int>::iterator::const_pointer. What do you think that means? std::vector<int>::iterator basically means: “I want a mutable pointer to the elements of an int vector (treated as a plain pointer)”. So std::vector<int>::iterator::const_pointer basically means: “I want a mutable pointer to the elements of an int vector no wait I changed my mind I want a const pointer to those elements (treated as a plain pointer)”. Meanwhile, there’s std::vector<int>::const_iterator, which actually means: “I want a const pointer to the elements of an int vector (treated as a plain pointer)”.
That’s another reason why const_pointer and const_reference make no sense in an iterator: that’s what const_iterators are.
In addition, if you want your type to work as an iterator, there are some other typedefs you need. You need to define difference_type, and you need to define iterator_category. The former could be std::ptrdiff_t, and the latter, since you want it to be an input iterator, should be std::input_iterator_tag.
pointer and reference should also probably be defined differently, but I’ll explain why later.
constexpr explicit input_iterator(const input_iterator& other) noexcept : input_iter{ other.input_iter } {}

~input_iterator() noexcept = default;

These are kinda pointless. If you don’t need to declare the destructor, don’t bother. And in the case of the copy constructor, defining it like this means the type is no longer trivially copyable (or movable). (The explicit keyword is also meaningless here, because a copy constructor is not a converting constructor. It makes no sense to “explicitly copy”.)
constexpr reference operator=(const input_iterator& other){
    if (input_iter != other.input_iter)
        input_iter = other.input_iter;
    return *this;
}

As above, this is kinda pointless, and it means the type is no longer trivially assignable. The implementation is also overly complicated, too, because there’s no need to check for equality before doing the assignment. What exactly would go wrong if the two pointers are the same, yet you did the assignment anyway?
constexpr const_reference operator*() const {
    return *this;
}

constexpr const_pointer operator->() const {
    return this;
}

Seems to me like all these operations, and the increment ops, too, could be noexcept.
However, both of these are wrong. Did you test the type? I can’t imagine it compiled. The reason why is that operator* on an iterator is supposed to return a reference to whatever is being pointed to. But you return *this. That’s a reference to the iterator… not to what the iterator is pointing to.
The same problem exists for operator->. You’re supposed to return the address the iterator is pointing… but you return the address of the iterator.
operator* should probably just be returning *input_iter, and operator-> should be probably returning input_iter itself.
But there’s a much deeper issue: you’re seeing cracks in your conceptual model. An iterator is basically a pointer—the abstraction is just to allow more powerful pointers; ones that can handle iterating in ways other than merely jumping to the next memory address. So you can mentally replace any iterator with T* to get a grasp on how operator* and operator-> should work.
So if you have int*, what should operator* return? The answer is int&… NOT int const&.
If you have int* const, what should operator* return? Again, int&… NOT int const&.
So with input_iterator<int>, operator* should return int&… NOT int const&.
With input_iterator<int> const, operator* should also return int&… NOT int const&.
In other words, this is the correct way to implement operator* for iterators:
constexpr reference operator*() const noexcept { return *input_iter; }

Note that it returns reference, and not const_reference (which is not a thing; iterators don’t have const_reference because it’s nonsensical). Similarly, operator-> should return pointer, not const_pointer.
Ah, but input iterators offer only read-only views of what they point to, so they should return const pointers and references. The correct way to handle this is to properly define reference and pointer… not to invent new typedefs.
reference should be defined as T const&, not T&, because if the iterator is an input iterator, a reference will be read-only. Having reference defined as T& makes no sense for an input iterator. Similarly, pointer should be T const*, not T*. If I do input_iterator<int>::pointer p = &(*i);, that should compile… that’s the point of the pointer typedef. It won’t if pointer is T* while operator* returns const&.
So your typedefs really need to be:
using value_type = T;

using reference = T const&;
using pointer   = T const*;

using difference_type = std::ptrdiff_t;

using iterator_category = std::input_iterator_tag;

That’s about it, except for:
constexpr bool operator==(const input_iterator& other) const noexcept {
    return (input_iter == other.input_iter);
}

constexpr bool operator!=(const input_iterator& other) const {
    return !(input_iter == other.input_iter);
}

You’re missing the noexcept for the inequality operator.
Standard practice is to use non-member functions for binary operators, and to define only one operator where possible and then all others in terms of that one. So:
friend constexpr bool operator==(const input_iterator& lhs, const input_iterator& rhs) noexcept {
    return lhs.input_iter == rhs.output_iter;
}

friend constexpr bool operator!=(const input_iterator& lhs, const input_iterator& rhs) noexcept {
    return not (lhs == rhs);
}

(It’s also a good idea, even though they’re non-member functions, to define them in the class as friends. This is called the “hidden friends” pattern, and it has several benefits, but it’s too much to go into here.)
Summary
The main problem here is conceptual confusion. “Input iterator” is an abstract idea. It’s a concept. You can’t make an implementation of input iterator any more than you can make an implementation of “equality comparable”. You can implement something that is equality comparable, but can’t implement the abstract concept “equality comparable”. (As of C++20, you can describe the concept, and use that to check that types satisfy the concept, but you still can’t implement the abstract concept as a type.)
So saying you are “implementing input iterator” is gibberish. Saying that you need “input iterator” for some constructor is also gibberish. Unfortunately, that’s all you’ve given, so I’m forced to guess what you really mean when you’re saying these things.
If you mean you need a constructor that takes input iterators… well, that’s just a template constructor, with a type that satisfies the input iterator concept. The type could be anything; it doesn’t need to be some concrete input_iterator type. It just needs to satisfy the concept.
The standard library has a couple types that satisfy the input iterator concept: istream_iterator and istreambuf_iterator are the two that spring to mind. So if you’re making a constructor that takes input iterators, just make a constructor template, and make sure it works with istream_iterators (and/or istreambuf_iterators).
For example, this is actually Clang 11’s implementation of std::vector’s input iterator constructor:
template <class _Tp, class _Allocator>
template <class _InputIterator>
vector<_Tp, _Allocator>::vector(_InputIterator __first,
       typename enable_if<__is_cpp17_input_iterator  <_InputIterator>::value &&
                         !__is_cpp17_forward_iterator<_InputIterator>::value &&
                         is_constructible<
                            value_type,
                            typename iterator_traits<_InputIterator>::reference>::value,
                          _InputIterator>::type __last)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
    __get_db()->__insert_c(this);
#endif
    for (; __first != __last; ++__first)
        __emplace_back(*__first);
}

Ignoring the enable_if and the debug stuff, and pretending it’s defined within the class body rather than outside, that’s just:
template <class _InputIterator>
vector(_InputIterator __first, _InputIterator __last)
{
    for (; __first != __last; ++__first)
        __emplace_back(*__first);
}

That’s all there is to it.
(The enable_if just makes sure that _InputIterator actually satisfies the input iterator concept, but not the forward iterator concept. That’s because the forward iterator version uses std::distance() to figure out how many elements there are, so it can preallocate enough memory. You can’t do that with input iterators, because you only get one pass; you can’t first count the elements, allocate the size, then copy the elements, because that second pass won’t work for input iterators. It’s a neat optimization you might consider, though it’s much easier with C++20 concepts than with enable_if.)
And you can test that constructor with input iterators like this:
auto iss = std::istringstream{"42 69 57"};

auto const vec = std::vector<int>(std::istream_iterator<int>{iss}, std::istream_iterator<int>{});

TEST(vec.size() == 3);
TEST(vec.at(0) == 42);
TEST(vec.at(1) == 69);
TEST(vec.at(2) == 57);

Another issue with your design is that “generic” iterators make no sense. Iterators are tightly bound to containers (or views, or other such things). You can’t simply make an iterator that just works with any container. Indeed the only standard containers your iterator works with are std::vector and std::array. For all other containers, it will trigger UB.
And finally, if you want this type to be an actual (input) iterator, you need to add some extra typedefs, modify the existing typedefs, and fix some problems in your dereferencing operators.
But honestly, I would suggest just throwing the whole thing out, because:

It’s poorly conceived (it is trying to be a concrete implementation of an abstract idea).
It’s dangerously buggy (it only works with certain containers).
It’s unnecessary (if you want an input iterator, there are already input iterators in the standard).


Aggregate loans report without using Python standard aggregate or group functions

Try not to use name of data-structure in your variables. Check: Do you prefix variable names with an abbreviation of the variable types?. Python 2 doesn't support annotations but you can use comments to specify the types. On Python 3+ you can use function annotations and in Python 3.6+ you can use variable annotations as well.
Use with-statement while handling files: open(loans_csv).

  It is good practice to use the with keyword when dealing with file
  objects. The advantage is that the file is properly closed after its
  suite finishes, even if an exception is raised at some point.

Use simple str.split instead of regex r'([A-z]+?-\d{4})': row['Date'].split('-').
You can pass qotechar="'" to csv.DictReader and then you won't have to strip them manually.
To append an item at the end use list.append instead of vlist.insert(len(list), item).
The for-loop in agg_dict_to_lists can be reduced to:

for key, values in agg_dict.iteritems():
    values_list = list(key) + [sum(values), len(values)]
    summary_list.append(values_list)

If you're expecting currency to be decimal then use decimal module instead of plain floats. Decimals objects provides better floating-point arithmetic and alterable precision.
The format() is not required here: datetime.today().strftime("{0}{1}{2}".format("%y", "%m", "%d")). You could simply do: datetime.today().strftime('%y%m%d').
If you're opening the file in binary mode open(output_csv, 'wb') the make sure you're converting the data being written to bytes first by encoding individual items of the rows. This would otherwise not even work in Python 3 where you cannot mix bytes and str anymore.
print is not a function in Python 2 unless your import it using from __future__ import print_function. Hence, don't use it with parenthesis.


Improving a Medicare Beneficiary Identifier (MBI) generator

Instead of while 1: please just use while True. while 1: is a throwback from old versions of C that didn't have stdbool.h. while True: is much most explicit a about what your intent is.

At the top you have
letter = 'ACDEFGHJKMNPQRTUVWXY' # not = B, I, L, O, S, Z
digit = str('0123456789')
partdig = str('123456789')
dig_let = digit + letter

Python actually has built-ins for these:
from string import digits, ascii_uppercase

# letter is the set of ascii characters minus B, I, L. . .
letter = "".join(set(ascii_uppercase) - {'B', 'I', 'L', 'O', 'S', 'Z'})
# Just use digits instead of digit
partdig = digits[1:]  # Remove the first digit
dig_let = digits + letter

That saves you from needing to type out each of the letters to include.
Also note, even if string.digits didn't exist, you could have also defined digit as:
>>> digit = "".join(str(n) for n in range(0, 10))
>>> digit
'0123456789'

Also, all variable names here should be lowercase, separated by underscores. partdig should be part_dig, or part_digits, or even better: non_zero_digits.
I also think letter should be letters, since it's a collection of letters. It's a small change, but it lets your readers know that it's multiple letters, not just a single one.

Watch your indentation:
mbi_need = int(input("How many MBI numbers do you need to generate?: "))
 for x in range(0,mbi_need):

Especially in Python that matters a lot. If that was just a pasting error, it's a good idea to look over the code before posting just to double check that errors weren't introduced accidentally.
You're using a odd 5-space indentation in the loop though, which is part of the problem. Please use 4-space indentation.

for x in range(0,mbi_need):
    mbi = ""
    for x in range(0, mbi_return):

Both loops define a x variable! Since you never use x in either loop though, use _ instead:
for _ in range(0,mbi_need):
    mbi = ""
    for _ in range(0, mbi_return):

_ is a convention that says "I needed to create a name, but don't need the variable", which is the case here.

range(0, mbi_need)

0 is the implicit start; it's not necessary to specify it if you only otherwise need to specify the ending number. Just write:
range(mbi_need)

mbi_char0 = random.choice(partdig)
mbi_char1 = random.choice(letter)
mbi_char2 = random.choice(dig_let)
mbi_char3 = random.choice(digits)
. . .

Whenever you find yourself creating many similar variables, and you're differentiating them by putting numbers in the name, stop! You should likely be using a list instead. Because the make-up of the MBIs doesn't follow an easy pattern, fixing this isn't super straightforward, but it's still possible. First, I'd create a list holding the order of partdig, letter, dig_let, digits. . . which will define the order of the different character types:
mbi_pattern = [non_zero_digits, letters, digit_letters, digits,
               letters, digit_letters, digits, letters,
               letters, digits, digits]

This looks ugly, but it will clean up the code later. Sometimes all you can do is move the ugly bulk to the side. Once you've defined that list, creating a MBI is trivial and tiny:
mbi = "".join(random.choice(part) for part in mbi_pattern)
print(mbi)

Get each of the part sets, generate a random character from each of them, then join them into a string.

Your inner
for _ in range(mbi_return):

loop doesn't appear to be doing anything. It seems like it's doing a similar job as the other loop, except it will always be range(1), which will only run once, which means it isn't really a loop. I got rid of it because it isn't doing anything except complicating the code.
The same can be said about the while True as well. You want to generate 10000 codes, repeatedly, forever? The while True loop will never end since you never break from it. I also got rid of it because it is also complicating the code without good reason.

 mbi = ""

This isn't necessary. Even if you needed mbi in the outer scope, loops in Python don't create scopes like they do in other languages. mbi "defined" inside the loop can be accessed from outside of the loop.

In your remaining loop, you're creating an mbi, then just printing it. That doesn't allow you to do anything with the data though, like save it to file. It would be much cleaner to store the generated MBIs in a list so that they can potentially be used later. If you do that, your loop can be made into a list comprehension:
mbis = ["".join(random.choice(part) for part in mbi_pattern)
        for _ in range(mbi_need)]

Each MBI is generated using the same generator expression as before, but now it's wrapped in a list comprehension to generate multiple.

In the end, this is what I'm left with:
import random
from string import digits, ascii_uppercase

letters = "".join(set(ascii_uppercase) - {'B', 'I', 'L', 'O', 'S', 'Z'})
non_zero_digits = digits[1:]
digit_letters = digits + letters

mbi_pattern = [non_zero_digits, letters, digit_letters, digits,
               letters, digit_letters, digits, letters,
               letters, digits, digits]

mbi_need = int(input("How many MBI numbers do you need to generate?: "))

mbis = ["".join(random.choice(part) for part in mbi_pattern)
        for _ in range(mbi_need)]

print("\n".join(mbis))

And its usage:
How many MBI numbers do you need to generate?: >? 10
5V70VK4JP28
8Y12N77RC51
9JM2JN8RQ38
3X08DH7FH95
3MH6Y49KU87
6N70AC7MW75
9A67A62TU38
4A48C94QT38
2NP7TY0DC65
1GP8A57JQ27

As mentioned in the comment though, really, code should be tucked into functions. In larger programs, that eases testing and comprehension of your code.
Here, you could have a function that generates a single MBI, then use it to generate a list of them. I also always have a main function that ties the whole program together so I can control the execution of the code easier.
I also realized after I had my coffee that all the variables at the top are really constants, so they should be in UPPER_SNAKE_CASE.
After those changes, I'm left with:
import random
from string import digits, ascii_uppercase

LETTERS = "".join(set(ascii_uppercase) - {'B', 'I', 'L', 'O', 'S', 'Z'})
NON_ZERO_DIGITS = digits[1:]
DIGIT_LETTERS = digits + LETTERS

MBI_PATTERN = [NON_ZERO_DIGITS, LETTERS, DIGIT_LETTERS, digits,
               LETTERS, DIGIT_LETTERS, digits, LETTERS,
               LETTERS, digits, digits]

def generate_mbi():
    return "".join(random.choice(part) for part in MBI_PATTERN)

def main():
    mbi_need = int(input("How many MBI numbers do you need to generate?: "))
    mbis = [generate_mbi() for _ in range(mbi_need)]
    print("\n".join(mbis))

if __name__ == '__main__':
    main()


When doing emulation you should disconnect from the real world and only provide a abstract view to a world.

In other words don't use a real time clock instead simulate the timer by linking it to the emulated clockspeed. For example if you pick 8 MHz you would have 133 333 instructions executed per decrement of each timer.

This will allow you to pause and fast forward when debugging programs.


Showing a menu with buttons with dropdown submenus

A few things first:

$menu_item == $active_item should probably be $menu_item[0] == $active_item
Depending on where that array is coming from, it should probably be associative.  Imagine if you came across the code out of context.  You'd quickly find yourself wondering what in the world menu_item[0] and menu_item[1] are.  menu_item['name'] and menu_item['down'] would be much more descriptive (or something like that).
if (... && $x == true) {} is identical to if (... && $x) { }.  Don't include the implicit truth comparison.  The only time you should compare against booleans is if you're wanting to compare type too.  if ($result === false) {}

Anyway, I would probably do something like this:

foreach ($menus_array as $menu_item) {

    $classes = array();

    if ($menu_item[0] == $active_item) {
        $classes[] = 'active';
    }

    if ($menu_item[1]) {
        $classes[] = 'dropdown';
    }

    $css_class = ' class="' . implode(' ', $classes) . '"';

}

Or, if you are into micro-optimizing (and you shouldn't be):

foreach ($menus_array as $menu_item) {

    $class = '';

    if ($menu_item[0] == $active_item) {
        //Could be = instead of .= but putting .= will mean that you
        //can add another assignment above this and not have to change
        //= to .= here.
        $class .= 'active ';
    }

    if ($menu_item[1]) {
        $class .= 'dropdown ';
    }

    $css_class = ' class="' . rtrim($class) . '"';

}

(The rtrim really isn't necessary, but I'm picky. If I were super worried about performance, I would omit the rtrim.)

I would go with the array based one.  Rendering HTML is never going to be your bottleneck, and it's the easier one for me to read.


Generating a sinusoid sound signal in Java

There's probably good room for performance gain regarding the Math.sin call itself. You could easily create a lookup-table - there's no faster way than just taking the values straight from an array. (The link's benchmark measures a factor ~6 speed difference.)

It may be problematic because it may cause audible distortions, but that would depend on how much memory you're willing to invest in the lookup-table. Also, you could invest a few more cycles by obtaining both array entries addressed by (_tone*i) and then adding them up, both multiplied by 0.x and respectively (1-0.x), effectively fading over between values.


Save multiple group permissions in one go

There's no need for fairly meaningless variable names like gsp, conn, tran, eItem,...

And result is equally bad, since it doesn't tell me what it contains.

Exception x is... unexpected. ex or exc is usually used.

You use var, but not consistently. Why SqlConnection conn, Group group, etc.?

I'm sure the .ToString() isn't necessary in "ProductName.GSP.cid" + companyID.ToString() -- unless you're coding to an old version of .NET.

Comments shouldn't tell me what is happening, but why. //End outer for and //important :) don't tell me anything useful.

Meanwhile //new permission that does not exist in the database. (INSERT) tells me that if (stepPermission.RowID == 0) isn't perhaps the best way to check if you need to do an insert or an update.

An enum shouldn't be called StatusEnum. Why not simply Status?

GroupStepPermissions is a class name, yet it seems to represent a single item. That's a big no-no.

Avoid concatenation:

"Added rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'"

This is why string.Format() was invented.

Now, let's look at the whole method. You have four parameters, which is bordering on getting hard to maintain. Consider a class that contains companyID, groups and gsp. Note that I leave connectionString out of it; quite frankly I find it odd to see you pass a connectionstring to a method.

There's a lot of semi-duplicate logic, especially in catch (Exception x) in the insert or update. Move that to a method and call it with the required parameters.

I'd also be inclined to move everything inside foreach (GroupStepPermissions stepPermission in gsp) to a separate method, if only to reduce all those indentations.

I don't see the point in doing this:

result.Add(new EventItem("Insert Step permissions"));
result.Add(new EventItem("Update Step permissions"));

...if that results in having to do this:

result[0].SubEvents.Add

Name one of them insertEventItem and the other updateEvenItem and only compile the result list at the end, e.g.

return new List<EventItem>{ insertEventItem, updateEvenItem };


A tiny switcher for arbitrary types in C++11

While the idea is OK, this seems to add very little over a (unordered_)map of strings to functions (created directly). The client code is almost the same as your client code anyway:

int main() {
    typedef std::pair<std::string, std::function<void(void)>> pair;
    std::string s1("hi");
    std::string s2("dear");

    auto defaultFn = [](){ std::cout << "Default "; };

    std::map<std::string, std::function<void(void)>> switcher{
        pair{"hi", [](){ std::cout << "Hello "; } },
        pair{"dear", [](){ std::cout << "World "; } },
    }

    switcher[s1]();
    switcher[s2]();

    switcher["hi"](); // not supported: chaining calls ("buddy")("?");

    if(!switcher.count("buddy"))
        defaultFn();
    else
        switcher["buddy"]();
    return 0;
}

The code is a bit bigger, and some syntactic sugar is missing (stuff that you added in your example, like chaining calls and multiple keys per entry) but the code is semantically the same.

My point to adding this code: your class only makes sense if you use lots of switches (on strings) in your code, and usually in OOP, if you do have big switches in your code, you should extract them as a hierarchy of classes (or a table of functions) anyway.


Yet another problem is the usage of lists. !! is O(N) operation. Use Data.Array instead.

As for randoms, you should call newGenIO only once and use the cryptographically secure generator it returned after that instead of creation of new generators each time you need a random character.

Your randVal function should look something like this:

randVal :: Int -> SystemRandom -> (Int, SystemRandom)
randVal len g = fromRight $ crandomR (0, len-1) g

It accepts old generator state and returns the new state to use in subsequent generations. To simplify passing the generator state around you can use a state monad. But there is already such monad - the CRand monad and corresponding CRandT monad transformer to combine random number generation with other monadic computations.

The example from the documentation for CRand fails to typecheck because of monomorphism restriction - getRandPair looks like a value but it isn't, so the compiler detects a potential problem. You can disable it for now by adding {-# LANGUAGE NoMonomorphismRestriction #-} before module Main where line.

Also, it is not clear how the SystemRandom generator works. It is secure, but I think it's not adviced to drain system entropy source. I'd rather use it just to seed HashDRBG from Crypto.Random.DRBG, which is SHA512-based RNG.

Here is a hint:

type Gen a = CRand HashDRBG GenError a

randValM :: Int -> Gen Int
randValM len = getCRandomR (0, len-1)

randomChoice :: [a] -> Gen a
randomChoice ls = do
    randomIndex <- randValM (length ls)
    return $ ls !! randomIndex

Your tabulax function will remain the same, but will operate in a different monad, so it's type will change to randomChoice :: [a] -> Gen a. Note also that I used getCRandomR from Control.Monad.Crypto.Random to make use of the monadic helper to implicitly pass the cryptogenerator around and perform error checking.

Your main will change too:

printGenerated values = do
    putStrLn $ "    " ++ join " " (chunksOf 1 ['A'..'Z'])
    putStrLn $ "  + " ++ (take 52 $ cycle "- ")
    putStrLn $ join "\n" (reverse values)

fromRight (Right a) = a

generate = evalCRand $ do
    a <- tabulay ['A'..'Z']
    return a

main = do
    g <- newGenIO :: IO HashDRBG
    printGenerated $ fromRight $ generate g

The idea is that we extracted generate - a pure function which accepts a generator and returns generated data. evalCRand is used to extract the inner a value from monadic Gen a value. It accepts two arguments: a monadic computation in Gen monad and initial state of random generator. There is also runCRand function which returns the final state of the generator in addition to the value, but we don't need the final state here.

I abused the do-notation here to help you understand code better. I would write generate and main shorter:

generate = evalCRand $ tabulay ['A'..'Z']

main = newGenIO >>= printGenerated . fromRight . generate

Your tabulatex' function is already there in the standard library. It is Control.Monad.replicateM:

import Control.Monad hiding (join)

tabulax :: Int -> Gen [Char]
tabulax cint = replicateM cint $ randomChoice characterMap

tabulatey' is also there in Control.Monad, it's mapM:

tabulay :: [Char] -> Gen [[Char]]
tabulay = mapM $ \x -> do
            chars <- tabulax 26
            let formatted = [x, '|'] ++ chars
                spaced = join " " (chunksOf 1 formatted)
            return spaced

Next step is to use immutable arrays:

import Data.Array.IArray

tabulax :: Int -> Gen [Char]
tabulax cint = replicateM cint $ randomChoiceA arrMap

arrMap :: Array Int Char
arrMap = listArray (0, (length characterMap) - 1) characterMap

randomChoiceA ls = do
    randomIndex <- randValM $ 1 + snd (bounds ls)
    return $ ls ! randomIndex

Now randValM seems to be perverted: we convert bounds from tuple to size and back. Eliminating the extra conversion we get rid of randValM completely, as getCRandomR and bounds perfectly fit each other:

randomChoiceA ls = do
    randomIndex <- getCRandomR $ bounds ls
    return $ ls ! randomIndex

Now we can shorten it by desugaring do-notation and using function composition and infix operator sections:

randomChoiceA ls = getCRandomR (bounds ls) >>= return . (ls !)

And even more using <$> from Control.Applicative (which is the same as fmap):

randomChoiceA ls = (ls !) <$> getCRandomR (bounds ls)

Finally, we can extract separate = join " " . chunksOf 1 as it is used 2 times and shorten tabulay just for fun:

tabulay :: [Char] -> Gen [[Char]]
tabulay = mapM $ \x -> separate <$> ([x, '|'] ++) <$> tabulax 26

and get rid of ugly -1 in array bounds:

arrMap :: Array Int Char
arrMap = listArray (1, length characterMap) characterMap

So the final source is:

{-# LANGUAGE NoMonomorphismRestriction #-}
module Main where

import Control.Monad.CryptoRandom
import Crypto.Random.DRBG
import Data.String.Utils
import Data.List.Split
import Control.Monad hiding (join)
import Control.Applicative
import Data.Array.IArray

printGenerated values = do
    putStrLn $ "    " ++ separate ['A'..'Z']
    putStrLn $ "  + " ++ take 52 (cycle "- ")
    putStrLn $ join "\n" (reverse values)

fromRight (Right a) = a

generate = evalCRand $ tabulay ['A'..'Z']

main = newGenIO >>= printGenerated . fromRight . generate

separate = join " " . chunksOf 1

tabulay :: [Char] -> Gen [[Char]]
tabulay = mapM $ \x -> separate <$> ([x, '|'] ++) <$> tabulax 26

tabulax :: Int -> Gen [Char]
tabulax cint = replicateM cint $ randomChoiceA arrMap

arrMap :: Array Int Char
arrMap = listArray (1, length characterMap) characterMap

randomChoiceA ls = (ls !) <$> getCRandomR (bounds ls)

characterMap :: [Char]
characterMap =
    let
        cmap = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9']
        symb = ",./?~`!@#$%^&*()-_+={[]}\\|:;\"'"
    in cmap ++ symb

type Gen a = CRand HashDRBG GenError a


Finding cost of tile to cover W x H floor

One of the most powerful techniques you will develop is called 'separation of concerns'. What this means when it boils down is that your program can be split into discrete logical units. Ideally one module (or in the case of c++, class) will do exactly one job without depending on any other.

This has a number of benefits in that the parts can be re-used without needing any knowledge of which parts of the program are using them.

here is your program again, split into essentially three sections, or concerns. Hopefully you will see that although there are more lines of code, the logic in the main() function is easier to follow. Also you can hopefully see that the "input_data" class is an entirely autonomous entity, which could be re-used to gather data for other parts of a bigger program:

I also fixed the small logic error in your calculation, which was easier to see when the calculations were separated from the input/output code.

#include <iostream>

using namespace std;

double area(double width, double height)
{
    return width * height;
}

double cost_to_cover(double area, double area_per_pack, double cost_per_pack)
{
    double packs_needed = area / area_per_pack;
    double cost = packs_needed * cost_per_pack;

    return cost;
}

struct input_data {
    double area_per_pack, cost_per_pack, width, height;    // Starting square meters and cost. Width and height of floor.

    void gather() {
        cout << "Enter value of 1 pack of tiles: ";
        cin >> cost_per_pack;

        cout << "Now enter the square metres covered by the pack: ";
        cin >> area_per_pack;

        cout << "What is the width of your room? ";
        cin >> width;
        cout << "Now enter the height:\n";
        cin >> height;
    }
};

int main() {

    // concern 1 - gather data
    input_data input;
    input.gather();

    // concern 2 - perform calculations
    double room_area = area(input.width, input.height);
    double cover_cost = cost_to_cover(room_area, input.area_per_pack, input.cost_per_pack);

    /// concern 3 - output the result
    cout << "You need to cover a total of " << room_area << " square metres.\n";
    cout << "The total cost will be: " << cover_cost << endl;

    return 0;
}


The "file and format ID" can be created in one step as

var fileTypeAndFormat = AudioFileTypeAndFormatID(mFileType: kAudioFileCAFType,
                                                 mFormatID: kAudioFormatLinearPCM)

Using a Swift Array as storage is fine, and has the advantage that
the memory is managed automatically (contrary  to memory from malloc
or UnsafeMutablePointer.alloc()). The array creation can be written
a tiny be shorter as

var audioDescriptions = Array(repeating: AudioStreamBasicDescription(), count: asbdCount)

because the element type is inferred from the first argument. I have
also chosen a different name, asbds is very short and cryptic.

For-loops are often better replaced by an enumeration:

for audioDesc in audioDescriptions {
    // ...
}

or, if you need the element index as well:

for (idx, audioDesc) in audioDescriptions.enumerated() {
    // ...
}

This saves array lookups inside the loop.

Treating the "four-character code" in mFormatID as a string is
dangerous and causes undefined behaviour, because the %s format
expects a zero-terminated sequence of chars.
You can get additional unwanted output, or the program might crash.

You could use the %4.4s format instead, which limits the output
to four characters:

for (idx, audioDesc) in audioDescriptions.enumerated() {
    var reformattedID = audioDesc.mFormatID.bigEndian

    withUnsafePointer(to: &reformattedID) { stringIDPtr in
        print(String(format: "%d: mFormatID: %4.4s, mFormatFlags: %d, mBitsPerChannel: %d",
                     idx, stringIDPtr,
                     audioDesc.mFormatFlags, audioDesc.mBitsPerChannel))
    }
}

A better solution is to convert the integer to a four-character
string, e.g. using one of the methods in
How to convert memory of Int32 as four characters, for example

func fourCCToString(_ value: FourCharCode) -> String {
    let utf16 = [
        UInt16((value >> 24) & 0xFF),
        UInt16((value >> 16) & 0xFF),
        UInt16((value >> 8) & 0xFF),
        UInt16((value & 0xFF)) ]
    return String(utf16CodeUnits: utf16, count: 4)
}

which is then used as

for (idx, audioDesc) in audioDescriptions.enumerated() {
    let reformattedID = fourCCToString(audioDesc.mFormatID)

    print(String(format: "%d: mFormatID: %@, mFormatFlags: %d, mBitsPerChannel: %d",
                 idx, reformattedID,
                 audioDesc.mFormatFlags, audioDesc.mBitsPerChannel))
}

Note that a Swift string is printed with the %@ format.

Or simply use string interpolation:

for (idx, audioDesc) in audioDescriptions.enumerated() {
    let reformattedID = fourCCToString(audioDesc.mFormatID)

    print("\(idx): mFormatID: \(reformattedID), mFormatFlags: \(audioDesc.mFormatFlags), mBitsPerChannel: \(audioDesc.mBitsPerChannel)")
}


There are some formatting and spelling issues.  I fixed those (somewhat arbitrarily changing to my style), removed redundant comments, and made a few other changes:

<?php
  function fetchTableFieldCount($mysqli , $databaseName , $tableName ) {
    $sql = "SELECT COUNT(`COLUMN_NAME`) AS FieldCount FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`= ?  AND `TABLE_NAME`= ? ";

    if ( ! ( $stmt = $mysqli->prepare($sql) ) ) {
      die("There is an error with mysql preparation statement".$mysqli->error);
    }

    $stmt->bind_param($databaseName, $tableName);

    if ( ! $stmt->execute() ) {
      echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    $res = $stmt->get_result();

    if ( $row = $res->fetch_array() ) {
      return $row['FieldCount'];
    }

    return 0;
  }

  function insert($mysqli, $tableName, $databaseName, $array) {
    //see if the table columns count does not match array data count we kill the script
    $tableColumnsCount = fetchTableFieldCount($mysqli, $databaseName, $tableName);
    $dataArrayCount    = count($array);
    if ( $tableColumnsCount != $dataArrayCount ) {
      die("Data array does not match table columns count");
    }

    if ( 0 == $dataArrayCount ) {
      return;
    }

    $sql = "INSERT INTO `{$databaseName}`.`{$tableName}` VALUES (";
    $sql .= implode(', ', array_fill(0, $dataArrayCount, '?'));
    $sql .= ')';

    for ( $i = 0; $i < $dataArrayCount; $i++ ) {
      $string         =  gettype($array[$i]);
      //taking the first letter; example:  string = s, integer = i
      $a_param_type[] =  $string[0];
    }

    if ( ! $stmt = $mysqli->prepare($sql) ) {
      die("error in preparation " . $mysqli->error);
    }

    // make the first element of the array a string representing the types
    // of the values of the rest of the array
    array_unshift($array, implode($a_param_type));
    // use call_user_func_array to pass the variable number
    // of elements in the $array as arguments
    call_user_func_array(array($stmt, 'bind_param'), $array);

    if ( ! $stmt->execute() ) {
      die("Error in executing the query:  " . $mysqli->error);
    }
  }

  $mysqli =  new mysqli('localhost','user','pass','dbname');
  if ( $mysqli->connect_errno > 0 ){
    die( "problem with the connection");
  }

  $array = array("", "catName" ,"catDescription", "", "", "", "");
  insert($mysqli, "items", "yaztor", $array);

First, I moved the connection info from the top to the bottom.  This puts all the commands outside of a function together.  Normally we'd move the functions into a different file and require it, but I skipped that here.

Next, I removed the first redundant comment.  A comment like "creat [sic] a function to get table information" doesn't tell me anything that function fetchTableFeildNames [sic] doesn't already tell me.  Save comments for explaining why you chose to do something.  That's what you'll forget before you have to go back to the code.

I changed the first function to get just the column count, as that's all we're using.  No need to ship the column names across the wire.

I changed $array to $row.  Row describes what the variable holds.  Array doesn't differentiate it from any other array.  I dropped $newArray entirely, but if needed, I would have called it $columnNames.

I added a check for an array with no elements.  This avoids a failed SQL query in that case.

I took the $sql concatenation out of the for loop.  This allows for the more efficient implode rather than a series of string concatenations.

I took out the extraneous for loop that copied the array.  The $array variable itself is a copy, so I just used that.  I also took out the manual splice in favor of array_unshift.  I would expect a built-in function to be faster than a for loop in PHP.

I didn't remove your column count check, but I don't know that it's necessary.  It removes one thing that can go wrong but leaves others.  It's not like you recover from the mistake.  It ends the program.  The same thing would happen with an invalid INSERT to the database.  I don't know that you gain much.

The code that you show here is reasonably safe and secure.  However, it was not reliably so.  It relied on the caller to secure $databaseName and $tableName.  If a caller bases either of those on user input, there's risk.


Optimise many namedtuple assignment statements

What if, instead of multiple variables, you would define a list of names, which you then use to create a dictionary of names to Unit instances which are initialized using dictionary unpacking:

names = [
    'trooper',
    'robot',
    'commando',
    'flame_trooper'
]
items = {
    name: Unit(**units[index])
    for index, name in enumerate(names)
}

Please think of better variable names for names and items.


Cross-browser double form submit prevention

Can't you just overwrite the onsubmit handler with the first submission?

function preventDoubleSubmit(e) {
    e = e || window.event;
    var form = e.target || e.srcElement;

    form.onsubmit = function() {
        return false;
    };
}


Before we even get started into optimizations, I would like to point out a couple of things. First- many permutations of operands + operators are going to behave identically. There isn't a whole lot we can do to skip these, but in practice it seems that "similar" permutations are composed of "similar" components. That is, a handful of permutations of operands + operators that differ by 1 operand or operator will often have very similar input->output mappings. Some times you can take advantage of this to speedup your search. Sometimes the best solution is to do a completely random search of permutations to avoid the problem completely (at the cost of trying duplicate permutations). I won't explore either option below, but I wanted to mention them for completeness.

Secondly, you are trying to create a (int->bool) input->output mapping for 100 unique values. Even if we never tried two permutations of operands + operators that produce the same mapping, there's still 2^100 unique mappings to explore. That is not something that we can reasonably brute force. For 5 operands chosen (with replacement) from your 8 and 5 constants each in the range [0-99] inclusive, we have 8^5 * 100^5 == 3.27*10^14 == 2^48 permutations. Unless we are astronomically lucky, you're going to need to at least double your operand + argument count anyways. We need something smarter.

We need to try to prune the search space, but in order to do that we need to be able to determine early on whether a permutations is worth pursing. In the process of  restructuring your code to support such a heuristic, we're also going to gain a small performance boost. The following line of code is executed over and over for all 100 indices, and isn't going to change when you change opB, opC, and so on.

int val = op(index, A, opA);

This logic also applies to val = op(val, B, opB);, and the others. This isn't too bad- you're only losing a factor of 5 in performance, but it needs to be changed anyways to give our algorithm some foresight. We can reorder your loops to put the argument and operand together, and then compute the intermediate values immediately-

for (int A=1; A < 2; A++) {
    std::cout << A << std::endl;
    for (int opA = 0; opA < 8; opA++) {
        int valA[100];
        // compute val for all indices
        // Loop over B, C, D

This will allow us to compute the intermediate value of val exactly once- every time it is changed, rather than every time we change any operand / operator.

Now how does this help us prune the search space? Notice that for any mapping our operand constant is... constant. Together with the operator, they make a new (unary) operator. We can take this further as well- since all our new operators are "chained" together, they can be seen as one big (unary) operator.

input <operator> <operand_constant>  => output
input <new_operator> output
...
input <new_operator_A> <new_operator_B> => output
input <combined_operator> => output

The index itself is the only input and each index is unique, but each intermediate value/output might not be unique. Regardless of the index value, if two intermediate operations produce the same intermediate value, then both will produce the same output value. We can use this to prune the search space.

If two values in the array are identical, then their corresponding bits in the original array must both be the same. If they are not, immediately attempt the next operator / operand value. If you reduce your computations to unsigned chars spanning [0, 255] inclusive, the probability of having two equal intermediate values is roughly 0.999999999827. There will likely be many intermediate values with the same value, allowing you to quickly prune bad branches in the search tree.

To quickly determine if two values in the array cause a conflict, use an external array of size 256. When you compute an intermediate value v, check that array[v] is either uninitialized, or matches the desired output (map 0->1 and 1->2 maybe, and leave 0 to indicate uninitialized) and set the array element accordingly. If it doesn't match, then there's a conflict.

You could probably optimize this further by using a linked list to store the unique values of the array (every time array[v] is uninitialized), and then only check that those values are correct- avoiding redundant computations.

Even with this pruning, I suspect this will probably still be intractable. 2^100 is a huge number. You'll likely need to find a second way to check for "dead-end" branches, and/or an algorithmic breakthrough.


Parse Bloomberg Excel/CSV with Pandas DataFrame

You can probably do most of what you want in native Pandas.
It has functions for excel file IO that will probably take care of much of the date-munging.

If you want to carry on with the intermediate .csv file, the following should help.

Because you have an empty column and 3 commas between EHFI38 Index BBGID and EHFI139 Index BBGID, your data are in a slightly strange format.

import pandas as pd
from cStringIO import StringIO

data = """\
EHFI38 Index BBGID,                   , , EHFI139 Index BBGID,
Date              , PX_LAST           , , Date               , PX_LAST
1999-12-31        , 100.0000          , , 1999-12-31         , 100.0000
2000-01-31        , 100.1518          , , 2000-01-31         ,  98.6526
"""
df = pd.read_csv(StringIO(data), header=[0, 1], parse_dates=True)
df

There should be a way to sort out the strange indexing but I cannot easily work it out. Try searching for pandas multi-index and hierarchical data.


Implementing a new event in an old mootools version

return false
I'd consider this a bug. Returning false "kills" the event, meaning nothing else will happen. Just because your event handler shouldn't be called doesn't mean that's the end of the story.

For instance, if you have a regular, normal link in the element you're attaching the event listener to, then that link won't behave normally anymore. Clicking it will cause an event to bubble up and get handled by your addLiveEvent code, but if the event target (the link) doesn't match the selector, your code just defaults to returning false, effectively cancelling the click. So now your links don't work anymore. Oops.

Related to this: You should return whatever fn return, if fn gets called at all. Otherwise you have the opposite problem: You want to "cancel" a click, but the return value from the fn handler you define just gets ignored.

Here's an example (note that the 2nd link isn't cancelled by the code, as it should be, but may be cancelled by the browser, since snippets run inside an iframe, and are thus subject to security restrictions).

// OP's code
Element.implement({
  addLiveEvent: function(event, selector, fn) {
    this.addEvent(event, function(e) {
      var t = $(e.target);
      if (!t.match(selector)) {
        t = $(e.target.parentNode);
        if (!t.match(selector)) {
          t = $(e.target.parentNode.parentNode);
          if (!t.match(selector)) {
            return false;
          }
        }
      }
      fn.apply(t, [e]);
    }.bindWithEvent(this, selector, fn));
  }
});

// listen for clicks on a selector that won't match anything
$("case1").addLiveEvent("click", ".no-such-class", function() {});

// listen for link-clicks and try to cancel them
$("case2").addLiveEvent("click", ".cancel-click", function() {
  return false; // doesn't work
});

  A link that should take you to CodeReview (but doesn't)

  A link that should not navigate anywhere (but does)

  Or, well, it tries to navigate there but may be blocked because it's running inside an iframe. Check the console

fn.apply(t, [e])
There's no need for apply when it's just one argument; just use call
bindWithEvent
As far as I can tell, this isn't necessary. You're attaching an even listener to this, and then you're binding it to this. Makes no difference, as far as I can tell.

And yeah, those nested ifs aren't very nice. You're also limiting it to 2 ancestors, which seems like something that could easy prove too limited.

You could do a recursive solution, but it's much simpler to loop through an array instead.

I looked up the docs, and it seems there's a Element.getParents method you can use. So if you know the event.target, you can simply get an array of all its ancestors, and go through them. Of course, you'll want to stop if you hit the element that you originally added the live event listener to (otherwise you'll continue to check ancestors all the way to document), but that's a simple equality comparison.

Please note that it's been almost a decade since I last used Mootools, but this should work:

Element.implement({
  addLiveEvent: function(event, selector, fn) {
    this.addEvent(event, function(event) {
      var target = $(event.target), // get event target
          path = target.getParents(), // get ancestors
          i, l;

      // add the target to the list, so it gets checked first
      path.unshift(target);

      // loop through the list
      for (i = 0, l = path.length; i < l; i++) {
        if ($(path[i]).match(selector)) {
          return fn.call(path[i], event); // got a match
        }

        if (path[i] === this) {
          // we've reached the element we attached to, so stop
          break;
        }
      }
    });
  }
});

// Usage
$("container").addLiveEvent("click", ".clickable", function (event) {
  // here, `this` will refer to the matched element
  alert(this.title);
});
div {
  padding: 0.5em 1em 1em 1em;
  margin-top: 1em;
  border: 1px solid #000;
}

.clickable {
  background: green;
}

  Container (listener attached here)

    Random DIV

      Another DIV

        Click target

          Nested target


I feel like some of the code you haven't shown has a few leaky abstractions. For example:

using (var emailProvider = new ReceiveEmailProvider(emailAccount.Email,
            emailAccount.Password, emailAccount.Host, emailAccount.Port, emailAccount.Secure))

Every argument you send to RecieveEmailProvider comes from emailAccount. I would add an overload to it's constructor so that you could simply pass in an emailAccount. I think it greatly simplifies the code.

using (var emailProvider = new RecieveEmailProvider(emailAccount))

There's something similar happening here.

var dbEmail = AddNewEmail(email, emailAccount.Id, emailCounter);

// Add email to category
AddEmailToCategory(emailAccount.User.UserId,dbEmail);

Why does the client code go through all the trouble of spelling this out? AddEmailToCategory should know how to get the info it needs from an emailAccount so the dev doesn't have to.