Finding all the prime factors of a number

Quick observation: you use Math.pow() to calculate powers of two. This is highly inefficient, use bit shifting to prevent long -> double conversion

For example, 2^10 can be calculated very quicky as 1 << 10. See for example here (https://stackoverflow.com/q/141525/461499)

Also you divide a double by a long and then convert to long (in effect flooring), you can skip conversion to double entirely to speed things up.


Select the Enum to classify a string based on the first word found

You can utilise the Enum class which can shorten your code significantly and it will be easier for future updates

private static QuestionIdentifier IdentifyQuestion(string vQuestion)
{
    //QuestionToLower
    string vQTL = vQuestion.ToLower();
    string[] enumNames = Enum.GetNames(typeof(QuestionIdentifier));
    foreach (var enumName in enumNames)
    {
        if (vQTL.Contains(enumName.ToLower()))
        {
            return (QuestionIdentifier) Enum.Parse(typeof(QuestionIdentifier), enumName);
        }
    }
    return QuestionIdentifier.Andere;
}

or with LINQ

private static QuestionIdentifier IdentifyQuestion(string vQuestion)
{
    string vQTL = vQuestion.ToLower();
    string[] enumNames = Enum.GetNames(typeof(QuestionIdentifier));
    string enumValueName = enumNames.FirstOrDefault(x => vQTL.Contains(x.ToLower()));
    return enumValueName != null
        ? (QuestionIdentifier) Enum.Parse(typeof(QuestionIdentifier), enumValueName)
        : QuestionIdentifier.Andere;
}

Now you can add as much types as you want in your enum without even touching this method it will still work and find your newly created type.

Update

As @t3chb0t pointed in the comments there is a way to avoid calling .ToLower() on both the input string and the enum value by using the .IndexOf() overload which accepts different comparison types :

private static QuestionIdentifier IdentifyQuestion(string vQuestion)
{
    string[] enumNames = Enum.GetNames(typeof(QuestionIdentifier));
    string enumValueName =
        enumNames.FirstOrDefault(x => vQuestion.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0);
    return enumValueName != null
        ? (QuestionIdentifier)Enum.Parse(typeof(QuestionIdentifier), enumValueName)
        : QuestionIdentifier.Andere;
}


Computing the standard deviation of a Number array in Java - follow-up

Boxing
Your current class MyConsumer implements Consumer<Double>. This means that every time an element is accepted, it will unboxed into a double.
@Override
public void accept(Double t) {
    sum += t;  // <-- unboxed into double
    sumOfSquares += t * t;   // <-- here also
}

On large datasets, this can have a huge performance impact. Instead, it would be preferable to implement the primitive DoubleConsumer interface, and thus change your accept method into
@Override
public void accept(double t) {
    // ...
}

This way, there won't be any overhead involving autoboxing.
This will also involve a change inside your main method. You will need to use mapToDouble instead of map.
Arrays.stream(array)
      .mapToDouble(Number::doubleValue)

This is also a good change to do: currently, each Number would be converted to a double, only to be boxed into a Double by map, then unboxed multiple times inside the consumer.
collect instead of forEach
You aren't using properly the Stream API in your main pipeline:
MyConsumer myConsumer = new MyConsumer();

Arrays.stream(array)
      .map(Number::doubleValue)
      .forEach(myConsumer);

The problem with this code is that it mixed both the functional approach of the Stream API with the traditional iterative forEach. This can generally break in multiple ways when you're using a parallel pipeline.
The Stream API was designed so that parallel capabilities can be introduced effectively. The case of forEach is even mentioned in the documentation:

A small number of stream operations, such as forEach() and peek(), can operate only via side-effects; these should be used with care.
 [...]
the forEach() can simply be replaced with a reduction operation that is safer, more efficient, and more amenable to parallelization.

This is what collect (and the more general reduce) is for.
So let's make that parallel-friendly and take a look at collect(supplier, accumulator, combiner) method.

The supplier is a function returning the new result container.
The accumulator is a function that takes the current result container and the current Stream element and incorporates it into the container.
The combiner is a function that takes two result containers and merges them into one. This argument is only used in case of a parallel pipeline.

To adhere with that contract, we need to change MyConsumer:

MyConsumer isn't really a consumer anymore, it will be a class responsible for collecting the values into statistics having notably a sum and sumOfSquares. Let's rename it StatCollector (for lack of a better name). It does consume double as input so it makes sense to let it implement DoubleConsumer.
As seen by the above signature, it needs to handle a case of merging two containers, so we need to add a method public void combine(StatCollector other) that will be responsible for that.

This is what we end up with:
private static final class StatCollector implements DoubleConsumer {

    private double sum;
    private double sumOfSquares;

    @Override
    public void accept(double t) {
        sum += t;
        sumOfSquares += t * t;
    }

    public void combine(StatCollector other) {
        sum += other.sum;
        sumOfSquares += other.sumOfSquares;
    }

    double getSum() {
        return sum;
    }

    double getSumOfSquares() {
        return sumOfSquares;
    }
}

used with
StatCollector stat =
    Arrays.stream(array)
          .mapToDouble(Number::doubleValue)
          .collect(StatCollector::new, StatCollector::accept, StatCollector::combine);


Minimum Sum Path of Pyramid with Data Structures

I have solved it by creating my own Tree. Here is how it is:

import java.util.LinkedList;
import java.util.Queue;
public class SolutionTree {

    SolutionNode root;

    public SolutionTree() {
        root = null;
    }

    public void addRoot(int rootValue) {
        root = new SolutionNode(rootValue);
    }

    // New Node Adder
    public void addSolutionNode(int newNodeValue) {
        SolutionNode newNode = new SolutionNode(newNodeValue);
        SolutionNode newNodeRoot = breadth(root);
        if(newNodeRoot.getChildLeft() == null) {
            newNodeRoot.setChildLeft(newNode);
            newNode.setParentLeft(newNodeRoot);
        }
        else if(newNodeRoot.getChildRight() == null) {
            newNodeRoot.setChildRight(newNode);
            newNode.setParentLeft(newNodeRoot);
            if(newNodeRoot != root) {
                    if(newNodeRoot.getParentLeft().getChildRight().getChildLeft() == null) {
                        newNodeRoot.getParentLeft().getChildRight().setChildLeft(newNode);
                        newNode.setParentRight(newNodeRoot.getParentLeft().getChildRight());
                    }
            }
        }
    }

    // Node Class of Solution Tree
    protected class SolutionNode {

        private int value;
        private SolutionNode parentLeft;
        private SolutionNode parentRight;
        private SolutionNode childLeft;
        private SolutionNode childRight;

        // Constructor
        public SolutionNode() {
            value = 0;
            parentLeft = null;
            parentRight = null;
            childLeft = null;
            childRight = null;
        }

        // Constructor
        public SolutionNode(int v) {
            value = v;
            parentLeft = null;
            parentRight = null;
            childLeft = null;
            childRight = null;
        }

        // MODIFIERS

        public void setValue(int val) {
            value = val;
        }

        public void setParentLeft(SolutionNode leftParent) {
            parentLeft = leftParent;
        }

    public void setParentRight(SolutionNode rightParent) {
        parentLeft = rightParent;
    }

        public void setChildLeft(SolutionNode leftChild) {
            childLeft = leftChild;
        }

        public void setChildRight(SolutionNode rightChild) {
            childRight = rightChild;
        }

        //ACCESSORS

        public int getValue() {
            return value;
        }

        public SolutionNode getParentLeft() {
            return parentLeft;
        }

        public SolutionNode getParentRight() {
            return parentRight;
        }

        public SolutionNode getChildLeft() {
            return childLeft;
        }

        public SolutionNode getChildRight() {
            return childRight;
        }

    }

    // function to compute the minimum sum path
    // It only returns the sum of the values of nodes on the min sum path
    int minSumPath(SolutionNode current) {
        if(current == null)
            return 0;

        int sum = current.getValue();

        int left_sum = minSumPath(current.childLeft);
        int right_sum = minSumPath(current.childRight);

        if(left_sum <= right_sum) {
            sum += minSumPath(current.childLeft);
        }
        else {
            sum += minSumPath(current.childRight);
        }

        return sum;
    }

    // Breadth First Traversal
    public static SolutionNode breadth(SolutionNode root) {
        Queue<SolutionNode> queue = new LinkedList<SolutionNode>() ;
        if (root == null)
            return null;
        queue.clear();
        queue.add(root);
       while(!queue.isEmpty()){
            SolutionNode node = queue.remove();
            if(node.childLeft != null)
                queue.add(node.childLeft);
            if(node.childRight != null)
                queue.add(node.childRight);
            if(node.childLeft == null || node.childRight == null)
                return node;
        }
        return null;
    }

}

I am invoking minSumPath at the main of my file reading program.

Have a nice day.


The number of permutations of n choose n items is always going to be n!. The way to optimize the solution is to prune the permutations to those that might solve the problem. This requires domain knowledge.

For example if the problem involves ordinary English words all permutations  matching *qz* or *mA* can be eliminated.

Incidentally, \$O(n*n!)\$ can be shortened to \$O(n!)\$ since it is roughly \$O((n+1)!)\$


Merging two lists from dictionary. How to do this in a better way?

You're looking for zip().

print zip(o['actor_name'], o['played'])

or to make it look like your output

for entry in zip(o['actor_name'], o['played']):
    print entry


Is the LINQ version faster than the foreach one?

As has been said, the for loop will most likely be more performant, but you can still clean the code up a bit more:

for (int i = 0; i < fpc.Vertices.Length; i++)
{
    if (cylindre.IsPointInside(fpc.Vertices[i]))
        listPoint.Add(fpc.Vertices[i]);
}

Can become:

foreach (var vertice in fpc.Vertices)
{
    if (cylindre.IsPointInside(vertice))
        listPoint.Add(vertice);
}

EDIT:  As per the performance question. This code will run in LINQPad. I found that the foreach version performs a few milliseconds better than the for loop.

var elements = Enumerable.Range(0, 4000000).Select(x => true).ToArray();

var sw = new Stopwatch();
var result = new List<bool>();
int trueCount = 0;
sw.Start();
for(int i=0; i < elements.Length; ++i)
{
    if (elements[i])
    {
        ++trueCount;
        result.Add(elements[i]);
    }
}

sw.Stop();
sw.ElapsedMilliseconds.Dump();

sw.Reset();
trueCount = 0;
result = new List<bool>();
sw.Start();
foreach(var element in elements)
{
    if (element)
    {
        ++trueCount;
        result.Add(element);
    }
}
sw.Stop();
sw.ElapsedMilliseconds.Dump();

EDIT2 - Regarding the link that seems to indicate such drastically poor performance in a foreach loop

The link (http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html) is dealing with removing elements from a list. In the case that you have a generic list, removing elements via a for loop is not normally the best approach. A better approach is to use the RemoveAll method. RemoveAll will remove all elements matching the predicate and then consolidate the list as opposed to RemoveAt which will require moving all elements above the removed element. For performance comparison of the removal please see the below code (once again, this can be run in LINQPad). In my testing the RemoveAll ran roughly 250x faster.

var elements = Enumerable.Range(0, 100000).Select(x => x % 2 == 0).ToArray();

var sw = new Stopwatch();
var source = new List<bool>(elements);
sw.Start();
for(int i=0; i < source.Count; ++i)
{
    if (!source[i])
    {
        source.RemoveAt(i);
        --i;
    }
}

sw.Stop();
sw.ElapsedMilliseconds.Dump();
int count = source.Count;

sw.Reset();
source = new List<bool>(elements);

sw.Start();
source.RemoveAll((bool x) => {return x;});
sw.Stop();
sw.ElapsedMilliseconds.Dump();


Sorting a list into different bags according to predicate

Here's another (Subjectively better or worse) way to write this, however it does require comparison unlike yours:

let sortIntoBags<'T,'TKey when 'TKey : comparison > (predicate:'TKey*'T -> bool) (bagKeys:'TKey list) (items:'T list) : ('TKey*'T list) list * 'T list =
    let bagMap:Map<'TKey,'T list> = bagKeys |> Seq.map(fun k -> k,List.empty) |> Map.ofSeq
    items
    |> List.rev
    |> List.fold(fun (bagMap,unmatched:'T list) (item:'T) ->
        match bagMap |> Map.tryFindKey(fun k _ -> predicate(k,item)) with
        | Some k -> bagMap |> Map.add k (item::bagMap.[k]), unmatched
        | None -> bagMap,item::unmatched

    ) (bagMap,List.empty)
    |> fun (m,x)->
        m |> Map.toList, x

and the xunit tests I used to make sure it matched the output

open global.Xunit

[<Fact>]
let originalQuestion2 () =
   let l= [1..25]
   let bags= [2; 3; 5; 7]
   let isDivisorFor (x, y) = 0=y%x
   let expected = [(2, [2; 4; 6; 8; 10; 12; 14; 16; 18; 20; 22; 24]); (3, [3; 9; 15; 21]);(5, [5; 25]); (7, [7])], [1; 11; 13; 17; 19; 23]
   let actual = l |> BagSort.sortIntoBags isDivisorFor bags
   printfn "%A" actual
   Console.Error.WriteLine(sprintf "%A" actual)
   Trace.WriteLine(sprintf "%A" actual)
   Assert.Equal(expected, actual)

[<Fact>]
let originalQuestionUnfolded2 () =
   let l= [1..25]
   let bags= [2; 3; 5; 7]
   let isDivisorFor (x, y) = 0=y%x
   let expected =
        let a =
            [   2, [2; 4; 6; 8; 10; 12; 14; 16; 18; 20; 22; 24]
                3, [3; 9; 15; 21]
                5, [5; 25]
                7, [7]
            ]
        let b = [1; 11; 13; 17; 19; 23]
        a,b
   let actual = l |> BagSort.sortIntoBags isDivisorFor bags
   Assert.Equal(expected, actual)
   Assert.Equal((fst expected |> fun x -> x.[0]), fst actual |> fun x -> x.[0])


Implementation of observer pattern for Node.js

The name of the Observer class is confusing: an Observer contains observers?  I think that the class would make more sense if you renamed it Observable.

For the .on() and .off() methods, I think that the event parameter should come first.  That would mimic the natural English expression: "on event tell observer to do action".  It's also how it's done in other frameworks like jQuery.

I'm mildly annoyed by the excessive vertical spacing of the code.


Avoid if/else in constructor - NavigableMap?

A NavigableMap would just move the current logic into an object.  You'd get something like

final static NavigableMap<Long, Calibrated> OD_CALIBRATIONS = new TreeMap();

static {
    OD_CALIBRATIONS.put(Long.MIN_VALUE, new Calibrated(K0, H0, K0_INV, H0_INV, F0));
    OD_CALIBRATIONS.put(762, new Calibrated(K1, H1, K0_INV, H0_INV, F1));
    OD_CALIBRATIONS.put(858, new Calibrated(K2, H2, K2_INV, H2_INV, F2));
    OD_CALIBRATIONS.put(859, new Calibrated(K1, H1, K0_INV, H0_INV, F1));
    OD_CALIBRATIONS.put(866, new Calibrated(K2, H2, K2_INV, H2_INV, F2));
    OD_CALIBRATIONS.put(1005, new Calibrated(K3, H3, K3_INV, H3_INV, F3));
    OD_CALIBRATIONS.put(1006, new Calibrated(K2, H2, K2_INV, H2_INV, F2));
    OD_CALIBRATIONS.put(1011, new Calibrated(K3, H3, K3_INV, H3_INV, F3));
}

private void setCalibratedValues(long odNumber) {
    this.calibratedValues = OD_CALIBRATIONS.floorEntry(odNumber).getValue();
}

Note:  I'm not sure about the map key initializations.  They get kind of weird since you are mixing less than ranges with single value equalities.  You could pull the exceptions out of the NavigableMap and put them in a regular Map instead.  That would make the code look something like

final static MAP<Long, Calibrated> OD_EXCEPTION_CALIBRATIONS = new HashMap();
final static NavigableMap<Long, Calibrated> OD_CALIBRATIONS = new TreeMap();

static {
    OD_EXCEPTION_CALIBRATIONS.put(858, new Calibrated(K2, H2, K2_INV, H2_INV, F2));
    OD_EXCEPTION_CALIBRATIONS.put(1005, new Calibrated(K3, H3, K3_INV, H3_INV, F3));

    OD_CALIBRATIONS.put(Long.MIN_VALUE, new Calibrated(K0, H0, K0_INV, H0_INV, F0));
    OD_CALIBRATIONS.put(762, new Calibrated(K1, H1, K0_INV, H0_INV, F1));
    OD_CALIBRATIONS.put(866, new Calibrated(K2, H2, K2_INV, H2_INV, F2));
    OD_CALIBRATIONS.put(1011, new Calibrated(K3, H3, K3_INV, H3_INV, F3));
}

private void setCalibratedValues(long odNumber) {
    if (OD_EXCEPTION_CALIBRATIONS.containsKey(odNumber)) {
        this.calibratedValues = OD_EXCEPTION_CALIBRATIONS.get(odNumber);
    } else {
        this.calibratedValues = OD_CALIBRATIONS.floorEntry(odNumber).getValue();
    }
}

Note that calling setCalibratedValues with both 762 and 763 will give each the same Calibrated object.  If that's not what you want, you could give Calibrated a copy constructor and make a new one each time.  Also note that this method requires creating all the calibrations at the beginning.  This can be wasteful if you only use one per program invocation.  Not so bad now, but what if you get more calibration sets?

It would be possible to put the rules into a file or files and then read them into the objects.  That would eliminate most of the constants.  You'd have to make sure that you read the file by the first time that you needed the values.  Perhaps put them into a Singleton object?  At worst case then, the Singleton constructor could read the file the first time that it was needed.  Or you could prime it earlier.

Some things that I don't like about setCalibratedValues that you didn't mention:

What's an odNumber?  Unless odNumber means something, you might as well call it n.  If odNumber does mean something, you should tell me so that I know it too.  If odNumber isn't a standard name, then I'd much prefer it was written out.  Why write out number which should be obvious from the type and leave od obscured?
Similarly, do k, h, k_inv, h_inv, and f have meaning?  I'd have trouble editing that code, as I have no idea what each of those means.  I sort of think that k and k_inv have something to do with each other, but no idea what.
Also, why are most of them arrays?  This should be understandable from the code, and it isn't here.
Your constants are named K0, H1, etc.  Why not give these more meaningful names rather than just 0, 1, 2, 3?  Of course, this could also argue in favor of moving these out of code entirely.  If position is all that separates them, why give them names at all?
You're repeating the exact same calibratedValues and overwriting previous values.

Why not something like

private void setCalibratedValues(long odNumber) {
    if (odNumber < 762) {
        this.calibratedValues = new Calibrated(K0, H0, K0_INV, H0_INV, F0);
    } else if (odNumber < 866 && odNumber != 858) {
        this.calibratedValues = new Calibrated(K1, H1, K0_INV, H0_INV, F1);
    } else if (odNumber < 1011 && odNumber != 1005) {
        this.calibratedValues = new Calibrated(K2, H2, K2_INV, H2_INV, F2);
    } else {
        this.calibratedValues = new Calibrated(K3, H3, K3_INV, H3_INV, F3);
    }
}

This reduces your repeated code.  Of course, it won't work as well if the exceptions aren't just off by one in the ranges.  Although if 1050 were supposed to get the 0 set, then you could use an || to move that value from the 3 set to the 0.

We might be able to suggest something better if we knew what odNumber, k, h, k_inv, h_inv, and f were and why they are related.  For example, if odNumber is the Orson Dines catalog number of a set and the other numbers are dimensions of the parts, you might put those in a database.  Then you could read the values from the database as necessary.


Basic memory pool, alignment, thread safety

Serious Bug

The moment you do this:

pool->memory = realloc(pool->memory, pool->memory_size);

all the existing head, next, ptr, and memory pointers become invalid, since they were pointing into the memory that was just freed.  So essentially, your memory pool becomes useless after you expand it.

Unsafe macros

This macro:

#define get_ptr_and_increase(pool, size) pool->memory; pool->memory += size

is unsafe for multiple reasons:

Arguments are not used inside parentheses, e.g. (pool)
The two statements could get split unexpectedly, such as in:

if (condition)
    p = get_ptr_and_increase(pool, size);

I suggest creating a static inline function instead:

static inline void *get_ptr_and_increase(MemoryPool *pool, size_t size)
{
    void *ret = pool->memory;
    pool->memory += size;
    ret += size;
}


Find the second-largest number in an array of elements

ArrayList is not the right tool.  Since ArrayList makes no attempt to arrange its elements, ArrayList.contains(...) is inefficient — it has to examine every previously added element to see whether it is present.  Then, at the end, you still have to sort the entire list.  If you're adding n numbers, and adding each number takes O(n) time, then your entire solution is O(n2), which is horrible for such a simple problem.

If you want to use a Java Collections data structure, why not use SortedSet instead?  The advantages of SortedSet are:

It maintains the order of elements as it adds them
It automatically deduplicates (TreeSet does it in O(log n) time)
You don't have to sort the elements again at the end

Here's a solution (that works in O(n log n) time):

int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9 };
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i: randomIntegers) {
    set.add(i);
}
// Remove the maximum value; print the largest remaining item
set.remove(set.last());
System.out.println(set.last());

A more efficient and minimalist solution wouldn't use any data structure.  You just keep track of the two largest numbers you have encountered as you walk along the input array.  See this related question.  That approach hardly uses any space and works in O(n) time, which is as good as it gets.


First a quote from Code Metrics Values on MSDN to make sure everyone knows what it is:

  Maintainability Index – Calculates an index value between 0 and 100 that represents the relative ease of maintaining the code. A high value means better maintainability. Color coded ratings can be used to quickly identify trouble spots in your code. A green rating is between 20 and 100 and indicates that the code has good maintainability. A yellow rating is between 10 and 19 and indicates that the code is moderately maintainable. A red rating is a rating between 0 and 9 and indicates low maintainability.

So is your code maintainable? Well, even though the score is not so bad I don't think it's. Why? Because it does two things that it shouldn't which are:

var startPath = new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)).LocalPath; //get current directory (Release/Debug)
var zipPath = new Uri(@"" + startPath + "-" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm") + ".zip").LocalPath;  //zip filename

You can see this by looking at another even more important score the

  Class Coupling – Measures the coupling to unique classes through parameters, local variables, return types, method calls, generic or template instantiations, base classes, interface implementations, fields defined on external types, and attribute decoration. Good software design dictates that types and methods should have high cohesion and low coupling. High coupling indicates a design that is difficult to reuse and maintain because of its many interdependencies on other types.

I measured your code and this score is 8. There is a way to improved it if you encapsulate the code creating the paths. Currently those two lines cannot be tested so you actually have to debug or run your application to be able to verify that both paths are the ones you expect.

If you put them inside another tool like a PathBuilder

class PathBuilder : IPathBuilder
{
    public string CreateStartPath()
    {
        return new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)).LocalPath;
    }

    public string CreateZipPath(string startPath)
    {
        return new Uri(@"" + startPath + "-" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm") + ".zip").LocalPath;
    }
}

the class-coupling score drops to 3 and 2 for each of the PathBuilder methods which is much better now:

public static void ExportProjectFolderToZip(PathBuilder pathBuilder)
{
    try
    {
        var startPath = pathBuilder.CreateStartPath();
        var zipPath = pathBuilder.CreateZipPath(startPath);

        CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
    }
    catch (Exception ex)
    {
        Logger.Error("Error: " + ex.Message);
    }
}

Btw this is not how you should use the logger for exceptions: Logger.Error("Error: " + ex.Message); There is an overload that accepts an exception so that you don't loose the stack-trace.


Cycling between element above and below current array element

First off, your code was a bit difficult to read, because you combined the algorithm you need with your functionality, that you didn't explain. It's not only easier for people helping you, but also yourself, if you try to separate your problem from the application.

Your attempt was to calculate an index from the previous index. I instead created a function, that mapped a increasing index (0, 1, 2, 3, 4,...) to the targets (0, 1, -1, 2, -2,...). So we are looking for a function f(i) where f(0) = 0, f(1) = 1, f(2) = -1, f(3) = 2, etc.

I came up with: (i % 2 ? 1 : -1) * Math.floor( (i+1) / 2 ).

Now you just need a condition to skip new indexes outside your array. I came up with the following:

var yourArray = new Array(10);
var start = 2;

var i = 0;
var max = yourArray.length;

while (max) {
  var newI = (i%2?1:-1) * Math.floor((i+1)/2) + start;
  if (newI >= 0 && newI < yourArray.length) {
    document.write( newI + "<br>");
    // do something with yourArray[newI];
    max--;
  }
  i++;
}

My problem was how to decide when to stop the loop. For now i just loop over twice the length of the array. That will usually lead to some unnecessary iterations, but maybe someone can come up with a better solution, or there maybe a condition that comes from your application. UPDATE: Found a solution.


Comparing two columns in two different rows

This part

        if entry in entries:
            entries[entry].append(line)
        else:
            entries[entry] = [line]

definitly smells like it could/should be written with setdefault or defaultdict.

This would be for instance entries.setdefault(entry, []).append(line).

Avoid to re-assign the same variable again and again as it makes it harder to hard to understand what the variable is supposed to represent.

        line = line.strip()
        line = line.split()

could be written : splitted_list = line.strip().split()

You are iterating over key ("kee"?)/values of a dictionnary but ignoring the actual key.

The convention is to use _ as the variable name for throw-away values so you could write : for _, val in entries.iteritems():. However, it would probably be better to just iterate over the values using itervalues, values or viewvalues.


Manager for customer billing and subscriptions in Rails

I think the real test of this architecture is the refactoring effort involved in moving away from Recurly. Ideally, you'd just need to rewrite your service layer classes, and none of the rest of your application.

The only major issue I see here is you've got a bunch of public methods that are returning Recurly business objects, which could allow you to couple your entire system to Recurly. Without seeing the rest of the code, I would mark all methods that return Recurly business objects as private or protected, and only expose the methods that are transactional in nature --- and even then I would limit the arguments and return values of those methods to primitive values, or business objects written by your team for this application.

There is one minor nitpick, though. The class name Tollbooth::Manager doesn't really communicate what it does. You describe this as a "service class", so why not name it accordingly: Tollbooth::SubscriptionService or Tollbooth::SubscriptionManager. Normally I would steer people away from naming classes "SomethingManager", but this class does indeed appear to manage things, so I think the "Manager" suffix works here.

If the rest of your application needs data provided by Recurly, I would recommend creating your own classes to represent that data, and then map them over from the Recurly objects (also known as Data Transfer Objects). This would provide a layer of decoupling in case you switch subscription providers in the future.


Please consider using format/2 for formatting output.

You do not need so many concatenations!

Also, check out the following sample query and interaction:

?- main([test]).
test
true ;
test
true ;
false.

This shows that internally, there are choice-points left, and in fact even alternative solutions.

Ideally, the predicate should be deterministic, i.e., succeed exactly once.


How do I dynamically create Python unit tests in a readable way?

Don't bother with generating tests:

class Tests(unittest.TestCase):
    def check(self, i, j):
        self.assertNotEquals(0, i-j)

    def test_thingies(self):
        for i in xrange(1, 4):
            for j in xrange(2, 6):
                self.check(i,j)

It would be nicer to generate individual tests, but do you really get that much benefit out of it?

Or write a reusable function:

data = [(i,j) for i in xrange(1,4) for j in xrange(2,6)]
add_data_tests(TestClass, data, 'check')


RubberDuck is right. It looks like you are reinventing the wheel. Unless you are doing this whole thing for educational purposes, you should rather use TPL. ForEach method does exactly what you are trying to do and most likely does a better job at splitting processing power between the tasks:

Parallel.ForEach(source, action);

Regarding your implementation: CountdownEvent implements IDisposable, so you should dispose it after you are done using it. Or wrap it into a using block.

Also this code is the kind of micro-optimization you should avoid:

if (exceptions == null)
    lock (syncRoot)
        if (exceptions == null)
            exceptions = new ConcurrentBag<Exception>();

Is new ConcurrentBag call a bottleneack of this method? Does it take anywhere near as much resources as calling an Action method? "No? Then don't introduce additional concurrency!" :)  Just call ConcurrentBag<Exception> exceptionsBag = new ConcurrentBag<Exception>(); and forget about synchronization. Or at least follow Eric's advice in above link and use Lazy<T>.


I would avoid the habit of declaring multiple variables in the same line. In most cases, they're hard to read especially when they get long. The only one exception I'd do this would be if everything is short enough to read, like your let line. But that one has other issues as well: why the two falses? and why initialize with false when they end up as other types (string for email and url, and an Error instance for error)?
A general rule for try-catch is to only use it for unexpected errors, like for calls to other functions. Never use it as a control structure. In your case, you're using thrown errors to bail out of the block. Throwing an error inside your own try-catch is an anti-pattern. It's better to use a conditional instead.
Then theres the inconsistent use of syntax, like the use of template literals here but not there, or the one-time assignments to a let which can just be a const, etc.
Now, doing away with the try-catch, the only thing that's complex is the relationship between error and valid. Everything else is just a value resulting from an expression, which in the following example... is just a series of const.
In your code, you compute validity twice and determine which error to use based on which check failed. This probably led to the strange complexity in your version of the code, you had to bail out with your error before it did the next check. But you can flip it around. You can use the check to determine the error. Then define valid based on the presence or absence of that error.

function validEmail(input = '') {
  const inputPattern = /^[^@]{1,64}@[^@]{4,253}$/
  const emailPattern = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i
  const email = input.trim()

  // handles punycode, etc using browser's own maintained implementation
  const url = new URL(`http://${email}`)
  const urlDerived = `${url.username}@${url.hostname}`

  // Same-ness is the same regardless of errors. Bumping up.
  const same = urlDerived === email;

  // Test for incorrectness, null if ok.
  const error = !inputPattern.test(email) ? new Error(`invalid email pattern on input: ${email}`)
    : !emailPattern.test(urlDerived) ? new Error(`invalid email pattern on url: ${urlDerived}`)
    : null

  // The presence/absence of the error determines validity.
  const valid = !Boolean(error)

  return { email, url, same, valid, error }
}

[
  'user+this@はじめよう.みんな',
  'stuff@things.eu',
  'stuff@things',
  'user+that@host.com',
  'Jean+François@anydomain.museum',
  'هيا@יאללה',
  '试@例子.测试.مثال.آزمایشی',
  'not@@really',
  'no'
].forEach(email => console.log(validEmail(email), email));


90 year data simulation in need of performance increase

This cleanup code at the end is indicative of the problem with this program:

clear i
clear j
clear k
clear l
clear m
clear n
clear o
clear p

Nobody is going to reverse-engineer your minified / obfuscated code to understand it.  You will probably have a hard time understanding it yourself if you come back to it after a few weeks.  The program is therefore unmaintainable.

I wouldn't have much confidence in the correctness of the results, either.  The code should be broken down into functions, each of which has a single purpose, specific inputs and outputs, and is separately testable.


Calculate min/max values for signed or unsigned integral number with any valid number of bits (up to 64)

First of all, I think there are misprints in your code that maximums are negative and minimums are positive.

Next. Since you need MinI, MaxI and MaxN values for a few bits only, it makes sense to calculate these values apriory. In this case we can use loop for calculation.
In the following code I've used recurrent formulas for calculation, which are much more readable in my opinion:

public class Bits
{
    public const int MaxBits = 64;

    public static readonly ReadOnlyCollection<long> MinI;
    public static readonly ReadOnlyCollection<long> MaxI;
    public static readonly ReadOnlyCollection<ulong> MaxN;

    static Bits()
    {
        long[] minI = new long[MaxBits + 1];
        long[] maxI = new long[MaxBits + 1];
        ulong[] maxN = new ulong[MaxBits + 1];

        maxN[1] = 1;

        for (int i = 2; i < MaxBits; i++)
        {
            maxI[i] = maxI[i - 1] * 2 + 1;
            minI[i] = -maxI[i] - 1;
            maxN[i] = maxN[i - 1] * 2 + 1;
        }

        maxI[MaxBits] = long.MaxValue;
        minI[MaxBits] = long.MinValue;
        maxN[MaxBits] = ulong.MaxValue;

        MinI = new ReadOnlyCollection<long>(minI);
        MaxI = new ReadOnlyCollection<long>(maxI);
        MaxN = new ReadOnlyCollection<ulong>(maxN);
    }
}

Usage:

Console.WriteLine(Bits.MinI[3]);
Console.WriteLine(Bits.MaxI[3]);
Console.WriteLine(Bits.MaxN[3]);

Output:

-4
3
7

The only difference in functionality I can see is that arrays have values for bits 0 and 1.
Hope it is not a problem for you.


What is wrong with simple code like?:

distances <- adist(candidates, target)
candidates[distances == min(distances)]

This is shorter and, in my opinion, easier to read, as it do not require any knowledge of additional packages.

Also, you mentioned that your data is small and it looks like you are working with vectors, in that case I do not see a point to use data.frame, dplyr etc.


General approach to build Web API without models, doesn't give the full web API capabilities.

E.g:

Help: You cannot have Web API help generated automatically.
You cannot return error handling scenarios: status, message

If you don't want to create the DTOs (Models), you can use the dynamic types. JSON formatter works well with the dynamic types.


Searching the Array Index & Element Equality

I think you've made the right call in going with binary search for this problem. I agree that in terms of asymptotic complexity it is \$ O (log(n)) \$ in time and \$ O(1) \$ in space.

The line ind = 0 is unnecessary because it will be reset 3 lines later before it's ever used.

The implementation seems broadly solid and you have your edge cases covered. I think you could simplify out that last if arr[left] == left: check by changing the loop condition to while left <= right:. That would mean the computer running a couple of unnecessary lines of code going through the loop one last time instead of you writing (and the computer parsing) a couple of unnecessary lines of code checking an edge case. I would probably favour the code uniformity, but there's not much in it.

I think if I was writing that innermost test block I'd do it slightly differently. I'd first check for equality and set last in the case of a match, and then independently (i.e. not in elif) check for which way to search. This just makes it easier to see what you are doing, in terms of record running best and continue search. Something that looks a bit like this

    if arr[ind] == ind:
        last = ind # found a satisfying index. Record it

    if arr[ind] >= ind:
        right = ind - 1 # Navigate left for smallest satisfying index
    else:
        left = ind + 1 # Navigate right for smallest satisfying index

You could possibly do with a couple of comments to help make it clearer what is going on. In particular, I would appreciate a comment explaining what your algorithm is doing at a high level, and where it differs from what I might expect. That is, for example, that it's using binary search, and that it doesn't return immediately on finding a solution because it needs the lowest satisfying number.
Also on code clarity, I find the variable name last confusing. What is it the last of? It could either benefit from a comment saying that it's the best satisfying index found thus far, or renaming to that effect.

if arr[ind] - ind < 0: is a slightly strange and unnecessarily complicated way of writing if arr[ind] < ind:. In python it is normally equivalent because python normally uses arbitrary precision integers, but in some cases where it's using a C style fixed length integer representation it could actually give the wrong answer because of integer underflow.

On a very pedantic note, this answer is potentially incorrect half the time because it ignores negative indicies. Python allows indexing to a[-x] to return the xth entry from the end. If your input array is a=[-7, -2, 5] then a[-2]==-2 and -2 is the lowest such index. I think this is a failure on the part of the question setter, and I'm confident that they don't have it in mind because they asked for a failing return code that would otherwise be a legal return code. Probably a case of "Clarify the requirements" in an interview or development situation rather than "Change the code" but it's worth bearing in mind.


Very basic "sleep calculator" algorithm in C using cs50 library

A few things:

Naming: b and w aren't particularly descriptive.  Even bampm and wampm are better.
You've got extra {} around your if statement for some reason.
Your algorithm does a lot of tests.  What if you convert to 24-hour time?

Doing so will let you get rid of b and w by changing bedtime and wakeup after you read them.

printf("When did you go to bed last night?\n");
int bedtime = GetInt();
// determine AM or PM
printf("AM [1]\nor\nPM [2]\n");
int ampm = GetInt();
// convert to 24-hour time
if (ampm == 2) bedtime = bedtime + 12;
// get user wake up time
printf("When did you wake up this morning?\n");
int wakeup = GetInt();
// determine AM or PM
printf("AM [1]\nor\nPM [2]\n");
ampm = GetInt();
// convert to 24-hour time
if (ampm == 2) wakeup = wakeup + 12;

Also, the conditionals get easier:

int slept = wakeup - bedtime;
if (slept < 0) { slept = slept + 24 } // math is your friend
printf("You slept for %i hours last night\n",slept);

Once principle of programming is "Don't Repeat Yourself" aka "DRY".  Do you really need 3 copies of the output printf?

Of course not.  You can move it after the end of the if statement.
Finally, I don't know if this was covered in class, but you're not doing any input checking.  What if the user puts in 3 instead of 1 or 2 ?  What if they put in times like -5 or 27 ?


Zip Code to City, State for registration form

Global variables
In your function getAddressInfoByZip, you are declaring quite a number of global variables.
This is bad practice: all these variables should be local variables because they only serve a purpose in this function.
Now, you may not notice that you are creating a bunch of global variables. The evilness is happening in this line:
var street_number = route = street = city = state = zipcode = country = formatted_address = '';

The only local variable that is being created here is street_number; all those other variables are global.
Experiment
Run this in your console:
(function() { var foo = bar = "Hello, World!"; } )();

Then, try this:
console.log(foo);

You will get an error, because now that the anonymous function is out of scope, foo no longer exists.
Now, try this:
console.log(bar);

You will see

Hello, World!

Why? Well, since you created bar in that variable chain, it is created globally because there is no var keyword assigned to it.

This if statement is a little long:
if (types == "sublocality,political" || types == "locality,political" || types == "neighborhood,political" || types == "administrative_area_level_3,political") {

I recommend you split up each conditional by line, like this:
if (types == "sublocality,political" ||
    types == "locality,political" ||
    types == "neighborhood,political" ||
    types == "administrative_area_level_3,political") {

I'm confused by this line:
...document.getElementById('<%=txtCity.ClientID%>')...
Previously, you were using JQuery to interact with elements. Why did you suddenly stop using it here? If you are going to "import" JQuery, you might as well use it.

Inside the body of a function passed to $.getJSON, you are accessing a parameter passed in to the function called results. However, every time you are accessing it, you are accessing the 0th index of the results property of this results parameter.
Why don't you just store that in a variable? It would make your code a lot cleaner in a lot of places, and it increases readability because it doesn't make someone wonder why you are specifically accessing this value each time you want to use it.
Create a variable set to this value:
results.results[0];

I recommend creating an object of constants that are the different types. That way, you won't have to keep writing, for example,
"sublocality,political"

The object only has to be really simple: it's merely to store constants:
var Type = {
    SP: "sublocality,political",
    LP: "locality,political",
    AAL1P: "administrative_area_level_1,political",
    ...
}

Note: I chose to name the identifiers using PascalCase for the object name and SHOUTCASE for the property names because most enumerated types are named like this.
Now, you can easily access a type like this:
Types.LP

This improves the readability of your code by a lot, because it gets rid of all the strings floating around your conditional statements.


Mutex helper for interprocess sychronization of accessing a network drive

Unfortunately you are in fact doing something wrong, but maybe not terribly! Because you are accessing the Mutex either side of an await, there is no guarantee that the same thread will be accessing it each time. The question and answer here have more detail. This is only a problem if your SynchronizationContext doesn't guarantee async calls will return to the same thread (as I suspect is the case when running your tests). If you only call this code from the UI thread of a WPF app for example, you won't have any issues. The code breaks when used in a console app however.

public class Program
{
    public static async Task Main()
    {
        using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
        {
            await Task.WhenAll(
                InterprocessSynchronizer.TryExecuteAsync("resource", c => SwitchThreads("FIRST", c), TimeSpan.FromSeconds(60), cts.Token),
                InterprocessSynchronizer.TryExecuteAsync("resource", c => SwitchThreads("SECOND", c), TimeSpan.FromSeconds(60), cts.Token)
            );
        }
    }

    private static async Task<int> SwitchThreads(string name, CancellationToken arg)
    {
        Console.WriteLine($"{name} ON THREAD ID {Thread.CurrentThread.ManagedThreadId}");
        await Task.Delay(1000, arg);
        Console.WriteLine($"{name} NOW ON THREAD ID {Thread.CurrentThread.ManagedThreadId}");
        return 0;
    }
}

  Object synchronization method was called from an unsynchronized block of code

If you encounter this error some of the suggesting in the afformentioned SO question could help.


Implementation of `ulp` and `nextAfter` for platforms where these are missing

The code looks neat enough, well formatted, etc. That's great. There is one common issue you have in your code, and that is the else-if for early-return blocks.

The code:

if (conditionA) {
    ... do something
    return something;
} else if (conditionB) {
    ... do something
    return something;
} else if .....

has redundant if blocks. The logic is right, but, it would be better as:

if (conditionA) {
    ... do something
    return something;
}
if (conditionB) {
    ... do something
    return something;
}
if .....

You have that pattern in a lot of places.

A second general concern I have is that you do not specify 'final' for your parameters in places where it can make sense. The 'final' concept is debatable for performance, but I have found that it makes a difference in both the disciple, and occasionally the performance. For example, the function:

private boolean isSameSign(double x, double y) {
    return copySign(x, y) == x;
}

would be better as:

private boolean isSameSign(final double x, final double y) {
    return copySign(x, y) == x;
}

ulp()

It would be convenient in your ULP to do the d = Math.abs(d) earlier in the function as it simplifies some logic. Consider the following:

public double ulp(final double input) {
    final double d = Math.abs(input);
    if (Double.isNaN(d)) {
        // If the argument is NaN, then the result is NaN.
        return Double.NaN;
    }
    if (Double.isInfinite(d)) {
        // If the argument is positive or negative infinity, then the
        // result is positive infinity.
        return Double.POSITIVE_INFINITY;
    }
    if (d == 0.0) {
        // If the argument is positive or negative zero, then the result is Double.MIN_VALUE.
        return Double.MIN_VALUE;
    }
    if (d == Double.MAX_VALUE) {
        //If the argument is ±Double.MAX_VALUE, then the result is equal to 2^971.
        return MAX_ULP;
    }
    return nextAfter(d, Double.MAX_VALUE) - d;
}

I assume that your research on \$2^{971}\$ is accurate for Double.MAX_VALUE.

copySign()

Edit: This method confused me, and lead me to introduce a bug in my code (now fixed).

It is my opinion that the arguments are the wrong way around. I would expect copySign(x, y) to copy the sign from x to y, but your code implements it the other way around. Instead of arguments x and y, they should have better names, and the method should be named differently as well:

public double copySignToFrom(final double target, final double sign) {...}

My preference would be to just reverse the arguments, but that method is overridden, and the implementation is not actually shown here (Note: Show all your code next time...).

nextAfter()

Again, like ulp(), this function would benefit from removing the 'else if' construct. The early return makes it unnecessary.

The logic in here looks good. I have tried to see if there's a better way of doing things, and, I think there may be... by recording the signs of the start & direction, you can do all the math in absolute terms, and re-conevrt the signs later.... It's a toss up as to whether the performance will be better to do the conversion each time, and then have simpler conditions on the logic.

So, the only real criticism I have here is the else if, but, for interest, consider the following:

Edit: revised my code example because of copySign usage bug...

public class DoublePlay {

    private static final long MASK = Long.MIN_VALUE;

//    @Override
    public double copySign(double target, double source) {
        if ((Double.doubleToLongBits(target) & MASK) == (Double.doubleToLongBits(source) & MASK)) {
            return target;
        }
        return Double.longBitsToDouble(Double.doubleToLongBits(target) ^ MASK);
    }

    private boolean isSameSign(double x, double y) {
        return copySign(x, y) == x;
    }

    public double nextAfter(final double start, final double direction) {
        if (Double.isNaN(start) || Double.isNaN(direction)) {
            // If either argument is a NaN, then NaN is returned.
            return Double.NaN;
        }
        if (start == direction) {
            // If both arguments compare as equal the second argument is returned.
            return direction;
        }

        final double absstart = Math.abs(start);
        final double absdir = Math.abs(direction);
        final boolean tozero = !isSameSign(start, direction) || absdir < absstart;

        if (tozero) {
            // we are reducing the magnitude, going toward zero.
            if (absstart == Double.MIN_VALUE) {
                return copySign(0.0, start);
            }
            if (Double.isInfinite(absstart)) {
                return copySign(Double.MAX_VALUE, start);
            }
            return copySign(Double.longBitsToDouble(Double.doubleToLongBits(absstart) - 1L), start);
        }

        // we are increasing the magnitude, toward +-Infinity
        if (absstart == Double.MAX_VALUE) {
            return copySign(Double.POSITIVE_INFINITY, start);
        }
        return copySign(Double.longBitsToDouble(Double.doubleToLongBits(absstart) +1L), start);

    }

    private static final void testValue(DoublePlay dp, final double base, final double direction) {
        double result = dp.nextAfter(base, direction);
        System.out.printf("From: %016x %s%nStep: %016x %s%nTo  : %016x %s%n%n",
                Double.doubleToLongBits(base), String.valueOf(base),
                Double.doubleToLongBits(direction), String.valueOf(direction),
                Double.doubleToLongBits(result), String.valueOf(result)
                );
    }

    public static void main(String[] args) {
        DoublePlay dp = new DoublePlay();
        testValue(dp, Double.MIN_VALUE, Double.POSITIVE_INFINITY);
        testValue(dp, Double.MIN_VALUE, Double.NEGATIVE_INFINITY);
        testValue(dp, -Double.MIN_VALUE, Double.POSITIVE_INFINITY);
        testValue(dp, -Double.MIN_VALUE, Double.NEGATIVE_INFINITY);
    }

}

The above code makes the decision 'early' about whether the magnitude of the nextAfter() is increasing (to infinity), or decreasing (to zero). It simplifies the rest of the conditions.

Added an Ideone with the code as well


How can I get this R code to pass the "1 minute" test for this Project Euler question?

You should change the algorithm in order to make your program run faster. The while loop is performed over 200 million times (printing out information in every iteration) until it reaches the desired number.

If you calculate the answer using LCM (taking the least common multiple of all numbers between 1 and 20), the program should run instantly in pretty much any programming language.


Entity Relationship Diagram for Grade Calculator

I've got a few thoughts:

The user table is related to the course table in a funny way. At first when I was looking at the diagram I assumed users were students, but after staring for a while, that seemed less and less likely. I'm now under the impression that the user is the owner of the course, and I think that having the user_id in the course table is a little funny. I would use a separate mapping table like so:

The lookup tables seem fairly useless as you are using the actual value in the base tables instead of a lookup id. Changing it to look like this will add usefulness:

Your naming is a little strange. I would change the course table to be named courseInfo, and change yearGroup to be named course. This might be a little nitpicky as this is a generally well done diagram. :P

Notes in response to comments:

If you want to share a course between users, you will need to change your schema to be similar to mine. If, as suggested in the comments, only one user will ever use a course, then you're probably okay with the schema your using. I just don't generally think of a user as an attribute of a course. It's a little ambiguous: is that user a teacher, student, or what have you.
One thing to think about for lookup tables is that if you're not using an id, then the value is duplicated. If you ever update the lookup table, you have to change all values in the other table as well.
I do definitely think yearGroup is a misnomer. Where I come from, courses are offered by semester or some other frequency besides yearly.


Find all root to leaf paths in binary tree

regarding the translation from int to String

path.add(""+root.val);

This is both unclear and also involves unnecessary String creation.  Why not use the "official" conversion method? it clearly states the intention and is more efficient

path.add(String.valueOf(root.val));


Iterate over two collections of equal length

You can use LINQ's Zip method. As usual, it's a bit slower than manually written code, but unless this is in a hot spot it rarely matters. The cost of Console.WriteLine vastly exceeds the cost of LINQ.

foreach(var pair in collection1.Zip(collection2, Tuple.Create))
{
    Console.WriteLine("{0}, {1}", pair.Item1, pair.Item2);
}

You can replace Tuple.Create by ValueTuple.Create if you target .net 4.7 or you referenced the compatibility nuget package. This saves a heap allocation and is usually faster.

In C# 7 you could use named tuples, which enables meaningful property names. It's based on ValueTuple and thus avoid the heap allocation as well.

names.Zip(ages, (name, age) => (Name:name, Age:age))


Variadic function to find the first matching (string) argument in a larger array

Good stuff!

I only see one big issue (which is actually what's preventing you from using this as a constexpr).

Errors:

UB: Unsequenced modification

matching[mi++] = (str[(SS - 1) - matching[mi]]
         ^^                               ^^

Which value does mi take for that second indexing? The C++ standard says: either the pre or post increment value is legal. You have undefined behavior here.

You can solve this by separating out the mi incrementation as a separate statement. Using the evil comma operator would allow you to do it as a fairly small modification of your existing code:

(
  ((matching[mi] = (str[(SS - 1) - matching[mi]] == values[i])
     ? (matching[mi] - 1)
     : ((str[0] == values[i]) ? (SS - 2) : (SS - 1))
  ), ++mi),
...);

This actually makes the constexpr version work!

Style

I think find_first should be a free-floating function, since you already have the [] accessors.
I would definitely try to format that fold expression in a more readable manner. See my version of it above for an example.

Improvements

Add a template deduction guide:

Something like this:

template<typename T, size_t LEN>
buffer(const T(&)[LEN]) -> buffer<T, LEN>;

So then your declare buffers in a cleaner manner, and have the buffer be perfectly sized:

buffer<char, 256> b { "find mefind me:gehoehgioewghowieanother string:" };
//becomes
buffer b { "find mefind me:gehoehgioewghowieanother string:" };


As you're beginner, your code can be considered ok.

However you may want to consider following points which help you to write reliable (maintainable) code and improve performance.

You want to store connectionstring to some common place like web.config. You don't have to find and change it all over the place you used it, just change at one place and it will be reflected.
You may want to use stored procedure instead of inline query. With stored procedure, your sql code will be more maintainable and you can go through execution plan of sql code to find out any performance bottleneck. To change sql code you don't have to modify and compile your .net code.

I hope it helps!


Setting a request header with or without Context in Golang

Long form comment:  Yes, the context version.  I'd consider it a bad pattern to modify incoming data inline (because it's harder to track later what came in and what the application did with it).  Especially in applications which do not only handle HTTP traffic, but also, say, gRPC calls, it's even more important that this data isn't stored for one type of handler only, but for all of them in a unified fashion.  Plus, context is (for better and worse) a kitchen sink for all layers of the code, even in the deepest layers you'll still be able to get that ID for various purposes, maybe auditing, or so.

Maybe it doesn't even need to go into the context, simply add it to the logger data (if there's such a thing), or however else that's being populated.  Doing that in a wrapper like this will again allow you to keep it out of the rest of the application - problem solved and no need to mess with the context object.  In any case it's not difficult to change that later.


Library functions usage

The unique_exam function is basically checking if the exam is in the array or not and returning false if it is not, the includes method is what You need.

return ! exam_array.includes(exam)

Inline

dayAvailable

Should be inlined as it boils down to just one comparison, instead the number of exams per day should be saved as a constant.


KQuery SPOJ problem, using merge sort segment tree

Your biggest issue here is that you are building a new list for every single query. Each of these lists can have size up to \$N\$ (since the query could be over the entire universe), so building this list takes time \$O(N)\$ in the worst case (this is true even though it is built from logarithmically many smaller lists). This makes the total runtime of your algorithm \$O(N\log^2 N + QN)\$, and \$O(QN)\$ is way too large to run in time for the parameters of this problem.

Of course, the solution to this issue is that you don't really need to build the list for each query; you just need to count how many elements are larger than k. Since the list for each query is just the union of logarithmically many sorted lists in your segment tree, just count this quantity for each of those lists and sum this up. This reduces your time complexity to \$O(N\log^2 N + Q\log^2 N)\$ (there are \$O(\log N)\$ lists, and it takes \$O(\log N)\$ time to binary search each one), which should run in time.

If your code still times out after making this change, I would recommend rewriting the code for build and query iteratively instead of recursively; this can sometimes speed things up a bit (however we're no longer in the realm of asymptotic improvements).

Some other code things:

I might be wrong, but I think it's generally accepted that the register keyword in C++ doesn't really do much anymore; compilers are way better than people at figuring out which variables should be stored in registers, so you're not going to get any speedup by explicitly declaring this.
Your query method accepts k as a parameter, but you don't actually use k anywhere (short of passing it along in recursive calls). That said, given the above answer, you probably should be using k in the query method.
I guess it's not super necessary for short and quick solutions to contest problems like this, but I think your code would benefit a lot from a bit more whitespace and consistent indentation (I think it would make it a lot easier to spot bugs as well). One of the things that bugs me the most about your code is how you write for(i=0;i<n;i++) and scanf("%d", &arr[n]) on two consecutive lines at the same indentation; it makes it very unclear that the second line is part of the for loop.


Optimizing reading integers directly into a set without a list comprehension in Python

inpt = raw_input("Enter a string of numbers: ")
numbers = sorted(set(map(int, inpt.split())))
print numbers

I would recommend separating the input-reading from the integer-extraction part.
Using raw_input (Python 2.x) or input (Python 3) is more usual for reading user inputs.
You can do it all in one line using sorted instead of sort.
Performance-wise it might be better to apply set first, and then map, so int has to be applied to fewer elements, but I don't think it makes much of a difference, if at all.


Instead of looking for cool new features of Java i would strongly suggest that you concentrate on the basics of Java: Objects:

Think in Objects:

So far you have identified these Objects: Map, a Cell and an Island - so make some Objects of that type.

Map map = new Map(int[][] src);
Island island = map.extractIsland();
int diameter = island.getPerimater();

the Map needs some methods to properly extract the island

Cell cell = getCellAt(int x, int y);

and a method to gain relationship between each Cells on the map:

List<Cell> getNeighbours(Cell center);

and some elementary methods on the Cell class

boolean isWater();
boolean isLand();
int getAmountCoasts();

if you would have these elementary Objects you can simply create readable Code - see this example:

Cell center; //yes, here center.isLand() = true
List<Cell> neigbour = map.getNeighbours(center);
for (Cell neigbour: neigbours){
    if (neigbour.isWater()){
        center.addCoast();
    }
}

once you are here you can use features from java 8

List<Cell> landCells = cells.stream.filter(Cell::isLand).collect(CollectorsToList());
int perimeter = landCells.stream.mapToInt(Cell::.getAmountCoasts).sum();

Hint: you better let the Island class handle that, see first hints - Responsibility for coastLine is within the Island class!)

NOTE:

it's hard to think in objects whenever you try minimal code snippets as suggested from leet code. if minimal code is required, look maybe you are interested at CodeGolf...


I am blown away by how much less code I need to write

I'm going to blow your mind even more because you actually do not need to dispatch any actions inside createAsyncThunk.  It does that for you!
The "pending" action doesn't have a payload so getting the cellId is a little bit tricky.  You can see the types of the dispatched actions in the docs.  The property that you want is action.meta.arg.cellId.
You get better TypeScript support on your reducer by using the builder callback notation.  It already knows the types of your thunk actions!
The part that I am unclear on is what your bundle function does as it seems like it catches errors on its own?  That's fine but you can also throw errors in the inner function of createAsyncThunk and handle them in the reducer with the createBundle.rejected action.  You can also use the rejectWithValue helper to customize the error payload.
export const createBundle = createAsyncThunk(
  "bundle/create",
  async (data: { cellId: string; input: string }) => {
    const { cellId, input } = data;
    const result = await bundle(input);
    // this is the payload
    return {
      cellId,
      bundle: result
    };
  }
);

const initialState: BundlesState = {};
const bundleSlice = createSlice({
  name: "bundle",
  initialState,
  reducers: {},
  extraReducers: (builder) =>
    builder
      .addCase(createBundle.pending, (state, action) => {
        const { cellId } = action.meta.arg;
        state[cellId] = { loading: true, code: "", err: "" };
      })
      .addCase(createBundle.rejected, (state, action) => {
        //??
      })
      .addCase(createBundle.fulfilled, (state, action) => {
        const { bundle, cellId } = action.payload;
        state[cellId] = {
          loading: false,
          code: bundle.code,
          err: bundle.err
        };
      })
});


I wouldn't want to maintain this code. Unless you have proven that this code is a performance problem, do the simple thing. Yes, the following solution will iterate over the lists 3 times. No, I don't care that it does.

var both = listA.Intersect(listB);
var listAOnly = listA.Except(listB);
var listBOnly = listB.Except(listA);

If you're worried about case insensitivity, pass in a StringComparer.


Looks good for a beginner.

Couple tweaks if you want to make it look nicer. The name of the class should be somewhat describing the purpose so in your case Calculator would fit better. If you are familiar with enum you could parse your +, -, / into an enum and do switch on that. Then next tweak could be to do the System.printout at the end and in the switch case to do just the operation.

Another suggestion would be to make 4 classes implementing binary operations with just one method taking two arguments and returning the result. Then you can have a map with a key being the operation (in enum or string) and the value would be the appropriate class. Then you end up with more classes but this main method gets shorter.

Generally it is better to split the code in more methods and classes and keep the motto "one class one responsibility", or Single Responsibility Principle. So as an example each of your arithmetic classes would be responsible for a single arithmetic operation. If you want to follow that completely, then you would have to create a class that gets the input from the user as well. The Calculator class then would be just like a coordinator saying: give me numbers, give me an operator, perform the operation and print out the result at the end.

Note: If you want some sample code leave me a comment here and I can add some.


Selecting multiple filters based on the true/false conditions

Yes your code has a lot of redundancy.  It can be simplified down to this:

if (residential)
{
    ClickButton(() => FindElement(By.CssSelector(propertyTypeResidentialCss)), "Residential");
}
if (commercial)
{
    ClickButton(() => FindElement(By.CssSelector(propertyTypeCommercialCss)), "Commercial");
}


Use a set

Sets guaranty the unicity of the items it holds, adding the same item twice will result in the second add doing nothing:

def get_startup_folders(self):
    folders = set()
    for item in STARTUP_FOLDERS:
        if item == "home":
            folders.add(self.home_folder)
        elif item == "file":
            folders.add(self.file_folder)
        elif item == "project":
            folders.update(self.project_folders)
        elif item == "user":
            folders.update(self.user_folders)

    # Fail-safe: If empty then use the home folder as a fall back;
    # self.home_folder is guaranteed to contain the home folder.
    if not folders:
        folders.add(self.home_folder)

    return folders
    # or if you trully need a list: return list(folders)

If order matters, there is no such thing as OrderedSet, but collections.OrderedDict should be close enough. You just need to handle values that you won't keep:

import itertools
from collections import OrderedDict

def get_startup_folders(self):
    folders = OrderedDict()
    for item in STARTUP_FOLDERS:
        if item == "home":
            folders[self.home_folder] = None
        elif item == "file":
            folders[self.file_folder] = None
        elif item == "project":
            folders.update(zip(self.project_folders, itertools.repeat(None)))
        elif item == "user":
            folders.update(zip(self.user_folders, itertools.repeat(None)))

    # Fail-safe: If empty then use the home folder as a fall back;
    # self.home_folder is guaranteed to contain the home folder.
    if not folders:
        return [self.home_folder]

    return list(folders.keys())


In such cases I try to move repeated code to separate method that accepts block.

def notify_client(url, params)
  notify(url, params) { |path| Net::HTTP::Patch.new(path) }
end

def notify_vendor(url, params)
  notify(url, params) { |path| Net::HTTP::Get.new(path) }
end

def notify(url, params)
  uri = URI.parse(url)
  https = Net::HTTP.new(uri.host, uri.port)
  https.use_ssl = !Rails.env.development?
  req = yield uri.path
  req.body = {data: {attributes: params}}.to_json
  res = https.request(req)
  puts "Response #{res.code} #{res.message}: #{res.body}"
end

That code refactoring quite simple. If you need more details - let me know.


Is this PHP Email Form Secure from injections or other abuses?

I use a blank input field in the form and hide it with css.  If the field exists upon form submit, I know it's spam and just ignore it.

<form method="post">
<input type="text" name="email" />
<input type="text" name="email2" style="display:none;" />
<input type="submit" />
</form>

<?php if (!$_POST['email2']) { // not spam } ?>

Of course this only works with bots and spammers who scrape sites to get all the input fields, but since I've implemented it, it's worked great.


Reading 8 divs across the screen depending on assignment time

Note: As I type "pony" and "ponies" in my code, I can't help but wonder what the hell I'm doing with my time. Never thought I'd be writing words like that in javascript...

Anyway! My first suggestion would be to make everything more flexible bynot relying on element IDs, and a set number of DIV elements. If you add or remove one, you'll have to make sure its ID is numbered correctly, and update your code to match. Much easier to just use jQuery to find and animate the DIVs, regardless of how many there are.

In fact, the elements plus jQuery can tell you everything you need to know, so there's no need to store anything along the way.

Also, the reset functionality is trivial. No need reload the entire page just for that.

Lastly, and perhaps most importantly, you code announces the winner immediately - before the poni-- ahem, the DIVs have even raced. Yes, the winner is picked right away, and it's kinda' obvious which one will reach the goal first, but still. Better to announce the winner when it crosses the finish line.

Of course, overall it'd be more fun to have something more random, where the DIVs move in fits and starts, so you can't tell who's going to win until the very end. But I'll stick to refactoring your current code.

Here's a demo of my version and here's the code:

$(function() { // just pass in a function; it's the same as using $(document).ready()
  var ponies = $(".pony"), // Again: I never thought I'd write "ponies" in code
      raceButton = $("#raceButton"); // use a single button for race and reset

  ponies.click(function (event) {
    ponies.removeClass('selected');
    $(this).addClass('selected');
    // no need to store the selection; we can always find it, now that it's got a "selected" class
  });

  // use one button for both start and reset
  raceButton.click(function() {
    // If we have a winner, the race is pretty much over
    // If we have no winner, and no elements currently animating, we're ready to race
    // Otherwise we're racing; don't do anything

    if( ponies.filter(".winner").length !== 0 ) {
      reset();
    } else if( ponies.filter(".winner, :animated").length === 0 ) {
      race();
    }
  });

  function race() {
    // check for selection
    if( ponies.filter(".selected").length === 0 ) {
      alert("Please click the pony you think will win the race.");
      return; // return here instead of having a big else-block
    }

    var times  = [], i, l;

    // disable the race button
    raceButton.prop("disabled", true);

    // build time array; don't hardcode it
    for( i = 0, l = ponies.length ; i < l ; i++ ) {
      times.push(i);
    }

    // Use .each() instead of relying on all the divs having numbered IDs.
    ponies.each(function () {
      var index = Math.floor(Math.random() * times.length),
          time  = times[index],
          pony  = $(this);

      times.splice(index, 1);

      // Use the onComplete callback to identify the winner
      pony.animate({left: '320px'}, {
        duration: (time + 3) * 1000, // only here do we set the minimum time by adding 3
        complete: function () {
          // If this was the fastest one
          if( time === 0 ) {
            pony
              .addClass("winner")
              .append("Winner!"); // use a span or something, so it's easier to remove later

            // alert the gambler and enable the reset button
            if( pony.hasClass("selected") ) {
              alert("You win tons of money or something");
            } else {
              alert("You lost. Boo-hoo");
            }
            raceButton.prop("disabled", false).val("Reset");
          }
        }
      });
    });
  }

  // just reset everything yourself; no need to reload
  function reset() {
    ponies
      .stop()                  // stop any running animations
      .removeClass("selected") // clear selection
      .removeClass("winner")   // clear winner
      .css({ left: '0px' })    // move 'em back
      .children("span").remove(); // remove the label
    raceButton.val("Race!");
  }
});

Addendum: As Sridhar points out in the comments, you there are some issues with the code above. Both are related to the state of the race, so one way to deal with it is to extract a few functions that check the state:

function raceInProgress() {
  return ponies.filter(":animated").length > 0;
}

function raceDecided() {
  return ponies.filter(".winner").length > 0
}

function raceNotStarted() {
  return !raceInProgress() && !raceDecided();
}

Now we can make sure that the gambler can't change the selection mid-race, by simply checking raceInProgress(). Plus, it's much easier to read and use than the raw jQuery selector magic.

I've made the changes in this demo rather than bothering to rewrite my original answer.


This looks pretty good for a start.

the only thing that I see right away is your CSS formatting

a {
    text-decoration: none
}

html, body {height: 100%; max-height: 100%; padding:0; margin:0;}
.wrapper {display:table; width:100%; height:100%;}
.wrapper > div {display:table-cell; vertical-align: top;}
.wrapper .left {width:200px; background-color:#34495E}

#btn_pri {
    background-color: 60A0DF;
    color: white;
}
#btn_sec { background-color: #e74c3c;
color:white;
}

Here you switch between what I would call Minified CSS and Egyptian Brackets and the last rule here is a mix.

you should always stay consistent with your Formatting, especially in CSS because it can get confusing when you start adding more rules

so if you did this in all Egyptian Formatting.

a {
    text-decoration: none
}

html, body {
    height: 100%;
    max-height: 100%;
    padding:0;
    margin:0;
}

.wrapper {
    display:table;
    width:100%;
    height:100%;
}

.wrapper > div {
    display:table-cell;
    vertical-align: top;
}

.wrapper .left {
    width:200px;
    background-color:#34495E
}

#btn_pri {
    background-color: 60A0DF;
    color: white;
}

#btn_sec {
    background-color: #e74c3c;
    color:white;
}

This is how I would do it personally, it is clear what rule is what, and it looks neat and tidy as well.

but how ever you decide to do it, please be consistent.

As far as these Empty Rules.

.navigation {
}
.navigation li {
}

I assume that you are going to use them in the future for something,  if not, get rid of them, they will clutter up your code.


You are storing the integers of a Triplet as a List internally, yet you are not really taking advantage of the interface List's functionality. For example:

return Objects.hash(triplets.get(0), triplets.get(1), triplets.get(2));

Why not simply do this:

return triplets.hashCode();

Or, another example:

return other.triplets.get(0) == this.triplets.get(0) &&
        other.triplets.get(1) == this.triplets.get(1) &&
        other.triplets.get(2) == this.triplets.get(2);

This can be replaced by this:

return other.triplets.equals(this.triplets);

There's an issue I didn't catch in the old question but which was already present there: Your code doesn't consider the possibility that the same sum is formed by more than one pair of numbers, because you are simply mapping integers to one pair of indices, and if you encounter a pair that adds up to a sum that is already stored in lookup, the old index pair gets overridden.

A way to overcome this problem could be to map the integers to a List<int[]>), but this would make things even more complicated, and I think the reason that this would get overly complicated is that you are, in fact, hard-coding a recursive process (first you create the pairs, then from the pairs you create the triplets etc.). You could instead try to write a method that accumulates all possible n-tuplets, with n being any arbitrary positive integer, through recursion, e.g. like this:

If n is 1, then return an array/list of all integers
If n is greater than 1, then iterate through the original array and, for every integer in it, combine this integer with all n-1-tuplets formed by the numbers that follow this integer in the array (taking only the following numbers and not the preceding numbers prevents duplicate tuplets that only differ in the order of the integers).

I imagine that this would be much easier to code than what you currently have (maybe this is also what you mean by your code being "muddy"), and also much more flexible. True, if it's just about pairs, then it might not be as fast as what you did here, but if it comes to tuplets of more than 2 numbers, I don't think there is much benefit of what you are trying to do here (although this is just a guess, I didn't actually benchmark it).


Filter array of objects by comparing nested object properties

We want to return every object in this array unless we have already returned an object with the same articleId.

I would use a Set object to keep track of which articleId values we've already used and then use .filter() to return only the items that pass the test.  Here's a runnable implementation:

let articles = [
  {dateAdded: "31-5-1989", readId: 123, article: { id: 1}},
  {dateAdded: "31-5-1989", readId: 124, article: { id: 2}},
  {dateAdded: "31-5-1989", readId: 125, article: { id: 1}}
];

function getUniqueArticles(array) {
    let ids = new Set();
    return array.filter(function(item) {
        if (!ids.has(item.article.id)) {
            ids.add(item.article.id);
            return true;
        }
        return false;
    });
}

console.log(getUniqueArticles(articles));

Note: Your articles array does not look valid as there seems to be a missing comma here in each array element and you probably mean to have quotes around the date to make it into a string:

{dateAdded: "31-5-1989", readId: 123, article: { id: 1}}
           ^^^       ^^^           ^^^


ForEachAsyncSemaphore asynchronously processing tasks but enable fast fail

First let me share with you my revised version then I will detail the changes what I've made:
public static async Task ThrottledConcurrenctForeach<T>(
    this IEnumerable<T> toBeProcessedItems, Func<T, Task> asyncOperation,
    int maxDegreeOfConcurrency, CancellationToken externalCancellationToken)
{
    ExceptionDispatchInfo capturedException = null;

    var internalCancellation = new CancellationTokenSource();
    var internalCancellationSignal = new TaskCompletionSource<object>();

    var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(externalCancellationToken, internalCancellation.Token);
    combinedCancellationTokenSource.Token.Register(() => internalCancellationSignal.TrySetCanceled(), useSynchronizationContext: false);

    using var throttler = new SemaphoreSlim(maxDegreeOfConcurrency);

    var processingOperations = toBeProcessedItems.Select(async item =>
    {
        await throttler.WaitAsync(combinedCancellationTokenSource.Token);

        try { await asyncOperation(item); }
        catch (Exception ex)
        {
            capturedException = ExceptionDispatchInfo.Capture(ex);
            internalCancellation.Cancel();
        }
        finally { throttler.Release(); }

    });

    await Task.WhenAny(Task.WhenAll(processingOperations), internalCancellationSignal.Task);
    capturedException?.Throw();
}

Naming
As you can see I've done a lots of renaming. I do believe that using the meaningful names improves readability and gives clarity. Here are a few examples:

ForEachAsyncSemaphore

Semaphore is an implementation detail

Try to focus on the provided functionality instead: throttling
You are using SemaphoreSlim not Semaphore that's why it's misleading

In case of I/O bound operations we are normally talking about Concurrency, in case of CPU bound operations we talk about Parallelism

If you want to emphasize your intent then make it visible to your
consumers

dop

This is a useless abbreviation

No-one will understand what that means unless (s)he reads the
implementation (if (s)he can access it)

Try to use as expressive parameter names as possible if you do not provide documentation comments

childCts

Yet again try to focus on the provided functionality

ExceptionDispatchInfo

If you don't want to change the StackTrace of the already thrown exception then please prefer ExceptionDispatchInfo
It preserves the original StackTrace with the re-throwability

CancellationToken's Register

Even though Task.Delay(Timeout.Infinite, linkedTokens.Token) works that's not the most elegant way to provide cancellation ability to Task.WhenAll
You can use the TaskCompletionSource<object> for signalling. It works fine with CancellationToken by combining Register and TrySetCanceled

using declaration

In order to reduce indentations (to streamline your code) please prefer using declaration if you are using C# 8 or greater


Time complexity

Your time complexity is linear but you can save a few traversals over the string and lower the constant factor as you improve readability. Checking whether a string is a palindrome can be done in one pass with two pointers at each end of the string (plus some conditionals for your special characters), but this gains speed at the expense of readability; I'd encourage a round of clean-up before going for optimizations.

Repeated code

Repeated code harms maintainability and readability. Notice that the line

str.replace(/[^\w\s]|_/g, "").toLowerCase().split(" ").join("");

appears in two places in the code. If you decide to change one to accept a different regex but forget to change the other one, you've introduced a potentially subtle bug into your program. Move this to its own function to avoid duplication.

Use accurate function names and use builtins

reverseString is a confusing function: it does more than reversing a string as advertised: it also strips whitespace and punctuation, which would be very surprising if I called this function as a user of your library without knowing its internals. All functions should operate as black boxes that perform the task they claim to, nothing more or less.

The array prototype already has a reverse() function, so there's no need to write this out by hand.

Avoid unnecessary verbosity

The code:

  if(str === reverseString(str))
  {
   return true;
  }
  else
  {
    return false;
  }

is clearer written as return str === reverseString(str);, which says "return the logical result of comparing str and its reversal".

Improve the regex to match your specification

Including spaces in your regex substitution to "" is easier than .split(" ").join(""). If you wish to remove all non-alphanumeric characters, a regex like /[^a-z\d]/gi reflects your written specification accurately (or use \W if you don't mind including underscores).

Style remarks

JS uses K&R braces instead of Allman by convention.
Add a blank line above for and if blocks to ease vertical congestion.
Add a space around keywords and operators like for( and >=0, which are clearer as for ( and >= 0.
No need for parentheses around a return value.
array.push(str[i]) is missing a semicolon.
CodeReview's snippet autoformatter will automatically do most of this for you.

Rewrite 1

const palindrome = str => {
  str = str.replace(/[^a-z\d]/gi, "").toLowerCase();
  return str === str.split("").reverse().join("");
};

console.log(palindrome("My age is 0, 0 si ega ym."));

Rewrite 2: uglier, but faster

Benchmark

const palindrome = str => {
  str = str.replace(/[^a-z\d]/gi, "").toLowerCase();
  let left = 0;
  let right = str.length;

  while (left < right) {
    if (str[left++] !== str[--right]) {
      return false;
    }
  }

  return true;
};

[
  "",
  "a",
  "aba",
  "racecar",
  "racecar ",
  " racecar",
  " race car",
  " r  r a c e   c a  rr     ",
  ".a .. r . ... . .{9f08e988-1e35-4dc6-a24a-5c7e03bce5ba}$ $!ace ca r3  a",
].forEach(test => console.log(palindrome(test)));

console.log();
[
  "ab",
  "abc",
  "racecars",
  "racescar",
  " ra scecar",
  " r   sace car",
  "a r  r a c e   c a  rr     ",
  " r  r a c e   c a  rr     a",
  ".a .. r . ... . .$$$ $!aces ca r  a",
].forEach(test => console.log(palindrome(test)));


Method to remove outliers from a set of values

You used Math.Abs(o.MyProperty - meanValue) to check both upper and lower cases.

But then you do specify minValue and maxValue separately. You could apply the same logic here:

decimal maxRange = (1.5m * quartiles.IQR);

if (Math.Abs(objectFarthestFromMean.MyProperty - meanValue) > maxRange)
{

Other than that, the calculation logic seems about as efficient as it can be (keeping readability in mind).


Remarks about your code

I, too, think that you should change the signature and not pass the year into that function, since basically it doesn't need to know about the year.  What it needs to know is whether it's a leap year or not (thus a bool from stdbool.h).  So pass that in. (A bit like Tell, don't ask in OOP)
Modifying the months length of February seems like the most "real world like" approach, but I wouldn't do it, because then you can make the months lengths const (and also static).  Do a correction (+ 1) for leap years after your calculation, then.
Going further, are you really interested in the lengths of a month? You could as well just store the number of days (in a non leap year) that precede a month (January -> 0, February -> 31, March -> 31 + 28, ...).  Then you can get rid of that loop all together.
Lack of assertments: When you make an assumption about the value of an function argument (1 <= months <= 12), then assert for that (even if the specification of your function does not include argument validation!) such that if an invalid value gets passed, you fail fast and loud. (Ooops .. an advise I should have implemented myself in the code below ...)
naming. monthToDays ... sounds like "convert a month into days" ... I would expect this to accept a month (number) and get the number of days in that month. ordinal_date ? Or a bit more detailed ordinal_date_day ?

Test, test, test!

Next, I'd like to introduce you to TDD (test driven development): Instead of first writing your code and then test it (as all - or almost all - code should be tested!) you start off writing tests, specifying the desired behavior, and then make these tests pass by actually implementing the logic to achieve that behavior.

Normally, you'd look into some testing framework / library, but we can go with a simple macro here for now:

#define check(expr) \
  if(!(expr)) { \
    printf("[FAILED] " #expr " in %s\n", __func__); \
  }

Note that this is the bare minimum of information we need out of a test case: An indication when it fails and which test case failed.  Testing frameworks can give you far better information, for example a comparison of the expected value of a function call and it's actual value.

Start with a simple case:

void ordinal_date_in_january_should_be_day_number() {
  check(ordinal_date( 1, 1, false) ==  1);
  check(ordinal_date( 1, 1,  true) ==  1);
  check(ordinal_date(11, 1, false) == 11);
  check(ordinal_date(11, 1,  true) == 11);
}

That's simple to implement:

int ordinal_date(int day, int month, bool leap_year) {
  return day;
}

Going to a slightly more complex case, days in February:

void ordinal_date_in_february_should_be_day_number_plus_days_in_january() {
  check(ordinal_date( 1, 2, false) == 32);
  check(ordinal_date( 1, 2,  true) == 32);
  check(ordinal_date(11, 2, false) == 42);
  check(ordinal_date(11, 2,  true) == 42);
}

Well, KISS:

int ordinal_date(int day, int month, bool leap_year) {
  if (month == 1) {
    return day;
  }
  if (month == 2) {
    return day + 31;
  }
  return -1; // Fall-through, always code defensively
}

Fine, tests pass again.  Time for new tests.  Check against known values:

void ordinal_date_should_match_known_values_for_non_leap_year_march_to_dezember() {
  check(ordinal_date( 1,  3, false) == ( 59 + 1));
  check(ordinal_date( 1,  4, false) == ( 90 + 1));
  check(ordinal_date( 1,  5, false) == (120 + 1));
  check(ordinal_date( 1,  6, false) == (151 + 1));
  check(ordinal_date( 1,  7, false) == (181 + 1));
  check(ordinal_date( 1,  8, false) == (212 + 1));
  check(ordinal_date( 1,  9, false) == (243 + 1));
  check(ordinal_date( 1, 10, false) == (273 + 1));
  check(ordinal_date( 1, 11, false) == (304 + 1));
  check(ordinal_date( 1, 12, false) == (334 + 1));
}

Ok, we can go on with these if .. but this starts to look like a lookup table to me, so better implement that instead:

int ordinal_date(int day, int month, bool leap_year) {
  static const int days_up_to_month[] = {
    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  return days_up_to_month[month - 1] + day;
}

Note that we can make this change with confidence of not breaking existing requirements due to the previous tests we wrote.

Finally, let's include the known values for a leap year:

void ordinal_date_should_match_known_values_for_leap_year_march_to_dezember() {
  check(ordinal_date( 1,  3, true) == ( 60 + 1));
  check(ordinal_date( 1,  4, true) == ( 91 + 1));
  check(ordinal_date( 1,  5, true) == (121 + 1));
  check(ordinal_date( 1,  6, true) == (152 + 1));
  check(ordinal_date( 1,  7, true) == (182 + 1));
  check(ordinal_date( 1,  8, true) == (213 + 1));
  check(ordinal_date( 1,  9, true) == (244 + 1));
  check(ordinal_date( 1, 10, true) == (274 + 1));
  check(ordinal_date( 1, 11, true) == (305 + 1));
  check(ordinal_date( 1, 12, true) == (335 + 1));
}

Of course this fails spectacularly, but is easily fixed with some "domain knowledge" (namely that in a leap year February is a day longer):

int ordinal_date(int day, int month, bool leap_year) {
  static const int days_up_to_month[] = {
    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  return days_up_to_month[month - 1] + day
         + ((leap_year && (month > 2)) ? 1 : 0);
}

Note that our tests would have revealed this domain knowledge, too.  Try the code without the month > 2 condition and see which tests fail.

Finally: Tests pass.  Fine.  I hope this is of potential use for you.

(Ideone link with above code)

That 2 is a naked magic number, which is not good.  Better define a constant FEB or something like that.
You wrote that the code is tested with 65000 random values.  Sorry, but that's useless.  For this example, it will - of course (with very high probability) - spot any errors in the implementation as there are only 365 + 366 different inputs that the function might take.  But what it won't help with is clearly documenting the desired behavior.  Moreover, running your test will take a lot more time than running the simpler tests here.  That's not an issue for just one function, but within a mid size to large size project these run times will build up quickly.  And the longer the test, the less often you will run it!  The less often you run it, the more code you write without testing it.


Determining if an entity exists in a database via a stored procedure

I may be pointing out the obvious here, but the ValidateEntity Method returns a string. I would expect it to return a Boolean.
There are a number of one and two letter variable names. We've not been restricted in the size of names for many years now. It would be good to give them more descriptive names and we can take advantage of C#'s case sensitivity.

da = adapter
ds = dataSet (but perhaps something even more meaningful)
dt = table or resultNames

If you return a bool instead of a string, you could directly return here instead of using an if statement.

if (dt.Rows[0]["Valid"].ToString()=="Y") { return "True"; }

Becomes

return (dt.Rows[0]["Valid"].ToString() == "Y");


Use .exec to match a group
Add comma removed by slice directly into the regexp
Use capturing groups: query for [1], not for [0]

let script = document.getElementById('source').text;
var result = /item:(.*|[\s\S]*),\s*onSelected/gm.exec(script)[1];
console.log(JSON.parse(result));
<script id="source" type="text/plain">
jQuery(function($) {

        new Selector('itemSelect', {
          item: {"id":9343513159,"title":"The thing","description":"\u003cp\u003eThis is the description\u003c\/p\u003e\n\u003cp\u003eIt has details\u003c\/p\u003e\n","published_at":"2016-12-10T10:08:00-05:00","available":true,"individuals":[{"id":34972221767},{"id":34972221768},{"id":34972221769}],"images":["\/\/cdn.site.com\/s\/files\/1\/0094\/2252\/items\/image.jpg?v=1481382473"],"options":["Time"],"content":""},
          onSelected: selectCallback,
          enableState: true
        });

       // Some stuff here

        $('.main:eq(0)').prepend('<label class="forever" for="time">Forever</label>');

    });

    window.mainItem = window.mainItem || {};

    mainItem.variables = {
      available : false
    };

    (function() {
      if (true) {
        mainItem.variables.available = true;
      }
    })()
</script>


Shell script for reading /etc/passwd into SQLite

Just don't create that many subprocesses. Your objective is to prepare a string of INSERT statements and feed it to one invocation of sqlite3. So drop the whole while read block and do the required text manipulations on the queried passwd entries before passing them off to sqlite3:

#!/bin/sh
db='./users.db'
sqlite3 "$db" <<EOF
DROP TABLE Users;
CREATE TABLE Users \
    (UID INTEGER PRIMARY KEY, GID INTEGER, Username TEXT, Home TEXT);
$(getent passwd 'joe' 'bill' 'tom' | awk -F':' -v quote="'" -v OFS="', '" \
    '{print "INSERT INTO Users VALUES ("quote $3, $4, $1, $6 quote");"}')
EOF

Doing a grep on /etc/passwd has a few drawbacks: the passwd file might not be located in /etc (I don't know of any Unix-like OS for which this is true, though), and it won't have the users that are stored in LDAP/NIS, etc. On the other hand, some systems don't have getent, so this method is not perfect, either. You might want to fall back to grep if getent returns a "command not found".


Longest palindromic subsequence by memoization

The simplistic answer, possibly not the most efficient answer, is simply to build a tuple result of the length, and the string, and then memoize that one.

When trying with longer strings, it turns out that your version of the recursive version from the link is not complete. You didn't handle the len(s) == 2 case which led to index errors. With that fixed, and the tuple returns, the code now looks like:

def max_palindrome(s):
    """ Returns the longest length palindrome that can
        be generated from s

    >>> max_palindrome("BBABCBCAB")
    (7, "BACBCAB")[1] -> BACBCAB
    """

    @memoize
    def inner(s):

        if len(s) == 1:
            return 1, s

        if s[0] != s[-1]:
            _, recursed = max(inner(s[1:]), inner(s[:-1]))
            return len(recursed), recursed

        elif s[0] == s[-1]:

            if len(s) == 2:
                return 2, s
            else:
                new_text = '{0}{1}{0}'.format(s[0], inner(s[1:-1])[1])
                return len(new_text), new_text

    return inner(s)[1]

You could also improve your code by commenting a little more, and giving some proper names instead of single character variables, which are usually reserverd for loops.

Addendum: Faulty algorithm

The suggested algorithm from your link, doesn't explore all possibilities available. Neither lengthwise, nor is all combinations covered. The following two test cases prove they are faulty:

print max_palindrome("abcABCBAabc")  # (7, 'cABCBAc')
print max_palindrome("abcABCBAcba")  # (11, 'abcABCBAcba')

Both of these should return the latter, if all combinations had been considered. This simple test run was done without memoization, which could introduce other faults. Did also test with the same strings in the online code generator linked from your proposed link.

Not that your link also states that you can rebuild the characters any way you like, whilst a more normal version is that the palindrome string must be displayed within the string itself. I.e. your links says that in the string "BBABCBCAB", all of the following are palindromes: "BACBCAB", "BBCBB", and "BBBBB". Neither of these are substrings.

Wikipedia has the more normal definition of longest palindromic substring and here is a Stack Overflow answer with links to two implementations of Manacher's algorithm.