Naming nitpicks: The relationship between count and maxThreads is not obvious. I would probably name them something like threads_arrived_ and total_threads_ (using the common convention of postfix-underscore for data members).

You might like to know that there's a std::barrier in C++20. Your wait is what C++20 calls arrive_and_wait.  Your generation is what C++20 calls the "phase."

Why is your notifyAll a separate function, given that it's private and called only in a single place? You should just inline it. As a bonus, you could then drop the mutex lock before calling cv.notify_all() — this is widely quoted as a performance optimization.

You wrote:

void wait(std::chrono::milliseconds = std::chrono::milliseconds(0));

Being as default arguments are the devil, this is a red flag. Personally I would write this as

void arrive_and_wait();
void arrive_and_wait_for(std::chrono::milliseconds timeout);

and continue adding an arrive_and_wait_until as well. I would not use overloading or default arguments to accomplish this, because "wait for 0 milliseconds" and "wait forever" are completely different things. You really really don't want someone doing, like,

barrier.wait(user_configured_timeout);      // wait for 1ms
barrier.wait(user_configured_timeout / 2);  // wait for half that

and getting an infinite wait instead. Follow the STL's lead here: wait, wait_for, and wait_until are all different operations.

if (0 == --count) notifyAll();
else {
    if (timeWait == std::chrono::milliseconds(0)) cv.wait(ulock, waitCondition);
    else {
        const auto timedOut = !cv.wait_for(ulock, timeWait, waitCondition);
        if (timedOut) ++count;
    }
}

This is a ridiculously misindented piece of code. Try this:

if (0 == --count) {
    notifyAll();
} else if (timeWait == std::chrono::milliseconds(0)) {
    // note that our refactored `wait_for` will not contain this branch
    cv.wait(ulock, waitCondition);
} else {
    // note that our refactored `wait` will not contain this branch
    bool timedOut = !cv.wait_for(ulock, timeWait, waitCondition);
    if (timedOut) ++count;
}

That ++count smells like a race condition to me. Sure, we're operating under the mutex lock here; but I suspect it's possible that some other thread might have observed the decremented value of count and acted on it, which might mean that here we're bumping count from 0 to 1, or from maxThreads to maxThreads+1. I'm not sure that this can happen, but I would look at this codepath very closely if I were you.

Consider what happens in code like

Thread A         Thread B         Thread C

Barrier b(2);
b.wait();        b.wait();
                 <notifyAll>
                 b.wait();        b.wait();
                                  <notifyAll>
                 <awaken>
<awaken>
<resume waiting>

If I understand correctly, when thread A finally gets scheduled and belatedly awakens from its cv.wait, it will observe gen == generation because generation has been toggled twice since it went to sleep. So it will remain blocked, even though it should have become unblocked as a result of thread B's first b.wait().

I'm not sure how to fix this, but it might involve thread B being forced to block, itself, until all the other threads in the current phase have indicated that they're unblocked. In fact I'm not sure that that would even fix the issue.

It's worth mentioning that it is physically possible for the programmer to destroy a Barrier while some other thread is still blocked waiting on it. Presumably you're okay with having this be undefined behavior.


It's hard to review this kind of code unless there's a clear idea of what your self-imposed constraints are. What I mean by this is that the code makes use of an assumption (all permutable primes over \$10^6\$ are repunits) that it does not check. But if it is legitimate to make use of assumptions that the program itself does not check, then it would be much faster to avoid all those calls to isprime and write:

# https://oeis.org/A004023
A004023 = 19, 23, 317, 1031, 49081, 86453, 109297, 270343
circular_lst.extend((10**p - 1) // 9 for p in A004023 if p <= digits)


Initializing a controller that uses Selenium

I found two better alternatives.

1. Change $driver from protected to public

Then you can pass the $this object directly to initDriver:

PortalController

public $driver = null;

public function main()
{
    //Before: $this->driver = Selenium::initDriver(array($this, "driver"));

    //After:
    Selenium::initDriver($this);
    ...
}

SeleniumUtility

public static function initDriver($thisObj)
{
    //Now I can do the if null check here

    if (thisObj->driver === NULL) {
       $thisObj->driver = RemoteWebDriver::create(self::SELENIUM_SERVER_ADDRESS, DesiredCapabilities::firefox(), self::DRIVER_TIMEOUT);
    }
}

2. Use getter and setter

PortalController

protected $driver = null;

public function getDriver()
{
    return $this->driver;
}

public function setDriver($driver)
{
    $this->driver = $driver;
}

public function main()
{
    //Before: $this->driver = Selenium::initDriver(array($this, "driver"));

    //After:
    Selenium::initDriver($this);
    ...
}

SeleniumUtility

public static function initDriver($thisObj)
{
    //Now I can do the if null check here

    if (thisObj->getDriver() === NULL) {
        $thisObj->setDriver( RemoteWebDriver::create(self::SELENIUM_SERVER_ADDRESS, DesiredCapabilities::firefox(), self::DRIVER_TIMEOUT));
    }
}

But in my opinion it makes no sense to make the driver protected, so the first solution is faster and better. As long as we do not store any valuable information like passwords in the driver, keeping it public is perfectly OK.


Java: Only log first error occurrence (with hourly reset)

Your code currently checks when the last error occurred. This might not be what you actually want. Assuming that an error occurs every 30 minutes, I would expect to have a log entry every 60 minutes. Your current code produces one log entry at the beginning, and no more log entries after that.

I once wrote similar code, and I separated the code into two Java classes: the Throttler for the actual algorithm and the ThrottledLogger for using the algorithm to throttle log messages.

I'm still happy with that old code, and it had the following additional features:

It allows several events before throttling kicks in.
When throttling kicks in, that is logged as well ("further log messages will be suppressed").
When throttling has finished, that is logged as well ("suppressed {} messages").

With these changes, the log messages do not hide any important information. The throttled logger I used was created like this:

new ThrottledLogger(
    logger,
    5,  // number of allowed messages
    1, TimeUnit.HOUR  // 1 more message every hour
);

With this information you should be able to write the same code as I did. Be sure to write some unit tests for the throttling algorithm, to demonstrate that it works indeed like you want it to work.

If you don't need this additional complexity, you should at least move the errorOccurred = assignment into the body of the if statement.


Count numbers with atleast one common factor, excluding one (updated)

Your algorithm is very far from optimal. In the worst case (if all numbers are equal to N in the input), it does O(N * T) operations, which clearly way too much (not just for python, for any programming language).

What they're asking to compute is n - phi(n), where phi is the Euler's totient function. Using the fact that the function is multiplicative one can derive a formula phi(n) = n * {product of (1 - 1 / p) over all prime p dividing n. Using this fact, we can compute it efficiently in O(N log log N) time for all 1 <= i <= N using something that looks like the sieve of Eratosthenes. After that, we can answer each query in O(1).

A C++ implementation is ridiculously concise and easily fits in the time limit:

#include <cstdio>
#include <vector>
#include <algorithm>

int main() {
    const int max_n = 1000 * 1000;
    std::vector<int> ans(max_n + 1);
    std::iota(ans.begin(), ans.end(), 0);
    for (int i = 2; i <= max_n; i++)
        if (ans[i] == i)
            for (int j = i; j <= max_n; j += i)
                ans[j] = ans[j] / i * (i - 1);
    int t;
    scanf("%d", &t);
    while (t--) {
        int x;
        scanf("%d", &x);
        printf("%d\n", x - ans[x]);
    }
}

Unfortunately, the same solution in python is too slow.

def calc_phi(n):
    res = [i for i in range(n + 1)]
    is_prime = [True] * (n + 1)
    for i in range(2, n + 1):
        if is_prime[i]:
            for j in range(2 * i, n, i):
                is_prime[j] = False
                res[j] = res[j] // i * (i - 1)
    return res

def solve():
    max_n = 10 ** 6
    phi = calc_phi(max_n)
    cnt = int(input())
    res = []
    for _ in range(cnt):
        n = int(input())
        res.append(n - phi[n])
    print('\n'.join(map(str, res)))

if __name__ == '__main__':
    solve()

With some optimizations (like more efficient input reading and handling small prime divisors separately), which made the code less readable and nice, I managed to make it complete under 1 second in the worst case on my machine, which is pretty close. It's still too slow for the online judge. So I'm not sure if it's actually solvable in python. That's the main reason why python is rarely used to solve problems with a tight time limit: it's much slower than C++ or Java.


Refactor two methods with similar logic but handling different entities

Disclaimer

From the comments:

the problem is that I don't have enough experience nor knowledge to improve it

I will stop you right there. If you don't have enough experience nor knowledge then I suggest you don't do refactoring on this specific code, not because you can't but because you endanger yourself of making undesired behaviour or making actually harder to read code.
The sole purpose of refactoring is making a code easier to understand. Now this can be tricky because sometimes some sections of your application have to be very performant, other sections need to be very readable as most of the business logic is there, some parts need to be very flexible since they are changing often there are many cases. The key to refactoring is first realizing what are you refactoring for - performance (very hard, if you don't have experience I would suggest not to do it), readability, extensibility and so on.
Back to your case

Playing with tasks if you are inexperienced often leads to some code running either slower or harder to reason about.
First (and probably the last one given the fact I don't know the business logic) change I would do to this code is postponing Task's awaiter.
// instead of this
public async Task UnpublishPersonAsync(string id)
{
    await QueueAndUpdateStatusAsync(id, PersonStatus.Unpublishing, QueueNames.Unpublish);
}

// strive to do this
public Task UnpublishPersonAsync(string id)
{
    return QueueAndUpdateStatusAsync(id, PersonStatus.Unpublishing, QueueNames.Unpublish);
}

// or arrow notation if your team likes it
public Task UnpublishPersonAsync(string id)
    => QueueAndUpdateStatusAsync(id, PersonStatus.Unpublishing, QueueNames.Unpublish);

Why is this?
I am always trying to explain the guys in the team that for a change that is so insignificant can give us little tiny bit of improvement. What I mean is that

it does not create async state machine class for your method

it does not introduce unnecessary code that has to be run (goto statements) really really small improvement but if the change is so little.

it leaves the consumer of your method to decide when he wants to await or if he wants to await.

Both methods(QueueAndUpdateStatusAsync and DeletePersonAsync) look the same, alas, they use different overloads of PublishToStorageQueueAsync methods and it will make the code harder to read if you try to abstract them.
What I don't like is throwing exceptions - I use them as a last resort really really last resort. In your case I will refactor both of the methods to follow the same pattern (not that they don't now) like so:
public async Task<bool> DeletePersonAsync(string id, bool deleteAssociatedData)
{
    var personDto = await _cosmosDbService.GetItemAsync<PersonDto>(id, id);
    var operationIsValid = ValidateOperation(PersonStatus.Deleting, personDto);

    // personal preference you can do it with brackets and newlines
    if (!operationIsValid) return false;

    personDto.Status = PersonStatus.Deleting;
    personDto = await _cosmosDbService.UpdateItemAsync(id, id, personDto);
    var person = _mappingService.MapToPerson(personDto);

    var deleteCommand = new DeletePersonCommand()
    {
        Person = person,
        DeleteAssociatedData = deleteAssociatedData
    };

    await _queue.PublishToStorageQueueAsync(deleteCommand, QueueNames.Delete);
    return true;
}

As you can see now you return if the whole transaction is successful or not simply by changing return type to Task<bool> let consumers handle errors the way they want don't force them to handle your exception especially for something so easy to fix.
If you have decided to go with exceptions nevertheless, then I strongly suggest you encode some information inside it. Say some message like "Validation of X failed." anything that can help you give meaning to it later when you happen to debug it. Also if this is some kind of library code, creating custom specific exception is also an option if you like exceptions so much, but as a rule of thumb I strongly suggest you to stay away from exceptions at all cost no matter the language or framework.
P.S. They also incur performance drawback for unwinding the stack later. Your clients need to catch it and probably re-throw it also if necessary, overall it gets messy IMO.
Conclusion

Other than that I think its relatively easy code to follow, don't refactor it unless you find problems with it - whether that will be performance problems, readability problems and etc.


You are currently mixing declarative and functional style. I suggest succinct functional style:

var keys = ["a", "b", "c", "d"];
var value = "Hello";
var res = keys.reduceRight((value, key) => ({[key]: value}), value);


Code organisation and other things well done

You've extracted the algorithm in a function on its own. Also, you've written you code behind the "if name == main" guard. Congratulations on this, these are two good things beginners usually don't do properly.
This makes your code clearer, easier to maintain and easier to test.

Also, I'd like to take this chance to congratulate you for using _ as a name for a throw-away value which is quite a nice habit.

Finally, you did notice that there was not point in looping over the whole string once you've reached the middle.

Getting rid of useless things

  It seems that perfection is attained not when there is nothing more to add, but when there is nothing more to remove. - Antoine de Saint Exupéry

I can see in your code artifacts of old versions of your code : arr and revarr are not used at all. Also you don't need to define i before the loop.

continue is nice keyword, available in most programming languages. However, from my experience, you don't need it that often. In your case, you might as will just write :

    if sdiff != rdiff:
           return False

Finally, 0 is not required as a first argument to range.

Style

Python has a style guide called PEP 8. It is definitly worth a read. You'll find various tools online to check your code's compliancy to PEP 8. From what I can see, the main "issue" is that the function name is CamelCased and not snake_cased.

Documentation

If you wanted to do things properly, it might be interesting to add some documentation to your function.

More details (and personal preferences)

We have a nice ternary operator in Python. Using it, you could write :

    print("Funny" if is_funny(word) else "Not Funny")

Also, your is_funny function looks like the typical situation where you could use the all/any Python builtin. However, because of the length of the expressions involved, it becomes a bit of a matter of personal preference. I'd write this (but you don't have to like it) :

def is_funny(word):
    """Check if a word is funny."""
    length = len(word)
    return all(
        abs(ord(word[i])-ord(word[i+1])) == abs(ord(word[length-i-1])-ord(word[length-i-2]))
        for i in range(math.ceil(length/2))
    )

Another thing that could be changed but might not make the code clearer to every one is the way you get the n-th element of the reversed string. You can use word[length-i-1] like you did but you can also take the most out of Python's index handling : negative indices are taken from the end of the container. So that you can write word[-i-1] instead (and the same principle applies to word[length-i-2]).


I can't see much wrong with it.  Maybe use BTRIM if on Db2 11.1 or above rather than RTRIM(LTRIM(
and maybe indent with fewer spaces (e.g. align the first column with the rest), but that is really a matter of style


var batchStockEvents = new BatchBlock<T>(batchSize);

I think that batchStockEvents is a weird name for a BatchBlock. It sounds like it's a collection of events, or something like that.

new Timer(delegate { batchStockEvents.TriggerBatch(); });

While using delegate this way allows you to ignore the parameter, I think it's cleaner (and shorter) to use lambda and use _ as the parameter name to indicate it's ignored:

new Timer(_ => batchStockEvents.TriggerBatch());

// Use a transform block to reset the timer whenever an item is inserted to avoid unnessary batches

Wouldn't it be enough to reset the timer whenever a batch is triggered? It would be more efficient and you would have one less block.

Also, the comment has a typo, it should be "unnecessary".

What's the purpose of the _buffer block? Couldn't Post() post directly to timeoutBlock?

  In particular, I'm not sure about my exception handling approach to raise errors when posting objects; but I couldn't come up with anything better.

Yeah, you can't rely on that check in Post() because by the time the failure happens, all items could have been posted. But if you just want to stop doing useless work by trying to Post() items that can never be processed, then I think this is the right approach.


Extracting components of a street address

To start with, your code doesn't make much sense to me. You're looping over $this->service_results->results[0]->address_components, and on each iteration, you seem to be setting all of the address values. If the address_components array contains 4 arrays, each setting all of the address vars, you're effectively overwriting the values, and are only left with the last set of values. More on this later, though (see "other niggles" below).

To answer your question:
Yes, you can improve this code. You have a rare case where a more readable implementation of your code actually becomes more performant, too.
The first thing to note is that the function you use the most (in_array), is implemented as a simple linear search of an array (hash table internally). This means it has a time complexity of O(n), n being the size of the array. Replacing it with a loop might seem to do the same thing, but you'll only go through the array once:

foreach ($this->service_results->results[0]->address_components as $component) {
    foreach ($component->types as $k)
    {
        switch ($k)
        {
            case 'street_number': $this->streetNumber = $component->long_name; break;
            case 'postal_town': $this->town = $component->long_name; break;
            case 'administrative_area_level_1': $this->district = $component->long_name; break;
            case 'postal_code': $this->postcode = $component->long_name; break;
            case 'route': $this->streetAddress = $component->long_name; break;
            case 'administrative_area_level_2':
                $k = 'country';//same as country, so reassign, don't break
            case 'country':
            case 'locality':
                $this->{$k} = $component->long_name;//key and property share the same name...
                break;
        }
    }
}

This already looks a tad better, but it still relies on us hard-coding all possible values for $component->types and assign the value of $component->long_name to the properties. I'd use a mapping array instead:

//outside all loops:
$map = array(
    'street_number' => 'streetNumber',
    'postal_town'   => 'town',
    'postal_code'   => 'postcode',
    'route'         => 'streetAddress',
    'country'       => 'country',
    'locality'      => 'locality',
    'administrative_area_level_1' => 'district',
    'administrative_area_level_2' => 'country'
);
//inner loop:
foreach ($component->type as $k)
{
    if (isset($map[$k]))
        $this->{$map[$k]} = $component->long_name;
    else
        //handle error, type not in $map: throw exception, log or "overload" $this (bad idea IMHO)
        $this->{$k} = $component->long_name;
}

Other niggles:
There are some other issues I have with your code. Two to be precise:

Data format:
Like I said before, you seem to be re-assigning the same properties over and over (or at least, there is a possibility you are). You might want to re-evaluate the data structure you have, if the $this->service_results->results[0]->address_components array looks something along the lines of:

[
    [
        'types' => ['street_number', 'postal_town', 'country',...],
        'long_value' => 'some value here'
    ],
    [
        'types' => ['street_number', 'postal_town', 'country',...],
        'long_value' => 'Another value'
    ]
]

Then your properties ($this->streetNumber, $this->town, $this->country,...) will all end up with the same value: "Another value" in this case. This is probably not what you want. Since each $component seems to have an array of type values, but only one real value (long_name), I suspect your data to look more like this:

[
    [
        'types' => ['street_number'],
        'long_value' => '10'
    ],
    [
        'types' => ['postal_town'],
        'long_value' => 'London'
    ],
    [
        'types' => ['country','administrative_area_level_1'],//alias for country
        'long_value' => 'UK'
    ]
]

Which means that, most of the time, traversing the entire types array is rather pointless, and so we can safely refactor the last snippet I suggested to break; once we've assigned our long_name value:

foreach ($component->type as $k)
{
    if (isset($map[$k]))
    {
        $this->{$map[$k]} = $component->long_name;
        break;//found the property to set, skip to next component
    }
}

If your data essentially does look like the first version (where the types array lists all possible types), then consider checking the value of long_name, because really: if the value represents a street number, you don't want to assign that value to the $this->country property, do you?
Add a var_dump($this->service_results->results[0]->address_components); to your question, so we know what type of data you're dealing with here.

Separation of concern:
Your class is, IMO, clearly breaking the SOLID principles. Single Responsability Principle (SRP) and, as a result, the separation of concern is not adhered to. The idea is that a class is a unit of code that has "at most one reason to change". That's a fancy way of saying that a class can have only 1 job. A class can be tasked to connect to a database, or perform cUrl request. But those classes should not be responsable for processing and storing the data it they obtain.

A PDO instance connects to the database, but does not handle prepared statements, or result sets. That's not its job, that's the reason for a PDOStatement to change. Neither of these two classes report errors, that's the job of the PDOException class.
Now look at your code. Your class might use another class instance to perform queries or curl requests, or it could contain the code that does this itself. If so: that's bad, because your class now does at least 2 things: fetching data and storing it (assigning to properties).

As if that weren't enough, the code you posted here also seems to take care of raw responses, extracting the data you're after and then storing it. So the class that contains the method you posted here has at least 2, and possibly even 3 "reasons to change". That's just plain evil.
What's more: your class doesn't only store the formatted data, it carries with it the raw data from which you extracted the address, the property $this->service_results. What is it for? You process the results, store the data you're after and either get rid of the raw data, or pass it on to another class/module that needs that data.

Post more code (as a separate review-request) if you want us to have a look at your class as a whole.


Windows filepath and filename validation

For the if(filePath.Length >= 240) part, you can use the Path object.
It throws a PathTooLongException.

You can then change to this :

try
{
    filePath = Path.GetFullPath(filePath);
}
catch (PathTooLongException ex)
{
    directoryFound = false;
    Console.WriteLine("Please keep the filepath under 240 chars so that you still are able to provide a name for the file.");
}

Note : you can find references to Path object here and see all exception you have to handle invalid path input.

Now for GetFileName(), you can use the same object Path.GetFileName(). It will check if the name is valid.

  ArgumentException : path contains one or more of the invalid characters defined in GetInvalidPathChars.

...
fileName = Console.ReadLine();
            Console.Clear();
try
{
    fileName = Path.GetFileName(fileName);
}
catch (ArgumentException ex)
{
    // Whatever exception handling you want.
}

Note : Since you have to check more than one time if the Path is valid, I would create a method to do this.

public static bool PathIsValid(string inputPath)
{
    try
    {
        Path.GetFullPath(inputPath);
    }
    catch(PathTooLongException ex)
    {
        return false;
    }
    return true;
}


First of all, you don't need to make your solution recursive. Iterative approach in your case would be more intuitive and simple.
Moreover, there is a better way to handle pagination for this particular website - the paginated parts of the video catalog are following http://www.wiseowl.co.uk/videos/default-<number>.htm pattern, which means that you can start with number=1 up until you get 404 which would conclude the catalog:
import requests
from lxml import html

URL_PATTERN = "http://www.wiseowl.co.uk/videos/default-{}.htm"

with requests.Session() as session:
    page_number = 1
    while True:
        response = session.get(URL_PATTERN.format(page_number))
        if response.status_code == 404:  # break once the page is not found
            break

        print("Processing page number {}..".format(page_number))

        tree = html.fromstring(response.text)
        for video_link in tree.xpath('//p[@class="woVideoListDefaultSeriesTitle"]//a'):
            title = video_link.text
            link = video_link.attrib['href']

            print(title, link)

        page_number += 1

Notes about some of the improvements I've made:

re-using the same Session instance - it results into a memory usage and performance improvement because it re-uses the same TCP connection:

if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

instead of searching the entire tree for the "video" elements 2 times, looping over video link elements directly once

naming: first of all, make sure to follow the lower_case_with_underscores Python naming recommendations. And, try to avoid meaningless variables like i and j if not used as throwaway loop variables; url1 was not a good variable choice as well

follow other PEP8 style guide recommendations - in particular, watch for the spaces around operators and newlines


Given a binary tree, \$T\$ whose nodes have positive values, find the value of the maximal path

The combination of the very long variable names and trying to follow the PEP8 "79 chars per line" rule really makes the code unreadable.

First of all, you can absolutely increase the allowed line length from 79 to a more practical 100 or 120. After all, we are writing code for humans to read, not machines.

Also, I think you can shorten the variable names by removing the "val_of_" part from the beginning. You don't lose any information by doing that.

Some other notes:

you can define tuples without extra parenthesis, e.g. return 0, 0 instead of return (0, 0)
the docstrings should be put in triple double-quotes. If a docstring is located on multiple lines, it should star with a new line (PEP8 reference)

Here is the code after applying the proposed changes:

class BinaryTree:
    def __init__(self, root=None):
        self.root = root

    def max_sum_path(self, root):
        _, max_path = self._max_path(root)
        return max_path

    def _max_path(self, root):
        """
        Returns a tuple:
            (val of the maximal path from a leaf up to root,
             val of the maximal path from a node to another node in this subtree).
        """

        # base case
        if not root:
            return 0, 0

        # recursive case
        max_path_from_a_leaf_up_to_left_child, max_path_in_left_subtree = self._max_path(root.left)
        max_path_from_a_leaf_up_to_right_child, max_path_in_right_subtree = self._max_path(root.right)

        max_path_from_a_leaf_up_to_root = root.data + max(max_path_from_a_leaf_up_to_left_child,
                                                          max_path_from_a_leaf_up_to_right_child)

        max_path_that_has_a_turning_point_at_root = max_path_from_a_leaf_up_to_left_child + \
                                                    root.data + \
                                                    max_path_from_a_leaf_up_to_right_child
        max_path_in_this_subtree = max(max_path_in_left_subtree,
                                       max_path_in_right_subtree,
                                       max_path_that_has_a_turning_point_at_root)

        return max_path_from_a_leaf_up_to_root, max_path_in_this_subtree


For odd numbered length arr [1,2,3,4,8] why place middle at the end of
  arr?

The middle element in an odd numbered array, is the next highest element to be paired up.  But since it is also the next lower element it doesn't have a pair, so it gets added by itself.

  And, for last index, why do we have to find abs difference between val
  at last index and first index?

To my mind, the problem states 'maximum sum of absolute difference of any permutation'. The permutation of the lowest number on the high side of the sorted array and the lowest number wouldn't get added to the max sum otherwise.

  Is there is any better and clear algorithm to think about

I believe there is.  The idea of calculating the differences on the fly and adding to the max sum directly, has merit.  It just needed tweaking a bit.  Heres some working code for that concept:

static int MaxSumDifference2(int []a, int n) {
    Arrays.sort(a);
    int maxSum = 0;
    int low = 0;
    int high = a.length - 1;
    for(;low < high; ++low, --high){
        maxSum += a[high] - a[low] + a[high] - a[low + 1];
    }
    maxSum += a[low] - a[0];
    return maxSum;
}


Since you asked for help slimming down your code, I'll give you some hints that might otherwise be inadvisable.

Don't use do-notation. In fact, you can replace

main :: IO ()
main = do
    [inp] <- getArgs -- get input from the command line
    putStrLn $ getAcronym inp

with

main :: IO ()
main = putStrLn =<< (fmap (getAcronym . head) getArgs)

I'd replace isWordSep to take advantage of pattern matching. As an example:

isWordSep :: Char -> Bool
isWordSep ' ' = True
isWordSep '-' = True
isWordSep _   = False

Consider using a parser library. Monadic parser combinators are quite nice, and they accomplish what you'd probably use regular expression for, but with far nicer error messages and type safety. Here's one example using megaparsec:

import           Control.Monad
import           Data.Void
import           Text.Megaparsec
import           Text.Megaparsec.Char

type Parser = Parsec Void String

uppercaseWord :: Parser Char
uppercaseWord = do
    h <- upperChar
    many $ noneOf "- "
    pure h

acronymP :: Parser String
acronymP = some $ do
    w <- uppercaseWord
    void (oneOf " -") <|> eof
    pure w

acronym :: String -> IO ()
acronym = parseTest acronymP

You can unpack the do-notation to get:

acronym :: String -> IO ()
acronym = parseTest (acronymP :: Parser String)
    where
        acronymP = some (uppercaseWord >>= ((void (oneOf " -") <|> eof) >>) . pure)
        uppercaseWord = upperChar >>= ((many (noneOf "- ") >>) . pure)

which, surprisingly enough, does indeed work.


For every call to String.concat(), a new string instance is created.  To create that instance, the contents of the previous string needs to be copied to the new one plus the contents of the concatenated string.  This is done for every string in the collection.  So if you look at in in terms of how many strings are concatenated (and not the characters copied), you're copying the contents of the n strings by the time you reach the nth iteration and all that matters is the worst case (the last iteration). Therefore it has \$O(n^2)\$ performance.


Generation of a  in React without  wrapping elements

as of React 16 version you can use

<React.Fragment>

Term

Definition

</React.Fragment>

React.Fragment will not render any DOM, but it'll act as a container.
You can also use a short hand for React.Fragment as <>

<>

Term

Definition

</>

It works in the same way, except that it doesn't support any attributes or key.

https://reactjs.org/docs/fragments.html


Functions good practices: Documentation, Parametrization, Single Purpose, Outside State Independence

Documentation

#random field generation
def generate():

Documentation is usually written as a docstring in triple quotes under the function definition (this allows programmatic access via help:

def generate():
    """ Random field generation. """

It also usually is a complete phrase, I would write it a little different:

def generate():
    """ Generates a random game of life board. """

Parametrization

Your function can only generate boards of size \$50 * 50\$, may I be interested in other sizes I would need to modify the definition accordingly.

I suggest asking x and y sizes as parameters:

def generate(x_size, y_size):
        print "Generating"
        for y in xrange(x_size):
                for x in xrange(y_size):
                        cells[x][y] = cell(0, random.randint(0, 1))
        print "DoneGen"

This way you gain more re-usability for your function (and you can test it simpler by giving small sizes).

Single Purpose

    print "Generating"
    ...
    print "DoneGen"

Your function prints to std-out in addition to building the board and this behaviour cannot be turned off. If printing out is not desired the user will not be able to use this function. I would just delete these printing statements after the debugging is complete.

Outside state independence

You need a 2d list called board for this function to work. You may instead create such list and return it.

Write functions to encapsulate logical units of action

wrap_around(dx, dy, x_size, y_size)

                            if dy < 0:
                                    dy = 49
                            if dy > 49:
                                    dy = 0
                            if dx < 0:
                                    dx = 49
                            if dx > 49:
                                    dx = 0

This 8 lines of code provide the program with wrap-around functionality (for example: going too far to the right leaves you all the way back to the left), it would ideal if you wrote a function for this.

next_state(cell, neighbours)

The same can be said for this block of code calculates the next state of a given cell:

                    if cellv2.state==1 and 2<=cellv2.ngb<=3:
                            cellv.state=1
                    else:
                            cellv.state=0
                    if cellv2.state==0 and cellv2.ngb==3:
                            cellv.state=1

decide_colour(cell)

                            if cells[x][y].state==1:
                                    pygame.draw.rect(mainsrf, black, (x*10, y*10, 10, 10))
                            else:
                                    pygame.draw.rect(mainsrf, white, (x*10, y*10, 10, 10))
                            if cells[x][y].ngb==3:
                                    pygame.draw.rect(mainsrf, red, (x*10, y*10, 10, 10))

The 3 options differ only in the colour of the drawing so you could also cut down code duplication by using such a function.

Minor: use ALL_CAPS for constants

As a widely accepted convention constants are written ALL CAPS to quickly discern them from variable variables.

RED = (255, 0, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
#neighbour coordinates
NEIGHBOURS = [[-1,-1],[-1,0],[-1,+1],
              [0,-1],        [0,+1],
              [+1,-1],[+1,0],[+1,+1],]

Give meaningful names: ngb?

self.ngb = 0

I cannot understand what the purpose of the ngb field is even after reading the code.

This is a bad sign indicating that a more descriptive name should be adopted.


Your code looks pretty great to me, especially for the current size of it. As it grows to do more things, you will probably want to start restructuring things a bit, so I'm looking at from that direction. It also depends a bit on your audience — if this is just a tool for you, then unwrapping is just fine as you will understand what the error message means and how to fix it.

  Is there an alternative to all of these unwrap() calls?

Absolutely. Check out The Rust Programming Language's section on error handling. In this case, it's probably simplest to use a Box<Error>, but in a larger program or a library you may want to investigate implementing your own error type. I almost put that version here, but it was so long that it would have been really inappropriate given the current size :-)

  It seems better (to me) to add the '\r' to the end of the command, making command_bytes mutable, than to call stream.write() another time. Think so?

I don't think there's going to be a major performance difference between the two, or at least it could be made negligible. When you call write_all, it may actually make multiple write calls. In a way, you are  implementing a simple BufWriter. I think it mostly comes down to semantics. In this case, I do like that you add the \r to the command packet, as it allows that logic to all be in one tidy spot.

  It also seems like a bad idea for a network client to read with no size limits. Any good way to deal with this?

You can use take, which will limit the number of bytes read. The amount you use is the tricky part. Are you guaranteed to always get responses less than some size? Maybe the protocol says that you will always get 4 bytes that then tell you how many bytes follow? In the example below, I just assumed a maximum of 1 KiB.

Following the error handling guides, I extracted the majority of your logic to a new function that uses Result. That way, main simply has to decide what to do on success or failure. This also means that you get nicer error messages like this:

  An error occurred: Unable to transmit: Network is unreachable (os error 51)

I also added a little bit of space between logically distinct parts of the method. They are a little small to be broken out for now, but they could easily lead to new methods in the future.

Some thoughts for the future:

It might be a good idea to parameterize the host value to the send_one_command method. You can then use the constant from within main.
Will you ever need to have multiple back-and-forth transmissions? If so, you may want to create a struct that holds the connection and keeps it open. Then you ask it to send a command.
The remaining unwrap in main is tricky. It seems very unlikely that the program name could be missing, so unwrap seems to be a good fit as it's a case you simply can't handle well. On the other hand, errors hiding other errors can be annoying to debug. You may want to use something like .unwrap_or_else(|| "unknown program name".into()).

extern crate encoding;

use std::{env, error};
use std::io::prelude::*;
use std::net::TcpStream;
use encoding::{Encoding, EncoderTrap};
use encoding::all::ASCII;

const HOST: &'static str = "10.21.39.30:23";

fn send_one_command(command: &str) -> Result<String, Box<error::Error + Send + Sync>> {
    let mut command_bytes = try!(ASCII.encode(command, EncoderTrap::Strict).map_err(|x| x.into_owned()));
    command_bytes.push('\r' as u8);

    let mut stream = try!(TcpStream::connect(HOST));
    try!(stream.write_all(&command_bytes));

    let mut response = String::new();
    let mut limited = stream.take(1024);
    try!(limited.read_to_string(&mut response));

    Ok(response)
}

fn main() {
    let command = match env::args().nth(1) {
        Some(cmd) => cmd,
        None => {
            let my_name = env::args().nth(0).unwrap();
            panic!("Usage: {} [command]", my_name)
        }
    };

    match send_one_command(&command) {
        Ok(response) => println!("{}", response),
        Err(err) => println!("An error occurred: {}", err),
    }
}


Various thoughts

You never use the max_size field, so you should delete it.
When pushing, you never check to see if the stack is full, so you could overrun your array if you push too many items.
Your current implememtation does not utilize the first array slot items[0].  You could make a few easy changes to fix that.
You have a check for position < 0 but it can never go negative.  You could even make position an unsigned value.

Rewrite
Here are your push and pop functions rewritten:
void stack_push(Stack *stack, int number)
{
    if (stack->position >= STACK_MAX_SIZE) {
        fprintf(stderr, "Stack is full\n");
        return;
    }
    stack->items[stack->position++] = number;
}

int stack_pop(Stack *stack)
{
    if (stack->position == 0) {
        fprintf(stderr, "Stack is empty\n");
        return -1;
    }
    return stack->items[--stack->position];
}


If you feel you need a comment like this:

    // ASCII a (97) + 26
    c = 123;

it means that the code is not clear. Consider

    c = 'a' + 26;

While we can figure out the significance of 26 (size of an English alphabet, right?) again it is better to be explicit. What you want is the first character beyond the [a-z] range, so:

    c = 'z' + 1;

Similarly, node->children[c-97] should be node->children[c-'a'].
The

    if (node->word == true) {
        return true;
    }

    return false;

is a long way to say

    return node->word;

Avoid globals. Make load return root (or NULL on failure), and pass root to check as a parameter.
Test what calloc returns.
root = calloc(1, sizeof(trie)); requires the knowledge that root is trie *, and therefore results a double maintenance. A preferred idiom is

root = calloc(1, sizeof(*root));

Branching factor of 27 adds a huge overhead. Most nodes will use just a few pointers, so most of the allocated memory is wasted. This in turn results in poor cache utilization, and may directly affect the performance. Consider allocating just as much as you need, and searching instead of indexing. It may or may not improve performance. Profile and compare.


There's two style comments, and one logic comment. The logic comment is the most significant.... you can rewrite your query as:

SELECT *
FROM `Users:Timesheets`
WHERE
      `start` >= '{$monday}'
  AND (`finish` IS NULL OR `finish` <= '{$sunday}')
  AND `username` = '{$username}'
  AND `shift_type` = 'ONCALL'
ORDER BY `id` ASC

Note, the style changes:

always put each SQL clause on it's own line (the FROM on a new line).
Try to indent each clause in the where clause so that the precedence of the logic is represented by the indentation.

Update: I assume, based on the variable syntax, and so on, that this SQL is not a direct query, but is rather the input to some string substitution that expands the {$...} variables. This is potentially vulnerable to SQL Injection attacks. Are you sure you shoud be running your SQL this way? Have you considered prepared statements? Is this a prepared statement?


Getting weather data from Open Weather Map API

private float temp;
    private float tempMax;
    private float tempMin;

You should avoid abbreviating temperature. Temp is commonly used as an abbrevation for temporary and confuses here. In C# we don't usually use abbreviations. There are exceptions but they consider some well know ones like xml or html.

CurrentURL = "http://api.openweathermap.org/data/2.5/weather?q="
            + location + "&mode=xml&units=metric&APPID=" + APIKEY;

You use some of the new C# 6 features already like the bodyless methods => so you might want to do the same for strings. The above line will become:

_currentURL =
    $"http://api.openweathermap.org/data/2.5/weather?q={location}" +
    $"&mode=xml&units=metric&APPID={APIKEY}";

Using the var could make you code look much simpler.

Consider this

    using (WebClient client = new WebClient())
    {
        string xmlContent = client.DownloadString(CurrentURL);
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xmlContent);
        return xmlDocument;
    }

vs that

    using (var webClient = new WebClient())
    {
        var xmlContent = webClient.DownloadString(CurrentURL);
        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xmlContent);
        return xmlDocument;
    }

XmlDocument

There's a newer and an easer way to work with xml. Try the XDocument out which is LINQ-capable. You'll like it. See XDocument or XmlDocument


Single MySQL Query one-to-many efficiency

I have seen (read) where in some instances it is more efficient to perform several queries and process the result of each in between rather than a complex SELECT query where several one-to-many or many-to-one relationships are involved.

Does that mean running a query to select data from each table and then subsequent queries to select the affiliated data? If so, repeated (redundant) queries (i.e. on one table where only a WHERE condition changes) can lead to poor performance. But, if the associated data can be shared across records (e.g. multiple accounts have the same location) then it might be better to have one query per table and then look up records in various result sets when needed.

If paging can be integrated, for example: populate the first \$n\$ results, where \$n\$ can be 20, 40, 60, etc. then the query with the joined tables might be optimal.

  Are there going to be any major issues with this single select as I have it currently constructed?

The query as it is above might likely take a while, given the high number of records in each table. But as mentioned above, paging would likely improve the situation greatly.


I've been working on it and I feel I finally have it like I wanted to.

Instead of using the __wakeup() function, I'm binding a closure to the new object that dispatches other closures whom are registered to a traits name. So as a result I don't even need the Constructor trait anymore.

Not only that, hooking this all up to an event system I was able to create destructors as well with an added bonus that I can use __wakeup() and __sleep() as they where designed for.

I'm reusing code by using the event system, so in summary its now more dynamic, shorter code and somewhat faster in execution


Finding the longest Collatz sequence using Go, concurrently

Longest Collatz sequence

  Problem 14

  The following iterative sequence is defined for the set of positive
  integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

  Although it has not been proved yet (Collatz Problem), it is thought
  that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

In Go, the testing package includes a benchmark facility. Therefore, if we are concerned about performance, as we often are, we start with a simple implementation and benchmark it. Starting number 837799 produces the longest chain of 525 elements. When I ran a Go benchmark, it took 231,949,902 nanoseconds, about one-quarter of a second.

BenchmarkEuler14-8   5   231949902 ns/op   0 B/op   0 allocs/op

euler14a_test.go:

package main

import "testing"

func lenChain(n int) int {
    c := 1
    for ; n > 1; c++ {
        if n&1 == 0 {
            n >>= 1
        } else {
            n += n<<1 + 1
        }
    }
    return c
}

func euler14() (maxn, maxc int) {
    maxs := 1000000 - 1
    for n := 1; n <= maxs; n++ {
        c := lenChain(n)
        if maxc < c {
            maxn = n
            maxc = c
        }
    }
    return maxn, maxc
}

func BenchmarkEuler14(b *testing.B) {
    for N := 0; N < b.N; N++ {
        euler14()
    }
}

If you you want it to be faster, perhaps we could remember some intermediate results. When I ran a Go benchmark, it took 16.979.849 nanoseconds, about than one-sixtieth of a second.

BenchmarkEuler14-8  100  16979849 ns/op  4005900 B/op  1 allocs/op

euler14b_test.go:

package main

import (
    "testing"
)

func lenChain(n int, a []int) int {
    if n < 1 {
        return 0
    }

    c := 1
    for m := n; m > 1; {
        if m < len(a) && a[m] > 0 {
            c += a[m] - 1
            break
        }

        if m&1 == 1 {
            // m is odd:
            // m = 3*m + 1
            m += m<<1 + 1
            c++
        }
        // m is even:
        // m = m/2
        m >>= 1
        c++
    }

    if n < len(a) && a[n] < c {
        a[n] = c
    }

    return c
}

func euler14() (maxn, maxc int) {
    maxs := 1000000 - 1
    a := make([]int, maxs/2)
    for n := 1; n <= maxs; n++ {
        c := lenChain(n, a)
        if maxc < c {
            maxn = n
            maxc = c
        }
    }
    return maxn, maxc
}

func BenchmarkEuler14(b *testing.B) {
    for N := 0; N < b.N; N++ {
        euler14()
    }
}

When I ran your "concurrent" program, using eight threads, it took 639,898,032 nanoseconds, about two-thirds of a second.

Some real-world code review questions: What is concurrency? What is parallelism? What do you expect to accomplish? What is your plan?

In your earlier Go performance question, Finding all prime numbers within a range, I pointed ot the importance of benchmarking and algorithms.

You only timed your program. You did not run Go benchmarks. You have no detail. You only used one simple algorithm. My benchmarks allowed me to peer into my code, often line by line. My code, using an optimized memoization algorithm, runs around nearly forty times faster than your concurrent code.

Efficient solutions to the problem exhibit little concurrency and little parallelism. Using concurrency tools adds overhead without any corresponding benefit.

  Comment:
  You compute a lot of intermediate values in the sequence, yet only
  cache the first (being m). I'd imagine your solution would be a lot
  faster if you made a second pass in lenChain that filled all the
  misses into a. If you bite the bullet with function call overhead for
  a recursive implementation, this change would even be trivial. –
  Dillon Davis

When I ran benchmarks, your idea, despite using more memory, was slower: 22,234,021 versus 16.979.849 nanoseconds.

euler14c_test.go:
BenchmarkEuler14-8   50  22234021 ns/op  8003587 B/op  1 allocs/op

euler14b_test.go:
BenchmarkEuler14-8  100  16979849 ns/op  4005900 B/op  1 allocs/op

euler14c_test.go:

package main

import (
    "testing"
)

func lenChain(n int, a []int) int {
    if n <= 1 {
        if n != 1 {
            return 0
        }

        c := 1
        if n < len(a) {
            if a[n] == 0 {
                a[n] = c
            }
        }
        return c
    }

    if n < len(a) {
        if a[n] > 0 {
            return a[n]
        }
    }

    m := n
    if m&1 == 0 {
        // m is even:
        // m = m/2
        m >>= 1
    } else {
        // m is odd:
        // m = 3*m + 1
        m += m<<1 + 1
    }
    c := 1 + lenChain(m, a)

    if n < len(a) {
        a[n] = c
    }

    return c
}

func euler14() (maxn, maxc int) {
    maxs := 1000000 - 1
    a := make([]int, maxs+1)

    for n := 1; n <= maxs; n++ {
        c := lenChain(n, a)
        if maxc < c {
            maxn = n
            maxc = c
        }
    }

    return maxn, maxc
}

func BenchmarkEuler14(b *testing.B) {
    for N := 0; N < b.N; N++ {
        euler14()
    }
}


C++ with Qt - Conversion of angle in radians to DDD°MM′SS.FFF″ string

Nice code - easy to read and well laid out.  No surprises in the code, apart from the need to clear up the carry from seconds to minutes etc.

Some small improvements:

Although M_PI is in POSIX, if you want to be properly portable, you'll want to define your own π, perhaps as 4*std::atan(1.);
You might help the compiler to hoist the value of 180/PI if you re-write the multiplication as angleInRad*(180/PI) or 180/PI*angleInRad.
There's no checking that the degrees value is in range of int when casting.
It might make more sense to represent the angle in seconds or minutes rather than degrees (compromising the range in exchange for easier handling of the modular arithmetic).

My version

#include <QString>

#include <climits>
#include <cmath>

QString radians_to_dms(double radians, int precision)
{
    static const double PI = 4*std::atan(1.);

    if (std::abs(radians) > ULONG_MAX*PI/180/60)
        // out of range
        return "---";

    const auto total_minutes = std::abs(radians*(60*180/PI));
    auto whole_minutes = static_cast<int>(total_minutes);
    auto seconds = 60 * (total_minutes - whole_minutes);

    auto secStr = QString::number(seconds, 'f', precision);
    if (secStr.startsWith("60")) {
        // it rounds up - carry to minutes
        secStr = QString::number(0.0, 'f', precision);
        whole_minutes += 1;
    } else if (secStr.startsWith('-')) {
        // negative zero - shouldn't happen
        secStr = QString::number(0.0, 'f', precision);
    }
    if (secStr.size() < 2 || secStr[1] == '.')
        // zero-fill
        secStr.prepend('0');

    return QString::fromUtf8(u8"%1%2°%3′%4″")
        .arg(radians < 0 ? "-" : "")
        .arg(whole_minutes / 60, 3, 10, QChar('0'))
        .arg(whole_minutes % 60, 2, 10, QChar('0'))
        .arg(secStr);
}

#include <QDebug>
int main()
{
    for (double a: { -0.0, -3.1415926535897932384, 1.0,
                     59.999996/3600*4*std::atan(1.)/180,
                     1. * ULONG_MAX})
        qDebug() << a << " = " << qPrintable(radians_to_dms(a, 5));

    const double step = .000142857;
    for (double a = 0;  a < 10*step;  a+= step)
        qDebug() << a << " = " << qPrintable(radians_to_dms(a, 5));
}

I get reasonable output from the test cases:

0  =  000°00′00.00000″
-3.14159  =  -180°00′00.00000″
1  =  057°17′44.80625″
0.000290888  =  000°01′00.00000″
1.84467e+19  =  ---
0  =  000°00′00.00000″
0.000142857  =  000°00′29.46637″
0.000285714  =  000°00′58.93274″
0.000428571  =  000°01′28.39911″
0.000571428  =  000°01′57.86549″
0.000714285  =  000°02′27.33186″
0.000857142  =  000°02′56.79823″
0.000999999  =  000°03′26.26460″
0.00114286  =  000°03′55.73097″
0.00128571  =  000°04′25.19734″
0.00142857  =  000°04′54.66371″

I'm not sure whether it's much improvement over the original, but I hope it gives you some ideas.


HackerRank "Bot Saves Princess" beginner code

The function should be path_to_princess(grid), using the naming convention specified in PEP 8.  The n parameter is redundant, as it can be inferred from the grid's dimensions.  In any case, redefining n=n-1 is confusing.  Also, it would be better to leave all I/O out of the function, so that it just does computation.

The while(flag) loop shouldn't exist.  If the princess is in another castle, you'll end up with an infinite loop; otherwise, the code executes just once.

Use the // operator for integer division.

Explicit looping can be greatly reduced through liberal use of list comprehensions, generators, and list multiplication.

def path_to_princess(grid):
    z = len(grid) - 1
    corners = [
        (0, 0), (0, z),
        (z, 0), (z, z)
    ]
    p = next((r, c) for r, c in corners if grid[r][c] == 'p')
    m = (z // 2, z // 2)
    row_diff, col_diff = p[0] - m[0], p[1] - m[1]
    yield from (['UP'] * -row_diff if row_diff < 0 else ['DOWN'] * row_diff)
    yield from (['LEFT'] * -col_diff if col_diff < 0 else ['RIGHT'] * col_diff)

n = int(input())
grid = [input().strip() for _ in range(n)]
for move in path_to_princess(grid):
    print(move)


Build a binary-heap from an array, which method is more efficient and why

Someone with more expertise on algorithms may provide a more concrete answer to your specific algorithms. However, I would like to point out two things on a general note:

1. Do the math.

Mathematically determining the complexity of an algorithm usually isn't that hard. Calculate big-O, check number of operations for given inputs and so on. While the answer may not be extremely precise, it's a nice exercise and can be very helpful.

2. Measure twice; cut once.

The best way to figure out the speed of an algorithm is to run it. Calculating the theoretical complexity is useful, but doesn't account for cache misses, branch prediction and the plethora of other things that can affect the execution speed. Run your algorithm on a large number of inputs and test cases to get statistically significant results. Run with and without a profiler to measure what exactly takes time. Sometimes you will find that altering the input, for example by sorting it or changing its layout to reduce cache misses, is more effective than altering the algorithm.


Mapping a user input string to a corresponding block of code

A problem with the code is that the async lambdas in the dictionary are actually async void.

  Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task<T> method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. -- Async/Await - Best Practices in Asynchronous Programming

It's also confusing because vcdLookup[commandName].DynamicInvoke() looks like a blocking call, but it isn't. Consider this code:

private static readonly Dictionary<string, Delegate> vcdLookup = new Dictionary<string, Delegate>
{
    { "OpenToDoList", (Action)(async () =>
        {
            Console.WriteLine("Opening to-do list...");
            await Task.Delay(TimeSpan.FromSeconds(1));
            Console.WriteLine("Opened to-do list");
        })
    }
};

public static void RunCommand(string command)
{
    vcdLookup[command].DynamicInvoke();
    Console.WriteLine("Finished command");
}

If we call RunCommand("OpenToDoList"), the output is

  Opening to-do list...

  Finished command

  Opened to-do list

I would recommend instead to change vcdLookup to a Dictionary<string, Func<Task>>.

private static readonly IReadOnlyDictionary<string, Func<Task>> vcdLookup = new Dictionary<string, Func<Task>>
{
    { "OpenToDoList", async () =>
        {
            StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"ToDo.doc");
            await Launcher.LaunchFileAsync(file);
        }
    }
};

public static async Task RunCommandAsync(string command)
{
    SpeechRecognitionResult result = command.Result;
    string commandName = result.RulePath[0];
    await vcdLookup[commandName]();
}

A couple of other notes:

Async methods should have the suffix Async, by convention
You probably don't want to make vcdLookup public, exposing it to the world
You can declare vcdLookup as an IReadOnlyDictionary so that its contents are not modified after creation


I don't know if it's still relevant for you, but I can see some optimization that you could do in your code.
As I see, you are passing all dataframe objects and then parsing specific columns in that dataframe:
def parse_url(df):
    for index, row in df.iterrows():
        parsed = urlparse(str(row['Destination URL'])).query #<==
        parsed = parse_qs(parsed)
        for k, v in parsed.iteritems():
            df.loc[index, k.strip()] = v[0].strip().lower()
    return df

It would be faster if you pass only the column that you need to parse.
E.g.
def parse_url(df):
    for index, row in df.iterrows():
        parsed = urlparse(str(row)).query # <- Notice the change here
        parsed = parse_qs(parsed)
        for k, v in parsed.items(): #use items() in Python3 and iteritems() in Python2
            df.loc[index, k.strip()] = v[0].strip().lower()
    return df

parse_url(df['columnName'])

Then first your function would have less work to do and performance would increase - at least slightly.


Getting all the master nodes in an elasticsearch cluster

Fix your indentation. Ruby uses 2 spaces of indentation.
Your naming is confusing. You have client_node, client and clients, which are all very different things (string, object, hash as far as I can tell). The only one that's well-named is client since that is indeed an instance of Client. But client_node you can skip entirely since you can just as well write ARGV.first (which is more Rubyesque than [0]) in the one place you need it. Or you can call it host since that what it is. And clients could be called client_info or something similar. Name it for what it is.

Note: In the following I keep your names for simplicity's sake, but you should really reconsider the naming in your code.
You can iterate keys and values in loops:

clients['nodes'].each do |name, info|
  puts info['host'] if info['attributes']['master'] == "true"
end

Things will break if the info hash doesn't have an attributes key - your code is assuming it's there. A way to avoid this is to use Hash#fetch to absorb nil values:

puts info['host'] if info.fetch('attributes', {})['master'] == 'true'

Since all you want is the master node, it'd be more expressive to find that node first - if it exists - and then do what you want with it:

master_node = clients['nodes'].detect do |name, info|
  info.fetch('attributes', {})['master'] == 'true'
end

puts master_node['host'] if master_node

Beyond that, I feel confident the Elasticsearch library exposes a bunch of convenience methods you can use instead of accessing values with string keys. There may also be a way to fetch just the master node, instead of looping through stuff to find it. But I don't know the library, so it's just a guess.


The original code seemed too complicated for this so I set out to write a simpler version. Should be fairly portable too, and fast as it is just bit shifts and subtraction.

(It works similarly to how one would accomplish division in assembly language on a processor without hardware division.)

// 128-bit / 64-bit unsigned divide

#include <stdio.h>
#include <stdint.h>

int main(void)
{
  // numerator
  uint64_t a_lo = 1234567;
  uint64_t a_hi = 0;

  // denominator
  uint64_t b = 10;

  // quotient
  uint64_t q = a_lo << 1;

  // remainder
  uint64_t rem = a_hi;

  uint64_t carry = a_lo >> 63;
  uint64_t temp_carry = 0;
  int i;

  for(i = 0; i < 64; i++)
  {
    temp_carry = rem >> 63;
    rem <<= 1;
    rem |= carry;
    carry = temp_carry;

    if(carry == 0)
    {
      if(rem >= b)
      {
        carry = 1;
      }
      else
      {
        temp_carry = q >> 63;
        q <<= 1;
        q |= carry;
        carry = temp_carry;
        continue;
      }
    }

    rem -= b;
    rem -= (1 - carry);
    carry = 1;
    temp_carry = q >> 63;
    q <<= 1;
    q |= carry;
    carry = temp_carry;
  }

  printf("quotient = %llu\n", (long long unsigned int)q);
  printf("remainder = %llu\n", (long long unsigned int)rem);
  return 0;
}


Try not to use using namespace std and system("PAUSE").

The former is okay for shorter programs or toy programs, or when used in local scope as opposed to global (such as within a function).

The latter is best avoided as it is problematic while safer and more portable alternatives are in existence, such as std::cin.get().  It's also non-portable and only works with Windows.
In certain environments (or depending on personal preference), new user-defined types should be capitalized and objects should be lowercase.

NewType objOfNewType;

Prefer an initializer list here:

NewType::NewType() : dataMember1(/* value */) {}

Although this may not make a huge difference in your code, it's still good to know about it when writing larger programs.  It is best when initializing objects (especially when the arguments are of the same name) and necessary when initializing constants.
As you're not using the destructor, you can leave it out.  The compiler will make one for you that does any of the default cleanup.
You shouldn't do this in the class declaration:

int decimalNum = 0;

You should instead put that into the initializer list as mentioned above:

// entries are separated by commas
// can also be listed on separate lines
className::className() : member1(0), member2(0) {}

You have declared printRoman(), but have not defined it.  Better yet, overload operator<< for your class and leave out that empty declaration.

Declare in header:

friend std::ostream& operator<<(std::ostream&, Class const&);

Define in source:

std::ostream& operator<<(std::ostream& out, Type const& obj)
{
    return out << obj.typeMember;
}

Print it out:

NewType objOfNewType;
std::cout << objOfNewType;

int is not a good loop counter type here:

for (int i = 0; i < romanNum.length(); i++) {}

romanNum is of type std::string, so you should use std::string::size_type.  This will ensure that you can loop through any string size while not being limited by int's size.

Better yet, use its iterators instead (using a range-based for-loop in C++11):

for (auto& iter : romanNum)
{
    if (iter == 'I')
        decimalNum++;
}

Another alternative (if you don't have C++11 and cannot use the above):

for (std::string::iterator = romanNum.begin(); iter != romanNum.end(); ++iter)
{
    if (*iter == 'I')
        decimalNum++;
}

Prefer not to pass-by-value here:

void romanType::setRoman(string troll)
{
    romanNum = troll;
}

As you're not modifying troll, prefer to pass by constant reference (const and &).  This will avoid unneeded copying, thereby also increasing performance.  It's best only for non-native types (such as std::string), so disregard it for any of the native ones.

Example (in different forms):

void func(const std::string& str) {}

void func(std::string const& str) {}

do-while loops are usually considered less-readable than while loops.  However, you don't need a while loop here as that would require adding another user input before the loop.

Instead, I'd recommend the "infinite loop" for (;;):

for (;;)
{
    std::cout << "This message will print forever!\n";
    std::cout << "But please do end this eventually!\n\n";

    bool keepGoing = true;
    if (!keepGoing) break; // or return
}

As described, this will keep looping until the loop is ended (usually with a break, return, or return X if non-void).  You'll just need a conditional that will decide when the loop should end.
Prefer to use variables as close in scope as possible:

std::cout << "Input: ";
int input;
std::cin >> input;

This is unneeded:

romanType Rom;
Rom.setRoman(numerals);

You're invoking the default destructor (no arguments) while calling the mutator.

Instead, the object should be constructed right away with numerals:

romanType Rom(numerals);

Beyond that, you won't need a mutator in your program.  They can also be bad for encapsulation, but that's another topic.  For now, focus on proper object construction while only using necessary implementations.  Keep your code as concise as possible.

Note that my previous point about the initializer list was for example purposes.  In this case, you'll need to add an argument to the list.

NewType::NewType(ArgType arg) : member1(arg) {}

With this in place:

NewType objOfNewType(5); // will compile
NewType objOfNewType;    // will not compile

In your program, the latter should still happen as the conversion process shouldn't work with no input given to the object.  You can also keep your existing default constructor, allowing the latter to still work.  But there may be no need for a default value if you want the user to give input.


Automatic Visual Studio Nuget consolidatation

You can use Select-Object instead of casting to pscustomobjects. For instance this:

foreach { [pscustomobject]@{ packagename=$_.packagename; VG=$_.VG; versions=$_.versions; versionCount= $_.versions.Count; versionMAX=$_.versionMAX }}

becomes this, which is somewhat shorter and less noisy:

select packagename VG versions @{Name="versionCount"; Exp={$_.versions.Count}} versionMAX

Notice the calculated property for versionCount.

Regarding the single line of code, I think you could have multiple statements separated by semicolons. You would work on the code as multiple lines in your text editor, and then join them together before pasting into VS.

Write-Output hello; Write-Output world


Import function vs turning it into custom hook

Well, in your case, your "hook" isn't really managing any state. I would say that you can safely hold it in a simple file and import it. But if your functions were to do something more than just logging, I would make a custom hook, since it would most likely work better with the lifecycle of components, triggering re-renders when needed.


How to find contradiction in order of items in multiple sequences

Consider the case

A: 1 2 3 2 4 5
B: 1 2 2 4 5
C: 3 2
D: 2 3
E: 2 2
F: 1 2 3 4 5

You report back:

1 2 3 2 4 5 contradicts 3 2
1 2 3 2 4 5 contradicts 3 2
1 2 3 2 4 5 contradicts 3 2
1 2 3 2 4 5 contradicts 3 2
3 2 contradicts 1 2 3 2 4 5
3 2 contradicts 2 3
3 2 contradicts 1 2 3 4 5
3 2 contradicts 1 2 3 2 4 5
3 2 contradicts 2 3
3 2 contradicts 1 2 3 4 5
2 3 contradicts 3 2
2 3 contradicts 3 2
1 2 3 4 5 contradicts 3 2
1 2 3 4 5 contradicts 3 2

I used this code to test: ( http://goo.gl/QOEBao or http://www.tutorialspoint.com/compile_csharp_online.php?PID=0Bw_CjBb95KQMZGNRVXQ2Y0JlOU0 )

static void Main()
{
    List<List<String>> seqs = new List<List<String>>{
        new List<String>{
            "1", "2", "3", "2", "4", "5"
        },
        new List<String>{
            "1", "2", "2", "4", "5"
        },
        new List<String>{
            "3", "2"
        },
        new List<String>{
            "2", "3"
        },
        new List<String>{
            "2", "2"
        },
        new List<String>{
            "1", "2", "3", "4", "5"
        }
    };
    if (HasContradiction(seqs))
    {
        Console.WriteLine("yep");
        foreach(Tuple<string, string> x in Cont)
        {
            Console.WriteLine(x.Item1 + " contradicts "+ x.Item2);
        }
    } else {
        Console.WriteLine("nope");
    }
}

There's a few that are not correct - if I label them...

X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 3 2 contradicts 1 2 3 2 4 5
Y 3 2 contradicts 2 3
Y 3 2 contradicts 1 2 3 4 5
X 3 2 contradicts 1 2 3 2 4 5
Y 3 2 contradicts 2 3
Y 3 2 contradicts 1 2 3 4 5
Y 2 3 contradicts 3 2
Y 2 3 contradicts 3 2
Y 1 2 3 4 5 contradicts 3 2
Y 1 2 3 4 5 contradicts 3 2

Then these are wrong:

X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 3 2 contradicts 1 2 3 2 4 5
X 3 2 contradicts 1 2 3 2 4 5

Basically, what you don't do is check for duplicates.

Now, there's two things this could mean:

First option, you don't actually support duplicates. It's logically impossible for there to be duplicates. In that case, you should take an ordered, unique collection as input (a sorted set, as it were). A weaker alternative might be checking if you have duplicates and throwing errors for that, if altering the signature is not possible.

Second option, you do support duplicates. In that case, you should alter your code to support duplicates.


This is exactly the implementation found in NumPy and SciPy Recipes for Data Science on k-Medoids Clustering but with some indentation mistakes (probably due to the copy & paste process). To understand the indentation being used in the algorithm is might be worth to read the answers on the for...else syntax:
https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops#9980752
A working script with the correct indentation and some improvement is found at
https://github.com/letiantian/kmedoids/blob/master/kmedoids.py :
import numpy as np
import random

def kMedoids(D, k, tmax=100):
   # determine dimensions of distance matrix D
   m, n = D.shape

   if k > n:
       raise Exception('too many medoids')

   # find a set of valid initial cluster medoid indices since we
   # can't seed different clusters with two points at the same location
   valid_medoid_inds = set(range(n))
   invalid_medoid_inds = set([])
   rs,cs = np.where(D==0)
   # the rows, cols must be shuffled because we will keep the first duplicate below
   index_shuf = list(range(len(rs)))
   np.random.shuffle(index_shuf)
   rs = rs[index_shuf]
   cs = cs[index_shuf]
   for r,c in zip(rs,cs):
       # if there are two points with a distance of 0...
       # keep the first one for cluster init
       if r < c and r not in invalid_medoid_inds:
           invalid_medoid_inds.add(c)
   valid_medoid_inds = list(valid_medoid_inds - invalid_medoid_inds)

   if k > len(valid_medoid_inds):
       raise Exception('too many medoids (after removing {} duplicate points)'.format(
        len(invalid_medoid_inds)))

   # randomly initialize an array of k medoid indices
   M = np.array(valid_medoid_inds)
   np.random.shuffle(M)
   M = np.sort(M[:k])

   # create a copy of the array of medoid indices
   Mnew = np.copy(M)

   # initialize a dictionary to represent clusters
   C = {}
   for t in xrange(tmax):
       # determine clusters, i. e. arrays of data indices
       J = np.argmin(D[:,M], axis=1)
       for kappa in range(k):
           C[kappa] = np.where(J==kappa)[0]
       # update cluster medoids
       for kappa in range(k):
           J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)
           j = np.argmin(J)
           Mnew[kappa] = C[kappa][j]
       np.sort(Mnew)
       # check for convergence
       if np.array_equal(M, Mnew):
           break
       M = np.copy(Mnew)
   else:
       # final update of cluster memberships
       J = np.argmin(D[:,M], axis=1)
       for kappa in range(k):
           C[kappa] = np.where(J==kappa)[0]

   # return results
   return M, C

Note that the else as well as the return are at the same indentation as the for-loop.
However, I recommend to change the second inner loop
# update cluster medoids
for kappa in range(k):
       J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)
       j = np.argmin(J)
       Mnew[kappa] = C[kappa][j]

to
# update cluster medoids
for kappa in range(k):
       J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)
       # Fix for the low-idx bias by J.Nagele (2019):
       shuffled_idx = np.arange(len(J))
       np.random.shuffle(shuffled_idx)
       j = shuffled_idx[np.argmin(J[shuffled_idx])]
       Mnew[kappa] = C[kappa][j]

as otherwise the resulting medoids depend on the order of the input. That is because the argmin command returns always the lowest index in case multiple potential medoids have equal distances to the cluster members.


Jasmine unit test that triggers mouse events in Angular 4

I did come up with one alternative which is as follows:

    function triggerEvents(debugElement: DebugElement, eventName: string, object: any){
            debugElement.triggerEventHandler(eventName, object);
        }

    function expectAndReset(spy: Function, object: any, spyObj: jasmine.Spy) {
        expect(spy).toHaveBeenCalledWith(object);
        spyObj.calls.reset();
    }

    it('test the move event', inject([MyService], (service: MyService) => {
        let spyObj = spyOn(service.x, 'emit');
        spyObj.and.callThrough();
        triggerEvents(de[0],'mousedown', { pageX: 10, pageY: 10 });
        triggerEvents(de[0],'mousemove', { pageX: 40, pageY: 20 });
        expectAndReset(service.x.emit,{ x: 30, y: 10 },spyObj);
        triggerEvents(de[0],'mousemove', { pageX: 45, pageY: 25 });
        expectAndReset(service.x.emit,{ x: 35, y: 15 },spyObj);
        triggerEvents(de[0],'mousemove', { pageX: 50, pageY: 30 });
        expectAndReset(service.x.emit,{ x: 40, y: 20 },spyObj);

    }));

I am not really satisfied with my own solution though, because the function implementation of triggerEvents is almost identical as the triggerEventHandler in the Angular Documentation. I am not doing anything special there. But I am hoping that the code reviewers on the community would comment or share their views and give me a better solution :)

Second Attempt:

        function triggerEvents(debugElement: DebugElement, eventName: string, object: any) {
            debugElement.triggerEventHandler(eventName, object);
        }

        function expectAndReset(spy: Function, object: any, spyObj: jasmine.Spy) {
            expect(spy).toHaveBeenCalledWith(object);
            spyObj.calls.reset();
        }

        it('test the move event', inject([MyService], (service: MyService) => {
            let spyObj = spyOn(service.x, 'emit');
            spyObj.and.callThrough();
            triggerEvents(de[0], 'mousedown', { pageX: 10, pageY: 10 });
            for (let i = 0; i <= 10; i += 5) {
                triggerEvents(de[0], 'mousemove', { pageX: 40 + i, pageY: 20 + i });
                expectAndReset(service.x.emit, { x: 30 + i, y: 10 + i }, spyObj);
            }

        }));

Somewhat satisfied with my second iteration.

Thank you.


Implementing a date validator using enum

Handling exceptions

Integer.parseInt throws a NumberFormatException when there is a parsing error, you may want to consider catching that and then just output the validation status as "Invalid".

Field names

final Set<Integer> values = new HashSet<Integer>(Arrays.asList(1, 3, 5, 7, 8, 10, 12));

These aren't just any values, these represent months with 31 days in them. :) Probably call this as monthsWith31Days? I also understand you want to make it clear that these months are obviously unique in the collection (in layman terms), but considering this is only used internally within the method, I don't think there's much harm leaving it as just a List.

Day validation logic

Personally, I will start from the most constrained case and work my way down. The slight advantage is that your 'wider' cases will not need to check that is it not any of the constrained cases (e.g. look at how you do a month != 2 for the first else if branch). In conclusion, this means you can validate for the month of February first, then the 31-day validation, and finally for all remaining months. You can also return immediately from each of the branch, instead of one return statement at the end.

Putting it altogether for DateValidator.isDateLegal()

    private boolean isDateLegal(final String date) {
        final int day = getDay(date);
        final int month = getMonth(date);
        final int year = getYear(date);
        final List<Integer> monthsWith31Days = Arrays.asList(1, 3, 5, 7, 8, 10, 12);
        if (day > 0) {
            if (month == 2) {
                // BTW no need to check if month = 2 here
                return day <= isLeapYear(year) ? 29 : 28;
            } else if (monthsWith31Days.contains(month)) {
                return day <= 31;
            } else if (month > 0 && month < 13) {
                return day <= 30;
            }
        }
        return false;
    }

Regex

Now onto the big one... your regular expression is ideal for simplification by applying the following rules:

[1-2] can be represented as [12].
Metacharacters (e.g. .) are interpreted literally in character classes, so there is no need to escape them.
To match - inside a character class, put it at the last so that it doesn't get interpreted as a range syntax.
Just as you have used a character class to do your separator replacement for date, you should do likewise for your DATE_PATTERN too.
In addition to the previous point, you can then apply capture groups to check that the same separator is used.

Putting it altogether for regex

private static boolean isDateFormatValid(final String date) {
    final String DATE_PATTERN = "^([0-9]{2}([./\\s-]?)[0-9]{2}([./\\s-]?)[12][0-9]{3}|"
            + "[12][0-9]{3}([./\\s-]?)[0-9]{2}([./\\s-]?)[0-9]{2})$";
    final Matcher matcher = Pattern.compile(DATE_PATTERN).matcher(date);
    return matcher.matches() && (Objects.equals(matcher.group(2), matcher.group(3)))
            && (Objects.equals(matcher.group(4), matcher.group(5)));
}

(BTW, Objects.equals() is a Java 7 method and it is a simple null-safe implementation of calling the first argument's equals() with the second argument. This is important as matcher.group() can return null for non-matches.)

Pro-tip: Actually, you may want to go a step further by grouping the day and year values, and make sure that the length of both parts (i.e. DD,YYYY or YYYY,DD) are different:

private static boolean isDateFormatOk(final String date) {
    final String DATE_PATTERN = "^([0-9]{2}|[12][0-9]{3})([./\\s-]?)[0-9]{2}([./\\s-]?)"
            + "([0-9]{2}|[12][0-9]{3})$";
    final Matcher matcher = Pattern.compile(DATE_PATTERN).matcher(date);
    return matcher.matches() && (matcher.group(1).length() != matcher.group(4).length())
            && (Objects.equals(matcher.group(2), matcher.group(3)));
}

(Pro-pro-tip: The Pattern can be a private static final field...)

For the validate() method, you can check for a valid format first before validating the entire string:

public boolean validate(final String date) {
    return isDateFormatValid(date) && isDateLegal(date.replaceAll("[./\\s-]", ""));
}


Wrong type

You defined a type called item_t but you didn't use it everywhere:

/* our stack data type */
typedef struct {
    int size;
    int capacity;
    int *elements;
} stack;

Here, elements should be of type item_t *.  Also, your pop function should return a item_t * instead of a void *.

You could go a different direction and use void * as your generic type instead of item_t.  That way, you could store anything in your stack, but you'd have to allocate each item.

Size of -1?

I agree with janos that size should start at 0 instead of -1.  That way, size will represent the number of items on the stack.

Error handling in push

You correctly check the return value of realloc() in your push function.  However, if it returns NULL, your code currently keeps going and causes a buffer overflow.  You should return 1 immediately and not fall through to the rest of the code.

Useless line

In delete_stack(), the line:

mystack = NULL;

doesn't do anything because it won't affect the caller's pointer.

Code simplification

There are a few things that you could do to simplify your code.  One is to eliminate your res variable if you can just return a value immediately.  Another is to merge the postdecrement/postincrement operation into the array access.  For example, your pop function:

void* pop_stack(stack *mystack)
{
    int *res;
    if(mystack->size == -1) {
        res = NULL;
    } else {
        res = &mystack->elements[mystack->size];
        mystack->size--;
    }
    return res;
}

could be simplified to:

item_t *pop_stack(stack *mystack)
{
    if (mystack->size == -1)
        return NULL;
    return &mystack->elements[mystack->size--];
}

Reducing memory

In regards to your question about reducing capacity when popping, you could shrink your array when you pop but you need to be careful:

You should probably remember the initial capacity and not shrink the array below that level.
You don't want to do something where you resize too often.  For example, if you did the natural thing of shrinking when you pop below half capacity: if (size == capacity/2) { resize smaller }, then what could happen is that you could bounce between sizes if the user pushes and pops right at the threshold.  In other words, if the last push caused an expansion, the next pop would cause a contraction, and that would be bad because they could keep pushing and popping at that level and cause a resize every time.  Therefore, you need to either use a smaller ratio than 1/2 for contraction or use a different criterion.


Calculate a month later than current month (without rolling over to next month)

I'm inclined to keep it simple:

$start = new DateTime('30-Jan-2014', new DateTimeZone("America/Toronto"));
$end = clone $start;
$end->modify('+1 month');
while (($start->format('m')+1)%12 != $end->format('m')%12) {
    $end->modify('-1 day');
}
echo $end->format('d-M-Y');

This just checks to see if the month is the expected one, and if not, backs up one day at a time until it is.  The advantage is that it's short, clear, and will work even in leap years (try 2004 to verify that).

Edit: It's also easy to make this into a user-defined function:

function addMonth($begin)
{
    $end = clone $begin;
    $end->modify('+1 month');
    while (($begin->format('m')+1)%12 != $end->format('m')%12) {
        $end->modify('-1 day');
    }
    return $end;
}


improvement of a database register function

You can actually merge them pretty easily. They're very similar, with just a minor difference in the strings that determine what key failed. But luckily you can get the bad key by using the message attribute of the exception:]

try:
    site_id = request.data['site_id']
    category_id = request.data['category_id']
except Exception as e:
    print('Request error or missing {}:'.format(e.message), e)
    return Response(status=status.HTTP_400_BAD_REQUEST)

Now they both work the same except that the missing key is taken out of your exception e and formatted into the message you print for the user.

I also think you should except KeyError, not just any old Exception. Using the latter would mask typos, while the former deals specifically with the typeof exception you expect to appear.


#include "../../std_lib_facilities.h"

While PPP is structured around using this header, you will eventually be including only what you really need to make your code self-sufficiently compilable.  So instead of including a bunch of libraries you don't need, just include what you use.

#include <iostream>
#include <vector>

The header Stroustrup provides also imports all visible symbols in namespace std into the global namespace.  The global namespace is then polluted with a bunch of names that could lead to collisions.  The compiler could resolve function overloads in unexpected ways.  Essentially, using namespace std; is considered bad practice.  If you must use using directives, keep the use in the narrowest scope possible.  Otherwise, qualify names with their namespace as the namespace will help the reader understand what is being called and from where.

    double median_value;

Avoid declaring variables before you need them.  This technique is an artifact of older programming languages that didn't allow initialization of variables and constants after a statement.  Errors commonly associated with this technique include use-before-set, incorrectly initialized variables, and possibly non-contextual reuse due to programmer laziness.

The simplest solution is to declare the variable as close to its initialization point.

    double median_value;
    if (temps.size() % 2 == 0)
        median_value = ...;

Even better, directly initialize the variable with a value.

    const auto median_value = median(temps);

This reduces the chance of errors happening as well as reducing the cognitive load for readers.  Directly initializing variables also allows you to take advance of const/constexpr.

    sort(temps);

Do you need to sort the entire container? When we're looking to find the median, we're only interested in picking out either the middle value or the middle two values.  Rather than sort, we would rather select.  C++ implementations typically provide introselect for its selection algorithm (std::nth_element).

As you learn more about <algorithm> and iterators, keep this in mind.

        median_value = (/* ... */ + temps[temps.size() / 2 - 1]) / 2;

It's really important to keep in mind the possible states a variable can represent.  In the case of temps, that std::vector<double> could represent any number of doubles as well as nothing.  When temps is empty, temps.size() / 2 - 1 evaluates to 0 / 2 - 1. It's important to note that temps.size() returns size_type, an alias for an unsigned value.  Thus, subtracting one from unsigned zero results in the maximum value held by std::vector<double>::size_type. It's essentially a really large value almost guaranteed to be out of bounds when used in your context.  Out of bound index access is a common case of undefined behavior.

If the user doesn't provide you with values, you can't calculate a median.  temps having at least one value is a precondition for calculating the median.  Check your preconditions and notify the user if they mess up.  How you notify the user is up to you, but keep this in mind as you go over chapters on error and exception handling.

    for (int i = 0; i < temps.size(); ++i) cout << temps[i] << ", ";

As stated before, temps.size() returns an unsigned value.  The comparison i < temps.size() is a signed-unsigned mismatch.  If temps contains more values than i can represent, you'll have a bug.

If you are simply accessing the elements and don't need to apply transformations on the index, use the range-based for loop.

    for (auto temp : temps) std::cout << temp << ", ";


Insertion sort with binary search in Python

Your binary_search is the same as the built-in function bisect.bisect, and you might find the implementation helpful to study.


Is this a decent way to create an EntityManager?

Ahhhhhhhhh
static EntityManager* instance();

No ownership associated with even the manager.
If I get a manager. Who is responsible for destroying it?
// Do this.
// Use the classic singleton pattern.
static EntityManager& instance()
{
     static EntityManager   managerInstance;
     return managerInstance;
}

https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289
Who owns the entity?
void registerEntity(Entity* entity)

Is the manager supposed to take ownership. Which means it will take responsibility for destroying the entity? Or are you giving the manager a reference it can use but does not own (thus it will not destroy).
As it stands. This is completely the wrong way of doing it. Once you tell me how you want to define the semantics of the interface I can tell you how to proceed.

Update The manager is supposed to take ownership.
So lets continue:
void registerEntity(Entity* entity)
{
    entityMap.insert(std::pair<int, Entity*>(entity->getId(), entity));
}

From the interface you can tell that the manager takes ownership. As a result it can easily be called like this:
Airplane    airplane;
EntityManager::instance()->registerEntity(&airplane);

Now what will happen in your code. I suspect it will blow up at some point in the distant future. Try tracking that bug down.
The way to do this is to tell the manager he is supposed to take ownership. To do this your interface is supposed to take a std::unique_ptr. Also a couple of potential bugs to watch out for. Somebody may pass you a NULL in which case calling getId() is going to generate undefined behavior (by that I mean crash).
int registerEntity(std::unique_ptr<Entity>&& entity)
{
    if (!entity.get())
    {    return -1;
    }

    entityMap.insert(std::pair<int, Entity*>(entity->getId(), std::move(entity)));
    return entity->getId();
}

Notice I am moving the smart pointer into the entityMap. This shows that you are moving ownership into the map. It must also be smart enough to hold the smart pointers. So you have two options:
std::unordered_map<int, std::unique_ptr<Entity>> EntityMap;

Alternatively boost has a pointer container library, where the container takes ownership. Unfortunately they don't have unordered_map but they do have map.
boost::ptr_map<int, Entity> EntityMap;

Using the boost pointer containers has the advantage as access to the elements in the container make them look like objects (not pointers) thus using with any of the standard algorithms is trivial (Note: using algorithms on normal containers that hold pointers is a pain because of the extra de-reference involved).
Anyway either technique will remove the problem of memory leaks.
No check for NULL. Also I see no advantage of having this interface when the previous one void removeEntity(int) does exactly the same thing and does not have the disadvantage of ownership semantics.
void removeEntity(Entity* entity)
{
    removeEntity(entity->getId());
}

Returning a pointer here:
Entity* getById(int id)
{
    return entityMap.at(id);
}

Does this give you ownership of the object back?
I would think not. If you return a pointer you open yourself up to the user being confused and deleting the pointer.
Entity* plane = EntityManager::instance()->getById(12);
// WORK on place
delete plane;     // BANG

So return a reference to indicate the caller is not getting ownership back. This does open the question of how do do you handle values that would have returned NULL previously. I would handle this by having an existence test. So for ID that you are not sure about you can validate before a retrieval.
Entity& getById(int id) const
{
    return *entityMap[id];   // de-reference the smart pointer.
}
bool checkById(int id)
{
    return entityMap.find(id) != entityMap.end();
}


Returning a validation error from a command handler

This is an interesting question because I've never seen the MVC and the command pattern implemented together.  Typically I think WebForms when I think of the command pattern.  I'm still on the fence on whether or not it is a good fit but there are a couple of MVC concepts you can use to make your code cleaner.  The most valuable of which in your case is to:

Leverage Custom Model Binding

I agree, your controller shouldn't have to do work to build the request model (slug, post request), this should all be happening in a custom model binder:

public class AddPostCommandModelBinder : DefaultModelBinder
{

    protected virtual void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var command = (AddPostCommand)bindingContext.Model;
        // Add the ExpectedSlug property to the request command and have the ModelBinder do this work (as well as any other post-binding logic
        command.ExpectedSlug = command.Title.Replace(" ", "-");
    }
}

In addition to this, your PostRequestHandler is a concern much better solved using Model Binding, as the responsibility of Model Binding is to take request parameters and map them to a strongly typed object as well as validating those inputs (by default using the DataAnnotations namespace: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations%28v=vs.110%29.aspx.

In yet another Model Binder, you can put any custom validation logic, for example:

public override Object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var newModel = (PostRequest)bindingContext.Model;
    newModel.AttemptedSlug = bindingContext.ValueProvider.GetValue("title").AttemptedValue;

    if(string.IsNullOrWhiteSpace(newModel.AttemptedSlug))
    {
        bindingContext.ModelState.AddModelError("AttemptedSlug", "The Attempted Slug is required.");
    }
    // Other custom logic

    return newModel;
}

A point on Injection

As with anything MVC, the code should be test-able.  I'm not sure if you omitted it for brevity, but the command handlers should be constructor-injected interfaces bound to concrete types (ideally) using an IoC container.  Also, with the changes above, your controller should now look like this:

public class PostController : Controller
{
    IPostCommandHandler _postCommandHandler;

    public PostController(IPostCommandHandler addCommandHandler)
    {
        this._postCommandHandler = addCommandHandler;
    }

    [HttpPost]
    public ActionResult AddPost(AddPostCommand command, PostRequest submitRequest)
    {
        ActionResult result = null;
        if (!submitRequest.IsValid)
        {
            result = View("AddPost", submitRequest);
        }
        else
        {
            string actualSlug = this._postCommandHandler.Handle(command);
            result = RedirectToAction("Index", "Post", new { actualSlug });
        }

        return result;
    }
}

Ultimately, I follow several rules of thumb as far as my separation of concerns that have kept me mostly out of trouble.

Model binders bind all request parameters to strongly typed request objects (with a few exceptions).

Model binders handle basic data-validation and error handling for user input

Controllers accept request models, check for validity, call external data services to build response view models, and determine action (redirect, view, etc...)

Other Notes

The usage of the word "post" as part of your domain (presumably you're using the term in the sense of a blog "post"), should be re-considered.  POST carries a lot of context with it and some developers (myself included) will have to read around the common use of post when reading this code.

Consider renaming post to blogPost or forumPost or newsPost to make the code clearer.

Adding validation logic in the controller should be a red flag, but adding messaging in the controller is perfectly appropriate, as the messaging is directly related to the view (which is found, prepared and delivered by the controller).  I wouldn't do a null check as you have done, but either use a validator in the model binder (ModelState.IsValid), or providing your own as I did above as part of the PostRequest object.

You may also want to consider adding an AddPostCommand property to your PostRequest, which would then require your controller to take only one argument.  You can still have a custom model binder for each type.


Just do:

// Default value
select @Title = "invalid";

// If a record is found, replace "invalid" by the Title value
select @Title = Title from MyTable where ID=@ID;