Show results of a runners' competition with details about each runner

for (int i = 0; i < a.length; ++i) {
        System.out.print("|"+a[i]+"|");
     }

This could be just

     for (String heading : a) {
         System.out.print("|" + heading + "|");
     }

You don't need an i variable.

        for(int j = 0; j < b[i].length; ++j) {
            System.out.print("|"+b[i][j]+"|");
        }
        System.out.println("\n-----------------------------");

This could be

        System.out.println(
            String.format("|%6d||%4d||%4d||%7d|\n-----------------------------",
            c[0], c[1], c[2], c[3]));

This allows you to get rid of b entirely.

You might point out that this hard codes c[0], etc.  But that's not nearly as big a deal as it might first seem.  The formats are specific for each one, so you have to write out those variables anyway.  The real solution would probably be a Runner class where you could say things like runner.getNumber() instead of c[0].  Because right now it's not clear why 0 means Runner.

      //int pm = position man, pw = position woman
      int pm = 0;
      int pw = 0;

If we replace that with

      final int SEX_COUNT = 2;
      int[] firstBySex = int[SEX_COUNT];

Then we can change

     //for to find the minimun time of man
     for ( int i = 0 ; i < 7 ; i++) {
        if ( c[i][1] == 1 ) {
            if ( c[i][3] < c[pm][3] ) {
                pm = i ;
            }
        //else to find the minimum of woman
        } else {
            if ( c[i][1] == 0 ) {
                if ( c[i][3] < c[pw][3] ) {
                    pw = i ;
                }
            }
        }//end else
    }//end for

with

    for (int runner = 0; runner < c.length; runner++) {
        int sex = c[runner][1];

        // [3] is the runner's time
        if (c[firstBySex[sex]][3] > c[runner][3]) {
            firstBySex[sex] = runner;
        }
    }

We no longer hard code the number of rows in c.  Now, if we change the number of rows in c, the code automatically handles it.

We don't have to handle males and females separately.  We use the same code for both.

The intermediate variable sex saves us from having to write a comment explaining what column 1 is.

    //for to print the winners
    for (int i = 0 ; i < 1 ; i++ ) {
        System.out.print("Runner num "+c[pm][0]
                +" with an age of "+c[pm][2]
                +" and time of "+c[pm][3]
                +" min is the male winner.");
        System.out.println("");

        System.out.print("Runner num "+c[pw][0]
                +" with an age of "+c[pw][2]
                +" and time of "+c[pw][3]
                +" min is the female winner.");
    }//end for

You could write this as

    for (int sex = 1; sex >= 0; sex--) {
        System.out.println(formatRunnerData(c[firstBySex][sex]]));
    }

with an array

public final String[] SEXES = { "female", "male" };

and a helper method

public static String formatRunnerData(int[] runnerData) {
     StringBuilder builder = new StringBuilder();

     builder.append("Runner num ").append(runnerData[0])
         .append(" with an age of ").append(runnerData[2])
         .append(" and time of ").append(runnerData[3])
         .append(" min is the ").append(SEXES[runnerData[1]).append(" winner.");

     return builder.toString();
}

Now if you make a change to this display, you can make it in one place rather than two.

Originally, you didn't need a for loop.  You only ran the code once.  This makes use of a loop.

This adds an extra end of line at the end, which I find better anyway.  So if you add more text, you don't have to put an end of line before it to print on a new line.

Other than that, this should produce the same display.


Jvector Map add/remove function shorten code

You are looking to remove the copy pasted code, to make it more DRY.

Beyond that, it seems that really whether you getID or removeGetID, you set a number of ID's and then update mapObject. Furthermore, it seems that you do not need to update mapObject within the loop, which is slow.

I would counter-propose

var helpfullyNamedConstant1 = '#3e9d01';
var helpfullyNamedConstant2 = '#128da7';

function setContinentCodes(continentId, continentCodesValue ){
    jQuery.each(mapObject.mapData.paths, function(i, val) {
            if (val.continent == continentId){
                continentCodes[i] = continentCodesValue ;
            }
    });
    mapObject.series.regions[0].setValues(continentCodes);
}

jQuery('.continentLink').hover(function(e) {
    setContinentCodes(this.id, helpfullyNamedConstant1);
}, function(){
    setContinentCodes(this.id, helpfullyNamedConstant2);
});


Drawing sets of boxes to display contents of arrays

Multiplies can be pretty expensive within loops, so I minimized the use of them by precalculating where possible. It is also better to have the Y loop before the X loop to prevent cache misses (which wouldn't matter on a really small array like this but is a good practice). Consider this alternative:

for(int y = 0; y < 3; y++)
{
  final int yy = y * size;

  for(int x = 0; x < 3; x++)
  {
    final int xx = x * size;

    if(pattern[x][y] == 1)
    {
      g.setColor(colorrange.colb());
      g.fillRect(actlo + xx, actlo + yy, size, size);
    }

    g.setColor(Color.yellow);
    g.drawRect(actlo + xx, actlo + yy, size, size);

    if(patternb[x][y] == 1)
    {
      g.setColor(colorrange.colb());
      g.fillRect(actlo + xx, inlo + yy, size, size);
    }

    g.setColor(Color.yellow);
    g.drawRect(actlo + xx, inlo + yy, size, size);
  }
}


This is not a Sieve of Eratosthenes for a few reasons.

Instead of just throwing a real one at you, lets see how we can deduce a Sieve of Eratosthenes just by improving the current code.

The first thing to note is that we can clean up the recursive function be removing the return; you're only returning the list they already have.

Secondly, you can remove the else and remove the last if by making the first check stricter. That gives:

def filter_multiples(lst, n, counter):
    ''' A recursive method used to remove multiples of n in a list(lst)
        and using a counter to iterate through that list
    '''
    if len(lst) <= counter:
        return

    # See if a number in a list is divisble by n and if so, remove it
    if lst[counter] % n == 0 and lst[counter] != n:
        lst.remove(lst[counter])

    filter_multiples(lst, n, counter+1)

You then find that the recursive function is easier as a loop:

def filter_multiples(lst, n, counter):
    while counter < len(lst):
        # See if a number in a list is divisble by n and if so, remove it
        if lst[counter] % n == 0 and lst[counter] != n:
            lst.remove(lst[counter])

        counter += 1

If this insistence to use an imperative style makes you confused about what the point of recursion is, let me assure you there are uses. Traversing tree data structures is traditionally done recursively. Here's some example of that. It's not, however, good to use recursion for the sake of it unless using a language specifically designed to do so.

This uses remove repeatedly to filter elements. remove is O(n) so the overall time for this is O(n²). You know this can't be a Sieve of Eratosthenes because the whole sieve is meant to be O(n log n)!

One way to improve this is to use a list comprehension:

def filter_multiples(lst, n):
    lst[:] = [i for i in lst if i == n or i % n]

which, you might think, is then better just using return:

def filter_multiples(lst, n):
    return [i for i in lst if i == n or i % n]

However, the outer loop

for i in odd_nums:
    filter_multiples(odd_nums, i)

would be changed to

for i in odd_nums:
    odd_nums = filter_multiples(odd_nums, i)

and this means the for i in odd_nums would be iterating over the old odd_nums. Thus, this needs to be in place with how you've made it. However, modifying the number of elements in lists while you're iterating over them is heavily discouraged. This means that maybe we should think of a different technique for filter_multiples.

One such technique is marking all of the elements to remove and then doing a list comprehension:

for i, val in enumerate(lst):
    if not (val == n or val % n):
        lst[i] = None

lst[:] = [val for val in lst if val is not None]

The advantage of this is that we can hoist the final comprehension outside of the two loops and just skip None in the outer loop:

def filter_multiples(lst, n):
    for i, val in enumerate(lst):
        if val is None:
            continue

        if not (val == n or val % n):
            lst[i] = None

# Cycle through the numbers and use filter_multiples to remove the factors and keep the primes
for val in odd_nums:
    if val is not None:
        filter_multiples(odd_nums, val)

odd_nums = [val for val in odd_nums if val is not None]

This seems more complicated, true, and it's probably also slower than the comprehension because it's looping over more numbers. However, think about this check:

if not (val == n or val % n):
    lst[i] = None

Since we're not compressing lst, val will directly map to a given i (or None). As such, if we work out that mapping we can avoid the check by just going over all the i that map to {2n, 3n, 4n, ...}.

One way of doing that is just making val map to i:

sieve = range(100)
sieve[0] = sieve[1] = None

def filter_multiples(lst, n):
    for i in range(2*n, len(lst), n):
        if lst[i] is None:
            continue

        lst[i] = None

# Cycle through the numbers and use filter_multiples to remove the factors and keep the primes
for val in sieve:
    if val is not None:
        filter_multiples(sieve, val)

sieve = [val for val in sieve if val is not None]

print sieve

In fact, the if is no longer needed inside this loop and we can do:

def filter_multiples(lst, n):
    for i in range(2*n, len(lst), n):
        lst[i] = None

Then you'd probably want to tidy up the code by putting it in a function:

def mask_indicies(lst, start, step):
    for i in range(start, len(lst), step):
        lst[i] = None

def primes_below(maximum):
    sieve = list(range(maximum))
    sieve[0] = sieve[1] = None

    for val in sieve:
        if val is not None:
            mask_indicies(sieve, 2*val, val)

    return [val for val in sieve if val is not None]

if __name__ == "__main__":
    print(primes_below(100))

That is a Sieve of Eratosthenes. I've added Python 3 compatibility.

Note that I have previously talked about doing similar things really fast, first with a Sieve of Sundaram and then comparing it to a Sieve of Eratosthenes (Eratosthenes won).


If there is more than one way to construct an instance, then static factory methods backed by one private constructor, can really help readability, since they can be named differently.

Range halfOpen = Range.largerThan(5);
Range closed = Range.between(7, 12);

If it is really about setting some properties and not others, then the Builder pattern can be what you want.

Person john = Person.named("John")
    .lastName("Lennon")
    .gender(Male)
    .yearOfBirth(1940)
    .build();

Both of these approaches also allow for hiding which implementation class is really returned. Our Person instance may be an instance of subclass Man, and the half open Range may be an instance of HalfOpenRange. Both methods allow returning a cached instance, rather than an actual new instance.


One thing I recommend is to use a "scale factor" (I'm making names, there might be an official name for this approach) - a unit-less value that you multiply to time-sensitive values to compensate for frame rate differences. One perk when doing it this way is you don't have to write time sorcery in your equations (which is everywhere usually). You write them as is and just multiply this value to the result.

The formula is scale = delta / 16.6 where 16.6 is the frame time for 60fps. But this may differ per device, so you might need to find out the device refresh rate first and adjust this accordingly. According to MDN:

  The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.
  https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

Here's an example calculation with a box that should move 60 units at 60fps. At 60fps, it moves an intended 60 units. But if the frame rate drops to 40fps, it should not move 40 units. Scale factor compensates for that by scaling up the calculated value.

// At 60fps, a frame takes 16.6ms
const delta = 16.6;
const scale = delta / 16.6; // 1
const boxMoved = 60; // your logic at 60fps calculates 60 units
const officialBoxMoved = boxMoved * scale; // 60

// At 40fps, a frame takes 25ms
const delta = 25;
const scale = delta / 16.6; // 1.5
const boxMoved = 40; // your logic at 40fps calculates 40 units
const officialBoxMoved = boxMoved * scale; // 60

Your code would look like:

let lastTime = performance.now();

(function gameLoop(currentTime){
  requestAnimationFrame(gameLoop);

  const scale = (currentTime - lastTime) / (100 / 6);
  lastTime = currentTime;

  gameLogic(scale);
  gameDraw();

}());

In terms of the code you just posted, there isn't much of a difference. But where the difference will be is in how you write your game logic using this value.


You are beginning to mix up the business logic with the user interface. You should (be able to) design a "game driver" class without regard to user interface. You want to keep your GUI code separate from your game logic code. And another OO paradigm is to create new objects separately and pass them into where they are used.

I see a Game class ( "Dealer" might be a better name) that handles the cards, deals them to players, etc. Then your ScoreTable class wires-up it's buttons to the Game methods. For example a "Deal" button's click event handler might be Game.DealCards().

pseudo code for the idea:

  Player me = new Computer();
  Player you = new Human();
  Game aNewGame = new Game (me, you);
    // I'm imagining that the game creates the card deck internally
  ScoreTable theCasino = new ScoreTable(aNewGame);

  // inside ScoreTable constructor...
  DealButton.onClick += aNewGame.DealCard();

Suggestions

Classes and their interaction reflect real life. Write code that way. I.E. A "Dealer" deals "Card"s from a "CardDeck" to "Player"s. (Now I really like "Dealer" better than "Game" as a class name). Therefore the Game must have (references to the) Players, so we pass player objects into the Game constructor.
Think in terms of the ScoreTable only displaying the game, NOT actually playing the game. The Game class plays the game. Thus the ScoreTable must interact/communicate with Game to display what's going on.
Think of ScoreTable as telling Game what to do and Game does it. For example you click "Hit Me" (ScoreTable) and that fires the Game.DealCard() method.
BlackJackTable sounds better to me than ScoreTable for that class name.

  Can i have a ScoreTable class which implements Player and a stand alone Button class?

Do not do this. Think in real-life terms to keep things straight. A ScoreTable is a Player? That does not make sense. A ScoreTable has to display stuff on the screen so it is (inherits from) a Window - whatever the appropriate class is in Java.

  What kind of classes should i have?

I see a ScoreBoard class. Your diagram inspired the thought. The diagram directly suggests the class would have an array (of hands) each element of which holds the final score for both players.  This data structure, then, maps clearly to your UI concept. I see it as a separate class because it keeps score for both players, so it is inappropriate to be inside the (individual) Player class. A Player might have his score (hand) for the current game, but not past games, and certainly not the past games of a different player.

*Your Other classes *

Card
Deck - it's an stack of cards, it is not a card. And I mean "stack" in the way it behaves.
Human - a Player that is stupid (we're going to click buttons to tell her what to do).
Computer - a Player that knows by itself when to hold 'em and when to fold 'em
Game - the dealer essentially. Shuffles and deals cards.
ScoreTable - displays what's going on. "Controls" the Game via button clicking, etc.
ScoreCard - keeps history of past game results.


I think that one of the collections you iterate already has all the data you need. Try this:

$linkQuery = $xpath->query("//div[@class='news-archive']//a");
foreach ($linkQuery as $link) {
    $data[] = array('link' => $link->getAttribute('href'), 'title' => $link->nodeValue);
}

Btw. array_map() is another way for traversing two (or more) arrays simultaneously:

$group_elements = function($link, $title) {
    return array('link' => $link->value, 'title' => $title->nodeValue);
};
$data = array_map($group_elements, $linkQuery, $titleQuery);


Must reset timeout
select() is allowed to modify your timeout value.  So for your program, what happens is that the first call to select() takes 0.1 seconds because of the timeout, but the timeout is then reduced to 0.  The next 99999 calls to select() have a zero timeout.  You should reset the timeout right before you call select(), like this:
timeout.tv_sec = 0;
timeout.tv_usec = 100000;
select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);

Once you do that, you no longer need 100000 iterations, because each iteration will have the proper 0.1 second timeout instead of returning "immediately".


why not use the toWcharArray?

BSTR ExcelClass::qstringToBstr(const QString &qstring) const
{
        WCHAR* const pBuffer = new WCHAR[qstring.size()+1]; //large enough to hold the string plus null terminator
        qstring.toWCharArray(pBuffer);
        pBuffer[qstring.size()]=0;//terminate with 0
        BSTR result = SysAllocString(pBuffer);
        delete [] pBuffer;
        return result;
}

or simply preallocate result with SysAllocStringLen(&result, qstring.length()); and translate into that

BSTR ExcelClass::qstringToBstr(const QString &qstring) const
{
        BSTR result= SysAllocStringLen(0, qstring.length());
        qstring.toWCharArray(result);
        return result;
}


Check that elements in list follow a specified date-format schema and are not null/na/nan

One of my friends on Discord helped me out. He didn't like me attempt either! =oP
I created this function:
import datetime

def str2date(string):
   try:
       datetime_holder = datetime.datetime.strptime(string, "%Y-%m-%d")
       return datetime_holder.date()
   except ValueError:
       return string
   except TypeError:
       return string

And looped over it like this:
def datetime_check_format(col):
tracker = []
false_dates = []
true_dates = []
counter = -1
for element in col:
    counter +=1
    if isinstance(str2date(element), date):
        true_dates.append(str2date(element))
    else:
        tracker.append(counter)
        false_dates.append(str2date(element))

return tracker, false_dates, true_dates


Followup: How do I optimize this Java cube root function for BigInteger?

I think your final solution is on the right path.

Just to be clear, I'm assuming you want the integral part of the cube root, i.e. for a given \$n\$, cbrt(n) will return the integer \$m\$ such that \$m^3 \leq n < (m + 1)^3\$. I'm also assuming you only care about positive inputs.

Here is the code I posted in a comment on the previous question, with an improved initial estimate. Inspired by There are Only Four Billion Floats -- So Test Them All!, I have tested it successfully on all integers in the range [1, Integer.MAX_VALUE) (took about 40m, by the way).

private static final BigInteger THREE = BigInteger.valueOf(3);

private static BigInteger cubeRoot(BigInteger n) {
    // Using Newton's method, we approximate the cube root
    // of n by the sequence:
    // x_{i + 1} = \frac{1}{3} \left( \frac{n}{x_i^2} + 2 x_i \right).
    // See http://en.wikipedia.org/wiki/Cube_root#Numerical_methods.
    //
    // Implementation based on Section 1.7.1 of
    // "A Course in Computational Algebraic Number Theory"
    // by Henri Cohen.
    BigInteger x = BigInteger.ZERO.setBit(n.bitLength() / 3 + 1);
    while (true) {
        BigInteger y = x.shiftLeft(1).add(n.divide(x.multiply(x))).divide(THREE);
        if (y.compareTo(x) >= 0) {
            break;
        }

        x = y;
    }

    return x;
}

The test code:

for (int i = 1; i < Integer.MAX_VALUE; i++) {
    // Report progress.
    if (i % 1000000 == 0) {
        System.out.printf("%d%n", i);
    }

    BigInteger n = BigInteger.valueOf(i);
    BigInteger m = cubeRoot(n);

    BigInteger lower = m.pow(3);
    BigInteger upper = m.add(BigInteger.ONE).pow(3);

    if (lower.compareTo(n) <= 0 && n.compareTo(upper) < 0) {
        continue;
    }

    System.err.printf("Error for input %s: Got %s%n", n, m);
    System.err.printf("Expected m^3 <= %s < (m + 1)^3%n", n);
    System.err.printf("But m^3 = %s, (m + 1)^3 = %s%n", lower, upper);
}


My attempt at an immutable container view in C++

Your view isn't immutable, though immutability might be a property of the underlying object. It's a constant view, meaning the underlying object might change, but not from that view. The canonical way to get a constant view is by the way to use a constant reference, unless the view should erase some of the differences between underlying containers, like std::string_view does.

You are missing .begin(), .end(), .rbegin() and .rend().
Your view is constant, fine, but forcing everyone to explicitly say so for each function-call breaks interface conventions.
The missing functions are the common interface, the ones you provided just optional convenience-functions for calling manually which might not be provided even if possible, and certainly never used in generic code. Take a look at <iterator> and the free functions for accessing any generic range there.


C++ choose between runtime and compile time implementation functions

As of C++20, you can use std::is_constant_evaluated(), which is more portable and considerably easier to read.  I realize you have only tagged C++17, but I just wanted to point out that there is now a cleaner solution to this problem.
#include <type_traits>
#include <cmath>

namespace example
{
    namespace impl
    {
        template<typename T>
        constexpr auto sqrt(const T& m) noexcept -> decltype(std::sqrt(m)) {
            // implementation details
        }
    }

    template<typename T>
    constexpr auto sqrt(const T& m) noexcept {
        if (std::is_constant_evaluated())
            return impl::sqrt(m);
        else
            return std::sqrt(m);
    }
}


I have tried make a more optimized version here which also will work for string of any sizes and any number of words:
void main() {
  print(setSearchParam("Dr apj abdul Kalam"));
  // [D, Dr, a, ap, apj, a, ab, abd, abdu, abdul, K, Ka, Kal, Kala, Kalam]

  print(searchParamWord('test'));
}

List<String> setSearchParam(String caseNumber) =>
    caseNumber.split(' ').expand(searchParamWord).toList();

Iterable<String> searchParamWord(String word) sync* {
  final sb = StringBuffer();

  for (var i = 0; i < word.length; i++) {
    yield (sb..writeCharCode(word.codeUnitAt(i))).toString();
  }
}

I have split the logic of your code into two parts.
searchParamWord takes one word and split it into its components like "(t, te, tes, test)" and returns a lazy evaluated iterator. This iterator can then later be used by expand in setSearchParam where we split the long String into each separate word.
By request, example how to upper case first letter in each word
void main() {
  print(setSearchParam("Dr apj abdul Kalam"));
  // [D, Dr, A, Ap, Apj, A, Ab, Abd, Abdu, Abdul, K, Ka, Kal, Kala, Kalam]

  print(searchParamWord('test'));
}

List<String> setSearchParam(String caseNumber) =>
    caseNumber.split(' ').expand(searchParamWord).toList();

Iterable<String> searchParamWord(String word) sync* {
  final sb = StringBuffer();

  for (var i = 0; i < word.length; i++) {
    yield (i == 0)
        ? (sb..write(word[i].toUpperCase())).toString()
        : (sb..writeCharCode(word.codeUnitAt(i))).toString();
  }
}


Efficient solution to Project Euler 14 (Longest Collatz sequence)

n must be 0, 1, 2 ...

Should be:

n must be 1, 2, 3 ...

Or say that:

n must be a positive integer.

Your code doesn't give an infinite loop, but it doesn't make sense really that you return [0] for your function. If you "allowed" 0 the collatz funciton would return an infinite list of 0s. (Why?)


Writing to an HttpURLConnection in a loop

In my opinion the key way to improve this code is decomposition. Actually, methods with more than 15 java lines are usually smells for me. So

//There should be other signature depending on what does this method actually do
public static String foo(Path path) throws InterruptedException, IOException {
    final StringBuffer messagebuffer = new StringBuffer();
    final byte[] buf = new byte[64 * 1024];
    InputStream in = null;
    try {
        in = Files.newInputStream(path);
        int bytesRead;
        int i = 0;
        while ((bytesRead = in.read(buf)) != -1) {
            dealWithConnection(bytesRead, messagebuffer, buf, i);
            i++;
            Thread.sleep(16);
        }
    } finally {
        closeQuietly(in);
    }
    return messagebuffer.toString();
}

private static void dealWithConnection(int bytesRead, StringBuffer messagebuffer, byte[] buf, int i) throws IOException {
    final URL u = new URL(defaultURL);
    HttpURLConnection huc = null;
    try {
        huc = (HttpURLConnection) u.openConnection();// wrong
        init(huc, i);
        send(huc, buf, bytesRead);
        fillData(huc.getInputStream(), huc.getContentLength(), messagebuffer);
        fillResultInfo(huc, messagebuffer);
    } finally {
        if (huc != null) huc.disconnect();
    }
}

private static void send(HttpURLConnection huc, byte[] buf, int bytesRead) throws IOException {
    OutputStream os = null;
    try {
        os = huc.getOutputStream(); // wrong
        os.write(buf, 0, bytesRead);
        os.flush();
    } finally {
        closeQuietly(os);
    }
}

private static void fillResultInfo(HttpURLConnection huc, StringBuffer messagebuffer) throws IOException {
    int statusCode = huc.getResponseCode();
    String message = huc.getResponseMessage();
    messagebuffer.append("status code=").append(statusCode).append("\n");   //Don't use concatenation when you can append
    messagebuffer.append("response message=" + message + "\n");
}

private static void fillData(InputStream inputStream, int contentLength, StringBuffer messagebuffer) throws IOException {
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(inputStream); // wrong

        //if (contentLength != -1) {    //we don't need this check actually
        int ch;
        for (int k = 0; k < contentLength; k++)
            if ((ch = dis.read()) != -1)
                messagebuffer.append((char) ch);
            else {
                // if the content-length is not available
                while ((ch = dis.read()) != -1)
                    messagebuffer.append((char) ch);
            }
    } finally {
        closeQuietly(dis);
    }
}

private static void init(HttpURLConnection huc, int i) throws ProtocolException {
    huc.setRequestMethod("POST");
    huc.setRequestProperty("chunk-number", i + "");
    huc.setDoOutput(true);
    huc.setDoInput(true); // wrong
}

If you haven't closeQuietly() in your libs, it can be implemented like

private static void closeQuietly(Closeable closeable) {
    if (closeable == null) return;
    try {
        closeable.close();
    } catch (IOException ignored) {
    }
}

It's not so easy task to figure out what does this code do. So further improvement can be easily done. Personally I would start from variables names.

BTW, comments like if the content-length is not available is good signal that there should be some method/variable for this to make code be self documented.


Controller for handling user registration

There are many ways you can refactor this method but since you are using Laravel things are pretty easy. Here is my attempt on refactoring (I'd rather call it re-writing) this method.

First of all, this controller is overloaded with so many responsibilities, a controllers sole job should only be to accept an HTTP Request, defer the execution to responsible object and deliver an HTTP Response, that is all a controller need to do. so lets refactor it first.

Defer execution to service class

I'd create a service class with name AccountService and inject it into AccountController (or whatever you call it in your case), then on AccountService I'd create a method named

createNewAcocunt($firstName, $lastName, $email, $password)

which will validate the data and create new account.

Take care of responsibilities

The else part of controller method store() defeats the purpose of REST thingy, I'd just issue a redirect to login page with an appropriate message instead of trying to log them in. all of login stuff and account activation status checking should be performed over login route so it clearly does not belongs to the account creator (or signup) route. with these 2 things in place the controller method store() would look like this

public function store()
{
    $details = Input::only('firstName', 'lastName', 'email', 'password');
    try {
        $user = $this->accountService->createNewAccount($details['firstName'], $details['lastName'], $details['email'], $details['password']);
        Auth::login($user->id);
        return Redirect::route('admin.dashboard');
    } catch (ValidationException $validationEx) {
        return Redirect::back()->withError($validationEx->getErrors()); // assuming you set errors on exception object before throwing it
    }
}

Now over to the AccountService class.
The method createNewAcocunt($firstName, $lastName, $email, $password), by its name, should create an account with data fed to it. In case there is an error it should throw an exception.

Take advantage of events as they happen

Now, you need to take care of responsibilities once again, do not overload this method with mail sending, user login or stuff like that, the only responsibility of this method is to create an account. To handle the mail sending and other tasks you need to perform after creating an account you can use laravel's EventDispatcher class or Event facade (Documentation here).
My method would look like this

public function createNewAcocunt($firstName, $lastName, $email, $password)
{
    $validation = $this->accountValidator->validate(
            compact('firstName', 'lastName', 'email', 'password')
    );

    if($validation->fails())
    {
        $up = new ValidationException('Invalid data for new account');

        // set error messages on exception to communicate them to upper layer
        $up->setErrors($validation->errors);
        throw $up;
    }

    $token = str_random(60)

    // if you use a repository then
    $user = $this->repository->createNewAccount($firstName, $lastName, $email, $password, $token);
    // or do it in whatever way you prefer

    // Now that the user is created fire suitable event
    Event::fire('account.created', [$user]);

    return $user;
}

Most of it has already sorted out, now you can catch the event account.created and perform whatever action you want.
My advice for sending out emails would be to queue emails instead of sending them in real time, this will decrease the response time since the codes will no longer poll for email to be dispatched

Mail::queue('emails.auth.email_confirmation', $data, function ($message) use ($mail_subject)
{
    $message->to(Input::get('email'))->subject($mail_subject);
});

read more about email queue here

and at last, you can customize the validation error message for email:unique rule and make that include a link to login page. check out the custom error message section over here. basically you can just pass in an associative array to Validator like this:

$messages = [
    'email.unique' => 'Looks like you already have an account, please Log in here'
];

$validation = Validator::make($data, $rules, $messages);
$validation->errors->get('email'); // should display the message as defined above

I hope this will give you at least an idea to get started with. I, for one, am really happy about your decision to go pro.


I'll not address the security analysis; I'll assume you've done threat modelling and are happy with the overall approach.

Instead of a chain of if/elif all testing the same variable, the natural approach is a switch.  I'll also take advantage of ${:-} to default the argument:

case "${1:-d}" in
    d)
        # Decrypt
        # (commands)
        ;;
    e)
        # Encrypt
        # (commands)
        ;;
    i)
        # Initialize
        # (commands)
        ;;
    *)
        # invalid
        exec >&2
        echo "Usage: $0 [option]"
        echo "Options:"
        echo "  d - decrypt [default]"
        echo "  e - encrypt"
        echo "  i - initialize"
        exit 1
        ;;
esac

Note that I've sent the error message to error output (&2) and exited with an error code.  Actually, this should really be return 1 since it's a function rather than a complete script.

In the decrypt code, you use pushd and popd.  These are suited to interactive use, but are best left alone in scripts or functions (that's why you discovered that you need to redirect their output).  Instead, you can use a sub-shell:

(cd ~; commands... )

or use full paths.  In this case, we want tar to output to ~, and we can tell it to do so, using its -C option:

openssl -in ~/.kruptos.tar.gz.aes | tar -C ~ -xz -f -

Finally, you can avoid duplication by putting paths that are used more than once into variables.  This protects you against mis-typing any of them, and makes it easier if you should ever want to change them.

Modified code

Here's what I have, after applying the above changes:

function kruptos
{
    local dir=~/.kruptos
    local file=~/.kruptos.tar.gz.aes
    local keyfile="$dir/.phrazein"

    case "${1:-d}" in
        d)
            # Decrypt
            openssl aes-256-cbc -d  -in  \
                | tar -C "$dir" xfz - \
                && rm "$file"
            ;;
        e)
            # Encrypt
            tar -C "$dir" cfz - . \
                | openssl aes-256-cbc -out "$file" -kfile "$keyfile" \
                && rm -r "$dir"
            ;;
        i)
            # Initialize
            mkdir "$dir"
            echo pswd >"$keyfile"
            ;;
        *)
            # invalid
            exec >&2
            echo "Usage: $0 [option]"
            echo "Options:"
            echo "  d - decrypt [default]"
            echo "  e - encrypt"
            echo "  i - initialize"
            return 1
            ;;
    esac
}


Dynamically changing available select options

This is a classic example of counting on the UI to keep track of state and model.

Because you know there are only 2 options, and you know how to go from one option to another, you simply hide and add options. Nowhere in your code is explicitly declared what durations are linked to which option.

If you dont care about that, you could optimize the code doing something like this:

$(document).ready(function() {
  var monthsDifference = $("#term option[value='48'], #term option[value='42']");

    $("input.radio-button-selector").change(function(){
        if ( $(this).val() == "opt2" ) {
            monthsDifference.hide();
        }
        else if ( $(this).val() == "opt1" ) {
            monthsDifference.show();
        }
        });
    });

I would advise you to care though, and have the code know what the months are and build selectors for each option. Something like this (untested):

$(document).ready(function() {
  var optionMonths = {
      opt1: [6,9,10,12,18,24,30,36,42,48],
      opt2: [6,9,10,12,18,24,30,36]
  }
  //Cache all options
  var $options =  $("#term option");

    $("input.radio-button-selector").change(function(){
        //Hide all options first
        $options.hide();
        //Then show relevant options
        showOptionMonths( optionMonths[ $(this).val()] );
    });
});

function showOptionMonths( months ){
    months.forEach( function( month ){
       $("#term option[value='" + month + "']").show();
    });
}

Of course, I would try to find a better name than opt1 or opt2, but I dont have enough knowledge of what you are trying to achieve to suggest something more meaningful.

Finally, you could cache the selectors for each option, I leave that as an exercise for the reader.


Buttons labelled with the number of times they have been clicked

Here are a few things I'd recommend changing:

There's no need to store the sum of a and b. You can always compute it in the view with a + b. This simplifies the update function a lot.
You can match Foo A and Foo B in update instead of a nested case.
Optionally, you can destructure model into {a, b} in view. I don't have any opinion on this. Either way is fine.

Here's the final elm-format'd code:

module Main exposing (..)

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)

main =
    Html.beginnerProgram { model = model, view = view, update = update }

type alias Model =
    { a : Int
    , b : Int
    }

model : Model
model =
    Model 0 0

type Msg
    = Add Foo

type Foo
    = A
    | B

view : Model -> Html Msg
view { a, b } =
    div []
        [ button [ onClick (Add A) ] [ text (toString a) ]
        , button [ onClick (Add B) ] [ text (toString b) ]
        , div [] [ text (toString (a + b)) ]
        ]

update : Msg -> Model -> Model
update msg model =
    case msg of
        Add A ->
            { model | a = model.a + 1 }

        Add B ->
            { model | b = model.b + 1 }

Live: https://ellie-app.com/c7GLFrXx3a1/0


Computing an approximate value of Pi via Monte Carlo method in Java with streams

You have some superfluous imports.  I also think that you can rename computeApproximateValueOfPi() to approximatePi() without losing any clarity.

The simulation is complicated by the fact that the circle is centered at an adjustable point (radius, radius).  You could just as easily use a unit circle centered at the origin, and generate points in a square with x in the range [0, 1) and y in the range [0, 1).  The computation is mathematically equivalent, with less shifting and scaling.

Furthermore, there is no need to instantiate a Point2D for each generated point.  You can use .distance(x, y).  Better yet, avoid computing the square root by using .distanceSq(x, y).

The output routine in main() could be improved.  Your percentage variable doesn't actually store a percentage as its name suggests; the 100× happens in the formatting instead.  Splitting up the formatting into several System.out.print() calls defeats the purpose of String.format().  I'd combine them all into one System.out.format() call.  Finally, the "percentage from" wording implies that you are calculating the difference; the calculation that you actually performed is what I would call "percentage of".

import java.awt.geom.Point2D;
import java.util.Objects;
import java.util.Random;
import java.util.stream.IntStream;

public class MonteCarloPiComputer {
    /**
     * The random number generator.
     */
    private final Random random;

    public MonteCarloPiComputer(Random random) {
        this.random = Objects.requireNonNull(
            random,
            "The input random number generator is null."
        );
    }

    public MonteCarloPiComputer() {
        this(new Random());
    }

    /**
     * Computes an approximate value of Pi via a Monte Carlo method. The method
     * creates {@code samples} random points in the upper-right quadrant,
     * computes the fraction of all points within the radius from the origin
     * and multiplies it by {@code 4.0}.
     *
     * @param samples the number of points to create.
     * @return an approximate value of Pi.
     */
    public double approximatePi(int samples) {
        Random r = this.random;
        Point2D.Double origin = new Point2D.Double();
        long pointsWithinUnitArc = IntStream.range(0, samples)
             .filter(i -> origin.distanceSq(r.nextDouble(), r.nextDouble()) < 1)
             .count();
        return (4.0 * pointsWithinUnitArc) / samples;
    }

    public static void main(String[] args) {
        MonteCarloPiComputer computer = new MonteCarloPiComputer();

        for (int samples = 100_000; samples <= 1_000_000; samples += 100_000) {
            double approximation = computer.approximatePi(samples);
            double pctDiff = 100 * (approximation - Math.PI) / Math.PI;
            System.out.format("%7d: %10f, deviation from exact Pi: %+10f%%%n",
                samples,
                approximation,
                pctDiff
            );
        }
    }
}


str[strcspn(str, "\n")] = '\0'; is an overkill. fgets reads (at most) one string, that is there is at most one '\n' in the buffer, and strchr will return its position. Consider

    char * newline = strchr(str, '\n');
    if (!newline) {
        .... // handle input too long condition
    } else if (newline == str) {
        .... // handle empty input condition
    }
    *newline = '\0';
    break;

Notice that even newline = '\0' is redundant: '\n' is a whitespace.

Do not invent error messages. This is what strerror and perror are for. Also keep in mind that strtod may set errno to errors other than ERANGE (some implementations use EINVAL as well). Consider

    if (errno != 0) {
        perror("strtod");
    }


While OP seemed to find the comments useful, we're supposed to put this stuff in answers.  Seems about as sensible as Jeopardy's "put your response in the form of a question."  Still, that's the rule, so:

Why are you doing jmp merge_from_2? Where do you think the execution is going to go if you don't do that jmp?
And in copy2, why have 2 jumps, instead of just jnz merge_from_2?
Which brings us to jz copy1. In copy1, you are going to check if esi is zero. But you just checked that before the jz.  If there no way to get to copy1 with esi zero, then checking for zero there is redundant. And if you remove the test/jz, that just leaves jmp merge_from_1. Why have a jump to a jump?

And one more:

When you do dec edi or dec esi, the dec sets the flags.  You can do the conditional jump right there.  Since you are only decrementing one or the other, jumping back to a place where you test both again seems redundant.  If you check the results of the decrement, you don't need to do this.  Maybe move the begin_merge label down so you only do the 2 tests on entry.


Stored procedure to classify policies by sales date

I will try to cover several points:

1) Naming

Try to use homogeneous naming. Pascal/Camel case seem too be used most often, so stick to it. E.g. @Policy_ID should be @PolicyId, CoverageID should be CoverageId.

2) Improve readability of your declarations

Your table variables could be declared like this:

DECLARE @Coverages TABLE
(
   CID INT IDENTITY(1,1),
   CoverageID BIGINT NOT NULL
)

DECLARE @Units TABLE
(
   UID INT IDENTITY(1,1),
   CoverageID BIGINT NOT NULL,
   SalesClosing DATE
)

DECLARE @CoveragesOut TABLE
(
   CoverageID BIGINT NOT NULL,
   MultiFlag CHAR(1)
)

3) Put clauses on separate lines for better readability

First statements could be rewritten like this:

SET @Year =
   (
      SELECT p.Reins_Year
      FROM dbo.Policy p
      WHERE p.Policy_ID = @Policy_ID
   )

--INSERT ALL COVERAGE FOR THIS POLICY
INSERT INTO @Coverages (CoverageID)
SELECT Coverage_ID
FROM dbo.Coverages c
WHERE c.Policy_ID = @Policy_ID

4) Defensive set

If by any chance, the select for year returns more that one year, set statement will fail. You might consider assigning with SELECT and/or using TOP 1, just to be sure it does not fail (however, it may return an incorrect value).

SET @Year =
   (
      SELECT TOP 1 p.Reins_Year
      FROM dbo.Policy p
      WHERE p.Policy_ID = @Policy_ID
   )

5) Easier date arithmetic

You have a case for spring and fall that performs some ad-hoc computation, that can be simplified. Also, since @Year is computed before the cycle, all those boundaries can be precomputed. You did not specify SQL Server version, so I hope for the best (2012+):

 DECLARE @StartOfYear DATE = DATEFROMPARTS(@Year, 1, 1)
 DECLARE @EndOfApril DATE = DATEFROMPARTS(@Year, 4, 30)
 DECLARE @FirstOfMay DATE = DATEFROMPARTS(@Year, 5, 1)

so, that the "Spring" CASE would be something like this (reformatted for better readability):

WHEN u.SalesClosing BETWEEN @StartOfYear AND @EndOfApril
   OR u.SalesClosing >= @StartOfYear
   AND u.SalesClosing < @FirstOfMay
THEN 'S'

However, logic for the dates is unclear for me, even after reading operator precedence (AND takes precedence over OR and BETWEEN). It is strongly recommended to use parenthesis when using multiple operators with close precedence.

6) Set based logic

WHILE and other looping constructs are intruders in T-SQL language. They will usually behave (much) poorer than set based approaches. So, your WHILE can be converted into something this:

;WITH U_CTE AS (
    SELECT DISTINCT C.CoverageID, CAST(pu.Sales_Closing_Date AS DATE),
        COUNT(1) OVER (PARTITION BY C.CoverageId) AS Cnt
    FROM dbo.Policy_Units PU
        JOIN @Coverages C ON PU.Coverage_ID = C.CoverageID
)
INSERT INTO @CoveragesOut (CoverageID, MultiFlag)
SELECT DISTINCT
    u.CoverageID,
    CASE
        WHEN @Cnt = 1 THEN
            CASE
               WHEN -- spring logic
               WHEN -- autumn logic
        WHEN 2 THEN 'B'
    ELSE NULL
FROM U_CTE

Also, @Units table is not required anymore and the whole block is slimier.

7) Proper data types

CAST(pu.Sales_Closing_Date AS DATE) suggests that Sales_Closing_Date is not a DATE (maybe a DATETIME or VARCHAR). If possible, use the most appropriate data type to avoid explicit or implicit (silently occurring in queries) casts.

8) Comments

It's a matter of taste, but I like comments written as normal text, not using CAPS


Parsing a C++ function declaration with Perl 6 grammar

I'd expect to see many more tests of any program that addresses a problem as gnarly as parsing a C++ declaration.

Choosing a couple I've recently had cause to write (on Stack Overflow), I would immediately add

void (SENDER::*get_func())(double, double);

(from Passing pointers to member function as returned values to QObject::connect())
constexpr std::size_t len(const T(&)[length]);

(from Differentiate between array and pointer as function parameter)

Neither of these succeeded when I tried them.


Make HTML/Javascript Geolocation function more linear

Most native functions require callback instead of Promise because they support older browsers, so what you have to do is to pack the method in a Promise

function getLocation() {
    return new Promise(function(resolve, reject){
        navigator.geolocation.getCurrentPosition(
            function(position) { resolve(position); },
            function(error) { reject(error); }
        }
    });
}

Now are able to determine what should happen with the position and the error.

const response = getLocation()
    .then(position =>
        ( {"latitude": position.coords.latitude,
           "longitude": position.coords.longitude} ))
    .then(latLong => { unlock_request(latLong) },
          error => { get_location_denied(error[1]) });

You know that for this request that you want to get the latitude and longitude out of position so you just return a new object with longitude and latitude, the smart thing with promises is that is it a builder pattern, so can call then again and now the parameter will be what was returned in the last then, so all power is given to response rather than getLocation()


Calculating top position of elements based on their heights

If you sort your elements ascending by order, you can get rid of the nested loop and just keep a running sum as you loop through:

start: function () {
    // sort ascending by order
    this.data.sort(function (a, b) {
        if (b.order < a.order) {
            return 1;
        }
    });
    var len = this.data.length;
    var i = 0;
    var sum = 0;
    while (i < len) {
        var item = this.data[i];

        // the top of this element is the sum of all previous element's heights
        item.top = sum;

        // don't reset sum here, just keep adding to it
        sum += item.height;
        i++;
    }
    console.log('after', this.data);
}

I have also removed the re-sorting at the end of the function as it is no longer needed due to the initial sort being ascending.


letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",`
           "v", "w", "x", "y", "z"]

This method of writing the alphabet is very error prone. I would import string and use string.ascii_lowercase in place of letters. If you want to generate your own range of letters for whatever reason, I would write
letters = [chr(n) for n in range(ord('a'), ord('z') + 1)]

since there's then no danger of omitting or duplicating a letter.

password_length = 0
password_numbers = []
password_letters = []

These default values are never used. The defaults for password_numbers and password_letters don't make sense since those variables hold numbers. I would delete all three lines.

if not password_length_input.isnumeric():
    print(f"{password_length_input} is not a number, try again:")
    continue
else:
    password_length = int(password_length_input)
    print(f"Password length: {password_length}")

I would instead write
try:
    password_length = int(password_length_input)
except ValueError:
    print(f"{password_length_input} is not a number, try again:")
    continue
print(f"Password length: {password_length}")

while True:
    if password_numbers == password_length:
        ...
        break
    else:
        ...
        break

There is no sense in having a while loop here since you always break out of it on the first iteration.

range(0,password_numbers)

You can just write range(password_numbers).

password.append(random.randrange(0,9))

This will append a digit from 0 to 8 inclusive, never 9. If you want all ten digits you should write random.randrange(10). Or, perhaps better, use random.choice(string.digits).

password_string = ''.join([str(item) for item in password])

If you use string.digits then every element of password will be a character so you can simplify this to password_string = ''.join(password).


Hangman game, with the number of guesses depending on the word length

dropping you some small comments about the code you posted

The idea of splitting the code into smaller functions works, the first methods you have are 10 lines or less and is not hard to follow what they do. Would be interesting to go ahead and split some parts of hangman() into smaller pieces as well
The name of the variable for your application main loop can be a bit misleading, would suggest something different instead of no_of_guesses, you could think of a can_guess(counter) boolean function that checks a counter and returns if the counter reached zero
Another part that may be tricky to understand is if blank==random_word, could be easier to read if it was more verbose about what happens, like in if not has_more_characters_to_guess(random_word)
As a general advice, don't be shy to have longer function names. available_letters is preferred to any shorter name. fill_blank can be replaced with get_partial_word_guess which may be more legible and explain a bit more on the insights


The usual advice is "make meaningful variables". However, we know this algorithm (essentially a modification of that published by a young Gauß) and those variables don't have a simple meaning. (See Decoding Gauss Easter algorithm). We know b represents centuries, but even if you did find a word to describe what the variables represent, would using epact or even ageOfMoonOnJanFirst help to understand the algorithm? The variable represent stages of the algorithm. As Gauss wrote "It is not possible to present the full analysis that led to the algorithm".

So the usual cure of incomprehensible code - clear variables names - won't help much here.  What can we do for the poor person who has to maintain this code 6 months, or 6 years, later?  We can let them know where this algorithm comes from. This is easy enough. A comment referencing the source would allow someone seeing this to check that it is still doing what it is supposed to do.

Beyond adding this comment, the algorithm for calculating Easter is unlikely to be a bottleneck in any piece of software, so assuming that this algorithm is correct (proven and tested) I would leave it as is.


A fast and (Ideally) thread safe object pool in C

One small improvement would be to not acquire the lock in AEPoolPut until right before you access pool (i.e., clear out the fields in scratch before acquiring the lock).

There isn't really anything else I see that can change here that would help (all assuming the number of scratches required is more-or-less stable, so that AEPoolGet will quickly reach the point where it won't have to allocate any more scratches.  There are some tweaks that might be applicable if you continually grow the number of pools.

In code the threads that use this, you can implement some sort of thread local scratch caching mechanism, so that if a thread finishes using a scratch object it'll hang on to it locally and reuse it.  This will bypass all this code.  If there are too many of these "free" scratch objects, you can return the excess back to the pool.  Depending on your usage, you might only need to cache one scratch object.


Lint

str_tab, hm, and tab are all unused variables.

In br.readLine().toString(), the .toString() is superfluous, as br.readLine() already returns a string.

In main(), the for (int i = 0; i < T; i++) loop would be better as for (int i = 1; i <= T; i++) so that you can avoid the (i+1).

Instead of catch (Exception e) { e.printStackTrace(); }, you could just declare main(String[] args) throws Exception.  But what kind of exception?  The code would be clearer if you narrowed it down to throws IOException.  (It's also possible to get a NumberFormatException, but for a contest problem, I wouldn't bother handling it.)

Skeleton

I would use the following outline:

public class Password {

    public static class DistinctPasswordCounter {
        public DistinctPasswordCounter(Scanner in) {
            this.in = in;
            this.n = Integer.parseInt(in.nextLine());
            …
        }

        public int count() {
            while (this.n --> 0) {
                …
            }
            return …;
        }
    }

    public static void main(String[] args)
            throws FileNotFoundException, NoSuchElementException {
        try (Scanner in = new Scanner(new File("password.in"));
             PrintWriter out = new PrintWriter("password.out")) {
            int t = Integer.parseInt(in.nextLine());
            for (int i = 1; i <= t; i++) {
                DistinctPasswordCounter counter = new DistinctPasswordCounter(in);
                out.printf("Case %d: %d\n", i, counter.count());
            }
        }
    }
}

Notable improvements:

password.out would be a more logical filename for the output.
Use try-with-resources for AutoCloseable resources.
Using Scanner instead of BufferedReader would let you not have to deal with IOException.
Passing a Scanner instead of a List<String> lets each test case work on the fly as the input streams in.
solve() doesn't really "solve".  I'd pick a more descriptive name.  Here, I've instantiated an object to represent each test case.  (I think that a good solution requires more state than I would like to pack into a single function.)  If the challenge had not required the program to be named Password, I would have just used DistinctPasswordCounter as the name of the class, and eliminated the inner class.

Strategy

Your solve() compares each password with every previously seen password, which makes it O(N2).  It's not surprising that the solution is slow, considering that N is large (up to 105).

Consider a different strategy: when you encounter a password, also note all possible variants of it.  For example, if the password 31415 appears, then also register the variants 20304, 20306, 20324, 20326, etc.

How many variants would we be talking about?  Given an original password, such as 31415, there would be…

31415 itself
the ±1 variants:
$${2 \choose 4}{0 \choose 2}{3 \choose 5}{0 \choose 2}{4 \choose 6}$$
… of which there are 25: 20304, 20306, 20324, 20326, 20504, 20506, 20524, 20526, 22304, 22306, 22324, 22326, 22504, 22506, 22524, 22526, 40304, 40306, 40324, 40326, 40504, 40506, 40524, 40526, 42304, 42306, 42324, 42326, 42504, 42506, 42524, 42526.
the ±2 variants:
$${1 \choose 5}\left(3\right){2 \choose 6}\left(3\right){3 \choose 7}$$
… of which there are 23: 13233, 13237, 13633, 13637,  53233, 53237, 53633, 53637.
the ±3 variants:
$${0 \choose 6}\left(4\right){1 \choose 7}\left(4\right){2 \choose 8}$$
… of which there are 23: 04142, 04148, 04742, 04748, 64142, 64148, 64742, 64748.
the ±4 variants:
$$\left(7\right)\left(5\right){0 \choose 8}\left(5\right){1 \choose 9}$$
… of which there are 22: 75051, 75059, 75851, 75859.
the ±5 variants:
$$\left(8\right)\left(6\right)\left(9\right)\left(6\right)\left(0\right)$$
… of which there is 1: 86960.

In the worst case, a password like 44444 or 55555 would generate 1+32+32+32+32+1 = 130 entries.  If you stick them all in a HashSet with O(1) insertion and lookup time, then the solution would be O(130 N), which is much better than O(N2) for N ≫ 130.

In practice, there will probably be much fewer than 130 variants.  For example, 31415 has just 54 variants.  Passwords that are shorter or that have a wide distribution of digits would have fewer variants.  Passwords that are equivalent to another password would generate no variants at all.  (For large N, the proportion of passwords that are equivalent to an existing password should rise dramatically due to the Birthday Paradox.)

Suggested solution

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.HashSet;
import java.util.NoSuchElementException;

public class Password {

    public static class DistinctPasswordCounter {
        private final Scanner in;
        private final HashSet<String> seenPasswords;
        private int n, distinctCount;

        public DistinctPasswordCounter(Scanner in) {
            this.in = in;
            this.n = Integer.parseInt(in.nextLine());

            // 100 is a rough estimate of the number of variants
            // per password, based on (5 * Math.pow(2, maxLength)).
            // For very large n, it could probably be tuned lower
            // due to the Birthday Paradox.
            this.seenPasswords = new HashSet<>(100 * this.n);
        }

        public int count() {
            while (this.n --> 0) {
                String password = this.in.nextLine();
                if (this.seenPasswords.add(password)) {
                    // No variant of this password has been seen before
                    this.distinctCount++;
                    int variants = this.addVariants(password);
                    // System.err.printf("%3d variants of %s\n", variants + 1, password);
                }
            }
            return this.distinctCount;
        }

        private int addVariants(String password) {
            int diff = 0, variants = 0, v;
            while (0 < (v = this.addVariants(password, ++diff, 0))) {
                variants += v;
            }
            return variants;
        }

        private int addVariants(String password, int diff, int pos) {
            if (pos >= password.length()) {
                this.seenPasswords.add(password);
                return 1;
            }
            char c1 = (char)(password.charAt(pos) - diff),
                 c2 = (char)(password.charAt(pos) + diff);
            String head = password.substring(0, pos),
                   tail = password.substring(pos + 1);
            return (c1 < '0' ? 0 : this.addVariants(head + c1 + tail, diff, pos + 1)) +
                   (c2 > '9' ? 0 : this.addVariants(head + c2 + tail, diff, pos + 1));
        }
    }

    public static void main(String[] args)
            throws FileNotFoundException, NoSuchElementException {
        try (Scanner in = new Scanner(new File("password.in"));
             PrintWriter out = new PrintWriter("password.out")) {
            int t = Integer.parseInt(in.nextLine());
            for (int i = 1; i <= t; i++) {
                DistinctPasswordCounter counter = new DistinctPasswordCounter(in);
                out.printf("Case %d: %d\n", i, counter.count());
            }
        }
    }
}


Batch script to start the service in a gap of 10 min

This is a nice and simple script.  There's not a lot to mess up here.  Really, any embellishments to the script are personal preference, and the suggestions I or anyone else might offer are little more than opinion here.

Be that as it may, I do have a few suggestions.  As is my habit in all the other reviews I've offered thus far, I suggest a couple of general practice behavior changes.

Add setlocal to the top of every script you write.  This script uses a lot of variables.  After you exit, those variables are still hanging around, junking up your environment, potentially causing problems for other scripts that expect them not to be defined.  Adding setlocal just below @echo off will narrow the scope of those variables to this script, and the variables will be forgotten on exit (whether the script exits gracefully or not).  See this page for a more detailed explanation of why this is considered good practice.
Get into the habit whenever you set a variable to a string, to set "var=value" with the var + value pair enclosed in quotation marks.  One of these days you may need to capture special characters like & or |, or some XML or HTML to a variable.  If you set "var=<xml tags>" you don't have to worry about those special characters getting evaluated unintentionally.  Get this habit under your fingers now and you will spend much less time in the future debugging.

My script-specific suggestions may not be relevant, depending on your needs.  Really, your script is mostly fine already, and I hope you don't consider these suggestions as my being hyper-critical, or suggesting you're doing anything wrong.  Ultimately, you know what will work best for you.
Unless you have a specific reason for including it, consider removing the final line, timeout /t %timeout% /nobreak.  Does your script really need to pause for 10 minutes after executing its final action?
Since the service name is the same for all four servers, how about doing set "service=swiftalm", then sc \\%host1% start %service% with %service% in all four sc commands?  I see little reason to maintain four variables all with the same value.
If the context under which this script runs has admin privilege on the remote servers, sc is lovely for starting services remotely.  For future projects, if you ever find yourself needing to supply a username and password with the commands, wmic can perform the same task with different credentials.

set /P "user=Domain\Username? "
set /P "pass=Password? "
wmic /node:%host1% /user:%user% /password:%pass% service where 'name="%service%"' call startservice

If you wish, you can mask the input of %pass% with PowerShell (credit: Matt Williamson):

<NUL set /P "=Password? "
set "psCommand=powershell -command "$p=read-host -AsSecureString;^
$m=[System.Runtime.InteropServices.Marshal];$m::PtrToStringAuto($m::SecureStringToBSTR($p))""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set "pass=%%p"

You could condense your script quite a bit by adding a for /f loop to loop through your %hostN% variables.

Example:

@echo off
setlocal
set timeout=600
set "service=swiftalm"
set "host1=Server_IP1"
set "host2=Server_IP2"
set "host3=Server_IP3"
set "host4=Server_IP4"

for /f "tokens=2 delims==" %%I in ('set host') do (

    echo ******Starting the Digite service on %%~I*****.
    sc "\\%%~I" start %service%

    if not "%%~I"=="%host4%" timeout /t %timeout% /nobreak
)

...although, admittedly, that may not as instantly readable as your code above.  It's really a matter of personal preference.
Instead of making the workstation from which you run this script perform the waiting, you could initiate a one-time scheduled task on each server, making the server do the waiting.  Because this involves datetime math, it gets a little complicated.  I typically borrow from JScript when I need to do date math.

@if (@CodeSection == @Batch) @Then

:: begin batch portion

@echo off
setlocal
set "service=swiftalm"
set "host1=Server_IP1"
set "host2=Server_IP2"
set "host3=Server_IP3"
set "host4=Server_IP4"
set /a timeout=600, loop = 1

:loop
echo;
:: start first task immediately
if %loop% equ 1 (
    echo ******Starting the Digite service on host%loop%******
    sc "\\%host1%" start %service%
    set /a loop += 1
    goto loop
)
:: else schedule for later remotely

:: use JScript because cmd is horrible at date math.
:: JScript passes stDate=date and stTime=time back to batch.
for /f "delims=" %%I in ('cscript /nologo /e:Jscript "%~f0" %timeout% %loop%') do (
    set "%%I"
)

echo ******Scheduling the Digite service to start on host%loop%******
setlocal enabledelayedexpansion
schtasks /create /tn "Start %service%" /tr "cmd /c sc start %service%" /sc once /sd %stDate% /st %stTime% /s !host%loop%! /z
endlocal

:: If more hosts in the list, increment loop counter and go back
set /a loop += 1
if defined host%loop% goto loop

:: Runtime complete.
echo All tasks complete.  Press any key to exit.
>NUL pause
goto :EOF

@end
// end batch / begin JScript hybrid code

var seconds = WSH.Arguments(0) * WSH.Arguments(1) - WSH.Arguments(0),

future = new Date(new Date().getTime() + seconds * 1000),

z = function(num) { return num < 10 ? '0' + num : num },

MM = z(future.getMonth() + 1),
DD = z(future.getDate()),
YYYY = z(future.getFullYear()),

oSH = WSH.CreateObject('wscript.shell'),
localeDateFormat = oSH.RegRead('HKCU\\Control Panel\\International\\iDate'),
localeDateSeparator = oSH.RegRead('HKCU\\Control Panel\\International\\sDate'),
localeTimeSeparator = oSH.RegRead('HKCU\\Control Panel\\International\\sTime'),

/* note: the iDate registry value can contain the following values:
VALUE   MEANING
0       mm/dd/yy
1       dd/mm/yy
2       yy/mm/dd
*/

strDate = [

    [MM,DD,YYYY],
    [DD,MM,YYYY],
    [YYYY,MM,DD]

][localeDateFormat].join(localeDateSeparator),

strTime = z(future.getHours()) + localeTimeSeparator + z(future.getMinutes());

// feed calculated "stDate=date \n stTime=time" string back to batch
WSH.Echo('stDate=' + strDate + '\nstTime=' + strTime);

Even though that's much more complicated and much uglier than your original script, it should result in a nicer user experience.  Your script will run from start to finish in a matter of seconds, rather than 30+ minutes.

Update: The above script now gets the locale date format from the registry and formats the date appropriately.

Here's another method, employing PowerShell to perform the date / time math.  It's a little slower to execute, but significantly simpler.

@echo off
setlocal
set "service=swiftalm"
set "host1=Server_IP1"
set "host2=Server_IP2"
set "host3=Server_IP3"
set "host4=Server_IP4"
set /a timeout=600, loop = 1

:loop
echo;
:: start first task immediately
if %loop% equ 1 (
    echo ******Starting the Digite service on host%loop%******
    sc "\\%host1%" start %service%
    set /a loop += 1
    goto loop
)
:: else schedule for later remotely

:: use PowerShell because cmd is horrible at date math.
set /a i = timeout * loop - timeout
for /f "tokens=1*" %%I in ('powershell -command "(Get-Date).AddSeconds(%i%) -f 'HH:mm'"') do (
    set "d=%%I"
    set "t=%%J"
)

echo ******Scheduling the Digite service to start on host%loop%******
setlocal enabledelayedexpansion
schtasks /create /tn "Start %service%" /tr "cmd /c sc start %service%" /sc once /sd %d% /st %t% /s !host%loop%! /z
endlocal

:: If more hosts in the list, increment loop counter and go back
set /a loop += 1
if defined host%loop% goto loop

:: Runtime complete.
echo All tasks complete.  Press any key to exit.
>NUL pause
goto :EOF

Ultimately, the only items of real importance that I feel strongly ought to be addressed are items 1 and 3.  Everything else is just a matter of personal coding style and preference.  Nevertheless, I hope this information is useful, or at least interesting.


Constructing a cumulative distribution function from a histogram

Your problem starts here:

val cdfData: MutableMap<Int, Double> = mutableMapOf()

This is the data that you want to your CDF class, but anyone can make a mutable map anywhere and use it for tons of things. So this is what you want to hide. So put this inside a CDFBuilder

class CDFBuilder {
     private val cdfData: MutableMap = mutableMapOf<Int, Double>()

     fun withData(a: Int, b: Double): CDFBuilder {
          // verification and stuff
          cdfData[a] = b
          return this
     }
}

Now, the problem is to build the CDF class without letting anyone else do it, right? There are a few options here:

Make a copy of the cdfData public from the CDFBuilder and read it in the CDF constructor, passing a CDFBuilder to the constructor.

Or 2, make a private constructor on the CDF-class, allowing it to only be constructed from the builder:

class CDF private constructor(val map: SortedMap<Int, Double>) {

    class CDFBuilder {
        private val cdfData: MutableMap = mutableMapOf<Int, Double>()

        fun withData(a: Int, b: Double): CDFBuilder {
            // verification and stuff
            cdfData[a] = b
            return this
        }

        fun build(): CDF {
            return CDF(map.toSortedMap())
        }
    }
}


Parallelization of number factors using OpenMP

I see that OpenMP's rules will make things a little difficult here.  For instance, I won't be able to concisely set i to either 2 or 3, depending on integer's parity.  This is because OpenMP requires the loop counter to be set within the loop, though it can still be declared beforehand.  I would otherwise have to put a ternary within the loop statement, which would look ugly.  It could save one iteration, which may not make a huge difference.

As such, I might as well initialize i within the loop statement and then remove the private part from the preprocessor directive:

    shared(factors, integer)
for (std::int64_t i = 2; i <= integer; i++)

Performance-wise, I was able to get a small boost by initializing factors outside of the timed section and passing it to calcFactors().  Regardless of the time it usually takes to initialize an std::map, my runtime will always be limited by that as it's part of the serial code.

With the same division and modulus operations, I would likely not get any significant performance boost.  Regardless of the thread count, the number of modulus and division operations still vary, which may explain the poor scalability over time.  I also cannot test with higher thread counts due to my machine's limited number of available threads.


Sanitize file or folder names to work with a legacy system

I think you need separate some parts of code.

If you use ES5 with Decorators you can todo general determination Errors, and add for instance, function-condition in this Decorator.
You can apply mechanismes Extract Methods, Simplifying Conditional Expressions and Replace Magic Number with Symbolic Constant from sanitizeFolderOrFile.

/* Decorator file */
 function determinationError(condition) {
   return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value;
    descriptor.value = function () {
      try {
         condition.apply(this, arguments);
         method.apply(this, arguments);
      }
      catch(e) {
        console.error(e.message);
      }
    };
    return descriptor;
  };
}

//export determinationError;

/*enum MODE file */
 const MODE = {
     FILE: 'file',
     folder: 'folder'
  };

//export MODE;

/*file sanitizeFolderOrFile */

//determinationError = require('determinationError'); // require our decorator file
//MODE = require('MODE'); // require our MODE file

function isFileOrFolderCondition(mode) {
  if (mode !== MODE.FILE && mode !== MODE.FOLDER) {
    throw new Error('It is not file or folder') ;
  }
}

  const replaceValues = [{
        value: '+\\&',
        replacement: 'u'
    }, {
        value: 'äÄ',
        replacement: 'ae'
    }, {
        value: 'öÖ',
        replacement: 'oe'
    }, {
        value: 'üÜ',
        replacement: 'ue'
    }, {
        value: 'ß',
        replacement: 'ss'
    }, {
        value: ' \\`\\´\\?\\(\\)\\[\\]\\{\\}\\/\\\\$\\§\\"\\\'\\!\\=\\-\\.\\,\\;\\:<>\\|\\^\\°\\*\\+\\~\\%',
        replacement: '_'
    }];

function replacerAndToLowerCase(name) {
   replaceValues.forEach(function(element) {
        name = name.replace(new RegExp('([' + element.value + '])', 'g'), element.replacement);
    });

   return name.toLowerCase();
}

function sanitizeFile(fullName) {
   const ext = fullName.split('.').pop();
   let name = fullName.replace(new RegExp('(\.' + ext + ')', 'g'), '');
   name = replacerAndToLowerCase(name);

   return `${name}.${ext}`;
}

function sanitizeFolder(fullName) {
   return replacerAndToLowerCase(fullName);
}

//@determinationError(isFileOrFolderCondition)
function sanitize(mode, name) {
   if (mode === MODE.FILE) {
     return sanitizeFile(name);
   }

   return sanitizeFolder(name);
}

const fileName = sanitize(MODE.FILE, 'TeSäÄtTE.txt');
console.log('fileName', fileName);

const folderName = sanitize(MODE.FOLDER, 'SuperFolder???????');
console.log('folderName', folderName);

I added comment in Snippet when you can add Decorator and separate on files


define_method vs method_missing and CodeClimate scores

Notes:

I am afraid I'd propose a very boring solution: don't use meta-programming. I mean, why add methods and more methods, polluting the class, when you can add just one method and use symbols for the days? Add validations if you're worried about invalid values for days.
The usual trick of using powers of two as a mask is that, a trick, very handy in low-level languages (C, assembler, ...). In a higher-level language you strive for writing code as declarative as possible, with data structures like lists, hashes, trees, or sets, not masks of powers of 2 :-) Here I'd use a set.
I prefer functional solutions even with OOP, just return new instances instead of modifying the existing ones. Referential transparency, idempotence, all the goodies follow.

I'd write (orientative, you get the idea):

class WeekSauce
  DAY_NAMES = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday]

  def initialize(days)
    @days = days.to_set & DAY_NAMES
  end

  def has_day?(name)
    @days.include?(name)
  end

  def add_days(names)
    WeekSauce.new(@days.union(names))
  end
end


Conditional execution based on input string's prefix

I don't like too much the fact that you use a String as the returned type of your function.

What about using a class hierarchy or exceptions?

I see opportunities to create a hierarchy even for the messages. Why don't you create a BotMessage and a SkypeMessage?

Both should have the logic to decide what to do in the base case, maybe in an analyze method. The analyze method of the SkypeMessage should, in addition, manage the Skype-specific aspects.

Finally you should simplify the code and remove the list of if statements.
Introduce a new set of objects to parse the messages. These objects should have a match method that check whether the string matches with their definition, and a performAction method that generates the return value.


Powershell script to iterate through folder and restore SQL backups

This is mostly style things, but:

You should store all your constants at the top (including $logsFolder)
#this ouputs the SQL output into a logfile: you misspelled outputs
You should use the string concatenation syntax:

"TO N'$($sqlDatabaseLocation)$($newDBName)_log.ldf',"

You only use $todayUK once, so you should include it directly as a string instead of declaring it.
Instead of concatenating each string component together, use a multi line string operator like @" or a trailing backtick `.

    [string] $dbCommand = @"RESTORE DATABASE [$newDBName]
FROM    DISK = N'$backupFilePath'
WITH    FILE = 1,
MOVE N'$newDBName'
TO N'$($sqlDatabaseLocation)$($newDBName).mdf',
MOVE N'$($newDBName)_log'
TO N'$($sqlDatabaseLocation)$($newDBName)_log.ldf',
NOUNLOAD, REPLACE, STATS = 5"

Now, you can just directly call that string instead of assigning it to $dbCommand:

    Write-Host @"RESTORE DATABASE [$newDBName]
FROM    DISK = N'$backupFilePath'
WITH    FILE = 1,
MOVE N'$newDBName' #more stuff here


Different payment details in a common list, to be casted

I'm not in love with having an enum to know what base type to cast to.  If you want to stick to it then I'll give you a couple of pointers then later I'll give you a couple more options to think about

Make the base abstract and make the enum abstract

public abstract class PaymentDetailBase
{
    protected PaymentDetailBase(string id)
    {
        this.Id = id;
    }

    public string Id { get; }

    public abstract PaymentMethodEnum PaymentMethod { get; }
}

if you are going to cast based on the Enum then you don't want it being sent in the constructor.  What if I sent in the wrong enum for the type

Now classes the inherit from the base will be forced to fill in the type

public class CardDetail : PaymentDetailBase
{
    public CardDetail(string id, string last4, DateTime expiry, PaymentCardTypeEnum cardType) : base(id)
    {
        this.Last4 = last4;
        this.Expiry = expiry;
        this.CardType = cardType;
    }

    public string Last4 { get; }

    public DateTime Expiry { get; }

    public PaymentCardTypeEnum CardType { get; }

    public override PaymentMethodEnum PaymentMethod => PaymentMethodEnum.CreditCard;
}

I've worked with applications like this and I don't really care for the Enum.  It violates the open/close principle.  If I want another payment type I need to change the enum and some switch code that does hardcoded cast (yuck).   And what are you saving?  A switch statement instead of getting the base class and doing the AS statement and checking for null?

Really when you run into this situation you need to think about your design.  What in the outside needs to know about those extended properties.  If everything then why cast to the base object in the first place just pass in the right class or you can try to make use of generics with constraints.

Another option is if not a lot needs to know about the specific class then have the class do the operation you want done.  For Example you need to just copy over those properties to an entity.  Then aleave the base class abstract and make an abstract method like

public void UpdateEntity(PaymentEntity entity);

now each class need to implement the update entity and it knows about it's own properties.


Split redirecting to multiple files in bash

There are a number of things here which concern me.

First up, the stderr log file does not have the time on the file name (missing _%T). This is a classic copy-paste+partial-fix issue, you copied the same code to multiple places, then needed to fix it, but you only fixed some of them.

The solution to that is to extract the code to just one place, and reuse that:

local basename=command_"$@"_$(date +%F_T)
tee ${basename}.stderr.log

Now, basename is reusable, and if you want to change all three (stderr, stdout, full), then you can change them in just one place.

Your code does not handle complex commands gracefully. What if the command is ls -laR /etc .... how will it save away to log files called:

command_ls -laR /etc_2015-09-22_10:25:30.stdout.log

You need to rationalize that. I started with the spaces and slashes first... using a bash regex/replace for [ \/] to be replaced with an _ underscore.

local command="$@"
local base=command_${command//[ \/]/_}_$(date +%F_%T)

Next up, I am concerned that you have two tee processes both writing to the same "full" file. The one that starts second will overwrite what the first one started with, but I suspect that they will subsequently "merge" the results. It would be better to start a clean file, and then have both tee processes append to the existing file.

I messed around with your function, and came up with:

threepipe () {
    local command="$@"
    local base=rcommand_${command//[ \/]/_}_$(date +%F_%T)
    local both=$base.both.log
    rm -f $both
    touch $both
    $command 2> >(tee -a $both | tee "$base.stderr.log" >&2) | tee -a $both | tee "$base.stdout.log"
}

Note that only the stderr needs to be handled by the anonymous fifo. The redirect back to stderr keeps it out of the way of the rest of the stdout. Also, note the use of the -a flag for tee.


Rotating a character upside down and vice versa

Your code seems to be quite clear to me. The only thing I can offer as a suggestion is as follows:

if (IsNormalPosition)
{
    CharacterTargetAngle = 180;
}
else
{
    CharacterTargetAngle = 0;
}

This is a little more concise.

CharacterTargetAngle = IsNormalPosition ? 180 : 0;


Temporal kernel filtering on video frames coming in a loop

Maybe not the answer you're looking for, but I focused on that loop:

for j in range(1, NewDepth) :  # iterate from oldest to newest frame
    temp = temp + model['TempKern'][j]*Buffer[sindex]
    sindex = (sindex+1) % NewDepth

To speed this up you could:

create a variable to avoid accessing model['TempKern'] (dict access)
use in-place adition for temp

improved:

tk = model['TempKern']
for j in range(1, NewDepth) :  # iterate from oldest to newest frame
    temp += tk[j]*Buffer[sindex]
    sindex = (sindex+1) % NewDepth

Aside: outside the loop you do:

temp=np.zeros(tuple(clip_size),dtype=float)
temp = model['TempKern'][0]*Buffer[sindex]

so you can remove the first line, as it has no effect, temp is overwritten at the next line.


Why do you only return a value if $properties['step'] == 1? If you could somehow change it so that both return, or both didn't need to, you could make it neater.

$req = array('cshort');
$return = FALSE;

if($properties['step'] == 1) {
    $req[] = 'cid';
    $return = TRUE;
}

foreach($req as $required) {
    $step = 1;
    if($return) {
        return $st;
        /*
          $step? what is this where did it come from?
          Unless you are in a function, you don't need to return.
          Just use $st/$step when you need it since you only ever
          gave it one value. Just check if it isset first.
          If you want to break from the loop, just use break,
          or continue to skip.
        */
    }
}

You mentioned expanding. If this gets too much bigger you could try a switch statement instead of multiple if statements. Assuming the rest don't use the same format, otherwise just tweaking what I gave above should work.

switch($properties['step']) {
    case 1:
        foreach($req as $required) {
        }
    break;
    case 2:
        $req[] = 'cid';
        foreach($req as $required) {
        }
    break;
}


JavaScript - Optimizing a two array.map loop

That'd be with map:

this.countries = this.countries.map(country => {
    var concession = concessions.find(x => x.address.country === country.iso);
    country.address = concession.address;
    country.slug = concession.slug;
    return country;
});

That'd be with forEach:

this.countries.forEach(country => {
    var concession = concessions.find(x => x.address.country === country.iso);
    country.address = concession.address;
    country.slug = concession.slug;
});

I don't know if you can be sure there always be a concession for each country and how you should proceed in case there isn't.


Functional Programming Style in Javascript Picking a Random Item from an Array

Naming
The name pickRandomItemFrom is too long

pick implies removal which the function does not do
from is redundant.

Thus pickRandomItemFrom can simply be randomItem with Item implying an array
Ignoring the obvious problems and removing the unnecessary currying we can rewrite your code as
const randomItem =  array => array[Math.floor(Math.random() * array.length]);
console.log(randomItem(items));

Math.random is not pure
The function Math.random is not pure because you can not control the seed value. Using it in any function will make that function impure.
To be pure a function must return the same value given the same input.
You can create a pure random function but the function must take a seed value from which to calculate a random value.
Example
const seededRandom = (() => {
    const max = 2576436549074795, add = 8507698654323524, scale = 8765432352450986;
    return seed => ((scale * Math.abs(Math.floor(seed))) + add) % max;
})();

Selecting random item
You can then create the randomItem function using
const randomItem = ((rand) => (arr, seed) => arr[rand(seed) % arr.length])(seededRandom);

Used as follows
console.log(randomItem([1,2,3], Date.now()));

Note that the function can be called many times every ms. To ensure a unique seed modify the seed each call.
Example

const seededRandom = (() => {
    const max = 2576436549074795, add = 8507698654323524, scale = 8765432352450986;
    return seed => ((scale * Math.abs(Math.floor(seed))) + add) % max;
})();

const randomItem = (rand => (arr, seed) => arr[rand(seed) % arr.length])(seededRandom);

const test = [1, 2, 3, 4, 5, 6, 7, 8];

var seed = Date.now();
console.log(randomItem(test, seed++));
console.log(randomItem(test, seed++));
console.log(randomItem(test, seed++));
console.log(randomItem(test, seed++));

// or
console.log("-------------------------");
console.log(randomItem(test, seed = seededRandom(seed)));
console.log(randomItem(test, seed = seededRandom(seed)));

// or curried
const randomizeItems = ((random) => (arr, seed) => () => arr[seed = random(seed) % arr.length])(seededRandom);

const randomTestItem = randomizeItems(test, seed);

console.log("-------------------------");
console.log(randomTestItem())
console.log(randomTestItem())
console.log(randomTestItem())
console.log(randomTestItem())

Note Random means pseudo random in context of this answer


//creating cimsession to remote host
CimSession session = await Task.Run(() =>
{
     return CimSession.Create(computerHostName);
});

Task.Run is a red flag. This should be

CimSession session = await CimSession.CreateAsync(computerHostName);

Similarly for every method you call on session which has a ...Async version, you should use the ...Async version.

It seems that you're calling this from a GUI thread. That means you need to be careful about where your continuations are executed. I would suggest pulling the async calls out into a method and using .ConfigureAwait(false) on all of them, and then calling that method from the GUI thread with ContinueWith(...) to update the GUI, but since you refuse to provide more context I can't be more specific.


Naive Implementation of Automatic Memoisation

This looks good to me and I have nothing important to add.

the nonlocal are not required here
in the code sample, you could use the @decorator syntax
maybe you could write something more generic than just functions taking a single parameter.


You really shouldn't mix event and data-binding together.

The proper way of updating value from UI, would be using ComboBox.DataBindings.Add(Binding). And, not patching it via ComboBox.SelectedSomethingChanged.

Here is how I would do it :

// mock model
var person = new Person { Gender = Gender.Female };;

// mock data source
var personBindingSource = new BindingSource();
personBindingSource.DataSource = new List<Person> { person };

// initialize
var combo = new ComboBox();
// you may want to set DropDownStyle to ComboBoxStyle.DropDownList
// from the designer to disable text input.
//
// choose one of the two below :
//    combo.DisplayMember = "Value";
//    combo.ValueMember = "Key";
//    combo.DataSource = EnumHelper.GetEnumDefinitions<Gender>();
combo.BindTo<Gender>();

// databind
combo.DataBindings.Add(new Binding(
    nameof(combo.SelectedValue), personBindingSource, nameof(person.Gender), false, DataSourceUpdateMode.OnPropertyChanged));

public static class EnumHelper
{
    public static IList GetEnumDefinitions<TEnum>()
        where TEnum : struct, IConvertible
    {
        var type = typeof(TEnum);
        if (!type.IsEnum)
            throw new ArgumentException($"'{type}' is not an enum type.");

        return type
            .GetFields(BindingFlags.Public | BindingFlags.Static)
            .ToDictionary(x => (TEnum)x.GetValue(null), x =>
                x.GetCustomAttribute<DisplayAttribute>()?.GetName() ?? x.GetValue(null).ToString()
            )
            .ToList();
    }

    public static void BindTo<TEnum>(this ComboBox combo)
        where TEnum : struct, IConvertible
    {
        combo.DisplayMember = "Value";
        combo.ValueMember = "Key";
        combo.DataSource = EnumHelper.GetEnumDefinitions<TEnum>();
    }
}


Combining CSVs using ruby to match headers

Your overall approach seems fine (i.e. get all headers, then combine the files). However, it can be made much simpler.

Before getting into that, though, I'm slightly concerned about how you "manually" parse the headers of each file. The CSV format can have some nasty syntax, so simply splitting on commas may give you the wrong results (for instance, if the header text itself contains a comma). So I'd use the CSV methods for reliable, robust parsing of the header lines.

As for the actual "meat" of the script, it seems to me that you're working way, way too hard, using arrays, hashes, indices, and all sorts of other stuff. No need for that. In fact, you rarely ever need to muck around with low-level array/index stuff in Ruby.

And the neat thing about Ruby's CSV library is that you can reference cells by the header they belong to. So you don't need numeric indices. Instead, if you can do something like:

CSV.foreach(some_file, headers: true) do |row|
  puts row["Column A"] # grab the value from a named column in the row
end

CSV.foreach avoids reading everything all at once. Instead it reads the rows, one by one, passing them to the block. And since it's passing them as CSV::Row objects, so you can access the row cells by header name.

So here's my take:

require 'csv'

# Get input files
input_files = Dir.glob("datasample*.csv")

# Collect/combine headers
all_headers = input_files.reduce([]) do |all_headers, file|
  header_line = File.open(file, &:gets)     # grab first line
  all_headers | CSV.parse_line(header_line) # parse headers and merge with known ones
end

# Write combined file
CSV.open("out.csv", "w") do |out|
  # Write all headers
  out << all_headers

  # Write rows from each file
  input_files.each do |file|
    CSV.foreach(file, headers: true) do |row|
      out << all_headers.map { |header| row[header] }
    end
  end
end

The output file will contain all the headers, and all the data in the correct order, interspersed with blank cells where necessary. The memory usage should be really, really low, because no file is read in its entirety. We just read a single line from each to get all the headers, and afterward, we go row by row, outputting them as we read them.


Finding the greatest common factor of a list of numbers in JavaScript

Formatting

Before addressing optimizations, let's address some formatting problems

while vs. for loops

It is preferred to use a for loop when you:

Have an incrementer
The incrementer is not used outside of the loop
The incrementer is either strictly increasing or strictly decreasing

This is the case with both of your while loops. They can be refactored to the following:

In listFactors():

for (var i = 2; i <= number; i++){
    if(isFactor(number, i)){
        factors.unshift(i);
    }
}

In GCF():

for (var count = 0; count < factorsOfFirst.length; count++){
    var toTest = factorsOfFirst[count];
    var passTest = factorsOfEach.every(arrayContains);
    if (passTest) {
        return toTest;
    }
}

Avoid explicit booleans when possible

Instead of:

if(num % fact === 0){
    return true;
}
else{
    return false;
}

it is preferable to write:

return num % fact === 0;

and the same for your other functions.

Avoid global variables

As you correctly pointed out, you should try not to use mutable global variables; it makes the code much harder to understand. To avoid this, you could make the arrayContains function merely an arrow function and pass in toTest as well:

var testPassed = factorsOfEach.every(arr => arr.indexOf(toTest) !== -1);

A Cleaner Solution

Using the Euclidean Algorithm to find the GCD/GCF of two numbers (assuming non-negative numbers) is a much more cleaner and optimized approach:

function GCF(a, b) {
    if (b === 0) return a;
    else         return GCF(b, a % b);
}

Then, just use a reduce statement to apply GCF to all of the numbers in the array:

function findGCFofList(list) {
    return list.reduce(GCF);
}


What you have here is a right-only in order traversal of your "tree". This means you will have to FIFO-Queue the discovered down nodes to continue from, when you can't traverse right anymore.

Your code nicely reflects this, but I have some comments, especially concerning style and naming:

if (currNode.down != null) { nodeHead.add(currNode.down);  }

IMO you put too much in this line at once, especially when your currNode cannot be nicely read out loud.

I do this as a sanity check for my variable names:
read them out loud, when you can't the name is gruesome,
when it sounds silly, the name is bad,
and only when you can read your complete variable name, without sounding Czech, your names are good.

In accordance to that "policy" I'd rename currNode to currentNode or even better traversalNode.

Something similar goes for your nodeHead. I set as a goal for myself:

  If anybody (not even programmer) can read the name, and instantly tell what the variable, class, interface [...] does, it's good. If a programmer can read the name and instantly tell, it's acceptable, all other names are subject to renaming.

If you hadn't provided the nice graphic, I'd have no clue what nodeHead does.
I'd rename to remainingTraversalHeads or something similar.

Additionally to already made points I personally prefer having blocks separate.
The code from above becomes:

if (traversalNode.down != null) {
    remainingTraversalHeads.add(traversalNode.down);
}

With just these two renames, a little styling and the comments removed, your flatten method becomes:

public static <T> List<T> flatten(Nodes<T> node) {
    final List<T> flattenedList = new ArrayList<>();
    final Queue<T> remainingTraversalHeads = new LinkedList<>();
    remainingTraversalHeads.add(node);

    while (!remainingTraversalHeads.isEmpty()) {
        Nodes<T> traversalNode = remainingTraversalHeads.poll();
        while (traversalNode != null) {
            if (traversalNode.down != null) {
                 remainingTraversalHeads.add(traversalNode.down);
            }
            flattenedList.add(traversalNode.item);
            traversalNode = traversalNode.right;
        }
    }
    return flattenedList;
}

This code IMO is more obvious in it's intention and behaviour.

If I got it right, then this is in fact \$O(n)\$ complexity.


Handling many networking exceptions in Ruby

Since you're rescuing all 7 subclasses of Patron::Error, it would make sense to directly rescue Patron::Error rather than rescuing them one by one.

You're also duplicating work that has already been done for you, by formulating your own error message for each exception: the exceptions will already contain a useful error message, which even contains more information than yours do (for example if the host could not be resolved, the exception's message will contain the hostname that could not be resolved instead of just saying "Error resolving remote host").

Lastly I would print error messages to stderr, not stdout, as that's where they're supposed to go.

So I would write the code like this:

begin
  response = session.get url
rescue Patron::Error => e
  $stderr.puts e.message
  exit 1
end


Since this is about strings, I would rather use strcpy instead of memcpy. This has the benefit, that it saves the unnecessary strlen

strcpy(buffer, haystack);

You can declare the other parameters const too, e.g.

char *buffer;
const char *needle, *rep;

The for loop is a bit confusing, because it copies just one character at offset diff, no matter how large diff is. If you want to close a potential gap, you could again use strcpy

size_t needle_length = strlen(needle);
...
strcpy(buffer + rep_length, buffer + needle_length);

The other way round - if rep is larger than needle, you need to make space for the larger replacement string. Otherwise, you overwrite parts of haystack! (Unless this is what you intended, of course.)

You can avoid this, when you copy from haystack to buffer as you go, something like

size_t needle_length = strlen(needle);
char *found;
while ((found = strstr(haystack, needle))) {
    /* copy haystack part until needle */
    size_t n = found - haystack;
    strncpy(buffer, haystack, n);
    /* copy replacement string */
    strcpy(buffer + n, rep);
    /* adjust pointers */
    buffer += n + rep_length;
    haystack = found + needle_length;
}

/* copy remaining haystack */
strcpy(buffer, haystack);