Java 8 constructs

The following

function.putIfAbsent(startState, new HashMap<>());
function.get(startState).put(character, goalState);

can be simplified by using the computeIfAbsent(key, mappingFunction) method. This method will return the current value associated with the given key or compute a new value for that key and return it. As such, you could have:

function.computeIfAbsent(startState, k -> new HashMap<>()).put(character, goalState);

Also, the following

if (!function.containsKey(startState)) {
    return null;
}
return function.get(startState).get(character);

can be also written more simply with the getOrDefault(key, defaultValue) method. This will return the value associated with the given key or else return the default value. You could have:

return function.getOrDefault(startState, Collections.emptyMap()).get(character);

When the map doesn't contain the key startState, an empty map (that was already instantiated, it is a cached value) is returned with Collections.emptyMap().

Code structure

You currently have a class TransitionFunction that holds all transitions and offers a method to go from one state to another for a particular character.

I find the name TransitionFunction a bit misleading because it would imply that the class is in fact a Function in that it is a functional interface taking a parameter and returing a value. But it is more than that since it is the class that holds all possible transitions.

Why not rename the class Transitions and:

Rename the method setTransition to addTransition to better reflect the fact that this method adds a transition (instead of setting it).
Move the code for processing all transitions, that is currently placed inside the matches method, in this class. This method would be called processAll(Integer startState, char[] characters) and would process all the characters given starting at the given state.

This is what the class could look like

public class Transitions {

    private final Map<Integer, Map<Character, Integer>> function = new HashMap<>();

    public void addTransition(Integer startState, Integer goalState, char character) {
        function.computeIfAbsent(startState, k -> new HashMap<>()).put(character, goalState);
    }

    public Integer process(Integer startState, char character) {
        return function.getOrDefault(startState, Collections.emptyMap()).get(character);
    }

    public Integer processAll(Integer startState, char[] characters) {
        return IntStream.range(0, characters.length)
                        .boxed()
                        .reduce(startState, (s, i) -> s == null ? null : process(s, characters[i]));
    }

}

Notice that the processAll method leverages an IntStream over the indexes of the input array. The final state is calculating by reducing from the starting state and calling process each time on the accumulated result. The difference between your initial code is that it is not short-circuiting; if you wish to keep that, you can keep your for loop as-is.

With this change, the matches method would just be:

public boolean matches(String text) {
    Integer finalState = transitionFunction.processAll(startState, text.toCharArray());
    return finalState != null && acceptingStates.contains(finalState);
}

Using Optional

You are currently relying on null values to mean "no state". Using an Optional would remove all that. We could make the methods process and processAll return an Optional<Integer> with

public Optional<Integer> process(Integer startState, char character) {
    return Optional.ofNullable(function.getOrDefault(startState, Collections.emptyMap()).get(character));
}

public Optional<Integer> processAll(Integer startState, char[] characters) {
    return IntStream.range(0, characters.length)
                    .boxed()
                    .reduce(
                      Optional.of(startState),
                      (o, i) -> o.flatMap(s -> process(s, characters[i])),
                      (o1, o2) -> o1.map(Optional::of).orElse(o2)
                    );
}

process makes a call to Optional.ofNullable to wrap the value. The reducing part works on the optional values. The combiners combines two optional into a single one.

Then, the matches method becomes

public boolean matches(String text) {
    return transitionFunction.processAll(startState, text.toCharArray())
                             .map(acceptingStates::contains)
                             .orElse(false);
}


While looking at the code, the first thing that poped on me was the indentation. It is too strict, too inflexible, context-less, width-less... It isn't a good indentation.

Right in the middle of your code, you have this:

// LESS code blocks
if ($('.field-style .less')
    .length) {

This is next to unreadable. I even though it had broken syntax. Here's how it should be:

// LESS code blocks
if ($('.field-style .less').length) {

The { on the same line is target of discussion. In my opinion, it should be in a line on it's own but most people prefer this way.

Other things like this:

$('.field-style a')
    .each(function() {

Which can and should be all in the same line. You should only split the methods in new lines if and only if they look too wide.

Now, lets split it up and analise:

// Links
$('.field-style a')
    .each(function() {
        var base =
            $(this)
            .next('pre')
            .children('code')
            .text();
        var replaced =
            base
            .replace(
                /    |{|}|^a |\r?\n|\r/g,
                '');
        $(this)
            .attr('style', replaced);
    });

You re-use the $(this) in there, and store the text on a variable. Your priorities are swapped! The slowest thing in that code is repeated, but you have to store a string in a new variable.

This is how I would write it:

$('.field-style a').each(function() {
    var $this = $(this);

    var replaced = $this
        .next('pre')
        .children('code')
        .text()
        .replace(/    |{|}|^a |\r?\n|\r/g, '');

    $this.attr('style', replaced);
});

You could even write it as:

$('.field-style a').each(function() {
    var $this = $(this);

    $this.attr(
        'style',
        $this
            .next('pre')
            .children('code')
            .text()
            .replace(/    |{|}|^a |\r?\n|\r/g, '')
    );
});

This part can also be used for the $('.field-style .colored') block.

But a major concerning area is that regular expression. It is made to match newlines, the first a and a space and {}. Here's my proposal:

/a |\s*(?:\r|\n|\r\n)\s*|[\{\}]/g

This goes a step further and also deletes any tab or any other whitespace after and before a newline.

An input like:

a {
    color: red;
    size: auto;
    width: 120px;
    white-space: break;
}

Will result in:

  color: red;size: auto;width: 120px;white-space: break;

While yours results in:

  <TAB>color: red;size: auto;<TAB>width: 120px; white-space: break;

(Due to limitations on the representation of whitespace, I've seen myself forced to replace all tabs with a <TAB> 'indicator')

Lets analise the .less block:

// LESS code blocks
if ($('.field-style .less')
    .length) {
    $('.field-style .less')
        .html($('.field-style .less')
            .html()
            .replace(
                /(none)|(decimal)|(inside)|(hidden)/g,
                '$&'));

    $('.field-style .less')
        .html($('.field-style .less')
            .html()
            .replace(
                /(em)|(px)/g,
                '$&'));
};

First, you have that dangling ;.

You are currently wasting too much CPU! You repeated $('.field-style .less') 5 times! You have no idea how slow that is. Store that in a new variable.

You could remove repetitions, like this:

var $less = $('.field-style .less');
if( $less.length ) {
    $less.html(
        $less
            .html()
            .replace(
                /(none)|(decimal)|(inside)|(hidden)/g,
                '$&'
            )
            .replace(
                /(em)|(px)/g,
                '$&'
            )
    );
}

But I'm still not happy. The regex don't need the () around every word. Or at all. Basically, you could write both as this:

/none|decimal|inside|hidden/g
/em|px/g

In the replacements, instead of $&, you use $0. This will replace everything that was matched.

You currently have the following code:

// Animation
$('.show-code')
    .on('click', function() {
        $(this)
            .next('pre')
            .slideToggle();
        return false;
    });

There's not much to say on this one. Using the .on() handler, you can take advantage of it by picking a common parent node. Then you set the 2nd argument to have a selector. Like this:

$('#fake-parent').on('click', '.show-code', function(){
    [...]
});

Also, notice that when you use return false; on an event handler, jQuery runs event.preventDefault() and event.preventPropagation(). Depending on what you are trying to do, you should be careful when returning anything in an event handler.


Since you have a lot of fields, I would suggest using a DataTable where each column is a field.  This not only keeps your data organized and easily accessible, but you can very efficiently write the data to a database, and display the data in a DataGridView, which also gives you ready access to methods for adding and editing the data.


Show/hide image in each list individually with same class

You need to find the .name item that is in the same block of HTML as the one being hovered.  One way to do that is to go up the parent chain from the one begin hovered to get the li tag and then use .find() from thereto find that .name item in that block.  You can use this code to do that:

$('.name').hide();

$(".first").hover(function() {
    $(this).closest("li").find(".name").stop(true).show();
}, function() {
    $(this).closest("li").find(".name").stop(true).hide();
});


Calculating percentages in arbitrary number of columns

It's quite good. I can only slightly simplify it:

NR==1 {print; next}
{
    label[NR] = $1
    for (i=2; i<=NF; i++) { sum[i] += $i; val[NR,i] = $i }
}
END {
    OFS = "\t"
    for (nr=2; nr<=NR; nr++) {
        $1 = label[nr]
        for (i=2; i<=NF; i++) $i = sprintf("%.2f", 100*val[nr,i]/sum[i])
        print
    }
}

don't need to store the header line, just print it and move on
I find sum[i] += col[i][NR] = $i needlessly complicated
take advantage of OFS and awk can build the line itself


I don't like a class that's just called Helpers - that's generally a code smell, something that ends up a big dumping ground for anything that doesn't quite fit anywhere else. Be more specific when naming things, perhaps VisualHierarchyHelper would be a better name?
I'm using a very similar method - the main difference is essentially the number ot return statements, and the childName parameter; I found this code on Stack Overflow a little while ago:
    /// <summary>
    /// Finds a Child of a given item in the visual tree.
    /// </summary>
    /// <param name="parent">A direct parent of the queried item.</param>
    /// <typeparam name="T">The type of the queried item.</typeparam>
    /// <param name="childName">x:Name or Name of child. </param>
    /// <returns>The first parent item that matches the submitted type parameter.
    /// If not matching item can be found,
    /// a null parent is being returned.</returns>
    /// <remarks>
    /// https://stackoverflow.com/a/1759923/1188513
    /// </remarks>
    public static T FindChild<T>(this DependencyObject parent, string childName)
       where T : DependencyObject
    {
        if (parent == null) return null;

        T foundChild = null;

        var childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            var childType = child as T;
            if (childType == null)
            {
                foundChild = FindChild<T>(child, childName);
                if (foundChild != null) break;
            }
            else if (!string.IsNullOrEmpty(childName))
            {
                var frameworkElement = child as FrameworkElement;
                if (frameworkElement != null && frameworkElement.Name == childName)
                {
                    foundChild = (T)child;
                    break;
                }
            }
            else
            {
                foundChild = (T)child;
                break;
            }
        }

        return foundChild;
    }

Notice the guard clause preventing a NullReferenceException that your method would throw if obj was null. I think this is a pretty neat way of finding a child node in the visual tree.
That said, it might be personal preference, but I think the readability of your code could benefit from implicit typing (var), especially in cases like this where the type is already pretty obvious:
TabItem ti = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem;
Popup popup = (Helpers.FindVisualChild<Popup>(ti) as Popup);
ImageColorPicker icp = (popup.Child as StackPanel).Children[0] as ImageColorPicker;

Becomes:
var ti = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem;
var popup = (Helpers.FindVisualChild<Popup>(ti) as Popup);
var icp = (popup.Child as StackPanel).Children[0] as ImageColorPicker;

And here you would have to make sure popup isn't null before accessing its Child member, if you want to avoid that possible NullReferenceException.
Also, you're casting too much - T should be of the type you've specified, so the return type of FindChild<ImageColorPicker> is ImageColorPicker, casting it to ImageColorPicker is redundant.

Update
The ImageColorPicker child has a Popup parent, which has a StackPanel parent, which has a Grid parent, which has a TabItem parent.
You're not fully using the recursiveness of your function when you're getting the color picker. I'd believe you could get it like this:
var tab = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem;
var picker = VisualHierarchyHelper.FindChild<ImageColorPicker>(tab, "ColorPicker");

That should work, because the search is recursive; you don't need to get everything in-between.


Bash is not efficient for processing large files line by line. For small data it's fine, but when a script starts to feel heavy, it's good to look for other alternatives. Also note that the line by line processing and breaking into columns is not easy to get right, I bet you spent quite some time on this. You wrote it well, but the result is not particularly easy to read, and I'm afraid this is as good as it gets with Bash.

So what's the alternative? Try with cut in a loop. Yes that will imply reading the file n-3 times, but I bet it will be faster than the pure Bash solution. And it will be nicely readable too, which is an extremely important benefit.

A few notes about technique:

Use $(...) instead of `...`
You took care to save IFS and then restore at the end, but it was unnecessary: when you do var=... somecmd, the value of var is only set in the environment of somecmd, it is unchanged for the current script. That being said, what you did is safe, so it's fine.
The incrementing i variable in the loop is a bit misleading, because i is a common name in counting loops, and at first I thought the count itself has some purpose. But it doesn't, this variable is used only to distinguish the first line from the others. I would write differently, to make the intention perfectly obvious.


Longest Substring Without Repeating Characters in JS

Style

Nice usage of arrow functions and spread operators. You can extend this to the function name as well:

const lengthOfLongestSubstring = s => { ... };

The code switches between two and four spaces within a block and between blocks. Choose one and stick with it throughout the entire program (the auto-formatter built into Stack Exchange does the job well).
Avoid the intermediate variable len here:

    const len = s.length;
    if (len < 2) { return len; }

The extra variable obfuscates the direct and explicit s.length and offers no performance benefit (as it would in C with strlen, which is linear). s.length is a numerical property and doesn't walk the list per call.
Use vertical whitespace around blocks. Here's how I'd rewrite the above lines:

    ...
    if (s.length < 2) {
      return s.length;
    }

    let res = [];
    ...

Then again, I prefer to omit this logic because the rest of the function body will handle the precondition automatically.
Variable names can be a bit more specific: tmp => seen, x => char, res => longest.

Performance

Your solution runs in O(len(longest_subsequence) * n) time, which is in the 70th percentile of solutions for this problem. The culprits are includes, findIndex, slice and spread inside the for loop, all of which require visiting up to every element in tmp.

We can improve the time complexity to linear and reach the 99th percentile. The key is using an object as a hash map instead of an array to keep track of the history. For each character in s, add it to the object with a value of its latest-seen index. Keep track of the start of the current candidate run. Whenever we encounter an item already in the map, check to ensure its index is indeed inside the current run. If so, record a new longest (if applicable) and begin a new candidate run.

Here's the code:

const lengthOfLongestSubstring = s => {
  let longest = 0;
  let start = 0;
  const seen = {};

  [...s].forEach((char, i) => {
    if (char in seen && start <= seen[char]) {
      longest = Math.max(i - start, longest);
      start = seen[char] + 1;
    }

    seen[char] = i;
  });

  return Math.max(s.length - start, longest);
};


Find the total number of ways W, in which a sum S can be reached in N throws of a dice

1. Review

The sum \$s=0\$ can be reached in \$n=0\$ throws in exactly one way, but:

>>> get_sum_dp(0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr161002.py", line 32, in get_sum_dp
    t[1][j] = 1
IndexError: list index out of range

The name get_sum_dp could be clearer (what does "dp" mean? dynamic programming?). I would use a name like dice_rolls.
A docstring would be helpful in understanding what the function does.
It's usually more convenient to return a result instead of printing it. This would allow the result to be used in other computations if needed.
Instead of

t = [[0 for i in xrange(1,s+2)] for j in xrange(1,n+2)]

you could write:

t = [[0] * (s + 1) for _ in xrange(n + 1)]

(It's conventional to use _ for a loop variable whose value is not used.)
The initial condition is:

for j in xrange(1,7):
    t[1][j] = 1

but it would be simpler to use the following initial condition:

t[0][0] = 1

and change:

for i in range(2, n+1):
    for j in range(1, s+1):
        if k < j:

to:

for i in range(1, n+1):
    for j in range(1, s+1):
        if k <= j:

(This also fixes the bug I noted in point 1 above.)
In the nested loops:

for i in range(2, n+1):
    for j in range(1, s+1):

the loop over j goes all the way from 1 to s. But some of this may be wasted, because the sum of i dice must be between i and i * 6. So you could reduce the amount of work by writing:

for i in range(2, n+1):
    for j in range(i, min(s, i * 6) + 1):

Similarly, instead of checking k on every loop iteration:

for k in range(1,7):
    if k < j:
        t[i][j] += t[i-1][j-k]

you could compute the loop bounds in advance:

for k in xrange(1, min(6, j) + 1):
     t[i][j] += t[i - 1][j - k]

2. Revised code

def dice_rolls(n, s):
    """Return the number of ways in which a sum s can be reached in n
    throws of a 6-sided die.
    """
    t = [[0] * (s + 1) for _ in xrange(n + 1)]
    t[0][0] = 1
    for i in xrange(1, n + 1):
        for j in xrange(i, min(s, i * 6) + 1):
            for k in xrange(1, min(6, j) + 1):
                t[i][j] += t[i - 1][j - k]
    return t[n][s]

3. Alternative approach

Dynamic programming builds up a table of solutions to sub-problems from the bottom up (starting with small problems and using those to solve larger problems). But an alternative approach works from the top down, using recursion to compute the sub-problems, and memoization to avoid duplicated work. This often results in clearer code and it is easier to compute only the table entries that you need.

In Python 3.2 or later, you can easily memoize a function using the @functools.lru_cache decorator, like this:

import functools

@functools.lru_cache(maxsize=None)
def dice_rolls(n, s):
    """Return the number of ways in which a sum s can be reached in n
    throws of a 6-sided die.
    """
    if s < n or s > n * 6:
        return 0
    elif n == s == 0:
        return 1
    else:
        return sum(dice_rolls(n - 1, s - i) for i in range(1, 7))

(Python 2.7 lacks functools.lru_cache, but there's a backport package.)


"Can you answer these queries I" challenge

static int[] dist ;
static int[][][] vis;
static ArrayList<Integer>[] resu;
static char[][] graph;
static int max;
static int min;
static int[] dp;
static int zz;
static int zzz;
static nodes[] som;
static nodes temp;
static boolean fin;

Your variable names are very hard to understand. What's dist? Distance? Then why is it an array? What's vis? Visuals? Why is it a 3D array?

Make your variable names clearer, and add comments what it does.

Also, there is inconsistent spacing. You do stuff like:

static int[] dist ;

and you also do:

static int[][][] vis;

Be consistent. The conventions are "no space before ;", so this:

static int[][][] vis;

is correct. Also:

static class nodes{

Standard conventions for class names are PascalCase, not camelCase or alllowercase.

Also, I think all your variables need some breathing space:

if(j<=mid) return query(2*current, a, (a+b)/2, i, j);

should be:

if(j <= mid) return query(2 * current, a, (a + b) / 2, i, j);

Also, your formatting seems messed up. You have extra spaces everywhere, so try removing them.


Okay, I realized what I was doing all wrong.
The Manhattan distance defined here is not admissible. Consider an initial state: 0 1 7 2 3 4 5 6 8. So the possible number of moves required to move 7 to its original position (i.e index 7) is 3 (down->down->left) but here the heuristic estimates it as 5 (i.e 7-2). So a better way of defining heuristic would be :

def manhattan(self):
        h = 0
        for i in range(3):
            for j in range(3):
                x, y = divmod(self.board[i][j], 3)
                h += abs(x-i) + abs(y-j)
        return h


3 last distinct values of a list taken from a list of dictionaries

Use a dict comprehension to keep track of the last index for each order_id_local and skip blank entries:

local_ids = {order['id']['order_id_local']:n for n,order in enumerate(data) if order['id']}

Then reverse sort the dictionary keys by their value and slice off the first 3:

sorted(local_ids.keys(), reverse=True, key=local_ids.get)[:3]

result:

['xxx_003', 'xxx_002', 'xxx_001']


struct link{
    int data;
    link *next;
};

Are you sure you want this to be outside of the class? This could be in the private section in the class link_list since the outside world does not need to know of this class at all.

int boundaries = 0;

What is boundaries? It seems like this is your actual size of the list but I had to check your code to make sure what it is. Call it size or entries or something like this.

link *tail;
link *temp;
link *head = NULL;

There is no reason to have temp as a instance variable. And you do not use tail in your code, so drop them both. And use nullptr instead of NULL.

void add_node(int data){

    temp = new link;
    temp->data = data;
    temp->next = NULL;
    if (head == NULL){
        head = temp;
        boundaries++;
    }
    else{
        link *tail = head;
        while (tail->next != NULL){
            tail = tail->next;
        }
        tail->next = temp;
        boundaries++;
    }
}

Again, use nullptr. And if you had used your tail you wouldn't need to iterate over the whole list to get to the end.

void delete_b(){
    link *end = head;
    link *next_to_end = NULL;
    while (end->next != NULL){
        next_to_end = end;
        end = end->next;
    }
    next_to_end->next = NULL;
    end = NULL;
    boundaries--;
}

What's b? (Oh yeah, I think I don't need to remind you about nullptr again.)

void add_front(int data){
    link *ptr = new link;
    ptr->next = head;
    ptr->data = data;
    head = ptr;
    boundaries++;

}

add_node and add_front? What's the difference? Sure, I know what the difference is; I've seen the code. However, I don't like to look through the code to see what a function does. Call them add_front and add_back or something like this (head and tail might fit better, programmers will understand).

void delete_front(){
    link *new_head = head;
    new_head = head->next;
    head = NULL;
    head = new_head;
    boundaries--;

}

What is this playing around? That's three useless lines of code:

void delete_front(){
    link* tmp = head;
    head = head->next;
    delete tmp;
    boundaries--;
}

void add_by_position(int data, int pos){
    link *node = new link;
    link *linker = head;
    node->data = data;
    for (int i = 0; i < pos; i++){
        linker = linker->next;
    }
    node->next = linker;
    linker = head;
    for (int i = 0; i < pos - 1; i++){
        linker = linker->next;
    }
    linker->next = node;
    boundaries++;

}

by_position sounds silly. Call it add_at. And why do you reset linker and start over again? That's totally unnecessary.

void add_at(int data, int pos){
    link *node = new link;
    node->data = data;
    boundaries++;
    if(pos == 0) {
      node->next = head;
      head = node;
      return;
    }

    link *linker = head;
    for (int i = 0; i < pos - 1; i++){
        linker = linker->next;
    }
    node->next = linker->next;
    linker->next = node;
}

You should also delete the nodes in your delete/remove functions.

That's everything for now. You could've easily made a template out of this class, however, you should first fix your problems and then - if you like - ask another question with your new code.


HackerRank - Binary tree to compute the Nth power of natural numbers that sum up to X

What you're essentially doing with your binary tree is checking all possible combinations of numbers from the list [i^n | i <- [1..x]]. That's quite a lot of combinations! (Exercise: how many?)
Not all of those combinations are sensible, however. For example, if x = 100 and n = 2, and you've already chosen, say, 4 and 5 (giving 62+72=85), then adding 82=64 is not going to help, nor is adding 92=81. In your current solution, however, you're still checking those.
So how does one encode this knowledge in the search for solutions? The key thing is that we can build the solution recursively: we can use an already computed answer for a smaller case to help answer a larger case. If we're given x = 10 and n = 2, then we can only add 12, 22 or 32. If we try adding 32, we have only 1 left to fill, which we can only do by adding 12. If, instead, we start by trying 22, we have to make 6, which is impossible. Starting with 12 lets us choose 32 to fill up the remaining 9. Since only the set of numbers counts, not their order, this means there is only one solution for x=10,n=2: namely, {12,32} (as stated in the problem).
Checking whether two solutions are the same modulo ordering is annoying, however. Can we do better? Yes we can, by adding another parameter to the problem.
Think about how we could do this before reading on.

A way to change the problem to prevent us from generating multiple solutions that are really the same set of numbers, is to add as a parameter the maximum value we're allowed to choose. So a problem is now not only specified by (x=10,n=2), but also by an integer M; for example, if M=9, then we may add 12≤9, 22≤9 and 32≤9, so (x=10,n=2,M=9) has one solution: {12,32}. However, (x=10,n=2,M=2) has no solutions, because by only using 12 and 22 you can never make 10.
How is this useful? Well, consider how we could, as a lazy office worker, go about computing how many solutions there are to (x=10,n=2,M=10). (For the original problem, we just set M=x, since choosing numbers higher than x is certainly useless.) This lazy office worker realises that either x=0, in which case we have precisely 1 solution (choosing no numbers at all), or x≠0, in which case we need to choose at least one number. If we choose, say, i2, then the remainder still to fill is 10 - i2. Since our lazy office worker is also clever, they realise that if we force any solutions for 10 - i2 to only choose numbers smaller than i2 (i.e. set M = i2 - 1), then we won't ever get any duplicates: there may certainly be solutions for our (x,n,M) that choose i2 and also some larger j2, but then we'll find that one by starting with j2 and then going downward.
So our lazy office worker writes down a series of smaller problems: [(x-in,n,in-1) | i <- [1..M]], to solve for the next office worker in line. (These are recursive calls.) The total number of solutions is just the sum of the number of solutions for each of these subproblems.
An alternative, more direct way to explain the same way of solving, is to note that while all solutions are sets of distinct integers, we can represent those sets by sorted lists. If the empty solution is not possible (i.e. x≠0), then each of the possible solutions for our current problem has one largest value, so we can find all solutions for the problem going over each largest value in from 1 to M, computing the solutions for (x - i2, n, in - 1), and prepending that largest value i2 to its corresponding sub-solutions. If, instead of building the actual solution lists we just compute the number of them, we arrive at the same solution as above.

Now the above is not very formalised yet, and that is on purpose. Because for me, the next step to formalisation would be writing out the recursive function, which is 95% of the work in implementing the program. And that's your task. :)
If any of the above is unclear (probably), or you get stuck, feel free to ask further questions.
EDIT: When I coded out my first solution for the problem, I also cached recursive calls in a table, making it a dynamic programming solution. However, for the given input range that apparently doesn't help, so a standard recursive program works fine.
EDIT 2: If you want to handle 1000 1, then you do need dynamic programming :)


Prepare data for a contour plot with matplotlib

You may want to follow PEP8 a bit more closely to learn how to write code that is easily understood by most Python developers. Eg. mom = [0.3, 0.13] instead of mom = [0.3,0.13] and four spaces indentation.

Try to be more careful about variable names. I couldn't understand what most of them meant, which is probably because I don't much about the code you're writing. But think about your readers (including you in three months) and wonder what are the best ways to convey information in your variable names. For example, 'myfile'  suggest that this is not a collection. And 'my' doesn't provide any useful information.

There's a common idiom in Python to avoid dealing with ranges explicitely: enumerate().

for i, this in enumerate(myfile):
    for j, that in enumerate(myfile[i]):
        i_new = ...
        y[i_new] = ...
        x[i_new] = ...
        z[i_new] = ...

If you often deal with ranges, it will certainly help you at some point.


Navigational bar content built depending on login state

I discovered that inside of ng-repeat directive expressions aren't evaluated which is why the function wasn't affecting the navigation state. to make the navigation state change I created another array of objects inside my navigation controller like this:

  $this.loggedInLinks = [
    {name: 'About-us', ref:'about', title: 'About DeafandHoh Page'},
    {name: 'Facts', ref: 'facts', title: 'Facts & Deaf Empowerment Page'},
    {name: 'News', ref: 'news', title: 'News Page'},
    {name: 'Products', ref: 'products', title: 'Products Page'},
    {name: 'Directory', ref: 'directory', title: 'Directory Listings Page'},
    {name: 'Resources', ref: 'resources', title: 'Resources Page'},
    {name: 'Profile', ref: 'profile', title: 'User Profile Page'},
    {name: 'Chatroom', ref: 'chatroom', title: 'Come Chat!'},
    {name: 'Logout', ref: 'logout', title: 'Login & Register Page'}
];

and to allow the state to change when the user logged in I attached a ng-hide to the default HTML navigation bar like so

And Replicated that in another HTML section but instead with ng-show for when the LoginService.loggedIn state changed to truthy

Now when a user logs in the navigation bar changes appropriately.


Parsing a string with regex to build JSON

I would manipulate RegExp.lastIndex with the sticky flag to avoid slicing the source string:

function parseGame(text) {
  const RX_HEADER = /!report Game Type:\s*(\d|\w+)(?:\s*(\w.*))?/y;
  const RX_TEAM = /Team:\s*(\d+)/y;
  const RX_DISCORD = /<@(\d+)>/y;
  const RX_POSITION_DISCORD = /(\d+):\s*<@(\d+)>\s*(?:\w+\s?\w+)?/y;
  const RX_WHITESPACE = /\s+/y;

  let pos = 0;
  const data = {players: []};

  function match(rx) {
    rx.lastIndex = pos;
    const matches = rx.exec(text);
    if (!matches) {
      return [];
    }
    pos = rx.lastIndex;
    if (pos < text.length) {
      RX_WHITESPACE.lastIndex = pos;
      RX_WHITESPACE.exec(text);
      pos = RX_WHITESPACE.lastIndex || pos;
    }
    return matches;
  }

  function readHeader() {
    const ID_NAME_MAP = {
      1: 'Diplo',
      2: 'Always War',
      3: 'FFA',
      4: 'No Diplo',
      5: 'Team',
      6: 'Duel',
      7: 'No War',
    };
    let [_, gameType, gameMod] = match(RX_HEADER);
    if (!gameType) {
      return;
    }
    gameType = gameType.toLowerCase();
    for (const type in ID_NAME_MAP) {
      if (type === gameType || ID_NAME_MAP[type].toLowerCase() === gameType) {
        data.type = Number(type);
        break;
      }
    }
    if (gameMod) {
      data.moddifier = gameMod;
    }
  }

  function readTeams() {
    let teamId;
    while ((teamId = Number(match(RX_TEAM)[1]))) {
      let position = 0;
      let discordId;
      while ((discordId = match(RX_DISCORD)[1])) {
        data.players.push({
          teamId,
          discordId,
          position: ++position,
        });
      }
    }
  }

  function readPlayers() {
    while (true) {
      const [_, position, discordId] = match(RX_POSITION_DISCORD);
      if (position) {
        data.players.push({
          discordId,
          position: Number(position),
        });
      } else {
        break;
      }
    }
  }

  readHeader();
  if (data.type === 5) {
    readTeams();
  } else {
    readPlayers();
  }
  return data;
}

And just to nitpick:

[\s+]? matches whitespace and a + which seems weird so I replaced it with  \s*
[\s\S]? in rePlayer is ambiguous as it allows any single character, which seems weird.
I would expect only whitespace and new line(s) allowed e.g. \s*
I usually specify a match group is unused via ?: e.g. (?:foo)?
Indent the code consistently
Consistently use spaces before opening braces e.g. if (foo) { instead of if(foo){
No need for var generally if you use ES6 anyway
Use const for variables you don't reassign (more info)
Use a consistent type for the id and position instead of mixing strings & numbers
Use a JS linter like eslint to catch the errors like a global player variable
Use camelCase for properties and variable names
Use object literals like arr.push({foo: 'bar'}) without an interim variable


Assign variables to save each directories from a folder

You should create functions to get rid of your repetitive logic. This is called DRY (Don't repeat yourself).

The first task you repeatedly accomplish is getting the first object in a base folder matching some string.

This can be accomplished using this function:

def find_in(root, string):
    return next(os.path.join(root, x) for x in os.listdir(root) if string in x.lower())

Instead of building the whole list and then taking only the first element, this is a generator and the first element of that generator is returned. This should save a bit of time and memory. To appreciate how much, try running these three commands and see how long they take:

>>> next(x**2 for x in xrange(100000000)
>>> next(x**2 for x in range(100000000)
>>> [x**2 for x in range(100000000)][0]

(The first one uses xrange, which is like range, but returns also an object like a generator, whereas the normal range returns the full list in Python 2.7.)

The second task you accomplish is the same thing as the first, but nested once. You want the first element in a stepX folder and then get the first object containinginput or output from that folder.

For this we can use the previous function and define a second function:

def find_nested(root, step, direction):
    return find_in(find_in(root, step), direction)

After this is done we can save the results in lists, instead of separate variables. Lists are for collections of similar objects.

In addition, there is an official Python style-guide, PEP8, which you should adhere to. It recommends using lower_case_with_underscores instead of camelCase. You should also avoid abbreviating variable names. Clear and more readable is better.

Final code:

import os

def find_in(root, string):
    """
    Returns the first object in the folder `root` which matches `string`.
    Case in-sensitive.
    """
    return next((os.path.join(root, x) for x in os.listdir(root) if string in x.lower()))

def find_nested(root, step, direction):
    """Returns the `direction` object from the `step` folder in `root`."""
    return find_in(find_in(root, step), direction)

if __name__ == "__main__":
    model_field = r'C:\model'
    root_folder = find_in(model_field, 'base')

    folders = ['oilwell', 'waterwell', 'quar', 'linear', 'county', 'tiger']
    fields = [find_in(root_folder, string) for string in folders]

    steps = ["step%i" % (i + 1) for i in range(6)]
    input_fields = [find_nested(root_folder, step, "input") for step in steps]
    output_fields = [find_nested(root_folder, step, "output") for step in steps]

In case not all stepX folders actually contain an input or output file/folder, this will raise a StopIteration. To avoid this, you can unwrap the list comprehension into an actual for loop and print the missing file:

input_fields = []
for step in steps:
    try:
        input_fields.append(find_nested(root_folder, step, "input"))
    except StopIteration:
        print "Folder", step, "has no `input` file."

And similar for the output_fields.


Sorting an array using a Binary Search Tree with C++

Your code is readable and easy to understand. Said that I would like to make you think about how you handle the operations in your BSTree.

You are building the functions alone, and what that causes is to manually manage these functions and compromise the structure of your tree if accidentally you write something wrong.

You should opt for an Internal management rather than external one. For example:

struct BinaryNode
{
    int label_;
    Node* left_;
    Node* right_;

    //having constructors makes you write less code

    BinaryNode(Node *left, const int &label, Node *right) :
        label_(label), left_(left), right_(right)
    {
    }

    //const [datatype]&
    //means to not copy the value of the parameter
    BinaryNode(const int &label) :
    //nullptr is typesafe use it instead of NULL which is a macro
        label_(label), left_(nullptr), right_(nullptr)
    {
    }

    ~BinaryNode() {
        delete left_;
        delete right_;
    }
};

class BinarySearchTree
{
private:
    BinaryNode *root_;

protected://if some derived class is needed (as an AVLTree)
    //Google about virtual functions for abstract classes (pure virtual too)
    virtual void Insert(const int &x, Node *node)
    {
        if (x < node->label_)
            if (node->left_ == nullptr)
                node->left_ = new BinaryNode(t);
            else Insert(t, node->left_);
        else if (x > node->label_)
            if (node->right_ == nullptr)
                node->right_ = new BinaryNode(t);

        //If x is in the tree it does not include x again
    }

public:
    virtual void Insert(const int &x)
    {
        Insert(x, this->root_);
    }
};

Don't misunderstand me, Your code is useful and is pretty (is something good to read). But, manage things externally can be messy.

Also, I recommend you to read the Google C++ Code Style

Hope it helped.

Edit: What does const int& x means?

const int& x is a constant reference to a value of type int so, when you use it, your function does not copy the sent value, instead it "sees where the value is allocated" takes it in account and then starts the procedure you describe within the function, additionally you cannot modify that value (because it's constant [const])

the main difference is with const [datatype]& you save space. With [datatype] [paramName] you Copy the value which implies allocate the copied value.

If you feel lost in some part read it slowly it has many concepts, and remember practice makes this make sense.


BIOS Video Service INT 10H (functions 9 and 13H) functionality

Some corrections

The LEAVE comments mention ES:SI where you intended DS:SI
If the comment for mov dx, 0x11e talks about "Line 2", then it should also say "Column 31" (in stead of "32")

add     dx, 255         Row 3, Column 30

This is a very nice approach! Although for reviewing purposes I had to read it a few times over, it is definitely better here than the simpler mov dx, 0x021d would have been.

Optimizations

When registers need to be preserved, it will be better to group the pushes and pops together. You've put them amongst the rest of the instructions and maybe because of this introduced the error of inverse restoration. A trick I've been using for many years now is numbering my push and pop instructions (see below). This facilitates enormously discovering these errors.

push    es            ;(1)
push    di            ;(2)

The calculation of the ES segment register can be shorter and clearer.

mov     ax, VIDEO_SEG ;0xB800
add     ah, bh        ;BH=Display page
mov     es, ax

The calculation for the video address in DI can be optimized a lot. Next code does it in 14 bytes, where your code used 18 bytes. Also it uses only half the instructions.

movzx   ax, dh        ;DH=Row
imul    ax, 80        ;80 characters per row
add     al, dl        ;DL=Column
adc     ah, 0         ;(*)
imul    di, ax, 2     ;Double for character+attribute AND bring in DI

(*) If you know that the counter in CX will always be reasonably small, then maybe write adc ah,ch here and shave off another byte.
In order to decide what the function should do you test the CX register using or cx, cx jz 553H. This can easily be shortened to jcxz 553H. A 2 byte gain.
Incrementing the resulting counter in CX will be shorter using inc cx because that's a 1-byte instruction.
The loop currently uses 2 jump instructions per iteration. This is wasteful in terms of speed and can easily be avoided as you'll see in below summary.

In summary

  push    es            ;(1)
  push    di            ;(2)
  mov     ax, VIDEO_SEG ;0xB800
  add     ah, bh        ;BH=Display page
  mov     es, ax
  movzx   ax, dh        ;DH=Row
  imul    ax, 80        ;80 characters per row
  add     al, dl        ;DL=Column
  adc     ah, 0         ;(*) Possibly use "adc ah, ch" with CH=0
  imul    di, ax, 2     ;Double for character+attribute AND bring in DI
  lodsb
  jcxz    Test          ;Till end of string marker
Char:
  push    cx            ;(3)
  rep     stosw
  pop     cx            ;(3)
  jmp     Exit
String:
  inc     cx
  stosw
  lodsb
Test:
  test    al, al
  jnz     String
Exit:
  pop     di            ;(2)
  pop     es            ;(1)
  ret


go is under your control, you can guarantee that it will always have a result, so you don't need to use Option for it. Also, the special cases for 0 and 1 are not neccessary. Counting backwards instead of forwards is more a matter of taste here, but it does reduce the dependency on the outer context.

def fib(n: Int): Option[Int] = {
    @tailrec
    def go(count: Int, prev: Int, acc: Int): Int = {
        if (count == 0) acc else go(count-1, acc, acc + prev)
    }
    if ( n < 0) None else Some(go(n, 1, 0))
}

However, if you want a really fast implementation (only interesting when you use BigInt), you should use these formulas, where you need only ~log(n) iterations instead of n:

$$
\begin{align}
F_{2n-1} &= F_n^2 + F_{n-1}^2 \\
F_{2n}   &= (F_{n-1} + F_{n+1}) F_n \\
         &= (2F_{n-1} + F_n) F_n
\end{align}
$$


Google Maps API - reading locations from file and displaying markers on map

Your Marker and ShelterObject instances have the same data inside. (except the additional hardcoded (!) string "Antal platser:", whatever that means) Now you have two islands of data. You collect them in two different lists, shelterObjects and shelterMarkers. That is bad, High memory usage and difficult modifications are the drawback. If you want to add/delete/modify one you have to to it in two lists and keep it synchronized. I recommend to only have one island of data (ShelterObjects-array) and whenever you need ShelterMarkers, you convert them. For example you can add a method getAsMarker() to your ShelterObject class that returns itself as Marker. If you have enough memory and want to save performance you only create them when needed and store them for later re-use(see Lazy Instantiation), like so

class ShelterObject {
   ...
   int Marker marker;
   public Marker getAsMarker(... mMap) { // or pass mMap in constructor.
      if (marker != null) {
         return marker;
      }
      LatLng geoPosition = new LatLng(this.getLatitude(), this.getLongitude());
      marker = mMap.addMarker(...); // creates marker via MarkerOptions
      return marker;
   }
   ...
}

What is "LatLng"? You barely can speak that out. If you mean just a pair of latitude and longitude coordinates, then just name it like that: geoPosition, coordinates, latitudeAndLongitude. Try to use short and meaningful names, but no abbreviations. In old times, even Microsoft used code abbreviations like "lptcstr" (google it). Because of bad experience, this is discouraged now. I can't count how many times I have looked up which combination of manager and number the managerNumber was abbreviated: "num", "nbr", "no", "numero", "man", "mgr", "mangr" etc.
Delete the code line below. You overwrite it right away, so you can leave it out for less code clutter.

String line = "";
You forgot to close your stream in a finally-statement of your try-block. This is a severe bug since it's hard to detect when files remain open and suddenly your program crashes when it runs out of file handles. Alternatively you can use a try-with-resources statement.
Avoid using member variables like they are global. Just pass them as parameters. You can better test it and make your code more stable.
I will give you an example what I mean:
Assume you have following lines inside your init-method:

generateShelterObjects();
addShelterMarkersToMap();

Now somebody changes it to following code that crashes or does not add the shelterMarkers:

addShelterMarkersToMap();
generateShelterObjects();

Does he know that he is not allowed to swap the lines when he needs to refactor?
Maybe he does it by accident?

You can avoid that by coding:

ArrayList<ShelterObject> newShelterObjects = generateShelterObjects();
ArrayList<Markers> newShelterMarkers = addShelterMarkersToMap(shelterObjects);
shelterMarkers = newShelterMarkers;
shelterObjects = newShelterObjects;

Now when you swap the first two lines, it will not compile anymore. Also there is no possibility that you can have a nullPointerException in addShelterMarkersToMap() anymore. (I assume that you return an empty Map instead of null in generateShelterObjects() or throw an exception there).
You also cannot have inconsistent data anymore. Just imagine in generateShelterObjects() your map is half-filled when an error occurs. Or your markers are half created when an error occurs. You need to catch the exception and clean both maps. Having inconsistent data is worse than just keeping the old, consistent ones.

Use "/** comment **/" instead of "// comment" on top of your methods, so you can create javadocs easily and the IDE can show it as mouseover-message


Is there a better way to implement this string builder?

I really have difficulty understanding your explanation or your code, but the wanted output is clear. So going only by that I propose this function:

function duplicates(testArray, id = 1)
{
    return testArray.filter(testId => testId !== id);
}

the filter() method creates a new array with all elements that pass the test implemented by the provided function. In this case I test that the array items are unequal to the given id. The output of your tests is:

  This item is the same as item 2
  This item is the same as item 2,3
  This item is the same as item 2,3,4

So, there's not the fancy 'and' in there yet, but that can be added. Is it really needed? Anyway, adding a bit of extra code like this:

function formatArray(idArray)
{
    var ending = (idArray.length > 1) ? ' and ' + idArray.pop() : '';
    return idArray.join(', ') + ending;
}

function duplicates(testArray, id = 1)
{
    return formatArray(testArray.filter(test => test !== id));
}

where we join the array to a string separated by commas, except for the ending if there are multiple items, when we insert an 'and'. The thing that might not be obvious is the conditional (ternary) operator. If you don't like it you can replace it with a normal if (...) {...} else {...} statement. This returns:

  This item is the same as item 2
  This item is the same as item 2 and 3
  This item is the same as item 2, 3 and 4

Now this is "Code Review" so I should review your code. That is difficult. I can almost see what you were trying to do, but it is such a mess (sorry). It seems you started with the for loop and then just created this Frankenstein monster by adding bits. Inside the loop you have four ifs, two elses and even a return. Some of the actions are the same, like adding a space. I don't believe even you know exactly what's going on there. It might work, but that's it. This is not how you should be programming.

Some advice:

Try to analyse the problem before you start writing any code. There are two clear distinct jobs to do:

Get rid of the duplicates.
Generate the output.

Keep these two jobs apart. That makes each problem easier to solve and leads to easier to understand code, because the jobs themselves are easier. Ideally these two jobs should be done in two seperate functions. A function should only do one thing, and not two.

Now I have to agree that, what I did, simply requires a lot of experience. You need to know the language you're using. That will come with time and practice.

Another thing you need to pay attention to is the names you use. One of the major reason I cannot understand your code is that it is unclear what it all means. What is in duplicatesArray? And why is the function called duplicates? That just doesn't make much sense. Something like removeDuplicates would be better as a function name, because it implies a clear action.

In my personal opinion each function should always, and only, have one return in it. I'll admit that I don't always stick to this rule, but as a general idea it is sound. Having multiple returns makes a function harder to understand, and having no return just seems lazy. There's always something to return.


Dividing the screen in two halves using LinearLayout

Your layout looks very good. android:layout_weight is the correct way to solve this.
A couple of other notes regarding your XML layout:

As your outermost LinearLayout has match_parent for both width and height, there is no need for android:gravity="center".

I would write 0dp instead of 0dip (even though it is the exact same thing). Using dp just seems more common to me. This is a very minor nitpick though :)

Don't hardcode strings in your XML. Use the strings.xml resource file and use android:text="@string/button3text"

You might know about this but either way you (and any future readers of this post) should also be aware that there exists android:layout_gravity. Although they sound similar, they are not the same thing. Read more about the differences between them in Android - gravity and layout_gravity

If, in the future you want to play around a bit more with layout_weights, you should take a look at What is android:weightSum in android, and how does it work?, especially this answer

If you would like to support landscape mode as well, I suggest learning how to use Android Fragments. If you would like to support older devices, there's a support package that can help with that. A Fragment has one onCreate method and one onCreateView method, which makes it easy to persist data between screen orientation changes (or other changes) while creating a new view for the data.

Summary:
Your layout looks excellent. At least in my eyes.


Calculating series of rows to use to play a melody on 5-row Bayan Accordion

Done:

improved formatting and layout
instead of car and cdr, use first and rest.

Missing:

documentation strings
example

Only slight improvements.

No need to use list:

(defparameter *rows* '((:c  :ds :fs :a )
                       (:cs :e  :g  :as)
                       (:d  :f  :gs :b )))

Okay:

(defun row-for-note (note)
  (position-if (lambda (row) (find note row))
               *rows*))

(defun rows-for-notelist (notelist)
  (mapcar #'row-for-note notelist))

Compute alternatives directly, without setq. Local functions for repeated use. Use cons. Not so good: recursion limits use, because of limited stack depth.

(defun possible-alternates (rowlist)
  (let ((alternatives (if (rest rowlist)
                          (possible-alternates (rest rowlist))
                        '(()) )))
    (flet ((add (item)
             (mapcar (lambda (x) (cons item x))
                     alternatives)))
      (case (first rowlist)
        (0 (add 0))
        (1 (append (add 1) (add -2)))
        (2 (append (add 2) (add -1)))))))

(defun count-jumps (rowlist)
  (loop for (a b) on rowlist
        while b
        count (> (abs (- a b)) 1)))

Slight improvements:

(defun best-pattern (notelist)
  (let* ((alternates (possible-alternates (rows-for-notelist notelist)))
         (jumps      (mapcar #'count-jumps alternates))
         (min-jump   (loop for j in jumps minimize j)))
    (loop for a in alternates and j in jumps
          when (= min-jump j)
          collect a)))


It's very strange you're using instance_eval. That's not how a regular program should work and is not needed in your code.

If you want to avoid calling 4 instance methods from a class instance method, then you can create a new instance method like:

def workflow
  seek_ticket_price
  seek_number_of_attendes

  print_revenue
  print_profit
end
def self.run
  TheatreCLI.new.workflow
end

Maybe it's not a problem here, but using a lot of instance_eval for saving keystrokes looks like working around a bad API.  Also my gut feeling tells me that such practice can lead to unexpected troubles if used outside class body.


Php Login Class - Security and Logic check

Security

sha1 is not secure enough for password hashing as it's way too fast. This is also noted in the documentation. Use bcrypt instead.
=== is not timing safe, use a timing safe string compare instead (bcrypt does this for you).
You should really use salts when hashing passwords (bcrypt does this for you).
You shouldn't safe the password in the session data.

Misc

Your formatting is all messed up, leading to less readable code. Your indentation is off quite often, your usage of newlines and curly brackets is inconsistent, and you should really always use curly brackets, even for one-line statements (to reduce bugs and increase readability; return false; return false; eg is hard to understand, especially with your indentation).
if (cond) return true; else return false; can be written as return cond.
Binding the session to the ip increases security, but decreases usability (eg for mobile users).
Having three nested ifs instead of one if with & can sometimes reduce readability.
You seem to use == and === interchangeably. In most cases, === would be the correct choice, as it can avoid bugs.
You should only create one db object and pass that around, instead of creating a new one each time.
I'm not sure what verifySessionUser is actually used for. The user didn't set the user id, you did. So it should always be correct, and the check should be unnecessary.
getSession: From the name, I would expect that this returns a session. But it doesn't. isLogedIn seems more fitting. And then I would rename verifyUser to logIn to make it fit.


Loop months between a time span yyyy-mm and yyyy-mm

These are all good sugestions but to my taste not linq-ish enough and not really reusable. Since I don't like writing the same code serval times you might want to encapsulate some of this logic for later use.

You can extract two pieces. First you have a date-time range so create a Range struct. Here's a very simple one (as an example without any parameter validation - actually T should be IComparable so you can assure the range is valid).

readonly struct Range<T>
{
    public Range(T min, T max)
    {
        Min = min;
        Max = max;
    }

    public T Min { get; }

    public T Max { get; }
}

Then you are interpolating between min and max. Put this in an extension that will consume a Range and do the rest:

public static IEnumerable<T> Interpolate<T>(this Range<T> range, Func<T, T> next) where T : IComparable
{
    var current = range.Min;
    while (current.CompareTo(range.Max) <= 0)
    {
        yield return (current = next(current));
    }
}

Now all you need is to parse the date so how about one more helper for that too?

static class Range
{
    public static Range<DateTime> FromDateTime(string min, string max, string format)
    {
        return new Range<DateTime>(
            DateTime.ParseExact(min, format, CultureInfo.InvariantCulture),
            DateTime.ParseExact(max, format, CultureInfo.InvariantCulture)
        );
    }
}

And we're ready to go. Create a range and let the extension work.

var range = Range.FromDateTime("2015-02", "2018-11", "yyyy-MM");
range.Interpolate(d => d.AddMonths(1)).Dump();

Now you have nice components that you can use in many more places and maybe in several projects.


Custom Exceptions based off the Visual Studio snippet

Using strongly typed data avoids this situation.

One easy and simple way to fix this argument confusion would be passing the user defined datatype instead of string which is reserved for message.

In TenantException sample, if you have Object model for Tenant, pass that object and let the constructor does the remaining with that.

[Serializable]
public class TenantNotFoundException : Exception
{
    public TenantNotFoundException()
    { }

    public TenantNotFoundException(string message)
        : base(message)
    { }

    public TenantNotFoundException(string message, Tenant tenant)
        : base(string.Format("Tenant '{0}' not found. {1}", tenant.Name, message))
    { }
}


Some suggestions:

Passing the code through at least one linter such as flake8 or pycodestyle will make for more idiomatic and therefore readable code.
Do you have any automated tests? If so, do they test all four combinations of weights and bin_index?
Do you really need weights and bin_index to be defaulted? I'm generally suspicious of code which defaults parameter values without a very clear reason.
Functions are first class citizens in Python, so rather than your nested if statements you can decide which method to call and what the second parameter should be with two unnested if statements:

if bin_index:
    binning_function = _bincenter
else:
    …

if weights:
    …

Naming is very important. I can't easily follow your code because things are named for what they are and not for what they contain or what they are used for. For example, pointdict tells me nothing about its contents and res could be short for “result”, “response” or something else entirely.
Reusing variables is generally discouraged - they make the information flow confusing, and they should be optimized away by the interpreter.
I don't remember the precedence rules other than for simple arithmetic by heart, so I'd enforce it using parentheses in expressions like x//res+0.5.

Rather than using a defaultdict(list) you can just pointdict.get(key, []) if you know the dict is sparse. This is purposely not a suggestion because whether it's appropriate or not depends on the programming environment, but it is an option.


You can get the same results a little more directly.

def cumulativeTokenise(string: String): Array[String] =
  string.split("\\s+")
        .inits
        .map(_.mkString(" "))
        .toArray
        .reverse
        .tail

Or a, perhaps simpler, two step procedure.

def cumulativeTokenise(string: String): Array[String] = {
  val tokens = string.split("\\s+")
  Array.tabulate(tokens.length)(n => tokens.take(n+1).mkString(" "))
}

One problem I see here is that you rely on whitespace to separate tokens. That might not always be the case.

def cumulativeTokenise(string: String): Array[String] =
  string.split("((?=\\W)|(?<=\\W))")
        .filter(_.trim.nonEmpty)
        .inits
        .map(_.mkString(" "))
        .toArray
        .reverse
        .tail

cumulativeTokenise("here@there")
//res0: Array[String] = Array(here, here @, here @ there)

Probably not the best solution to the problem, but it's something to think about.


Regarding the code, I'd have only 2 suggestions:

Use brackets even for single-line ifs. It improves readability and makes the code less error prone.
Try not to shorten member names too much (like iter or it for example). It improves readability.

As for the chosen algorithm and possible alternative I'd suggest Iterative Deepening DFS. It has the best of both Depth-First Search and Breadth-First Search - it's complete, finds the optimal solution, and doesn't use too much space.

Let me know if anything's unclear.


Creating an object out of an array of functions

Why use the underscore at all.

For simple array manipulation, the objecfify can be modified as below:

function objecfify(arr) {
    var res = {};
    for (var i = 0, l = arr.length; i < l; i++) {
        res[functionName(arr[i])] = arr[i];
    }
    return res;
}


Kudos for creating a struct to strong type the data, but what does Index mean? It's an odd term for course information. I'd look for a better name.
Also, don't string type all the things. You have a date here, you should store it as a date.

public string CompletionDate { get; set; }

MSDN article on parsing dates from strings.
You're duplicating string literals like "Email". Extract constants for these.
You're splitting on the same character array in several places, but recreating the array for each call. Extract a local variable for ['(', ')']


The comment in the ISBN class should rather be outside the class declaration, and it should contain a few words for the human reader, such as the expanded abbreviation and the Wikipedia page, to make it easy to get additional information about the topic of ISBNs.

Storing an ISBN as 5 numbers is wrong. If the length of these numbers doesn't sum up to 13, you cannot be sure where to add the zeroes. The Wikipedia article contains a table of example ISBN-10 numbers, and some of them have leading digits.

The variable names isbn_field1 are bad. The word isbn is not necessary since that information is given by the class ISBN already. Therefore field1 is better than isbn_field1. But what is field1, what does it mean? The Wikipedia article gives nice names to these fields, and so should your code.

The characters between the digits are not "minus signs" (as you say) but hyphens.

The no-argument constructor is wrong. There should be no way to construct an ISBN object without specifying all its parts. Having a single "best default" is simply not possible for an ISBN. You definitely don't want to convert all your programming mistakes to a book about analytic geometry.

In the constructor with the const unsigned int& parameters, the const& is not necessary. Integer values are typically passed directly instead of referencing them since they are one machine word long, and the computer can process them quickly. References make your code run slower in this case. For larger types such as std::vector<std::vector<ISBN>> it makes sense to use references instead of simple values.

In the is_valid_isbn function, you should add spaces around the tokens in i=0. Most C++ programmers are used to read this as i = 0.

In the same line, the parentheses around digits.length() are not necessary.

Instead of calling std::stoi, you can also write digits[i] - '0', which gives you the numeric value of a digit character. Which reminds me that some of the characters might not be digits at all. Your code should skip them and later verify that the string contained 13 digits in total.

In the ISBN::ISBN constructor, instead of checking whether the last field has length 1, you can just check whether e < 10. This is simpler and faster.

When validating multiple values, you should validate them in reading order. Start with the first field, and validate the last field last.

You didn't test your code by calling ISBN{0, 0, 0, 0, 0}.

When you throw something from your code, it should be a proper exception from the C++ standard library, such as std::invalid_argument.

Instead of the verbose std::string temp; temp = std::to_string(e); temp.length() != 1, you can simply write std::to_string(e).length() != 1. This way you don't have to think about a better variable name instead of temp. The name temp is always a bad variable name since it doesn't tell enough of a story. (Well, except if you use it as an abbreviation for temperature, but that's not the case here.)

The exception strings should not include a newline character. That character should be added when the exception is printed in a log file. If you want to save the exception somewhere else, the newline is probably wrong.

The main program is pretty useless. There is no way to enter an ISBN and validate it. You should rather define the following functions to get some automated tests:

void assert_valid_isbn(const std::string &isbn)
{
    /* TODO */
}

void assert_invalid_isbn(const std::string &isbn, const std::string &expected_error)
{
    /* TODO */
}


Merging the vector-group to get the common vector

Here are some things that may help you improve your code.

Use const where practical

A number of places in the code should have the const keyword added.  For example instead of this:

int three_vec_common(double *U1, double *U2, double *U3,
                     int len1, int len2, int len3, double *temp) {

one might instead write this:

int three_vec_common(const double *U1, const double *U2, const double *U3,
                     int len1, int len2, int len3, double *temp) {

Doing so makes it clear that the inputs are not altered and that the temp pointer is an output.

Avoid buffer overflow

The code as written doesn't necessarily have a problem writing past the end of allocated memory, but it also doesn't have any way to avoid it.  That is, the temp pointer passed in is assumed to have enough space for any result, but the actual allocated length is not passed in with the pointer, making it impossible for the code to avoid a buffer overflow if the buffer does not happen to have enough memory.

Consider checking for bad pointers

It may be that surrounding code checks explicitly for bad (NULL) pointers or has some other means of preventing them from being passed in, but it still might not be a bad idea to check for NULL pointers before dereferncing memory with either reads or writes.

Consider a better way of passing variables

It's not to bad to pass two arrays and their lengths, and even three is not completely onerous, but consider how one might pass fifty arrays into a similar function.  It's obvious that one would not (and should not!) consider actually having one hundred named parameters, so the better way to do this would be to pass in a pointer to an array of such bufffers instead.  To make it simpler, I'd advocate adding a data structure to represent both the length and the array:

struct array {
    size_t size;
    double *data;
};

Try to use descriptive names

The variable names count and min_val are good because they give a good clue as to what they're for, but the name temp is not very descriptive or useful to the reader.

Think carefully about signed versus unsigned

What is the correct interpretation if, say, len1 is a negative number?  I'm guessing that there isn't a reasonable interpretation and that all of the the lengths are expected to be non-negative.  I'd recommend making them all of type size_t.

Make assumptions explicit

The algorithm will only work correctly if all input arrays are sorted in ascending order.  That's not necessarily a bad assumption, but it does need to be explicitly stated in either the program description or the code comments or both.

Generalize the algorithm

If we wanted to accept any number of arrays, we might use a function with this kind of template:

size_t merge(const struct array *arr, size_t arrlen, struct array *out)

If we consider the algorithm generally, it is:

set the current item to the head of each input array
find the minimum among current items
add that minimum value to the output array
advance each input array if the current value is equal to the minimum value
if all lists are not yet empty, go back to step 2

It doesn't matter if there are 2 or 3 or 1000 input arrays.  I'm hoping this is enough to suggest how one might write the remaining general code.


PascalCase the method names and method params if you are feeling overly ambitious.

    // Set new width if in bounds
    if (onlyResizeIfWider)
    {
        if (ImageToResize.Width <= newWidth)
        {
            newWidth = ImageToResize.Width;
        }
    }

FindBugs barks in Java for the above behavior... refactor into a single if since you are not doing anything within the first if anyways...

    // Set new width if in bounds
    if (onlyResizeIfWider && ImageToResize.Width <= newWidth)
    {
        newWidth = ImageToResize.Width;
    }

Comments here could be a bit more descriptive; while you state what the end result is I am still lost as to why that would resolve the issue.

    // Prevent using images internal thumbnail
    ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
    ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

Maybe something similar to what is stated on this blog...

    // Prevent using images internal thumbnail since we scale above 200px; flipping
    // the image twice we get a new image identical to the original one but without the
    // embedded thumbnail
    ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
    ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);


Your script is slow because you are doing a sequence of HTTP REQUESTS. Most of the time your server / script is just waiting for the RESPONSE of the requested URL.

small things you can do

as mentioned yourself in the comments you can change your max execution time to prevent reaching it. (which does not make your script any faster ; -)
move away from get headers and use curl or similar to have the ability to change the connection timeout. You could set it to 1 sec and flag every url which fails to manual review (assuming all healthy urls will respond in time , and some slow false positives). Small benefit: your script should be finished in max url*sec time

big things

so the problem is: in practice is your script waiting for responses, in theory it does not have to , as the checking of an url does not depend on each other. Classic case for parallelization. Downside: php is not the language you want to do parallelization in.

upside: you are not the first with this problem

https://stackoverflow.com/questions/9308779/php-parallel-curl-requests
http://reactphp.org/

or use golang or something with build in parallelization


PHP Class for sending a response to Flash

I have used PHP for a few years now, and here are my suggestions:

array_push() can be used to add multiple values into an array at once, but in your case, your pushing only one value in at a time which means you can use:

$ar[] = $key . "=" . $value

This should also speed up your code a little( What's better to use in PHP $array[] = $value or array_push($array, $value)?).

die() is normally used when there is an error. It spits out a message to the user. If you are using this code to just connect to a MySQL database then change die(implode("&", $ar)); to  echo(implode("&", $ar));

But honestly, you should be able to take out the respond() function if you are only using it to send an array to flash.

        // Connection could not be established
        if(!$this->con)
        {
            $this->response = array(
                "status" => "no_connection",
                "message" => "Could not connect to MySQL, try again later."
            );

             echo(implode("&", $this->response));
        }


Unit testing code that calls RESTful API

Yes, it looks like a reasonable design and approach.

At the nit-pick level getMockedRequestor should be private or protected, to document that it is a helper for the tests. Also, if every test is going to be calling it, some people might move that code into setUp(). But that only saves one line ($requestor = $this->getMockedRequestor();) in each unit test, so I'd keep it where it is: I like to avoid using member variables, but that is personal preference.

You could use the phpUnit mock interface, but you don't have to. It gives you some very useful things, such as when you say you expect a function to be called once with "Hello World":

$requestor->expects($this->once())
  ->method('afunction')
  ->with($this->equalTo('Hello World'));

Then it will not only complain if afunction() never gets called, but also if it gets called twice.

But structure like this also brings restrictions. Have a poke around some of the phpunit mock questions on StackOverflow to see if you will hit them.


Read n lines, and count the lines that do not contain the string "CD"

If you used better variable names, you wouldn't need your first comment. The second one, though, is pure noise as it just repeat the code without adding anything.

To save on memory (and thus a bit on speed as you won't need to allocate the array) you should use xrange rather than range.

You don't use the variable i so better call it _ as it is a convention in Python for unused variables.

Lastly, you can use the sum built-in and a generator expression to perform the looping in C rather than in Python:

cases_count = int(raw_input())
wins = sum('CD' not in raw_input() for _ in xrange(cases_count))
print wins


Get locations that are x km away using Latitude/Longitude

There are a number of performance optimization tricks that you can take advantage of when trying to find efficiency. One mechanism commonly used is to reduce complexity of the code by algorithmic change..... but in your case, you can't really improve the "Big O" complexity that way, you are running at O(n) already, and there's nothing you can do to improve that.
So, it then comes down to nickel-and-diming the current algorithm to shave time off of the work you're already doing. This requires looking at the expensive computations, and reducing the number of operations to improve them.
In your example, you're converting degrees to radians often. In the case of newLocation you're doing it repeatedly for each comparison. It would make sense for you to convert all locations to radian form, and then not have any conversions inside the computation loop. This will be especially useful if your real-world code has to do multiple comparisons on the locations.
So, simply doing something like (include the radian values as part of the location):
func locationToRadians(degrees) {
  return {
    lat: degrees.lat,
    lon: degrees.lon,
    rlat: convertDegToRad(degrees.lat),
    rlon: convertDegToRad(degrees.long)
  }
}

const locationListRadians = locationList.map(locationToRadians);

Do the same with the fromLocation.
Now, in your distance function, you're repeating complex computations (trig functions are non-trivial at a computational level, so let's avoid repeats - I realize that premature optimization is not always great, but this also improves the readability). Your distance computation is significantly simpler:
function findDistanceInKm(location1, location2) {
    const sinLat = Math.sin((location2.rlat - location1.rlat) / 2);
    const sinLon = Math.sin((location2.rlon - location1.rlon) / 2);
    const earthRadius = 6371;
    const squarehalfChordLength =
      sinLat * sinLat +
      sinLon * sinLon *
      Math.cos(location1.rlat) * Math.cos(location2.rlat);

    const angularDistance = 2 * Math.atan2(Math.sqrt(squarehalfChordLength), Math.sqrt(1 - squarehalfChordLength));
    const distance = earthRadius * angularDistance;
    return distance;
}

Now, you can add in the distances that way.
The savings from doing the above will only be noticeable if you reuse computations often, but in a busy system where lots of locations are being repeatedly compared to each other I can easily see a 50% CPU saving.
As a final comment, the last loop does not need the indexing mechanism, a filter is better:
const neadLocations = locationList.filter(location => {
    const distance = findDistanceInKm(newLocation, location);
    console.log(distance);
    return distance < 1
});

(it would be better without the console logging in there...)


Vector-based flood-fill algorithm queue class

A note on terminology: What you have implemented is usually called a stack rather than a queue, but it can also be called a LIFO (last in, first out) queue, so it's not wrong to call it a queue, only uncommon.

The nextPixel() method is rather inefficient. You keep track of the number of elements in the queue, and you never do anything that allows any array element with an index >= numberOfElements to be anything but null. So instead of starting the search at elements.length - 1, you should start at numberOfElements - 1.

But that still leaves an inconsistency/inefficiency. The add() method doesn't guard against adding nulls to the queue, but you never return a null until the queue is empty.

You should either return nulls if you accept them to be added to the queue, or, better, I think, guard against nulls in add(). So I'd recommend

public void add(Pixel pixel) {
    if (pixel == null) return; // nothing to do
    // pixel isn't null, add it
    elements[numberOfElements] = pixel;
    ++numberOfElements;
    fixVector();
}

and then - also if you decide to return nulls if they're added - nextPixel() can simply be

public Pixel nextPixel() {
    // queue empty
    if (numberOfElements == 0) return null;
    // decrement numberOfElements and
    // return the last added Pixel
    return elements[--numberOfElements];
}

In fixVector(), you can probably be a bit more efficient if you use the generic Arrays.copyOf method, but maybe you are not allowed to use that either.


SPOJ - Alphacode, using dynamic programming

First of all, I would simplify the driver loop in main(), like this:

int main() {
    std::string msg;
    while ((std::cin >> msg) && (msg != "0")) {
        std::cout << decodings(msg) << '\n';
    }
}

Observations:

The status of the >> operator is checked, so that an input error or EOF would cause the program to end.
a was a cryptic variable name.
There is no point in saving all of the input first.  Each message is an independent test case.  You can start computing the result for each line as you encounter it.  That potentially saves you some delay.  It also eliminates the input global variable.  Most importantly, it helps declutter the dp() function, which only cared about input[i] anyway.
dp(i) was a cryptic and unhelpful function name.  It's not obvious what it stood for, and even if you knew that it meant "dynamic programming", it didnt't say anything about what it computes.

Your algorithm seems very complicated.  It seems to use a 2D table of strings (which is like a 3D table of chars) for memoization.  There are no comments, so I couldn't figure out what you were trying to do.  I decided it would be easier to write a solution from scratch.

Suggested solution

#include <cassert>
#include <cstdint>
#include <iostream>
#include <string>

/**
 * Checks whether the character 'a' could represent a letter (1 to 9).
 */
bool isletter(char a) {
    return '1' <= a && a <= '9';
}

/**
 * Checks whether the string "ab" could represent a letter (10 to 26).
 */
bool isletter(char a, char b) {
    return (a == '1' && ('0' <= b && b <= '9')) ||
           (a == '2' && ('0' <= b && b <= '6'));
}

/**
 * Counts the number of ways the message could be decoded.
 */
std::int64_t decodings(const std::string& msg) {
    std::string::size_type len = msg.length();
    if (len == 0) return 1;

    std::int64_t prev_count = 1,
                 curr_count = isletter(msg[0]);
    for (int i = 1; i < len; ++i) {
        // Try decoding the last two characters as a letter, and
        // try decoding the final character as a letter.
        std::int64_t new_count = prev_count * isletter(msg[i - 1], msg[i]) +
                                 curr_count * isletter(msg[i]);
        prev_count = curr_count;
        curr_count = new_count;
    }

    return curr_count;
}

int main() {
    assert(decodings("25114") == 6);
    assert(decodings("1111111111") == 89);
    assert(decodings("3333333333") == 1);

    std::string msg;
    while ((std::cin >> msg) && (msg != "0")) {
        std::cout << decodings(msg) << '\n';
    }
}

Observations:

decodings() is obviously O(L) in time and O(1) in space, so it's hard to beat.
I've used std::int64_t, since that is what the challenge specifies.
For good measure, I've added assertions for the three provided test cases.


Consider using mysqli instead of mysql:

mysqli

Mysqli (the "i" stands for "improved") is more OO-friendly and has better security.  It also seems like the standard mysql functions are being deprecated (some of them anyway).


Use braces { in all your if blocks. It makes it easier to read.

if (byletter[firstletter]){
    byletter[firstletter]++;
}else{
    byletter[firstletter]=1;
}

You have for loops like : countries.forEach(function(c){ which are also hard to read. I'd only use this if you have a function you want to apply.

for(var countryindex = 0; countryindex < countries.length; countryindex++)
{
    var c = countries[countryindex];
    // ...
}

Use descriptive variable names.

if (FirstLetter != newFirstLetter)
{
    var l1 = cc.length;
    var l2 = l1 + byletter[newFirstLetter];

What is l1 & l2 ? What is c or cc?


Get an array of strings separating a string on N character incrementally

Which makes me wonder, is there a better way to do this without
  recursion, but just as succinctly?

Recursion can be an issue if your input size is huge and you recurse often and your JavaScript engine can't perform tail call optimization. Due to limited call stack size, you might then encounter a Maximum call stack size exceeded error. You might also want to avoid recursion if performance is a concern, as the function call overhead is not marginal in JavaScript.

So, how do you eliminate the recursion?

First of all, in order to gain a clear understanding of Redu's minified one-liner:

res = s => s.length ? [s].concat(res(s.match(/.*(?=\/.+$)/)[0])) : [];

I recommend to rewrite it into a self-documenting but otherwise equivalent function:

function expand(path) {
  if (path.length == 0) return [];
  let result = [path];

  path = path.match(/.*(?=\/.+$)/)[0];
  result = result.concat(expand(path));

  return result;
}

Now, we can analyze how that function works:

It appends the current path to the result
It replaces the current path with the parent path
It recurses to find a solution for the parent path
It appends the complete path to the solution for the parent path

It is always possible to turn a recursive function into a non-recursive function. We just need to manually keep track of already found paths and the current parent path:

function expand(path) {
  let result = [];

  while (path.length > 0) {
    result.push(path);
    path = path.match(/.*(?=\/.+$)/)[0];
  }
  return result;
}

console.log(expand("/bob/ross/is/awesome/squirrels"));

This non-recursive solution works as-is for empty strings without having to check for this base case.

We could even minify it again, which I don't recommend:

const res=(s,r=[s])=>{while(s.length)r.push(s=s.match(/.*(?=\/.+$)/)[0]);return r};

In a practical setting, I would recommend a more generative and more robust approach which, in a first step, extracts all valid path segments from the input. In a second step, you would then build the cumulative paths from those segments.

Using Array.map():

function expand(path, prefix = '') {
  return path.match(/[^\/]+/g).map((segment) =>
    prefix += '/' + segment
  ).reverse();
}

console.log(expand("/bob/ross/is/awesome/squirrels"));

Using Array.reduce():

function expand(path, prefix = '') {
  return path.match(/[^\/]+/g).reduce((path, segment) => {
    prefix += '/' + segment;
    path.unshift(prefix);
    return path;
  }, []);
}

console.log(expand("/bob/ross/is/awesome/squirrels"));


My objective now is to improve it so it may serve as a reference to anyone trying to implement or understand it.

In light of that goal I would have thought it made more sense to use the documented test vectors of RFC 2202 rather than make up your own one.

### hash (key xor opad || hash ( (key xor ipad)||message ) )
part2 = K_opad + hash1
print("hash (key xor opad || hash ( (key XOR ipad)||message ) ):\n"+part2.hex())
hash_final = hash(part2)
print("\n\nFinal Hash:\n"+hash_final.hex())

The comment and the first print describe hash_final, not part2. IMO this is a bug, albeit a minor one.


Find all the paths of tree that add to a input value

public AllPathsAddingSum(List<Integer> items) {
    create (items);
};

Unneeded space, unneeded semicolon. Consider autoformatting your code.

for (Integer i : path) {
    System.out.print(i + " ");
}
System.out.println();

This section in computePaths is doing something different than the function description. It doesn't calculate, it prints.

Move it to a separate method. Then give the class a PrintStream to use. This PrintStream would be System.out, or a dummy PrintStream that just copies everything to an internal buffer.

Then you can unittest your code.


Finding unique top sums from multiple lists


Splitting TSV file into multiple files based on content of column

First I would like to say that your code looks clean and well structured. You are doing most things well like using the proper casing for naming your things, using using's and stacking them as well, using readonly where you should.

Improvements could be made by using better names for your variables like e.g _csv and csv. A reader of your code who is switching between the AmazonCsvWriter class and the ProcessFbaOrders() method will get confused because in the AmazonCsvWriter class the _csv variable holds an instance of a CsvWriter and in the mentioned method the csv variable holds an instance of a CsvReader.

You are using a Dictionary<string, AmazonCsvWriter> to write the the unordered records to their desired destination based on the SalesChannel of the record.

Although your code accomplish its goal you could do better by using Enumerable.GroupBy() like so

IEnumerable<IGrouping<string, AmazonOrderRow>> query =
        records.GroupBy(record => record.SalesChannel, record=> record);

and then you can iterate over it like so

foreach (IGrouping<string, AmazonOrderRow> recordGroup in query)
{
    string csvOutputPath = Path.Combine(_platform.OutputFolder, recordGroup.Key);
    Directory.CreateDirectory(csvOutputPath);

    using (var streamWriter = new StreamWriter(Path.Combine(csvOutputPath, $"{DateTime.Now:yyyyMMddHHmmss}.txt"), false, Encoding.GetEncoding("Windows-1252")))
    using (var csvWriter= new CsvWriter(streamWriter))
    {
        csvWriter.Configuration.Delimiter = "\t";
        csvWriter.Configuration.RegisterClassMap(new AmazonOrderRowMap());
        csvWriter.WriteHeader<AmazonOrderRow>();
        csvWriter.NextRecord();
        foreach(var record in recordGroup)
        {
            record.Sku = GetRealSku(record.Sku);
            csvWriter.WriteRecord(record);
            csvWriter.NextRecord();
        }
    }
}

As a side note, you don't need to check if a directory exists before you call Directory.CreateDirectory() because the CreateDirectory() method checks the same and if the directory exists it simply returns.


I would say the short answer to your questions is no.
But since this is code review a deeper explanation is required.
Natual vs. Supernatural Async
Logging every request to a database is a common practice but can be done many different ways (IIS does this for you by default BTW).  Generally speaking the desire is usually something like this:

"We need to track user metrics or gather data to help identify potentially malicious activity on our web-server.  Let's grab all user information (with time stamp) so we can get better visibility into what is happening.  In order to pull this off though, we need to not impact normal site operations."

Ajax (to me) is the ideal candidate since it will be made on a separate request and any DB connectivity issues, latency, errors etc will not affect the actual application receiving the request.
The question is what level of detail is needed for logging.  Your code seems to indicate that all that is needed is the client IP and User-Agent.  That being the case, I would opt for a pure JS solution that makes a naturally asynchronous call and logs that information.
By using Ajax you're working with the expectations of the web server (at least in an HTTP/1 world) which expects to generally use 1 thread per request to retrieve 1 resource.
By using the TaskFactory or any form of the TPL for asynchronous processing, you're potentially breaking the model.
On the surface, this is a technicality, but if we dig deeper, we find that there are some scalability issues here.
Stephen Cleary (and others) write extensively on this subject so I will include some links to additional reading but allow me to summarize here:
Task.Run is simply a wrapper introduced in .NET 4.5 on top of TaskFactory.StartNew, which had a more complicated signature.  For more on this, see here: https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/
The behavior of this method is to create a new thread if no thread is available.
Below is a quote from a Stephen Cleary article that succinctly summarizes what happens when Task.Run fires (particularly in an ASP.NET Environment).

Taken from: http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html

The request starts processing on an ASP.NET thread.
Task.Run starts a task on the thread pool to do the calculations. The ASP.NET thread pool has to deal with (unexpectedly) losing one of its threads for the duration of this request.
The original request thread is returned to the ASP.NET thread pool.
When the calculation is complete, that thread completes the request and is returned to the ASP.NET thread pool. The ASP.NET thread pool has to deal with (unexpectedly) getting another thread.

If you have multiple calls to Task.Run, then the performance problems are compounded. On a busy server, this kind of implementation can kill scalability.
That’s why one of the principles of ASP.NET is to avoid using thread pool threads (except for the request thread that ASP.NET gives you, of course). More to the point, this means that ASP.NET applications should avoid Task.Run.

Code
So, in your JS, I would recommend the following approach:

This is a link

Then in your server-side code, you can remove those task runs completely (as from JS they don't serve a purpose).
//get the repository instance
private RequestsRepository _repo = new RequestsRepository();

public ActionResult Index()
{
    return View();
}

public ActionResult HomeLog() {
    _repo.RegisterRequest(Request.UserHostAddress, Request.UserAgent);
}

public void LinkLogger()
{
    _repo.RegisterRequest(Request.UserHostAddress, Request.UserAgent);
}

And if you really wanted to make those ajax calls more "parallel" you can decorate the actions using async / await.
Here are some articles on the subject for further reading:

http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html
http://blog.stephencleary.com/2013/10/taskrun-etiquette-and-proper-usage.html
http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-using.html
https://stackoverflow.com/questions/13489065/best-practice-to-call-configureawait-for-all-server-side-code
http://bradwilson.typepad.com/blog/2012/04/tpl-and-servers-pt1.html


That would be a fraction not a percentage

You should add an order by EmployeeFirstName, EmployeeLastName, ID