For each of the visitors, find if they were present within a time period: code is running slow

I think it is slow because your periods_breakdown is gigantic, and to fill each cell you have to compute its value.
But what you compute is whether each individual visit overlapped with each other visit, which is overkill.
If what you want is to know when there is two visits (or more) overlapping, but don't need to know which specific ones, you can simply count how many visits there are during each hour slot and you will know when there was an overlap because the count will be more than one.
Based on the data you provided :
import pandas as pd
data = pd.DataFrame({"start": [pd.Timestamp("2020-01-01 01:23:45"),
                               pd.Timestamp("2020-01-01 01:45:12")],
                     "end": [pd.Timestamp("2020-01-01 02:23:00"),
                             pd.Timestamp("2020-01-01 03:12:00")]})

NUMBER_OF_PERIODS = 6  # FIXME: use an upper bound
visitors_count_per_hour = [0] * NUMBER_OF_PERIODS

year_start = pd.Timestamp(year=2020, month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
for visit_start, visit_end in zip(data["start"], data["end"]):
    print(f"there was a visit between {visit_start} and {visit_end}")
    start_hour = visit_start.floor("H")
    end_hour = visit_end.floor("H")
    print(f"  in hours, it spanned from {start_hour} to {end_hour} included")
    visit_hours = pd.date_range(start=start_hour, end=end_hour, freq="1H")
    offset = len(pd.date_range(start=year_start, end=start_hour))
    print(f"  it started at period n°{offset}")
    for i, visit_hour in enumerate(visit_hours):
        print(f"  - so we count one person at hour {visit_hour}")
        visitors_count_per_hour[i + offset] += 1

print(visitors_count_per_hour)

periods_breakdown = pd.DataFrame()
for hour_index, visitor_count in enumerate(visitors_count_per_hour):
    slot_hour = year_start + pd.Timedelta(hours=hour_index)
    periods_breakdown["period" + str(hour_index)] = [slot_hour] + \
                                                    ([True] if visitor_count > 1 else [False]) + \
                                                    [visitor_count]

print(periods_breakdown)

which outputs
there was a visit between 2020-01-01 01:23:45 and 2020-01-01 02:23:00
  in hours, it spanned from 2020-01-01 01:00:00 to 2020-01-01 02:00:00 included
  it started at period n°1
  - so we count one person at hour 2020-01-01 01:00:00
  - so we count one person at hour 2020-01-01 02:00:00
there was a visit between 2020-01-01 01:45:12 and 2020-01-01 03:12:00
  in hours, it spanned from 2020-01-01 01:00:00 to 2020-01-01 03:00:00 included
  it started at period n°1
  - so we count one person at hour 2020-01-01 01:00:00
  - so we count one person at hour 2020-01-01 02:00:00
  - so we count one person at hour 2020-01-01 03:00:00
[0, 2, 2, 1, 0, 0]
               period0              period1              period2              period3              period4              period5
0  2020-01-01 00:00:00  2020-01-01 01:00:00  2020-01-01 02:00:00  2020-01-01 03:00:00  2020-01-01 04:00:00  2020-01-01 05:00:00
1                False                 True                 True                False                False                False
2                    0                    2                    2                    1                    0                    0

My result is slightly different than yours because my period0 is 2020-01-01 00:00:00 while you started at 01:00:00.
Speaking of performance, your algorithm will fill N*M cells, N being the number of visits, M being the number of slots in your data. With the values you provided (N=1000000 and M=6000), it is not surpising it slow.
My solution, by not comparing each visit with each other, only does roughly N+M computes, which is a whole algorithmic complexity class down.
I'm no expert of pandas, so there may a better way to write the code to do essentially the same thing. But if you want to have an even quicker program, maybe you can simplify your problem (find another algorithm) or make better use of pandas than me.


MVC API controller processing POST request

I'd certainly try to reduce the indentations, not in the least because in the case of if(ModelState.IsValid) it involves a 30-line block, and the else is just a single line. Also: if you're going to fail, do it fast.

But there are other issues to consider.

You expect an Exception to happen when you create or update a Boat? That seems odd.
I understand the GetBoat then AddNew vs Update logic, but I'd move that out of the Controller and into a Business layer. Keep your Controllers clean. Right now this is a fairly simply operation and already there are twenty or so lines. Just imagine the mess it'll become once you need to do more complicated operations.
I'm also a bit mystified by the logic WRT the update: you retrieve the boat and then you do BoatProvider.Update(boat); -- shouldn't you have done something with that boat first?
Most/all of your comments are superfluous. Comments shouldn't tell me what is happening (that's what your code your do), but why.


Calculate the sum over a list of minima of two vectors

Minimum calculation could be vectorized:

import numpy as np

def f(x, y):
    return 1 - np.minimum(x, y).sum()


increase the efficiency of a matching algorithm

1. The Hopcroft–Karp algorithm

The problem you're trying to solve here is to find a maximum matching in an unweighted bipartite graph. This can be solved in \$O(\sqrt V E)\$ by the Hopcroft–Karp algorithm.

Here's a sketch of how the Hopcroft–Karp algorithm works. Suppose that we have a bipartite unweighted graph, like the one you use as an example in the post:

Because it's bipartite, there are two sets of vertices which we'll call \$U\$ and \$V\$:

The Hopcroft–Karp algorithm works by repeatedly augmenting the matching, increasing the number of edges in the matching by one. Suppose that we have added one edge to the matching so far, between \$y\$ and \$2\$, drawn as a red edge:

The algorithm now searches for an augmenting path. This is a path that starts at an unmatched vertex in \$U\$, crosses to \$V\$ on an unmatched (black) edge, crosses back to \$U\$ on a matched (red) edge, and so on, finally ending in \$V\$. Here's an augmenting path, starting at \$x\$, following an unmatched edge to \$2\$, following a matched edge to \$y\$, and following an unmatched edge to \$3\$:

An augmenting path has an odd number of edges (because it starts in \$U\$ and finishes in \$V\$) and the edges along the path alternate between unmatched and matched. This means that if we swap all the edges along the augmenting path (matched becoming unmatched and vice versa), we get a new matching with one more edge, like this:

Now carrying on with the algorithm, there is another augmenting path, \$z\$–\$2\$–\$x\$–\$1\$:

Swapping the edges along this path, we increase the matching again:

Now there are no more augmenting paths (because there are no unmatched vertices in \$U\$) and we are done.

How do we find the augmenting paths? Well, we use a combination of breadth-first search and depth-first search. At each stage we do a breadth-first search to divide the vertices into layers according to their shortest distance from an unmatched vertex along an augmenting path. Suppose we are at this stage of the algorithm, where \$y\$ has been matched with \$2\$:

Now the breadth-first search divides the vertices into the following layers:

Using this structure, an augmenting path can be found efficiently (linear time) by a depth-first search that only follows edges from lower-numbered layers to higher-numbered layers.

2. Implementation

This is a direct translation of the pseudocode from Wikipedia into Python. To help with book-keeping, this implementation introduces a distinguished node nil, with all vertices being artificially matched with nil to start with. When there are no more augmenting paths ending at nil then we know the matching is maximal.

from collections import deque

def maximum_matching(graph):
    """Find a maximum unweighted matching in a bipartite graph. The input
    must be a dictionary mapping vertices in one partition to sets of
    vertices in the other partition. Return a dictionary mapping
    vertices in one partition to their matched vertex in the other.

    """
    # The two partitions of the graph.
    U = set(graph.keys())
    V = set.union(*graph.values())

    # A distinguished vertex not belonging to the graph.
    nil = object()

    # Current pairing for vertices in each partition.
    pair_u = dict.fromkeys(U, nil)
    pair_v = dict.fromkeys(V, nil)

    # Distance to each vertex along augmenting paths.
    dist = {}
    inf = float('inf')

    def bfs():
        # Breadth-first search of the graph starting with unmatched
        # vertices in U and following "augmenting paths" alternating
        # between edges from U->V not in the matching and edges from
        # V->U in the matching. This partitions the vertexes into
        # layers according to their distance along augmenting paths.
        queue = deque()
        for u in U:
            if pair_u[u] is nil:
                dist[u] = 0
                queue.append(u)
            else:
                dist[u] = inf
        dist[nil] = inf
        while queue:
            u = queue.pop()
            if dist[u] < dist[nil]:
                # Follow edges from U->V not in the matching.
                for v in graph[u]:
                    # Follow edge from V->U in the matching, if any.
                    uu = pair_v[v]
                    if dist[uu] == inf:
                        dist[uu] = dist[u] + 1
                        queue.append(uu)
        return dist[nil] is not inf

    def dfs(u):
        # Depth-first search along "augmenting paths" starting at
        # u. If we can find such a path that goes all the way from
        # u to nil, then we can swap matched/unmatched edges all
        # along the path, getting one additional matched edge
        # (since the path must have an odd number of edges).
        if u is not nil:
            for v in graph[u]:
                uu = pair_v[v]
                if dist[uu] == dist[u] + 1: # uu in next layer
                    if dfs(uu):
                        # Found augmenting path all the way to nil. In
                        # this path v was matched with uu, so after
                        # swapping v must now be matched with u.
                        pair_v[v] = u
                        pair_u[u] = v
                        return True
            dist[u] = inf
            return False
        return True

    while bfs():
        for u in U:
            if pair_u[u] is nil:
                dfs(u)
    return {u: v for u, v in pair_u.items() if v is not nil}


It can be made shorter:

public static void main(String[] args) {
    byte[] result = new byte[] {0x41, 0x42, 0x43, 0x44};
    byte[] multipled = new byte[result.length * 5];
    for (int i = 0; i < multipled.length; i++)
        multipled[i] = result[i % result.length];
    ...
}


Leetcode 38: The “count-and-say” sequence

Your iterative solution

This is generally fine, with the only exception that it operates on an array of strings –  I'll come back to that later.

Variables should be defined in the narrowest scope where they are used. This applies to

var temp: [String], j: Int

which are used only in the inner loop. Both variable names are non-descriptive and can be improved (e.g.: j actually counts the number of consecutive equal numbers).

Your recursive solution

Here

let arr = Array(str).map{Int(String($0))}

the conversion from str to an array is not needed: A Swift string is a collection of its characters, and you can call map() directly on the string. You also know that the string contains only decimal digits. Therefore you can force-unwrap here, replacing several force-unwraps in the following code:

let arr = str.map{ Int(String($0))! }

This

var final = temp.last!
final.count += 1
temp.removeLast()
temp.append(final)

is more simply and more efficiently done as

temp[temp.count - 1].count += 1

And this loop

var result = ""
for key in temp{
    result += "\(key.0)\(key.1)"
}
return result

can be simplified using map():

return temp.map { "\($0.count)\($0.val)" }.joined()

Generally, this looks less efficient to me than the first approach, because a string is converted to an integer array in each recursion step.

Redesign

In order to avoid unnecessary conversions between strings, characters, and integers, I would suggest to operate on an integer array generally, and create the string answer only as the final step.

Instead of an inner loop or recursion I would put the code to compute the next iteration into a separate function. That makes the code easier to read and to test:

class Solution {
    func countAndSay(_ n: Int) -> String {
        var seq = [1]
        for _ in 1..<n {
            seq = transform(seq)
        }
        return seq.map(String.init).joined()
    }

    func transform(_ seq: [Int]) -> [Int] {
        // ... TODO ...
    }
}

This works with both your solutions. For your first solution the transform function would be something like this:

func transform(_ seq: [Int]) -> [Int] {
    var result = [Int]() // The transformed sequence
    var current = seq[0] // The current number
    var count = 1 // Counts # of consecutive equal numbers
    for num in seq.dropFirst() {
        if num == current {
            count += 1
        } else {
            result.append(count)
            result.append(current)
            current = num
            count = 1
        }
    }
    result.append(count)
    result.append(current)
    return result
}

Instead of comparing against arr[i-1] the current number is “remembered” in a local variable, so that we can iterate over the sequence (without its first element) instead of iterating over the array indices.

Your second solution creates an array of (count, value) tuples first, and therefore does not need to handle the case of the last run separately. If you start with an empty array of tuples (and use optional chaining to compare against the last value) then you even don't have to handle the first value separately:

func transform(_ seq: [Int]) -> [Int] {

    var pairs: [(count: Int, val: Int)] = []
    for num in seq {
        if num == pairs.last?.val {
            pairs[pairs.count - 1].count += 1
        } else {
            pairs.append((count: 1, val: num))
        }
    }
    return Array(pairs.map { [$0.count, $0.val] }.joined())
}

In my tests this was a bit faster than your original solution, but slower than the first approach, probably because of the intermediate array.

A third solution

Here is another possible solution, which combines the advantages of both approaches. Instead of traversing the array elements, we directly search for the next index of a number different from the current. Neither the first nor the last run has be be treated specially:

func transform(_ seq: [Int]) -> [Int] {
    var result = [Int]()
    var fromIndex = seq.startIndex // Start index of current run
    while fromIndex != seq.endIndex {
        let current = seq[fromIndex]
        // Start index of next run:
        let toIndex = seq[(fromIndex+1)...].firstIndex(where: { $0 != current }) ?? seq.endIndex
        result.append(toIndex - fromIndex)
        result.append(current)
        fromIndex = toIndex
    }
    return result
}


LeetCode on Longest Palindromic Substring in Python

Disclaimer: Not a Code Reviewer
Here are some short comments though:

You're looping though twice.
That'd make it brute force.
Brute force does usually fail for some medium and hard questions on LeetCode.

Alternative Solution

Here we'd loop through once:

class Solution:
    def longestPalindrome(self, s):
        if len(s) < 1:
            return s

        def isPalindrome(left, right):
            return s[left:right] == s[left:right][::-1]

        left, right = 0, 1
        for index in range(1, len(s)):
            if index - right > 0 and isPalindrome(index - right - 1, index + 1):
                left, right = index - right - 1, right + 2
            if index - right >= 0 and isPalindrome(index - right, index + 1):
                left, right = index - right, right + 1
        return s[left: left + right]

Your Solution

I just tested your solution (marginally passes):

class Solution(object):

    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s) < 1:
            return s

        P = [[False] * len(s) for i in range(len(s))]

        for i in range(len(s)):
            P[i][i] = True

        for i in range(len(s) - 1):
            P[i][i + 1] = (s[i] == s[i + 1])

        for s_len in range(3, len(s) + 1):
            for i in range(len(s) + 1 - s_len):
                P[i][i + s_len - 1] = P[i + 1][i + s_len - 2] and (s[i] == s[i + s_len - 1])

        ip = 0
        jp = 0
        max_len = 1

        for i in range(len(s)):
            for j in range(len(s)):
                if P[i][j] and j + 1 - i > max_len:
                    max_len = j + 1 - i
                    ip = i
                    jp = j
                    continue

        return s[ip:jp + 1]

Since the runtimes is high, it's possible that it would fail sometimes.

I guess LeetCode has a time limit for each problem, maybe 10 seconds would be the limit for this specific problem.

Probably based on the geolocation/time, the runtime would be different also.

Just a bit more optimization:

Please see this line for j in range(i + 1, len(s))::

class Solution(object):

    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s) < 1:
            return s

        P = [[False] * len(s) for _ in range(len(s))]

        for i in range(len(s)):
            P[i][i] = True

        for i in range(len(s) - 1):
            P[i][i + 1] = (s[i] == s[i + 1])

        for s_len in range(3, len(s) + 1):
            for i in range(len(s) + 1 - s_len):
                P[i][i + s_len - 1] = P[i + 1][i + s_len - 2] and (s[i] == s[i + s_len - 1])

        ip = 0
        jp = 0
        max_len = 1

        for i in range(len(s)):
            for j in range(i + 1, len(s)):
                if P[i][j] and j + 1 - i > max_len:
                    max_len = j + 1 - i
                    ip = i
                    jp = j
                    continue

        return s[ip:jp + 1]

It reduces about 1 second but still not good.

I'm sure there are more ways to optimize.

Wait a bit! There are good Python reviewers here. Would likely help you out.

With some comments:
class Solution:
    def longestPalindrome(self, s):
        if len(s) < 1:
            return s

        def isPalindrome(left, right):
            return s[left:right] == s[left:right][::-1]

        # We set the left pointer on the first index
        # We set the right pointer on the second index
        # That's the minimum true palindrome
        left, right = 0, 1

        # We visit the alphabets from the second index forward once
        for index in range(1, len(s)):
            # Here we move the right pointer twice and once checking for palindromeness
            # We boundary check using index - right, to remain positive
            if index - right > 0 and isPalindrome(index - right - 1, index + 1):
                print(f"Step {index - 1}: Left pointer is at {index - right - 1} and Right pointer is at {index + 1}")
                print(f"Palindromeness start: {index - right - 1} - Palindromeness end: {index + 1}")
                print(f"Window length: {right}")
                print(f"Before: Left is {left} and Right is {left + right}")
                left, right = index - right - 1, right + 2
                print(f"After: Left is {left} and Right is {left + right}")
                print(f"String: {s[left: left + right]}")
                print('#' * 50)
            if index - right >= 0 and isPalindrome(index - right, index + 1):
                print(f"Step {index - 1}: Left pointer is at {index - right} and Right pointer is at {index + 1}")
                print(f"Palindromeness start: {index - right - 1} - Palindromeness end: {index + 1}")
                print(f"Window length: {right + 1}")
                print(f"Before: Left is {left} and Right is {left + right}")
                left, right = index - right, right + 1
                print(f"After: Left is {left} and Right is {left + right}")
                print(f"String: {s[left: left + right]}")
                print('#' * 50)
        return s[left: left + right]

Solution().longestPalindrome("glwhcebdjbdroiurzfxxrbhzibilmcfasshhtyngwrsnbdpzgjphujzuawbebyhvxfhtoozcitaqibvvowyluvdbvoqikgojxcefzpdgahujuxpiclrrmalncdrotsgkpnfyujgvmhydrzdpiudkfchtklsaprptkzhwxsgafsvkahkbsighlyhjvbburdfjdfvjbaiivqxdqwivsjzztzkzygcsyxlvvwlckbsmvwjvrhvqfewjxgefeowfhrcturolvfgxilqdqvitbcebuooclugypurlsbdfquzsqngbscqwlrdpxeahricvtfqpnrfwbyjvahrtosovsbzhxtutyfjwjbpkfujeoueykmbcjtluuxvmffwgqjgrtsxtdimsescgahnudmsmyfijtfrcbkibbypenxnpiozzrnljazjgrftitldcueswqitrcvjzvlhionutppppzxoepvtzhkzjetpfqsuirdcyqfjsqhdewswldawhdyijhpqtrwgyfmmyhhkrafisicstqxokdmynnnqxaekzcgygsuzfiguujyxowqdfylesbzhnpznayzlinerzdqjrylyfzndgqokovabhzuskwozuxcsmyclvfwkbimhkdmjacesnvorrrvdwcgfewchbsyzrkktsjxgyybgwbvktvxyurufsrdufcunnfswqddukqrxyrueienhccpeuqbkbumlpxnudmwqdkzvsqsozkifpznwapxaxdclxjxuciyulsbxvwdoiolgxkhlrytiwrpvtjdwsssahupoyyjveedgqsthefdyxvjweaimadykubntfqcpbjyqbtnunuxzyytxfedrycsdhkfymaykeubowvkszzwmbbjezrphqildkmllskfawmcohdqalgccffxursvbyikjoglnillapcbcjuhaxukfhalcslemluvornmijbeawxzokgnlzugxkshrpojrwaasgfmjvkghpdyxt")

Prints:
Step 18: Left pointer is at 18 and Right pointer is at 20
Palindromeness start: 17 - Palindromeness end: 20
Window length: 2
Before: Left is 0 and Right is 1
After: Left is 18 and Right is 20
String: xx
##################################################
Step 25: Left pointer is at 24 and Right pointer is at 27
Palindromeness start: 23 - Palindromeness end: 27
Window length: 3
Before: Left is 18 and Right is 20
After: Left is 24 and Right is 27
String: ibi
##################################################
Step 462: Left pointer is at 460 and Right pointer is at 464
Palindromeness start: 459 - Palindromeness end: 464
Window length: 4
Before: Left is 24 and Right is 27
After: Left is 460 and Right is 464
String: pppp
##################################################

Happy Coding! ( ˆ_ˆ )


Calculating optimal video capture card configuration based on channels needed

Your own answer is pretty good.  I would tighten it up a bit.  In particular,

It's not immediately clear, based on the variable name, what answer represents.  Furthermore, since you are only interested in Math.floor(channels/16), I would compute it in a more succinct and efficient way: var sixteens = channels >> 4;.
I don't like reassigning cards["US-HDVRC2-16-480D"] or recomputing remainder > 8.
To cast a boolean as 1 or 0, you can use the unary + operator.
Consider creating the cards object in a single statement.  That means you may get some members whose value is 0 — I don't know if that is acceptable to you.

function getCardObject(channels) {
    var sixteens = channels >> 4;   // Math.floor(channels / 16)
    var remainder = channels & 15;  // channels % 16
    return {
        "US-HDVRC2-16-480D": sixteens + (8 < remainder),
        "US-HDVRC2-8-240D": +(4 < remainder && remainder <= 8),
        "US-HDVRC2-4-120D": +(0 < remainder && remainder <= 4),
    };
}

For comparison, here's a single-expression version using explicit formulas for everything.  I don't think that it is better than what you have — it's certainly not easy to understand.

function getCardObject(channels) {
    return {
        // Use a 4-channel card if  1 <= (channels % 16) <= 4
        'US-HDVRC2-4-120D':  +(((channels - 1) & 15) <  4),

        // Use an 8-channel card if  5 <= (channels % 16) <= 8
        'US-HDVRC2-8-240D':  +(((channels - 1) & 12) == 4),

        // 16-channel cards for the rest
        'US-HDVRC2-16-480D': (channels >> 4) + ((channels & 15) > 8),
    };
}


Constructors - lots of paramters or none and use of set methods

It depends on whether the data elements are required for the object to be well defined or if they are completely optional.

My personal preference is for the constructor to have parameters for all the required data elements and use set methods for everything else.  I also declare the default (parameterless) constructor to be private.  That way the compiler guarantees that no one will create an incompletely defined object.

If firstname and lastname are required but address and phone number are optional, I would do the following:

private string _firstname;
private string _surname;
private Address _homeAddress;
private PhoneNumber _homeNumber;

private Person()
{
    // Ensure unitialized Person cannot be created
}

public Person(string firstname, string surname)
{
    _firstname = firstname;
    _surname = surname;
}

// getters and setters omitted for brevity

The disadvantage of using the Builder pattern as recommended in other answers is that the completeness check is deferred to runtime.  If you have a code path that is very rarely executed and you change Person so that more data is required, then you could deliver code that will fail in the field.  With my approach, you will know about the problem the next time you try to compile your code.


I guess you thought about avoiding of Thread.Sleep() method, not Wait() you mentioned in title. I can't test your code because I don't have either COM port nor motor. I would like to give you some general tips how to improve your code.
Let's implement some SOLID and DRY principles. I would start with class Motor which will represent your device. You can implement for example singleton class for this purpose. This helps you to separate your motor logic from other logic such is user interface. I can also imagine your port settings as a part of application configuration.

Motor.cs

public sealed class Motor : IDisposable
{
    public static readonly Motor Instance = new Motor();

    private Motor()
    {
        MotorPort = new SerialPort();
        MotorPort.PortName = "COM6";
        MotorPort.Handshake = Handshake.RequestToSend;
        MotorPort.ReceivedBytesThreshold = 8;
        MotorPort.DataReceived += new SerialDataReceivedEventHandler(dataRecievedHandler);
        MotorPort.Open();
    }

    public SerialPort MotorPort { get; private set; }
    public decimal Position { get; private set; }
    public void StopRotate()    { }
    public void StartRotate(string speed) { }
    public void MoveToPosition(int position) { }
    private void dataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
    {
    }
    public void Dispose()
    {
        if (MotorPort.IsOpen)
        {
            MotorPort.Close();
        }
    }
}

Instead of using global fields (M, buf), encapsulate them into object and set the proper access modifier or better create properties. Use meaningful names your fields and properties. Use Capitalization Convention.

You can isolate your repeating strings into separate static class to make your string constant repository which would be more easily maintainable against direct using of particular string.

StringConstants.cs

static class StringConstants
{
    public const string Prefix = "SR,00,002,";
    public const string PrefixCrLf = "SR,00,002\r\n";
}

Extension methods can simplify your code and make it more readable.

Extensions.cs

static class Extensions
{
    public static decimal GetDecimalOutput(this SerialPort port)
    {
        return decimal.Parse(Regex.Split(port.ReadLine(), StringConstants.Prefix)[1]);
    }
    public static void SendCommand(this SerialPort port)
    {
        port.WriteLine(StringConstants.PrefixCrLf);
    }
}

If you have implemented Motor.cs methods, you can use it or extend it.

Form1.cs

private void btnTest_Click(object sender, EventArgs e)
{
    Motor.Instance.StartRotate(speed);
    Thread.Sleep(5000);
    Motor.Instance.StopRotate();
    Motor.Instance.MoveToPosition(0);

    //read sensor
    serialPort2.SendCommand();
    decimal caliber = serialPort2.GetDecimalOutput();

    do
    {
        serialPort2.SendCommand();
        actualValue = serialPort2.GetDecimalOutput();
    }
    while (actualValue <= caliber);
}

I am not experienced in serial port programming, but I am pretty sure that event SerialPort.DataReceived should be used to invoke subscribed method as you do with your serialPort3. I don't know exactly why you are using Thread.Sleep(), because I cannot see getPosi(C); method.


Your indents could use a little work.
Typical JS use the collapsed braces or "egyptian braces", where the opening brace is on the same line as the opening statement.
Use template literals to construct strings.
Comments be their own line. That way, they're readable from the very start and don't run off to the right.
Do the "early return" pattern, where you return on invalid cases until you can assume validity. That way, you avoid deeply nested conditions.

Here's a more concise version:

server.em.addListener('hostGame', function(settings){

  // Get essential values. You can inline them, but I prefer putting them in
  // variables for clarity.
  const gameKeys = Object.keys(hostingGames);
  const gameUids = gameKeys.map(key => hostingGames[key].userId);
  const userHasGame = gameUids.includes(settings.userId);

  // The only time the code ever bails out is when the user has a game.
  if(userHasGame) return;

  // userHasGame can also be false if there are no games since gameKeys will
  // be empty, causing gameUids to be empty, causing includes to be false.

  // Otherwise, a game is created.
  const hostGame = new HostGame();
  hostGame.initialise(settings.userId, settings.userName, settings.boardSize, settings.gameMode, settings.gameNote);
  hostingGames[settings.userId] = hostGame;
  server.updateGamesList(hostingGames);

  server.consoleLog('APP', `${settings.userName} is hosting a game. ID: ${settings.userId}`);
});


Associative container

Update: Because of the O(n.log(n)) nature of std::map we have concluded this is not a good idea (But it was worth the test).

Rather than using a vector to store the count you can use an associative container.

std::vector<std::size_t> counts(max - min + 1, 0);

// replace with

using ValueType = std::iterator_traits<InputIterator>::value_type;
std::map<ValueType, std::size_t>  counts;

This will limit the amount of memory you use otherwise the amount of space you use could potentially exceed memory.
Also iterating over a sparse array would be expensive (As there will be lots of zero counts). By using an associative container you only iterate over valid values.

Range based for

Use the new range based for.

for (auto it_c = counts.begin(); it_c != counts.end(); ++it_c) {

// replace with:

for(auto const& value: counts) {

Combine range based for and associative containers

void counting_sort(InputIterator first, InputIterator last)
{
    using ValueType = std::iterator_traits<InputIterator>::value_type;
    std::map<ValueType, std::size_t> counts;

    for(auto value: boost::make_iterator_range(first, last)) {
        ++counts[value];
    }

    for(auto count: counts) {
        ValueType&   value = count.first;
        std::size_t& size  = count.second;
        std::fill_n(first, size, value);
        std::advance(first, size);
    }
}


Intersection of two sorted vectors in C++

Indentation

Your indentation is not consistent. This makes the code hard to read and maintain. It should be fixed so you don't give other people headaches.

    if(left < right){
    while(l < nums1.size() && nums1[l] == left )l++;
    }else while( r < nums2.size()  && nums2[r] == right )r++;

That is basically unreadable giberish (opinion of Martin).
Using namespace std; is super bad

This is mention in nearly every C++ review. There is a large article on the subject here: Why is “using namespace std” considered bad practice?. The second answer is the best in my opinion (Martin) see
Multiple declarations in one is bad (thanks to terrible syntax binding rules)

The one declaration per line has been written about adnausium in best practice guides. Please for the sake of your reader declare one variable per line with its own exact type.

The syntax binding rules alluded to above is:

int* x, y;   // Here x is int* and y in int
             // confusing to a reader. Did you really mean to make y an int?
             // Avoid this problem be declaring one variable per line

Typically, functions like this would be based on iterators to work on any container

Here your code is limited to only using vectors. But the algorithm you are using could be used by any container type with only small modifications. As a result your function could provide much more utility being written to use iterators.

The standard library was written such that iterators are the glue between algorithms and container.
It would be a lot simpler, if not necessarily more efficient at runtime, to just use some hash sets.
This function could be generic in T rather than assuming int.
The repeated conditions make me feel like there's simplification waiting here, although exactly what that is eludes me in the two minutes I'm spending on this.
Should take by const ref, not ref, so that you can operate on temporaries.


Querying a list of jobs on a server using EJBs

Your @Stateless service contains a shared state. It looks weird for me.
You never modify a state of jobs, you always create a new object

this.jobs = Collections.synchronizedSet(new HashSet<String>());

Could you please clarify why ?
From synchronization standpoint you have a race condition in setJobs method, so it should be synchronized.
Now, since your write operation (setJobs method) is protected by the intrinsic lock, all read operations should be also protected by the same lock to ensure data visibility. Make isJobCancelled synchronized too.


There are several thread safety issues :

if size(), remove() and removeAll() need to wait(), they will throw an IllegalMonitorStateException since they do not hold the lock on this at the time they call wait();
for that same reason, they may see stale values for isUpdating
if size() would be interrupted while waiting (supposing that gets fixed) its return statement would result in a NullPointerException.
while many threads may be waiting, only one will be notified when isUpdating is set to false again, since you call notify() instead of notifyAll()
operations such as contains() and isEmpty() may see stale values since they are not properly synchronized.
when interrupted all overridden methods violate the Set contract.
the interrupted flag is cleared upon interruption since the InterruptedException is caught and the state is not set to interrupted again.
not strictly a problem, but you synchronize on this. This means third party code locking on your Set will influence its behavior. It is preferrable to lock on a private Object.

I'm not sure what you mean exactly by 'proper size'.

Also, I think that if you properly implement this, you'll basically end up with the same behavior as what you'd get from Collections.synchronizedSet(new LinkedHashSet())


C++ Fixed-size general-purpose thread pool

Ensure the mutex is locked when changing should_terminate_m

In the destructor, you should hold the mutex locked while changing should_terminate_m. It may work as it is in this particular case, but in general, if you hold a mutex while accessing a variable anywhere in the code (it's held in thread_loop() while reading it), you should hold the mutex everywhere you access it. This avoids unexpected behavior.

Stick with either std::unique_lock or std::scoped_lock

You use both types of locks in the code. While functionally it should be perfectly fine, it's weird to mix these two. Be consistent and use only one of them. I recommend sticking with std::scoped_lock if you don't mind not being compatible with pre-C++17 compilers.

Issues with wait()

One issue I see is that in order to support the wait() member function, you have a reference counter busy_m, and you have to notify the condition vairable pool_cv_m every time a task finishes. This adds overhead even if nothing is actually calling wait(), but more importantly, because you use main_thread_cv.notify_one(), if multiple threads are calling wait(), then the notification might go to the wrong thread.

Another issue is that if jobs are enqueued often enough that the queue is never empty, wait() never returns, even though all jobs that were enqueued before wait() was called did finish.

You could indeed make it explicit that only the main thread is allowed to enqueue jobs and call wait(), but that might limit the usefulness of this thread pool somewhat.


Writing input into separate arrays and an output file

It's a good idea to order your STL #includes either alphabetically or by groups (see this answer for more details).  Header files should also precede STL #includes to avoid dependencies.
I'd give your IO files more accurate names (such as inFile and outFile).
Include <cstdlib> for EXIT_FAILURE.
This is C++ and not C, so use std::size_t instead of size_t.
Put the std::vector declarations (A1, B1, C1) on separate lines.
You don't have to create another size variable for A1.size() just for a loop.

In that same loop: you're looping through all three arrays at once, but are using one vector's size to do that.  That's a bad idea.  If they happen to be different sizes, you're going to run into problems.
This:

int n1 = sub(n, &A1[0], &B1[0], &C1[0]);

is best written as this (with iterators):

int n1 = sub(n, A1.begin(), B1.begin(), C1.begin());


Convert an integer to its Roman numeral equivalent

Using the tuples for the list, is this good practice, or would a dict have worked better?

Yes, in this case I think it's ok. Alternative is using orderdict or dict but sorting it by value which is not that good.

Now to make it work faster you can use division and multiplication. So it will look like this:

def convert_to_roman(number):
    """ Convert an integer to Roman
    >>> print(convert_to_roman(45))
    XLV """
    roman_numerals = []
    for numeral, value in ROMAN_NUMERAL_TABLE:
        count = number // value
        number -= count * value
        roman_numerals.append(numeral * count)

    return ''.join(roman_numerals)


My take at ProjectEuler #17 - counting counting characters

A matter of priorities

Make it work, make it right, make it fast : at the moment, your code does not work in that sense that it does not give the solution to the project euler problem.

Nevertheless, I'll try to give you hints to rewrite your code in such a way that it returns the same results as it does currently but in a better way.

In order to do so, I've written a few assertions to be more confident when I perform changes.

assert number_let_count(5) == 19  # given by project euler
assert number_let_count(100) == 864  # found by running your code
assert number_let_count(345) == 6178  # idem
assert number_let_count(1000) == 21077  # idem and we know this result is wrong

Style

You code looks mostly good. Something that I find really confusing (and so does my text editor) is the fact that you named your variable int : i would probably be better.

Then, the logic can be rewritten by removing a level of nesting in the ifs using elif.

Here is what I have at this point :

def number_let_count(n):
    sum_let = 0
    numbers = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine',
               10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'
               ,20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred'}
    for i in range(1,n+1):
        if i in numbers and i != 100:
            sum_let += len(numbers[i])
        elif i in range(21,100):
            sum_let += len(numbers[(i//10) * 10]) + len(numbers[i % 10])
        elif i in range(100,1000):
            if i % 100 == 0:
                sum_let += len(numbers[(i//100)]) + len(numbers[100])
            else:
                sum_let += len(numbers[(i//100)]) + len(numbers[100]) + len('and') + len(numbers[((i % 100)//10) * 10]) + len(numbers[(i % 100) % 10])
    return sum_let

Making debugging easier

Now that you know that your code is wrong, you might as well try to make it easier to debug. My suggestion is to work with strings until the very last moment so that you can print it whenever you need. At the end, you just need to get the length of the string and you are done.

def number_let_count(n):
    numbers = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine',
               10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'
               ,20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred'}
    ret = ""
    and_ = "and"
    for i in range(1,n+1):
        if i in numbers and i != 100:
            ret += numbers[i]
        elif i in range(21,100):
            ret += numbers[(i//10) * 10] + numbers[i % 10]
        elif i in range(100,1000):
            if i % 100 == 0:
                ret += numbers[(i//100)] + numbers[100]
            else:
                ret += numbers[(i//100)] + numbers[100] + and_ + numbers[((i % 100)//10) * 10] + numbers[(i % 100) % 10]
    return len(ret)

This is making your code slower (performing string concatenations instead of additions) but you shouldn't be able to notice this because we are working with pretty small values. Also, this is a first step for an actual optimisations to be performed once it works : you just need to replace whatever involves string with their length variant :

def number_let_count(n):
    numbers = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine',
               10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'
               ,20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred'}
    numbers = {i:len(s) for i,s in numbers.items()}
    ret = 0 # ""
    and_ = len("and")
    for i in range(1,n+1):
        if i in numbers and i != 100:
            ret += numbers[i]
        elif i in range(21,100):
            ret += numbers[(i//10) * 10] + numbers[i % 10]
        elif i in range(100,1000):
            if i % 100 == 0:
                ret += numbers[(i//100)] + numbers[100]
            else:
                ret += numbers[(i//100)] + numbers[100] + and_ + numbers[((i % 100)//10) * 10] + numbers[(i % 100) % 10]
    return ret

Here, 'len' is called only a few times.

I'll keep on working on the "slow" versions because it is a better starting point for your investigations but you know what you can do when it works.

Rewrite interval checks

Computing if i in range(100, 1000) is slow because we'll compare i to many values. What you want to know if just if i is bigger than 100 and (stricly) smaller than 1000. Python has a cool way to write this (you won't find this in all programming languages) : if 100 <= i < 1000.

for i in range(1,n+1):
    if i in numbers and i != 100:
        ret += numbers[i]
    elif 21 <= i < 100:
        ret += numbers[(i//10) * 10] + numbers[i % 10]
    elif 100 <= i < 1000:
        if i % 100 == 0:
            ret += numbers[(i//100)] + numbers[100]
        else:
            ret += numbers[(i//100)] + numbers[100] + and_ + numbers[((i % 100)//10) * 10] + numbers[(i % 100) % 10]

Now, the first check begs to be rewritten as a range check too. A cool thing to notice is that cases such as forty as properly handled by ret += numbers[(i//10) * 10] + numbers[i % 10] because the second term will correspond to "". For that reason, we can simply write : if 0 < i <= 20.

Then successive range checks do not make that much sense : it is probably not interesting checking if i is bigger than 21 if we know it is stricly bigger than 20. Similarly for 100.

Then, the whole logic can be rewritten (adding some logs you might find useful):

for i in range(1,n+1):
    if i < 1:
        print("Oops, did not handle", i)
    elif i <= 20:
        ret += numbers[i]
    elif i < 100:
        ret += numbers[(i//10) * 10] + numbers[i % 10]
    elif i < 1000:
        if i % 100 == 0:
            ret += numbers[(i//100)] + numbers[100]
        else:
            ret += numbers[(i//100)] + numbers[100] + and_ + numbers[((i % 100)//10) * 10] + numbers[(i % 100) % 10]
    else:
        print("Oops, did not handle", i)
return len(ret)

Divisions and modulos

Isn't it a pain to have to perform to operations to have the quotient and the remainder of a division ? It is not anymore with the pretty cool divmod

for i in range(1,n+1):
    if i < 1:
        print("Oops, did not handle", i)
    elif i <= 20:
        ret += numbers[i]
    elif i < 100:
        tens, units = divmod(i, 10)
        ret += numbers[10 * tens] + numbers[units]
    elif i < 1000:
        hundreds, units = divmod(i, 100)
        if units:
            tens, units2 = divmod(units, 10)
            ret += numbers[hundreds] + numbers[100] + and_ + numbers[10 * tens] + numbers[units2]
        else:
            ret += numbers[hundreds] + numbers[100]
    else:
        print("Oops, did not handle", i)

Another hint for one of the bugs

Try to see how "119" gets converted to a string.


SQL server efficiency, comparing date time of latest record and the one under it

Aliasing
The use of T and T1 as aliases in this query made me take twice as long to work out what it is actually doing. I would give these a more meaningful alias.
Brackets
The Where clause contains this:
AND (controllerID in(2,13,28,30,37,40))

The brackets around this are unnecessary and a little confusing. I would only recommend brackets in the Where clause when you are using both AND and OR.
Removing a select
Firstly, let's ask ourselves what this query is doing.
Step 1, get the controllerID's and MAX(dtReading)'s from the ReaderData table.
Step 2, do a datediff of the MAX(dtReading) and the next highest dtReading.
First lets write a simple query to do step 1:
SELECT
    base.controllerID,
    MAX(base.dtReading) AS [Most Recent Reading Date]
FROM ReaderData AS base
WHERE base.CardID = 'FFFFFFF0'
AND base.controllerID IN (2,13,28,30,37,40)
GROUP BY base_data.controllerID

Now let's bring in the second dtReading:
SELECT
    base.controllerID,
    MAX(base.dtReading) AS [Most Recent Reading Date],
    prior.[Prior Reading Date]
FROM ReaderData AS base
OUTER APPLY
(
    SELECT MAX(extra.dtReading) AS [Prior Reading Date]
    FROM ReaderData AS prior
    WHERE prior.CardID = base.CardID
    AND prior.controllerID = base_data.controllerID
    AND prior.dtReading < base_data.Max_dtReading
) AS prior
WHERE base.CardID = 'FFFFFFF0'
AND base.controllerID IN (2,13,28,30,37,40)
GROUP BY base_data.controllerID

You'll notice that I changed the CardID = 'FFFFFFF0' and controllerID IN (2,13,28,30,37,40) in the apply to check if it is equal to the value in the main select. It is easier to understand this way, you want to make sure that they are equal, plus it lets you avoid the possible mistake of forgetting to update of the sets of values.
Then we add the datediff:
SELECT
    base.controllerID AS [Controller ID],
    DATEDIFF(SECOND,MAX(base.dtReading),prior.[Prior Reading Date]) AS [Elasped Time]
FROM ReaderData AS base
OUTER APPLY
(
    SELECT MAX(extra.dtReading) AS [Prior Reading Date]
    FROM ReaderData AS prior
    WHERE prior.CardID = base.CardID
    AND prior.controllerID = base_data.controllerID
    AND prior.dtReading < base_data.Max_dtReading
) AS prior
WHERE base.CardID = 'FFFFFFF0'
AND base.controllerID IN (2,13,28,30,37,40)
GROUP BY base_data.controllerID

Here I took the liberty of aliasing the returned columns to make them a little easier on the eye for the end user, as well as capitalising keywords.
There is no agreed upon standard to SQL, so feel free to re-lowercase everything, but conventionally SQL is written with keywords in ALL CAPS
Performance Increases
The query I walked through above should perform better than the one in the question as it avoids the sub-select.
I would make sure that the ReaderData table is properly indexed, this can and will drastically speed up queries and make sure that the statistics on the table are up to date.


public IDictionary<Type, IFormatProvider> FormatProviders { get; set; }

This is bad. Having a public setter for the dictionary will let a user of that code pass in null resulting in the Format() method throwing a NullReferenceException.

You don't check the passed in parameters of the Format() method if they are valid. By omiting the validation of the arguments you are exposing implementation details for the case they aren't valid. E.g if the passed object arg is null then the call to arg.GetType() will throw and exposes that you are requesting the type of that object.

You only want to show the user that the passed in arguments are invalid, but you shouldn't let the code do it for you.


Inheriting from collections is rarely a good practice. In your case it's better to have a private collection (SortedDictionary in your case), and populate it as needed (in other words it's better to use delegation than inheritance here).

The reason why inheriting is not so good here is that your class will expose a lot of functionality that users of RestaurantData aren't actually interested in.


Encoding and decoding in Haskell -- 99 Problems exercise 13, 14

The general idea, which is to use group and Data.List.group and replicate, is right.  Your implementation is a bit verbose, though.

The top-level functions (encode, decode, and main) should have type signatures.  You didn't write one for main :: IO ().  The inner functions, though, don't need type signatures, since the compiler can infer their types.

Avoid nesting parentheses.  All of your nested parentheses could be written with $ instead.  For example:

print $ decode $ encode "Mississippi"

I don't think you need so many helper functions.

Both encode and decode could be written in point-free style.

Writing decode = foldl (++) "" (map replicateChars (map fromEncoding encodings)) is too complicated.  concatMap would do the trick.

import Data.List (group)

data Encoding = Multiple Int Char | Single Char deriving (Show)

encode :: String -> [Encoding]
encode = map toEncoding . group
  where
    toEncoding (c:[]) = Single c
    toEncoding group  = Multiple (length group) (head group)

decode :: [Encoding] -> String
decode = concatMap fromEncoding
  where
    fromEncoding (Single char)       = [char]
    fromEncoding (Multiple num char) = replicate num char

main :: IO ()
main = do
    print $ decode $ encode "Mississippi"


The String class can do this already, see answer here: https://stackoverflow.com/a/391978/4217399. You can always look at the source of the String class to check how it's done, should be fairly optimized there, as it's a part of the JDK. It's actually offloaded to the java.util.Formatter class.


Nested switch to return configuration for combination of 3 database types and 4 domains

Just declare a (static readonly) dictionary:

var values = new Dictionary<(DatabaseType, DomainType), DatabaseConfigType>()
{
    { (DatabaseType.Type1, DomainType.Domain1), DatabaseConfigType.Type1Domain1 }
};

Filled with all possible combinations. Then your function will be reduced to:

DatabaseConfigType GetDatabaseConfiguration(DatabaseType database, DomainType domain)
    => values[(type, domain)];

You may want to use TryGetValue() to customize error message or to throw a different, more informative, exception. I'm using C# 7 named tuples but you can do it without them, it's just little bit more verbose because you need to declare your own Tuple because we need it to be a struct unless you use a custom comparer.

Edit: what if you need custom error messages (saying which part is unknown)? You need to nest dictionaries:

var values = new Dictionary<DatabaseType, Dictionary<DomainType, DatabaseConfigType>>()
{
    {
        DatabaseType.Type1, Dictionary<DomainType, DatabaseConfigType>
        {
            { DomainType.Domain1, DatabaseConfigType.Type1Domain1 }
        }
    }
};

In this case to get a value:

DatabaseConfigType GetDatabaseConfiguration(DatabaseType database, DomainType domain)
{
    if (values.TryGetValue(database, out var configTypes))
    {
        if (configTypes.TryGetValue(domain, out var configType))
            return configType;

        throw new ArgumentException($"Unknown domain {domain} for {database}");
    }

    throw new ArgumentException($"Unknown database {database}");
}

Which exception should be thrown? Assuming you can change this part of the code contract I feel ArgumentOutOfRangeException is not the appropriate one in this case (POLA?). Some combinations aren't allowed, an enum may have an invalid value (GetDatabaseConfiguration((DatabaseType)333, (DomainType)444)) or you may simply forgot to update this function after an update to the enum.
In my opinion a generic ArgumentException may be enough (unless you want to differentiate the invalid combination case). A specific exception exists (InvalidEnumArgumentException) but I seldom saw it in real-world code (probably because it doesn't add much value over ArgumentException).

Assuming you changed names but not style then DOMAIN_1 isn't a good name because it doesn't follow common C# naming conventions: it's all uppercase and it uses underscore as separator, it should be Domain1.


ServiceLocator for easy and central access to replaceable parts

You have some clean looking code there, but there's a huge problem with Service Locators. They're hidden dependencies. If I reference your class from elsewhere, I'm going to be really confused about the exceptions I'm going to get when I try to use it.

  Where is this null EmailService exception coming from?! WTF???

It's much better to use proper constructor injection of dependencies. That makes it crystal clear what is needed to make your class work.


Re-arranging data on a worksheet based on contents of Column A

Your nesting ifs have things in common, so you can restructure it
Option Explicit
Public Sub FixAbstracts()
    Dim lastRow As Long
    lastRow = Cells(Rows.Count, 1).End(xlUp).row
    Dim i As Long
    Dim rowCount As Long
    Dim isEmptyCell As Boolean

    For i = lastRow To 2 Step -1
        isEmptyCell = IsEmpty(Cells(i, 1))
        If isEmptyCell Then
            rowCount = Application.CountA(Rows(i))
            If rowCount > 0 Then Cells(i, 1).Delete xlshift:=xlToLeft
            If rowCount = 0 Then Rows(i).Delete
        ElseIf Not IsNumeric(Cells(i, 1)) Then
            Cells(i - 1, 13) = Cells(i, 1)
            Cells(i, 1).Delete xlshift:=xlToLeft
        End If
   Next i
End Sub

Now you have a For loop so no need to increment i.
It also steps backwards bottom to top so nothing is skipped. If you delete row(10) and go to the next row, the original row(11) is skipped. That's a result of the For loop, but it prefer it much to a Do While.

Is it empty?
We also declared a boolean to check for empty so it's only done once per loop. Now we base our if on that to reduce multiple checks.
So now the logic is

empty? Yes? Count the row. Now do something
empty? No? is it a number by itself? Yes? Do something

Is it a number?
Let's look at the logic of yours

is it a number? yes? goto next iteration
is it a number? no? is it empty? yes? Do something
is it empty? yes? count the values in the row = 0 then do something
is it empty? yes? count the values in the row > 0 then do something

See the reduction? We get rid of the initial isnumeric because the loop will iterate by itself. We also check for empty only once and we only count once.
Not to mention your code is very difficult to follow.
If Application.WorksheetFunction.IsNumber(Rng.Value) = True Then
    i = i + 1

ElseIf IsNumeric(Rng.Value) = False And Application.WorksheetFunction.CountA(Rng) = 1 Then
    Rng.Copy Destination:=Rng.Offset(-1, 13)
    Rng.Delete Shift:=xlToLeft
ElseIf IsEmpty(Rng) = True And Application.CountA(row) > 0 Then
    Rng.Delete Shift:=xlToLeft
ElseIf IsEmpty(Rng) = True And Application.CountA(row) = 0 Then
    row.Delete

Else: Stop
End If

I had to reread this a bunch of times and I'm still not sure if I'm doing all the checking you are. You aren't consistent with how you're checking for a numeric value, you use a worksheet function and the vba function, there's probably no need to use the worksheet function if your data is standardized.
There's also no need to check if something like isempty = true as the result of isempty is either true or false.


A fold isn't a great fit for this problem, they don't support any sort of pushback so you'd have to get fancy with the accumulator value and it certainly wouldn't get any prettier.

Tail recursion isn't an important concept in Haskell ([1], [2], &c). If you have a specific performance concern feel free to bring it up, but I don't see any particular reason to think your function is more likely to blow the stack than any other.

I can't come up with any appreciably simpler solutions than yours, but you might like this version which has more reusable components.

redistributeIn :: [(a, b)] -> Maybe (a, [(b, a)], b)
redistributeIn []             = Nothing
redistributeIn xs@((a0, _):_) = (a0, insides xs, b0)
  where
    (_, b0) = last xs

    insides ((_, b):xs@((a, _):_)) = (b, a) : insides xs
    insides _                      = []

redistributeOut :: (a, [(b, a)], b) -> [(a, b)]
redistributeOut (a0, xs, b0) = outsides a0 xs b0
  where
    outsides a_i ((b_i, a_j):xs) b_z = (a_i, b_i) : outsides a_j xs b_z
    outsides a   []              b   = (a  , b  )

merge :: [(Int, Int)] -> [(Int, Int)]
merge [] = []
merge xs = redistributeOut . second (filter (not . adjacent)) . fromJust . redistributeIn $ xs
  where
    second f (a, b, c) = (a, f b, c)

    adjacent (a, b) = a + 1 == b


Here are a few changes that make image generation near instant, and slightly speed up root generation, and lower memory overhead.

def roots(n): # given n, returns a Littlewood polynomial with coefficients representing the binary representation of n
    return np.polynomial.polynomial.polyroots([int(i)*2-1 for i in bin(n)[2:]])

The only change here is to just return the roots rather than messing with them, so we pass less data around.

x, y = [], []
for i in range(0,2**16):
    if i%10000==0:
        print(i)
    root = roots(i)
    x.extend(np.real(root))
    y.extend(np.imag(root))

Here I removed temp to halve memory use, and used vectorization where applicable for small speed boosts.
the major changes are in the image generation

hot = np.asarray(128*cm.hot(normal_histogram)[:,:,0:3], dtype=np.uint8)
im = Image.fromarray(hot, mode="RGB")
spectral = np.asarray(128*cm.nipy_spectral(normal_histogram)[:,:,0:3], dtype=np.uint8)
im2 = Image.fromarray(spectral, mode="RGB")
im.show()
im2.show()

here, rather than making a blank image and filling it bit by bit, we make an image from an array created using vectorization. This takes 3 seconds with gap = 0.001 instead of over 16 times that before. This is far from optimized, vectorizing roots would help a lot, but that is hard.


You've erred many times in the above code. However, that means you get to learn a lot about how to properly interact with the DOM. In many instances, there are built-ins that quickly and efficiently get the job done.

First off, you're incorrectly accessing the body. document.body is a well-supported reference to the body that's been around since at least DOM Level 1.

Secondly, you're taking the hard route towards creating an array. In his book, "JavaScript: The Good Parts", Douglas Crockford insists on using literals instead of constructors. In this case, an array literal is []. This is an easier way of calling new Array().

Thirdly, you're incorrectly iterating over the cdn array with a for...in loop instead of a for loop. A for...in loop is meant for objects as it iterates over the properties of an object. Not only is it slower than a normal for loop, but it also is very susceptible to prototype modification. For example, try running this code with a build of MooTools (jsFiddle has one enabled by default):

for(var key in [])
{
    console.log(key);
}

You'll get a ton of hits because MooTools modifies the Array prototype. You'd have to do a hasOwnProperty check for each property just to avoid those pitfalls. Avoid for...in on anything but objects.

Next, declaring the i variable inside of the for...in loop gives the illusion of block scope. This isn't the case, since i is available anywhere in the function after it's been defined. Only functions have scope in JavaScript. Here are Crockford's thoughts via "...The Good Parts" (page 102):

  In most languages, it is generally best to declare variables at the first site of use. That turns out to be a bad practice in JavaScript because it does not have block scope. It is better to declare all variables at the top of each function.

Finally, setting the attributes for each script tag isn't necessary. Since you're already interacting with the DOM, setting their cousin, the DOM property is a better idea. The DOM provides shortcuts to node properties and is more stable than setting attributes. get/set/removeAttribute all have the unfortunate shortcoming of being very weird in various Internet Explorer builds. They're best avoided unless completely necessary.

Fixed + optimized:

function async_init() {
    var element;
    var parent = document.body;
    var cdn = ["http://code.jquery.com/jquery-1.6.2.js", "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"];
    var i = 0, file;
    for (i;i<cdn.length;i++) {
        file = cdn[i];
        element = document.createElement("script");
        element.type = "text/javascript";
        element.src  = file;
        parent.appendChild(element);
        //free file's value
        file = null;
    }
    /*
    * Cleanup at end of function, which isn't necessary unless lots of memory is being
    * used up.
    * No point nulling a Number, however. In some ECMAScript implementations
    * (ActionScript 3), this throws a warning.
    */
    //empty array
    cdn.splice(0, cdn.length);
    //clear variable values
    element = null;
    parent = null;
    cdn = null;
}

Also note that since you're adding these scripts asynchronously, there's no stable way to detect when the file has loaded, short of a script loader or a timer (my opinion is neither are stable).

An alternative is to use document.write to append these scripts synchonously. However, you'll have to use a DOMString and escape the forward slash in the script's end tag. This will append it to the end of the body tag.

Example: document.write("<script type=\"text/javascript\" src=\"\"><\/script>");

Note that the backslash character (\) escapes characters in JavaScript. I've used it to escape the double quotes for each attribute along with the forward slash in the end tag.

If you have any more questions regarding JavaScript or the DOM, feel free to ask in the comments.

-Matt


The code is rather clear, so consider the following to be nitpicks.

I'd say that you are generating a new key stream from the key. I'd certainly not reuse the key variable.

The first i = 0 before the loop seems spurious.

Using i as a counter is well understood, and I'd not worry overly much on the style of it. You are probably the only one who cares if it is really Ruby-esk; developers down the line will understand it.

What I wonder though is that you run your loop length times, but there is a break that seems to trigger before that. That's not all too clear to me.

I wonder what happens if you supply it an "empty" key string. Some guard statements may be in order.

Same for the curly braces. It's clear as it is, choose whatever you want. Personally I slightly favor the braces.

You could consider creating a mod function, however since % is already the modulus, which will never return a negative value if the right value is positive, it seems to me that removing the + 26 is probably the only thing you need to change (during decryption).

Instead of using 26 as unexplained magic value, you should get the size of the LETTERS range instead. That way you can also expand your ciphertext later.

I've got no opinion on the private_class_method as I'm not a Ruby developer (I'm specialized in knowing many languages / constructs and of course applied crypto).


A hash cracker for Python 3.0 and up (module)

This can be shortened:

self.charset = charset
...
charset = ""
charsets = {"L": ascii_lowercase,
            "U": ascii_uppercase,
            "D": digits}
for key in self.charset:
    charset += charsets[key]
self.charset, charset = charset, None

To:

charsets = {"L": ascii_lowercase,
            "U": ascii_uppercase,
            "D": digits}
self.charset = ""
for key in charset:
    self.charset += charsets[key]

The last part can be shortened further by the use of str.join:

self.charset = ''.join(charsets[key] for key in charset)

You might want to wrap this in a try:...except KeyError block for some nice feedback if an unsupported key is supplied, or just leave it as is.

You should also have a look at Python's official style-guide, PEP8. It recommends using a space after the : when defining key: value pairs.


You are right it seems rather weird for an immutable object to provide setters, which will throw an exception no matter how you call it. I would use inheritance and two different interfaces in this situation.

Imagine the base set. I would argue the base class should be the immutable set, since the immutable set declares functionality which both classes should be able to use. An example could be:

interface ImmutableInterface {

    public function fetch($key);
    public function exists($key);

}

class ImmutableSet implements ImmutableInterface {

    protected $items = [];

    public function __construct(array $items)
    {
        $this->items = $items;
    }

    public function fetch($key)
    {
        return $this->items[$key];
    }

    public function exists($key)
    {
        return array_key_exists($key, $this->items);
    }

}

You now have a basic implementation. You make your set manipulatable you could write a new interface declaring methods for changing values inside your set. The new interface could be:

interface ChangeableInterface {

    public function add($key, $value);

}

You could then write a sub-class of your original immutable set and implement the new interface. Since the $items array was declared protected any sub-class also has access to it.

class ChangeableSet extends ImmutableSet implements ChangeableInterface {

    public function add($key, $value)
    {
        $this->items[$key] = $value;
    }

}

You can now type-hint against a specific required implementation by using the interfaces. You also have the opportunity to use other classes as long as they implement the specific interface.

You can think of this strategy as declaring the fewest amount of required methods for your class to work. If you want to add more functionality you write an interface declaring no more than the required methods for that functionality to work. You can even take this further. Imagine not all your changeable sets should be able to remove items again. This could be an interface:

interface RemoveableInterface {

    public function remove($key);

}

You would then write a new sub-class of either the ChangeableSet or ImmutableSet, depending on your requirements, and implement the new interface. You can now type-hint specifically against sets which are only able to remove items. This strategy can continue forever, but do be careful. This can also be too much. Too many sub-classes can become a hell to maintain. So try to keep the amount of interfaces low, while still maintaining your required flexibility and the method signatures they declare concise.

The interface/class names used in these examples are not set in stone. They are by purpose very descriptive, so you can always rename them. Also keep in mind  there are no error checking in the examples.

I hope this can help you, happy coding!


C++ console based - "Word Guessing" game

Well, there is much to improve with your code, so let's begin at the beginning:

You should avoid using namespace std; It's a plague and just biding its time to bite you later.
Why is “using namespace std;” considered bad practice?
You might want to rework your logic regarding the tries. It's somewhat cruel to let the user go on guessing after he already cannot win anymore. And it's somewhat pointless if he can ask for every single character.
You should const-qualify what you can. Doing so makes logic-errors compile-errors, which can be caught by the compiler.
Use auto where you can. Remember that repetition is error-prone and everything you don't write nobody ever has to understand and check. Also known as the "Don't repeat yourself" (DRY) principle.
In that vein, I would also reorder your functions so you don't have to provide forward-declarations.
Consider everything but main() for static linkage, as it is never used outside the TU.
I'm sorry, but at best your comments are a blatant violation of DRY. Never repeat the code in the comments, write about why the code does something surprising or at least not quite straight-forward.
Consider consistent casing. Most of your variables begin with lower-case, why not all? Also, consider consistently having one space around binary operators.
There's nothing quite as useless as explicitly requesting something which will happen implicitly anyway. Aside from immediately afterwards undoing it.

std::string hiddenWord = "";
unsigned long int _length_ = randomWord.length();
hiddenWord.append((_length_),'_');
// Has the same effect as
std::string(randomWord.length(), '_');

Avoid beginning and/or ending names with an underscore. Even if you know the rules, it's error-prone and ugly.
Casts, function-style or not, are a last resort. And if you must use them, consider using the new-style casts as they are more prominent and explicitly name your intent.
Anyway, just use the right type.
Don't use std::endl unless you really need a manual flush. First, it's way uglier than a simple newline '\n', second, it kills performance as flushing is costly, and third, it's superfluous.
The standard input- and output-streams std::cin and std::cout are coupled so using the latter flushes the former if used with an interactive console.
If you want to do something a specific number of times, use a for-loop, that's what it's for.
Always test whether input succeeded. A pipe for example could be closed prematurely, or a file run out.
Also, you might want to re-try until you get something.
I wonder why checkLetter doesn't return whether now everything is revealed.
return 0; is implicit for main() in C++ and C99+.
rand and srand is quite a bad random-number-generator. Still, if you insist on using it, consider initializing it directly in main() to make sure you never inadvertently initialize it twice. And especially to make sure you don't repeatedly re-initialize it before using it again.
Take a look at <random> for better RNGs.
There's absolutely no reason to limit yourself to the first five words in the input-file. Or to fail if the file contains less words.
All error output should be send to the error stream, not standard output. That's what it's there for.
Consider accepting the input-filename as an argument, instead of hardcoding it. You might even give it a default.
Extract the task of reading the opening and reading the file. std::istream_iterator might come in handy for it.
Why does checkLetter() accept everything by modifiable reference? hiddenWord should be, sure, but randstr (which should be named randomWord for consistency) should be a constant reference, newLetter a value and strlen is superfluous.
That function also has two variables named it, the first one should be summarily removed.

Modified code:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string_view>

static bool checkLetter(
    char newLetter,
    std::string_view randomWord,
    std::string &hiddenWord
) {
    for(auto it = randomWord.begin(); it != randomWord.end(); ++it)
        if(*it == newLetter)
            hiddenWord.at(it - randomWord.begin()) = newLetter;
    std::cout << hiddenWord << '\n';
    return randomWord == hiddenWord;
}

static auto readFile(const char* filename) {
    std::ifstream file(filename);
    using isi = std::istream_iterator<std::string>;
    std::vector<std::string> arr{isi(file), isi()};
    return arr;
}

static void removeBadEntries(std::vector<std::string>& arr) {
    std::sort(arr.begin(), arr.end());
    arr.resize(std::remove_if(arr.begin(), arr.end(),
        [last = std::string_view()](auto& x) mutable{
            for(auto y : x)
                if(!isgraph((unsigned char)y))
                    return true;
            if(last == x)
                return true;
            last = x;
            return false;
        }) - arr.begin());
}

static auto getRandWord(const char* filename) {
    auto arr = readFile(filename);
    removeBadEntries(arr);
    std::cout << "Choosing from " << arr.size() << " unique valid entries.\n";

    return arr.empty() ? std::string("CANCER") : std::move(arr[rand() % arr.size()]);
}

int main(int argc, char* argv[]) {
    std::setlocale(LC_ALL, "");
    srand((unsigned)time(NULL));

    const auto randomWord = getRandWord(argc > 1
        ? argv[1]
        : "/Users/nedimkanat/XCODE/testcpp/testcpp/words.txt");
    std::string hiddenWord(randomWord.length(), '_');

    std::cout << "The Word is " << randomWord.length() << " letters long.\n";

    for(auto chances = randomWord.length() + 1; chances > 0; --chances){
        char c;
        do {
            if(!(std::cin >> c)) {
                std::cerr << "Error reading a character from stdin.\n";
                return EXIT_FAILURE;
            }
        } while(!std::isgraph((unsigned char)c));

        if(checkLetter(c, randomWord, hiddenWord)) {
            std::cout << "Congratulations! You won the game.\n";
            break;
        }
    }
}


My own implementation of Linq SelectMany extension method

The as cast in the return statement is entirely redundant, it doesn’t serve a purpose.

Furthermore, The problem with this implementation is that it’s not lazy. You should use a yield generator instead.

public static IEnumerable<TResult> MySelectMany<T, TResult>(this IEnumerable<T> source, Func<T, IEnumerable<TResult>> selector)
{
    foreach (T item in source)
        foreach (TResult inneritem in selector(item))
            yield return inneritem;
}

If C# already had a yield from statement, this would be even shorter since you wouldn’t need to iterate the inner items explicitly.


don't use a busy wait but instead use a wait condition (here using the built-in monitor in Object):

public void run() {
   while(true){
      while(!finished){
         // do stuff
      }
      try{
          synchronized(this){
              while(finished)
                   wait();//wait until notify gets called in startThread
          }
      }catch(InterruptedException e){}
   }

}

public synchronized void startThread() {
   finished = false;
   notify();//wake up the wait
}

I note that finished should remain volatile.

I put the wait() in the synchronized block in a while loop to avoid the race where the thread has just tested the first while condition and is about to enter the synchronized block but startThread() then gets called; putting finished back to false and the thread waiting anyway. This can lead to the thread blocking while waiting on a notify() that never happens.

To help any more I need to see what exactly happens inside that while loop.


Environment variable check with default value in csharp

Use ??. Null-coalescing operator.
Null check only
public static string GetEnvironmentVariable(string name, string defaultValue)
    => Environment.GetEnvironmentVariable(name) ?? defaultValue;

Null and empty string check
public static string GetEnvironmentVariable(string name, string defaultValue)
    => Environment.GetEnvironmentVariable(name) is string v && v.Length > 0 ? v : defaultValue;

Pattern matching.


Implementation in js to find if N can be written as X ^Y , N<100

The algorithm is wrong. canBeExpressedAsXraisedToY(81) returns false.

Of course any n can have a trivial solution x=n and y=1.  I assume you want to require y>1. But you didn't state that anywhere, and in fact initialize y=1 in your code.

Initializing prod=1 is sloppy programming. You should structure the loops to compute prod before testing it.

That is pretty much a brute-force exhaustive search. For large n, a much better strategy would be to analyze the prime factors of n instead.


Hiding all list items except the current and next element

Here are a few tips.

1)

childNum is not needed since it's only used once.

Old Code:

var childNum = $('#h').roundabout("getChildInFocus");
var cNum = (Number(childNum)) + 2;

New Code:

var cNum = $('#h').roundabout("getChildInFocus") + 2;

2)

In general, adding a object to a string results in a string.
And adding a object to a number results in a number.
Use parentheses to make the conversion clear.

Old Code:

$("#h li:nth-child(" + (Number(cNum) + 1).toString() + ")").show();

New Code:

$("#h li:nth-child(" + (1 + cNum) + ")").show();

3)

Cache commonly referenced elements.
Old Code:

$("#h li:nth-child(" + cNum + ")").show();

New Code:

var $lis = $("#h li");
$lis.find(":nth-child(" + cNum + ")").show();

4)

Combine operations on selectors.
Old Code:

$("#h li").hide();
$("#h li:nth-child(" + cNum + ")").show();

New Code:

$("#h li").hide().find(":nth-child(" + cNum + ")").show();

5)

Resetting the value of cNum to get rid of the else condition gives the following.

Old Code:

if (cNum == 4) {
    $("#h li:nth-child(1)").show();
} else {
    $("#h li:nth-child(" + (1+cNum) + ")").show();
}

New Code 1:

if (cNum == 4) {
    cNum = 0;
}
$("#h li:nth-child(" + (1+cNum) + ")").show();

New Code 2:

if (cNum == 5) {
    cNum = 1;
}
$("#h li:nth-child(" + cNum + ")").show();

As you can see New Code 2 is the same from the new code in tip 4.
So you can delete this redundant code.

Final Code:

var cNum = 2 + $('#h').roundabout("getChildInFocus");
if (cNum == 5){
    cNum = 1;
}
$("#h li").hide().find(":nth-child(" + cNum + ")").show();


Ok, the general critiques first:

Please, subscribe to the coding standards. It may seem irrelevant to you now. But believe me when I say that coding style is as important as unit tests once you start collaborating on a project.
Add use statements, to see all of the class' dependencies at a glance
Be consistent, both in method/property names as in the naming of local variables.
Don't use a closing ?> tag, if a script contains nothing but PHP code. The official docs explain why
Sanitize method arguments, don't simply string them together.
Use type-hints and inject dependencies whenever you can.
Doc-blocks save lives. Add them to your code ASAP. Use a decent IDE, and you'll soon find you can't do without these comments.

Now what does this all mean, applied to your code? Quite simply that you have to use that most valuable trait of all: common sense. A quick re-write of your code, applying most of these critiques.

<?php
use Httpful\Request;//add use statement
/**
 * @package DocumentCloudAPI
 * @author <your name>
 */
class PHPDocumentCloud
{
    //immutable part of url is just that: a constant value
    const BASE_URL = 'http://www.documentcloud.org/api/';

    /**
     * @var string
     */
    public $var = 'a default value';

    /**
     * @var Request
     */
    protected $requester = null;

    /**
     * Constructor, allows users to pass child class of
     * dependency as parameter, assign to property
     * @param Request $requester
     */
    public function __construct(Request $requester)
    {
        $this->requester = $request;
    }

    /**
     * @param int $id
     * @return \stdClass
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
    public function getById($id)
    {//next line, after more descriptive method name
        if (!is_numeric($id) || $id != (int) $id)//check numeric && not float
            throw new \InvalidArgumentException(
                sprintf(
                    '%s expects argument to be an int, instead saw %s',
                    __METHOD__,
                    gettype($id)
                )
            );
        $url = sprintf(
            '%sdocuments/%d.json',
            self::BASE_URL,
            (int) $id
        );//construct request url
        $response = $this->requester::get($url)->send();
        //no response, or no raw_body property => exception
        if (!$response || !property_exists($response, 'raw_body'))
            throw new \RuntimeException(
                sprintf(
                    'Request failed: %s',
                    json_encode($response)//force string
                )
            );
        //check for json errors
        $response = json_decode($response->raw_body);
        $err = json_last_error();
        if ($err === \JSON_ERROR_NONE)//No errors?
            return $response->document;
        //error, throw exception
        throw new \RuntimeException(
            sprintf(
                '%d - %s',
                $err,
                json_last_error_msg()
            )
        );
    }

    /**
     * Accepts assoc array, with keys q, page, per_page and mentions
     * @param array $params
     * @return array|\stdClass (don't know what type documents is
     * @throws \InvalidArgumentException
     * @throws \RuntimeExcpetion
     */
    private function getSearchPage(array $params)
    {
        $url = self::BASE_URL.'search.json?';
        //TODO: move this to a custom, more generic filterValidKeys method
        //along the lines of: filterValid(array $params, array $keys)
        //keys array could be assoc, where values are names of validation callbacks
        $keys = array('q', 'page', 'per_page', 'mentions');
        foreach ($keys as $key)
        {
            if (isset($params[$key]))
            {
                if ($key === 'q')
                    //in real life, check if the string isn't already url-encoded
                    $params[$key] = urlencode($params[$key]);
                else//given that other params are numeric
                    $params[$key] = (int) $params[$key]
                $url .= $key.'='.$params[$key].'&';//add & here
            }
        }
        if (substr($url, -1) === '?')//if last char of url is ?, no params were set
            throw new \InvalidArgumentException(
                sprintf(
                    '%s requires at least one of %s keys to be set',
                    __METHOD__,
                    implode(',',$keys)
                );
        $response = $this->requester::get($url)->send();
        if (!$response)
            throw new \RuntimeException(
                sprintf(
                    'Request to %s failed',
                    $url
                )
            );
        $response = json_decode($answer);
        $err = json_last_error();
        if ($err !== \JSON_ERROR_NONE || !property_exists($response, 'documents'))
        {
            if ($err === \JSON_ERROR_NONE)
                $msg = sprintf('%d - %s', $err, json_last_error_msg());
            else
                $msg = sprintf('documents not found in %s', json_encode($response));
            throw new \RuntimeException($msg);
        }
        if (empty($response->documents))
            return null;//return null if we reached the end
        return $response->documents;
    }

    /**
     * Public alias for getSearchPage, with loop
     * @param string $query
     * @return array
     */
    public function search($query)
    {
        $params = array(
            'q'        => $query,
            'page'     => 1,
            'per_page' => 1000,
            'mentions' => 3
        );
        $list = array();
        while ($results = $this->getSearchPage($params))
        {
            $list = array_merge($list, $results);
            ++$params['page'];//get next page
        }
        return $list;
    }
}

Disclaimer:
I wrote this off the top of my head, so there might be some syntax errors and oversights. This code is not meant to be copy-pastable at all. It's just an example of how to use doc-blocks, type-hinting, data sanitation, exceptions and all coding standards.

Onwards

Now, at first glance, you may think this code over-complicates things hideously. And truth be told, it does add some more complexity to the mix. What do you get in return?
Again at first glance: a class that throws exceptions whenever it encounters something that isn't quite right. But that's how a class should behave. A class is meant to perform one (and just one) task. If the data that is provided does not fit the criteria, that class's job is not to make do. The code that is calling the class needs to be fixed. An exception represents an emergency.
The calling code should handle the exception, or should be fixed. You can't ignore exceptions.

In the long run, though, this class offers a safer API, it's quite clear-cut. As long as you (the person calling the code) provide the correct data, you know what to expect. You can inject your own implementation of this Httpful\Request class to work with, and adding simple methods to perform certain calls are very easy to add. You just have to, basically, follow the same pattern:

Build url, starting with self::BASE_URL
use $this->requester::get($url)->send(); to get the response
check the response, and the result of json_encode. Return, or throw exceptions accordingly.

If you don't quite understand all of the functions used here, then don't worry: php.net/<function here> will tell you all you need to know.

Just one more thing:
In going over your code, and rewriting it, I couldn't help myself, but code like this:

$loop = True;
while ($loop) {
    $results = $this->get_search_page($query, $page, 1000);
    if (!empty($results)){
        $document_list = array_merge($results, $document_list);
        $page++;
    }else{
        $loop = False;
    }
}

Is just all shades of wrong. A while(true) loop (in PHP it's true, as opposed to python's True) is to be avoided as much as possible.
However, if you want to break an infinite loop, don't do that by setting a variable to another value, do so by using the cleverly named break; keyword:

while(true)
{
    if (empty($foo))
        break;//ends loop
    $foo = $this->doStuff();
}

But in most cases, ie: fetching rows from a result-set, it's best to perform a loop while you're fetching the data, and write it accordingly:

while($row = $stmt->fetch())
{
    //do stuff with $row
}

This works, simply because an assignment is an expression, and like any expression, it can be evaluated to a singular value. PHP assignment expressions evaluate to the new value of the left operand. In other words:

if ($x = false)
{//$x is left operand, being assigned false, expression evaluates to false
    echo 'This will never echo';
}


In the end I refactored like this:

{% set node_group_name = sceptre_user_data.node_group_name %}
{% set node_labels = sceptre_user_data.node_labels %}
{% set taints   = sceptre_user_data.taints %}
{% set cni_custom_network = sceptre_user_data.cni_custom_network %}

...

do_bootstrap() {
  {% set args = "--kubelet-extra-args '--node-labels=nodegroup=" + node_group_name %}

  {% if node_labels != "None" %}
    {% set args = args + "," + node_labels %}
  {% endif %}

  {% if cni_custom_network == "Yes" %}
    zone=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
    {% set args = args + ",k8s.amazonaws.com/eniConfig=pod-netconfig-$zone" %}
  {% endif %}

  {% if taints != "None" %}
    {% set args = args + " --register-with-taints=" + taints %}
  {% endif %}

  {% set args = args + "'" %}

  eval "/etc/eks/bootstrap.sh ${EKSClusterName} {{ args }}"
}

do_bootstrap

I would still welcome feedback from anyone who knows a Jinja2 trick that might help that I don't know.


Handling external API calls status code in my application

I have only 2 things to note.

Returning the same status code as the remote server could lead to confused clients of your API due to incorrect status codes. What if the remote server has returns a 5xx status code? Your server didn't have an internal server error, the remote did, but then why is your server returning a 5xx status code?

Instead, I recommend replacing it with returning a fixed status code (or something depending on the status code the remote API returned). The method name is Get, so I'd go with a 404 Not Found.
Use attributes. In ASP.NET and ASP.NET Core the runtime can figure out which method to call by the http method and the name of it (call Get when an http get request comes, Post when a post comes etc), but it would be a lot more obvious not only for the runtime but also for developers if you named your methods a good name (e.g GetName) and decorate it with attributes specifying the route and the http request method to respond to.

Plus, you could also do yourself and any future developer a favor by specifying where the parameter to the method comes from. Right now it's part of the URI string (also called query parameters), but other methods might accept JSON to deserialize, you can do this by adding an attribute to the parameter. More about it here.

Putting number 2 into code:

[Route("Result/GetName")]
[HttpGet]
public async Task<ActionResult<Models.Result>> GetName([FromUri] string name)
{
    // ...
}


2D Platformer Collision Detection/Resolution

You have some code duplication there

for(int row = topLeft.y; row <= bottomRight.y; row++)
{
    if(map.getType(row, topLeft.x) == Tile.SOLID)
    {
        collision = true;
        break;
    }
}

which should be extracted to a method like

private boolean hasCollision(int start, int stop, int x){

    for(int row = start; row <= stop; row++)
    {
        if(map.getType(row, x) == Tile.SOLID)
        {
            return true;
        }
    }
    return false;
 }

If a collision is found you have this

dx = 0;

// Move player to edge of solid tile
int col = ((int)(xtemp + dx) - collisionWidth/2) / map.getTileSize();

Do you on purpose set dx = 0 and calling then (xtemp + dx) ?
You are also doing a lot of collisionWidth/2 which should be extracted to a variable.
you should extract the left and right checking to separate methods.
in Java the convention is to place the opening brace { on the same line.
using a guard clause for dx == 0 well remove the creation of the Point's
comments should describe why something is done. **What is done should be described by the code itself by using meaningful names.

Implementing most the points above leads to

// Corrects X movement if a collision occurs.
private void checkXCollision()
{
    if (dx == 0) {
        return;
    }

    Point topLeft = new Point(((int)(xtemp + dx) - collisionWidth/2) / map.getTileSize(), ((int)ytemp - collisionHeight/2) / map.getTileSize());
    Point bottomRight = new Point(((int)(xtemp + dx) + collisionWidth/2) / map.getTileSize(), ((int)ytemp + collisionHeight/2) / map.getTileSize());

    if(dx < 0){

        checkLeftXCollision(topLeft, bottomRight);

    } else {

        checkRightXCollision(topLeft, bottomRight);

    }
}

private void checkLeftXCollision(Point topLeft, Point bottomRight) {

    if(hasCollision(topLeft.y, bottomRight.y, topLeft.x)) {
        dx = 0;

        int col = ((int)(xtemp + dx) - collisionWidth/2) / map.getTileSize();
        xtemp = col * map.getTileSize() + collisionWidth / 2;
    } else {
        xtemp += dx;
    }
}

private void checkRightXCollision(Point topLeft, Point bottomRight) {

    if(hasCollision(topLeft.y, bottomRight.y, bottomRight.x)) {
        dx = 0;

        int col = ((int)(xtemp + dx) + collisionWidth/2) / map.getTileSize();
        xtemp = (col + 1) * map.getTileSize() - collisionWidth / 2 - 1;
    } else {
        xtemp += dx;
    }
}

private boolean hasCollision(int start, int stop, int x){

    for(int row = start; row <= stop; row++)
    {
        if(map.getType(row, x) == Tile.SOLID)
        {
            return true;
        }
    }
    return false;
}


Shifting records in SQL Database while sorting with algorithm

There is a much, much, much easier way to do this. You can use real values for order, so when you want to move the row from position 16 to position 7 you give it an order value which is the average between the order values of rows 6 and 7.

The precision of real numbers is huge, and I presume that the re-orderings of images in your database will be happening at human reaction speeds, so you probably won't run into precision problems during the remainder of the expected lifetime of the universe. But if you are really insecure about the possibility of precision problems, you can rectify your table every once in a while, by reading the rows sorted by their order, and writing them into a new table, re-assigning the order values by copying them from an integer identity field. Then you delete the old table and rename the new table to the old name.


I don't see any reason why the PrintDict class should exist.  Furthermore, there's no point in keeping self.data as part of the object state.  A standalone function print_dict_to_screen(data) would work just fine.

Much of the code is concerned with printing out the value lists in the right format.      This whole chunk of code…

items = len(self.data[key])
iterate = -1
for i in range(items):
    iterate += 1
    print self.data[key][iterate],

… could be replaced with

print ' '.join(self.data[key])

It's usually more manageable if you consistently put your newlines at the end rather than at the beginning of your output.

There's no need to cast the key as a str, since the %s format specification always interprets its input as a string.

So, the code can be simplified to:

def print_dict_to_screen(self, data):
    for key in sorted(data):
        print "%s\n%s\n" % (key, ' '.join(data[key]))

It would be even cleaner if the output had no excessive leading or trailing newlines.  To accomplish that, I would use join() again:

def dict_to_string(data):
    return "\n\n".join(
        "%s\n%s" % (key, ' '.join(data[key])) for key in sorted(data)
    )

Here, dict_to_string() returns the string to be printed rather than printing it directly.  Then, the caller is free to print the resulting string, log it to a file, or whatever.


In the try block, temp might not get assigned, so temp.name would be an error. But this is an extremely unlikely scenario.

You seem to be going out of your way to defeat the natural clean-up capability of the named temporary file:

  If delete is true (the default), the file is deleted as soon as it is closed.

Since the file is opened via a with block, it should be closed automatically at the end of the block, and automatically deleted as well, if you let it.  Therefore, you shouldn't need the try...finally at all, and you can remove the delete=False parameter from NamedTemporaryFile:

def test_read(self):
    """Test read from file"""
    import tempfile

    with tempfile.NamedTemporaryFile() as temp:
        content = 'Some data'
        temp.write(content.encode('utf-8'))
        temp.flush()
        self.assertEqual(content, b.read(Path(temp.name)))

When you open a file for reading, you can omit the r in here:

with open(path.as_posix(), 'r') as file:
   return file.read()

Finally, b is terrible name. It doesn't tell anything about the module.