Casting the left and right numbers as integers or doubles

One option would be to do your math operations on a double.  You can use a generic method that accepts any derivative of the Number class and use the doubleValue() method for your calculation.  The caller of the method can cast to Integer as needed:

enum Operators {
    ADD,
    SUB,
    MUL,
    DIV
}

public static <T1 extends Number> Double doMath(T1 left, T1 right, Operators operator) {
    switch (operator) {
        case ADD:
            return left.doubleValue() + right.doubleValue();
        case SUB:
            return left.doubleValue() - right.doubleValue();
        case MUL:
            return left.doubleValue() * right.doubleValue();
        case DIV:
            return left.doubleValue() / right.doubleValue();
        default:
            return 0.0;
    }
}


Validating user-provided control points for a Bézier curve

There are things that can be improved:

You could return the points instead of asigning the global variabel p
You could split the function in two functions:

get_four_bezier_points
get_point

it probably would be better to return float values instead of string values.
You could inform the user that the input x and y values should be between certain values and must be separated with a comma.
the error checking logic's could be restructured such that the second input statement can be removed.

Putting these together as an example:

def get_point(description):
    while True:

        p_input = input("Enter X,Y Coordinates for " + description + ": ")
        p_components = p_input.split(',')

        if len(p_components) != 2:
            print("Not two comma seperated values, please try again")
            continue # (jumps to the beginning of the while loop)

        try:
            x = float(p_components[0])
            y = float(p_components[1])
        except ValueError:
            print("No float values, please try again.")
            continue

        if(x > 1020 or x < 10) or (y > 760 or y < 10):
            print("Values out of bounds.")
            continue

        # oke values are good
        return [x,y]  # jumps out of the function and while loop

def get_four_bezier_points():
    p = []
    print("Enter four bezier points with x in [10,1020] and y in [10,760]")
    points = ["Start Point(P0)", "Control Point 1(P1)", "Control Point 2(P2)", "End Point(P3)"]
    for description in points:
        p.append(get_point(description))
    return p

p = get_four_bezier_points()


JavaScript does type conversion automatically, there is no need to create the myArray variable. You can do that entire bit using a for loop similar to this:

var showArray = function (num) {
  $('.info').empty();
  for (var i = num; i < Math.max(num + 5, 13); ++i) {
    $('.info').append(`<h1>${n}</h1>`);
  }
};

(Maybe instead of hardcoding 13, you have a const for the length)
Keep your use of semicolons consistent. Either have them or don't. Pick a style convention and stick to it.


Monitoring directories for files that are generated by an engineering program

In this case, it would likely not make a difference. It is one call into the standard library that does a string operation that produces a short lived variable. If you want to know the correct answer, you should profile the code with real data to see what performs better.

If you don't care enough to profile it, do whatever lets you sleep better at night.

An optimization that you can do to speed up the code is change the if clauses.

In both cases, you execute NormalizePath(Path.GetDirectoryName(e.FullPath)).

This can be done once, then use the result in the string comparison of the if clause.
Perform the check of e.ChangeType first.

If the type doesn't match, you don't need do any path manipulation. Simply moving that check to the left side of the && instead of the right means the boolean expression can short circuit after a cheap operation before doing the expensive one. Also, since both cases are checking for the same type, you can pull the whole check out to an outer if block.
Do this.failFolder or this.successFolder change?

If not, you can store the normalized path as a instance variable and not perform the operation each time.

The IOException is being handled in the same way and (it appears that) CopyToDestination() is the only thing that would cause it. You reduce this down to one try catch instead of two.

In general, you shouldn't be commenting your if clauses. If the boolean expression is complicated enough that it needs to be described, it should be extracted into a function with a descriptive name. In theses cases, the check being performed is straight forward.

Throw that all together and you get something like this:

if (e.ChangeType == WatcherChangeTypes.Created)
{
    var normalizedPath = NormalizePath(Path.GetDirectoryName(e.FullPath));
    try
    {
        if (normalizedPath == this.normalizeSuccessFolder)
        {
            string fileExtension = Path.GetExtension(e.FullPath);
            if(this.successDictionary.ContainsKey(fileExtension))
            {
                CopyToDestination(this.successDictionary[fileExtension], e);
            }
        }
        else if (normalizedPath == this.normalizeFailFolder)
        {
            activeLog.WriteLineToLog(e.FullPath + " has been added to the fail folder.");
            string fileExtension = Path.GetExtension(e.FullPath);
            if (this.failDictionary.ContainsKey(fileExtension))
            {
                CopyToDestination(this.failDictionary[fileExtension], e);
            }
        }
    }
    catch (IOException ioe)
    {
        activeLog.WriteLineToLog("FolderMonitor IOException: " + ioe.Message);
    }
}

Edit:

Extracting common code into a method as pointed out by ChrisWue. There is still a repeated pattern there, but with just two cases, it isn't needed to abstract it more.

Had to make an assumption about the dictionary type and make up a name for the type of e. Even though this code doesn't care if the copy is attempted, I added a boolean return to indicate if it did. I also switched to using TryGetValue() instead of indexing into the dictionary twice.

private bool AttemptCopyToDestination(IDictionary<string,string> knownExtensions, SomeTypeName e)
{
    string fileExtension = Path.GetExtension(e.FullPath);
    string destination;
    if (knownExtensions.TryGetValue(fileExtension, out destination)
    {
        CopyToDestination(destination, e);
        return true;
    }
    return false;
}

// ...

if (e.ChangeType == WatcherChangeTypes.Created)
{
    var normalizedPath = NormalizePath(Path.GetDirectoryName(e.FullPath));
    try
    {
        if (normalizedPath == this.normalizeSuccessFolder)
        {
            AttemptCopyToDestination(this.successDictionary, e);
        }
        else if (normalizedPath == this.normalizeFailFolder)
        {
            activeLog.WriteLineToLog(e.FullPath + " has been added to the fail folder.");
            AttemptCopyToDestination(this.failDictionary, e);
        }
    }
    catch (IOException ioe)
    {
        activeLog.WriteLineToLog("FolderMonitor IOException: " + ioe.Message);
    }
}


const bool Game::isColliding(...

This indicates that the returned type is const, and should not be modified by any part of your code. But it's not a reference, so it doesn't make sense. It should compile, but it's a little confusing. Removing that const is clearer.

see this SO question for more information on that.

Your parameters to isColliding should be const references:

bool Game::isColliding(const sf::RectangleShape& player, const sf::RectangleShape& enemy) const

because you don't modify them, and references will prevent each object form being copied.

You never use the player parameter that you pass to the isColliding function. this->player is not the same as player in this context. It seems like you want to check the Game's current player object against collisions with arbitrary objects. You either

Make the function static (so it doesn't rely on a particular Game state) and pass two arbitrary objects to be checked for collision, or
Change the function name to something that indicates it will only be used with the player object.

One of:

static bool Game::isColliding(const sf::RectangleShape& a, const sf::RectangleShape& b)

or

bool Game::isPlayerColliding(const sf::RectangleShape& other) const

These Vector2d assignments can be made into const references to prevent copy construction.

    const sf::Vector2f& playerPosition = this->player.getPosition();
    const sf::Vector2f& enemyPosition = this->enemy.getPosition();


Calculating travel statistics based on CSV data

What you did well

You used the csv module for parsing the CSV file, and you processed it in one pass.  Your code is therefore reasonably efficient, and I wouldn't worry much about its performance.

Bugs

Your code reports "The Car that ends up furthest away from its drop is: …", but that is, in my interpretation, not the same as the longest single trip, which is what you were asked to calculate.

Concerns

Your data analysis code is mingled with the CSV parsing.  That makes the code hard to read and hard to maintain.

The deeply nested dictionaries are hard to understand.  What does myDict store?  Its purpose is not apparent from its name.  It's a two-level dictionary, where the first-level key is a vehicle_id, the second-level key is some attribute of that vehicle (the 'drop' coordinate, the 'start_ride' coordinate, or the 'allDistances' running total).  You would be better off with three independent dictionaries.  Better yet, as I've done below, define an Itinerary class instead.

What's aDict?  It keeps track of the distance from each car's drop point to the endpoint of its last trip.  Again, the variable name does not help.

The print() call is hard to read, in an excessively long line of code, with lots of str() casts and unnecessary string concatenations.  In this situation, I would recommend f-strings (introduced in Python 3.6), or str.format().

Suggested solution

This solution reports the car that ends up the furthest from its drop point, as you did, rather than the longest single trip as requested.

The Shapely library is overkill; subclassing namedtuple with a .distance() method is all I need for a handy Point class.  Euclidean distances can be calculated using math.hypot.

If you look at the data, you'll see that each car acts as a state machine.  It is initialized with a DROP event.  Thereafter, it alternates between START_RIDE and END_RIDE events.  No traveling is allowed when a START_RIDE occurs; the car is always the same place as its preceding DROP or END_RIDE coordinates.  In my Itinerary class, I've kept track of the .state of the car so that I can perform certain assertions, but it's only essential to keep track of the coordinates at each DROP and END_RIDE event.

The itineraries() function parses the CSV into one simple data structure: a dictionary mapping vehicle IDs to their itineraries.  I've chosen to use fileinput.input() to accept the file on the command line or through sys.stdin without hard-coding the filename.

The data analysis is accomplished using built-in functions len() and max() with generator expressions.  That is more expressive and less cumbersome than maintaining several intermediate results each time an END_RIDE event occurs.

from collections import namedtuple
import csv
import fileinput
from math import hypot
from operator import attrgetter

class Point(namedtuple('Point', 'x y')):
    def distance(self, other):
        """Euclidean distance between two points."""
        return hypot(self.x - other.x, self.y - other.y)

class Itinerary:
    def __init__(self, car, x, y):
        self.car = car
        self.coords = [Point(x, y)]
        self.state = 'DROP'
        self.cumul_dist = 0

    def start_ride(self, x, y):
        assert self.state in ('DROP', 'END_RIDE'), "Restarting unfinished ride"
        assert Point(x, y) == self.coords[-1], "Teleportation occurred"
        self.state = 'START_RIDE'

    def end_ride(self, x, y):
        assert self.state == 'START_RIDE', "Ending a ride that hasn't started"
        self.coords.append(Point(x, y))
        self.state = 'END_RIDE'
        self.cumul_dist += self.coords[-1].distance(self.coords[-2])

    @property
    def final_dist(self):
        return self.coords[-1].distance(self.coords[0])

def itineraries(f):
    cars = {}
    for timestamp, car, event_id, x, y, user_id in csv.reader(f):
        if event_id == 'DROP':
            assert car not in cars, "Dropping the same car twice"
            cars[car] = Itinerary(car, float(x), float(y))
        elif event_id == 'START_RIDE':
            cars[car].start_ride(float(x), float(y))
        elif event_id == 'END_RIDE':
            cars[car].end_ride(float(x), float(y))
    return cars

def main():
    cars = itineraries(fileinput.input()).values()
    drops = len(cars)
    furthest = max(cars, key=attrgetter('final_dist'))
    most_traveled = max(cars, key=attrgetter('cumul_dist'))
    print(f"""There are {drops} total drops.
The car that ends up furthest from its drop is {furthest.car}, at distance {furthest.final_dist}.
Car {most_traveled.car} travels the longest cumulative distance: {most_traveled.cumul_dist}.""")

if __name__ == '__main__':
    main()


Different methods of API that use similar Services

Use English for your variable names, request routes, and Exception messages. Imagine a remote developer joins your company (very common these days), they wouldn't be able to understand the stack traces.
validate your parameters before creating unnecessary objects

Validacao validacao = validacaoDAO.findById(validacaoId);
if (validacao == null) {
    throw new NotFoundException("Validacao cannot be null");
}
Permalink permalink = new Permalink().setId(Util.getMd5Time(validacaoId));

The switch statement however is fine.


Computing the probability of rolling a given total with five dice

I feel like there is a recursive answer here that I can't put my finger on that would work for different numbers of dice.

Sure. Let's work with an example, let's say the one in the question: how many ways can we roll 5 dice to get 21.
The answer could be computed as the sum of answers of the following questions:

How many ways are there to roll 4 dice to reach 20? (first roll was 1)
How many ways are there to roll 4 dice to reach 19? (first roll was 2)
...
How many ways are there to roll 4 dice to reach 15? (first roll was 6)

And each of these questions can be further broken down:

How many ways are there to roll 3 dice to reach 19? (first roll was 1, 2nd was 1)
How many ways are there to roll 3 dice to reach 20? (first roll was 1, 2nd was 2)
...
How many ways are there to roll 3 dice to reach 9? (first roll was 6, 2nd was 6)

I hope you see how the pattern will reach a point where we are actually able to give an answer, for example:

How many ways are there to roll 0 dice to reach 0 -> 1 :-)
How many ways are there to roll 0 dice to reach 1 -> 0, not possible to reach non-zero without dice
How many ways are there to roll 2 dice to reach 0 -> 0, not possible, the remaining rolls will be greater than 0
...

In other words, the recursive function must first check the terminating condition, as usual. If we know the answer given the input (0 or 1), we return it. Otherwise, we compute the sum of calling the function for each possible path (dice value), with one less dice, and reduced target to reach.


BinaryReader.ReadString() expects the string prefixed with the number of bytes to read, not the number of characters (I think this is because of variable-length encodings, especially UTF-8, but also UTF-16).

So, you can't use ReadString() directly, but you also don't have to convert the characters byte by byte like you do (which wouldn't work for non-ASCII characters anyway).

For this, you can use ReadChars(), which takes as a parameter the number of characters (not bytes) to read.

You also need to figure out what format is the number of bytes saved in. It could be a simple single-byte number (which means the string can have at most 255 characters), or it could be VLQ-encoded, which you can read using Read7BitEncodedInt(). Though that method is protected, so I'm going to assume the former for simplicity.

So, the code could look like this:

using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))
{
    int characterCount = reader.ReadByte();
    char[] characters = reader.ReadChars(characterCount);
    return new string(characters);
}


Yes, $category in your query string, coming directly from $_GET is a problem.

You should validate $category, and that's not exactly the same as escaping. I assume you have a limited set of valid categories in your database, so validation should be something like:

$valid_categories = array("sector", "industry", "company");
if (!in_array($category, $valid_categories)) {
    // no no
}

As for the other part of your question, paraphrased:

  Is it pointless to use prepared statements if there is a variable part in the query?

It's not pointless, because every time you run the query for the same $category value, it can benefit from the previously prepared statement.


Merge hashes that have the same description field, summing the other fields

Besides the code being a little more complex than it needs to be, I see two issues:

a performance problem: the .find { |l| l[:description] == line[:description] } is called for each element in the array of hashes, leading to an O(n^2) time algorithm (because the array lookup takes linear time)
a more subtle thing: the initial hashes are mutated by your code. When you do old_v + new_v that modifies the very hashes that have been provided as an input to your function/code. This might not be a problem for you, but I think it's good practice to avoid mutability where possible.

To solve these things, let's use a hash of hashes. We'll have a hash that has the :description values as key (thus allowing to look things up in constant time) and a hash containing the values to be cummulated.

Also, to save the verification of whether a certain key already exists or not, I will use the new {|hash, key| block } syntax when creating the outside hash.

Here's the code:

results = Hash.new { |h, k| h[k] = {b: 0, c: 0} }
array_of_hashes.each do |h|
  cummulative_hash = results[h[:description]]
  cummulative_hash[:b] += h[:b]
  cummulative_hash[:c] += h[:c]
end

At this point, results looks like this:

{"string"=>{:b=>3, :c=>6}, "other_string"=>{:b=>1, :c=>2}}

This can be easily converted to your array format, like this:

results.map{|k, v| {description: k}.merge v}

=> [{:description=>"string", :b=>3, :c=>6},
    {:description=>"other_string", :b=>1, :c=>2}]

In the example above I hardcoded the :b and :c keys.
For a more generic treatment of the keys to be cummulated, here's the (slightly adjusted) code:

results = Hash.new { |h, k| h[k] = {} }
array_of_hashes.each do |h|
  cummulative = results[h[:description]]
  h.each do |k, v|
    cummulative[k] = (cummulative[k] || 0) + h[k] if k != :description
  end
end
results.map{|k, v| {description: k}.merge v}


Converting numbers 1-99 to Spanish in Javascript

The function declarations are at least lacking a const statement (or let or var if you prefer):

const getSpanishCardinal = cardinal => {

However I would suggest to using regular function statements instead.

The getCardinals function is a bit pointless. A simple constant instead would make more sense:

const CARDINALS =  {
  0: "cero",
  1: "uno",
  // ...
}

For readability I'd also suggest to split it up into separate objects for 0 to 15, the tens, the hundreds, etc.

This would also allow to assign assign the tens to the base number e.g.:

const TENS = {
     2: "veinte",
     3: "treinta",
     4: "cuarenta",
     // ...
}

and then you don't need to "build" numbers in leftMostMultiplier:

const twentyToNinetynine = cardinal => {
  // ...
  return (
    TENS[cardinal / 10] +
    " y " +
    getSpanishCardinal(rightMostDigit(cardinal))
  );
};

(BTW, there seem to be a lot of unnessecary toString()s.)


You need to add persist() like so:

...
$post->setAuthor($formData->getAuthor());
$em->persist($post);
$em->flush();
...

That should do it!


The heapify and parentfunctions can be avoided:

You just need the sinking logic that you already implemented. But instead of having current always starting at 0 you can set it as a parameter:

template<typename I>
void sink(I begin, I end, std::size_t index)
{

    std::size_t size = std::distance(begin, end);
    std::size_t current = index;
    while (current < size)
    {
        std::size_t child1 = current * 2 + 1;
        std::size_t child2 = current * 2 + 2;
        std::size_t goodChild = current;

        if (child2 < size)
        {
            goodChild = (*(begin + child1) > *(begin + child2)) ? child1 : child2;
        }
        else if (child1 < size)
        {
            goodChild = child1;
        }
        if (*(begin + current) < *(begin + goodChild))
        {
            std::swap(*(begin + current), *(begin + goodChild));
            current = goodChild;
            continue;
        }
        break;
    }
}

Due to the fact that the elements  are leafs you can ignore them, so you just need to apply sink

times to build the heap:

template<typename I>
void heap_sort(I begin, I end)
{
    std::size_t size = std::distance(begin, end);
    for (int i = size / 2 - 1; i > -1; --i)
    {
        sink(begin, end, i);
    }
    while (begin != --end)
    {
        std::swap(*begin, *end);
        sink(begin, end, 0);
    }
}

Alternative sink implementation:

IMO this implementation is more concise:

template<typename I>
void sink(I begin, I end, std::size_t index)
{

    std::size_t size = std::distance(begin, end);
    std::size_t current = index;
    std::size_t child;

    std::less<decltype(*begin)> less;

    while ((child = 2 * current + 1) < size)
    {
        I itr_child   = begin + child;
        I itr_current = begin + current;

        if(child < size - 1
            && less(*itr_child, *(itr_child + 1))
        {
            ++itr_child;
        }

        if (!less(*itr_current, *itr_child))
        {
            break;
        }
        std::swap(*itr_current, *itr_child);
        current = child;
    }
}


Most elegant way to copy type alias class to original collection

You definitely don't want to extend a type in order to alias it.
This introduces complexity, is not idiomatic, and most importantly doesn't create an alias.
I believe what you're looking for is the type alias syntax
using System;
using System.Collections.Generic;

using SmallDictionary = Dictionary<string, JToken>;
using NestedDictionary = Dictionary<string, SmallDictionaly>;

As their name implies, type aliases do not create any new types, they simply introducing a scoped alias that refers to the aliased type.
The only real drawback to type aliases is that they cannot be generic.
Moving on the the logic itself,
There's no need to write a loop over the dictionary entries to copy them into it new dictionary.
Dictionary<TKey, TValue> provides a constructor which takes an IEnumerable<KeyValuePair<TKey, TValue> allowing us to specify its initial contents.
return new Dictionary<string, Dictionary<string, JToken>>(configurationEntry);

or
return new NestedDictionary(configurationEntry);

Thanks to the type alias


F# code to check whether there are three same digits within a given number

Followed upon @hocho's comment and agree that using groupBy is much better as it can generalise the solution to check any number of same digit rather than limited to just 3 from my initial implementation. I have also simplified the helper method which converts a number into a collection; returning a sequence is enough as there is no need to return an array.

let convertNumberToSeq (number: bigint) =
        let numberString = string number
        numberString.ToCharArray()
        |> Seq.map (string >> int)

///<summary>
/// Check whether a given number has at least n same digits
///</summary>
///<param name="number">The given number</param>
///<param name="n">How many same digits to be checked</param>
///<returns>
///True if there are n same digits otherwise False
///</returns>
let SameDigitCheck (number : bigint) (n : int) =
    if n < 2 then failwith "n must be at least 2"
    let digits = convertNumberToSeq number
    let q = query { for digit in digits do groupBy digit into g; select g }
    q |> Seq.exists (fun x -> Seq.length x >= n)


Compute a value (and update a CSV record), based on prior value

First question - no, there is no way to get rid of this "initial" value completely. There is, however, a way to make it more intuitive that the values is "missing" - the Option type. Pass None as initial state, and return Some from then on. This will also allow you to elegantly get rid of that initial value by using Seq.choose.

Second question - easy: just make target first parameter of the folder function and pass it in via partial application:

let updateBarValue target state (line:string) =
   let effectiveState =
      match state with
      | None -> line
      | Some s -> s
   Some (buildLineWithBarValue (effectiveState, target) line)

File.ReadLines(inFile)
   |> Seq.map appendEmptyColumnForBarValue // add the col to hold the new barValue
   |> Seq.scan (updateBarValue target) None // compute the barValue, based on prev state and target
   |> Seq.choose id // get rid of the initial input
   |> Seq.iter outFile.WriteLine

As an aside, I noticed your tendency to tuple function arguments. That is generally considered bad form, unless arguments inherently "belong together" - e.g. point coordinates, - because curried arguments give more freedom. To this end, I would make buildLineWithBarValue's arguments curried as well.


As far as I can see, there is no need for the StringIO (?).
You can just use query.split('\n'). Regardless, that for loop can be condensed into a list comprehension:

rows = [[el.strip() for el in row.split('|')] for row in query.splitlines()]

If the StringIO is really needed, I would use with..as:

with StringIO.StringIO(query) as s_obj:
    rows = [[el.strip() for el in row.split('|')] for row in s_obj]

For the column widths you can use that len is already a function, so there is no need for lambda x: len(x). This way you can also inline all of it into one list comprehension:

col_widths = [max(map(len, column)) for column in zip(*rows)]

For the alignments, I would define a function that returns the alignment, given the content of a cell. First I had this function return your strings. But then I realized that you are already using entry.ljust further down. I then changed it to return the function to use here. Note that str.ljust("ab", 2) and "ab".ljust(2) are equivalent, so later we just call align(entry, width).

def get_alignment(cell):
    """"
    :---"    left aligned
    "---:"    right aligned
    ":--:"    centered (also accepts "---"), default
    """
    if cell.startswith(":") and not cell.endswith(":"):
        return str.ljust
    elif cell.endswith(":") and not cell.startswith(":"):
        return str.rjust
    return str.center

To get all alignments, we just use map again:

alignments = map(get_alignment, rows[1])

Finally, the output part. Since you already build a nice tuple with zip, you should use tuple unpacking to give the element readable names. entry_and_widths is a confusing name, especially since it also contains the alignments!

Here we can now get rid of most of your code, since it boils down to:

entry = align(entry, width)
out.append("| {} ".format(entry)

Here I used str.format to make it a bit easier and avoid the costly string addition. Note that we could also use str.format to do the adjusting for us (using e.g. "{>2}".format(entry) instead of "{}".format(str.rjust(entry, 2)), but that would mean nesting formats, which starts to get ugly very quickly.

I also use the fact that 0 compares to False to make the code skipping a column if it is empty shorter.

out = []
for row in rows:
    for entry, width, align in zip(row, col_widths, alignments):
        if not width:
            continue
        out.append("| {} ".format(align(entry, width)))
    out.append("|\n")
query = "".join(out)

Final code:

#!/usr/bin/env python

"""MMD Table Formatter.

Silly script that takes a MMD table as a
string and returns a tidied version of the table
"""
import sys

def get_alignment(cell):
    """"
    :---"    left aligned
    "---:"    right aligned
    ":--:"    centered (also accepts "---"), default
    """
    if cell.startswith(":") and not cell.endswith(":"):
        return str.ljust
    elif cell.endswith(":") and not cell.startswith(":"):
        return str.rjust
    return str.center

query = sys.argv[1]

# For "cleaned" table entries:
rows = [[el.strip() for el in row.split('|')] for row in query.splitlines()]

# Max length of each "entry" is what we'll use
# to evenly space "columns" in the final table
col_widths = [max(map(len, column)) for column in zip(*rows)]

# Let's align entries as per intended formatting.
# Second line of input string contains alignment commmands:
alignments = map(get_alignment, rows[1])

# Prepare for output string:
out = []
for row in rows:
    for entry, width, align in zip(row, col_widths, alignments):
        if not width:
            continue
        out.append("| {} ".format(align(entry, width)))
    out.append("|\n")

query = "".join(out)

sys.stdout.write(query)


Maybe this looks better to you.  Encapsulating a loop's contained logic in dedicated single-purpose procedures generally makes a loop easier to read and understand(IMO).  In this case, the loop conditions requiring the repeated code to run 'one last time' becomes a little more clear as well.
    Option Explicit

    Dim første_økt_anodeskift(1 To 10, 1 To 2) As Long

    Const farge_anodeskift_1 As Long = 14395790 ' RGB(142, 169, 219)

    Sub main()
        Dim syklus As Long

        syklus = 1

        Call legg_inn_verdier
        Call fargelegg(første_økt_anodeskift(syklus, 1), første_økt_anodeskift(syklus, 2), farge_anodeskift_1)
    End Sub

    Private Sub fargelegg(fra, til, farge)
        Do
            DoStuff fra, til, farge

            fra = GetNextFra(fra)

            If fra = til Then
                DoStuff fra, til, farge
                Exit Do
            End If

        Loop While True
    End Sub

    Private Sub legg_inn_verdier()
        første_økt_anodeskift(1, 1) = -11: første_økt_anodeskift(1, 2) = 6
    End Sub

    Private Sub DoStuff(fra, til, farge)
        ' Do stuff
    End Sub

    Private Function GetNextFra(fra) As Variant
        fra = fra + 1

        If fra = 0 Then
            fra = 1
        ElseIf fra = 56 Then
            fra = -55
        End If

        GetNextFra = fra
    End Function


Using foldl is the right idea, I think.  (\acc x -> foldingFunction acc x) is a useless lambda, which could just be written as foldingFunction.  The fact that it's a folding function is evident from the fact that you passed it to foldl; you could name it something more useful, such as manipulateStack.

Consider breaking up solveRPN.  For example, it might be useful to inspect the end state of the whole stack rather than just taking the top element.  Also, it's possible that the input might already be split into words (from the command line via getArgs, for example).

The beauty and simplicity of RPN comes from the fact that operators can manipulate the stack directly.  Instead, you've implemented a calculate function that performs binary operations only.  That results in two problems:

In the case of RPN stack underflow, you'll get a "Non-exhaustive patterns in function calculate" error.
You can't support unary operators (such as "sqrt"), nor can you support nullary operators (such as a "pi" operator that pushes 3.141592653589793 onto the stack).

import System.Environment

manipulateStack :: [Double] -> String -> [Double]
manipulateStack stack s
  | s == "+"     = (next + top) : stack''
  | s == "-"     = (next - top) : stack''
  | s == "*"     = (next * top) : stack''
  | s == "/"     = (next / top) : stack''
  | s == "^"     = (next ** top) : stack''
  | s == "sqrt"  = (sqrt top) : stack'
  | s == "sin"   = (sin top) : stack'
  | s == "cos"   = (cos top) : stack'
  | s == "tan"   = (tan top) : stack'
  | s == "pi"    = pi : stack
  | s == "e"     = (exp 1) : stack
  | otherwise    = (read s::Double):stack
  where top = head stack
        stack' = tail stack
        next = head stack'
        stack'' = tail stack'

rpn :: ([Double] -> [String] -> [Double])
rpn = foldl manipulateStack

solveRPN :: String -> Double
solveRPN s = head $ rpn [] $ words s

main = do
  args <- getArgs
  putStrLn $ show $ head $ rpn [] args


An algorithm that finds the number of "lined up columns"

You loop over all pairs, which costs O(n^2) time. This is not necessary.

You can partition your input in "good sets": such a set consists of all columns that are on a certain 45-degree line. Every column is in exactly two such sets. You can identify the set by - for instance - its intersection with the x-axis (which is always an integer) plus wether it is upward or downward. As an example, column 3, which has height 5, is in set -2 (upward diagonal) and set 8 (downward diagonal).

Create two hashmaps (one for upward, one for downward) with set identifier as key and number of columns in there as value. You can create these maps in linear time. Now, a set consisting of n columns has n choose 2 = n(n-1)/2 good pairs. Adding them all up gives your answer, still in linear time.

In code, that would be something like:

public static int CountGoodPairs(params int[] heights)
{
    var upCounts = new Dictionary<int, int>();
    var downCounts = new Dictionary<int, int>();

    for (var i = 0; i < heights.Length; i++)
    {
        var height = heights[i];
        IncrementCount(upCounts, i - height);
        IncrementCount(downCounts, i + height);
    }

    return upCounts.Values
                   .Concat(downCounts.Values)
                   .Sum(c => c * (c - 1) / 2);
}

private static void IncrementCount(Dictionary<int, int> counts, int key)
{
    var count = 0;
    counts.TryGetValue(key, out count);
    counts[key] = count+1;
}


Python vs Java performace: brute force equation solver

An obvious possible improvement for both languages is storing the values to the fifth power (But I'm going to focus on python here).

In python, while is a keyword and does not need parenthesis. Also, global lookup of methods is slower than local  lookup, so I would define pow = math.pow

pow = math.pow
while keep_searching:
    a += 1
    a5 = pow(a, 5)
    for b in range(1, a+1):
        b5 = pow(b, 5)
        for c in range(1, b+1):
            sum_begin = a5 + b5 + pow(c, 5)
            for d in range(1, c+1):
                sum = sum_begin + pow(d, 5)
                ...

Also note that python has an official style-guide, PEP8, which recommends putting spaces around operators and after commas in argument lists (I applied those rules in the code above).

Note that str.format does not care what it's parameters are. It will just call str on them and use that. So no need to call int on your parameters (they are already ints anyway).


Correct way to center logo and navigation

There is no real "correct" way to go about it; it all depends on how you want it to look. I can't quite speak to that, only the code you posted, and how it fares.

Anyway: Review.

General cleanliness

You should clean up your code (preferably before posting it, since many the following things should be fairly obvious). You've got a bunch of CSS that doesn't do anything:

There's a line that's just commented out: Remove it.
The #nav_links > img:hover doesn't affect anything. There's no img element immediately descendent from #nav_links
The #bottom_nav style (and indeed the entire element!) is pointless. It seems only to exist to clear any floats. But there are no floats. Similarly, the #nav_links li style has a float: none declaration which does nothing.
You can skip every single link ID (e.g. nav_whoweare); you're not using them. If you find yourself needing them, then add them. But not before.
You don't need width: 100% on the nav element. It's a block element, so it'll do that automatically.
You don't need display: inline-block on the ul element.

I'd also advice you to use a more logical order for you CSS rules. Right now it's haphazard:

#nav_links li a
#nav_links            << high-level
#nav_links li
#nav_links li a:hover << low-level

but it would make more sense to mirror the structure of the markup (and just the complexity of the CSS selectors):

#nav_links            << high-level
#nav_links li
#nav_links li a
#nav_links li a:hover << low-level

Class names and IDs

"It should be as simple as possible, but no simpler". In other words, only add stuff when there would otherwise be ambiguity.

For instance, there no reason to give the #nav_links list an ID. It's the only
 element inside #top_nav, so you can unambiguously reference it as simply #top_nav ul. Or, if you get rid of the bottom_nav element since it's not doing anything, you're left with simply nav ul. (You might want a bottom nav later, but cross that bridge when you come to it; not now).

Furthermore, don't use classes like nav_links_border. It's given that it's a navigation link, because it's inside the  element, and it's given that it's a link because it's an  element. So you CSS rule should target nav a rather than an overly specific class like a.nav_links_border.

What you're left with is just border, but that's not terribly descriptive. Looking at it overall, though, it's also obvious that all the links - with 1 exception - have a border. So, really, you'll want a way to treat the exception differently, rather than add a class to everything else.

I'd suggest giving the
 containing the logo an ID - simply call it logo. This lets you do two things:

You can style all the list items the same basic way, and only do something different for #logo
You can get rid of the ID on the  element, since you can instead reference it as #logo img

I get this:

WHO WE ARE

WHAT WE DO

EXPLORE

DONATE

And this:

nav {
    text-align: center;
}

nav ul {
    padding: 0 0 30px 0;
    list-style:none;
    text-align:left;
    white-space: nowrap;
}

nav li {
    vertical-align: text-top;
    display: inline-block;
    margin: 0 -3px 0 0;
}

nav a {
    padding: 15px 20px;
    text-decoration: none;
    font-family: Arial;
    font-size: 24px;
    color: #000;
    border-right: 1px solid #f37f43;
}

nav a:hover {
    text-decoration: underline;
}

#logo a {
    border: none;
}

#logo a:hover {
    text-decoration: none;
}

#logo img {
    width: 142px;
    height: 159px;
    padding-right: 20px;
}

Here's a jsfiddle - should look the same (apart from less margin, but that's because I remove the  tag from your code; jsfiddle add that itself; you shouldn't do it yourself)


First of all I would not use boost::range::for_each . There is already standard algorithm std::for_each in C++.

Secondly I would not use a lambda-expression if the algorithm with the predicate is used more than one time.

And if it is used only one time I would use the range-based for statement. For example

for ( const Person &person : vec )
{
    int age = person.getAge();

    if ( age < AGE_LOW_LEVEL )
    {
        age += 2;
    }
    else if ( age < AGE_HIGH_LEVEL )
    {
        age += 1;
    }
    else
    {
        age -= 5;
    }

    result.insert( { person.getName(), age } );
}


Re-worked Workbook_Open, Creating DateStrings

First thought: It feels really rewarding to see a new User who takes on advice that's offered and proactively uses it to improve.

Second thought: MUCH, MUCH better. Now if you (or somebody else) ever has to come back to this code, it's going to be crystal clear what everything does and how it all works.

One more improvement:
Stop this right now.

Dim strTableTitle       As String
Dim StrTodaysDate       As String
Dim StrThisDay          As String
Dim StrThisMonth        As String
Dim StrThisYear         As String

Dim strSaveFileFolder   As String
Dim StrSaveFilename     As String
Dim StrSaveDate         As String

I  get it, it looks really pretty. I was exactly the same when I started. Here's the thing though good code isn't pretty. Clear, concise, consistent, tidy, but not necessarily pretty. Pretty takes time. Time that could be spent actually improving your code.

Plus, if you ever change any of those variable names, it's going to be a real pain getting it all to line up again, especially if you write one that's longer than the current ones.


Python - Input Filtering, Calculating with a Variable Amount of Inputs

Welcome to Code Review! I'll be adding onto what @Linny has already said about type hints and variable naming. Variable naming is part of python's PEP-8 guidelines (see bottom).
Magic numbers
You have a lot of magic numbers in your code, which are really conversion constants, but appear with no such explanation.
Variable names
Since you're writing an aerodynamics calculator, it'd help if you use full names for various variables in your code. For eg. altitude instead of alt, temperature instead of just temp (temp is generally used as a temporary variable in code).
Ground temperature
Based on the flow of program, I assume that ground_temperature is essential for any calculations. Perhaps check for it at the very beginning and break early in case of invalid checks.
Optional arguments
From the above, only ground_temperature is needed to call the calculator. Everything else is optional, and can be computed. Perhaps a function which defaults other values to None might suit you better:
def aerodynamic_calculator(
    ground_temperature: float,
    temperature: float = None,
    altitude: float = None,
    pressure: float = None,
    density: float = None,
):

Booleans for each parameter
With the above approach, you can just validate for the value itself, without having to keep track of a boolean for those values.
if temperature and not altitude:
    altitude = compute_altitude_from_temperature(temperature, ground_temperature)

PEP-8
In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.
Functions and variables should be named in a lower_snake_case, classes as UpperCamelCase, and constants as UPPER_SNAKE_CASE.


Find the intersection of ArrayList elements inside an ArrayList

Approaching programming interview questions

One of the most important things during programming interviews is clarifying the problem.
If the task is intersection of lists as opposed to sets,
an important question is how to handle duplicate values.

For example, the current implementation is buggy.
The intersection method will return a,a,a for the input a,a,a and a,a, but it will give a,a for the input a,a and a,a,a.
The logical assumption would be that it should always return a,a regardless of the order of parameters.
Then again, you should not just assume things,
you should ask for the expected behavior,
or at least state your assumptions loud and clear.

And if there can be no duplicates in the inputs,
then why aren't they sets instead of lists?

Why is ArrayList specified instead of just List?
ArrayList is a specific implementation,
when List is the general concept.

Generic type tokens

String, the name of a common class in the JDK,
and written in PascalCase,
is a terrible choice for a generic type token in this code:

public <String> List<String> intersection(List<String> list1, List<String> list2) {
    List<String> list = new ArrayList<String>();

    for (String t: list1) {
        if(list2.contains(t)) {
            list.add(t);
        }
    }

    return list;
}

It should have been written like this:

public static <T> List<T> intersection(List<T> list1, List<T> list2) {
    List<T> list = new ArrayList<>();

    for (T t : list1) {
        if (list2.contains(t)) {
            list.add(t);
        }
    }

    return list;
}

Intersection of many lists

  But how do I make it work for multiple ArrayLists inside one ArrayList?

I'm not sure I get what's blocking you.
Perhaps you mean, instead of the intersection of 2 lists,
how to intersect more than 2?

In that case,
that's an interesting question to discuss about,
and consider different alternatives,
starting from simple (brute force) techniques,
and then trying to improve.

Simple solution: if you have n lists, you could intersect the first 2,
then intersect the result with the 3rd,
then intersect the result with the 4th,
and so on, until the last.
The final result will be the intersection of all the lists,
reachable in n - 1 steps.

Is it possible to do better?

Hint 1: consider the concept of divide and conquer.
Hint 2: how does merge sort work?


The biggest change you can do is to the value function. Because most of what you are building is actually provided via HashMap'sentry API. This could reduce the body of your value function to simply this:

match self.values.entry(arg) {
    Entry::Occupied(val) => val.into_mut(),
    Entry::Vacant(slot) => slot.insert((self.calculation)(arg)),
}

You could also mess with Entry's or_insert_with function, but I personally prefer the approach above.

You may also consider using Clone instead of Copy. The advantage of Clone are that it is more explicit and that it should support more types. The disadvantage obviously is that clone can be arbitrarily expensive. In general I'd say you want Clone for a generic interface such as this.

Finally, I understand it's an exercise, but the names are a bit plain:

Cache is very generic: what do you actually cache? Call it something like FunctionResultCache or Memoizer
value is also a bit weird. What you're doing in essence is wrapping a function, so I'd name this call or invoke or something similar.


A tiny util to converts an SO URL to revised version

I'd suggest making this a function - while as a oneliner, it's good as is, when we start scaling it, adding in more cases, etc., it becomes a mess that requires rearranging for even the tiniest changes.

But first, let's start off with the changes I'd suggest.

First off, I'd like to slightly adjust your regex to handle URL parameters:

\/\d{3,9}(\/?\?([\-\w%*.~]+=[\-\w%*.~]+(&*))*)?$

The explanation is below. Also, to make it a bit easier for us later, we'll wrap this all in a capture group (simply surround with brackets).

(  # Start main set
  \/\d{3,9}  # Find any '/' character followed by 3-9 numbers
  (  # Start 'Parameter' set, which matches any query parameters
    \/  # Match '/' character...
      ?  # ... optionally
    \?  # Match escaped '?' character
    (  # Start 'Parameter List' set
      [\-\w%*.~]  # Character set, according to HTML5 spec (parameter name)
                +  # Match as many characters as possible
      =  # Followed by equals
      [\-\w%*.~]  # Character set, according to HTML5 spec (parameter value)
                +  # Match as many characters as possible
      (&*)  # Optionally match any '&' characters on the end.
    )  # End 'Parameter List' set
      *  # 'Parameter List' set is optional, but can also be repeated infinite times.
  )  # End 'Parameter' set
    ?  # Parameter set is optional
)
  $  # The match should be at the end of the string

It's fine that we're matching the query parameters with the last set of numbers (which we're going to delete), i.e it's not a problem that we delete the query parameters, because using the same parameters on a different page would be fairly useless.

Next, I'd put all of your code in a function block:

def convertURLToRevisionsFromQ(url):

Note how we're taking url as an argument, not as a user input.

The next step is to implement some basic error-checking, to throw some ValueErrors. Error handling manually is always superior to either catching built-in errors, or, even worse, not doing anything about them. So, we'll write an error handling helper function inside our main function, like so:

def throwInvalidInputError(err):
  raise ValueError("Invalid URL type! Error: " + err)

We can now do some error checking right off the bat, before we go on with processing the URL:

question_path_search = re.search('(\/q(uestions)?\/)', url)

if "stackoverflow.com/" not in url:
  throw_invalid_input_error("URL not from Stack Overflow.")
if len(url) < 23 or not question_path_search:
  throw_invalid_input_error("URL not from a Stack Overflow question path.")

You can see that we are also accepting /questions/ as valid, since we'll add support for those paths too in a moment.

The next change I'd suggest is to add support for URLs which don't necessarily have both number sequences, e.g https://stackoverflow.com/q/57449318 as opposed to https://stackoverflow.com/q/57449318/10731613. We're also going to bring in our Regex here, since we're finally going to start matching the ending. The only difference is, the 'ending' bit we need to remove will count as either only the query parameters, in the case of just one number sequence, or the last number sequence and the query parameters, in the case of two number sequences. So, we'll do the following:

matched = re.search('((\/?\?([\-\w%*.~]+=[\-\w%*.~]+(&*))*)?$)', url)
ending = matched[0]

if not matched:
  throw_invalid_input_error("Could not find question IDs in valid format!")

if len(re.findall('\/\d{3,9}', url)) > 1:
  matched = re.findall('(\/\d{3,9}(\/?\?([\-\w%*.~]+=[\-\w%*.~]+(&*))*)?$)', url)
  if not matched:
    throw_invalid_input_error("Could not find question IDs in valid format!")

  ending = matched[-1][0]

if len(matched) > 1:
  throw_invalid_input_error("Malformed URL")

Now, it's mostly just your code, except we'll add in one more flexibility: allowing both /q and /questions. To do this, we'll just use the question_path_search variable, which we defined earlier. Grab the first capture group from it, and that will be the version of /q vs /questions we'll use:

question_path = question_path_search[0]

url = url.replace(ending, '', 1)\
  .replace(question_path, '/posts/', 1)\
  + 'revisions'

Finally, we'll just do return url.

So, here's our final code, with a bit of testing code at the bottom:

import re

def convertURLToRevisionsFromQ(url):
  def throw_invalid_input_error(err):
    raise ValueError("Invalid URL type! Error: " + err)

  question_path_search = re.search('(\/q(uestions)?\/)', url)

  if "stackoverflow.com/" not in url:
    throw_invalid_input_error("URL not from Stack Overflow.")
  if len(url) < 23 or not question_path_search:
    throw_invalid_input_error("URL not from a Stack Overflow /q question path.")

  matched = re.search('((\/?\?([\-\w%*.~]+=[\-\w%*.~]+(&*))*)?$)', url)
  ending = matched[0]

  if not matched:
    throw_invalid_input_error("Could not find question IDs in valid format!")

  if len(re.findall('\/\d{3,9}', url)) > 1:
    matched = re.findall('(\/\d{3,9}(\/?\?([\-\w%*.~]+=[\-\w%*.~]+(&*))*)?$)', url)
    if not matched:
      throw_invalid_input_error("Could not find question IDs in valid format!")

    ending = matched[-1][0]

  if len(matched) > 1:
    throw_invalid_input_error("Malformed URL")

  question_path = question_path_search[0]

  url = url.replace(ending, '', 1)\
    .replace(question_path, '/posts/', 1)\
    + 'revisions'

  return url

res = convertURLToRevisionsFromQ(input("Enter Stack Overflow URL: "))
print(res)

Not so 'tiny' any more, but it's definitely more adaptable, and will probably work with few adjustments to whatever similar problem you throw at it. Now, it's more generally a URL path redirector, than just some ultra-specific code to solve an ultra-specific problem.


You have access to the stack array directly so you can copy the unsorted stack it to a new stack and sort it in place using Array.sort

"use strict";
function sortStack(stack) {
    const sorted = new Stack();
    while (!stack.isEmpty()) { sorted.push(stack.pop()) }
    sorted.storage.sort((a, b) => a - b);
    return sorted;
}

or

"use strict";
function sortStack(stack) {
    const sorted = new Stack();
    sorted.storage = [...stack.storage].sort((a, b) => a - b);
    return sorted;
}

If they did not want you to access the storage array directly they would have protected it in closure. (well if that crossed their minds)

BTW your should always add "use strict" to the top of your javascript code as you have neglected to declare any of your variables, making them all global and setting your self up for some horror bugs.

The use strict directive will not let you use undeclared variable.


NHibernate select with Query Over optimization for user roles base case

If this is a web application, you can use an HttpModule to do your session management. Begin every web request by opening a session and beginning a transaction. At the end of every web request, commit the transaction and close the session.

As long as you're wrapping all the hits to the database in a single transaction, you don't need to worry about efficiency too much.


Calculate future date based on business days

I propose a class, BusinessDayCalculator, which would handle all this logic in one place. Here's an example:

<?php

class BusinessDaysCalculator {

    const MONDAY    = 1;
    const TUESDAY   = 2;
    const WEDNESDAY = 3;
    const THURSDAY  = 4;
    const FRIDAY    = 5;
    const SATURDAY  = 6;
    const SUNDAY    = 7;

    /**
     * @param DateTime   $startDate       Date to start calculations from
     * @param DateTime[] $holidays        Array of holidays, holidays are no conisdered business days.
     * @param int[]      $nonBusinessDays Array of days of the week which are not business days.
     */
    public function __construct(DateTime $startDate, array $holidays, array $nonBusinessDays) {
        $this->date = $startDate;
        $this->holidays = $holidays;
        $this->nonBusinessDays = $nonBusinessDays;
    }

    public function addBusinessDays($howManyDays) {
        $i = 0;
        while ($i < $howManyDays) {
            $this->date->modify("+1 day");
            if ($this->isBusinessDay($this->date)) {
                $i++;
            }
        }
    }

    public function getDate() {
        return $this->date;
    }

    private function isBusinessDay(DateTime $date) {
        if (in_array((int)$date->format('N'), $this->nonBusinessDays)) {
            return false; //Date is a nonBusinessDay.
        }
        foreach ($this->holidays as $day) {
            if ($date->format('Y-m-d') == $day->format('Y-m-d')) {
                return false; //Date is a holiday.
            }
        }
        return true; //Date is a business day.
    }
}

$calculator = new BusinessDaysCalculator(
    new DateTime(), // Today
    [new DateTime("2014-06-01"), new DateTime("2014-06-02")],
    [BusinessDaysCalculator::SATURDAY, BusinessDaysCalculator::FRIDAY]
);

$calculator->addBusinessDays(3); // Add three business days

var_dump($calculator->getDate());

In the above example the nonBusinessDays of the week are SATURDAY and FRIDAY, and 1st and 2nd of June are holidays. In that case, 3 business days from now is June 5th.

This can probably be improved further, let your imagination run wild :P


Java splitting too large text file enhance performance

As said in the comment, you program is slow because you load the full file in memory. To change that you should keep only your first loop where you read but also write and split into files.

while(scanner.hasNext()){
    str+=scanner.nextLine()+"\n";
    if ( mustSplit(str) ) {
        writeToAnotherFile(str);
        str = "";
    }
}


These things are very much a matter of preference but I would go for something like:

mails = [ @note.cc_emails,
          @note.to_emails ].compact.join('')

which tends to remain usable as you add more clauses


Remove the additional ()s in the statusFilter and employeeFilter lines as they are unnecessary.
Indent the statusFilter and employeeFilter lines so that they are symmetrical with the search lines.
Change search to be searchTerm as it is more specific.  search by itself could mean anything like a stored query, a boolean value, etc.
As per Magus' comment you can change t to task since it is more clear and will not add space that starts pushing statements across extra lines.

var tasks = db.Tasks
  .Include(task => task.Employee)
  .Include(task => task.Status)
  .Where(task =>
    (
      searchTerm == null ||
      task.Employee.FirstName.Contains(searchTerm) ||
      task.Employee.LastName.Contains(searchTerm) ||
      task.Employee.EmployeeId.Contains(searchTerm)
    ) &&
    (
      statusFilter == null ||
      task.StatusId = statusFilter.Value
    ) &&
    (
      employeeFilter == null ||
      task.EmployeeId == employeeFilter
    )
);


For a 3x3 tic-tac-toe board it hardly provides any real advantage, but if you where to play on an nxn board, with n consecutive same player marks determining a winner, you could do the following...

class TicTacToe(object):
    def __init__(self, n=3):
        self.n = n
        self.board = [[0 for j in range(n)] for k in range(n)]
        self.row_sum = [0 for j in range(n)]
        self.col_sum = [0 for j in range(n)]
        self.diag_sum = 0
        self.diag2_sum = 0

    def add_move(self, player, row, col):
        assert player in (0, 1)
        assert 0 <= row < self.n and 0 <= col < self.n
        delta = [-1, 1][player]
        winner = None
        self.board[row][col] = delta
        self.row_sum[row] += delta:
        if self.row_sum[row] = delta * self.n:
            winner = player
        self.col_sum[col] += player:
        if self.col_sum[col] = player * self.n:
            winner = player
        if col == row:
            self.diag += delta
            if self.diag == delta * self.n:
                winner = player
        if row == self.n - row - 1:
             self.diag2 += delta
             if self.diag2 == delta* self.n:
                 winner = player
        return winner

You basically initialize the board to all zeros, use -1 for one player and 1 for the other, and keep track of the sum of values in each row, column and diagonal. Whenever you add a new move, you can update all your data in constant time, and check in constant time if the player has won.


Changing php.ini with code in a LEMP stack on Debian systems

By doing ad hoc editing like that, you're making certain assumptions about what the php.ini configuration currently looks like.  For example, you have assumed that the size limits end with M, and that those lines are not commented out.  You have also assumed that the cgi.fix_pathinfo line is commented out.

There are two better ways that I prefer.

The simple solution is to put all of the local overrides together in one file.  From the PHP manual:

  Within each directory, PHP will scan all files ending in .ini in alphabetical order.

So, instead of editing, simply create a file with a name like /etc/php/7.0/fpm/zz_overrides.ini containing four lines:

[PHP]
post_max_size = 200M
upload_max_filesize = 200M
cgi.fix_pathinfo = 0

This has the benefit that you leave all of the distro-provided configuration files in their pristine state, and won't need to merge your changes when upgrading.  The disadvantage is that you will need to keep in mind where to look for the effective settings — but that's not hard if you make it a habit.
Alternatively, use augtool, which is a configuration file editor, as in this example.


MVVM model letting the user select a directory in a testable manner

Review

You always instantiate inner dialogs for both platforms, even though one will never be called. Your platform will not change at runtime. Use the Lazy pattern to only instantiate the required dialog at first access.
Rather than returning the magic path null, I would opt to use a TryShow method returning a boolean whether a path got selected an an out parameter for the path.

Object Destruction

From Programming Guide: Destructors:

  The programmer has no control over when the finalizer is called
  because this is determined by the garbage collector. The garbage
  collector checks for objects that are no longer being used by the
  application. If it considers an object eligible for finalization, it
  calls the finalizer (if any) and reclaims the memory used to store the
  object.

Since your class is not sealed, derived classes can be made. These classes will not be able to control the order of finalisation code. The order of destructors is fixed as this snipped from the link shows:

protected override void Finalize()
{
    try
    {
        // Cleanup statements...
    }
    finally
    {
        base.Finalize();
    }
}

That's why you should implement the dispose pattern instead. It allows for more flexibility in flow and distinguishes between disposing managed vs unmanaged code.

Unit Tests

  My reasoning for this design is that now the 3 readonly variables can be mocked in unit tests via reflection, while this isn't an ideal way
  of doing it, it's better than nothing.

When writing code with testability in mind, you don't want to resort to reflection to mock private state of your classes. There are a couple of options available:

Make the private methods protected virtual. Mocking frameworks and derived classes are able to override the methods. Partial mocks could be used in this case.
Wrap both internal dialogs behind a custom interface, injected into the outer class. The class no longer has dependencies on native win and vista components and interfaces are easy to mock.


Helper methods

    int  numOfTestCases = 0;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter number of test cases");

    try {
        numOfTestCases = Integer.parseInt(input.nextLine().trim());
    }
    catch (NumberFormatException e) {
        System.err.println("You must enter an number" );
        System.exit(1);
    }

You can rewrite this as

    Scanner input = new Scanner(System.in);
    System.out.println("Enter number of test cases");

    int remaining = inputInteger(input);
    input.nextLine();

With

public static void inputInteger(Scanner input) {
    try {
        return input.nextInt();
    } catch (NumberFormatException e) {
        System.err.println("You must enter a number" );
        System.exit(1);
    }
}

This saves having to separate declaration and initialization of the variable.  Now you can do both in one line.

I prefer the name remaining to numOfTestCases.  Why may become clearer when you see how I use it.

You don't need to jump through hoops to get an integer with a Scanner.  There's a method just for that.

Don't overcomplicate things

    boolean validInput = false;
    for (int i = 0; i < numOfTestCases ; i++) {
        validInput = false;

        while (!validInput)
            try {

                String maxEatingInput = input.nextLine();
                String[] individualEatingCaps = maxEatingInput.trim().split("\\s+");
                maxEatingCaps_Limark.add(Integer.parseInt(individualEatingCaps[0]));
                maxEatingCaps_Bob.add(Integer.parseInt(individualEatingCaps[1]));
                validInput = true;

            } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                System.err.println("Enter in the form: INTEGER:(Limark's Max Eating Capacity) INTEGER:(Bob's Max Eating Capacity)");
                validInput = false;

            }

    }

}

You don't need validInput.  Consider

    while (remaining > 0) {
        try {
            String maxEatingInput = input.nextLine();
            String[] individualEatingCaps = maxEatingInput.trim().split("\\s+");
            maxEatingCaps_Limark.add(Integer.parseInt(individualEatingCaps[0]));
            maxEatingCaps_Bob.add(Integer.parseInt(individualEatingCaps[1]));
            remaining--;
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
            System.err.println("Enter in the form: INTEGER:(Limark's Max Eating Capacity) INTEGER:(Bob's Max Eating Capacity)");
        }
    }

This saves you two variables and a loop and gives the same result.

Note that you could also drop down to

    while (remaining > 0) {
        try {
            maxEatingCaps_Limark.add(input.nextInt());
            maxEatingCaps_Bob.add(input.nextInt());
            remaining--;
        } catch (NumberFormatException e) {
            System.err.println("Enter in the form: INTEGER:(Limark's Max Eating Capacity) INTEGER:(Bob's Max Eating Capacity)");
        }
    }

But this doesn't enforce the two numbers per line requirement.  Up to you if you care.

Equations over iteration

You don't have to iterate through the candy.  You can do the quadratic formula instead.

$$\frac{(n + 1)^2}{4} = m$$

Where \$n\$ is the number of candies that first bear eats and \$m\$ is the maximum for that bear.  Solving for \$n\$ gives

$$n = 2\sqrt{m} - 1$$

Rounding down to an odd integer gives the last number of candies that bear can eat. Add 2 to give the first number that it can't eat.  Now do the equivalent for the second bear.

$$n(n+1) = m$$

And the quadratic formula gives

$$n = \frac{-1 \pm \sqrt{1 + 4m}}{2}$$

Negative numbers aren't meaningful here, so

$$n = \frac{\sqrt{4m + 1} - 1}{2}$$

Round down to an even integer to get the last number of candies that can be eaten.

Whoever gets farther wins.

Now you just have to turn those equations into Java.


Roughly:

twitter = Twitter::Client.new

img, max = @post.image ? [@post.image.path.to_s, 120] : ["", 140]
twitter.update("#{@post.content.truncate(max)}#{img}")

redirect_to root_path

All the Twitter stuff shouldn't be in the controller, rather in a utility class. This makes testing easier, makes plugging in implementations easier, makes extension easier, and so on.

Also, truncate should be already adding the "..." if truncation was necessary.

Personally, I prefer Amit's answer. IMO it's easier to read and more obvious than mine.

I would probably tighten it up a bit after an initial review to something like this:

s = @post.image ? "#{@post.content.truncate(120)}... #{@post.image.path.to_s}"
                :    @post.content.truncate(140)
twitter.update(s)

It's formatted to highlight the similarities between the two, another option is to use string interpolation again, but it seems redundant in this particular case.

(Obviously the string creation would go into a method in some sort of support decorator etc.)

All the above is untested, but probably close.


Since you are concerned about execution speed, you should write this program in some other programming languages as well and compare their performance. I'd take Java, C++, Go, Perl, Python and Rust. Traditionally, AWK gets the job done but is not optimized for processing huge amounts of data.

Instead of setting FS on the command line, it should be in a BEGIN clause since it is an essential part of the program:

BEGIN {
    FS = /[[:digit:]]+/;
}

Asking for code that is not yet implemented is off-topic on this site, so I won't comment much on that. The code will become much larger by that requirement though and will require more thought. Be prepared to have a collection of small sample files to test the edge cases automatically.


Really good library.

Here are my proposals:

1) Annotation mapping it would be really cool to use annotations (in spring boot application for example) like this:

@RstreamerProcessor
public class SampleWorker {

    @RstreamerListener(queue = "my:task:queue")
    public void processSingleItem(String item) {
        System.out.println("Got item: " + item);
    }
}

2) Add the library to maven central(publish artifact) or another repository and describe the usage on README.md

3) Consider to add Spring boot starter spring-boot-custom-starter

4) Add version compatibility table rstreamer to jedis and resilience4j.

5) It would be nice to have exception handling section with samples and description of errors and best practices to handle them.


sizeof(a) in this case is sizeof(int*) which is 4 or 8 on most machines. The most simple solution would be passing the length of the input array. Otherwise, your code looks nifty.


Questions

Is it a good practice to solve such task in this manner?

Yes. Sort of.
Distributing work across threads will get the work done quicker usually (especially when there is no interactions between threads).
BUT: The cost of spawning threads is relatively high. Doing it for such a simple problem may not be worth the cost (you should time it and try). So I am going to assume this is a trivial example just for review.
Normally you would spin up your threads into a generic pool. Then send the job to the pool for processing. The threads will continue to live after they have done the job waiting for more jobs to be added to the pool
Secondly this is a very low level interface.
C++ has added the concept of future and promise as a higher level interface to threading.

If it is, do I optimally pass and receive parameters in thread_func?

Sure that looks fine.
Code Review
So here ds is a shared resource used by all threads.
void thread_func(Iterator b, Iterator e, Distributions& ds)

If there is any mutation in this object then any gains can immediately be lost because of contention. So either the usage of this object has to be very well known or it needs to be const. To prevent contention you should make that a read only object that is shared across the threads.
So even if there is only 1 for concurrency you are spinning up threads?
    auto nthreads = std::thread::hardware_concurrency() ?: 1;

If you want to use this I would check that you have more than one core available.
    auto nthreads = std::thread::hardware_concurrency();
    if (nthreads < 2) {
        thread_func(std::begin(events), std::end(events), distributions);
    }
    else // Do it in parallel.
    {
    }

Don't rely on statement size scope:
    for (int i = 0; i < 10; i++)
        distributions.emplace_back(5);

It is just as easy to write:
    for (int i = 0; i < 10; i++) {
        distributions.emplace_back(5);
    }

This will protect you from accidental errors.
You don't need to re-calculate these every time.
        auto left  = begin(events) + nparts * i;
        auto right = begin(events) + nparts * (i+1);

Also if you update your code to use another container (or any generic container) the operator+ may not work. You should be using std::advance()
auto  segmentBegin = begin(events);
auto  segmentEnd   = segmentBegin;
std::advance(segmentEnd, nparts);

for (int i = 0; i < nthreads - 1; i++) {
   threads.emplace_back([l=segmentBegin, r=segmentEnd, &d=distributions] { thread_func(l, r, d); });

    segmentBegin = segmentEnd;
    std::advance(segmentEnd, nparts);
}
threads.emplace_back([l=segmentBegin, r=std::end(events), &d=distributions] { thread_func(l, r, d); });

Iterators are very cheap objects.
 l=std::move(left), r=std::move(right)

don't see the need to move them.


A few things.

When you connect, don't hard code mysql, you are already fetching all the db info from a registry/config ... make the the dbtype configurable as well. That is after all, the point of PDO.

When you catch errors in connection or when executing a query, use the PDOException class

use exceptions for your prepare and execute calls instead of counting the errors that happens...as that's not really useful (it will be obvious an error happened, what I care about is what that error actually is).

personally, I would break down this class into specific methods. instead of connecting to the db in the constructor, I would have a connect() method to do this. I would also have a query, prepare, and bind method and then have interaction method: delete, update, insert and then a set of fetch methods, fetchOne, fetchAll, fetchCol, etc.

Also the connect method would check for a set conn, and only attempt to connect if you didn't already have an existing connection. The query method would call connect(). The reason for this is that you may include your db class throughout your code, even if you dont fetch anything in particular requests...with your code if this is the case a connection will be made regardless. What you want is lazy loading...meaning a db connection will only be made if you actually attempt to use the db with a fetch/update/delete/insert/etc.

Here is some sample pseudo code

$db = new MyPdoClass();
$db->connect();
$stmt = $db->query($sql, $params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// or call your MyPdoClass::fetchAll, which would do that so you would just call
$results = $db->fetchAll($sql, $params);


Your rawData (which should be ideally named raw_data, python suggests a style guide to name variables and functions in lower_snake_case) is already in a list structure. You can manipulate this in place, without having to process the whole dataset manually.
for row in raw_data:
    row.update(row.pop("prices"))


This code is written very idiomatically, so I don't have any style points.

For speed, the first thing to do is use PyPy. That gives a 5x throughput improvement.

Then one should consider your algorithm. A quick run with cProfile gives

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  8420076    1.231    0.000    1.231    0.000 p.py:5(<listcomp>)
  1414943    0.966    0.000    0.992    0.000 p.py:14(all_unique)
  1414943    0.557    0.000    2.462    0.000 p.py:8(make_triangle)
  1414943    0.504    0.000    0.504    0.000 p.py:18(<listcomp>)
  8420076    0.477    0.000    1.708    0.000 p.py:4(next_level)
        8    0.275    0.034    4.347    0.543 p.py:23(stable_triangles)
  8421251    0.114    0.000    0.114    0.000 {method 'append' of 'list' objects}
12667944/12667894    0.109    0.000    0.109    0.000 {built-in function len}
  1414943    0.077    0.000    1.610    0.000 p.py:20(is_stable)
  1414943    0.037    0.000    0.541    0.000 p.py:17(flatten1)
        1    0.020    0.020    4.466    4.466 p.py:1(<module>)

This means that next_level is taking a considerable amount of time. I noticed it's better written

[left + right for left, right in zip(level[:-1], level[1:])]

but this doesn't change speed much.

The first useful thing I would consider is interspersing generation and testing to prevent many calls to next_level. This also prevents the need to keep the whole triangle - one only needs the base and current row. This can be done by making triangle yield rows instead.

from itertools import permutations

def next_level(level):
    return [left + right for left, right in zip(level[:-1], level[1:])]

def make_triangle(base):
    row = base

    while row:
        yield row
        row = next_level(row)

def is_stable(triangle):
    seen = set()

    for row in triangle:
        if not seen.isdisjoint(row) or len(row) != len(set(row)):
            return False
        seen.update(row)

    return True

def stable_triangles(base_length):
    for base in permutations(range(base_length * 2), base_length):
        if is_stable(make_triangle(base)):
            yield make_triangle(base)

This is pretty fast comparatively. Not fast enough, though!

Here's where we get to the really interesting parts.

Consider some unique triangle:

    9
  3   6
1   2   4

and the next

     26
    9  17
  3   6  11
1   2   4   7

It's not a coincidence that one is a superset of another. In fact, is must be so. For any non-trivial unique triangle, there are subsets you can find by dropping the left or right hand side.

So consider building them up in this manner, filtering as early as possible. One problem is that we need a value limit to prevent infinite recursion. Luckily, I can choose the same rule you already have to avoid changing behaviours:

def next_level(level):
    return [left + right for left, right in zip(level[:-1], level[1:])]

def make_triangle(base):
    row = base

    while row:
        yield row
        row = next_level(row)

def is_stable(triangle):
    seen = set()

    for row in triangle:
        if not seen.isdisjoint(row) or len(row) != len(set(row)):
            return False
        seen.update(row)

    return True

def stable_triangle_bases(base_length, limit):
    if base_length < 0:
        raise ValueError("Base length must be nonnegative")

    if not base_length:
        yield ()
        return

    for base in stable_triangle_bases(base_length - 1, limit):
        for i in range(limit):
            if is_stable(make_triangle(base + (i,))):
                yield base + (i,)

if __name__ == "__main__":
    for base_length in range(40):
        print(list(next(stable_triangle_bases(base_length, limit=base_length * 2))))

This works really well - up to about length 300 or so, in fact.

I suppose we could try to speed this up more, but that seems beside the point. We want to find the minimum. Well, this isn't totally pointless - we can just run a min with a good key on our result. Unfortunately, though, I haven't managed to get past

                                1001
                             523     478
                         309     214     264
                     195     114     100     164
                 125      70      44      56     108
              79      46      24      20      36      72
          48      31      15       9      11      25      47
      27      21      10       5       4       7      18      29
  14      13       8       2       3       1       6      12      17

with that code.

Further, a limit of base_length * 2 is not optimal. Consider the triangle

                              1000
                           485     515
                       273     212     303
                   171     102     110     193
               112      59      43      67     126
            73      39      20      23      44      82
        46      27      12       8      15      29      53
    28      18       9       3       5      10      19      34
17      11       7       2       1       4       6      13      21

!

Raising the limit makes things even slower - an unbounded limit would take forever!

One conceptually easy, but extremely effective, change is to apply a heuristic to the search. This says that if we have found a triangle of cost \$k\$ and our new path could not give us a cost lower than that, do not try the path.

I originally avoided this because I could not think of a strong enough heuristic. It turns out, though, that it's really simple. Consider this unfinished triangle:

       ??
     ??  ??
    9  ??  ??
  3   6  ??  ??
1   2   4   x  ??

We are going to place onto x next, for all values that will fit. Fill in the unknowns on the base with the minimal values that fit, pushing larger numbers to the edges.

In this case, we cannot add 1, 2, 3 or 4, so we fill in a 5. Treat the x as a 0 for now:

       38
     19  19
    9  10   9
  3   6   4   5
1   2   4   x   5

Note that the duplicates here are allowed, as removing them requires knowing the value of x.

Further, consider the contribution of x:

       4x
      x  3x
    0   x  2x
  0   0   x   x
0   0   0   x   0

We can add these two triangles together, giving a top value of

4x + 38

as our heuristic. Now when outputting results, we can ignore any branches where the heuristic brings us above (or equal to) that. (If you want all of the best options, use strict inequality. If you only need one, use non-strict inequality.)

Here is some code to try. It is not particularly pretty, but it works and is pretty fast.

from itertools import chain, count

def pascal_row(row):
    val = 1
    yield val
    for k in range(row):
        val *= row - k
        val //= k + 1
        yield val

def make_triangle(row):
    while row:
        yield tuple(row)
        row = [left + right for left, right in zip(row[:-1], row[1:])]

def heuristic_minimum(base_so_far, length):
    used = set().union(*make_triangle(base_so_far))
    unused = (x for x in count(1) if x not in used)

    factors = pascal_row(length - 1)
    raw_cost =  sum(a * b for a, b in zip(base_so_far, factors))
    x_factor = next(factors)
    raw_cost += sum(a * b for a, b in zip(unused, sorted(factors, reverse=True)))

    return x_factor, raw_cost

def is_stable(triangle):
    seen = set()

    for row in triangle:
        if not seen.isdisjoint(row) or len(row) != len(set(row)):
            return False
        seen.update(row)

    return True

def stable_triangle_bases(base_length, upper_bound, full_length):
    if base_length < 0:
        raise ValueError("Base length must be nonnegative")

    if not base_length:
        yield ()
        return

    for base in stable_triangle_bases(base_length - 1, upper_bound, full_length):
        x_factor, min_const_cost = heuristic_minimum(base, full_length)

        for i in count(1):
            cost = i * x_factor + min_const_cost

            if cost >= upper_bound.value:
                break

            if is_stable(make_triangle(base + (i,))):
                if base_length == full_length:
                    upper_bound.value = cost

                yield base + (i,)

class UpperBound:
    def __init__(self):
        self.value = float("inf")

if __name__ == "__main__":
    base_length = 10

    bases = stable_triangle_bases(
        base_length,
        UpperBound(),
        base_length
    )

    for result in bases:
        print(result)

This will print the improving bound as time progresses.

To top this off, here's a nice big triangle:

                                      4497
                                  2301    2196
                              1298    1003    1193
                           778     520     483     710
                       479     299     221     262     448
                   296     183     116     105     157     291
               181     115      68      48      57     100     191
           109      72      43      25      23      34      66     125
        65      44      28      15      10      13      21      45      80
    38      27      17      11       4       6       7      14      31      49
20      18       9       8       3       1       5       2      12      19      30


Validating a model and focus to the element if validation fails

I'm not very familiar with Backbone, however I do have a couple of comments:

To simplify your life, check out Marionette Forms. It can handle quick validation of forms. This is an alternative to Backbone Forms, which is generally more demanding in terms of code needed.
The following snippet:

if(!validUser){
    $(e.target).find('#userName').select();
} else{
    $(e.target).find('#userName').next(':input').select();
}

if(!validPass){
    $(e.target).find('#userName').select();
}

could simply be:

if (validUser && validPass) {
    $(e.target).find('#userName').next(':input').select();
} else {
    $(e.target).find('#userName').select();
}


First off, the file jsonArray.js doesn't contain "JSON". It's a JavaScript source code file containing an JavaScript array literal which in turn contains JavaScript object literals. And since it's not JSON, you could theoretically put functions into the objects:
{
  alt: "clearValueIcon", // Quotes around key are not needed, since it's not JSON
  src : "...", // shortened
  style: "grid-column:1/2;grid-row: 2/3;",
  handler() {
     this.value = ""; // For example
  }
},

And with a helping method:
methods: {
  callHandler(handler) {
     handler.call(this);
  }
}

<img
     v-for="img in imagesData"
     :key="img.alt"
     @click="callHandler(img.handler)"
     :alt="img.alt"
     :src="img.src"
     :style="img.style"
/>

However I don't really see the point of outsourcing the buttons into a data array like this. Unless you are using the array in some other way in the project, you should just straight up have a list of imgs (or custom "button" components) in your template.
Two more things:

The styles belong in the style sheet.
The chosen texts for the alt attributes are bad. They are supposed to be fallback texts that displayed to the user in the case the images can't be displayed to (or seen by) the user. For the shown buttons something like "Clear", "+/-" and "%" would be better choices.

EDIT: One more thing: You shouldn't be using a plain image with a click handler, but for accessability wrap them in a <button> (or <a>) and put the handler on them.


Extending Sieve of Eratosthenes beyond a billion

A few things you can do:

Use a bit vector (with bit manipulation) instead of a bool array. This gives you 8 times more memory. If you use C++ vector< bool> you get this optimization for free.
Store only odd numbers in the array. This will save additional factor of 2 in memory. You need to adapt the logic of the program a little bit, but this is not extremely difficult. This saves also some time because in the first iteration the algorithms just marks half of the numbers.
The outer loop (the while (i < MAX)) only needs to run from 0 to ceil(sqrt(MAX)).
The inner loop can start at i*i not just 2*i.

Summarizing the first two will give you factor of 16 more memory (or factor of 16 more numbers to sieve with given memory) and the last two will significantly improve the run-time (not sure by how much exactly).

The segfault is most likely due to the fact that a == NULL, i.e. the malloc routine fails to allocate the memory. You need to check for NULL after the malloc call and before memset.


You do not have to initialize string array with "". By default array values will be initialized with null. So afterwards, you can check if (store[index] == null).
You are already doing '%' operation in for loop, no need to check if(index == 10)
String array is not required at all as mentioned by @kraskevich. But if you do need, make it as a property of class LinearProbbing. So that you do not have to pass it within methods.
No actual implementation of Hash is involved. So better rename methods.


The design of the readconfig() function is seriously problematic.  It makes no sense to convert caught exceptions into data, as if the file literally contained the string "FileNotFoundError" or "PermissionError".  If you don't have a good way to handle an exception, the right thing to do is let it propagate.

The readfile() function should be simpler:

def read_file(path):
    with open(path) as file:
        return file.read()

To note:

Since "read file" is two words in English, it should not be written as a compound word.
myfile could be better named.  It's a filesystem path, not a file handle.  Also, who is "me" in this case?
The 'r' mode is the default.
You don't need to call file.close() on an already closed file.  The whole point of the with block is that the file is automatically closed when exiting the block.


Creating holes in the type system:

operator T& and it's const sibling is probably very undesirable conversion. Why, then, std::string doesn't have operator const char*()? The answer is a type system. It meant to be explicit. std::optional uses overloading of operator*() and operator->().

Don't pay for what you don't use:

I would expect constructor to not check for is_valid of itself, because it is obvious (you're calling create() from constructor, which does check for validity). In most cases this won't make a difference, but you still should strive for perfection.

Missing features:

swap
comparison operators
emplace
value_or, which is I think the most useful. Returns provided default value if there optional is not initialized yet.
one function that throws when the optional is not initialized yet. just() is a great candidate.

Style:

You could enter a newline in some places where the line is long.

I think that calling global std might be somewhat restricting. It is arguable, though.


feedback needed for my first python tkinter simple MVC, list element to print to label

The code looks like it is set up fine for MVC. I'm not an expert but I have enogh experience to tell that it's fine.


Sieve of Eratosthenes prime number finder up to n in C++

What you are doing here is first calculating primes under sqrt and then crossing out the multiples like sieve says. However the standard approach is to calculate primes as you go and cross out multiples of each prime :

vector<bool> isPrime(MAXIMUM, true);   //we only need bool, less memory usage

isPrime[0] = false;
isPrime[1] = false;

for (int i = 4; i < MAXIMUM; i+=2) { // even numbers are handled first for efficiency
    isPrime[i] = false;
}

for(int i = 3; i < MAXIMUM; i+=2){
    if (isPrime[i]) {
        //the usual is for(int j = i * 2; j < MAXIMUM; j += i) { but I am using a bit more optimized loop
        for(int j = i * i; j < MAXIMUM; j += 2 * i) {
            isPrime[j] = false;
        }
    }
}

for(int x = 1; x<MAXIMUM; x++){
    if(isPrime[x]){cout<< x <<'\t';}
}

This way code is much shorter and if you try it, also much faster.


From a once over:

You should consider MVC, your data should live in an object you created, you should update your model, and then from your model update the UI
If you dont want to do this, then you should at least find all cells and assign each cell to a 2d JS array

var tiles = [];
for (w = 0; w < arraySize; w++) {
    tiles[w] = [];
    for (h = 0; h < arraySize; h++) {
        tiles[w][h] = $('.arrayContainer .row').eq(w).children().eq(h);
    }
}

Otherwise you are executing $('.arrayContainer .row') far too many times, and that operation takes a lot of time, then you can do your logic like this:

for (w = 0; w < arraySize; w++) {
    for (h = 0; h < arraySize; h++) {
        tile = tiles[w][h]
        if (tile.html() != '' && tiles[w][h-1].html() == '' && (h-1) >= 0) {
            tiles[w][h-1].html(tile.html());
            tile.html('');
        }
    }
}

You could consider assigning tiles[w][h-1] to a variable as well to make it more readable
Consider c and r as variables ( column and row if you are feeling verbose ). Those are better names than height and width.
I hope you declared tiles with var somewhere else, otherwise you have global namespace pollution.
As for not having to repeat the same 2 loops for every direction, you could think about passing a columnDelta and RowDelta ( for your 2 loops, columnDelta would be -1, rowDelta would be 0 ) I am not sure it is worth it, since you only have 4 cardinal directions, up to you.


Welcome! Here is some feedback, in no particular order.

Avoid using namespace std

This advice is often repeated for good reason. See also: code guidelines SF.6. It's useful when you're learning the C++ standard library to know what belongs in the standard library and what doesn't.

cout << "Enter your 2 numbers: "<< endl;

Becomes

std::cout << "Enter your 2 numbers: "<< std::endl;

Consistent spacing

Maybe this is caused by the formatting on Stack Exchange. There are many online style guides, I would choose one that is most readable to you and your peers and stick with it throughout the source code.

int add (int x, int y){
return x+y;
};

Becomes

int add(int x, int y) {
    return x + y;
};

Semicolons

Functions don't need semicolons at the end (main & add). This is only used for function prototypes.

int add(int x, int y) {
    return x + y;
};

Becomes

int add(int x, int y) {
    return x + y;
}

Avoid std::endl

Unless you need to flush the stream, using std::endl can be replaced with a newline character.

std::cout << "Enter your 2 numbers: "<< std::endl;

Becomes

std::cout << "Enter your 2 numbers:\n";

Combine multiple std::cout and std::cin calls.

This is just my preference. It reduces the amount of code I have to write.

std::cin >> n1;
std::cin >> n2;

Becomes

std::cin >> n1 >> n2;

And

std::cout << "1) Add: " << std::endl;
std::cout << "2) Divide: "<< std::endl;
std::cout << "3) Multiply: "<< std::endl;
std::cout << "4) Subtration: "<< std::endl;

Becomes

std::cout << "1) Add:\n2) Divide:\n3) Multiply:\n4) Subtration:\n";

In the above example, there are many other ways to do it. For example, you can use multi-line strings, adding the strings, and so on.

Make use of your functions

You define the add, divide, multiply and subtract functions, but you don't call them. Here is how you would do that:

std::cout << n1 + n2 << '\n';

Becomes

std::cout << add(n1, n2) << '\n';

It's as simple as that!

In complex applications, splitting things into functions makes the code easier to work with. For example, say you wanted the "add" operation to have saturating arithmetic (doesn't overflow). It's easier to add that logic to a separate function rather than inserting it into a long block of code.

Or, if you want to handle a division-by-zero case.

Don't use goto

While goto is useful in a few cases, it's not particularly useful here. Instead you can use a do-while loop.

SomeLine:

// code

if (userchoice == 'y'){
    goto SomeLine;
}
else if(userchoice == 'n'){
    goto Exit;
}

Exit:
return 0;

Becomes

do {
     // code
} while (userchoice == 'y');

return 0;

Variable naming

The variables x and y are used in the function signatures. You can also use those names in main. I'd prefer that over n1 and n2. Likewise, user14 is vague (do we change it to user15 if we include another operation?). Something like operation or op isn't vague. userchoice is a bit long, exit is shorter and clearly shows its purpose.

const

Make use of the const keyword where it makes sense. For example, in add, we intend for the x and y variables to never themselves be modified. So we can declare them as const, and the compiler will give us an error if we accidentally change their values.

This isn't particularly useful anything other than readability here, but can be useful if you get into more advanced topics, such as const references.

The functions add, divide, multiply, and subtract can be constexpr. The compiler may already evaluate these at compile time, but using constexpr marks them as such (broadly speaking).

Move variables to the lowest scope

Now that we've gotten rid of the gotos, we can move x, y, and op to a lower scope. They can also all be declared on the same line.

Consider edge cases

The following are a few example cases where you may wish to add extra handling -- or leave as it currently is.

What if the user enters a letter where you're expecting an integer?
What if the user enters an operation number outside of the range?
What about possible signed integer overflow (undefined behavior)?
What about division-by-zero?
What if the input stream is no longer valid after user input?
...

Conclusion

Here is the code I ended up with:

#include <iostream>

constexpr int add(const int x, const int y) {
    return x + y;
}

constexpr int divide(const int x, const int y) {
    return x / y;
}

constexpr int multiply(const int x, const int y) {
    return x * y;
}

constexpr int subtract(const int x, const int y) {
    return x - y;
}

int main() {
    char exit;

    do {
        int x, y, op;

        std::cout << "Enter your 2 numbers:\n";

        std::cin >> x >> y;

        std::cout << "Ok, now what do you want to do with those numbers?\n";
        std::cout << "1) Add:\n2) Divide:\n3) Multiply:\n4) Subtration:\n";

        std::cin >> op;

        switch (op) {
            case 1:
                std::cout << add(x, y) << '\n';
                break;
            case 2:
                std::cout << divide(x, y) << '\n';
                break;
            case 3:
                std::cout << multiply(x, y) << '\n';
                break;
            case 4:
                std::cout << subtract(x, y) << '\n';
                break;
        }

        std::cout << "Would you like to perform any other operations? y/n\n";

        std::cin >> exit;
    } while (exit == 'y');

    return 0;
}

Hopefully this has been helpful. I hope you continue to enjoy programming as much as we all do!


Sure there is... use the native libraries...

Your code here:

 int length=0;
 char* str1=str;

 while(*str++)
    ++length;

counts the number of chars until it finds the null terminator.

This is an inefficient way of doing it, 1 byte at a time. A much more efficient way to do it is to work on word-sized memory chunks - 32-bits and 64-bits on respective platforms. If you do a fold of the 8-bit bytes using bitwise operators on the value, you can identify whether there is a null byte in fewer CPU operations than by processing each byte individually. If this sounds complicated, well, it sort of is, but, on the other hand, it is already done for you:

#include <string.h>

....

    length = strlen(str);

That will likely halve the time needed to find the string length.

Then, your code would be a lot easier to read if you used array-like subscripts to access the chars instead of pointers..... that way you can get rid of the str1 variable as well:

 char  temp;

 for ( int i = 0; i < length/2; ++i) {
       temp = str[i];
       str[i] = str[length - 1 - i];
       str[length - 1 - i] = temp;
 }

If you want, you can reduce that to a while-loop with converging indices:

 int right = length - 1;
 int left = 0;
 while (left < right) {
     temp = str[left];
     str[left++] = str[right];
     str[right--] = temp;
 }


Subprocess CSV validator and multiprocessing on Python

Only a few small things I would suggest changing.
Pep8
You should consider formatting your code in accordance with pep8.  This is important when sharing code, as the consistent style makes it much easier for other programmers to read your code.  There are various tools available to assist in making the code pep8 compliant.  I use the PyCharm IDE which will show pep8 violations right in the editor.
ALL_CAPS_IS_FOR_CONSTS
So generally ALL_CAPS is reserved for constant variables. So this sort of thing:
TOTAL_FILE_COUNT = len(CSV_LIST)

is more Pythonic as:
total_file_count = len(CSV_LIST)

And even better is getting rid of this intermediate assignment altogether with:
print("Processing file {}/{}".format(current_file_count, len(CSV_LIST)))

Testing for presence in dicts
Often when you find code checking for a key presence in a dict before performing some work:
if args['CSV_ENCODING'] is not None:
    CSV_ENCODING = args['CSV_ENCODING']

Basically the same thing can be done without the explicit check:
CSV_ENCODING = args.get('CSV_ENCODING', CSV_ENCODING)