As for me, this code is fine. Maybe there's some Reflection dark magic available but this one will be anyway faster.
The only thing I can suggest here is optimizing out an async State Machine because there's no code after await and the only await in the method can be executed.
Also note that you lookup through the Dictionary twice, first time when you check key with .ContainsKey, second time when you get the value with the same key. It can be done with single lookup using Dictionary.TryGetValue() method.
Also I suggest to follow async naming policy suggested by Microsoft, and rename the method to InvokeNotificationAsync.
private Task InvokeNotificationAsync(string userName, string methodName, params object[] parameters)
{
    if (connections.TryGetValue(userName, out var connection))
    {
        var proxy = Clients.Clients(connection);
        switch (parameters.Length)
        {
            case 0:
                return proxy.SendAsync(methodName);
                break;

            case 1:
                return proxy.SendAsync(methodName, parameters[0]);
                break;

            case 2:
                return proxy.SendAsync(methodName, parameters[0], parameters[1]);
                break;

            default:
                throw new HubException($"No method was defined with {parameters.Length} parameters in Hub");
        }
    }
}

Also it can look a bit better with C# 8.0 syntax
private Task InvokeNotificationAsync(string userName, string methodName, params object[] parameters)
{
    if (connections.TryGetValue(userName, out var connection))
    {
        var proxy = Clients.Clients(connection);
        return parameters.Length switch
        {
            0 => proxy.SendAsync(methodName),
            1 => proxy.SendAsync(methodName, parameters[0]),
            2 => proxy.SendAsync(methodName, parameters[0], parameters[1]),
            _ => throw new HubException($"No method was defined with {parameters.Length} parameters in Hub")
        };
    }
}


Twitch client that notifies me when a followed streamer comes online

It's good that you use absolute imports instead of wildcard imports.

VERSION_NO = 1.0

While it is usually correct to use ALLCAPS for constants, the version number should be called __version__.  That way, the help() function will know which version the program is and will display it accordingly.

Using % for format strings is not officially deprecated, but it is recommended to use .format() instead since it is more flexible.

When you have a try: block, you presumable know what errors could possibly happen.  You should list those errors in your except: statement.  That way, if one comes up that you didn't expect, you will know about it.  You might want to have two except: blocks: one for the errors you know about, and one for all the rest.  The second might be except Exception as e: print e, "Something has gone wrong.  Please ..." or whatever.

except ValueError, e:

In Python2, you use parentheses around multiple errors that you want to catch, but the syntax used above means to call the error e.  In Python3, the parentheses are not needed, so what that line means is to catch all errors of type ValueError or of type e.  What you do in Python3 is to use except ValueError as e:  That is still possible in Python2, so to be in good practice, you should use it here.

if stream_info['stream'] is None:
    return False
else:
    return True

That's great that you used is None instead of == None.  Many people wouldn't do that.  The problem I have with this code is that if ... is checking if ... is True.  Since you are already creating a boolean, take advantage of it and do it in one line:

return stream_info['stream'] is not None


Equals method for a class representing an origin and destination

Equals

You have a bit of repetition between your Equals methods. Since no instance is equal to null, you can replace your entire overridden Object.Equals method with:

return Equals(obj as ODPair);

If the obj is not an ODPair, this will just pass in a null which will then return false.

At a pinch, XOR is a passable way of combining hash-codes. But it has collision issues:

All instances where the origin and destination are the same will have the hash code of 0 (you mentioned this will never be the case for this class, but it's worth keeping in mind in general)
Two instances where the origin and destination are swapped will have the same hash code.
As Simon mentions in his answer, if the hashcodes being XORed occupy a small subset of the integers, there will be frequent collisions. This too is not likely to be much of a problem for you because the codes getting combined are from strings, so are likely to span the integers pretty well.

So of those it's likely to be the second, if any, which is of concern in this particular case.

My preference is to avoid the complexity of trying to implement my own hashing algorithm and let .NET do it for me:

return Tuple.Create(Origin, Destination).GetHashCode();

or:

return new {Origin, Destination}.GetHashCode();

Only if this presents a noticeable performance issue should you worry about trying to implement your own- premature optimization is still premature optimization even inside a GetHashCode method!


Printing all prime factors of a number input by the user

Consistency

Why is there sometimes a 1 at the end of the results?  Should it even be there, considering that 1 is not a prime number?  If you do include it in the results, why is it at the end instead of at the beginning of the list?

Enter the integer you wish to find the prime factors of: 60
[2, 2, 3, 5, 1]

Enter the integer you wish to find the prime factors of: 5
[5, 1]

Enter the integer you wish to find the prime factors of: 4
[2, 2]

Lint

PEP 8, the official style guide, specifies 4 spaces per level of indentation.  This is a strong convention for Python, where whitespace is significant.

Also, by PEP 8, primefactor() would be better named prime_factors().

It makes no sense to convert n to a float, then convert it again to an int.

import math is pointless; you never use anything in the math module.

Some of your comments are unclear.  For example:

if i>=(b/2): #number is prime

… would be better written as # b is prime.

Since this is all integer arithmetic, you can prepare your code for use with Python 3 by using the // operator rather than /.

Counting loops in Python are better written using some kind of for loop in conjunction with an iterator.  Here, I recommend itertools.count(2).

Generality and organization

primefactor() would be better as a function that accepts a parameter, rather than using the global variable n.  It should definitely return a list that it created, rather than modifying a global L as a side-effect.

Why doesn't primefactor() also work for n ≤ 4?  If you organized the code properly, the caller wouldn't be responsible for handling special cases (which aren't even necessary in the first place).  There would be no need to call exit() — which you should almost never need in a properly structured program.

Flag variables, especially poorly named ones like test, are rarely desirable or necessary.  Here, you can easily eliminate the test variable by changing test=False to return L.

First rewrite

Incorporating the remarks above, and more…

from itertools import count

def prime_factors(n):
    factors = []
    for i in count(2):
        while n % i == 0:
            factors.append(i)
            n //= i
        if 2 * i > n:
            return factors

n = int(raw_input('Enter the integer you wish to find the prime factors of: '))
print(prime_factors(n))

Yielding results

You can stream the results back to the caller by yielding prime factors as you find them, rather than building the entire list.

As an optimization, you can avoid considering even factors other than 2.

from itertools import chain, count

def prime_factors(n):
    for i in chain([2], count(3, 2)): # Try 2, 3, 5, 7, 9, 11, 13, 15...
        while n % i == 0:
            yield i
            n //= i
        if 2 * i > n:
            return

n = int(raw_input('Enter the integer you wish to find the prime factors of: '))
print(', '.join(prime_factors(n)))


For an array, check if an index exists where the sum of the elements to the left of it is equal to the sum of the elements right of it

First of all, I don't think your final return statement is correct: As far as I can figure, it compares the total sum of the array numbers to 0, which is in no way relevant to the question, and it causes the program to output true for arrays like [-1,1] or [1,2,-3].

Also, as you have already discovered with the help of JS1's observation, leftToRightRightSum and rightToLeftLeftSum only contain valid values once i >= j - 1, or, in other words, once every number in the array has been iterated over by at least one of the two pointers. Likewise, once these two variables contain valid values, the two pointers combined again iterate over every number in the array to check whether one of them fulfills the condition stated in the task.

So your two pointers merely divide the work that could as well be done by one single pointer: Calculate the total sum of the numbers (first array iteration), and then go through the array and divide the total sum into left and right for every element (second array iteration). This might seem like more work because code-wise it requires two iterations whereas your code only requires one iteration, but on the other hand, your code does more work per iteration loop than this algorithm would do due to the presence of two pointer variables, so in the end, I guess that there wouldn't be much difference in performance.

public static boolean isBalanced(int[] values) {
    int totalSum = Arrays.stream(values).sum(); // first "iteration"

    for (int i = 0, leftSum = 0, rightSum = totalSum;
            i < values.length;
            i++) { //second iteration
        rightSum -= values[i];
        if (leftSum == rightSum) {
            return true;
        }
        leftSum += values[i];
    }

    return false;
}


Check if string can be rearranged into a palindrome

Your assumption is not quite correct.

Even number of letters: every letter must occur even amount of times (not necessarily twice)
Odd number letters: one letter must occur an odd amount of times, every other letter the same as above.

For example, aaa is a valid palindrome where no letter occurs once or twice.

As to your code, it is way too complex. If you look closely it has a complexity of \$O(n^2)\$, with n being the length of the string, because you have nested loops:
 you call findUnique() which contains a loop over the letters in a loop over the letters.

You just have to count all the letters and check if there are letters with odd counts. If there are more than one letter with an odd counts the string does not satisfy the above palindrome condition. Furthermore, since a string with an even number letters must not have a letter with an odd count it is not necessary to check whether string length is even or not:

even + odd = odd
n * even = even

The function could look like this:

function canRearrangeToPalindrome(str)
{
    var letterCounts = {};
    var letter;
    var palindromeSum = 0;
    for (var i = 0; i < str.length; i++) {
        letter = str[i];
        letterCounts[letter] = letterCounts[letter] || 0;
        letterCounts[letter]++;
    }
    for (var letterCount in letterCounts) {
        palindromeSum += letterCounts[letterCount] % 2;
    }

    return palindromeSum < 2;
}


Three implementations of observable objects

First thing, you should use new-style classes, inheriting from object. (Not necessary if you are in Python3, but convenient for backwards compatibility).

So, in short, your choices are:

Store them in a list
Store them in a dictionary

Of the two, the dictionary is the best option, because the keys are stored in a hash table, and you can look up items in O(1), whereas in the list you have to transverse the whole thing until you find it, so it is O(N).

Now, note that your dictionary implementation is a very thin layer on top of a dict. I would recommend inheriting from dict. If you are bound to the specific interface (.add, .remove) instead of the __setitem__ and pop, you can just create aliases. This can help you reduce the amount of code and also give you easier access to all the expresiveness of Python dicts.

Note that the third method is broken. In particular:

self.observers.add(observer)

when self.observers is a list, that doesn't have the method add.


Slow foreach loop to check for intersect

You're not using the C# naming convention:

class ClassNamesShouldBePascalCase
{
    const CONTANTS_ARE_IN_ALL_CAPS;
    private _membersShouldStartWithAUnderScoreAndBeCamelCase; //_camelCase
    public PropertiesShouldBePascalCase {get; set;} //PascalCase

    public void PublicMethodsShouldBePascalCase
    {
        object methodLevelVariablesShouldBeCamelCase; //camelCase
    }
}
//The underscore for private variables is optional, but good practice.

Is there a reason you are using a custom class called rectList instead of using a List<Rectangle>, besides the type ? If there are more reasons, I recommend calling the class Rectangles, otherwise, just manage the Type separately.

Don't call your parameter rectangles2 ... rectangles, or values is a good name.

if (rectangles2[i].rect.Y < 500)

500 is a magic number, and should be declared somewhere else as a constant with a useful name, so that those reading it know what it is for.

Give your booleans more descriptive names like:

bool bottomHasCollision

bool hasCollisionBottom

Use the ternary operator to clean up your final return statement:

return bBOTTOM       ? BOTTOM :
       bBOTTOM_RIGHT ? BOTTOM_RIGHT :
       bBOTTOM_LEFT  ? BOTTOM_LEFT :
       rectangles2[i].rect;

If you could fix these things, and upload another question I'd be more inclided to review the performance of the program, however I will need to know more about the program and see some of the other classes. You should try saving the DateTime.Now at the beginning and end of the method, and various other places inside to track the performance to pinpoint what is taking so long. There is also software out there that can help you do that.

Edit:

I've taken the liberty to implement the code changes I was talking about above. Plus some others to make the code more concise.

private Rectangle Rectangleupdated(List<Rectangles> rectangles, int i)
{
    Rectangle rect = rectangles[i].Rectangle;

    //fills rectangles with rectangles to check intersect with
    bottom = bottomLeft = bottomRight = rect;

    //bool to be set to false if intersects returns true
    bottomFlagged = bottomLeftFlagged = bottomRightFlagged = true;

    //move the intersect rectangles
    bottom.Y++;

    bottomLeft.Y++;
    bottomLeft.X--;

    bottomRight.Y++;
    bottomRight.X++;

    foreach (Rectangles rects in rectangles)
    {
        if (rects.Type.Contains("bg") || rect.Y >= 500) continue;

        bottomFlagged     = bottomFlagged && !bottom.IntersectsWith(rects.Rectangle);
        bottomLeftFlagged = bottomLeft    && !bottomLeft.IntersectsWith(rects.Rectangle);
        bottomRight       = bottomRight   && !bottomRight.IntersectsWith(rects.Rectangle);
    }
    return bottomFlagged      ? bottom :
           bottomRightFlagged ? bottomRight :
           bottomLeftFlagged  ? bottomLeft :
           rect;
}

I would however like to see your Rectangle and rectList classes, to understand where the pain points might be.


You aren't using regular expressions to your advantage.  Capture, don't split.  Capturing helps you analyze the tokens you are interested in.  Splitting just gets you the location of the delimiters.

function fuzzQuery(rawQuery) {
    "use strict";
    //              ( 1 )     (   2   )    (   3   ) (    4    ) (     5    ) (  6   )
    var re = /\s*(?:(NOT)\s+)?([a-z]+:)?(?:("[^"]*")|(\([^)]*\))|(\[[^\]]*\])|([a-z]+))\s*/g;
    var matches;
    var lastIndex = -1;
    while (matches = re.exec(rawQuery)) {
        var relOp      = matches[1],
            qualifier  = matches[2],
            quotedStr  = matches[3],
            parensStr  = matches[4],
            bracketStr = matches[5],
            bareWord   = matches[6];
        lastIndex = re.lastIndex;

        console.log("relOp=" + relOp +
                    ", qualifier=" + qualifier +
                    ", quotedStr=" + quotedStr +
                    ", parensStr=" + parensStr +
                    ", bracketStr=" + bracketStr +
                    ", bareWord=" + bareWord);
    }
    if (lastIndex != rawQuery.length) {
        console.log("Junk=" + rawQuery.substring(lastIndex));
    }
}

Examples:

name:(john doe)

relOp=undefined, qualifier=name:, quotedStr=undefined, parensStr=(john doe), bracketStr=undefined, bareWord=undefined

name:[andy TO charlie]

relOp=undefined, qualifier=name:, quotedStr=undefined, parensStr=undefined, bracketStr=[andy TO charlie], bareWord=undefined

john doe

relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=john
relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=doe

james NOT jane

relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=james
relOp=NOT, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=jane

james NOT (james smith)

relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=james
relOp=NOT, qualifier=undefined, quotedStr=undefined, parensStr=(james smith), bracketStr=undefined, bareWord=undefined

james NOT jane smith

relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=james
relOp=NOT, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=jane
relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=smith

name:"john doe" australia

relOp=undefined, qualifier=undefined, quotedStr="john doe", parensStr=undefined, bracketStr=undefined, bareWord=undefined
relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=australia


Codility's count passing cars in opposite directions in C#

Overflow averted

Performance of your algorithm is optimal since you iterate the input just once in \$O(n)\$ time complexity. There is a way to avoid the checked overflow guard. Noone forces you to use int to perform the arithmetic in the method body.

int carTravelingEast = 0, pairOfPassingCars = 0;

Using uint with a max value of \$4,294,967,295\$ would never overflow, since:

carTravelingEast can never be more than int's max value \$2,147,483,647\$ (because of the length of an array is capped)
the maximum value \$3,147,483,647\$  as the sum of the custom threshold of one billion + int's max value could never exceed uint's max value (and we exit early on reaching one billion)

Code Conventions

Don't use UPPERCASE variable names for constants; use PascalCase instead.
Use white space according to Conventions.

GetNumberOfPassingCars( int[] passingCars ) -> GetNumberOfPassingCars(int[] passingCars)
foreach( var passingCar in passingCars ) -> foreach (var passingCar in passingCars)

Use plural name for a variable that represents multiple objects: pairOfPassingCars -> pairsOfPassingCars.
Use a constant to avoid magic numbers; const uint maxLimit = 1000000000;.
Throw ArgumentNullException when mandatory arguments are null in public methods.

Code Refactored

public static int GetNumberOfPassingCars(int[] passingCars)
{
    if (passingCars == null) throw new ArgumentNullException(nameof(passingCars));

    const int Overflow = -1;
    const int East = 0;
    const int West = 1;
    const uint maxLimit = 1000000000;
    uint carsTravelingEast = 0, pairsOfPassingCars = 0;

    foreach (var passingCar in passingCars)
    {
        if (passingCar == East)
        {
            ++carsTravelingEast;
        }
        else if (passingCar == West)
        {
            pairsOfPassingCars += carsTravelingEast;
            if (pairsOfPassingCars > maxLimit)
            {
                return Overflow;
            }
        }
    }

    return (int)pairsOfPassingCars;
}


function player(type, name, pokemon) {
    this.type = type;
    this.name = name;
    this.pokemon = pokemon;
}

var user = new player("User", "Arhum", "Charizard");
console.log(window[user.pokemon].hp)

There's some really strange and bad practices going on here, especially with the pokemon field. Here, you are relying on the fact that the string passed in will correspond with some variable on the global scope that is hopefully of the type pokemon.

That's not the right way to do things. Instead, player objects should be instantiated with the actual pokemon object itself:

var user = new player("User", "Arhum", Charizard);

Then, whenever you need to access information about the player's pokemon, rather than doing this:

window[user.pokemon]

You just do this:

user.pokemon

This is a lot safer, and follows practices much better.

var user_attack = function() {
  var uhigh = window[user.pokemon].highest_attack
  var ulow = window[user.pokemon].lowest_attack
  return Math.round(Math.random().toFixed(1)*uhigh)
}

var comp_attack = function() {
  var chigh = window[comp.pokemon].highest_attack
  var clow = window[comp.pokemon].lowest_attack
  return Math.round(Math.random().toFixed(1)*chigh)
}

These two functions do exactly the same exact thing, except they are for two very specific instances of a class. This is also terrible practice, as nothing is flexible here and functions not only repeat themselves but rely on two very specific objects to be, again, in the global scope.

Instead, these two functions should become one instance method of the player class:

player.prototype.attack = function() {
  var uhigh = this.pokemon.highest_attack
  var ulow = this.pokemon.lowest_attack
  return Math.round(Math.random().toFixed(1)*uhigh)
}

Then, you should use this methods instead of those other two functions.

user.attack();
comp.attack();

You may want to rename to doAttack as the wording can be confusing.

function player(type, name, pokemon) {
    this.type = type;
    this.name = name;
    this.pokemon = pokemon;
}

var user = new player("User", "Arhum", "Charizard");

Are there any types other than "User" and "Computer"? If not, then you should turn this property into a boolean value something like this:

function player(isComputer, name, pokemon) {
    this.isComputer = isComputer;
    this.name = name;
    this.pokemon = pokemon;
}

var user = new player(false, "Arhum", "Charizard");

var Charizard = new pokemon("Charizard", 90, 30, 1, 15);
var Blastoise = new pokemon("Blastoise", 95, 28, 1, 14);
var Venasaur = new pokemon("Venasaur", 100, 26, 1, 13);

var poke_choice = new Array ("Charizard", "Blastoise", "Venasaur")

Now that we're done relying on these three pokemon variables to be in the global scope, we can clean up this part of the code, too.

We don't need to explicitly store the three pokemon variables anymore with their variable names; those can just go straight into the array. However, when we do that, we can no longer access the pokemon by name so it would be best to create a map/object for this situation:

var pokeChoice = {
    Charizard: new pokemon(...),
    Blastoise: new pokemon(...),
    ...
}

With this in place, this

for(i = 0; i<= 2; i++) {
  if (poke_choice[i] === user.pokemon) {
    poke_choice.splice(i,1);
  }
}

can be simplified to:

if(pokeChoice.hasOwnProperty(user.pokemon.name)) {
    delete pokeChoice[user.pokemon.name];
}

Here is your full code now:

function pokemon(name, hp, critical_attack, lowest_attack, highest_attack) {
    this.name = name;
    this.hp = hp;
    this.critical_attack = critical_attack;
    this.lowest_attack = lowest_attack;
    this.highest_attack = highest_attack;
}
var pokeChoice = {
    Charizard: new pokemon("Charizard", 90, 30, 1, 15),
    Blastoise: new pokemon("Blastoise", 95, 28, 1, 14),
    Venasaur: new pokemon("Venasaur", 100, 26, 1, 13)
};

function player(isComputer, name, pokemon) {
    this.isComputer = isComputer;
    this.name = name;
    this.pokemon = pokemon;
}
player.prototype.attack = function() {
    var uhigh = this.pokemon.highest_attack
    var ulow = this.pokemon.lowest_attack
    return Math.round(Math.random().toFixed(1)*uhigh)
}

var user = new player("User", "Arhum", pokeChoice.Charizard);
if(pokeChoice.hasOwnProperty(user.pokemon.name)) {
    delete pokeChoice[user.pokemon.name];
}

var comp_choice = function() {
    var pokeKeys = Object.keys(pokeChoice);
    var pokeAmt = pokeKeys.length;
    return pokeChoice[pokeKeys[Math.round(Math.random() * (pokeAmt-1))]]
}
var comp = new player("Computer","Red", comp_choice());

console.log(user.attack())
console.log(comp.attack())

I made some other small changes here and there. If you have any questions, feel free to ask.

Also, the naming convection in JavaScript is:

PascalCase for classes.
camelCase for functions.

You are breaking these rules in some cases.


Extracting single files from a tarball (spreadsheets)

Your main questions

  Are there better ways to extract from a tar?

Using shell commands, no. Well, with any modern version of tar, instead of tar -x -f archive file you could write simpler as tar xf archive file.

I don't know Ruby, but probably there exist libraries to extract files from archives. It would be better to use that.

The current script is a mixture of Ruby and Bash commands.
This is a fragile setup:

It requires two technologies to run
It requires understanding two technologies

The solution would be more robust if it was written either completely in Ruby or in Bash.

  I know it doesn't delete the directory that is created from extracting the spreadsheets, mostly because I don't trust myself enough to remove a directory called home.

You could recursively remove the empty parent directories. That should be safe.

Naming

Looking at this usage:

ss = ArchiveManager.new(ARGV[0])
ss.num_check

This doesn't really tell what's going to happen.
The program extracts a file from an archive.
This would look like a more natural usage:

archive_manager = ArchiveManager.new()
archive_manager.extract_file(ARGV[0])

Design

The naming issue brought to the fore some design issues.
The naming change I suggested earlier for more natural usage,
also forces further changes that will lead to better design:

Currently the ArchiveManager class is one-time use to extract a single file. That's not a natural way to use classes. Making the ArchiveManager reusable by adding a extract_file method with a file parameter is more natural.
Currently many methods of ArchiveManager depend on the folio_num stored in the class. Methods are easier to understand when their dependencies are more directly visible, for example as input parameters. It also makes them easier to test.


return_byte doesn't tell much what the function is intended to do. btoa would be more in line with C naming convention (akin to itoa)
A p variable is pretty much useless. Consider

static unsigned char byte[CHAR_BIT];
unsigned char i;

for(i = 0; i < CHAR_BIT; i++)
    byte[i] = '0' + ((source & (1 << i)) > 0);

return byte;

Using an unsigned char for indexing is questionable. In any case it doesn't buy you much against a native int.
A boolean expression as + operand may raise some eyebrows (true is guaranteed to be a non-zero in an arithmetic context, but it is not guaranteed to be 1). I recommend to force an arithmetic value by right-shifting source instead of left-shifting the mask:

for(i = 0; i < CHAR_BIT; i++) {
    byte[i] = '0' + (source & 1);
    source >>= 1;
}

You do not null-terminate the resulting string. The fact that your test succeeded is a sheer (un)luck.
You probably know that returning static makes the code non-reentrant and thread-unsafe. You may want to let client provide a space for a resulting string.


In general, you want to give as little information as possible for why access was denied.  So I would change that section of code to:

if (session == null || session.Expired)
{
    throw new SecurityException("Access Denied");
}

Presumably this exception gets converted to an appropriate HTTP status code.

SendAsyc is an odd name for a function that enforces security, but maybe you have a reason for that.  That said, it seems like there's something missing since I don't see where it is async or returns a Task.


More convenient way to use comparators in Kotlin

Is comparator.use { a > b } more readable than comparator.compare(a, b) > 0?

Readability is relative and more a point of view. Usually something is considered more readable, the more people say it is.

In my personal opinion both solutions are easy to read, while I like the syntax of the first more. Actually something very similar exists in the language already: compareBy

list.sortedWith(
  compareBy{ it.a }.thenBy { it.b }.thenByDescending { it.c }
)

It has all combinations you need and provides a nice, well readable syntax.

Is it a good idea to replace use with invoke operator or make this function infix?

use isntead of invoke

It is opinion based, just like readability. Its up to you and your team.

Infix

Making a function an infix function is just another customisation option for your syntax. The only important thing to remeber is:

  Infix function calls have lower precedence than the arithmetic
  operators, type casts, and the rangeTo operator. The following
  expressions are equivalent:

  1 shl 2 + 3 is equivalent to 1 shl (2 + 3)
  0 until n * 2 is equivalent to 0 until (n * 2)
  xs union ys as Set<> is equivalent to xs union (ysas Set<>)

  On the other hand, infix function call's precedence is
  higher than that of the boolean operators && and ||, is- and
  in-checks, and some other operators. These expressions are equivalent
  as well:

  a && b xor c is equivalent to a && (b xor c)
  a xor b in c isequivalent to (a xor b) in c

Kotlinlang.org

-

Any improvement suggestions that you can think of

Strongly consider to use compareBy like described before.


I'm not entirely sure what you are asking for, but if this were my program I would do a few things differently.

SQLite

I would place the journal entries in a sqlite database rather than raw files and directories.

D provides an interface to sqlite. Sqlite provides great abstraction over raw files. Keeping your files consistent, and not corrupting them is difficult. sqlite already does the right thing, and more!

Command Pattern instead of switch

I would provide a nicer abstraction for commands instead of a switch statement. This Python code works as a template.

By implementing a switch statement, each new command increases the cyclomatic-complexity of the main() function. Thus your testing requirements increase exponentially. By breaking out each command to implement an ICommand interface, your testing requirement increases linearly. The visitor pattern might also provide a nice mechanism to process each command.


The algorithm seems okay so I'll review the OOP aspect.
Naming

The method named PrintBinaryZigZag but it doesn't print anything.
The class named BinaryTree isn't really a binary tree, it's more of a Node.

Implementations vs interfaces
You return List<int>, but do you really need a list?
The goal of this method if to return a list that represents a binary tree.
Should you be able to add/remove objects from this list? Do you need the indexer, that is specific to the list? I don't think so. In this case, return IEnumerable<int>.
C# details
BinaryTree temp = currentLevel.Peek();
currentLevel.Pop();

You could simply do : BinaryTree temp = currentLevel.Pop();
Flow
if (leftToRight)
{
    if (temp.Left != null)
    {
        nextLevel.Push(temp.Left);
    }
    if (temp.Right != null)
    {
        nextLevel.Push(temp.Right);
    }
}
else
{
    if (temp.Right != null)
    {
        nextLevel.Push(temp.Right);
    }
    if (temp.Left != null)
    {
        nextLevel.Push(temp.Left);
    }
}

I'm sure there's a way to make this smaller. Now, this is a take to maybe give you an idea, I don't think it's perfect, it's weird to use a foreach when you only have two elements in the list. But maybe if can give you an idea to make this code smaller.
var orderedNodes = leftToRight ? new []{ temp.Left, temp.Right } : new []{ temp.Right, temp.Left };

foreach(var node in orderedNodes.Where(n => n != null))
{
    nextLevel.Push(node);
}

This :
if (currentLevel.Count == 0)
{
    leftToRight = !leftToRight;
    Stack<BinaryTree> tempStack = currentLevel;
    currentLevel = nextLevel;
    nextLevel = tempStack;
}

I think it could be outside your while loop.


KMeans in the shortest and most readable format

You use vstack a lot to build arrays row by row, with the additional complication of initializing the array variable to None, which needs a special case in your loops then. This complication could be avoided by intializing to zero-height 2D array instead, but in any case repeated vstack use is inefficient because it copies the array every time. Better options are:

Collect rows in a list and vstack the list in the end. Good approach when you don't know the height of the array in advance.
Initialize array to right size and assign into rows.
Best of all, create array at once by a vectorized operation.

For example this

self.means = None
for i in randomMeansIndices:
    if self.means is not None:
        self.means = np.vstack( ( self.means, data[ i ] ) )
    else:
        self.means = data[ i ]

could be done in one line, as you can index arrays with arrays:

self.means = data[randomMeansIndices]

This code could avoid the loop

distances = {}
meanID = 0
for mean in self.means:
    distances[meanID] = LA.norm(mean - row)
    meanID += 1
nearestMean = min( distances, key=lambda x: distances[x] )

by computing all the norms at once (NumPy 1.8 required). argmin gives the index of the minimum.

distances = LA.norm(self.means - row, axis=1)
nearestMean = np.argmin(distances)

The KMeans class has no purpose other than holding the result of clustering. The cluster method could be a stand-alone function instead and just return means, data_assignments. If you prefer to access the two items by name, use a collections.namedtuple as the return value.


max_heap = []

I think the essentially Hungarian naming here is actually fairly helpful, but it would be very useful to have a comment explaining that the library support is only for min heaps, so everything must be negated when pushed or popped.

    # Checking for 2 as prime factor
    if n % 2 == 0:
        heapq.heappush(max_heap, -2)
        # dividing by 2 until n becomes odd
        while n % 2 == 0:
            n = n/2
    # dealing with odd numbers
    for i in range(3,int(sqrt(n)),2):
        if n % i == 0:
            heapq.heappush(max_heap,-1*i)
            while n % i == 0:
                n = n/i

Reasonable use of a special case: I see you've given some thought to optimisation.

It's better to use -i than -1*i, and n // i (since you want integer division) than n / i.

    # dealing with case where n is a prime by itself

That's open to misinterpretation. Is it talking about the original value of n or the current value? I think I would phrase it

    # if n > 1 here then it's a prime

    return heapq.heappop(max_heap) * (-1)

See previous point about unary minus.

I wanted to address minor improvements before addressing the big one. Why use a heap at all? The largest prime is the last prime encountered, and there's no need to store the smaller ones. Removing the heap would make the code simpler and faster.


So what you are trying to do is to have an implementation of IEnumerable<T> which has a singleton IEnumerator<T>? Why not implement that explicitly, instead of using undocumented (?) behaviour of List<T>'s iterator?

Simply create a class that consumes a IEnumerable<T>, takes its iterator and wraps it in an implementation of IEnumerator<T> that has a dysfunctional Reset method. IEnumerator<T>.GetEnumerator() can then return the instance to that same iterator instead of creating a new one for each call. It could look something like this:

  public class OnlyOnceIterator<T> : IEnumerable<T>, IEnumerator<T> {
    private readonly IEnumerator<T> enumerator;
    internal OnlyOnceIterator(IEnumerable<T> sequence) {
      enumerator = sequence.GetEnumerator();
    }

    public T Current => enumerator.Current;

    object IEnumerator.Current => enumerator.Current;

    public void Dispose() {
      enumerator.Dispose();
    }

    public IEnumerator<T> GetEnumerator() => this;

    public bool MoveNext() {
      return enumerator.MoveNext();
    }

    public void Reset() {
      return;
    }

    IEnumerator IEnumerable.GetEnumerator() => this;
  }

This could then be used in an extension method:

  public static OnlyOnceIterator<T> ToOnlyOnceIterator<T>(this IEnumerable<T> sequence) {
    if (sequence == null) {
      throw new System.ArgumentNullException(nameof(sequence));
    }

    return new OnlyOnceIterator<T>(sequence);
  }

Additionally, I would prefer a more specific return type than IEnumerable<T>, since the returned behaviour is significantly different to what any user might expect from IEnumerable<T>. Consider creating a new interface that inherits from IEnumerable<T> with a more descriptive name. Through inheritance, Linq will still be able to be used, and you can create methods that only accept this specific interface, (compare this to IOrderedEnumerable<T>).


Parameterized Verilog shift register code

I don't see any problems with the code functionally, and the layout follows good practices for the most part.  You chose meaningful names for the signals and parameters, and the parameters make your design scalable to different data widths.  It also follows good practices using nonblocking assignments for the sequential logic.  This is excellent for a beginner.
You should use a sized constant for the data reset value ('h0) in order to avoid synthesis lint warnings from some tools.  I prefer the replicated concatenation style for this: {DATA_WIDTH{1'h0}}.
I think it is more conventional to omit the 1'h1 == in comparisons to 1 for 1-bit signals.  It makes the code a little cleaner, and all the tools do the right thing.  For example: (wr_enable).
Similarly for comparisons to 0, omit the 1'h0 ==, and use either ! or ~ (they are equivalent for 1-bit signals): (!s_rst_n_i)
You did a fantastic job of using a consistent layout style.  The following comments are my preferences, but you might consider using them as well.
I use 4-space indentation because I think it is easier to see the different levels of your code's logic.
I prefer to place the begin and end keywords on the same line as the if/else keywords in order to reduce vertical space and get more code on one screen.  It also makes the branches of your code more evident.
Here is the code with the above suggestions:
`timescale 1ns / 1ps

module shift_reg #
(
    parameter integer DATA_WIDTH   = 16,
    parameter integer DO_MSB_FIRST = "TRUE"
)
(
    input  wire                      clk_i,
    input  wire                      s_rst_n_i,
    input  wire                      enable,
    input  wire                      wr_enable,

    input  wire [DATA_WIDTH - 1 : 0] wr_data_i,

    output wire                      serial_data_o
);
    localparam integer MSB = DATA_WIDTH - 1;
    localparam integer LSB = 0;
    localparam integer XSB = ("TRUE" == DO_MSB_FIRST) ? MSB : LSB;

    reg [DATA_WIDTH - 1 : 0] parallel_data;

    assign serial_data_o = (enable) ? parallel_data[XSB] : 1'hz;

    always @ (posedge clk_i) begin
        if (!s_rst_n_i) begin
            parallel_data <= {DATA_WIDTH{1'h0}};
        end else if (wr_enable) begin
            parallel_data <= wr_data_i;
        end else if (enable) begin
            if ("TRUE" == DO_MSB_FIRST) begin
                parallel_data <= {parallel_data[MSB - 1 : 0], 1'h0};
            end else begin
                parallel_data <= {1'h0, parallel_data[MSB : 1]};
            end
        end
    end
endmodule


If there are 1 million datasets, and i enter the first three letters, it will have to filter all 1 millionen values (let us asume the result will be 200 hits). When i now add a fourth letter, it will have to filter AGAIN all 1 million values and not just the 200 hits.
Therefor, if it is absolutly necessary to do the filtering codewise, then you could implement a kind of memory effect.
When the first filtering is executed (after the first 3 letters), you store the searchphrase and the filter result. When now the fourth letter is added, you just check if the first three letters are still the same. If yes, then you can shorten your filtering by just filtering the reduced list from the filtering before.
That way you swap runtime against memory consumption (a typical trade off).
My question would be if it is absolutly necessary to do the filtering codewise. When this search should be applied mostly on big datasets, then i would move the filtering to the backend. Then you have a lot more of requests to the backend, but the backend (the database to be precise) could handle such filtering much more efficiently.
But as always, it depends. For small sets of data, the roundtrip time (FE -> BE -> FE) for each search request will eat all performance gains that you have aquired with the more efficient filtering. But for large datasets, the roundtrip time will be less bad, in comparision to the filtering performance (and the memory consumption) on the client.
warm regards
Jan


Hackerrank "Strings: Making Anagrams" Javascript Solution

I like your idea of counting character frequencies first. This allows you to count the required deletions in linear time.

Your code is readable, but readability can be improved by more semantic naming and leveraging modern JavaScript language features.

Naming:

Regarding the variable names a, objA, mainObj, resultObj, arrOfAlphabets: Those identifiers mainly include type information (obj, arrOf). But as a reader, I am more interested in the role of your variables instead of their type. So instead of objA I would prefer to read frequenciesA or even freqA. And instead of arrOfAlphabets I suggest the simpler characters.

For-loops:

First of all, you probably forgot to declare the local loop iterator in for (i = 0; ...). Unfortunately, those omissions can introduce very hard to trace bugs as you now access and potentially share a global variable i.

Also, JavaScript arrays and strings implement the iterable protocoll. This means you can iterate over them using a simpler for-of loop:

for (let char of characters) { ... }

This allows you to replace arrOfAlphabets[i] with the more readable char.

Default properties:

There is a pretty common technique used to handle default values of object properties. Replace

if (obj[arrOfAlphabets[i]]) {
  resultObj[char] += 1;
} else {
  resultObj[char] = 1;
}

with the shorter and idiomatic

resultObj[char] = (resultObj[char] || 0) + 1;

Enumerate object keys:

Instead of

for (var k in mainObj) {
    if (mainObj.hasOwnProperty(k)) { ... }
}

you can nowadays use Object.keys to write

for (let key of Object.keys(mainObj)) { ... }

Refactoring:

You probably noticed the redundancy in

var numOfDeletionsA = countNumberOfDeletions(objA,objB);
var numOfDeletionsB = countNumberOfDeletions(objB,objA);
console.log(numOfDeletionsA + numOfDeletionsB);

If you modify your countAlphabetFrequency function to increment frequencies for string a and decrement frequencies for string b, you can simply sum the absolute frequencies to get the number of required deletions.

If you combine that with a more descriptive approach by replacing for-loops with forEach and reduce, you get a simpler implementation:

// Count character deletions required to make 'a' and 'b' anagrams:
function count(a, b) {
  let freqs = {};
  a.split('').forEach(char => freqs[char] = (freqs[char] || 0) + 1); // increment
  b.split('').forEach(char => freqs[char] = (freqs[char] || 0) - 1); // decrement
  return Object.keys(freqs).reduce((sum, key) => sum + Math.abs(freqs[key]), 0);
}

// Example:
console.log(count('ilovea', 'challenge')); // 9


Algorithm to park cars with minimal moves (2nd version)

Why do you need a separate position dict, that you have to maintain whenever you move a car ? You can just use input.index(car_id) anytime you need to get a car position.
Also your print_move() function is almost useless, since it just swaps 2 positions, one of which is assumed to be empty. That could be written in a single line.

Here are my proposed improvements, with an modified move() that takes the car id to move and the target free slot, and returns the new freed slot:

def car_move_v2(initial_slots, target_slots, EMPTY=None):
    current_slots = initial_slots # will use as working slots
    def move(car, free_slot):
        "move car to free_slot, returns the newly freed slot"
        assert current_slots[free_slot] == EMPTY, "Slot {0} is not free".format(free_slot)
        car_slot = current_slots.index(car)
        current_slots[free_slot], current_slots[car_slot] = current_slots[car_slot], EMPTY
        print('car {0} moved from {1} to {2}, {3}'.format(car, car_slot, free_slot, current_slots))
        return car_slot

    for slot, (current_car, target_car) in enumerate(zip(current_slots, target_slots)):
        if current_car == target_car: # if car is already in target position, do not move
            continue
        elif current_car != EMPTY: # if there is an unwanted car in the slot, move it to the empty slot
            free_slot = move(current_car, current_slots.index(EMPTY))
        else:
            free_slot = slot
        # at this point we have a free slot to work with
        while target_slots[free_slot] != EMPTY:
            other_target_car = target_slots[free_slot]
            free_slot = move(other_target_car, free_slot) # move that car to the current free pos

if __name__ == "__main__":
    car_move_v2(initial_slots=[None,1,2,3,7,6,4,5], target_slots=[4,6,5,1,7,3,2,None], EMPTY=None)


Check whether all checkboxes are checked and then execute a function

I was thinking something along these lines. The condition checks whether there are no unchecked checkboxes (length of the selection is 0) and then executes the appropriate branch.

$("#btnSubmitToCheckOut").click(function(event) {
    if ($('.age_agree input[type="checkbox"]').not(':checked').length == 0) {
        $(this).parents('form').submit();
    } else {
        alert('Please accept all the Terms and Conditions');
    }
});


Optimizing solution of Sum of Pairs: Codewars in Python

You could use a set as lst1 instead of a list. Every time you check if n is in lst1, it’s \$ O(n) \$ time complexity. Using a set instead will lower that to \$ O(1) \$.


Extract the common logic to a function,
where the varying parts are parameters.
Unless I'm missing something, this looks trivially easy to do:

function setup_namespace(org_id) {
    var nsp = io.of('/nsp_bucket_' + org_id);
    nsp.on('connection', function(socket){
        console.log('someone connected to namespace bucket ' + org_id);

        socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){
            console.log('addEmp - Org_Id : ' + login_org_id);
            console.log('addEmp - Emp_Id : ' + login_emp_id);
            console.log('addEmp - Emp_Name : ' + login_emp_name);
        });

        socket.on('disconnect', function() {
            console.log('Someone disconnected from namespace bucket ' + org_id);
        });
    });
    return nsp;
}

var nsp_1005 = setup_namespace(1005);
var nsp_1010 = setup_namespace(1010);

If you don't need to retain those variables,
then you could remove the variables and just leave the calls:

setup_namespace(1005);
setup_namespace(1010);


Merge all files in a directory with a specific extension

scandir

It is not a good name for 2 reasons. First, it exists in a global namespace, and second, it doesn't tell what the function does. Your scandir not only scans the directory, but does an actual merge as well. I would recommend to scan the directory with a standard library's scandir and then merge files (from the list it returns) in a merge function.

A perk benefit of using a stock scandir is an ability to control the merge order. Right now it is unpredictable.

Yet another benefit of separating responsibilities is that if outfile is in the same directory with source files and it has an target extension, the results could be very strange.
has_extension presumes that the extension is always 3 characters. It is not necessarily so. It should calculate an actual length of the ext argument.
append_to_file produces a misleading diagnostics. The fopen may fail for many reasons, but file being empty is not one of them. Display the error message with perror or strerror.
path_combine

Contrary to a popular belief, windows understands a forward slash as a path separator (backslash is an artifact of cmd.exe). There's no need to special case windows.

It is also not necessary to test for last character for being a separator. Just add the separator anyway, it is harmless.

That said, I don't think that you need it at all: just chdir() to the source directory first.


Converting a query result into an key=>value pairs for a lookup table

Given you are working with PHP, there is no reason to neglect such a feature that already exists in the language.

For example when you query one of the lookup tables for all values,

$data = $pdo->query("SELECT * FROM lookup")->fetchAll(PDO::FETCH_KEY_PAIR);

you get an array like this:

 1 => 'Trivial',
 2 => 'Moderate',
 3 => 'Challenging',
 4 => 'Formidable'

all thanks to PDO::FETCH_KEY_PAIR fetch mode.

Of course it works only with PDO, but you are supposed to use this driver anyway.


Removing numbers from the middle of an array

Firstly: Don't use for...in on arrays.

Secondly, I suppose you can find the 1-boundaries, and add/subtract 4:

var left = array.indexOf(1) + 4;
var right = array.lastIndexOf(1) - 4;
for(; left <= right ; left++) {
  array[left] = 0;
}

Not particularly clever, but it does the job.

(Note: lastIndexOf is widely supported in modern runtimes, but older ones may not have it)

But also take @itsbruce's advice from the comments, and consider another structure for these data.


Analyzing distances between clusters of orders

self.date = str(date)

This is a pet peeve of mine. Stringly-typed variables are usually a bad idea. If you receive a datetime object, you should usually keep it as datetime until you actually need it to be a string.

Load_Order_Lat_Long_Date_Zone_Data

If at all possible, shorten this method name. Also, methods are lowercase by convention.

self.distinct = set([str(row.Requirements) + ' ' + str(row.Route_Date) for row in self.order_data])

Here you make a generator, construct a list and then convert it to a set. Skip the list - the set constructor can accept generators directly. Better yet, if you're in a sane version of Python, just use a set literal (and use a format string):

self.distinct = {'%s %s' % (row.Requirements, row.Route_Date) for row in self.order_data}

Your container = [] / container.append() loop can be replaced by proper use of a generator. Same with out.

latlng does not (and should not) be materialized to a list. It should be left as a generator, since you only iterate over it once.

This:

container.append((i[0][0][0], i[0][0][1], i[0][0][2], i[0][0][4], i[0][0][5], i[0][0][6]))

can be:

container.append(tuple(i[0][0][j] for j in (0, 1, 2, 4, 5, 6)))


Correctly using promises with node-mysql

Remove the async method call from the constructor, and make the async method return the instance (this):
class Player {
  constructor(user_id, socket, connection) {
    this.socket = socket;
    this.connection = connection;
  }

  async loadUser() {
    let _self = this;
    return new Promise((resolve, reject) => {
      _self.connection.query(`SELECT * FROM users WHERE id = ${this.user_id}`, (err, res) => {
        this.user = res[0];
        resolve(this)
      });
    })
  }
}

Then you can instantiate a new Player and wait for it to load the necessary data from the database, all in one line, like this:
const player = await new Player(user_id, socket, connection).loadUser();

Or like this:
new Player(user_id, socket, connection).loadUser().then(player => {

});


Object-oriented implementation on Expense Tracking App

There are several aspects about your code worth reviewing: OO-principles, code conventions, functional design. Since you specifically requested to review OO-design and your question lacks context to review functional design, I'll focus on the former.

Inheritance
Expenses and Earnings both derive from Account to provide their specific implementation of Initialze. Because of a lack of context, I can't make a call about this design. The implementation of both classes does seem off. I don't think you want each instance of these classes to create and store the same fixed list of presets.

Polymorphism
This is proper use of polymorphism. The declaring type Account is the closest fit to enable the use case Initialize. The instance type Expenses provides the specific implementation of that method.

Account expense = new Expenses();
expense.Initialize();

Composition
You have been a bit too diligent in the composition of some of your classes. AccountType is a redundant class, which acts only as a wrapper for AccountTypes Type. Get rid of it and use AccountTypes directly in Account.

public class AccountType
{
     public AccountTypes Type;
}

Encapsulation
Account is an abstract class that does not provide an explicit constructor. A public default constructor is implied. It is impossible for derived classes to reduce the scope of the access modifier, hence it's a breach in encapsulation. Consider providing a protected constructor for abstract classes.
public abstract class Account
{
    protected Account() {}
}

All your properties and fields are mutable. This might be as desiged, but at least think about whether this is a requirement or just lazy design.

public decimal Value { get; set; }


The Miller-Rabin Primality Test in Clojure

There is an error in the translation of the probablyPrime function. In Clojure, a function body is an implicit do form. The two if forms and  the cond form:

(defn probablyPrime [p accuracy upto]
  (if...
    )

  (if ...
    )

  (cond
    ...
    ))

... will be evaluated in succession. The values of the (if ...)s will be discarded; the result of the (cond ...) will be returned. The Python returns the associated value if either if condition is satisfied.

For example, the Clojure gives

(probablyPrime -2 0 1)
;true

... whereas the Python returns false.

I suggest you bring all the conditions under the cond:

(defn probablyPrime [p accuracy upto]
  (cond
    (or (= p 2) (= p 3)) true
    (< p 2) false
    (> upto accuracy) true
    (isWitness (rand-between (- p 2)) p (:exponent (decompose 0 (- p 1))) (:n (decompose 0 (- p 1))) 0) false
    :else (probablyPrime p accuracy (inc upto))))

There are other problems that make your Clojure unworkable for testing large numbers:

You use proper recursion to express Python for loops. This may
cause stack overflow and will certainly slow things down. Use
Clojure's recur instead.
Your rand-between function is \$\mathcal{\Theta}(n)\$. This is a performance
disaster when \$n\$ is huge.

There are also some constructions that would improve your code in small ways:

Use let forms to avoid recalculating expressions.
Use inc and dec instead of (+ ... 1) and (- ... 1).
Prefer explicit arities to rest parameters in function pow.

With these improvements, the rest of the code now looks as follows:

(ns miller-rabin.core
  (:gen-class)
  (:require [clojure.math.numeric-tower :as math]))

(defn pow
  ([x y] (math/expt x y))
  ([x y z] (mod (pow x y) z)))

(defn rand-between [n]
  (+ (rand-int (- n 2)) 2))

(defn decompose [exponent-of-two n]
  (if (odd? n)
    {:exponent exponent-of-two :n n}
    (recur (inc exponent-of-two) (quot n 2))))

(defn checkWitness [possibleWitness p exponent remainder upto]
  (let [possibleWitness (pow possibleWitness 2 p)]
    (or
     (> upto exponent)
     (and
       (not= (dec p) possibleWitness)
       (recur possibleWitness p exponent remainder (inc upto))))))

(defn isWitness [possibleWitness p exponent remainder upto]
  (let [possibleWitness (pow possibleWitness remainder p)]
    (cond
     (or (= possibleWitness 1) (= possibleWitness (dec p))) false
     (zero? exponent) true
     :else (checkWitness possibleWitness p exponent remainder upto))))

I've noticed that, in translation, several functions have acquired an extra argument that is used internally to control repetition. I'll just restore decompose:

(defn decompose [n]
  (loop [exponent-of-two 0, n n]
    (if (odd? n)
      {:exponent exponent-of-two :n n}
      (recur (inc exponent-of-two) (quot n 2)))))

The others - isWitness and probablyPrime  - are up to you. If you follow the Python, you don't need to factor out checkWitness.

To do:

I have not seriously tested the above.
Factoring out checkWitness from isWitness can be bettered using
the sequence library.


Transform an object into another object structure

So you have five data series here right (A through E)?  What happens when you have 4 or 6 data series?  Do you really want to rewrite your code?

Also, unless you have some reason to do so, lodash seems kind of unnecessary for these sort of simple data transforms these days.  I am guessing using ES6 Array.map, Array.reduce and similar would do the same exact thing while also yielding a more fluent, readable style,


pairs is overcomplicated indeed. Notice that a block of size k contributes k-1 pairs, and no other pair exists. So the total is a sum of (k - 1) taken over all blocks. Final observation is that the sizes of blocks add up to the size of array, therefore pairs = num.size() - blocks.size() is all you need.
shuffle can be performed in linear time (strictly speaking, in \$O(kn)\$, where k is number of blocks) in place (\$O(1)\$ space complexity). The key algorithm is known as rotate. One possible implementation is

void rotate(int[] array, int first, int mid, int last) {
    reverse(array, first, mid);
    reverse(array, mid, last);
    reverse(array, first, last);
}

There also is an arguably faster implementation, where each element is moved exactly once. Try to figure it out yourself.


A Summation Function For Boost.MultiArray in C++

Implement a recursive std::reduce()
You shouldn't need to special-case boost::multi_array and related types, as those types already act like STL containers (they provide begin() and end() for example). The main problem however is how to deduce the return type of recursive_sum(). Your functions seem to work because they deduce T from a boost::multi_array<T, Dims>, but do they really? Your recursive_sum() recurses over the dimensions of a multi_array, but it doesn't actually handle nested multi_arrays, like for example:
boost::multi_array<boost::multi_array<double, 2>, 3> array;

The reason is that in the above case, calling recursive_sum(array) will deduce T to be a boost::multi_array<double, 2> instead of a double.
To solve this issue, I would do what std::reduce() does, and sidestep the issue by requiring an initial value for the sum. The type of this initial value will also be the return type. For example:
template<class T, class ValueType, class Function = std::plus<ValueType>>
auto recursive_reduce(const T& input, ValueType init, const Function& f)
{
    return f(init, input);
}

template<class Container, class ValueType, class Function = std::plus<ValueType>>
requires is_iterable<Container>
auto recursive_reduce(const Container& input, ValueType init, const Function& f = std::plus<ValueType>())
{
    for (const auto &element: input) {
        auto result = recursive_reduce(element, ValueType{}, f);
        init = f(init, result);
    }

    return init;
}

Then you can call it like so:
boost::multi_array<...> array(...);
std::cout << recursive_reduce(array, 0.0) << "\n";

You could perhaps write some template to find the inner-most value type, so that you can use that as a default for the template parameter ValueType in recursive_reduce(), and then you can use {} as the default value for init, and be able to write:
std::cout << recursive_reduce(array) << "\n";


Terminated due to timeout Mapping phone numbers

Naming

Single character name is a bad practice. Use the descriptive names for variables.

r => rows
o => noOfRecords
c => noOfRows
x => ...

They are not searchable and can be easily confused with numbers. For example, l and 1, 0 and o/O.

Dead/Unused Code

Variables c and x are not used and thus can be removed.

Overriding Variables

<opinion-based>Variable o is used to get the first line in the file and then inside forEach it is again used to store the match result. This will work fine, but will also confuse other users(or you after few months). The variables should be used for single-purpose.</opinion-based>

Slice down input data

Inside forEach, input data is used to search for the name. input here is complete data with the number of records on the first line, name-numbers and then names.
This data can be sliced down to keep only name-number. This will reduce the data to work on and will improve the performance.

var rows = input.split(/\n/);
var nameAndNumbers = rows.slice(1, numberOfRows + 1);

and use nameAndNumbers to search name from.

As greybeard mentioned in comment, you should use object/Map to store the name and number.

function processData(input) {
    var rows = input.split(/\n/);
    var numberOfRows = Number(rows[0]);

    var nameAndNumbers = rows.slice(1, numberOfRows + 1);
    var names = rows.slice(numberOfRows + 1);

    var phoneBook = {};
    nameAndNumbers.forEach(function(number) {
        var data = number.split(' ');
        phoneBook[data[0]] = data[1];
    });

    return names.map(name => phoneBook[name] ? name + '=' + phoneBook[name] : 'Not Found').join('\n');
}


If you need to prepend a number of characters to a string you might consider String.PadLeft().

For example:

string str = "abc123";
Console.WriteLine(str);
str = str.PadLeft(10);
Console.WriteLine(str);

Will produce:

abc123
    abc123

On the efficiency of your example, StringBuilder.Append() is more efficient than StringBuilder.Insert(), so you might try something like:

public static string PrependSpaces2(string str)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < (10 - str.Length); i++)
    {
        sb.Append(" ");
    }
    sb.Append(str);
    return sb.ToString();
}

EDIT As svick suggested, Append(char, repeat) is simpler and faster on the order of the native Pad methods:

public static string PrependSpaces3(string str)
    StringBuilder sb = new StringBuilder();
    if((NUM - str.Length) > 0)
    {
        sb.Append(' ', (NUM - str.Length));
    }
    sb.Append(str);
    return sb.ToString();
}

Which when tested with this:

string str = "abc123";
Console.WriteLine("str: " + str);

int iterations = 100000;

string result = string.Empty;
Stopwatch s1 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
    result = PrependSpaces(str);
}
s1.Stop();
Console.WriteLine(iterations + " calls to PrependSpaces took: {0:0.00 ms}", s1.Elapsed.TotalMilliseconds);

string result2 = string.Empty;
Stopwatch s2 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
    result2 = PrependSpaces2(str);
}
s2.Stop();
Console.WriteLine(iterations + " calls to PrependSpaces2 took: {0:0.00 ms}", s2.Elapsed.TotalMilliseconds);

string result3 = string.Empty;
Stopwatch s3 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
    result3 = str.PadLeft(NUM, ' ');
}
s3.Stop();
Console.WriteLine(iterations + " calls to String.PadLeft(" + NUM + ", ' ') took: {0:0.00 ms}", s3.Elapsed.TotalMilliseconds);

string result4 = string.Empty;
Stopwatch s4 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
    result4 = PrependSpaces3(str);
}
s4.Stop();
Console.WriteLine(iterations + " calls to PrependSpaces3 took: {0:0.00 ms}", s3.Elapsed.TotalMilliseconds);

returns this (benchmarks for prepending 1000 characters):

str: abc123
100000 calls to PrependSpaces took: 20190.16 ms
100000 calls to PrependSpaces2 took: 1025.87 ms
100000 calls to String.PadLeft(1000, ' ') took: 84.32 ms
100000 calls to PrependSpaces3 took: 84.32 ms

for prepending 10 characters:

100000 calls to PrependSpaces took: 31.02 ms
100000 calls to PrependSpaces2 took: 11.41 ms
100000 calls to String.PadLeft(10, ' ') took: 4.53 ms
100000 calls to PrependSpaces3 took: 4.53 ms


A good way to do this would be by .Sentences, assuming your string doesn't appear more than once per sentence. You can use instr to get the location of your strings and then store them in an array. Then print them wherever you want:

Sub GetMediaStrings()
    Const BEGIN_STRING As String = "[Media:"
    Const END_STRING As String = ".jpg"
    Dim searchRange As Range
    Dim startString As Long
    Dim endString As Long
    Dim results() As String
    ReDim results(1 To 2)
    For Each searchRange In ActiveDocument.Sentences
        startString = InStr(1, searchRange, BEGIN_STRING, vbTextCompare)
        If startString > 0 Then
            endString = InStr(1, searchRange, END_STRING, vbTextCompare)
            If endString > 0 Then
                results(UBound(results) - 1) = Mid(searchRange, startString, endString - startString + Len(END_STRING))
                ReDim Preserve results(1 To UBound(results) + 1)
            End If
        End If
    Next
End Sub

You might also want to do it via .StoryRanges.


Applying DocumentListener on multiple JTextField

Almost fine. You are doing the same stuff in all 3 update methods of the DocumentListener, so I suggest creating a new private method in it and just calling it from all 3 update methods. That way you avoid code duplication and only have one location to change in the future instead of having to maintain the same code 3 times.

DocumentListener listener = new DocumentListener() {

    @Override
    public void removeUpdate(DocumentEvent e) {
        doStuff(e);
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        doStuff(e);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        doStuff(e);
    }

    private void doStuff(DocumentEvent e) {
        Object owner = e.getDocument().getProperty("owner");
        enableDetachButton(getContentPane());
        changeColor((JTextField) owner);
    }
});


Pass by Entity or EntityId in repositories?

If the return type is IQueryable<Attendance> then use a Person object because it implies that the method could use any of the passed Person object's properties to query other persons or other related objects.

If you want to find one person with Id, change the method's signature to tomething like this:

public Attendance GetByPersonById(int id)


Taking advantage of Array.prototype.flat()
 we might compact this a bit.

Basically, we filter all of our fields, making them an array if they are not already, getting out an array of arrays (nested only one level). After that, we can easily flatten it, so we iterate each element and we can just add it to our set.

let userFields = {
    id: {
        dbFields: 'id',
    },
    email: {
        dbFields: 'email',
    },
    first_name: {
        dbFields: 'first_name',
    },
    last_name: {
        dbFields: 'last_name',
    },
    name: {
        dbFields: ['first_name', 'last_name'],
        resolve: user => [user.first_name, user.last_name].filter(n => n.length).join(' '),
    }
};

let selectFields = ['name', 'first_name', 'email'];

let dbFields = new Set();
selectFields.map(key => {
    let field = userFields[key].dbFields;
    return (field instanceof Array) ? field : [field]
  })
  .flat()
  .forEach(v => dbFields.add(v));
console.log(Array.from(dbFields));


Staying with your original code you can change b to a simple break and you can change the inner while to a for which is easier to read:

public Asset[] merge2(final Asset[] firstArray, final ArrayList<CountR> secondList) {
    while (secondList.size() != 0) {
        for (int i = 0; i < firstArray.length; i++) {
            final CountR countR = secondList.get(0);
            final Asset asset = firstArray[i];
            if (countR.id.equals(asset.id)) {
                asset.TotaleRegistrazioni = countR.tot;
                break;
            }
        }
        secondList.remove(0);
    }
    return firstArray;
}

Searching in a HashMap should be faster than iterating through the whole array, so I'd do the following:

public Asset[] merge3(final Asset[] firstArray, final CountR[] secondArray) {
    final Map<Id, Asset> assetCache = new HashMap<Id, Asset>();
    for (final Asset asset : firstArray) {
        final Id id = asset.getId();
        assetCache.put(id, asset);
    }

    for (final CountR countR : secondArray) {
        final Id countRId = countR.getId();
        final Asset asset = assetCache.get(countRId);
        if (asset != null) {
            // I supposed that it's int
            final int total = countR.getTot();
            asset.setTotaleRegistrazioni(total);
        }
    }

    return firstArray;
}

(I supposed that the Asset.id is unique in the array.) In this case you don't have to convert the second parameter to an array (just the first to a map). Maybe it worth playing with the initialCapacity and loadFactor parameters of the HashMap to avoid the resizing.


Reimplementing enumerate() to produce a sequence or iterator

First of, depending on the implementations, __builtin__ may not be directly available (it seems to be in IPyton, but not in CPython). You should import __builtin__ beforehand so __builtin__ will always be in the global namespace. CPython implementation also have __builtins__ (with an s) directly available without imports.

Second, you should remove the print statements in enumerate. I guess it was for demonstrations purposes but if you want to use that in real code it will be pure noise.

Other than that, I’d just add a docstring to enumerate to explain the new behavior.

However, since you are using Python 2, you can take advantage of some features that were removed in Python 3. Namely the difference between zip and itertools.izip. The former returns a list, the latter an iterator: pretty much what you’re after. And since enumerate is somewhat equivalent to zipping itertools.count with its parameters, it is very simple to achieve what you’re looking for:

from itertools import count, izip

def enumerate(iterable):
    zip_ = zip if hasattr(iterable, '__getattr__') else izip
    return zip_(count(), iterable)


IniReader template overrides become ambiguous

I wouldn't worry too much about temporaries (shouldn't they be optimized away?), but I think you're focusing on the smaller problem. You fundamentally have the following options:

Disambiguate by disallowing certain combinations, like you say you've currently done (readValue<T>(string, string), readValue<T>(string, string, T), and readValue<T>(string, string, int, T) but no readValue<T>(string, string, int))
Disambiguate by changing parameters to the function (this could be by reordering non-template parameters e.g. readValue<T>(string, string, T) vs readValue<T>(string, int, string, T), or by the readValue<T>(IniPath, T) approach you describe where you make it someone else's problem)
Disambiguate by changing function names, e.g. readValue<T>(string, string, T) vs. readIndexedValue<T>(string, string, int) (and of course readIndexedValue<T>(string, string, int, T))
Disambiguate by changing function names the other way, e.g. readValue<T>(string, string) and readValue<T>(string, string, int) vs readValueDefault<T>(string, string, T) and readValueDefault<T>(string, string, int, T).

My opinion is that the first is too likely to create a pit of failure. Just like when you tried to add a non-defaulted readValue<T>(string, string, int) without immediately realizing the problem of doing so, users of your functions are likely to make the same mistake on the consumption side (hey, I've got readValue(sFoo, sBar) but now I need sBar 1, 2, and 3...) and wonder why things are compiling but not working correctly.

The second is okay; making it someone else's problem is a really good approach for some scenarios. Merely reordering the parameters like I mentioned can result in funky APIs like the deprecated parts of CRegKey::QueryValue where the order of parameters results in wildly different overloads that make the API hard to remember. I don't know whether this one is that bad, but I'm still predisposed against it.

The third is my favorite. It's simple, clean, and makes it easier to figure out what this extra int parameter is. The fourth is about as good, depending on whether indexes or defaults are more "natural", and of course you can combine both bullet's approaches.

But that's not the end of the story.

The bigger problem is this: You're migrating from existing usage with working code. You have to consider what the damage is, how to detect it, and how to fix it. Ideal case is things magically work 100%. Next best, in my opinion, is each call site either works the same as it used to or results in a compile-time error. Worse is a series of call sites you have to update, will find a pattern to do so, but sometimes the pattern is wrong (a change to IniPath might result in this). Worst by a long shot is call sites that change their meaning without any warning (you might be stuck here anyway if your call sites are ambiguous enough).

So do you have any call sites that will change meaning, and if so how will you address this? That will help determine how you disambiguate your function.


My answer focuses on the ajax requests.

Why 4 requests at each 1500 milliseconds to the same file (play.php)?

I would do only one request and I would "cycle" on a delay starting from the success callback... instead of a fixed interval, which does not take the request delay in account.

var players = [ // No need to use a push method when you already know the array content.
  $('#p0'),
  $('#p1'),
  $('#p2'),
  $('#p3')
];

i=0;

function cyclePlayer() {

  $.ajax({
    url: "play.php",
    data: {iteration:i},
    method: "GET",
    dataType: "json",
    success: (data)=>{

      console.log(JSON.stringify(data));  // See all the infos in the same request response.
      json = JSON.parse(data);

      players[i].html(json.playerTurn).parents(".card-header").addClass('border-success');

      i = ++i % players.length;

      $('#deck').html(json.deckUpdate);
      $('#pile').html(json.pileUpdate);
      $('#feedback').html(json.feedbackUpdate);

      PlayerLoop = setTimeout(cyclePlayer,1500);    // From here, set a new 1500ms timeout.
    },
    error: ()=>{

    },
  });
}

// on load, start a timeout.
var PlayerLoop = setTimeout(cyclePlayer, 1500 );

$("#stop").click(function(){
    clearTimeout(PlayerLoop);
});

$('#reset').click(function() {
  location.reload(true);  // true is to reload from server instead of possibly loading from cache.
});

And the PHP:

<?php
require '../vendor/autoload.php';
session_start();
use Svc\Myapp\FrontHandler;

if(!isset($_GET['iteration'])){die();}

$myApp= new FrontHandler();

if(!isset($_SESSION['winner'])){
  $results["playerTurn"] = $myApp->playerTurn();
}
$results["deckUpdate"] = $myApp->deckUpdate();
$results["pileUpdate"] = $myApp->pileUpdate();
$results["feedbackUpdate"] = $myApp->feedbackUpdate();

$results["isSetWinner"] = isset($_SESSION['winner']);

// Echo the array as a json. This will be the response of the request.
echo json_encode($result);
?>

Now, I could not test the above... I hope It does not have any typo.


Assuming that you control over the value of the target attribute, I suggest to store the reference chain as a list of attribute names. Then you can easily resolve the reference without having to resort to eval-like meta-programming. A reduction would be ideal like you mentioned.

function referenceToObject(json, target)
{
 if (target === undefined)
  target = json.target;

 return target.reduce(referenceToObject.reductor, json);
}

referenceToObject.reductor = function(obj, attrib)
{
 return obj[attrib];
};

var example = {
 "target": ['first', 'second'],
 "first": {
  second: 'hi'
 }
};

console.log(referenceToObject(example));


How to make a program that lies one-third of the time?

The concept you have going is 'OK' (cumbersome, but for a beginner it's OK). There are two bugs, and one recommendation that will help a lot.

First the recommendation....

Change numLies to be a boolean value like: boolean canlie = true;

Then, your code becomes:

if(canlie && itsLieNum == 1){
    canlie = false;
    ....
} else {
    canlie = true;

This makes the purpose of the code more apparent. Also, a bug is that you have to declare this ourside your method. It should be a class-variable, not a method variable, otherwise it will always be the wrong value.

The bug you have is a technical one (but important that you learn) ... Random.nextInt(value) will never return the input value. It will retrun 0(inclusive) to value(exclusive). In your case, with nextInt(2) it will only ever return 0, or 1. Change that to be nextInt(3) and you will get the values 0, 1, or 2 and it will be 1 1 third of the time.


Hm, why did you write go as a separate function? It is - as you state - the same as recoveries, why the local definition?

For making it more succinct, I think it's easiest to have an intermediate data structure that carries both pieces of information you seek in the case: Whether there are enough digits and what number the digits so far would form.

The first data structure that comes to mind is a list of numbers - we just need to construct it. In this case, scanl is our friend:

import Data.List (scanl)
import Data.Char (digitToInt)

type Memoizable a = a -> a

recoveries :: Int -> Memoizable (String -> Int)
recoveries _ _    ('0':_) = 0
recoveries _ _    []      = 1
recoveries m self ss      = result `rem` 0xfaceb00c
  where result = case tail (scanl addDigit 0 ss) of
          (_:_:c:_) | c <= m  -> aCase+bCase+cCase
          (_:b:_)   | b <= m  -> aCase+bCase
          (a:_)     | a <= m  -> aCase
          _                   -> 0
        addDigit x c = x*10 + digitToInt c
        aCase = self (drop 1 ss)
        bCase = self (drop 2 ss)
        cCase = self (drop 3 ss)

Unless I've made a mistake (can't test), this should do the same as your code, and now we can write everything cleanly using pattern matches and a few guards on the intermediate list.

You could get rid of aCase, bCase and cCase as well if you would zip the result of scanl with tails ss. But while this is more general, I felt it would have made the code harder to understand, so I left it like this.


Performing data transportations in RxJS with Promises

I would be more inclined to map with the flatMap to have my results flow through.

Something like the following, might do what you're looking for.

return observable
  .flatMap(item => Observable.fromPromise(fs.readFile('./config.json'))
    .map(file => ({ config: JSON.parse(file.toString()), testResult: item })))
  .flatMap(({ config, testResult }) => Observable.fromPromise(getStudentIdFromStudentNumber(item.testResult['Student Primary ID']))
    .map(id => ({
      'Test Date': config.testConstants.ROGL_Begin_Year.testDate,
      'Student Id': id,
      'Student Number': testResult['Student Primary ID'],
      'Grade Level': testResult.Grade,
      'Composite Score Alpha': testResult['Composite Score']
    })));


It's a good start!  Here are some things that may help you improve your program.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).  In this particular case, I happen to think it's perfectly appropriate because it's a single short program that and not a header. Some people seem to think it should never be used under any circumstance, but my view is that it can be used as long as it is done responsibly and with full knowledge of the consequences.

Use <cstdlib> instead of <stdlib.h>

The difference between the two forms is that the former defines things within the std:: namespace versus into the global namespace.  Language lawyers have lots of fun with this, but for daily use I'd recommend using <cstdlib>.  See this SO question for details.

Use for loops rather than while loops where practical

Your gameloop routine can be simplified a bit by using a for loop rather than a while loop.  here is the current code:

void gameLoop() {
    auto quit = false;
    while(!quit) {
        // other stuff
        quit = shouldGameExit();
    }
}

I'd recommend writing it as a for loop to do several things.  First, it changes the scope of the quit variable to solely within the loop.  Second, it makes it clear how the exit condition is set:

void gameLoop() {
    for (auto quit = false; !quit; quit = shouldGameExit()) {
        // other stuff
    }
}

Don't use std::endl if you don't really need it

The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.

Check return values and handle errors

The code calls getline but never checks for error return values.  If getline encounters a problem, it sets the failbit.  It's easy to check for this in C++, because of operator overloading.  That is, one could do this:

getline(cin, input)
if (cin) {  // if getline was OK
    ///
}

Think of the user

Generally speaking, it's not unusual for users to type in faulty input.  For that reason, I think I would not throw an exception from with getUserChoice.  Instead of abruptly aborting the user out of the program, a friendlier way to do it would be to give the user a chance to correct the input.  Here's one way to rewrite that function:

Choice getUserChoice() {
    Choice userchoice;
    for (auto valid{false}; !valid; ) {
        cout << "Rock, paper or scissors? \n";
        string input;
        getline(cin, input);
        if (cin) {
            if(input == "rock" || input == "ROCK" || input == "1" || input == "r" || input == "R") {
                valid = true;
                userchoice = rock;

            } else if(input == "paper" || input == "PAPER" || input == "2" || input == "p" || input == "P") {
                valid = true;
                userchoice = paper;
            } else if(input == "scissors" || input == "SCISSORS" || input == "3" || input == "s" || input == "S") {
                valid = true;
                userchoice = scissors;
            } else {
                cout << "Sorry, I didn't understand \"" << input << "\"\n";
            }
        }
    }
    return userchoice;
}

Note that one could code a return instead of using the userchoice and valid variables, but I prefer having an easier-to-read program flow without having to hunt for return statements.  You can decide for yourself which flavor you prefer.

Make sure all paths return a value

The decideOutcomeOfGame routine returns the outcome of the game.  It's probable that all combinations are enumerated, but I'd prefer to make sure the function returns something every time.  Here's how I'd write it.

Outcome decideOutcomeOfGame(Choice userChoice, Choice botChoice) {
    if (userChoice == botChoice) {
        return draw;
    } else if ((userChoice == rock && botChoice == paper)
              || (userChoice == paper && botChoice == scissors)
              || (userChoice == scissors && botChoice == rock)) {
        return bot;
    }
    return user;
}

Consider using a better random number generator

You are currently using

auto randomNumber = rand() % 3 + 1;

Normally I recommend the use of the C++11 std::uniform_int_distribution to replace the old-style rand() but since you're using C++17, you could use std::sample.  This reduces the getBotChoice() function to this:

Choice getBotChoice() {
    constexpr static std::array<Choice,3> choices{ rock, paper, scissors };
    static auto rnd{std::mt19937{std::random_device{}()}};
    std::vector<Choice> botChoice;
    std::sample(std::begin(choices), std::end(choices), std::back_inserter(botChoice), 1, rnd);
    return botChoice.front();
}

There is now no need for the throw because the code will never generate an invalid return value.

Use std::string_view where practical

Rather than mutable strings, the global variables outcomeMap and choiceMap would be better expressed as a std::array of std::string_view.  In other words, instead of this:

string outcomeMap[3] = {"You win!", "Bot wins!", "It was a draw!"};

Write this:

constexpr array<string_view, 3> outcomeMap{"You win!", "Bot wins!", "It was a draw!"};

Consider encapsulating into a namespace

It doesn't seem as though these functions are going to be useful without each other.  Because they're so closely related (and related as well to the data), I'd recommend consolidating everything into a namespace.

Understand return 0 in main

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.  I advocate omitting it to reduce the clutter and let the compiler generate code; others prefer to write it explicitly.  It's up to you to choose which style you prefer, but either way you should know about this compiler behavior.

Simplify your code

The code currently contains this construct:

if(input == "no" || input == "NO" || input == "n" || input == "N" || input == "0") {
        return false;
    } else {
        return true;
    }

As @Deduplicator correctly notes in a comment, better would be to simply return the value of the expression which is already bool:

return !(input == "no" || input == "NO" || input == "n" || input == "N" || input == "0");


You can use itertools.groupby to group the items by order number.
Don't use is to compare numbers. is checks object identity and the same number can be represented by different objects:

>>> a=1234
>>> b=1234
>>> a is b
False
>>> a=12
>>> b=12
>>> a is b
True

Checking if len(orders) > 0 before the for loop is redundant. If the list is empty the loop won't run even once.

Revised code:

from itertools import groupby
from operator import itemgetter

# Fetch my orders
orders = repo.get_orders_for(self._customer[0])

for order_number, items in groupby(orders, key=itemgetter(0)):
    print("Order #{}".format(order_number))
    for _, quantity, pid in items:
        print("    Product #{}, ordered x{}".format(pid, quantity))


Evaluate parenthesis expression for correct nesting and matching parens

Use snake_case (matchParens)
You are checking a property, so I would name your function has_correct_parens to make it clearer that this function return True or False
[i for i in iterable] is a longer way of saying list(iterable) so plist = [l for l in pstring] should become plist = list(pstring)
The preventive check should be at the start for clarity and efficiency
What if you will want to use square / curly / triangular parens in the future? I would use constants:

OPEN_PAREN = '('
CLOSE_PAREN = ')'


Try this:

<?php
if(isset($_POST['submit'])){
    foreach ($_POST as $k=>$v){
        // use even and odd count to differentiate TRP and CPP
        if ($k != "submit") {
            // split the form input on _
            $input = explode("_", $k);
            echo "
Region: " . $input[0];
            echo "
Date: " . $input[2];
            if($input[1] == "value1"){
                echo "
Value 1: " . $v;
            }
            elseif($input[1] == "value2"){
                 echo "
Value 2: " . $v;
            }
         }
        echo "
";
     }
}
else {
    $date_array = Array("01/01/2012", "01/08/2012", "01/15/2012");
    $region_array = Array("NYC", "DC");
?>
    <form name="test_form" id="test_form" method="post" action="">

<?php
                foreach ($date_array as $date){
                    echo "".$date."	";
                }
?>

<?php
        foreach ($region_array as $region){
            echo "
";
            echo "".$region."	";
            foreach ($date_array as $date){
                echo '<input type="text" name='.$region."_value1_".$date.'><input type="text" name='.$region."_value2_".$date.'>	';
            }
            echo "
";
        }
?>

    <input type="submit" name="submit">
</form>
<?php
}
?>


Sending large data package with TCP - winsock

In both read and write you should leave the loop after an error (unless you have explicitly tested and fixed the error).

while(totalRecieved < readSize)
{
    dataRecieved = recv(socket, date + totalRecieved, readSize - totalRecieved);
    if (dataRecieved > 0)
    {
        totalRecieved += dataRecieved;
        continue;
    }
    if ((dataRecieved == -1) && (errno == EAGAIN || errno == EWOULDBLOCK))
    {
        // Simple error just try again.
        continue;
    }
    if (dataRecieved == -1 && errno == EINTR)
    {
        // An interrupt was received.
        // This is usually a signal by another thread to give up
        // but you can ignore it if you want.
        continue;
    }
    // Any other error is bad.
    // looping is just going to cause infinite loops.
    break;
}

if (totalRecieved < readSize)
{
    // BAD THINGS HAVE HAPPENED
}


Extracting citations of court documents in multiple languages

Always use 4 spaces for your indentation, you use; 3, 4, and 5. If you're one space out, then it can break your code, so it really does matter.

You're doing roughly the same for all your different regexes, and so you should loop through the regexes, with the common code in the loop.
However I'd change your common code to not replace de la or du, and to not need the try-except as you can check if gericht is truthy,
so it isn't indexed if it's None or an empty array.
Take:

REGEXES = [
    r"Beschwerde gegen [a-z]+ [A-Z][a-züöä]+ ([^\n\n]*)",
    r"Beschwerde nach [A-Za-z]. [0-9]+ [a-z]+. [A-Z]+ [a-z]+ [a-z]+[A-Za-z]+ [a-z]+ [0-9]+. [A-Za-z]+ [0-9]+ ([^\n\n]*)",
    r"Revisionsgesuch gegen das Urteil ([^\n\n]*)",
    r"Urteil des ([^\n\n]*)",
    r"ricorso contro la sentenza emanata il [0-9]+ [a-z]+ [0-9]+ [a-z]+ ([^\n\n]*)",
    r"recours contre l'arrêt ([^\n\n]*)",
    r"recours contre le jugement ([^\n\n]*)",
    r"demande de révision de l'arrêt ([^\n\n]*)",
]

def gericht(doc):
    for regex in REGEXES:
        gericht = re.findall(regex, doc)
        if gericht:
            return gericht[0]

However this is needlessly finding all items for the regex in the document, which is not what you want. You just want the first.
To do this without editing the regexes you could use itertools.chain and use re.finditer.
This can get you:

from itertools import chain

def gericht(doc):
    gericht = next(chain.from_iterable(re.finditer(r, doc) for r in REGEXES), None)
    if gericht is not None:
        return gericht.group(0)

You may be able to change this to merge all the regexes together with |, but then you won't prioritize the first regex over the others. Which may work with:

def gericht(doc):
    gericht = next(re.finditer('|'.join(REGEXES), doc), None)
    if gericht is not None:
        return gericht.group(0)

But I'm not too good with regexes.


Creating restrictions for a sprite's possible position on the screen

It is possible to refactor your code starting from the definition of your variables:

int maxX = screenWidth - image.getWidth()/2;
int minX = image.getWidth() / 2;
int maxY = screenHeight - image.getHeight()/2;
int minY = image.getHeight() / 2;

You are repeating function calls image.getWidth(), image.getHeight() and divisions by 2 in more than one definition, while you could call store functions calls results and  division results in other variables like below:

int width = image.getWidth();
int height = image.getHeight();
int minX = width / 2;
int minY = height / 2;
int maxX = screenWidth - minX;
int maxY = screenHeight - minY;

The other code you can simplify is the following:

if (x > maxX)
        this.x = screenWidth - image.getWidth();
    else if (x < minX)
        this.x = 0;
    else
        this.x = x - image.getWidth() / 2;
    // same behaviour of the above code
    if (y > maxY)
        this.y = screenHeight - image.getHeight();
    else if (y < minY)
        this.y = 0;
    else
        this.y = y - image.getHeight() / 2;

It is the same code applied one time to width and other time to height : you could define a helper function to be applied two times like below:

private int getNewCoordinate(int c, int l, int max, int min, int maxl) {
        if (c > max) { return maxl - l; }
        if (c < min) { return 0; }
        return c - l / 2;
}

Now if I haven't made confusion with some variable your original code can be written like this:

public void move(int x, int y) {
    int width = image.getWidth();
    int height = image.getHeight();
    int minX = width / 2;
    int minY = height / 2;
    int maxX = screenWidth - minX;
    int maxY = screenHeight - minY;

    this.x = getNewCoordinate(x, width , maxX, minX, screenWidth);
    this.y = getNewCoordinate(y, height, maxY, minY, screenHeight);
}

private int getNewCoordinate(int c, int l, int max, int min, int maxl) {
    if (c > max) { return maxl - l; }
    if (c < min) { return 0; }
    return c - l / 2;
}


Swift format string with separator every n characters where n changes

There is one small bug in your code, a two-character string is formatted with an initial dash:

print(format("12")) // -12

There are various ways to fix  that, e.g. by replacing the condition

$0.offset == count - 2 && count % 3 != 0

with

$0.offset == count - 2 && $0.offset % 3 == 2

Now some suggestions to simplify the code and make it more readable.
Instead of

unformatted.characters.enumerated().forEach {
     // ... use `$0.offset` and `$0.element` ...
}

I would use for ... in, so that we can give the loop variables names:

for (offset, char) in unformatted.characters.enumerated() {
     // ... use `offset` and `char` ...
}

There is no need to convert $0.element to a String because you can
append a character directly:

formatted.append($0.element)

There is also no need to call return at the end of the iteration block.

The condition

if $0.offset % 3 == 0 && $0.offset != 0 && $0.offset != count - 1 || $0.offset == count - 2 && $0.offset % 2 == 2

is quite complex, I would  split it into two conditions with if/else if.

Putting it all together, the function would then look like this:

func format(_ unformatted: String) -> String {

    var formatted = ""
    let count = unformatted.characters.count

    for (offset, char) in unformatted.characters.enumerated() {
        if offset > 0 && offset % 3 == 0 && offset != count - 1 {
            formatted.append("-")
        } else if offset % 3 == 2 && offset == count - 2 {
            formatted.append("-")
        }
        formatted.append(char)
    }

    return formatted
}

The condition whether to insert the separator at an offset is quite complex and
it is easy to make an error. A completely different approach would be
a recursive implementation, which is (almost) self-explaining:

func format(_ str: String) -> String {

    switch str.characters.count {
    case 0...3:  // No separators for strings up to length 3.
        return str
    case 4: // "abcd" -> "ab-cd"
        let idx = str.index(str.startIndex, offsetBy: 2)
        return str.substring(to: idx) + "-" + str.substring(from: idx)
    default: // At least 5 characters. Separate the first three and recurse:
        let idx = str.index(str.startIndex, offsetBy: 3)
        return str.substring(to: idx) + "-" + format(str.substring(from: idx))
    }

}

More suggestions:

Choose a different name instead of format() which indicates the purpose of the formatting.
Make the separator character a parameter of the function.