JavaScript live grade Calculator Worth noting:
I cannot use any languages other than HTML5 and JavaScript (no JQuery!).
Grade calculator needs to update live.
Grade calculator needs to show a percentage grade based off score obtained/score possible AND a letter grade.
I've been at this for three days.  Please help me, and if possible, please explain why my code doesn't work, or why the solution does vs. mine, so that I can learn.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Grade Calculator</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"  href="styles.css">
    <link rel="javascript" href="script.js">

SAIT Grade Calculator

 Grade Calculator

        <input type="text" id= "enumerator" onkeyup="setGrades();" />
        <input type= "text" id = "denominator" onkeyup="setGrades();"/>

Your Percentage Grade

Your percentage grade is:

        <input type="text" id="percentgrade">

Your Letter Grade

Your letter grade is:

        <input type="text" id="letter">

© Nicole  2017

Firstly, there's an error in the code you've written which will prevent the calculator from working correctly:

document.getElementById('total').value = numbergrade;

You don't have an element with the ID of total so this will fail. I'm guessing you want to change this ID to percentgrade.

You also have invalid syntax here:

var percentscore =
if (numbergrade>=101) {

You need to assign a value to percentscore if you put an = sign after it. You're actually not using it in the rest of the code so you can get rid of the variable completely.

Next it can be cleaned up a bit. if (numbergrade >= 101) is a little unclear, compared to the shorter and simpler if (numbergrade > 100). The number 100 has meaning for a test because it's the maximum grade. The number 101 doesn't it's simply an invalid value. You could also extract this out into a variable to assign an even stronger meaning.

var MAX_OBTAINABLE = 100;

if (numbergrade > MAX_OBTAINABLE) {

Note the capital casing to indicate a constant. In more modern iterations of javascript you can actually create a true constant by using the const keyword rather than var or let

const MAX_OBTAINABLE = 100;

The next part which needs to be changed is your rendering of the values. Your percentgrade element is a textbox, so you should be setting it's value property. Currently you are setting the innerHTML which won't work.

document.getElementById("percentgrade").innerHTML =

Should become

document.getElementById("percentgrade").value =

The last part where you calculate the grade letter, could also do with some improvements. Whenever you find yourself using the same calculated more than once or twice, it becomes a good candidate to store in a variable. In this case, you've written document.getElementById('letter') many times. You can shorten in by extracting it into a variable before you start to determine the grade letter

var letterDisplay = document.getElementById('letter');

if (numbergrade >= 90) {
    letterDisplay.value = 'A+';
}
else if (89 >= numbergrade && numbergrade >= 85){
    letterDisplay.value = "A";
}

// ... etcetera

On this first line you've also attempted to assign the variable lettergrade to an if statement which is invalid syntax.

var lettergrade = if(numbergrade >= 90) {

You don't seem to be using this variable so you could get rid of this assignment. However, you could actually use that variable to make the above code even shorter. Starting off with the letter grade set to F we can do the following:

var letterDisplay = document.getElementById('letter');
var lettergrade = 'F';

if (numbergrade >= 90) {
    lettergrade = "A+";
}
else if (89 >= numbergrade && numbergrade >= 85) {
    lettergrade = "A";
}

// .... all the other if statements here.

else if (54 >= numbergrade && numbergrade >= 50) {
    lettergrade = 'D';
}

letterDisplay.value = lettergrade;

There are some more ways you could improve on this, but that's a few of the basic, for some slightly more advanced concepts like objects, functions and looping, take a look at this JS fiddle I created and have a play around


Multiple longest common subsequence (another algorithm) Here is the algorithm:

Input: a set of \$M\$ strings \$S=\{s_i\}\$ of length \$N\$ with alphabet \$\Sigma\$

Make an index of each string by chars.
Maintain a position \$p=(p_i)\$ where \$p_i\$ is an index into string \$s_i\$.
Set the initial position such that \$\forall i: p_i = |s_i|+1\$
(1-based indexing).

While chars left in strings do:

Select the next point among matches (same char in every string) by looping through the alphabet shared by the strings and picking the point with the minimal m-dimensional euclidean distance to the current point.

Is this \$O(|\Sigma|*M*\log(N))\$?

Here is (quite bad) sample python code:

from collections import defaultdict
import sys, bisect

def mlcs(strings):
    strings = list(set(strings))
    indexes = dict()

    sigma = set()
    for x in strings:
        sigma = sigma.union(set(x))

    for x in strings:
        tx = defaultdict(list)
        for i in range(len(x)):
            tx[x[i]] += [i]
        indexes[x] = tx

    def match(pos):
        s = True
        for i in range(len(strings)-1):
            x = strings[i]
            y = strings[i+1]
            s &= x[pos[x]] == y[pos[y]]
        return s

    def distance(ind1, ind2):
        d = 0
        for x in strings:
            d += (ind1[x] - ind2[x])**2
        return d

    def find(xs, y):
        i = bisect.bisect_right(xs, y)
        return i-1

    pos = {}
    for x in strings:
        pos[x] = len(x)
    result = ""
    loop = True
    while loop:
        for x in strings:
            if pos[x] < 0:
                loop = False
        if not loop:
            break
        indr = None
        dr = 12777216
        for c in sigma:
            ind = defaultdict(int)
            for x in strings:
                indxc = indexes[x][c]
                if indxc:
                    i = find(indxc, pos[x] - 1)
                    ind[x] = indxc[i]
                    if ind[x] > pos[x] - 1:
                        ind[x] = -128
                else:
                    ind[x] = -128
            d = distance(ind, pos)
            if d < dr:
                indr = ind
                dr = d
        x = strings[0]
        def notnegative(p):
            r = True
            for x in p.values():
                if x < 0:
                    r = False
            return r
        if notnegative(indr):
            result = x[indr[x]] + result
        pos = indr
    return result

def check(string, seq):
    i = 0
    j = 0
    while i < len(string) and j < len(seq):
        if string[i] == seq[j]:
            j += 1
        i += 1
    return len(seq) - j

def checkall(strings, seq):
    for x in strings:
        a = check(x, seq)
        if not a == 0:
            print(x, seq, a)
            return False
    return True

strings = []
sigma = ["a", "b", "c", "d"]
#sigma = ["a", "b"]
sigmax = ["e", "f", "g"]
import random
Nx = 67
N = 128
M = 13 # Number of strings
x = ""
for i in range(Nx):
    x += random.choice(sigmax)
for i in range(M):
    string = ""
    for j in range(N):
        string += random.choice(sigma)
    indexes = list(range(N))
    random.shuffle(indexes)
    indexes = sorted(indexes[:len(x)])
    for j in range(len(x)):
        string = string[:indexes[j]]+x[j]+string[indexes[j]+1:]
    strings += [string]

#strings = ["abbab", "ababa", "abbba"]
#strings = ["abab", "baba", "abaa"]
#strings = ["bacda", "abcde", "decac"]
#strings = ["babbabbb", "bbbaabaa", "abbbabab", "abbababa"]
print("Strings:", strings)
l = mlcs(strings)
print("Lcs:", l, len(l), checkall(strings, l))

1. Analysis

This is a greedy algorithm: at each step it prefixes one letter to the result, choosing the letter than minimizes the change in the indexes into the strings.

The main loop of the algorithm adds one letter to the result, so can execute at most \$ N \$ times. Each iteration of the loop considers each letter in the alphabet \$ Σ \$, and each of the \$ M \$ strings, and searches (by bisection) the list of occurrences of that letter in that string, taking \$ O(\log N) \$. Thus the overall runtime is \$ O(\left|Σ\right|NM\log N) \$. (You missed a factor of \$ N \$.)

This is polynomial time, but the longest common subsequence problem is NP-hard, so the algorithm does not solve the problem in the general case.

Here's a simple case where mlcs returns the wrong result:

>>> mlcs(('ab', 'aba'))
'a'

2. Review

There's no docstring for mlcs. What does this function do? How do I call it? What does it return?
The case of no strings is not handled:

>>> mlcs(())
Traceback (most recent call last):
    ...
IndexError: list index out of range

This should probably be a ValueError, like max(()).
The case where all strings are empty is not handled:

>>> mlcs(('', ''))
Traceback (most recent call last):
    ....
AttributeError: 'NoneType' object has no attribute 'values'

This should return the empty string.
The code takes the union of the letters in the strings. But the only letters that can appear in the longest common subsequence are those letters that appear in all the strings, so the intersection is needed here here, not the union.
The code accumulates a list by repeated addition:

for i in range(len(x)):
    tx[x[i]] += [i]

This wastes space because Python might have to allocate a new list each time and copy the old list across. It's more efficient to accumulate a list using the append method.
Iteration over the indexes of a sequence can often be simplified using enumerate, for example the loop above can be written:

for i, letter in enumerate(x):
    tx[letter].append(i)

pos is a dictionary mapping input string to the current position in that string in the search. Since strings is a list of strings, it would make more sense for pos to be a list of positions, so that pos[i] was the current position in strings[i]. Then match simplifies to:

def match(pos):
    c = strings[0][pos[0]]
    return all(c == s[p] for s, p in zip(strings, pos))

The function match is not called, so could be omitted.
The initialization of pos:

pos = {}
for x in strings:
    pos[x] = len(x)

Could be written as a dictionary comprehension:

pos = {s: len(s) for s in strings}

or, if you follow my advice above about making pos into a list, a list comprehension:

pos = [len(s) for s in strings]

This loop:

for x in strings:
    if pos[x] < 0:
        loop = False
if not loop:
    break

always tests all elements of pos, so that even if the first one is negative, it will go on and uselessly test all the others. It would be better to fail as soon as possible:

if any(pos[s] < 0 for s in strings):
    break

or, if you follow my advice above about making pos into a list:

if any(p < 0 for p in pos):
    break

Note that the change discussed above gets rid of the only assignment to loop, so that we have:

loop = True
while loop:
    if any(p < 0 for p in pos):
        break

which simplifies to:

while all(p >= 0 for p in pos):

Instead of setting ind[x] and then setting it back to the default value based on a condition:

ind = defaultdict(int)
for x in strings:
    indxc = indexes[x][c]
    if indxc:
        i = find(indxc, pos[x] - 1)
        ind[x] = indxc[i]
        if ind[x] > pos[x] - 1:
            ind[x] = -128
    else:
        ind[x] = -128

initialize it to the default value and set it only if the condition does not apply:

ind = defaultdict(lambda:-128)
for x in strings:
    indxc = indexes[x][c]
    if indxc:
        i = find(indxc, pos[x] - 1)
        if indxc[i] <= pos[x] - 1:
            ind[x] = indxc[i]

Just as I recommended making pos into a list, I also recommend making ind into a list. If you did, then distance would become:

def distance(v, w):
    return sum((i - j)**2 for i, j in zip(v, w)):

and since this is only called from one place, you could easily inline it.
Similarly, indexes would be more conveniently organized so that indexes[letter][i] is a list of the indexes of the occurrences of letter in strings[i].
A magic number like this:

dr = 12777216

needs to be explained. It looks to me as though this needs to be some number larger than the biggest possible distance between pos and ind. But for very long strings (tens of thousands of letters), this won't be the case. It would be more reliable to start at infinity:

min_distance = float('inf')

But it would be better to reorganize the code to call the built-in min function, and catch the ValueError that is raised when there are no elements. See the revised code in §3 below for how this is done.
Similarly, the magic number -128 needs explanation. The idea seems to be that this is so far away from the index of any character in the string that the distance will be large and the candidate will be rejected. But is this really true? If the strings are longer than 128 characters then a candidate might be included erroneously. It would be better to reject candidates where bisect_right returns 0.
The handling of the case where bisect_right returns 0 seems incorrect to me. In this case find returns -1, and then this leads to the assignment ind[x] = indxc[-1] which succeeds (getting the last element in indxc) but this is wrong.

3. Revised code

from bisect import bisect

def mlcs(strings):
    """Return a long common subsequence of the strings.
    Uses a greedy algorithm, so the result is not necessarily the
    longest common subsequence.

    """
    if not strings:
        raise ValueError("mlcs() argument is an empty sequence")
    strings = list(set(strings)) # deduplicate
    alphabet = set.intersection(*(set(s) for s in strings))

    # indexes[letter][i] is list of indexes of letter in strings[i].
    indexes = {letter:[[] for _ in strings] for letter in alphabet}
    for i, s in enumerate(strings):
        for j, letter in enumerate(s):
            if letter in alphabet:
                indexes[letter][i].append(j)

    # pos[i] is current position of search in strings[i].
    pos = [len(s) for s in strings]

    # Generate candidate positions for next step in search.
    def candidates():
        for letter, letter_indexes in indexes.items():
            distance, candidate = 0, []
            for ind, p in zip(letter_indexes, pos):
                i = bisect.bisect_right(ind, p - 1) - 1
                q = ind[i]
                if i < 0 or q > p - 1:
                    break
                candidate.append(q)
                distance += (p - q)**2
            else:
                yield distance, letter, candidate

    result = []
    while True:
        try:
            # Choose the closest candidate position, if any.
            _, letter, pos = min(candidates())
        except ValueError:
            return ''.join(reversed(result))
        result.append(letter)


Arabic to Greek numeral converter, 1 - 10 One of the things that's straight-forward in JavaScript is Unicode support. If you want to return ϝ (lowercase digamma, not a simple f), you simply tell it to do so. No look-up, conversion or unreadable Unicode codes required.

I want to build a translator between Arabic and Greek numerals. Since my projects tend to take forever to complete, I decided to post what I have instead of waiting till it's finished. The code currently supports 1 - 10 and translates them to the Unicode Greek equivalent.

I wrote it the most straight-forward way I could think of. It's not necessarily the best way.

function arabicToGreek(input) {
    'use strict';
    switch (input) {
    case 1:
        return "α";
    case 2:
        return "β";
    case 3:
        return "γ";
    case 4:
        return "δ";
    case 5:
        return "ε";
    case 6:
        return "ϝ";
    case 7:
        return "ζ";
    case 8:
        return "η";
    case 9:
        return "θ";
    case 10:
        return "ι";
    }
    return "";
}

Usage:

arabicToGreek(4);
arabicToGreek(10);

Output:

δ
ι

Run it at repl.it

I'm aware ϝ (6) should possibly be written as ϛ. I'm also aware I may or may not need to include diacritics.

I'm especially looking for a review on the usual suspects: naming, idiomatic style and modularity. All other advice is welcome as well.

Reviewing your current structure: your return ""; could be improved: it should / could be inside the switch statement as a default case.

It's better to use an object here, as later you can extend it without having to spend pointless LoCs on cases and breaking.

function arabicToGreek(input) {
    'use strict';
    var greek = {
        1: "α",
        2: "β",
        3: "γ",
        4: "δ",
        5: "ε",
        6: "ϝ",
        7: "ζ",
        8: "η",
        9: "θ",
        10: "ι"
    };
    //
}

Then, add greek.hasOwnProperty to check that your string is a valid object property, in which case that it isn't, you can throw an error.

if (!greek.hasOwnProperty(input)){
    throw new Error("input not a valid integer representing a character");
}

This also means you can store the greek characters and potentially other languages in an external JSON document.


Flatten a tree to a collection of nodes I have implemented simple tree class as follows:
public class MoveTreeNode
{
    public MoveTreeNode Parent
    {
        get;
        set;
    }

    private List<MoveTreeNode> children = new List<MoveTreeNode>();

    public IEnumerable<MoveTreeNode> Children
    {
        get
        {
            return children;
        }
    }

    public void Add(MoveTreeNode child)
    {
        child.Parent = this;
        children.Add(child);
    }

    private IEnumerable<MoveTreeNode> Flatten()
    {
        yield return this;

        foreach(var child in Children.Select(x=> x.Flatten()).SelectMany(x=>x))
        {
            yield return child;
        }
    }
}

This works, but I have concerns about the following line:
foreach(var child in Children.Select(x=> x.Flatten()).SelectMany(x=>x))
Since I'm using yield I'd prefer to gain some of the benefits of lazy evaluation but I fear that while each child of the root will be lazily evaluated, the childrens' children, etc will be evaluated at once when their parents are evaluated.
Is there some way I can refactor this to make the most of lazy evaluation, or am I better off leaving it this way?

I think you want to flatten each child in turn:

private IEnumerable<MoveTreeNode> Flatten()
{
    yield return this;

    foreach (var node in Children.SelectMany(child => child.Flatten()))
    {
        yield return node;
    }
}

That way you won't flatten the whole tree first.

Edit:

It's more difficult to talk about things so let's look at some code. SelectMany is roughly equal to:

public static IEnumerable<TOut> SelectMany<T, TOut>(this IEnumerable<T> source, Func<T, IEnumerable<TOut>> selector)
{
    foreach (var item in source)
    {
        foreach (var subItem in selector(item))
        {
            yield return subItem;
        }
    }
}

So as you can see, we will definitely get all of the nodes and if you stop iterating before the end (e.g. by calling .First()) you will only call Flatten() on a single child.


Reverse chars of each word in a string An algorithm to reverse characters of each word in a sentence.
What would be your concerns regarding the following solution?

Example input: "I love New York"
output: "I evol weN kroY"

public class Main {
    public static void main(String[] args) throws IOException {
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        final String words = bufferedReader.readLine().trim();
        final char[] reversedWord = reverseWords(words.toCharArray());

        bufferedWriter.write(reversedWord);

        bufferedReader.close();
        bufferedWriter.close();
    }

    private static char[] reverseWords(char[] input) {
        int startIndex = 0;
        int endIndex = 0;
        while (endIndex < input.length) {
            final boolean isLastWord = endIndex == input.length - 1;
            if (input[endIndex] == ' ' || isLastWord) {
                if (isLastWord) {
                    endIndex++;
                }
                reverseWord(input, startIndex, endIndex);
                startIndex = ++endIndex;
            } else {
                endIndex++;
            }
        }
        return input;
    }

    private static void reverseWord(char[] word, int startIndex, int endIndexExclusive) {
        final int wordLength = (endIndexExclusive - startIndex);
        for (int i = 0; i < wordLength/2; i++) {
            final char temp = word[startIndex + i];
            word[startIndex + i] = word[endIndexExclusive - i - 1];
            word[endIndexExclusive - i - 1] = temp;
        }
    }
}

Unit tests would be like:

public class QuestionOneTest {
    @Test
    public static should_reverse_chars() {
        // given
        final String input = "I love New York";

        // when
        final char[] reversed = QuestionOne.reverseWords(input.toCharArray());

        // then
        assert String.copyValueOf(reversed).equals("I evol weN kroY");
    }
}

If you don't want to reinvent the wheel, you can implement a very short and simple solution using java.util:

public class Main {
    public static void main(final String[] args) throws IOException {
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        final String line = bufferedReader.readLine().trim();
        List<String> words = Arrays.asList(line.split("\\s+"));

        String reversedWords = reverseWords(words);

        bufferedWriter.write(reversedWords.toCharArray());

        bufferedReader.close();
        bufferedWriter.close();
    }

    private static String reverseWords(final List<String> words) {
        return words.stream().map(word -> reverseWord(word)).collect(Collectors.joining(" "));
    }

    private static String reverseWord(final String word) {
        return new StringBuilder(word).reverse().toString();
    }
}


Optimize option pricing code I am new to Python and am trying to optimize the following code:

import sys
import numpy as np

def LSMPut(T, r, sigma, K, S0, TimeSteps, Paths, k):
    dt = T/TimeSteps
    t = np.arange(0, T+dt, dt).tolist()

    z=[np.random.standard_normal() for _ in range(Paths)]
    w = (r-sigma**2/2)*T + sigma*np.sqrt(T)*np.array(z)

    S = S0*np.exp(np.array(w))
    P=np.maximum(K-np.array(S),0)

    for i in range(TimeSteps-1, -1, -1):
        z=[np.random.standard_normal() for _ in range(Paths)]
        w = t[i]*np.array(w)/t[i+1] + sigma*np.sqrt(dt*t[i]/t[i+1])*np.array(z)

        S = S0*np.exp(np.array(w))
        itmPaths = [index for index,value in enumerate(K-np.array(S)) if value > 0]

        itmS = S[itmPaths]
        Pt = K - np.array(itmS)

        itmDiscP = P[itmPaths]*np.exp(-r*dt)

        A = BasisFunct(itmS, k)
        beta = np.linalg.lstsq(A,itmDiscP)[0]
        C = np.dot(A,beta)

        exPaths = [itmPaths[i] for i, value in enumerate(zip(Pt, C)) if value[0] > value[1]]
        restPaths = np.setdiff1d(np.arange(0, Paths-1, 1).tolist(), exPaths) # Rest of the paths

        P[exPaths] = [Pt[i] for i, value in enumerate(zip(Pt, C)) if value[0] > value[1]]
        P[restPaths] = np.array(P[restPaths])*np.exp(-r*dt)

        u=np.mean(P*np.exp(-r*dt))

    return u

def BasisFunct(X, k):
    Ones=[1 for _ in range(len(X))]
    if k == 1:
        A = np.column_stack((Ones,1 - np.array(X)))
    elif k == 2:
        A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2)))
    elif k == 3:
        A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3)))
    elif k == 4:
        A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3),1/24*(24 - 96*np.array(X) + 72*np.array(X)**2 - 16*np.array(X)**3 + np.array(X)**4)))
    elif k == 5:
        A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3),1/24*(24 - 96*np.array(X) + 72*np.array(X)**2 - 16*np.array(X)**3 + np.array(X)**4),1/120*(120-600*np.array(X)+600*np.array(X)**2-200*np.array(X)**3+25*np.array(X)**4-np.array(X)**5)))
    else:
            sys.exit("Too many basis functions requested")
    return A

print(LSMPut(1, 0.06, 0.15, 100, 90, 20, 1000000, 5))

The purpose of the code is to calculate the price of an American put option. The time to execute if Paths > 1,000,000 takes a long time, especially if I perform a sensitivity analysis. I would like to find out if there is any way for me to optimize the code or accelerate the processing time. Thank you.

I changed the main part of the script to:

from time import time
start = time()
val = LSMPut(1, 0.06, 0.15, 100, 90, 20, 40_000, 5)
print(f'Done in {time() - start:.3} seconds')
print(val)

The point is that Python will print how long the calculation took to
run. Before modifications, the script takes 3.05 seconds to run on my
computer.

Now I can modify lsmput (I renamed LSMPut and some other functions
and variables because they names shouldn't contain capital letters
according to the Python style guide) and see which changes makes it
run faster.

Here follows the changes that impacted the runtime the most. Changing

z=np.array([np.random.standard_normal() for _ in range(paths)])

to

z = np.random.standard_normal(paths)

brings the runtime down to 2.43 seconds. Changing

ones=[1 for _ in range(len(X))]

to

ones = np.ones(len(X))

reduces the runtime further to 2.21 seconds. Precalculating the powers
of X in basis_funct like this

X2 = X**2
X3 = X**3
X4 = X**4
X5 = X**5
...
A = np.column_stack((ones, 1 - X, 1/2 * (2 - 4*X + X2), ...

saves an additional 100 milliseconds. Changing

itmPaths = [index for index,value in enumerate(K - S) if value > 0]

to

itmPaths = np.nonzero((K - S) > 0)[0]

brings the runtime down to about 1.60 seconds. I think you see the
pattern now; anytime you loop over a numpy array there's a numpy
builtin function to do the job better and faster.

Then in the calculation of rest_paths:

rest_paths = np.setdiff1d(np.arange(0, paths - 1, 1), exPaths)

Is the paths - 1 intentional here? Looks like a bug to me. Assuming
it is a bug, updating P can be done more efficiently, like this:

mask = np.zeros(P.shape, dtype = bool)
...
mask.fill(False)
mask[itmPaths[Pt > C]] = True

P[mask] = Pt[Pt > C]
P[~mask] *= e_r_dt

Final code

The modified code runs in about 420 milliseconds on my computer. Note
that I have removed all branches except for the k == 5 one from the
basis_funct function. It should be straightforward for you to add it
back.

import sys
import numpy as np

# Uncomment this line during development to always get the same random
# numbers.
# np.random.seed(1234)

def lsmput(T, r, sigma, K, S0, TimeSteps, paths, k):
    dt = T/TimeSteps
    t = np.arange(0, T+dt, dt).tolist()

    z = np.random.standard_normal(paths)
    w = (r-sigma**2/2)*T + sigma*np.sqrt(T)*z

    S = S0*np.exp(w)
    P = np.maximum(K - S,0)

    e_r_dt = np.exp(-r * dt)
    mask = np.zeros(P.shape, dtype = bool)
    for i in range(TimeSteps-1, -1, -1):
        z = np.random.standard_normal(paths)
        w = t[i]*w/t[i+1] + sigma*np.sqrt(dt*t[i]/t[i+1])*z

        S = S0 * np.exp(w)
        itmPaths = np.nonzero(K > S)[0]
        itmS = S[itmPaths]
        Pt = K - itmS

        itmDiscP = P[itmPaths] * e_r_dt

        A = basis_funct(itmS, k)
        beta = np.linalg.lstsq(A, itmDiscP)[0]
        C = np.dot(A, beta)

        mask.fill(False)
        mask[itmPaths[Pt > C]] = True

        P[mask] = Pt[Pt > C]
        P[~mask] *= e_r_dt
    return np.mean(P * e_r_dt)

def basis_funct(X, k):
    ones = np.ones(len(X))
    assert k == 5
    X2 = X**2
    X3 = X**3
    X4 = X**4
    X5 = X**5
    A = np.column_stack((ones, 1 - X,
                         1/2 * (2 - 4*X + X2),
                         1/6 * (6 - 18*X + 9*X2 - X3),
                         1/24 * (24 - 96*X + 72*X2 - 16*X3 + X4),
                         1/120 * (120 - 600*X + 600*X2 - 200*X3 + 25*X4 - X5)))
    return A

from time import time
start = time()
val = lsmput(1, 0.06, 0.15, 100, 90, 20, 40_000, 5)
print(f'Done in {time() - start:.3} seconds')
print(val)


Min Heap implementation with Dijkstra's algorithm I am implementing Dijkstra's Algorithm using Min Heap to speed up the code.

For a small number of nodes, the code is really running very fast. But for a large number of nodes, my code is throwing java.lang.OutOfMemoryError: Java heap space exception. My Min heap implementation is based on the code, given here in C++. I changed this code into Java.

Below is my min heap code (I am not putting Dijkstra's algorithm code, as it is same as described in the above link).

public class Heap {
    private static int[] data;
    private static int[] index;
    public static int[] cost;
    public static boolean[] eval;
    private static int size;

    public Heap(int s) {
        data = new int[s];
        index = new int[s];
        cost = new int[s];
        eval = new boolean[s];
    }

    public void init(int s) {
        for (int i = 0; i < s; i++) {
            index[i] = -1;
            eval[i] = false;
        }
        size = 0;
    }

    public boolean isEmpty() {
        return (size == 0);
    }

    private void shiftUp(int i) {
        int j;
        while (i > 0) {
            j = (i - 1) / 2;
            if (cost[data[i]] < cost[data[j]]) {

                int temp = index[data[i]];
                index[data[i]] = index[data[j]];
                index[data[j]] = temp;

                temp = data[i];
                data[i] = data[j];
                data[j] = temp;
                i = j;
            } else
                break;
        }
    }

    private void shiftDown(int i) {
        int j, k;
        while (2 * i + 1 < size) {
            j = 2 * i + 1;
            k = j + 1;
            if (k < size && cost[data[k]] < cost[data[j]]
                    && cost[data[k]] < cost[data[i]]) {

                int temp = index[data[k]];
                index[data[k]] = index[data[i]];
                index[data[i]] = temp;

                temp = data[k];
                data[k] = data[i];
                data[i] = temp;

                i = k;
            } else if (cost[data[j]] < cost[data[i]]) {

                int temp = index[data[j]];
                index[data[j]] = index[data[i]];
                index[data[i]] = temp;

                temp = data[j];
                data[j] = data[i];
                data[i] = temp;

                i = j;
            } else
                break;
        }
    }

    public int pop() {
        int res = data[0];
        data[0] = data[size - 1];
        index[data[0]] = 0;
        size--;
        shiftDown(0);
        return res;
    }

    public void push(int x, int c) {
        if (index[x] == -1) {
            cost[x] = c;
            data[size] = x;
            index[x] = size;
            size++;
            shiftUp(index[x]);
        } else {
            if (c < cost[x]) {
                cost[x] = c;
                shiftUp(index[x]);
                shiftDown(index[x]);
            }
        }
    }
}

As far as the code is concerned, it is working fine for small s. How can I optimize this code for a large value of nodes?

The only memory that you are allocating is the four arrays: data, index, cost, and eval. That means that if you are running out of memory then you probably need to allocate more memory. An array of primitives is just about as compact a structure as you're going to get.

You don't say what  you mean by "large value of nodes", but you can figure that you will be allocating approximately 13 bytes (less because the boolean array will be packed) times the value of s passed into the constructor. I think the default heap is 64 MB, and some of that is allocated to other things, but you should be able to allocate at something in the millions range.

I added this main to your code and it showed that an array of 100,000 entries used just over 1.2 MB.

public static void main(String[] args) {
    Runtime r = Runtime.getRuntime();

    long t = r.totalMemory();
    long f = r.freeMemory();
    System.out.println("[Heap.main] " + t + "," + f);

    Heap h = new Heap(100000);
    h.init(0);
    h.push(1,2);
    System.out.println("[Heap.main] isEmpty returns: " + h.isEmpty());

    t = r.totalMemory();
    f = r.freeMemory();
    System.out.println("[Heap.main] " + t + "," + f);
}


3n + 1 problem optimization The problem can be viewed here, since it's styled. I don't think I should just copy and paste.

I implemented recessive function and dynamic programming to solve it. It can successfully passed UVa Judge with a score of 612ms, but it's not fast enough for this site. Which test my code against 200000 lines of input, and giving only 2s.

#include <cstdio>
#include <iostream>

int cycleLength(long long int);

int cycleLengthResult[1000001];

int main(int argc, char *argv[])
{
    int i = 0, j = 0, cur = 0, max = 0, k = 0, s = 0;
    for (i = 1 ; i < 1000001 ; ++ i ) cycleLength(i);

    while ( scanf("%d%d", &i, &j) != EOF )
    {
        printf("%d %d ", i, j);
        if ( i > j )
        {
            s = i;
            i = j;
            j = s;
        }
        max = 0;
        for ( k = i ; k <= j ; ++ k )
        {
            cur = cycleLengthResult[k];
            if (cur > max) max = cur;
        }
        printf("%d\n", max);
    }

    return 0;
}

int cycleLength(long long int arg)
{
    if ( arg > 1000000 )
    {
        if (!(arg & 1))
            return 1 + cycleLength(arg/2);
        else
            return 1 + cycleLength(arg*3+1);
    }
    if (!cycleLengthResult[arg])
    {
        int valueForArg = 0;
        if (arg == 1)
            valueForArg = 1;
        else if (!(arg & 1))
            valueForArg = 1 + cycleLength(arg/2);
        else
            valueForArg = 1 + cycleLength(arg*3+1);

        cycleLengthResult[arg] = valueForArg;
    }
    return cycleLengthResult[arg];
}

I took an elective last semester in which we had to do UVa questions.  Just dug up my old UVa 100 submission, and I have a few suggestions for speed (mine was accepted in 200 ms, though I suspect it could be optimized a ton more).

The main thing I see is that you shouldn't use recursion.  Due to the setup cost of calling functions, iteration is going to be way faster (in some situations the same stack frame can be reused, but I doubt that optimization is being done in your code).

Though that is my main suggestion, there are a few very minor algorithmic optimizations that can be noted mathematically.

t(n) = 1      if n is 1
     = 3n + 1 if n is odd
     = n / 2  if n is even

c(n) = number of times t(n) will happen
(terrible math syntax here, but erm... go with it)

Now, the approach I took was to build a table bottom up.  Basically an array like int m[1000001].

Then a loop like:

for (int i = 1; i <= 1000000; ++i) {
    if (i % 2 == 0) {
        //We know that i / 2 must already be set, so we can just do a constant time look up
        //(your code already does this implicitly through the recursion)
        m[i] = 1 + m[i / 2];
    } else {
        m[i] = cycleLength(i);
    }
}

Nothing special about this loop; it's just the iterative form of your code.

There is an odd little optimization you can make though:

if (i % 2 == 0) {
    m[i] = 1 + m[i/2];
} else if (i % 8 == 5) {
    m[i] = 4 + m[3 * ((i - 5) / 8) + 2];
} else {
    m[i] = cycleLength(i);
}

The theory here is that for any j < i, you know that m[j] is populated.  Thus, if you can do some manipulation to get m[i] = c + m[f(i)] such that f(i) < i you can do a constant time look up rather than the potentially enormously expensive cycleLength call.

It's the same concept in the 1 + m[i / 2] situation, just weirder.

If i mod 8 = 5, then by definition, i = 8j + 5 for some integer j.

i = 8j + 5 = 2k + 1 with k = 4j + 2 thus i is odd.

So we follow the pattern:

8j + 5 -> 24j + 16 -> 12j + 8 -> 6j + 4 -> 3j + 2

Note the crucial part here: 3j + 2 < 8j + 5.  This means that we can define m[i] in terms of 4 + m[3 * ((i - 5) / 8) + 2].

I'm too lazy to get out a pad of paper, but I suspect that more arithmetic trickery like this is possible (the weird situation of i mod 8 = 5 is something that the professor pointed out).  Even without it, an iterative approach is easily fast enough to be accepted by UVa's online judge, but it does make a surprising 48 ms difference with my program.


Errors with binary search in Haskell I just learned about Maybe in Haskell, so I decided to try to use it with a binary search.

Here's the function:

binarySearch :: (Ord a, Int b) => [a] -> a -> b -> b -> Maybe b

binarySearch l e beg last
 | lookat < e = (binarySearch l e i last)
 | lookat > e = (binarySearch l e beg i)
 | lookat == e = Just i
 | otherwise = Nothing
 where i = floor ((beg+last)/2)
       lookat = l !! i

l is a list, e is the element of interest, beg is the start of
the section of interest and end is the end of said section. The error I am getting is:

BinarySearch.hs:1:25:
    `Int' is applied to too many type arguments
    In the type signature for `binarySearch':
      binarySearch :: (Ord a, Int b) => [a] -> a -> b -> b -> Maybe b

I have tried a few other things including:

binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b

Yielding the error:

BinarySearch.hs:6:23:
    Could not deduce (b ~ Int)
    from the context (Ord a)
      bound by the type signature for
                 binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b
      at BinarySearch.hs:(3,1)-(9,22)
      `b' is a rigid type variable bound by
          the type signature for
            binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b
          at BinarySearch.hs:3:1
    In the first argument of `Just', namely `i'
    In the expression: Just i
    In an equation for `binarySearch':
        binarySearch l e beg last
          | lookat < e = (binarySearch l e i last)
          | lookat > e = (binarySearch l e beg i)
          | lookat == e = Just i
          | otherwise = Nothing
          where
              i = floor ((beg + last) / 2)
              lookat = l !! i

I am not sure what I am doing wrong. Any corrections or comments on style or solution would be highly appreciated.

You don't want Int b, you just want Int:

Ord a => [a] -> a -> Int -> Int -> Maybe Int


Filtering a collection by an async result I'm trying to do something like this:

var loudDogs = dogs.Where(async d => await d.IsYappyAsync);

The "IsYappyAsync" property would return a Task<bool>.

Obviously this isn't supported, so instead I've built an extension method called WhereAsync.

public static async Task<IEnumerable<T>> WhereAsync<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)
{
    var results = new List<T>();
    var tasks = new List<Task<bool>>();

    foreach (var item in items)
    {
        var task = predicate.Invoke(item);
        tasks.Add(task);
    }

    var predicateResults = await Task.WhenAll<bool>(tasks);

    var counter = 0;
    foreach (var item in items)
    {
        var predicateResult = predicateResults.ElementAt(counter);

        if (predicateResult)
            results.Add(item);

        counter++;
    }

    return results.AsEnumerable();
}

This probably isn't the best approach, but I'm at a loss for something better. Any thoughts?

There are several ways to achieve what you're after and it depends on whether you want the results drip fed to you as they're available or whether you're happy to have them all in one bang.
The way you've implemented your method gives it all in one bang - which is fine.

A shorter implementation could be

public static async Task<IEnumerable<T>> WhereAsync2<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)
{
    var itemTaskList = items.Select(item=> new {Item = item, PredTask = predicate.Invoke(item)}).ToList();
    await Task.WhenAll(itemTaskList.Select(x=>x.PredTask));
    return itemTaskList.Where(x=>x.PredTask.Result).Select(x=>x.Item);
}

It builds a list of an anonymous type where the type contains the item and the Task.
It then waits for all of the tasks to complete.
It then goes through that list from (1) and picks out the items that had a true result from the Task.

The other advantage is that you get rid of all of that counter and ElementAt() stuff.  Either way still builds a complete List for the items in the given Enumerable...

Aside: You could investigate something like Rx if you wanted the results via an IObservable<T> instead.  The result wouldn't even be async Task - it would just be an IObservable.


Removing Dicts with Null values from Only the End of a List Given input such as:

foos = [
    [],
    [{'a': 1}],
    [{'a': 1}, {'a': 2}],
    [{'a': 1}, {'a': 2}, {'a': None}],
    [{'a': 1}, {'a': 2}, {'a': None}, {'a': None}],
    [{'a': 1}, {'a': None}, {'a': 2}],
    [{'a': 1}, {'a': None}, {'a': 2},  {'a': None}],
    [{'a': 1}, {'a': None}, {'a': 2},  {'a': None}, {'a': None}],
]

I want a function remove_empty_end_lines that takes a list of dicts and will remove all dicts with null values that only appear at the end of the list, not in between.

for foo in foos:
    print(foo)
    print(remove_empty_end_lines(foo))
    print('\n')

[]
[]

[{'a': 1}]
[{'a': 1}]

[{'a': 1}, {'a': 2}]
[{'a': 1}, {'a': 2}]

[{'a': 1}, {'a': 2}, {'a': None}]
[{'a': 1}, {'a': 2}]

[{'a': 1}, {'a': 2}, {'a': None}, {'a': None}]
[{'a': 1}, {'a': 2}]

[{'a': 1}, {'a': None}, {'a': 2}]
[{'a': 1}, {'a': None}, {'a': 2}]

[{'a': 1}, {'a': None}, {'a': 2}, {'a': None}]
[{'a': 1}, {'a': None}, {'a': 2}]

[{'a': 1}, {'a': None}, {'a': 2}, {'a': None}, {'a': None}]
[{'a': 1}, {'a': None}, {'a': 2}]

My final solution is:

def remove_empty_end_lines(lst):
    i = next(
        (
            i for i, dct in enumerate(reversed(lst))
            if any(v is not None for v in dct.values())
         ),
        len(lst)
    )

    return lst[: len(lst) - i]

I'm not going for code golf, rather for performance and readability.

In the input I've listed above, the dicts are always a length of one, butin reality the lengths can be any amount. The lengths of each dict within a list will always be the same.

Some suggestions:

You are using i both inside your list comprehension and outside. This makes the code harder to follow than if the variables were differently named. For example, you could think of the outer i as the count of matching (that is, all None values) dictionaries at the end of the list.
Hungarian notation abbreviations like lst and dct don't tell me anything about what the variables actually are. In an actual application this should be possible, but more context would be needed for that.
You say "remove all dicts with null values", but you neither specify nor test what happens with a dictionary having some None values and some non-None values at the end of the list. As far as I can tell from your implementation you remove only entries with all None values, but it's not clear whether this is the intention.
I would pull out the tuple passed to next as a separate variable for clarity.


Is any further optimization possible? (Codeforces) I am an average coder trying to improve my Python by doing solved problems in it.

One of the problem I did is this, here is the code I tried which
I have based on the official solution:

def area(A, B, C):
  return float((x[B] - x[A])*(y[C] - y[B]) - (y[B] - y[A])*(x[C] -x[B]))/2
x, y = {}, {}
n = int(raw_input())
for i in xrange(n):
  arr = raw_input().split()
  x[i] , y[i] = int(arr[0]), int(arr[1])

maxarea = 0
for i in xrange(n):
  for j in xrange(i+1, n):
    maxminus, maxplus = -1, -1
    for k in xrange(n):
      if k != i and k != j:
        a = area(i,j,k)
        if(a<0):
          maxminus = max(maxminus, -a)
        else:
          maxplus = max(maxplus, a)
    if maxplus >= 0 and maxminus >=0:
      maxarea = max(maxarea, (maxplus+maxminus))
print maxarea

The code is still giving me TLE on test case 7.
Can anybody suggest further optimization?

Firstly you need to put all the global statements into a function because of Python code runs faster in a function compared to global scope.

You don't need the arr variable. You can just use

x[i], y[i] = map(int, raw_input().split())

instead of using the two lines. map uses the function(1st argument) on each of the outputs from the second argument.

After placing the global statements into a function then instead of passing i, j, k you would need to pass the values directly.

I'll look up the algorithm and see if there are other changes that can be made.


Syllable-counting function I was working on a syllable counting function for a text editor(this function is accurate enough). However, I would like to know if it is possible to optimize it, it already separated into another thread, but I would like to know if there is any kind of optimization that I can do with it to make it more efficient.

private static int SyllableCount(string word)
{
    word = word.ToLower().Trim();
    int count = System.Text.RegularExpressions.Regex.Matches(word, "[aeiouy]+").Count;
    if ((word.EndsWith("e") || (word.EndsWith("es") || word.EndsWith("ed"))) && !word.EndsWith("le"))
        count--;
    return count;
}

It uses regular expressions, something that this source mentions having poor performance in .net applications, is that the case? And if not, are there any other optimizations that I can perform on it?

Anyway, it does not lag much, but my application does use around four threads already, just for keeping up with various text entry statistics, so now I'm just trying to shave the fat off so to speak.

Well, Regex is going to be slow, by virtue of it being a very powerful, flexible engine that can't assume you'll never want to do something that a regex can achieve. This particular regex pattern is pretty simple (no lookbehinds, etc) but there will be some overhead inherent in Regex use which you can trim. You can iterate through the string and count occurrences of groups of vowels in linear time with very little overhead.

private static int SyllableCount(string word)
{
    word = word.ToLower().Trim();
    bool lastWasVowel;
    var vowels = new []{'a','e','i','o','u','y'};
    int count;

    //a string is an IEnumerable<char>; convenient.
    foreach(var c in word)
    {
       if(vowels.Contains(c))
       {
          if(!lastWasVowel)
             count++;
          lastWasVowel = true;
       }
       else
          lastWasVowel = false;
    }

    if ((word.EndsWith("e") || (word.EndsWith("es") || word.EndsWith("ed")))
          && !word.EndsWith("le"))
        count--;

    return count;
}

I'd A/B the above algorithm against the one you already have; you should see at least some performance increase. Notice that although this may well be faster as it does exactly what you want and doesn't see if you want to do anything else, it uses more LOC to achieve the same result. This is Regex's real power; powerful string analysis with very concise code.


Proper way to process the huge amount of data from a sensor using Parallel.For I am getting the huge amount of data from a sensor. In order to speed up data processing, I thought of using Parallel.For. Below is the sample code:

object sync = new object();
private Random random = new Random();
private List<byte> container = new List<byte>();
private readonly int FRAME_WIDTH = 1000;
private readonly int DATA_LENGTH = 217088;
private readonly int FRAME_HEIGHT = 800;

private void getPointsFromSensor(out Point2D[] points2d, out Point3D[] points3d)
{
    points2d = new Point2D[DATA_LENGTH];
    points3d = new Point3D[DATA_LENGTH];
    for (var index = 0; index < DATA_LENGTH; index++)
    {
        points2d[index] = new Point2D(random.Next(-index, index), random.Next(-index, index));
        points3d[index] = new Point3D(random.NextDouble(), random.NextDouble(), random.NextDouble());
    }
}

private void OnDataArrived(object sendor, DataArrivedEventArgs e)
{
    getPointsFromSensor(out Point2D[] points2d, out Point3D[] points3d);

    int validDataCount = 0;

    container.Clear(); // Remove old points
    // reserving 4 bytes for storing 'validDataCount' and we are going to modify it later
    container.AddRange(BitConverter.GetBytes(validDataCount));

    Parallel.For(0, DATA_LENGTH, index =>
    {
        int points2dX = points2d[index].X;
        int points2dY = points2d[index].Y;

        if (points2dX >= 0 && points2dX < FRAME_WIDTH && points2dY >= 0 && points2dY < FRAME_HEIGHT)
        {
            lock (sync)
            {
                container.AddRange(BitConverter.GetBytes(points3d[index].X));
                container.AddRange(BitConverter.GetBytes(points3d[index].Y));
                container.AddRange(BitConverter.GetBytes(points3d[index].Z));
            }
            Interlocked.Increment(ref validDataCount);
        }
    });

    var validDataCountBytes = BitConverter.GetBytes(validDataCount);//4 bytes
    container[0] = validDataCountBytes[0]; container[1] = validDataCountBytes[1];
    container[2] = validDataCountBytes[2]; container[3] = validDataCountBytes[3];
}

The Point2D and Point3D are defined as follows:

class Point2D
{
    public int X;
    public int Y;

    public Point2D(int x, int y)
    {
        X = x;
        Y = y;
    }
}

class Point3D
{
    public double X;
    public double Y;
    public double Z;

    public Point3D(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }
}

It turns out that the Parallel.For version is taking much time compared to simple for loop.

I am wondering if there exists is a better way to use Parallel.For inside a callback function in C#.

Usually it makes absolutely no sense to use a parallel loop with a lock inside it. The performance loss you are talking about comes most probably from it. They cannot run in parallel because they have to wait for each other. The lock also costs some time and if it happens to often, the parallel loop might actually be slower then the normal one.

You might gain some performance if you redesign it in a way that does not requrie synchronization.


A couple of basic string parsing functions I have an app that does a fair bit of text-parsing based on free-form user inputs.  In this, I run searches on the whole string, and then on the last value of the string separate from the rest of the string.  Here is a pair of functions I wrote to getLast and getSubString.

<cffunction name="getLast" output="no" returnType="string" access="public" hint="Takes a string and returns the last value by either comma or space, or returns nothing if the string is only one value long">
    <cfargument name="str" required="yes" type="string">

    <cfset var returnVar = "">

    <cfif listLen(arguments.str) GT 1>
        <cfoutput>listLen(#arguments.str#)</cfoutput>
        <cfset returnVar = trim(listLast(arguments.str))>
    <cfelseif listLen(arguments.str, " ") GT 1>
        <cfoutput>listLen(#arguments.str#, " ")</cfoutput>
        <cfset returnVar = trim(listLast(arguments.str, " "))>
    </cfif>

    <cfreturn returnVar>
</cffunction>

<cffunction name="getSubString" output="no" returnType="string" access="public" hint="Takes a string and returns the beginning of the string minus the last value">
    <cfargument name="str" required="yes" type="string">

    <cfset var last = getLast(arguments.str)>
    <cfset var lastLen = len(last) + 1>
    <cfset var thisLen = len(str) - lastLen>
    <cfset var returnVar = str>

    <cfif thisLen GTE 1>
        <cfset returnVar = trim(mid(str, 1, thisLen))>
    </cfif>

    <!--- remove trailing commas --->
    <cfif right(trim(returnVar), 1) IS ",">
        <cfset returnVar = mid(returnVar, 1, len(trim(returnVar)) - 1)>
    </cfif>

    <cfreturn returnVar>
</cffunction>

And just for fun, some code that was commented out of the second function:

<!---
<cfset var listDelim = ",">
<cfset var i = 0>
<cfset var returnVar = "">

<!--- if the string is longer than one value --->
<cfif len(last)>
    <cfif NOT findNoCase(arguments.str, ",")>
        <cfset listDelim = " ">
    </cfif>
    <cfloop from="1" to="#evaluate(listLen(arguments.str, listDelim) - 1)#" index="i">
        <cfset returnVar = "#returnVar# #listGetAt(arguments.str, i, listDelim)#">
    </cfloop>
    <cfset returnVar = trim(returnVar)>
<cfelse>
    <cfset returnVar = arguments.str>
</cfif>
--->

Next time I think I'm going to avoid parsing all my own text and just dumping it all into SOLR.

If you are using ColdFusion 9+, you should abandon your vars within functions and move toward using the LOCAL scope.  LOCAL vars do not escape the function.

This:

<cfset var last = getLast(arguments.str)>
<cfset var lastLen = len(last) + 1>
<cfset var thisLen = len(str) - lastLen>
<cfset var returnVar = str>

Should be:

<cfset LOCAL.last = getLast(arguments.str)>
<cfset LOCAL.lastLen = len(LOCAL.last) + 1>
<cfset LOCAL.thisLen = len(LOCAL.str) - LOCAL.lastLen>
<cfset LOCAL.returnVar = str>


Improvement of this method I'm coding a small web app with no real functionality. It's like a pilot program for something bigger. What I want is construct a program that works as a clock on/off for a restaurant. Actually I'm just trying to simulate one. What I'v done is working but I would like to know whether there is any java class that I can use in a session to calculate the difference between the clock on and off.

Index.jsp

<%@page import="javax.media.jai.operator.EncodeDescriptor"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Project</title>

Employees

        <form action=<%= response.encodeURL("CheckUser") %> method="get">
            <input type="hidden" name="userId" value="1">
            <input type="submit" value="Diogo">

        </form>

CheckUser

public class CheckUser extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userId = request.getParameter("userId");
        User user1 = new User();
        user1.setUserId(userId);

        HttpSession session = request.getSession();
        session.setAttribute("userId", userId);

        Hours h1 = (Hours) session.getAttribute("hours");

        if (h1 == null){
        h1 = new Hours(user1);
        }

        Calendar cal = new GregorianCalendar();

        h1.setMinutes(cal.get(Calendar.MINUTE));

        request.setAttribute("hours", h1);
        String url = "/show.jsp";

        session.setAttribute("hours", h1);

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);

    }

show.jsp

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <%@ page import="Business.*, process.*" %>

        <%
            String userId = (String) session.getAttribute("userId");
            Hours h = (Hours) session.getAttribute("hours");
            String actualMinute = h.getMinutes();
            String calcMinute = h.getCalMinutes();
        %>

<%= userId %>

<%= h.getMinutes() %> minuto atual

        <%
        if(!actualMinute.equalsIgnoreCase(calcMinute) || calcMinute == "0")
           {
        %>

<%= h.getCalMinutes() %> minutes

        <%
        }else
           {
        %>

It is working

<%= h.getCalMinutes() %>

        <%
           }
        %>

        <form action="<%= response.encodeURL("index.jsp") %>" method="get">
            <input type="submit" value="return">
        </form>

I assume that Hours is a custom class of yours.

If you are asking if there is an existing Java class that will automagically calculate the "difference" between two instances of your custom class, the the answer is "No".
If you are asking (more generally) what is the best class for handling temporal quantities so that you can compare them, calculate differences and so on, then the answer is to look at the JodaTime libraries.

I also note that you are STILL using "Business" as a package name.  You should stop it before The Protectors of Java Purity find a way to hack your PC and fill the disc drive with zeros!!!

Seriously, it is bad practice.  Don't do it.  Follow the standard Java naming conventions, like professional developers do.


Inserting robot moves into an SQLite3 database I'm just wondering if you would consider this to be safe from SQL injection.

A peculiarity of my program is I need to dynamically access table names depending on my scenario.

This is not for publishing online, but I wish to know if this approach is any good.

I'm using Python3 and SQLite3. My database object contains the table name, and is not controlled by any user. It comes from another class in a config.cfg file.

def save_record(state_int, database):
    query = '''INSERT INTO %s (state_int, turn_left, turn_right, move_forward) VALUES (?,?,?,?)''' %(database.records_table_name)
    database.cursor.execute(query, (state_int, 0, 0, 0))
    database.robot_memory.commit()

save_record(10012, database)

Just a philosophical answer here.

I think you're asking the wrong question. You shouldn't ask yourself "is my SQL code safe or vulnerable?" This is too hard to answer in any individual case, and coming up with the right answer could depend on a lot of contextual things such as the system configuration, the whole program structure, etc.

You don't want to have to consider all these things when writing code. People have already considered them a lot, and based on their experience they have come up with best practices.

Instead you should ask the question,

  Does my code follow the standard best practices for preventing SQL injection?

As alluded to in another answer, using string interpolation to build queries is against best practices. So, while it doesn't seem like this creates a vulnerability in your code, we can't rule out that there is some edge case based on the rest of your program structure that would allow an attacker to put something into this string interpolation.

Unless you have a very good reason for doing so, follow the best practices, even if you don't need to. Then you can sleep well and ignore pathological edge cases.


Every node in binary tree = sum of subtree I wrote this in Java (I know that the brackets don't exactly follow the standard way of doing it in Java - so it looks a bit like C#). But I was wondering how this algorithm is percieved. I have seen some iterative ways of solving the problem - but I thought recursion improves readability here.

Every node in a Binary Tree, has to have the value of it's subtree.

   8
  /  \
 3    2
/ \
1  2

Would be an example of such a tree. (1+2 = 3 at the bottom, and 1 + 2 + 3 + 2 = 8 at the top). An empty tree is considered 'valid'.

public boolean isValid()
{
    return isValid(root);
}

public boolean isValid(BinaryNode<E> node)
{
    if (node == null)
        return true;

    int sum = sumOfSub(node.getLeft()) + sumOfSub(node.getRight());

    if (node.getLeft() != null && node.getRight() != null)
    {
        if ((Integer) node.getData() != sum)
        {
            return false;
        }
    }
    else
        return true;

    return isValid(node.getLeft()) && isValid(node.getRight());
}

private int sumOfSub(BinaryNode node)
{
    if (node == null) return 0;
    int value = (Integer) node.getData();
    return value + sumOfSub(node.getLeft()) + sumOfSub(node.getRight());
}

This part of your code could probably be simplified

if (node.getLeft() != null && node.getRight() != null)
{
    if ((Integer) node.getData() != sum)
    {
        return false;
    }
}
else
    return true;

First off, don't do an else statement without curly braces when the corresponding if statement has curly braces, it doesn't follow expected coding practices.

Then you should return early

if (node.getLeft() == null || node.getRight() == null) {
    return true;
} else if ((Integer) node.getData() != sum) {
    return false;
}

As your code is written in the original post it will never hit this statement

return isValid(node.getLeft()) && isValid(node.getRight());

and will always return true, if (node.getLeft() == null || node.getRight() == null)


Return value related to file content header I have an attachment uploading feature in my web app.

File can have type- image/png or image/jpg or image/jpeg or application/pdf

For images, I need to return Photo, for pdf Document.

Documents will be only pdf, but images can be extended to images/ico, etc.

Now my code looks like this.

getAttachmentType(attachmentTypeHeader: string): string {
    if (
        attachmentTypeHeader === 'image/png' ||
        attachmentTypeHeader === 'image/jpg' ||
        attachmentTypeHeader === 'image/jpeg'
    ) {
        return 'Photo';
    }
    if (attachmentTypeHeader === 'application/pdf') {
        return 'Document';
    }
}

How I can make it check like image/*?

Usually if I have a big list of mappings from one string to another, that is likely to be later enhanced on, I use a generic mapping method, that is fed a static mapping constant.

So the first iteration would be something like:

type ExpectedMimeTypes =
  'image/png' |
  'image/jpg' |
  'image/jpeg' |
  'application/pdf' |
  never;

type ExpectedMagicOutput =
  'Photo' |
  'Document' |
  'Unknown' |
  never;

type MimeTypeMapping = {
  [key in ExpectedMimeTypes]?: ExpectedMagicOutput
}

const MAP_MIME_TYPE_TO_MAGIC_STRING: MimeTypeMapping = {
  'image/png': 'Photo',
  'image/jpg': 'Photo',
  'image/jpeg': 'Photo',
  'application/pdf': 'Document'
}

function getAttachmentType(attachmentTypeHeader: ExpectedMimeTypes): ExpectedMagicOutput {
  if (attachmentTypeHeader in MAP_MIME_TYPE_TO_MAGIC_STRING) {
    return MAP_MIME_TYPE_TO_MAGIC_STRING[attachmentTypeHeader]!;
  } else {
    return 'Unknown';
  }
}

If you are using TypeScript, go all in, meaning be as specific as possible. You do not expect arbitrary string as a result from getAttachmentType() but specific ones. You should explicitly model them, either by using unions or string-based enums. This fosters reusability.

The above solution gives you full type-safety, while being easily enhanced for other types; simply add them to the ExpectedMimeTypes and then you can easily add them to the constant MAP_MIME_TYPE_TO_MAGIC_STRING and vice versa, you cannot add mappings there, that have not been mentioned in the types above.

You could make ExpectedMimeTypes configurable by putting them into a dedicated file and let that be generated via a config and a simple script. That way you get both - configurable mime types and static compile type safety.


Texas Hold'em classes I am working on a simple Texas Hold'Em dealing simulator. I am new to Python and was hoping to get some advice on my use of classes here. I feel like I am not using them as efficiently as possible, especially when dealing out the player cards. Specifically, I feel like the def deal(self, n_players) could be simplified instead of using playercard1 and playercard2, and deleting the items from the "deck".

from random import shuffle

class TexasHoldem:
    #create deck
    def __init__(self):
        values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
        suites = ['Heart', 'Spade', 'Club', 'Diamond']
        self.deck = [j + " " + i for j in values for i in suites]

    #shuffle deck
    def shuffle(self):
        shuffle(self.deck)

    #deal for players
    def deal(self, n_players):
        count = 0
        #card 1 list (will be shuffled, delt 'around the table' as if a real stack)
        playercard1 = list()
        while count < n_players:
            card1 = self.deck[count]
            playercard1.append(card1)
            count += 1

        #remove cards from deck that were delt
        for i in playercard1:
            self.deck.remove(i)

         count = 0
         #card 2 list
         playercard2 = list()
         while count < n_players:
             card2 = self.deck[count]
             playercard2.append(card2)
             count += 1

         #remove cards from deck delt for 2nd card
         for i in playercard2:
             self.deck.remove(i)

        #merge cards of playercard1 and playercard2 into set
        self.playerhand = zip(playercard1, playercard2)

    #define the flop
    def flop(self):
        #burn a card
        del self.deck[0]
        #lay down three
        self.flopcards = self.deck[0:3]
        #delete flop from deck
        for i in self.flopcards:
            self.deck.remove(i)

    #same as flop for turn and river
    def turn(self):
        del self.deck[0]
        self.turncard = self.deck[0:1]

        for i in self.turncard:
            self.deck.remove(i)

    def river(self):
        del self.deck[0]
        self.rivercard = self.deck[0:1]

        for i in self.rivercard:
            self.deck.remove(i)

#create instance of Cards class
c = TexasHoldem()
#shuffle for this instance
c.shuffle()

#deal for n players
c.deal(9)

print 'Player Hands:'
for i in c.playerhand:
    print i

#flop
c.flop()
print 'Flop:'
print c.flopcards

#turn
c.turn()
print 'Turn:'
print c.turncard

#river
print 'River:'
c.river()
print c.rivercard

Your code does a few things repetitively:

count = 0
playercard1 = list()
while count < n_players:
    card1 = self.deck[count]
    playercard1.append(card1)
    count += 1

for i in playercard1:
    self.deck.remove(i)

I'll go through the problems with this:

You manually increment count, this is something that you should do with range.
You manually index every item.
You manually append to a list.
You manually remove each card from the deck, this causes the list to shift, and causes a small search of the list. (\$O(n)\$ complexity)

Instead you could either:

Pop the amount of cards you need.

pop = self.deck.pop
playercard1 = [pop() for _ in range(n_players)]

Slice the amount of items you need and then delete them.

playercard1 = self.deck[-n_players:]
del self.deck[-n_players:]

You should notice that I take from the end of the list, this is as you aren't using a queue and so they will be faster.

The other main code you use is:

del self.deck[0]
self.flopcards = self.deck[0:3]
del self.deck[0:3]

This uses the same code as before, but burns one card.
You can then just make two functions to do what most of your code is doing at the moment.

def take(self, number_cards):
    pop = self.deck.pop
    return [pop() for _ in range(number_cards)]

def draw(self, number_cards):
    self.deck.pop()
    return self.take(number_cards)

This then makes the rest of your code simple and easy to read and use.

def deal(self, n_players):
    self.playerhand = zip(self.take(n_players), self.take(n_players))

def flop(self):
    self.flopcards = self.draw(3)

def turn(self):
    self.turncard = self.draw(1)

def river(self):
    self.rivercard = self.draw(1)

Other than the above I'd:

Add shuffle to your __init__ so that the cards are pre-shuffled.
Move the deck creation into shuffle to allow more than one game, and
Move values and suites to the global scope as 'constants'.

This results in something like:

VALUES = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
SUITES = ['Heart', 'Spade', 'Club', 'Diamond']
class TexasHoldem:
    def __init__(self):
        self.shuffle()

    def shuffle(self):
        self.deck = [j + " " + i for j in VALUES for i in SUITES]
        shuffle(self.deck)


Convert rating value to visible stars using fontawesome icons Just curious if there is a more elegant way to perform the same result. I have a calculated rating which I want to convert to visible stars using fontawesome icons. Max rating is 5. I am rounding the rating to the nearest .5.
Done in js given a rating called data (sum of all votes / number of votes).

//example, can be anything from 0-5 after being computed
data = 3.65;

//get rating in nearest .5 value (this is how many stars need to be yellow)
rating = yellow = (Math.round(data*2)/2).toFixed(1);

//how many stars need to be white
white = 5 - rating;

output = '
';

//output full yellow stars
while (yellow >= 1) {
    output += '';
    yellow--;
}
//what is left can either be .5 or 0... if .5 output half yellow star
if (yellow == .5) {
    output += '';
}
//output remaining full white stars
while (white >= 1) {
    output += '';
    white--;
}

return output + '
';

The above does what I want it to, but I have to believe there is a better approach to get the same result.

I recently implemented this same thing, here's what I used. Main difference: Let the for loop do the math for you. By the end of the first loop, if there is half a star it will be in the i variable. Use an array to buffer your string (or create DOM objects instead, don't use += to build a string).

document.getElementById("stars").innerHTML = getStars(3.6);

function getStars(rating) {

  // Round to nearest half
  rating = Math.round(rating * 2) / 2;
  let output = [];

  // Append all the filled whole stars
  for (var i = rating; i >= 1; i--)
    output.push('&nbsp;');

  // If there is a half a star, append it
  if (i == .5) output.push('&nbsp;');

  // Fill the empty stars
  for (let i = (5 - rating); i >= 1; i--)
    output.push('&nbsp;');

  return output.join('');

}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

Rating:


Car dealership landing page Please give feedback on what I could do better next time. This is an Angular 1.x landing page I made for a pretend car dealership.

Here is what it looks like.

Here is the app.js:

(function(){

'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp',[]);

})();

Here is my car-slide.js directive that holds some car data, and has a controller for changing the current car picture and tagline:

angular.module('myApp').directive('carSlide', CarSlide);

function CarSlide(){
return {
   restrict: 'E',
   templateUrl: 'partials/car-slide.html',
   controller:function($interval){

    this.currentCar = 0;
    var self = this;

    function changeCar(){
      if (self.currentCar == 0){
        self.currentCar = 1;
      } else {
        self.currentCar = 0;
      }
    }

    $interval(changeCar, 4000);

    this.carData = [{
                    class:'A4',
                    name: "Audi A4",
                    tagline: "The time is now.",
                    img: "img/big/car1.jpg"
                    },
                    {
                    class:'A5',
                    name: "Audi A5",
                    tagline: "Do you like power?",
                    img: "img/big/car2.jpg"}
                  ];

  },
  controllerAs:'carCtrl'
};

};

Here is the directive for the slider on the bottom. All it does is change the header from one car type to another:

angular.module('myApp').directive('carTypeSlide', CarTypeSlide);

function CarTypeSlide() {
    return {
        restrict: 'E',
        templateUrl: 'partials/car-type-slide.html',

        controller: function($interval) {
            var self = this;
            this.carTypes = [
                "Sedans",
                "Crossovers and Minivans",
                "Hybrids",
                "Compacts"
            ];
            var initial = 0;
            var currType = 0;
            this.showType = this.carTypes[initial];

            $interval(changeType, 3000);

            function changeType() {

                currType++;

                self.showType = self.carTypes[currType];

                if (currType === self.carTypes.length) {
                    currType = 0;
                    self.showType = self.carTypes[currType];
                }

            }

        },
        controllerAs: 'carTypeCtrl'
    };
};

Here is the repo for it.

I have put AngularJS on pause and am trying to learn ES2015 right now, and then building a simple app with that. Do you think learning ES2015 will help with frameworks like Angular/React?

Here is an example of your carousel written in Angular 1.6 style with ES2015

(function(){
    class componentController {

        constructor($interval) {

            Object.assign(this, { $interval })

            this.currentCar = 0;

            this.carData = [
                {
                    class:'A4',
                    name: "Audi A4",
                    tagline: "The time is now.",
                    img: "img/big/car1.jpg"
                },
                {
                    class:'A5',
                    name: "Audi A5",
                    tagline: "Do you like power?",
                    img: "img/big/car2.jpg"
                }
            ];

            this.$interval(changeCar, 4000);
        }

        changeCar(){
            // this way you can have collection of any size
            this.currentCar = this.currentCar++ % this.carData.length;
        }
    }

    const componentOptions = {

        templateUrl: 'partials/car-slide.html',
        controller: componentController

    };

    angular.module('myApp').component('carSlide', componentOptions);

}());

ConrollerAs is $ctrl by default.


Join List with Separator I was implementing something similar to Python's join function, where

join([a1, a2, ..., aN], separator :: String)

returns

str(a1) + separator + str(a2) + separator + ... + str(aN)

e.g.,

join([1, 2, 3], '+') == '1+2+3'

I was implementing something similar and was wondering, what is a good pattern to do this? Because there is the issue of only adding the separator if it is not the last element

def join(l, sep):
    out_str = ''
    for i, el in enumerate(l):
        out_str += '{}{}'.format(el, sep)
    return out_str[:-len(sep)]

I'm quite happy with this, but is there a canoncial approach?

Strings in Python are immutable, and so 'string a' + 'string b' has to make a third string to combine them. Say you want to clone a string, by adding each item to the string will get \$O(n^2)\$ time, as opposed to \$O(n)\$ as you would get if it were a list.

And so, the best way to join an iterable by a separator is to use str.join.

>>> ','.join('abcdef')
'a,b,c,d,e,f'

If you want to do this manually, then I'd accept the \$O(n^2)\$ performance, and write something easy to understand. One way to do this is to take the first item, and add a separator and an item every time after, such as:

def join(iterator, seperator):
    it = map(str, iterator)
    seperator = str(seperator)
    string = next(it, '')
    for s in it:
        string += seperator + s
    return string


Code runs Speed Test CLI using the python wrapper and then stores values within CSV I wanted to make use of the speedtest-cli while also incorporating pandas into the project. My initial goal, which I am posting here, was to take the values of the speed test and incorporate them into a CSV. I've been learning about Pandas and figured it would be a good way to accomplish the project.

import speedtest
import pandas as pd
import os

# Initial Speedtest variables
s = speedtest.Speedtest()
servers = []

# File path variables
localpath = ''
filepath = ''
filename = ''

# Functions #

def speedtest():
    """Makes use of the speed-test-cli python wrapper
    to get speed test data and returns in a dictionary"""
    s.get_servers(servers)
    s.get_best_server()
    s.download()
    s.upload()
    s.results.share()
    results_dict = s.results.dict()
    return results_dict

def convert_mbps(arg):
    arg = arg / 1000000
    return arg

def csv_upload(localpath, filepath, filename):
    """Attempts to append a csv file and, if none
    exists, creates one in a specified path"""
    try:
        df2 = pd.read_csv(localpath)
        df2 = df2.append(df)
        df2.to_csv(os.path.join(filepath, filename), index=False)
    except OSError:
        df.to_csv(os.path.join(filepath, filename), index=False)

# Speedtest and convert to Data Frame
result = speedtest()
df = pd.io.json.json_normalize(result)
df2 = None

# Uploads CSV
csv_upload(localpath, filepath, filename)

I've tried as best as I could to document throughout my code, as well as to not statically specify parameters within functions; something which I've been bad for in the past. I've also tried to incorporate in some exception handling, though this is something that I believe needs more work in my code.

I've tested the code within a cron, it does exactly what it seems to be functioning as I would like it to. Future developments will surround analyzing data collected from the CSV; trying to determine trends in bandwidth or latency as a function of time of day. Any feedback would be most appreciated.

Don't use globals. E.g., you refer to df and df2 in csv_upload, why not make them parameters?
Use the standard if __name__ == '__main__': guard around the script's main body.
It's common to just accept a flat file path, and expect the calling code to perform any os.path.join in the creation of said path.
"upload" sounds like network activity, but you're saving the data to disk. This should probably follow a more typical naming scheme of to_csv or save or dump or something of that sort.
This seems like a prime candidate for being a class.

I'd suggest something like the following:

import speedtest
import pandas as pd
import os

class MySpeedtest:
    def __init__(servers, initial_data_path=None):
        # Initial Speedtest variables
        self.s = speedtest.Speedtest()
        self.servers = servers

        if initial_data_path is not None:
            self.df = pd.read_csv(initial_data_path)
        else:
            self.df = pd.DataFrame()

    def run_test(self):
        """Makes use of the speed-test-cli python wrapper
        to get speed test data and returns in a dictionary"""
        self.s.get_servers(self.servers)
        self.s.get_best_server()
        self.s.download()
        self.s.upload()
        self.s.results.share()
        results_dict = self.s.results.dict()
        self.df.append(pd.io.json.json_normalize(results_dict))

    @staticmethod
    def convert_mbps(arg):
        return arg / 1000000
        # Actually, this should probably be "arg / (2**20)"
        # 1 MB = 2**20 B

    def to_csv(self, path):
        """Attempts to append a csv file and, if none
        exists, creates one in a specified path"""
        self.df.to_csv(path, index=False)

if __name__ == '__main__':
    # TODO: populate a list of servers, define localpath/filepath/filename
    tester = MySpeedtest(servers, localpath)
    tester.run_test()
    tester.to_csv(os.path.join(filepath, filename))


Generate Cartesian product of List in Java My code, which generates Cartesian product of all lists given as arguments:

public static <T> List<List<T>> cartesianProduct(List<T>... lists) {

    List<List<T>> product = new ArrayList<List<T>>();

    for (List<T> list : lists) {

        List<List<T>> newProduct = new ArrayList<List<T>>();

        for (T listElement : list) {

            if (product.isEmpty()) {

                List<T> newProductList = new ArrayList<T>();
                newProductList.add(listElement);
                newProduct.add(newProductList);
            } else {

                for (List<T> productList : product) {

                    List<T> newProductList = new ArrayList<T>(productList);
                    newProductList.add(listElement);
                    newProduct.add(newProductList);
                }
            }
        }

        product = newProduct;
    }

    return product;
}

Can this code be simplified?

You should read about the diamond operator.  You don't need to write the types on the right hand side in some circumstances.
I avoid varargs because they confuse the type system.  My guess is that you are not using an IDE because mine (Netbeans) flags both the diamond operators and the varargs.
You can indeed shorten your code because you don't really need to do a conditional check on the empty list if you start with the right conditions:

public static <T> List<List<T>> computeCombinations2(List<List<T>> lists) {
    List<List<T>> combinations = Arrays.asList(Arrays.asList());
    for (List<T> list : lists) {
        List<List<T>> extraColumnCombinations = new ArrayList<>();
        for (List<T> combination : combinations) {
            for (T element : list) {
                List<T> newCombination = new ArrayList<>(combination);
                newCombination.add(element);
                extraColumnCombinations.add(newCombination);
            }
        }
        combinations = extraColumnCombinations;
    }
    return combinations;
}

Note that the scanning order changed: the first element stays fixed until all other combinations of the other elements are exhausted.  I prefer that order actually.
It think it would be cleaner to split this in two methods.  There is a sub-task of adding one list of elements to an existing set of combinations and the main task which must call the sub-task on all lists:

public static <T> List<List<T>> computeCombinations3(List<List<T>> lists) {
    List<List<T>> currentCombinations = Arrays.asList(Arrays.asList());
    for (List<T> list : lists) {
        currentCombinations = appendElements(currentCombinations, list);
    }
    return currentCombinations;
}

and the sub-task (using Java 8):

public static <T> List<List<T>> appendElements(List<List<T>> combinations, List<T> extraElements) {
    return combinations.stream().flatMap(oldCombination
            -> extraElements.stream().map(extra -> {
                List<T> combinationWithExtra = new ArrayList<>(oldCombination);
                combinationWithExtra.add(extra);
                return combinationWithExtra;
            }))
            .collect(Collectors.toList());
}

Actually, for this method, Java 8 does not make it shorter and makes it less readable than the old style.  I am leaving it nonetheless so you (and others) can get more familiar with Java 8.
Minor point: I think you use too many blank lines in your code.


Correct and portable serialization So I've made custom binary streams which work like this:

/// \brief Reads a variable from the stream.
/// \tparam T Type of the variable.
/// \param[out] var Variable to read.
/// \return Reference to this stream.
/// \throw TODO
/// \note No endianness conversion will be performed if a byte is not 8 bit
/// wide.
template <typename T>
BinaryInputStream& operator>>(T& var)
{
    static_assert(std::is_pod<T>::value, "BinaryInputStream::operator>>: "
        "Binary stream can only read POD types.");
    static_assert(!std::is_enum<T>::value, "BinaryInputStream::operator>>: "
        "Directly reading enums is unsafe. Implement a custom overload and "
        "check the value inside it.");
    char* buffer = reinterpret_cast<char*>(&var);
    std::size_t buffersize = sizeof(var);
    this->Read(buffer, buffersize);
#if CHAR_BIT == 8
    Endianness systemendianness = General::GetEndianness();
    if (systemendianness == Endianness::Unknown)
    {
        return *this;
    }
    if (systemendianness != this->GetEndianness())
    {
        SwapBytes(var);
    }
#endif
    return *this;
}

/// \brief Writes a variable to the stream.
/// \tparam T Type of the variable.
/// \param[in] var Variable to write.
/// \return Reference to this stream.
/// \throw TODO
/// \note No endianness conversion will be performed if a byte is not 8 bit
/// wide.
template <typename T>
BinaryOutputStream& operator<<(T var)
{
    static_assert(std::is_pod<T>::value,
        "Binary stream can only write POD types.");
#if CHAR_BIT == 8
    Endianness systemendianness = General::GetEndianness();
    if ((systemendianness != Endianness::Unknown) &&
        (systemendianness != this->GetEndianness()))
    {
        SwapBytes(var);
    }
#endif
    char* buffer = reinterpret_cast<char*>(&var);
    std::size_t buffersize = sizeof(var);
    this->Write(buffer, buffersize);
    return *this;
}

/// \brief Swaps bytes of a given variable.
/// \tparam T type of the variable.
/// \param[in,out] var Input variable.
template <typename T>
void SwapBytes(T &var)
{
    char* buffer = reinterpret_cast<char*>(&var);
    for (std::size_t i = 0, j = sizeof(var) - 1; i < j; ++i, --j)
    {
        std::swap(buffer[i], buffer[j]);
    }
}

Is this correct? Have I triggered undefined behavior? Are static_asserts correct? Maybe they are overly restrictive or not strict enough? Please quote the standard if possible.

TODO throw documentation

Throw documentation TODO? E. g. here:

/// \throw TODO

this pointer

Usage of this as in here is unnecessary.

this->Read(buffer, buffersize);

Calling the method without it is more common.

Read(buffer, buffersize);

endiannes

Endianness systemendianness = General::GetEndianness();

I would speculate that system endianness is not going to change during runtime.

Therefore I would probably use "more constant" representation something like

static const variable
template parameter
maybe even MACRO

read & swap

It doesn't look quite efficient to always read memory and swap if endiannesses don't match. What about having alternative version of Read() method already reversing the order during read?


Functional interface hierarchy in Java 8 I just created the following code and am wondering whether it is logically correct (all other feedback is of course also welcome):

public interface HandView extends View<Hand> {
    void onCardAdded(final Card card);

    void onCardPlayed(final int cardIndex);

    void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);

    public static HandView merge(final HandView... handViews) {
        return new HandView() {
            @Override
            public void onCardAdded(final Card card) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardAdded(card));
            }

            @Override
            public void onCardPlayed(final int cardIndex) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardPlayed(cardIndex));
            }

            @Override
            public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardsSwapped(cardIndexOne, cardIndexTwo));
            }
        };
    }

    @FunctionalInterface
    public static interface OnCardAddedListener extends HandView, Consumer<Card> {
        @Override
        default void accept(final Card card) {
            onCardAdded(card);
        }

        @Override
        void onCardAdded(final Card card);

        @Override
        default void onCardPlayed(final int cardIndex) { }

        @Override
        default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
    }

    @FunctionalInterface
    public static interface OnCardPlayedListener extends HandView, IntConsumer {
        @Override
        default void accept(final int cardIndex) {
            onCardPlayed(cardIndex);
        }

        @Override
        default void onCardAdded(final Card card) { }

        @Override
        void onCardPlayed(final int cardIndex);

        @Override
        default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
    }

    @FunctionalInterface
    public static interface OnCardsSwappedListener extends HandView {
        @Override
        default void onCardAdded(final Card card) { }

        @Override
        default void onCardPlayed(final int cardIndex) { }

        @Override
        void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);
    }
}

And then I used it like this in the following integration test (so you can see the usage):

@Test
public void testRemoveCallbackNotTriggeredAfterRemoval() {
    Hand hand = new Hand(5);
    AtomicInteger counter = new AtomicInteger(0);
    HandView.OnCardAddedListener handView = card -> counter.incrementAndGet();
    hand.addViewCallback(handView);
    HandView.OnCardAddedListener handView2 = card -> counter.incrementAndGet();
    hand.addViewCallback(handView2);

    hand.add(new MonsterCard("Test", 7, 7, MonsterModus.HEALING));
    assertEquals(2, counter.get());

    hand.removeViewCallback(handView2);
    hand.add(new MonsterCard("Test Test", 5, 5, MonsterModus.HEALING));
    assertEquals(3, counter.get());

    hand.removeViewCallback(handView);
    hand.add(new MonsterCard("Test Test Test", 3, 3, MonsterModus.HEALING));
    assertEquals(3, counter.get());
}

Where Hand.addViewCallback expects an argument of type HandView.

It seems to be working, the only thing I am left off wondering is:

Is it not normal to have HandView extends OnCardAddedListener, OnCardPlayerListener, OnCardsSwappedListener?

The caveat then is that I don't think methods accepting an HandView now, would accept those sub-interfaces then.

Honestly, skiwi, you make things more complicated than they need to be.

Please rename View to Listener to avoid confusion. Because that's really what they are, it's a Listener, not a View. It doesn't by itself provide any UI functionality.

Prefixing your interfaces with On is, although understandable why you are doing it, not something I recommend or have seen been done in other places. You're already suffixing Listener to the name (which is what I would recommend, and what I have seen in lots of other code), no need to prefix the interface with On. The method names can be prefixed with on, as they have been already.

Why are you bringing IntConsumer and Consumer<Card> into your code? In what way does that help you? In my opinion, it doesn't help you at all. It creates more confusion than brings something good. If you want to "transform" an IntConsumer into a CardPlayedListener, use Java 8's method reference style by using something like IntConsumer::accept.

Now, let's see if we can write more or less the same thing of your interface heirarchy but with fewer lines.

public interface HandListener {
    default void onCardAdded(final Card card) {}

    default void onCardPlayed(final int cardIndex) {}

    default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {}

    public static HandListener merge(final HandListener... handViews) {
        return new HandListener() {
            @Override
            public void onCardAdded(final Card card) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardAdded(card));
            }

            @Override
            public void onCardPlayed(final int cardIndex) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardPlayed(cardIndex));
            }

            @Override
            public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardsSwapped(cardIndexOne, cardIndexTwo));
            }
        };
    }

    @FunctionalInterface
    public static interface CardAddedListener extends HandListener {
        @Override
        void onCardAdded(final Card card);
    }

    @FunctionalInterface
    public static interface CardPlayedListener extends HandListener {
        @Override
        void onCardPlayed(final int cardIndex);
    }

    @FunctionalInterface
    public static interface CardsSwappedListener extends HandListener {
        @Override
        void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);
    }
}

This way, you can keep having only HandListeners as listeners in your Hand, no need to split it up into three separate listeners. And if you want to easily create a listener that listens only to cards being swapped, you can easily do so. The trick here is that I'm overriding a default method and removing the implementation, thus making it abstract again. While letting the original HandListener interface have default implementations for all the methods.

Original lines of code: 72
New lines of code: 43
Lines of code reduced by: 40%