id

you shadow the builtin id with this name as variable

itertuples

a way to improve performance is using itertuples to iterate over the DataFrame: for _, node, parent in df.itertuples():

iterations

You can do this in 1 iteration over the input with a nested loop over the ancestors:

node_ancestors = defaultdict(set)
node_ancestors[0] = set([0])
node_descendants = defaultdict(set)
node_descendants[0] = set([0])
for _, node, parent in df.itertuples():
    node_ancestors[node].add(node)
    node_ancestors[node].update(node_ancestors[parent])

    for ancestor in node_ancestors[node]:
        node_descendants[ancestor].add(node)

Depending on how nested the tree is, this will be faster or slower than iterating over the whole input twice. You'll need to test it on your dataset.

global vs local

another speedup might be achieved by doing this in a function instead of the global namespace (explanation)

def parse_tree(df):
    node_ancestors = defaultdict(set)
    node_ancestors[0] = set([0])
    node_descendants = defaultdict(set)
    node_descendants[0] = set([0])
    for _, node, parent in df.itertuples():
        node_ancestors[node].add(node)
        node_ancestors[node].update(node_ancestors[parent])

        for ancestor in node_ancestors[node]:
            node_descendants[ancestor].add(node)

    return node_ancestors, node_descendants


Coverage processing on multiple Java projects with gmake

.PHONY: checkout all clobber clean $(checkout.all)

There's no clobber target, so I think that will be ignored.

The root variable is unnecessary (CURDIR should be well known by anyone using make), and is even defined twice.

names=$(shell cat etc/projects.txt)

In my experience it's more common to write out the list in the makefile. If this is so long as to clutter up the file, you could create a separate makefile for variables like this and include variables.mk or similar.

projects build: ;  mkdir -p $@

Why not split this into two lines? Also, the -p doesn't make any difference since it's only creating a single directory under the current one.

touch $@

This looks like a hack to get around checkout not updating the modified date properly, or to rebuild a project when make doesn't think it needs to be rebuilt. You might be able to just set the relevant target .PHONY or change it so that rebuilding is only done when necessary.

cd projects/$* && git clean -xfd && git reset --hard

This is rather brutal. I'd rather advise to use non-recursive make (based on  Recursive Make Considered Harmful) and enumerate the files to remove to make sure you never remove anything other than generated files. You could have a separate target with cd projects/$* && git clean -xnd to check whether there's anything you still need to clean.

clobber-%:
  cd projects && rm -rf $*

This also looks dangerous. You're effectively saying that make clobber-whatever will delete whatever no matter what it is. I can't recall where I heard this advice, but I do believe it's good practice to enumerate the files which makefiles can and should work with, rather than adding general-purpose tactical nuclear missiles.

define testgen =
...
$(foreach var,$(testgen.types),$(eval $(call testgen,$(var))))

There's a lot of indirection going on here, so it's difficult to understand what will actually be run in the end. Are you sure this couldn't be done simpler?

This is a personal preference, but I tend to avoid any echo statements because the make output should make it clear what is actually happening, and comments like this often tend to get out of sync with the rest of the code. On the other hand, you can include special targets to get the value of all/any variables.


Find all concatenated words in a given list of words

I took me a while to understand your code since I didn't know from the beginning what each variable really meant:

i is probably an int, maybe an index
x is probably a number (maybe even a float), or something unknown, or a placeholder
seen is a set of something, and this something could really be anything
stack will only be used by calling append and pop, but what does it contain? ints, strings, complex objects? The name stack by itself doesn't give any clue.
w could also be spelled word, but that one is already the best of the variable names

Therefore, to really understand what each variable stands for, I had to run your code using only pen and paper, which was a good exercise since I really don't do that often.

By doing that I noticed:

the only purpose of the if not w: continue is to prevent the empty word from being output
the only purpose of the w[i:] in words is to speed up the implementation; it is not necessary for the pure algorithm
the expression i + x appears several times. I wondered whether the Python runtime would be able to apply common subexpression elimination to it, or whether it would make the program faster if that expression were saved into a separate variable
I wanted to replace the x != word_len with the simpler i != 0, but I quickly noticed that this would break the whole algorithm
using a stack is great because the larger string indices are pushed at the end, which means they are popped and checked first, which speeds up the program. At least in the catsdogcats case
the range should not start at 0, but at 1, since for the empty word, seen[i + x] is always True
the code is really efficient

After finishing the manual analysis, each and every little expression made sense. I didn't discover anything superfluous. Therefore: nice work. You should make the variable names a little more suggestive though.

i could be left
i + x could be right
x could be subword_len
stack could be indices_to_test
seen could be seen_indices

One idea I had during the analysis was that the code might become easier to understand if you used a nested function:

def find_all_concatenated_words_in_a_dict(words: List[str]) -> List[str]:
    words = set(words)

    def is_concatenated(word: str) -> bool:
        ...
        return True

    return [word for word in words if word and is_concatenated(word)]

After executing your algorithm using pen and paper, I thought that another implementation might be even more efficient, and maybe lead to shorter code. My idea was:

def is_concatenated(word: str) -> bool:
    word_breaks = [True] + [False] * len(word)

    for start in range(len(word_breaks)):
        if word_breaks[start]:
            for sub_len in range(1, len(word_breaks) - start):
                if sub_len != len(word) and word[start:start + sub_len] in words:
                    word_breaks[start+sub_len] = True

    return word_breaks[-1]

This code also starts at the beginning of the long word and marks all reachable word breaks. It uses fewer variables though.

The code can be further optimized:

for the sub_word length, only iterate over the lengths that actually appear in the word set
return early as soon as word_breaks[-1] becomes True

But even with these optimizations, the time complexity stays at \$\mathcal O({\text{len}(\textit{word})}^3)\$, which is quite much when \$\text{len}(\textit{word})\$ can be up to 10_000. Space complexity is \$\mathcal O(\text{len}(\textit{word}))\$, and the initial part of the word_breaks[:start] list could be thrown away early.

The \$n^3\$ is because of the 2 nested for loops, and deeply nested in these loops is a string comparison of the subword, which also depends on \$\text{len}(\textit{word})\$.

I'd rather have an \$\mathcal O(n^2)\$ or even \$\mathcal O(n)\$ algorithm though. I just don't know whether one exists.


Better is subjective but I will try and improve the code your have here to make it more robust and scalable. I will try to cover areas of improvement or focus and bring it together in the end. A lot of this is error hardening and trying to help remove potentials flaws in the assumptions the code was making.

Pitfalls with non validated paths passed

Hopefully not a nitpick but you are not doing any validation on your paths so it is possible for it to unexpectedly error out if a non-path based string is passed. Looking at about_Functions_Advanced_Parameters we see one option we can you is ValidateScript. The message returned for a failure now is arguably vague but it is a start. Consider one such parameter given the above suggestion.

[parameter(Mandatory=$true,Position=2)]
[ValidateScript({Test-Path -PathType Container $_ })]
[string]$Destination

Now if a bad path is passed the script will error before it starts processing. While we are not avoiding any bad issues really, in this case, this is a good habit to get into.

  Cannot validate argument on parameter 'DifferenceFolder'. The "Test-Path -PathType Container $_ " validation script
  for the argument with value "bagels" did not return a result of True.

Parameter names

You have inconsistent parameter names one for $source and one $dest. The latter one is a short form and the other is not. Also, these variables are common associated with copying. However your not doing that with this function. I am going to side with original author of your code snippet and use more meaningful names. $ReferenceFolder and $DifferenceFolder. Don't worry though. If you really wanted your variable names I would like to propose a compimise and use a parameter alias! This way you could use either and the script works just the same.

[alias("Destination")]
[string]$DifferenceFolder,

Also note worthy is that PowerShell will allow you to use short forms automatically as there is no ambiguity. So you can still use -Dest on the command line as there is only one thing that could mean.

Using Alias in production scripts

Many were consider this a faux-pas as it can obfuscate your code and make people (more ones not familiar with them) not understand what is happening. Testing/Code Golf? Sure use aliases as it can make the code more terse. Production? Use the full names to prevent confusion later if someone else or even you down the road are reading your code.

Using Select after Get-ChildItem

The code is creating a new object array that has the fullname of the file and its hash by use of a calculated property. Get-FileHash contrary to what your linked post says (and the documentation is seems) does accept pipeline input. Also the return properties of the cmdlets are path (which contains the fullpath), hash and algorithm. So there is not need to recreate what is already there. Removing the calculated properties saved some processing time in testing as well.

$referenceFolderHashes = Get-ChildItem $ReferenceFolder -File -Recurse | Get-FileHash -Algorithm $Algorithm | Select Path,Hash

Consider not using MD5

Like CodesInChaos states you should consider not using MD5. There is more likely chance that two different files could generate the same hash with MD5. So SHA256 would be an obvious candidate. Still it is only a chance. I have added a parameter called $Algorithm that will handle this. It is not mandatory and by default is "MD5" for your convenience. We use [ValidateSet] to ensure that you can only choose algorithms supported by Get-FileHash

[parameter(Mandatory=$false)]
[ValidateSet("SHA1", "SHA256", "SHA384", "SHA512", "MACTripleDES", "MD5", "RIPEMD160")]
$Algorithm="MD5"

Your output

I though it odd that you would want to see all the files that copied. It should be easy enough to only see the failures and assume everything else was fine. The part that I was having an issue with was the logic. If the folder contents you are comparing are not in the thousands then Compare-Object should work perfectly fine. So using that we can compare the hash of all files and spit out the ones that do not match.

The part I was having a real issue was that your code was dependent on the directories having the same amount of files. If either directory was missing or had an extra file then your logic would fail since you were comparing element positions and not the contents. This was another reason I opted for Compare-Object

If you do want to see the ones that matches as well I created a [switch] that would help you toggle that off and on again. You can think of it like a boolean. Compare-Object has a parameter for -IncludeEqual we could pass that the value of our switch.

[parameter(Mandatory=$false)]
[switch]$ShowMatches

.....

Compare-Object $referenceFolderHashes $differenceFolderHashes -Property Hash -PassThru -IncludeEqual:$ShowMatches.IsPresent

To continue about the output

So now we have the results of Compare-Object. The pertinent results are under the property SideIndicator which is ==,<= or => which show if an entry is present in only the reference object or difference object. Here I use a calculated property to make that information a little more end-user friendly.

Select-Object Path,@{Name="CopyStatus";Expression={If($_.SideIndicator -eq "=="){"OK"}else{"Check"}}}

Since we are also using the pipeline the way we are the output from this function to something like Export-CSV!

Here is my version of your function.

#Requires -version 4.0
Param(
    [parameter(Mandatory=$true,Position=1)]
    [ValidateScript({Test-Path -PathType Container $_ })]
    [alias("Source")]
    [string]$ReferenceFolder,
    [parameter(Mandatory=$true,Position=2)]
    [alias("Destination")]
    [ValidateScript({Test-Path -PathType Container $_ })]
    [string]$DifferenceFolder,
    [parameter(Mandatory=$false)]
    [ValidateSet("SHA1", "SHA256", "SHA384", "SHA512", "MACTripleDES", "MD5", "RIPEMD160")]
    $Algorithm="MD5",
    [parameter(Mandatory=$false)]
    [switch]$ShowMatches
)

$referenceFolderHashes = Get-ChildItem $ReferenceFolder -File -Recurse | Get-FileHash -Algorithm $Algorithm | Select Path,Hash
$differenceFolderHashes = Get-ChildItem $DifferenceFolder -File -Recurse | Get-FileHash -Algorithm $Algorithm | Select Path,Hash

Compare-Object $referenceFolderHashes $differenceFolderHashes -Property Hash -PassThru -IncludeEqual:$ShowMatches.IsPresent |
    Select-Object Path,@{Name="CopyStatus";Expression={If($_.SideIndicator -eq "=="){"OK"}else{"Check"}}}

Some sample output. I copied a small folder tree and changed a number in one file.

 .\Compare-FilesWithHash.ps1 -Source E:\Temp\csv -Destination 'E:\Temp\csv 2' -ShowCopied

Path                    CopyStatus
----                    ----------
E:\Temp\csv\export.csv  OK
E:\Temp\csv\file1.csv   OK
E:\Temp\csv\file2.csv   OK
E:\Temp\csv\sample1.csv OK
E:\Temp\csv\sample2.csv OK
E:\Temp\csv 2\file.csv  Check
E:\Temp\csv\file.csv    Check

Since the hashed do not match between file.csv then they both are flagged.

I thought about reducing the result set in that case so it only flagged the file once but I opted against it as it would add potentially unnecessary complexity.


Checking whether one string matches another

If your input strings are of length n, your current implementation has a cubic runtime complexity O(n³). This could become an issue for longer strings.

I recommend to split counting character frequencies and comparing those counts into two separate steps with nearly linear complexity O(n):

// Count characters in 'str':
function frequencies(str) {
  let result = {};
  for (let chr of str) {
    result[chr] = (result[chr] || 0) + 1;
  }
  return result;
}

// Check if 'str1' contains all characters of 'str2':
function scramble(str1, str2) {
  let frequencies1 = frequencies(str1);
  let frequencies2 = frequencies(str2);
  return Object.entries(frequencies2).every(([chr2, frequency2]) =>
    frequencies1[chr2] >= frequency2
  );
}

// Examples:
console.log(scramble("abc", "cba"));
console.log(scramble("aa", "aaaa"));
console.log(scramble("123", "234"));


Right, I'll be adding to this answer later on, but for a kick-off, here's a few quick remarks/considerations:

On the hidden input fields
As Martijn said in his comment: most bots will probably parse the DOM, and filter out those fields that are marked as required (looking for labels with a * text node in them), and they'll simply ignore hidden fields. You've created regular input fields that are not displayed. That might work on some bots, but like I said, they'll probably parse the DOM and see that they have a style attribute that sets the display to none.
It's not hard to deal with that, and if I were to write a bot, it wouldn't take me 5 minutes to add the code to deal with those input fields, too.

You can keep those hidden input fields as a means of security (they don't do any harm, after all), but don't set their style attributes in the markup, use CSS classes, or better still: use JavaScript to set class/attributes on the load event. That way, the DOM doesn't reflect what the page will actually look like as much as it does now.
This may help a little, but all in all, this will only protect you from script-kiddies and amateurish attacks.

The token stuff
That's fine. Session tokens that should be posted back are basic security steps that everybody should take. How you get those tokens is up to you, but an md5 of the timestamp? A hash doesn't make your token more secure. Don't go thinking that md5 does anything else than add overhead, however minor it may be.
Of course I get that a hash string just makes the token look more important, and in a way less random than it actually is, but why not hash some of the clients data in that case, like the remote address or referrer or whatever... though far from reliable, it can give you something extra to check, and log, and compare to the access logs of your server. It may also give you a clue as to what tools are being used when your page is targeted.

However, you should add checks along the lines of if (isset($_POST['yourlastname'])) and isset($_SESSION['token1']), to ensure that you can actually validate the form submission. But that's as an asside.

htmlspecialchars
Is it needed? NO. In fact, they're capable of doing more harm than good in some cases. Particularly when they're applied to the email address, as you seem to be doing. You're using filter_var($email, FILTER_VALIDATE_EMAIL), which is great, because that filter can handle the complex and wacky email addresses can contain htmlspecial chars, including: <. Here's what I'd do:

$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);//sanitize
if (filter_var($email, FILTER_VALIDATE_EMAIL))
    //continue

As far as the sanitation of the other data that'll make-up your email message is concerned: set the MIME type to text,because it would appear that that's all you need, and take measures against email injection.
A subject I've already discussed in my answer here

Code issues
Just a quick update of my answer. On second glance, I may have spotted an issue with your code that could sometimes result in your script treating a valid form submission as an invalid one:

$token1 = md5(microtime(true));
$_SESSION['token1'] = $token1;//set token, then:
?>
<!DOCTYPE html>
<html>
<!-- setting HTML... -->
<?php $token2 = md5(microtime(true)); ?>
<form method="post" name="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

<input name="token" type="hidden" value="<?php echo htmlspecialchars($token2); ?>">

The token value set in your form is a different variable than the one you've assigned to $_SESSION['token']! Why? The chances that the values of $token1 and $token2 are different are really quite high.
Why aren't you simply using $token1 in the form, too?

Next: htmlspecialchars? What's the point? $token1 and $token2 both are hash strings, which are all [a-z0-9] chars, to put it in regex terms. They don't need escaping, so this function call (which adds overhead) can, and should be dropped.

Also note that you don't have to specify the action attribute for the form, if the target is $_SERVER['PHP_SELF']. Leaving it blank triggers a form submissions default behaviour, which is to submit to self

<form method="post" name="form"> <!-- will do the trick -->

As an aside, also check my addition to the recommendations bit below on how you can make the mix-ins of your php in the markup, IMO at least, a bit more easy to read.

Recommendations
Given the fact you are looking into ways to ensure bots/spammers can't abuse your form, why not use a simple Captcha? It's proven technology, and rather effective anyway...

There are various scripts readily available, phpcaptcha is a free script you can download. It's easy, fairly well documented, actively maintained, there's a lot of plugins readily available for all major CMS/blog type of things and it's already been extensively tested.
I've just looked into the source of phpcaptcha now. I must say, there's a couple of things I don't much care for in there, but on the whole, it's not bad. I've even gone through the trouble of forking the repo, and I've started writing a little extra feature (which I'll call "mangler"). It'll transform words like transform into tr@nsf0rm, in such a way that both transform and tr@nsf0rm are accepted.
Though still work in progress, feel free to contribute ;-P

When echo-ing PHP variables inside HTML, you may find your code easier to read when using the short echo tag. This is not the same as the short open tag (<?) in that it does not require specific ini settings. In other words, it's always going to be available.
If nothing else, it at least requires less typing/code-chars

<input name="token" type="hidden" value="<?php echo htmlspecialchars($token2); ?>">
<!-- can be written as (I'm applying my critiques, too) -->
<input name="token" type="hidden" value="<?= $token1; ?>">

Not even the ; at the end of the line is required, but I prefer to have it there... it's a good habit.


Decoding binary coded decimal (BCD) value

it can be a lot simpler...

#include "seatest.h"

unsigned int BCDn( unsigned int n, const unsigned char * data )
{
    unsigned int uResult = 0;
    unsigned int i;

    for (i=0;i<n;i++)
    {
        uResult = (uResult * 100) + ((data[i] >> 4) * 10 ) + ( data[i] & 0x0F);
    }

    return uResult;
}
void test_max_bcd_convert()
{
    unsigned char bcd_data[]= { 0x97, 0x65 };

    assert_int_equal(9765, BCDn(2, bcd_data));

}

void test_fixture_bcd( void )
{
    test_fixture_start();
    run_test(test_max_bcd_convert);
    test_fixture_end();
}

void all_tests( void )
{
    test_fixture_bcd();
}

int main( int argc, char** argv )
{
    run_tests(all_tests);
    return 0;
}


I'm by far no expert, and I might be wrong on some of my statements, so take them as a basis for discussion. Anyway, I am trying to learn about code quality in C++ myself, so I'm giving it a shot.

printVector should take the argument as const-ref, because the vector is not supposed to be changed in the function call.
Consider using an iterator to loop through the vector in printVector. However, in a small-scale program like this I don't see this as a big issue. In larger programs, it might help you to make a function more general. And thanks to C++11's auto, it will be very readable -- even more so if you use a range-based for loop.
You're using the vector<int> guessed to store the chars from userGuess. Why not a vector<char> to store char? Would also make the type cast to (char) in printVector unnecessary.
Also you're mixing C-arrays and STL's std::vector, C-strings (char *) and std::string. Try to stick to the STL versions throughout. If you are using a C++11 capable compiler, you can even initialize the std::vector the same way as you're doing with the C-array now.
You are using curly braces {} in for loops and if/else statements only when absolutely required. Most style guides encourage using braces for every for/if/else block, or at most allow omitting them for one-line "blocks". The reason is readability (you can always expect to find a } where a longer block ends) and editability (It's easy to forget adding the braces when adding a line to the supposed for/if/else block).
It doesn't look like idiomatic C++ to compare a bool variable with == as in if(letterCorrect == false). You should use something like if (! letterCorrect) instead.
You should add a return 0; statement when the user is hanged. As far as I know it isn't required for the main function, but as you're already returning with return 0; when the user guesses the word, you should also do so at the end of the function.
The condition if (compWord == compHiddenWord) is wrong. You're looping over the array elements, but then you're comparing the pointer to the 0th element of the array to the std::string, instead of comparing the array elements. If you follow my suggestion above and change compHiddenWord to std::string, then you can omit the loop and simply write if(compWord == compHiddenWord) (Edit: As I learned, it also works correctly for comparisons of char* and std::string, so I deleted my example for by-character comparison)
You're using a as a loop index. While this isn't wrong, C++ programmers would typically use i or j for this purpose.
Edit: Your hangman array goes from 0 to 9 -- but in the while loop you never reach the 9 thanks to the hangManPos != 9 condition. Therefore, you will never print the completely hanged hangman.

Let me know what you think!


First, always use strict; use warnings; at the top of your code. The strict pragma restricts you to a sensible subset of Perl, which removes many sources for errors. Also, it forces you to declare all your variables with my. The warnings are very helpful, but non-fatal errors.

If you are on a fairly modern perl (10 or later), you can use the say function. This works exactly like print, but appends a newline at the end. Enable this feature with use feature 'say' or use 5.010.

If you have a set of mutually exclusive conditions in an if-cascade, you might want to look into the if/elsif/else structure.

Your while-loop is meant to execute up to six times. Instead of while, you might want to use a range, and a foreach loop:

for (1 .. 6) {
  # this stuff executes six times
}

Inside your loop, you only test if the user didn't hit the number. If his guessed number is equal to the secret num, then you continue with a new iteration. Don't.

Also, I would pack the whole algorithm into a subroutine. This is a good habit, and allows us to do an early exit:

sub guess_my_number {
  my %args = @_; # cast the subroutine arguments to a hash
  my $maxnum = $args{maxnum} || 100; # unpack named arguments,
  my $tries =  $args{tries}  ||   6; #   or give default value

  my $secret = int rand $maxnum;

  GUESS:  # a labeled loop
  for my $try (1 .. $tries) {
    say "Guess a number between 0 and $maxnum:";

    chomp( my $guess = <STDIN> );

    if ($guess == $secret) {
      say "Yay, that was right! $secret was my number.";
      say "You managed in $try tries.";
      return 1; # exit the subroutine
    } elsif ($guess < $secret) {
      say "Your guess was too low.";
    } elsif ($guess > $secret) {
      say "Your guess was too big."
    }
    # This is executed for both too low or too large numbers:
    say "You have ", $tries - $try, " tries left.";
  }

  # we land here if we didn't manage the guess
  say "You failed to guess the correct number $secret in $tries guesses.";
  return 0;
}

And then in the main code:

guess_my_number(maxnum => 50, tries => 5);

All arguments are optional.

The above might produce a session like

Guess a number between 0 and 50:
25
Your guess was too low.
You have 4 tries left.
Guess a number between 0 and 50:
37
Your guess was too low.
You have 3 tries left.
Guess a number between 0 and 50:
44
Your guess was too big.
You have 2 tries left.
Guess a number between 0 and 50:
40
Your guess was too low.
You have 1 tries left.
Guess a number between 0 and 50:
42
Yay, that was right! 42 was my number.
You managed in 5 tries.

What you could (or should) implement is input validation. Without strict and warnings, Perl will transform any string into a number, which will be zero for non-numeric strings. To assert that the input only contains ASCII digits, run a regex over it:

if (not $guess =~ /^[0-9]+$/) {
  say qq(Your guess "$guess" was not a number.); # special qq() quotes
  redo GUESS; # redo this iteration, without incrementing the counter
}

About your updated code:

Use whitespace. Whitespace is good and improves readability.
use warnings. use 5.016 should already be activating strict for you. More warnings = more bugs found early.
We don't call subs like &foo except when you know what you are doing. This style has a number of side effects that don't matter for your example, but can introduce bugs in complex applications. Always prefer foo().
Why on earth are you using our? The our is just like my, except that it declares globals. Don't use globals. Use lexicals with my. In either case, declare your variable once and use it throughout the remaining scope. I.e. declare the variable outside the loop.
If you look at all your execution paths, you test for duplicate conditions: $compNumber == $userNumber is tested two times. Look at my code again, which manages with one test. The real reason I used a sub is that I could return early, as soon as the correct number was guessed. This made my loop control easier.
You currently have this sequence of conditions inside the loop:

if    $compNumber == $userNumber
elsif $compNumber >  $userNumber
    if $_ == 5
        last
    else
elsif $compNumber <  $userNumber
    if $_ == 5
        last
    else

As soon as $compNumber != $userNumber, we can test for the last iteration. This structure is logically equivalent, but shorter:

if    $compNumber == $userNumber
elsif $_ == 5
    last
elsif $compNumber >  $userNumber
elsif $compNumber <  $userNumber

In my code, I simply drop of the last iteration of the loop, after telling the user if his guess was too small or too large, as usual.
You use the topic variable $_. This makes for short code, but also makes it hard to understand. Consider using a better name, like $try or $guess. The topic variable is the topic of the current code (you can often pronounce it this or it). Your topic is the guess the user made, not the number of the iteration.
The $n is always zero. You don't increment it. This is good, as it should be the same as your loop variable. As I print the congratulatory message inside the loop, I can use the loop variable, which will yield the correct value.
My subroutine argument unpacking code may seem a bit arcane if you are new to Perl, but using hardcoded constants is an anti-pattern in any language. (Also, named arguments make for really nice interfaces.)


Inserting 50k rows with Spring Data and JPA

To state the problem:
You have a large sum of operations that are repetitive and mostly similar(?) that are long running, and you want to reduce that run time.

If I have that right:

If order is not a concern You could consider inserting in parallel. If you can represent the 50,000 updates as a List, say, List<InsertCriteriaPojo>, and can represent the insert as a Consumer lambda, like so: ((InsertCriteriaPojo item) -> myDao.insert(item)), then this could be a one line call:

List<InsertCriteriaPojo> items = ...;

items.stream().parallel().map((InsertCriteriaPojo item) -> myDao.insert(item));

This creates a Stream of InsertCriteriaPojos, converts that to a ParallelStream, and them maps each item in the List to a Consumer and runs the Consumer/item tasks in a set of threads belonging to the common ForkJoinPool

While short, there are problems with this

The main problem as explained here is that you can't specify an Executor to ParallelStreams (as of Java 1.8*).

UPDATE: The above is inaccurate. This can be done like so:

List<InsertCriteriaPojo> items = ...;
ForkJoinPool customThreadPool = new ForkJoinPool(threadCount);
customThreadPool.submit(
    () -> items.stream().parallel().map(
        (InsertCriteriaPojo item) -> myDao.insert(item)
    )
).get;

Another, more complex way to run these tasks in parallel is to use an Executor you configure:

@Bean(name = "myExecutor")
public Executor executor(){
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(yourProperties.getCorePoolCount());
    executor.setMaxPoolSize(yourProperties.getMaxPoolCount());
    executor.setQueueCapacity(yourProperties.getMaxQueueSize());
    executor.setThreadNamePrefix(yourProperties.getThreadNamePrefix());
    executor.initialize();
    return threadPoolTaskExecutor;
}

To run your consumers asynchronously:

...
@Autowire
@Qualifier("myExecutor")
Executor executor;
...
List<InsertCriteriaPojo> items = ...
//Make a Future for each task
List<CompletableFuture<Void>> asyncTaskFutures = list.stream().map(
    (InsertCriteriaPojo item) ->{
        CompletableFuture.runAsync(
            () -> myDao.insert(item), executor
        ).handle(
            (asyncVoidFuture, possibleError)->{
                if(possibleError != null){ //Handle your errors here }
                else{return asyncVoidFuture;}
        })
    }
).collect(Collectors.toList());

//Create a Future that is complete when allOf your task futures are complete
CompletableFuture<Void> process = CompletableFuture.allOf(
    asyncTaskList.toArray(new CompletableFuture[asyncTaskList.size()])
).thenRun(() -> asyncTaskList.stream().map(future -> future.join()));

//Complete the process-level future, blocks until complete
process.get();

While significantly more complex, the second is a more configurable and reusable way to solve your problem, but depending on your case either approach could serve your goal.


Combine division and modulus

Use https://docs.python.org/3/library/functions.html#divmod

rather than this:

    digits.append(int(n % b))
    n //= b

Replace loop with sum

This

res = 0
for index, i in enumerate(reversed(n)):
    res += int(i) * b ** index
return res

is a good candidate for conversion to a generator, i.e.

return sum(int(i) * b**index for index, i in enumerate(reversed(n)))

However, you can get rid of that reversed if you change the power index to be len(n) - index.

Imports at the top

Move this:

from math import log2, ceil, log10, floor

to the top of your file.

Don't compare types

Rather than this:

if type(num) == list:

use isinstance.

Member mutability

You shouldn't care that num is coming in as a list; you should only check that it's iterable. And store it as a tuple, not a list, because you don't (and shouldn't) mutate it in your class code.

Call reversed once

This:

zip(reversed(self.digits), reversed(o.digits))

should be

reversed(tuple(zip(self.digits, o.digits)))

The inner tuple is required because reversed does not accept an iterator.

Don't use strings for math

Just don't. This:

a.digits, b.digits = ['0']

is not a good idea. Use actual digits whenever possible, and it is possible here.


I am afraid you're approach is too complicated. Just create a function that finds the first occurrence of an element using a binary search, an another function that finds the last one. And then you can write:

def find_indexes(xs, x)
  start = find_first_index(xs, x)
  return ((start, find_last_index(xs, x, start=start)) if start else None)

For a simple implementation of find_first_index and find_last_index, check bisect.bisect_left and bisect.bisect_right source code here.


Below is how I would clean this up, or maybe partially re-write [live example]:

// helpers
template <typename T>
struct id { using type = T; };

template <typename T>
using type_of = typename T::type;

template <size_t... N>
struct sizes : id <sizes <N...> > { };

// choose N-th element in list <T...>
template <size_t N, typename... T>
struct Choose;

template <size_t N, typename H, typename... T>
struct Choose <N, H, T...> : Choose <N-1, T...> { };

template <typename H, typename... T>
struct Choose <0, H, T...> : id <H> { };

template <size_t N, typename... T>
using choose = type_of <Choose <N, T...> >;

// given L>=0, generate sequence <0, ..., L-1>
template <size_t L, size_t I = 0, typename S = sizes <> >
struct Range;

template <size_t L, size_t I, size_t... N>
struct Range <L, I, sizes <N...> > : Range <L, I+1, sizes <N..., I> > { };

template <size_t L, size_t... N>
struct Range <L, L, sizes <N...> > : sizes <N...> { };

template <size_t L>
using range = type_of <Range <L> >;

// single tuple element
template <size_t N, typename T>
class TupleElem
{
    T elem;
public:
    T&       get()       { return elem; }
    const T& get() const { return elem; }
};

// tuple implementation
template <typename N, typename... T>
class TupleImpl;

template <size_t... N, typename... T>
class TupleImpl <sizes <N...>, T...> : TupleElem <N, T>...
{
    template <size_t M> using pick = choose <M, T...>;
    template <size_t M> using elem = TupleElem <M, pick <M> >;

public:
    template <size_t M>
    pick <M>& get() { return elem <M>::get(); }

    template <size_t M>
    const pick <M>& get() const { return elem <M>::get(); }
};

template <typename... T>
struct Tuple : TupleImpl <range <sizeof...(T)>, T...>
{
    static constexpr std::size_t size() { return sizeof...(T); }
};

Comments:

With a bit more infrastructure (helper structs that are typically reused here and there) at the beginning, the main tuple implementation becomes just 20 lines.
Instead of a recursive implementation, I have switched to multiple (variadic) inheritance of single tuple elements TupleElem, each with its own id N (so that each element is of unique type) and its own function get(). Hence Tuple's function get() just redirects to the appropriate base class.
Now a specialization of TupleElem for empty types can bring easily the desired empty base optimization without affecting the main tuple implementation.
No specialization is needed for empty tuple. This definition includes empty tuple as a special case.
No static assertions needed, an out-of-range index will give an error anyway (but you can add for better messages of course).

Now, there are so many things missing. I would start from support for rvalue references and, of course, constructors. If you want to get an idea, you can have a look at my own tuple implementation (of which this one here is a miniature) including tuple views, expression templates for lazy evaluation, loops, algorithms, integration with all C++ operators, and much more.

Template metaprogramming does not have to look terrible!


Format
Use proper indentation, after a curly brace use a tab or 4 spaces.
Readability
Add a message with your exceptions. It's a terrible practice to just throw a regular exception and no message. You'd have to look at the line numbers in the stack trace in order to know where the exception message came from. It's better to have a user-friendly message describing the issue that occurred.
Do not mix ! with > or <. It's confusing to read.
Try to use negative or positive validation. For example, be consistent either checking if the inputs are wrong, or always check that their right. In other words have your error messages all at the top or bottom.
OutputResponse Is not a good name. It's meaningless. Assuming this is a class you made, consider changing the name. Also consider using an ArrayList rather than separate fields, that way you don't need to refactor to include a 4+ separations.
Example code:
public OutputResponse splitAmount(BigDecimal totalAmount, int divideInto) {
    if ((1 > divideInto || 3 < divideInto)) {
        throw new Exception("Divide into must be between 1-3");
    }

    if (totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO <= 0) {
        throw new Exception("Total amount must be a number greater than 0!");
    }

    BigDecimal recurringAmounts = null;
    BigDecimal firstAmount = totalAmount;
    if (divideInto > 1) {
        recurringAmounts = totalAmount.divide(BigDecimal.valueOf(divideInto), 2, RoundingMode.FLOOR);
        firstAmount = totalAmount.subtract(recurringAmounts.multiply(new BigDecimal(divideInto - 1)));
    }

    OutputResponse outputResponse = OutputResponse.builder()
            .firstAmt(firstAmount)
            .secondPmtAmt(recurringAmounts)
            .build();

    if (divideInto > 2) {
        outputResponse.setThirdPmtAmt(recurringAmounts);
    }
}


Limit acceptable values for function parameter in VBA

I see several issues with this.

First is the naming. Row and Column both hide global Excel variable (although whether this is good or bad is debatable...). This otherwise valid code becomes a compile error "Expected Array" everywhere in the project that contains the enumeration.

Public Sub Test()
    Debug.Print Row(1).Address
End Sub

I would personally change the Enum name to something like LimitDimension (Pascal case for namespace identifiers) and the two options to LimitRow and LimitColumn. This will be much less likely to create collisions. Note that r and c are also really common local loop counter variables.  If they're public enumeration member, they pollute the global namespace and can create bizarre\misleading compile errors:

Option Explicit

Public Sub Test1()
    Dim c As Long
    Debug.Print c   'This works just fine, prints 0.
End Sub

Public Sub Test2()
    Debug.Print c
    Dim c As Long   'Compile error.  Duplicate declaration in same scope.
End Sub

Public Sub Test3()
    For c = 1 To 5  'Compile error.  Variable required - can't assign to this expression.
        Debug.Print c
    Next
End Sub

Public Sub Test4()
    Dim c As Long
    For c = 1 To 5  'Works fine.
        Debug.Print c
    Next
End Sub

Second, enumerations should only have one member for each distinct value. The only real point to using them in VBA is to make your code more readable (there's no strict type enforcement), and it isn't immediately clear when you see something like this...

Select Case foo
    Case rowOrColumnOption.r
        'Do something.
    Case rowOrColumnOption.Row
        'Do something else.
End Select

...that it's a coding error.  This is immediately obvious:

Select Case foo
    Case rowOrColumnOption.Row
        'Do something.
    Case rowOrColumnOption.Row
        'Do something else.
End Select

Third (on a related note), you should use the Enum explicitly when you're checking for it's members.  This...

If rowOrColumn = 0 Then
    '...
ElseIf rowOrColumn = 1 Then
    '...
Else
    '...
End If

...is much clearer as:

If rowOrColumn = rowOrColumnOption.Row Then
    '...
ElseIf rowOrColumn = rowOrColumnOption.Column Then
    '...
Else
    '...
End If

Not only is the much clearer as to the intent of the code, it also prevents it from breaking if you decide to or need to change the values of the members. It also makes the code document itself, so you don't have to sprinkle comments like this around:

'  0 corresponds to "Row" in the custom variable type "rowOrColumnOption".

Fourth, IMHO the statement delimiter : is if not pure evil, mostly evil. It's much more natural to read code with the statements arranged vertically than it is if statements are arranged horizontally.  This is much easier to process at a glance:

Public Enum rowOrColumnOption
    r = 0
    Row = 0
    c = 1
    Column = 1
End Enum

While the intent may have been to group aliased members, you can make this explicit by just assigning aliases within the declaration itself:

Public Enum rowOrColumnOption
    Row = 0
    r = Row
    Column = 1
    c = Column
End Enum

Finally, just as an aside - I have no idea what ...some code... is doing in GetHighestRowOrCol, but from the If block it appears that ...some code... is calculating both maxRow and maxCol when it only ever returns one of them.  I'm guessing this would be a more efficient structure:

If rowOrColumn = rowOrColumnOption.Row Then
    '...some code to determine the highest row number.
    GetHighestRowOrCol = maxRow
ElseIf rowOrColumn = rowOrColumnOption.Column Then
    '...some code to determine the highest column number.
    GetHighestRowOrCol = maxCol
Else
    GetHighestRowOrCol = 0
End If


Code review
You should use better variable names then a, x and y. But otherwise since your code works your code is fine.
Performance
It seems a couple of users are confused why Python has strange performance.
Enumerate vs index
This is pretty simple both enumerate and index have the same time and space complexity.
If we have a list of False and set one to True and want to find the index of that, both will run in \$O(n)\$ time. It may seem like enumerate is \$O(1)\$ however it is the same as zip(range(len(sequence)), sequence) and we know range is \$O(n)\$.
The difference in speed that we can see is because index is just faster than enumerate.
Your insertion sort vs Grajdeanu Alex's
This comes down to Python being slower than C. If we look at the core of Grajdeanu's solution:

currentvalue = lst[index]
position = index

while position > 0 and lst[position - 1] > currentvalue:
    lst[position] = lst[position - 1]
    position = position - 1

lst[position] = currentvalue

This is doing two things:

Finding the index to stop iterating to:

while position > 0 and lst[position - 1] > currentvalue:

Performing an optimized version of insert and pop. This is as they only touch a subset of the array, but insert and pop touch the entire array, worst case. (Python lists are arrays in the backend.)

If you were to translate Grajdeanu Alex's solution into C the code would out perform your insert and pop.
Bisecting
There's a nice property about insertion sort, as you're iterating through the data everything before your index is sorted. This means we can use a better algorithm to find where to insert into.
We can use the strategy you use in the Guess a Number Between 1-100. By halving the amount of the list we have to search each check we can find where to insert into in \$O(\log(n))\$ time. This is faster than than the \$O(n)\$ that your enumerate and Grajdeanu's algorithms are running in.
There is a library for this, bisect, and most of the legwork is in C too, so it's nice and fast.
My timings
My code to get the timings:

import time
import math
import random
import copy
import bisect

import matplotlib.pyplot as plt
import numpy as np

from graphtimer import flat, Plotter, TimerNamespace

class Iteration(TimerNamespace):
    def test_baseline(data):
        pass

    def test_iterate(data):
        for value in data:
            pass

    def test_enumerate_list(data):
        for item in list(enumerate(data)):
            pass

    def test_enumerate_partial(data):
        for item in enumerate(data):
            pass

    def test_enumerate(data):
        for i, value in enumerate(data):
            pass

class Insertion(TimerNamespace):
    def test_baseline(data, i, value_i, j, value_j):
        pass

    def test_plain(data, i, value_i, j, value_j):
        data.insert(j, data.pop(i))

    def test_index(data, i, value_i, j, value_j):
        data.insert(data.index(value_j), data.pop(i))

    def test_python(data, i, value_i, j, value_j):
        while i < j:
            data[j] = data[j - 1]
            j -= 1
        data[j] = value_i

class Joined(TimerNamespace):
    def test_enumerate_plain(data, i, value_i, j, value_j):
        for j, value_j in enumerate(data):
            if value_i <= value_j:
                data.insert(j, data.pop(i))

    def test_enumerate_index(data, i, value_i, j, value_j):
        for j, value_j in enumerate(data):
            if value_i <= value_j:
                data.insert(data.index(value_j), data.pop(i))

    def test_iterate_index(data, i, value_i, j, value_j):
        for value_j in data:
            if value_i <= value_j:
                data.insert(data.index(value_j), data.pop(i))
                break

class Sorts(TimerNamespace):
    def test_manuel_base(a):
        for i, x in enumerate(a):
            for j, y in enumerate(a):
                if y >= x:
                    a.insert(j, a.pop(i))
                    break

    def test_manuel_insert(a):
        for i, x in enumerate(a):
            for y in a:
                if y >= x:
                    a.insert(a.index(y), a.pop(i))
                    break

    def test_other(lst):
        for index in range(1, len(lst)):
            currentvalue = lst[index]
            position = index
            while position > 0 and lst[position - 1] > currentvalue:
                lst[position] = lst[position - 1]
                position = position - 1
            lst[position] = currentvalue

    def test_peilon(lst):
        output = []
        for item in lst:
            bisect.insort(output, item)

memoize = {}

def create_args(size, *, _i):
    size = int(size)
    key = size, _i
    if key in memoize:
        return copy.deepcopy(memoize[key])
    array = random_array(size)
    j = random.randrange(0, size)
    array[:j] = sorted(array[:j])
    i = 0
    while array[i] < array[j]:
        i += 1
    output = array, i, array[i], j, array[j]
    memoize[key] = output
    return output

def random_array(size):
    array = list(range(int(size)))
    random.shuffle(array)
    return array

def main():
    fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, subplot_kw=dict(xscale='log', yscale='log'))
    axis = [
        (Iteration, {'args_conv': lambda i: [None]*int(i)}),
        (Insertion, {'args_conv': create_args, 'stmt': 'fn(args[0].copy(), *args[1:])'}),
        (Joined, {'args_conv': create_args, 'stmt': 'fn(args[0].copy(), *args[1:])'}),
        (Sorts, {'args_conv': random_array, 'stmt': 'fn(args[0].copy(), *args[1:])'}),
    ]
    for graph, (plot, kwargs) in zip(iter(flat(axs)), axis):
        (
            Plotter(plot)
                .repeat(10, 2, np.logspace(1, 4), **kwargs)
                .min()
                .plot(graph, title=plot.__name__)
        )
    plt.show()

if __name__ == '__main__':
    main()

(click to expand)

Iteration

test_baseline
The timings are flat as they are the time it takes to run the test suit. When determining the performance of each function we need to see how far away from the baseline it is.

test_enumerate & test_enumerate_partial
These are roughly the same and so we know that enumerate, and not tuple unpacking, is the factor at play that is taking up a lot of performance.

test_enumerate, test_enumerate_list & test_iterate
We can see adding more \$O(n)\$ operations makes the code slower. However enumerate is a pretty slow function.

In all enumerate is slow.
Insertion

test_baseline
Since we are copying the data in the test suit we see that at times the other functions are running the fastest that they can.
This is to be expected as we are running tests on a partially sorted array. Ranging from no sort to fully sorted.

test_plain
We can see that data.insert(j, data.pop(i)) is really fast and is consistently around test_baseline. This means if enumerate was faster than data.index then the other answer would not be true.

test_index & test_python
From the areas we can see that optimized Python runs significantly slower than Python's C methods.
This is to be expected, Python is slow.

Joined
These merge the above two together to show the impact of the difference in timings.
These are a single insertion of a full insertion sort.
Unsurprisingly given the previous timings test_enumerate_plain is by far the slowest.
Sorts
This shows that whilst your changes are fast, my answer from '17 is a pretty darn fast insertion sort.
Complexity vs Performance
It should be apparent that in Python these are two entirely different metrics. Complexity is more important when playing on a level playing field, which isn't the case in Python.
But just because Python isn't a level playing field doesn't make it useless. When programming if you try to get the best performance complexity wise then you'll have a good baseline to then optimize from. From here you can then focus on performance which is harder to reason with and harder to compare. And worst case converting the code into C will be far easier.


Generating primes with Sieve of Eratosthenes

I take it you are really hell bent to use STL for everything but maybe you are over using it. However your code as it is, is very redundant. The specific issue I found are:

Whenever you call isPrime(), you are generating the primes array inside generatePrimesBelow() from scratch. Its not a problem now, but if you call isPrime() from main inside a loop for a couple of numbers, it will be very inefficient.
Since you are using only one vector<int> for storing both the primes and the sieve, you are using find_if(), remove_if() and erase() which would not be needed if you use 2 vectors for storing the primes and the sieve separately, and hence make the code more efficient.
In isPrime(), you can simply use the find() function from STL to look whether your number is in primes or not. You don't need to write your own look-up code. Better yet, since the primes is sorted, you can directly use binary_search() STL algorithm on it. But all of this is moot as should search for a number to be prime or not if you have already found whether it is prime or not using generatePrimesBelow().

As per my understanding you can do everything in your isPrime() function itself, including what you are doing in generatePrimesBelow() in lesser lines of code that what your current isPrime() looks like. Here is what you can do:

Have two vectors<int>, primes and eratosthSieve with eratosthSieve's size being the number - 1 where number was passed in as argument.
Use STL generate algorithm to populate eratosthSieve from 2 to number, by having a function passed in as the generating function. It would like like this:

int fillUp() {
    static int i = 1;
    return ++i;
}

and will be used as generate( eratosthSieve.begin(), eratosthSieve.end(), fillUp)
Your sieve logic would become something like this with the two vectors:

vector<int>::iterator currentStart = eratosthSieve.begin();
vector<int>::iterator currentNumber;
do
{
    int numberAtStart = *currentStart;
    if ( numberAtStart != 0 )                 // If the number is 0, it means has been filtered out in the sieve.
    {
        primes.push_back( numberAtStart);
        currentNumber = currentStart + numberAtStart;
        do
        {
            *currentNumber = 0;
            advance(currentNumber, numberAtStart);
        } while (currentNumber < eratosthSieve.end());
    }
    currentStart = find_if(currentStart + 1, eratosthSieve.end(), isNextStart);
} while (currentNumber < eratosthSieve.end());

Check if the last element of the primes vector is equal to number or not:
    return ( number == primes.back() );


I'm going to give you a review of this as to how I'd improve this, and though it pulls some data from the other answer a little bit, it uses a bit different syntax.  Namely, I don't like using in-built f"" for formatting strings with replacements, so I use the full "".format() syntax.

Some of the changes are suggested in order to allow easy expansion of this 'API wrapper', so that you can build out new functions more easily.  Sorry about that, but I'm one of those coders who has written entire API wrappers and therefore I think in terms of "How could I expand the API" and such.

Also, my apologies for a wall-of-text, but I am overly descriptive sometimes.  I also give you the fully revised code at the bottom of this post, if you don't want to read the wall of text, however I suggest that you at least read the section headers in bold, and then the code.

Variables should be snake_case, or CAPS_CASE for 'constants' if you wish.

All variables should be in snake_case.  This technically includes the 'global' variables that are essentially constants, though I use CAPS_CASE as they are global constants that won't change (and this is technically acceptable in the PEP8 style guides).

So, all of your variables inside the functions, where applicable, are converted to snake_case, and the URL and API key variables became CAPS_CASE like so:

QUERY_URL = "https://www.alphavantage.co/query?function={REQUEST_TYPE}&apikey={KEY}&symbol={SYMBOL}"
API_KEY = "AN ACTUAL KEY"

Condense URL formatting into a single URL generation method

Your method of generating a URL is clunky.  We can glean the following information from your URL structure, though:

You need to provide the type of request, which is a specific type of data from their API.
You need to provide the symbol being looked at.
You need to provide an API key.

Since all three parts are necessary, we can use a structured string to create the URL.  We also, already, know the base URL, so we don't need to declare another variable for it.  We end up with this string for the QUERY_URL variable (again, I made this one all-caps to be a "global" or a "constant" - this is acceptable, and though it's not snake-case, it's actually acceptable):

QUERY_URL = "https://www.alphavantage.co/query?function={REQUEST_TYPE}&apikey={KEY}&symbol={SYMBOL}"

Similarly, we also have API key as API_KEY:

API_KEY = "AN ACTUAL KEY"

We'll be using this in the next session, so let's focus on that.

Make a generic 'request' function that will accept arguments and issue the request

Rather than structuring the URL and creating individual requests for each type of function you want (which will require code duplication and increase the difficulty of maintaining things down the line), we can take the entire request URL generation and the actual task of making a request and split it off into a separate function.

However, we have to be careful as to how we return the web request. The way your existing code works returns an HTTPRequest object, and not the results of the request. To get the data, you need to read() the data. The data returned from the request is in the form of bytes, and currently the json library is looking for a file pointer (for load) or a string (for loads, which is what you'll want to use). So, we've not only got to do a read() call to the request object, we also have to decode the bytes response into a string with .decode('UTF-8'), as the bytes returned from the API are UTF-8 encoded.

For reasons, I use internal functions that shouldn't be referenced from outside the Python script/library itself which start with a _, to imply that it's a protected member.  While there is no mechanism to actually do protected members, most code analysis tools will assume things with underscores are protected elements.

With all this in mind, you get this for your actual web request function, which returns the data, and gets rid of having to take the API key as an argument too:

def _request(symbol, req_type):
    with urllib.request.urlopen(QUERY_URL.format(REQUEST_TYPE=req_type, KEY=API_KEY, SYMBOL=symbol)) as req:
        data = req.read().decode("UTF-8")
    return data

The reasons for doing this become more prevalent in the next section of this review, though.

Change your dailyData function to snake_case, but take advantage of the new _request function

Now that we have the dedicated _request function, we can get rid of all of your URL construction code that you had in dailyData.  We can also reduce this function, now to be named get_daily_data, to only require you to pass in the symbol and lets URL construction take place in the actual request handling function we made.  This saves us from having to construct brand new URLs within each and every 'getter' that would get data from the API.

All this said and done, you end up with this for your get_daily_data function, which looks a bit cleaner than the original version, in my opinion:

def get_daily_data(symbol):
    return json.loads(_request(symbol, 'TIME_SERIES_DAILY'))

Now, the only thing you really need to do is make sure you're passing the proper request/function string to the _request library, and also pass the symbol.

This has an added bonus, though: because we're using _request to do the URL construction and the actual web request processing, we can easily expand this code for other functions in your API wrapper - all you need to change is the 'function' call to get different data.

Unused Libraries

You import datetime but you don't use it for anything.  So, don't include it in the import statements until you actually use it for something.

Now on to testing.  I use a slightly different form of your test code here, compressing everything into a one-liner call:

print(get_daily_data("AAPL")["Time Series (Daily)"]["2018-03-02"])

This in turn returns this data:

{'1. open': '172.8000', '2. high': '176.3000', '3. low': '172.4500', '4. close': '176.2100', '5. volume': '38453950'}

The code after all my revisions above, and after removing comments, ends up being this:

import json
import urllib.request

QUERY_URL = "https://www.alphavantage.co/query?function={REQUEST_TYPE}&apikey={KEY}&symbol={SYMBOL}"
API_KEY = "AN ACTUAL KEY"

def _request(symbol, req_type):
    with urllib.request.urlopen(QUERY_URL.format(REQUEST_TYPE=req_type, KEY=API_KEY, SYMBOL=symbol)) as req:
        data = req.read().decode("UTF-8")
    return data

def get_daily_data(symbol):
    return json.loads(_request(symbol, 'TIME_SERIES_DAILY'))

This being said, this program could be developed to take the stock ticker to check as a runtime argument, thereby permitting you to run the core code against any symbol that you define, but that's outside the scope of this review, technically.


CodeIgniter method to get requests for superiors to approve

I am able to remove one for loop in my code with the following:

I changed my method in the Controller

public function process()
{
    $data = new stdClass;
    $data->param_menu = 'request';

    $staffInfo = $this->staffinfo_model->selectItem(array('member_idx'=>$this->session->userdata('member_index')));

    $requests = $this->staffrequisition_model->getRequestsToProcess($staffInfo->position_depth,$staffInfo->department_group);

    foreach ($requests as &$item) {
        for ($y = 1; $y <=5 ; $y++) {
            if ($item->{'line'.$y.'_action'}!=='PENDING' && $item->{'line'.$y.'_action'}!==''){
                $item->is_checked = TRUE;
                break;
            } else {
                $item->is_checked = FALSE;
            }
        }
    }

    $data->param_requests = $requests;

    $this->load->view('dashboard/staff/process_view', $data);
}

I changed my method in the Model

public function getRequestsToProcess($depth,$departmentGroup)
{
    $this->db->select('*, ns_request_info.idx as request_idx, ns_staff_info.idx as staff_idx');
    $this->db->from('ns_request_info');
    $this->db->join('ns_staff_info', 'ns_request_info.requested_by_idx = ns_staff_info.member_idx');
    $this->db->where("((ns_request_info.line1=".$depth." AND ns_request_info.line1_action='PENDING') OR (ns_request_info.line2=".$depth." AND ns_request_info.line2_action='PENDING') OR (ns_request_info.line3=".$depth." AND ns_request_info.line3_action='PENDING') OR (ns_request_info.line4=".$depth." AND ns_request_info.line4_action='PENDING') OR (ns_request_info.line5=".$depth." AND ns_request_info.line5_action='PENDING'))");
    $this->db->where("(ns_request_info.status='PENDING' OR ns_request_info.status='ONGOING')");
    if($departmentGroup!='HIGHER TIER'){ $this->db->where('ns_staff_info.department_group', $departmentGroup); }
    $this->db->order_by('ns_request_info.idx', 'desc');
    $query = $this->db->get();
    return $query->result();
}

Now I dont have to loop my query five times. Instead I get it with just one query and loop through the result.


I tested with a couple of input values and for the most part, it seem
fine.  Note however, that the standard sort also works with
e.g. [1 nil] (with output [nil 1]) whereas this code breaks with an
exception during the comparison.

Code looks fine with a few minor issues:

The name should be merge-sort; rsort is not meaningful.
The values (first slh) and (first srh) are written down twice; the
compiler might optimise that away, but IMO it would be nicer to have a
separate let for them.
Emacs' clojure-mode indents the :else branch differently, dunno
about that.

Some suggestions:

Support the same signature as the standard sort.
Add a docstring explaining the function.
Add tests, possibly with randomised input as well.


Transforming data from an array of objects to a nested array of objects

The general idea of your attempt is not so bad.

Its main default is to be not generic enough so you repeat some code. This can be simply avoided using this (already antique) rule: never prepare a container before you know you need it.
So here, instead of immediately creating a first date item, wait for the time you see that it's required.

A fortunate side effect is that it responds to another lack in your code: if original contains a sequence of unsorted events, it will fail. With the new method, all events will be regularly processed.
(look at this fiddle, where I intentionally interweaved dates)

Modified code looks like this:

var original = [
  {
    datetime: '2015-07-22 09:00:00'
  },
  {
    datetime: '2015-07-22 11:00:00'
  },
  {
    datetime: '2015-07-23 10:00:00'
  }
];
var result = [], // (don't like "var new", which is a reserved word!)
    index = [];

for (var i in original) {
  var date = original[i].datetime,
      day = date.substr(0,10),
      j = index.indexOf(day);
  if (j == -1) {
    // first instance for the current day, create it
    result.push({
      date: day,
      event: [],
    });
    // register its index
    index.push(day);
    // get this new index value
    j = index.length - 1;
  }
  // in any case, populate the right day with the current event
  result[j].event.push(date);
}


Finding the occurrences of all words in movie scripts

A few things I can think of are:

parse_text can be marked as a private method. def _parse_text(self):. I understand this won't actually be hidden, but its a convention followed in python to treat methods starting with an underscore as private.
In MovieScript __init__ method maybe have the url as a kwarg (defaulting to http://www.springfieldspringfield.co.uk, but can be overwritten and point to another site in case you ever have to scrape another site)
In def get_text: You can cache the result from the request.get you're running and check the cache before making the request
Finally consider moving the logic of calculating the top keywords inside the MovieScript class itself (call it something like def get_common_words(self, count=20):) and allow the count to change in case you ever want more than the default.

I'm sure there are more and people will have there own preferences, but this is just what I could suggest in a quick glimpse :)


Toggle between two options in an object?

You currently only print the currently selected mode to the console, but you probably will use this mode for other purposes, such as the business logic of your application. To that end, I suggest splitting the toggling logic from the presentation and use booleans to store the value which you can easily use for branching depending on the currently selected mode.

// Logic: Define the two modes and toggling logic
const MODES = { ON: true, OFF: false }
const toggleMode = currentMode => !currentMode;

// Presentation: Display a selected mode
const displayMode = currentMode => currentMode ? 'ON' : 'OFF';

// Demo
const firstState = MODES.ON
console.log(displayMode(firstState));
const secondState = toggleMode(firstState);
console.log(displayMode(secondState));
const thirdState = toggleMode(secondState);
console.log(displayMode(thirdState));


Fetching settings for batches of wafers using loops

Your program reminds me of a Java applet that I wrote during my first summer internship.  I spent a significant chunk of that summer writing code to query several database tables and match values from one table with values from another table.  The performance sucked, but it was tolerable.  Then the applet was deployed to an overseas office — and it took minutes to display one screen.

The lesson is, any time you execute queries in a loop, and the number of those queries depends on how much data you have, you're going to have a bad time.  The overhead of issuing a query and retrieving the results is significant.  What you should do instead is issue one query (or a small fixed number of queries) that gets all of the information you want.

I later learned that all of those troubles could have been avoided by writing a proper SQL query in the first place, namely a join query.

Here, it looks like you are interested in constructing lstoflst, which contains the runsettings used for run 1 of each wafer that was in a batch that went through equipment DUV001.  The program should look more or less like this:

cnx = …
cursor = cnx.cursor()
cursor.execute("""
    SELECT batchdata.wafer
         , runsettings.settingname
         , runsettings.float8value
        FROM runsettings
            INNER JOIN batchdata
                ON batchdata.equipment = runsettings.equipment
                AND batchdata.wafer = runsettings.wafer
        WHERE
            runsettings.equipment = 'DUV001' AND
            runsettings.runnumber = 1
        ORDER BY batchdata.wafer;
""")
wafer_groups = itertools.groupby(cursor.fetchall(), key=operator.itemgetter(0))
lstoflst = [dict(row[1:] for row in group[1]) for group in wafer_groups]


First of all: nice work! It's easy to read and understand.

Program organization

It's very good that you split the task to small functions.
Reading the body of main reveals nicely the overall flow.

Ideas for further improvement:

place does two things: it reads input from user and updates the state of the board. It would be good to separate these logically distinct steps to different functions. A new function, say read_next_move could return boolean just like place, and take parameters board and pointers to x and y, whose values will be used when updating the board state.
The name check is too generic. How about is_game_over or has_player_won.
Printing the winner would be good to move to a dedicated function, as you did with other steps.

Use more constants

The special symbols -, x and o would be good to define as constants.
So that instead of if (board[pos] == 'x' || board[pos] == 'o'),
you could write more descriptively if (board[pos] == PLAYER_X || board[pos] == PLAYER_O), and if ever needed change the values easily.
By the way, in this particular example I would replace the condition with if (board[pos] != AVAILABLE).


defualt_title and defualt_options are misspelled.
Those empty else{;} statements are unnecessary.  If there is eventually a need for actual else statements, then they can be added later.
With those "stray" data members, this should really be a class so that they can be private.  Data members should not be directly exposed to the interface.  Any functions that shouldn't be called by the user should also be private, otherwise they should be public.


This looks pretty nice, I only have a few nit-picks, really.

What you call "rows" are actually "columns". It's a bit misleading.
The rows are actually the var arr that you're making.

The ternary is a bit confusing.
If clarity is important to you (as you mentioned),
then I think a good old-fashioned if-else would be better.

Lastly, the idx function parameters in the inner map calls are unused, so you could just as well drop them.


Abstractions
When working with collections, there are three layers of functions - each essentially justifying a module:
  h(url[], url[]) -> url[]
  g(url, url[])   -> url[]
  f(url1, url2)   -> url

The dependencies are h <- g <- f. The functions at f are more reusable than those at g are more reusable than those at the highest level h.
Complected.
I'll reflect my bias:  If a function is so complex it is hard to name, it might need to be refactored.
The place to start is with a function [let's call it g] that takes one item from redirects and modifies existingRedirects atomically. Then the existing function ensureRedirects can focus on operations at the level of the collection.
Conceptual mangling of the three levels - processing a collection of possible changes versus processing one possible change versus comparing two items - is clear from the description of the ensureRedirects's behavior in the question. A lot of it is at the level of processing a single URL against a collection of URL's even though ensureRedirects operates on collections. Some of it is about dealing with two URL's.
The naming should flow from smaller pieces to larger pieces. Or h could just be redirects.foreach(g)


When writing a simple function to return something if something is true or return something else, you should probably only have one return statement in the function.

increasing the amount of returns in a function makes the function less readable and more prone to mistakes.  if you only need one return statement, then only use one return statement.

Personally I would write this

public getBlanco(){
  if(this.array.length){
    return this.array[1][0];
  }
  return null;
}

like this instead

public getBlanco(){
    return this.array.length ? this.array[1][0] : null;
}

using a ternary is really the cleaner way to do this because you are really saying

if there are items in the array
    return item [1][0]
else
    return null


Base class for subclasses that can track their own instances

Generally, that all looks pretty good - Pythonic and well laid out. A few possible improvements below.

Per PEP-0008, multiple imports from the same module can be done on one line, and I would recommend alphabetical order:

from __future__ import absolute_import, division, print_function, unicode_literals

If you have a line length problem doing so, use parentheses:

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

Although it doesn't work with from __future__ ..., note that if you only want something imported in a particular version, you can do something like:

from sys import version_info

if version_info.major < 3:
    ...

This line:

return tuple(
  [instance() for instance in cls._classnames[cls.__name__]])

Could be simplified to:

return tuple(
  instance() for instance in cls._classnames[cls.__name__])

You don't need to build the list, you can pass the generator expression straight to tuple().

I would check whether you have too many instances as the first thing in __new__; why do work you don't need to?

def __new__(cls):
    """Create instance, if not over limit, and store ref to it."""
    if cls.max is not None and len(cls.instances) >= cls.max:
        raise Exception("Too many instances of class: {0}".format(cls.__name__))
    ...

Note:

Removal of the import - that should be at the top of the file, with the others;
Use of str.format rather than + string concatenation; and
Removal of redundant parentheses (just my personal taste) and comment.

Making SelfTrackingClass._classnames a defaultdict(list) from collections would save you from needing to manually check and add a new list when a new class name is used. Alternatively, you can use dict.setdefault:

cls._classnames.setdefault(cls.__name__, []).append(weakref.ref(instance))

It seems unnecessary to remove the empty list from _classnames when you delete an instance.


Each add entry in connectionStrings section will be parsed as ConnectionStringSettings at the end of the day.
This class has 3 properties: Name,ConnectionString and ProviderName.
In your provided sample you have defined only the first two.
Your provided sample seems to me a bit too specific/strict:

Replace only the connectionStrings attribute
Match the entity where the name equals MyConnectionString

The same result could be achieved with less specific transformation rules:
<connectionStrings>
    <remove xdt:Transform="Replace" name="MyConnectionString" />
    <add name="MyConnectionString" connectionString="...;User Id=******;Password=123;"
      xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
  </connectionStrings>

I've specified the name as an attribute of the add element
I've changed the Locator attribute value from Condition to Match
And I've removed the (connectionString) suffix from the Transform attribute

I've checked the transformation with this tool.


Write a lock free singleton factory using generics in c#

A delegate can be seen as method signature contract. You can define what sort of methods are you willing to work with. For example

The method should accept type x, type y and type z as parameters
and should return with type w

Any method, which satisfy this contract, is a valid method from the delegate perspective.

public delegate TType CreateObjectDelegate();

This delegate says that any method that has no parameter and will return with TType is a good one.

You can describe the same by using the Func class:

Func<TType> CreateObjectDelegate

Whenever you want to call the Register method you just have to pass a method which satisfies this contract. For example (let's suppose TType is int):

cacheProvider.Register("MyChild1Cache", () => 0);

Func<int> alternative1 = () => 1;
cacheProvider.Register("MyChild2Cache", alternative1.Invoke);

Func<int, Func<int>> alternative2 = i => () => i;
cacheProvider.Register("MyChild3Cache", alternative2.Invoke(2).Invoke);


Safe cracker string with all combinations

Your algorithm is suboptimal.  According to this website, a de Bruijn sequence for SafeCracker.genCrackerString("0123", 3) should be 66 characters long:

000100200301101201302102202303103203311121131221231321332223233300

However, your output is 74 characters long:

00010020030011012013011121021131031122022123023121320321330331322232332333

A simpler example is genCrackerString("12", 2), which your unit test says should be "112122".  However, "11221" is shorter.  So, your unit tests are invalid as well.


Greedy adaptive dictionary (GAD) for supervised machine learning

I haven't read the paper so don't necessarily understand the algorithm, but this seems wrong to me:

    # 3. Find residual column (l1 to l2 norm ratio)
    min_eps = float('inf') # to search min initialize to infinite
    j_min   =   -1
    for j in range(X.shape[1]):
        norma1 = norma2 = 0
        for i in range(X.shape[0]):
            norma1 += abs(X[i][j])
            norma2 += (X[i][j])**2
        norma2 = math.sqrt(norma2)
        eps = norma1/norma2   # sparsity index
        if min_eps > eps and j not in I: #excludes if already inserted
            min_eps=eps
            j_min = j

The pseudocode says to find the column of \${\mathbf R}^l\$ with minimum ratio, but this code finds the column of \$\mathbf X\$ with minimum ratio.

Have you tested your code and made sure it returns the correct result?


(AbstractDocument) textField.getDocument()

This is bad practice.

I recommend that you do one of these options:

The simple way would be to create a method toAbstractDocument(Document document)
The better way would be to create a field at TextField class such as ? extends Document document.


Using Dynamic Programming to reduce time complexity

'''
The Problem can be thought as string pattern matching, Where output will be minimum no of spaces in bigger string(piStr) to match maximum no of strings from list of smaller strings(favNumArr).
To solve this, we take one var "ans" to store no spaces and one variable "curr" to store the current pattern.
Now we iterate through the piStr and whenever we encounter(ith pos) that curr pattern is in favNumArr, we use recursion and call findMinSpaces for i+1 and increment ans with 1.
There is no need to use DP if we return from the loop with first occurrence of match and hence the loop will not run after it return value of recursion call.
The last return statement is to counter when i == N-1 when we reach the end of piStr.
The time complexity for this solution is O(n)
Any suggestion for further enhancement or if  breaks any edge case is open.'''

def findMinSpaces(k, piStr, favNumArr):
    curr = ''
    ans = 0
    N = len(piStr)
    if( k == N):
        return 0
    for i in range(k, N):
        print(curr)
        curr += piStr[i]
        if(curr in favNumArr and i != N-1):
            ans += 1 + findMinSpaces(i+1, piStr, favNumArr)
            return ans
    return ans

def minSpaces(piStr, favNumArr):
    return findMinSpaces(0, piStr, favNumArr)

print(minSpaces('',['3149v','40x9','15926535c897','1c4','932c3','84626c43383279','4c793']))


JavaScript function to calculate the average of an array

First of all, your code is incorrect. Arrays have a starting index of 0, not 1. Furthermore, array.length is one more than the last filled index (because the length is 1 based, and the array is 0 based. Yes, this is confusing.) So you're starting by not including the first item, and then also adding up an undefined item.

And what happens if you get an empty array? You divide by zero, which is MADNESS!! MADNESS I TELL YOU!

Second, there's a reason the code looks the same as everywhere: You have followed the definition of the average; the sum of components divided by the number of components. There's no shame in this, you should actually be proud that you've managed to conform to the standard.

If you really want, you can make the loop implicit. ES5 (ECMAScript 5, the latest js standard) defined an Array.prototype.reduce function (click link for the reference.) It's a perfect fit for your needs, but doesn't change the core algorithm.

Third, your mean function is doing something unexpected: Instead of just calculating the mean, it displays it as well. This does not follow expectations (or at least my expectation), as a function which calculates the mean should do that, and just that. That translates to a very important design aspect, which says that a function should do one thing, one thing only, and do it well. Because imagine if Math.sqrt, for instance, starts displaying the square roots instead of giving you them. Like division by zero, it's madness all over again!


Quick review:

Remove this damn
, styling is for CSS.
In each
, you better have an
 :-)
You can add rel="author" to your  link on the author. Even better, you can use The author's name (Google will recognize this as a "rich snippet" and show your face in google results. Take a look at http://schema.org for more information). Rich snippets are a whole other topic, so I'll stop talking about it :)

Edit after your comment:

Each article should contain an
 for its article sections.
Each article should have its title in an
. Yes, even if there are multiple
 in the main page. If there is just the titles on the main page (no article's text), feel free to use
.
The
 on the frontpage is tolerated, not on the blog pages. Feel free to use it or not on the frontpage, but make sure that each blog page has the title of the post as an
, not the site's name.

Related picture:


def printIntro():
    print("This program simulates a bunch of blackjack games.")

Python style guide recommend lowercase_with_underscores for function names

def getInputs():
    while True:
        n = eval(input("How many games should be simulated? "))

not a really good idea to use eval, because that allows the user to input any python expression which may not make sense. Instead use int, which will only allow numbers

        if n <= 0:
            print("You must enter a number greater than zero!")
        else:
            break

    return n

def simOneGame():
    score = 0
    blacklist = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
    while not gameOver(score):
        blackscore = blacklist[randrange(len(blacklist))]

Python has a function, random.choice() which returns a random element from a list.

        score = score + blackscore

        if score >= 17:
             break

Why? The loop will terminate anyways. There doesn't seem to be a reason to break here

        if blackscore == 11 and (score >= 6 and score <= 10):
            score = score + 11
        else:
            score = score + 1

I assume that this has to do with handling aces, but I don't understand the logic. You've already added blackscore to score, so I wouldn't think this would do the right thing. Also, couldn't you need to change the value of an ace to a 1, from an eleven due to later cards?

    return score

You only really care about busts/holds so maybe you should return True or False?

def simNGames(n):
    holds = 0
    busts = 0
    for i in range(n):
        score = simOneGame()
        if score >= 22:
            busts = busts + 1
        else:
            holds = holds + 1

    return holds, busts

def gameOver(score):
    return score >= 22 or score >= 17

That's the same as score >= 17, no reason to include the first part of the condition

def printSummary(holds, busts):
    n = holds + busts
    print("Number of holds and busts: Holds: {0:0} Busts: {1:0}".format(holds, busts))
    print("Percentage of holds and busts: Holds: {0:0.1%}".format(holds / n), end = " ")
    print("Busts: {0:0.1%}".format(busts / n))

def main():
    printIntro()
    n = getInputs()
    score = simOneGame()
    holds, busts = simNGames(n)
    printSummary(holds, busts)

if __name__ == "__main__":
    main()


SSH Class with a method for downloading via SCP

Some notes:

Your documentation doesn't match... well, it doesn't match anything in your code! Wrong documentation is the only thing worse than no documentation.
A ternary should not span multiple lines. Thankfully, a regular if..else is also an expression in Ruby.

@keys = if args.empty?
  Etc.getpwnam(Etc.getlogin).dir + '/.ssh/id_rsa'
else
  args
end

While you're at it, don't name the argument args: Name it keys, since that's what it is.
I haven't played around with Net::SCP, but if I'm reading the docs right, download will return immediately (i.e. before the file's been downloaded). And your next line closes the connection. As far as I can guess, you, in effect, just cancel all of your downloads as soon as you start them. What you want is probably download! (note the bang).
Incidentally, it's perhaps overkill to make a class for this. Net::SCP already has a download! class method. If we rewrite your class with this, we get:

class SSHOps
  def initialize(host, user=Etc.getlogin, *args)
    @host = host
    @user = user
    @keys = if args.empty?
      args << Etc.getpwnam(Etc.getlogin).dir + '/.ssh/id_rsa'
    else
      args
    end
  end

  def download_file(remote_path, local_path)
    options = {
      ssh: { keys: @keys },
      preserve: true
    }
    Net::SCP.download!(@host, @user, remote_path, local_path, options)
  end
end

At this point, the class is only adding defaults for username and keys. That's it. So it might be simpler to write a few simple helper methods:

module SSHOps
  module_function

  def default_key
    File.join(Etc.getpwnam(default_user).dir, ".ssh", "id_rsa")
  end

  def default_user
    Etc.getlogin
  end

  def download!(host, remote_file, local_file)
    options = {
      ssh: { keys: [default_key] }
      preserve: true
    }
    Net::SCP.download!(host, default_user, remote_file, local_file, options)
  end
end

Which you can then use like:

SSHOps.download!("example.com", "/some/remote/file", "/some/local/file")

I've intentionally left out some stuff. My hunch is that you almost always want to use your current username and keys, because that's the functionality that your current class adds. Anything else can basically be achieved just as simply with plain Net::SCP.download!, possibly using the two other helper methods in the module above.
Of course, if you plan to download multiple files in a row, then it'd make sense to use a class if you at least reuse your SSH session rather than opening one for each download.


Better way to write this code in functional manner using map and reduce?

Your “functional” approach is overly complicated. Notice that this is completely equivalent:

var result = arr.map(some_action).filter(other_action);

I.e. If you're only delegating to another function, you can specify that function directly. Also, an == true test is superfluous.

Your “procedural” variant is not equivalent, that would have to be:

var result = [];
arr.forEach(function(item){
    var changedItem = some_action(item);
    if (other_action(changedItem))
        result.push(changedItem);
});

Note that both variants have the same algorithmic complexity, and that the cost of iteration is likely negligible compared with the cost of some_action and other_action.

Functional programming does not mean unreadable code. Even if you're not just delegating to another function, you could improve formatting, e.g. to

var result = arr.map(function (item) {
  return some_action(item);
}).filter(function (item) {
  return other_action(item);
});


Find the first reoccuring char from a String

The Character type already has everything you need. It is either a character or the special value null.

For this task you don't need a map, a simple set is enough.

When you move this code into a separate method, using break becomes bad style because you should directly return. In the currect code it's ok.

public static Character findFirstRecurring(String str, char ch) {
    // Left as an exercise
    …
    return null;
}


Pre-calculate the winning combinations for an n-sized tic tac toe board using C++ functional programming

Here are some suggestions.  This answers uses the Range-v3 library and assumes

#include <range/v3/all.hpp>

namespace view = ranges::view;

Please include the #includes and supply a small test program in the future.  You probably have written them anyway, so why not post them to save reviewers' time? :)
int may be too small for indexes.  Consider using std::size_t.  You can define a type alias for flexibility.

using index_t = std::size_t;

The type std::vector<std::vector<index_t>> occurs many times.  Save time by writing

using rule_t = std::vector<index_t>
using rules_t = std::vector<rule_t>;

The concept "\$n \times n\$ board" only makes sense when \$n\$ is a positive integer.  Therefore, enforce the pre-condition \$n \ge 1\$.  Also, the name x is a bit vague.  size may be better.

rules_t rules(index_t size)
{
    if (size == 0)
        throw std::invalid_argument{"..."};
    // ...
}

rules(1) currently returns {{0}, {0}, {0}, {0}}, which is definitely wrong.  It should return {{0}}.  Your general logic is "\$n\$ rows + \$n\$ columns + \$2\$ diagonals", which only applies to \$n \ge 2\$.  The easiest approach would be a special case:

rules_t rules(index_t size)
{
    // ...
    else if (size == 1)
        return {{0}};
}

Following the previous bullet, why not make separate functions to make your logic clear?

rules_t rules(index_t size)
{
    // ...
    else {
        auto rows = rules_row(size);
        auto columns = rules_column(size);
        auto diagonals = rules_diagonal(size);
        return ranges::to<rules_t>(view::concat(rows, columns, diagonals));
    }
}

where view::concat concatenates the three vectors and ranges::to converts the result to the desired return type.  (Note that view::concat is disabled with rvalues to prevent dangling iterators, so we first store the subvectors.)
The rules_row function is easy to write:

rules_t rules_row(index_t size)
{
    return view::ints(index_t(0), size * size) | view::chunk(size);
}

view::ints generate a left-inclusive sequence of integers {0, 1, 2, ..., size * size - 1}, and view::chunk(size) breaks it into chunks each of size size.
The rules_column function is a bit tricky, because the Range library does not provide a function like chunk that splits like this.  We do have a function stride, so we can write a manual "loop":  (it took me quite a while to figure this out, so tell me if there is a better way!)

rules_t rules_column(index_t size)
{
    return view::ints(index_t(0), size) |
               view::transform([=](index_t col) {
                   return view::ints(index_t(col), size * size) | view::stride(size);
               });
}

view::ints(index_t(0), size) generates the column numbers.  Each of them is passed to the lambda.  The lambda returns the corresponding rule for each column.
The rules_diagonal function is moderately simple:

rules_t rules_diagonal(index_t size)
{
    return {
        view::ints(index_t(0), size) |
            view::transform([=](index_t r) { return r * (size + 1); }),
        view::ints(index_t(1), size + 1) |
            view::transform([=](index_t r) { return r * (size - 1); })
    };
}

Here, we always have two rules: one for the primary diagonal

{0 * size + 0, 1 * size + 1, 2 * size + 2, ..., (size - 1) * size + (size - 1)}

which is equivalent to

{0, 1, 2, ..., size - 1} * (size + 1)

and the other for the secondary diagonal

{size - 1, 2 * size - 2, 3 * size - 3, ... size * size - (size - 1)}

which is equivalent to

{1, 2, 3, ..., size + 1} * (size - 1)

Putting everything together:

#include <vector>
#include <range/v3/all.hpp>

namespace view = ranges::view;

using index_t = std::size_t;
using rule_t = std::vector<index_t>;
using rules_t = std::vector<rule_t>;

rules_t rules_row(index_t size)
{
    return view::ints(index_t(0), size * size) | view::chunk(size);
}

rules_t rules_column(index_t size)
{
    return view::ints(index_t(0), size) |
               view::transform([=](index_t col) {
                   return view::ints(index_t(col), size * size) | view::stride(size);
               });
}

rules_t rules_diagonal(index_t size)
{
    return {
        view::ints(index_t(0), size) |
            view::transform([=](index_t r) { return r * (size + 1); }),
        view::ints(index_t(1), size + 1) |
            view::transform([=](index_t r) { return r * (size - 1); })
    };
}

rules_t rules(index_t size)
{
    if (size == 0)
        throw std::invalid_argument{"A board cannot have size zero"};
    else if (size == 1)
        return {{0}};
    else {
        auto rows = rules_row(size);
        auto columns = rules_column(size);
        auto diagonals = rules_diagonal(size);
        return view::concat(rows, columns, diagonals);
    }
}

(live demo, tests the function for size = 1, 2, 3, ..., 10)


Binning whilst avoiding the need for for-loops in Python?

"Relatively simple" is in the eye of the beholder. Some ideas though:

This code

int_temp = []
int_sal = []

for i in range(5):
    int_temp.append(np.digitize(np.ndarray.flatten(T_mean[i,:,:,:]), T_bins))
    int_sal.append(np.digitize(np.ndarray.flatten(S_mean[i,:,:,:]), S_bins))

can be transformed into two list comprehesions

int_temp = np.array([np.digitize(T_mean[i, :, :, :].flatten(), T_bins) for i in range(5)])
int_sal = np.array([np.digitize(S_mean[i, :, :, :].flatten(), S_bins) for i in range(5)])

I also converted the results into numpy arrays, for reasons that I'll refer to later. Also take note that np.ndarray.flatten(T_mean[i,:,:,:]) was rewritten as T_mean[i, :, :, :].flatten() which is the usual way to use np.ndarray.<fun>: call whatever.<fun>() (<fun> is meant to be a placeholder here, not actual code).

The next part of the code that caught my eye was

np.ndarray.flatten(volume_mean[k, l, :, :, :])
    [np.argwhere(np.logical_and(int_temp[l] == i, int_sal[l] == j))])

This line is very hard to read, but can easily be rewritten as:

indices = np.argwhere(np.logical_and(int_temp[l] == i, int_sal[l] == j))
volume_sum[k, l, j, i] = nansum(volume_mean[k, l, :, :, :].flatten()[indices])

which looks muss less frightening. You can even get rid of np.argwhere and use np.logical_and(int_temp[l] == i, int_sal[l] == j) directly as binary mask:

mask = np.logical_and(int_temp[l] == i, int_sal[l] == j)
volume_sum[k, l, j, i] = (
    np.nansum(volume_mean[k, l, :, :, :].flatten()[mask])
)

To see if there is a difference in performance, I put the original code and the refactored version into functions:

def compute_volume_sum(volume_mean, s_mean, t_mean, s_bins, t_bins):
    """Original implementation"""
    int_temp = []
    int_sal = []
    for i in range(5):
        int_temp.append(np.digitize(np.ndarray.flatten(t_mean[i,:,:,:]), t_bins))
        int_sal.append(np.digitize(np.ndarray.flatten(s_mean[i,:,:,:]), s_bins))

    volume_sum = np.zeros((2, 5, s_bins.size, t_bins.size))
    for k in range(2):
        for l in range(5):
            for i in range(t_bins.size):
                for j in range(s_bins.size):
                    volume_sum[k, l, j, i] = (np.nansum(
                        np.ndarray.flatten(volume_mean[k, l, :, :, :])[np.argwhere(
                            np.logical_and(int_temp[l] == i, int_sal[l] == j))]))

    return volume_sum

def compute_volume_sum_ref(volume_mean, s_mean, t_mean, s_bins, t_bins):
    """Refactored implementation"""
    int_temp = np.array([np.digitize(t_mean[i, :, :, :].flatten(), t_bins) for i in range(5)])
    int_sal = np.array([np.digitize(s_mean[i, :, :, :].flatten(), s_bins) for i in range(5)])

    volume_sum = np.zeros((2, 5, s_bins.size, t_bins.size))
    for k in range(2):
        for l in range(5):
            for i in range(t_bins.size):
                for j in range(s_bins.size):
                    mask = np.logical_and(int_temp[l] == i, int_sal[l] == j)
                    volume_sum[k, l, j, i] = (
                        np.nansum(volume_mean[k, l, :, :, :].flatten()[mask])
                    )

    return volume_sum

BTW: You can confirm that both functions return the same value using np.allclose

I then measured how long it takes to run each function ten times. The results were as follows:

original: 16.860085s
refactored: 11.849922s

Not bad, but those loops still hurt.

Enter numba, a just-in-time Python compiler. It works nicely with numpy and can make loops quite a bit faster since they are compiled to native code. I recommend to use a scientific Python distribution like Anaconda if you want to try/use it.

Unfortunately, numba does not support the full feature set of Python (e.g. list comprehensions are not supported), so I had to resort to a little bit of trickery to get it working:

import numba

def compute_volume_sum_nb(volume_mean, s_mean, t_mean, s_bins, t_bins):
    """numba version"""
    int_temp = np.array([np.digitize(t_mean[i, :, :, :].flatten(), t_bins) for i in range(5)])
    int_sal = np.array([np.digitize(s_mean[i, :, :, :].flatten(), s_bins) for i in range(5)])

    return _numba_inner(volume_mean, s_bins, t_bins, int_temp, int_sal)

@numba.njit()
def _numba_inner(volume_mean, s_bins, t_bins, int_temp, int_sal):
    volume_sum = np.zeros((2, 5, s_bins.size, t_bins.size))
    for k in range(2):
        for l in range(5):
            for i in range(t_bins.size):
                for j in range(s_bins.size):
                    mask = np.logical_and(int_temp[l] == i, int_sal[l] == j)
                    volume_sum[k, l, j, i] = (
                        np.nansum(volume_mean[k, l, :, :, :].flatten()[mask])
                    )

    return volume_sum

numba.njit() is a decorator that can be used on functions to mark their function body for jit-compilation. The first time compute_volume_sum_nb is called, numba triggers the compilation process so be sure to exclude the first call from any timings you do.

Let's see how the timings now look like:

original: 16.860085s
refactored: 11.849922s
numba: 0.833529s

That's quite a bit faster, isn't it?

I'm almost sure that some of the loops could be replaced by clever indexing and use of vectorized functions in numpy, but I don't have the time to dive deeper into the problem.

A few non-performance related notes: be sure so have a look at the Style Guide for Python Code (aka PEP 8). The code sometimes already follows those guidelines, but sometimes also doesn't, e.g. when using uppercase letters in variable names.

Maybe also think about how you can modularize your code, e.g by using functions. Those separated parts are also easier to document. You want to write """"documentation""" to save future you some headache, don't you?