I see a few things that could allow you to improve your program.  First, though, I don't consider myself a bash expert, so there may well be better ways of doing these things.

Use a "shebang" line

As this question points out, you should always use a "shebang" line for your bash scripts.  So the first line would be:

#!/usr/bin/env bash

Pass values as arguments

Rather than prompting for the SCALE value, it's generally better to use a command line argument.  That way, the script can be reused by other shell scripts.

Provide a stopping mechanism

As each term is calculated, eventually, it will be equal to zero given the passed scale.  This suggests a mechanism for stopping: check each term for 0 before adding it.

Indent do and while loops

I don't know of a bash style guide (there probably is one!) but I like to see the contents of loops indented to make it easier to read.

Putting it all together

Here's a modification of your script with all of these suggestions implemented:

bashpi.sh

#!/usr/bin/env bash
SCALE=$1
VALUE=2
PI=0
FITNESS=1
DELTA=3
while [ $(echo "$DELTA==0" |bc) != "1" ]
do
    PI=$(echo "$PI+$DELTA" | bc)
    DELTA=$(echo "scale=$SCALE;(4/($VALUE*($VALUE+1)*($VALUE+2)))-(4/(($VALUE+2)*($VALUE+3)*($VALUE+4)))" | bc)
    VALUE=$(($VALUE+4))
    FITNESS=$(($FITNESS+1))
    echo "###############"
    echo "--> $FITNESS // $VALUE"
    echo "$PI"
done

To better understand how this works, you can replace the three echo statements with this one:

echo "DELTA = ${DELTA} --> ${FITNESS} // ${VALUE} : ${PI}"

Sample output

With ./bashpi.sh 4, and the modified echo above I get this output:

DELTA = .1333 --> 2 // 6 : 3
DELTA = .0064 --> 3 // 10 : 3.1333
DELTA = .0012 --> 4 // 14 : 3.1397
DELTA = .0003 --> 5 // 18 : 3.1409
DELTA = .0001 --> 6 // 22 : 3.1412
DELTA = .0001 --> 7 // 26 : 3.1413
DELTA = .0001 --> 8 // 30 : 3.1414
DELTA = 0 --> 9 // 34 : 3.1415


Disclaimer: Current version of the code seems to be very weirdly indented. Some comments might be wrong because of some misinterpretation of your code.

Style

Python has a style guide called PEP 8. It is usually a good idea to try to stick to it unless you have good reasons not to. In any case, it is definitly worth the read. You'll find various tools to check compliancy. In your case, the main issues would be : naming (snake_case is recommended for function names), spacing (whitespace around operators), indentation (4 spaces)

Design

Your function returns either a list of food or None is there is no food. This seems to be more complicated than it should be: it could return a list of food (empty is there is no food). It makes your function easier to use, easier to explain and more concise: you can simply remove the if len(foods) == 0: condition.

From the Zen of Python:

  Special cases aren't special enough to break the rules.

In any case, your function deserves some documentation.

Tuple unpacking

One of my favorite feature of Python is iterable unpacking. You can do something like:

a, b, c = my_list_with_3_elements

and have easy access to the different elements (and an exception if the list has the wrong number of elements).

In your case, assuming location and size have the wrong length, you could simply write:

 x, y = self.location
 c_x, c_y = self.size

This is very convenient to avoid long expressions with error-prones bracket access to a particular index.

Going further, you could do the same with food[0] and food[1].

Now, (assuming I haven't broken too many things) looks like:

def got_food(self, all_foods):
   foods = []
   x, y = self.location
   c_x, c_y = self.size
   for f_x, f_y in all_foods:
      if f_y >= y - c_y and f_y <= y + c_y and f_x >= c_x and f_x <= x + c_x:
          if f_y > y and f_y < y + c_y and f_x > x and f_x < x + c_x:
              foods.append((f_x, f_y))
          elif f_y < y and f_y > y - c_y and f_x  > x and f_x > x - c_y:
              foods.append((f_x, f_y))
      if f_x >= x - c_x and f_x <= x + c_x and f_y >= y and f_y <= y + c_y:
            foods.append((f_x, f_y))
  return foods

Chained comparisons

From the doc:

  Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

In your case, many things can be rewritten:

def got_food(self, all_foods):
   foods = []
   x, y = self.location
   c_x, c_y = self.size
   for f_x, f_y in all_foods:
      if y - c_y <= f_y <= y + c_y and c_x <= f_x <= x + c_x:
          if y < f_y < y + c_y and x < f_x < x + c_x:
              foods.append((f_x, f_y))
          elif y > f_y > y - c_y and f_x > x and f_x > x - c_y:
              foods.append((f_x, f_y))
      if x - c_x <= f_x <= x + c_x and y <= f_y <= y + c_y:
            foods.append((f_x, f_y))
  return foods

I do not understand enough of the intent to go any further (also I suspect the condition f_x > x is wrong).


Whether or not to name Boolean parameters in Scala

Personally, I think it's a reasonable suggestion.

If you change the parameter name in a way that changes its meaning, it's a good thing that the code using the old name doesn't compile anymore.
If you change the parameter name, keep the meaning the same and all your code is in the same solution, then your IDE should be able to rename all usages at the same time.
If you change the parameter name, keep the meaning the same, but your code is not all in the same solution (e.g. when you're writing a library used by third parties), then somebody could be using this practice, no matter what you use. So, the name is already part of the interface, no matter what you use.

There is a middle ground where all your code is not in the same solution, but you have control over all of it (e.g. by specifying coding guidelines for your company). In this case, you might decide that it's an unnecessary dependency. But in all the other cases, I think that using named parameter often makes sense.


Here's my first pass on stylistic feedback.

Unneeded parenthesis around args[1]
Redundant type specifications, everywhere
Remove commented-out code
Add spaces around binary operators (/, +, <=, +=)
Don't have double semicolons at the end of the line
Don't add space inside [], like in vec![]
Split multiple statements on different lines
Add spaces after commas
Add spaces after colons
Basically never use &Vec<T>, use &[T] instead
Don't use an explicit return at the end of function
Typo in the println! (pi vs phi)

I believe that you can change some of the loops to use more iterators, but I haven't figured those out yet.

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let x: usize = args[1].trim().parse().expect("expected a number");

    let root = (x as f64).sqrt() as usize;
    let y = (x as f64).powf(0.3333333333333) as usize + 1;

    let sieve_size = x / y + 2;
    let mut sieve = vec![true; sieve_size];
    let mut primes = vec![0; sieve_size];
    sieve[0] = false;
    sieve[1] = false;

    let mut a = 0;
    let mut num_primes = 1;

    let mut num_primes_smaller_root = 0;

    // find all primes up to x/y ~ x^2/3 aka sieve_size
    for i in 2..sieve_size {
        if sieve[i] {
            if i <= root {
                if i <= y {
                    a += 1;
                }
                num_primes_smaller_root += 1;
            }

            primes[num_primes] = i;
            num_primes += 1;
            let mut multiples = i;
            while multiples < sieve_size {
                sieve[multiples] = false;
                multiples += i;
            }
        }
    }

    let mut phi_results = vec![vec![0; a + 1]; x + 1];

    let mut p_2 = 0;
    for i in a + 1..num_primes_smaller_root + 1 {
        let mut first_term = 0;
        while primes[first_term] < x / primes[i] {
            first_term += 1;
        }
        if primes[first_term] == x / primes[i] {
            first_term += 1;
        }
        p_2 += (first_term - 1) - i + 1;
    }

    println!("pi({}) = {}", x, phi(x, a, &primes, &mut phi_results) + a - 1 - p_2);
}

fn phi(x: usize, b: usize, primes: &[usize], phi_results: &mut [Vec<usize>]) -> usize {
    if b == 0 {
        return x;
    }

    if phi_results[x][b] != 0 {
        return phi_results[x][b];
    }

    let value = phi(x, b - 1, primes, phi_results) - phi(x / primes[b], b - 1, primes, phi_results);
    phi_results[x][b] = value;
    value
}

When I run this code with 1000000 it takes ~300 milliseconds:

$ cargo build --release && time ./target/release/sieve 1000000
phi(1000000) = 78498

real    0m0.307s
user    0m0.204s
sys     0m0.102s

Note that you need to build the code and time it in a separate pass, to not include the time spent compiling.

Performance-wise, I'm not seeing many obvious changes.

Try to avoid direct slice access when feasible (vector[0]). These accesses are checked at run time to avoid walking off into undefined memory. Iterators guarantee that no undefined memory will be accessed and can sidestep that small performance bit.

Iterator adapters can also allow removing mutability:

let mut p_2 = 0;
for (i, zz) in primes[a + 1..num_primes_smaller_root + 1].iter().enumerate() {
    let i = i + a + 1;
    let first_term = primes.iter().take_while(|&&p| p <= x / zz).count();
    p_2 += (first_term - 1) - i + 1;
}

Then, move that arithmetic on i to the end, and apply more adapters to remove more mutability:

let interesting_primes = primes[a + 1..num_primes_smaller_root + 1].iter();

let p_2 =
    interesting_primes
    .map(|ip| primes.iter().take_while(|&&p| p <= x / ip).count())
    .enumerate()
    .map(|(i, v)| v - 1 - i - a)
    .fold(0, |acc, v| acc + v);


Determining if a check box has been checked or not

A common question, your question is not so much ugly as it is repetitive. Because of that it violate DRY.

You basically have copy pasted the same structure over and over :

if ($("#XXXOld").is(":checked")) {
    var XXXOldGuide=1;
} else {
    var XXXOldGuide=0;
}

If you turn these vars into the properties of a class, then you could do these assignments in a loop over strings. Something like this:

function Guides(){
  this.update();
}

Guides.prototype.list = ['amOld','folOld','tichOld','bookOld','nebOld','sterOld','byteOld','ingOld'];

Guides.prototype.update = function(){
  for( var i = 0 ; i < this.list.length ; i++ ){
    var guide = this.list[i];
    this[ guide + 'Guide' ] = $("#" + guide ).is(":checked") ? 1 : 0;
  }
}

Or, if you do not wish to expose the list, you could go for something more functional (hat tip to @Warbo):

function Guides(){
  this.update();
}

Guides.prototype.update = function(){
  var list = ['amOld','folOld','tichOld','bookOld','nebOld','sterOld','byteOld','ingOld'],
      self = this;
  list.forEach( function( guide ){
    self[ guide + 'Guide' ] = $("#" + guide ).is(":checked") ? 1 : 0;
  });
}

I also threw in a ternary for good measure since I don't like one liners in curly braces.

You can then access bookOldGuide like this:

var guides = new Guides();
console.log( guides.bookOldGuide );

If you  need to refresh the values inside guides ( because you are about to save data for example ), you simply need to

guides.update();

Finally, there is a performance hit you should be aware of, I am not caching any of the jQuery lookups. You could have update create a cache of the lookups if performance becomes an issue.


Simple countdown programs to print "3, 2, 1, Action!" using while loop

Why does it has to be a while?

Maybe it is preference but for loops look cleaner.

Reversing can be done by using reversed function which reverses a iteration

countdown = 3
for count in reversed(range(1, countdown+1)):
    print(count)
print('action!')

Or you could use the step parameter in range(start, end, step) and rewrite the for loop to

for count in range(countdown, 0, -1):


Refactoring same loop logic with different input data

One way using the Template method pattern:

abstract class LineBuilder {
    protected abstract String getLine(String value);

    public String buildLine(String[] values) {
        StringBuilder lineBuilder = new StringBuilder();
        for (int i = 0; i < values.length - 1; i++) {
            lineBuilder.append(getLine(values[i])).append(SEPARATOR);
        }
        lineBuilder.append(getLine(values[values.length - 1]));
        return lineBuilder.toString();
    }
}

class StringLineBuilder extends LineBuilder {
    protected String getLine(String value) {
        return value;
    }
}

class NodeWorkerLineBuilder extends LineBuilder {
    private final NodeDecorator nodeWorker;

    public NodeWorkerLineBuilder(NodeDecorator nodeWorker) {
        this.nodeWorker = nodeWorker;
    }

    protected String getLine(String value) {
        return nodeWorker.getItemValueFromAttribute(value);
    }
}

Once you define the above classes you can replace the code inside your methods with:

public static String buildLine(String[] values) {
    return new StringLineBuilder().buildLine(values);
}

public static String buildLineFromNodeWorker(String[] values,
        NodeDecorator nodeWorker) {
    return new NodeWorkerLineBuilder(nodeWorker).buildLine(values);
}


Create a state dropdown with an abbreviation option and a full option

I'm going to assume here (having done this myself before when I first started out with PHP), that you are storing the state data in a MySQL database, which you are pulling and storing in the global $state var.

Do not do that. You're slowing down the entire program by making a call out to the database for what is pretty much static data (the last state to join the union joined 55 years ago).

Now, I would just have the dropdowns stored in functions which just return a string. One function for long name, one for abbreviated.

However, using this as an exercise for you in DRY, I went ahead and created a class, StateDropDown, which contains an associative array of states/properties and their abbreviation. On initiation, the class generates the output form. If the $style contains 'abbr', then we use the abbreviated version after performing a ksort(). Otherwise, since the data in the array is static and already sorted as we prefer, we don't perform an asort and just go straight to storing the select form in a property $output.

class StateDropDown{
    protected $states = array(
        "Alabama" => "AL",
        "Alaska" => "AK",
        "Arizona" => "AZ",
        "Arkansas" => "AR",
        "California" => "CA",
        "Colorado" => "CO",
        "Connecticut" => "CT",
        "Delaware" => "DE",
        "Florida" => "FL",
        "Georgia" => "GA",
        "Hawaii" => "HI",
        "Idaho" => "ID",
        "Illinois" => "IL",
        "Indiana" => "IN",
        "Iowa" => "IA",
        "Kansas" => "KS",
        "Kentucky" => "KY",
        "Louisiana" => "LA",
        "Maine" => "ME",
        "Maryland" => "MD",
        "Massachusetts" => "MA",
        "Michigan" => "MI",
        "Minnesota" => "MN",
        "Mississippi" => "MS",
        "Missouri" => "MO",
        "Montana" => "MT",
        "Nebraska" => "NE",
        "Nevada" => "NV",
        "New Hampshire" => "NH",
        "New Jersey" => "NJ",
        "New Mexico" => "NM",
        "New York" => "NY",
        "North Carolina" => "NC",
        "North Dakota" => "ND",
        "Ohio" => "OH",
        "Oklahoma" => "OK",
        "Oregon" => "OR",
        "Pennsylvania" => "PA",
        "Rhode Island" => "RI",
        "South Carolina" => "SC",
        "South Dakota" => "SD",
        "Tennessee" => "TN",
        "Texas" => "TX",
        "Utah" => "UT",
        "Vermont" => "VT",
        "Virginia" => "VA",
        "Washington" => "WA",
        "West Virginia" => "WV",
        "Wisconsin" => "WI",
        "Wyoming" => "WY",
        "American Samoa" => "AS",
        "District of Columbia" => "DC",
        "Federated States of Micronesia" => "FM",
        "Guam" => "GU",
        "Marshall Islands" => "MH",
        "Northern Mariana Islands" => "MP",
        "Palau" => "PW",
        "Puerto Rico" => "PR",
        "Virgin Islands" => "VI",
        "Armed Forces Africa" => "AE",
        "Armed Forces Americas" => "AA",
        "Armed Forces Canada" => "AE",
        "Armed Forces Europe" => "AE",
        "Armed Forces Middle East" => "AE",
        "Armed Forces Pacific" => "AP"
    );
    public $output = "";

    public function __construct($style = false, $form = null){
        if($style === true){
            ksort($this->states);
        }

        $this->output = "<select name='state'>";
        $this->output .= "<option value=''>--</option>";

        foreach($this->states as $name => $abbr){
            $this->output .= "<option value='" . $abbr . "'";
            if($form === $abbr){
                $this->output .= "selected='selected'";
            }

            if($style === true){
                $this->output .= ">" . $abbr . "</option>";
            } else {
                $this->output .= ">" . $name . "</option>";
            }
        }
        $this->output .= "</select>";
    }
}

To use, simply instantiate and echo output.

Here, we do a regular state name, with no selected state:

$dropdown = new StateDropDown();
echo $dropdown->output;

Here, we do a regular state name, with a selected state, NY:

$dropdown = new StateDropDown(null, "NY");
echo $dropdown->output;

Here, we do an abbreviated state name, with no selected state:

$dropdown = new StateDropDown(true);
echo $dropdown->output;

Here, we do an abbreviated state name, with a selected state, FL:

$dropdown = new StateDropDown(true, 'FL');
echo $dropdown->output;

While we may have the overhead of instantiating a new object, etc - we save on a possible database call. Additionally, we no longer do multiple checks, but rather do one check for abbreviation preference and assume the non-abbreviated by default, as well as keeping it non-abbreviated sort by default.

EDIT

Since OP indicated that I was incorrect in my assumption that they were storing this data in a database, I've modified my above Class into a function which does the same thing:

function statesDropdown($style = false, $form = null){
    $states = array(
        "Alabama" => "AL",
        "Alaska" => "AK",
        "Arizona" => "AZ",
        "Arkansas" => "AR",
        "California" => "CA",
        "Colorado" => "CO",
        "Connecticut" => "CT",
        "Delaware" => "DE",
        "Florida" => "FL",
        "Georgia" => "GA",
        "Hawaii" => "HI",
        "Idaho" => "ID",
        "Illinois" => "IL",
        "Indiana" => "IN",
        "Iowa" => "IA",
        "Kansas" => "KS",
        "Kentucky" => "KY",
        "Louisiana" => "LA",
        "Maine" => "ME",
        "Maryland" => "MD",
        "Massachusetts" => "MA",
        "Michigan" => "MI",
        "Minnesota" => "MN",
        "Mississippi" => "MS",
        "Missouri" => "MO",
        "Montana" => "MT",
        "Nebraska" => "NE",
        "Nevada" => "NV",
        "New Hampshire" => "NH",
        "New Jersey" => "NJ",
        "New Mexico" => "NM",
        "New York" => "NY",
        "North Carolina" => "NC",
        "North Dakota" => "ND",
        "Ohio" => "OH",
        "Oklahoma" => "OK",
        "Oregon" => "OR",
        "Pennsylvania" => "PA",
        "Rhode Island" => "RI",
        "South Carolina" => "SC",
        "South Dakota" => "SD",
        "Tennessee" => "TN",
        "Texas" => "TX",
        "Utah" => "UT",
        "Vermont" => "VT",
        "Virginia" => "VA",
        "Washington" => "WA",
        "West Virginia" => "WV",
        "Wisconsin" => "WI",
        "Wyoming" => "WY",
        "American Samoa" => "AS",
        "District of Columbia" => "DC",
        "Federated States of Micronesia" => "FM",
        "Guam" => "GU",
        "Marshall Islands" => "MH",
        "Northern Mariana Islands" => "MP",
        "Palau" => "PW",
        "Puerto Rico" => "PR",
        "Virgin Islands" => "VI",
        "Armed Forces Africa" => "AE",
        "Armed Forces Americas" => "AA",
        "Armed Forces Canada" => "AE",
        "Armed Forces Europe" => "AE",
        "Armed Forces Middle East" => "AE",
        "Armed Forces Pacific" => "AP"
    );
    $output = "";
    if($style === true){
        ksort($states);
    }

    $output = "<select name='state'>";
    $output .= "<option value=''>--</option>";

    foreach($states as $name => $abbr){
        $output .= "<option value='" . $abbr . "'";
        if($form === $abbr){
            $output .= "selected='selected'";
        }

        if($style === true){
            $output .= ">" . $abbr . "</option>";
        } else {
            $output .= ">" . $name . "</option>";
        }
    }
    $output .= "</select>";

    return $output;
}

To output the dropdown, simply do:

echo statesDropdown();


DataKey

State- vs. Input validation:

In your constructor you do something not quite intelligent. You first set all the fields and then check them for integrity.

IMO you should check the input data for validity before using it with something. This allows you to extract a so-called "leading guard clause". Some condition before a block of code makes it fail.

In fact you could extract the validation from the DataKey to the Builder while you're at it. Compare:

private DataKey(Builder builder) {
    if(!builder.isValid()){
         throw new IllegalStateException(INVALID_BUILDER_MESSAGE);
    }
    //keep doing the stuff you do ;)
}

Or even sooner:

public DataKey build(){
    if(!this.isValid()){
        throw new IllegalStateException(INVALID_BUILDER_MESSAGE);
    }
    return DataKey(this);
}

then you could remove the validation "clutter" from your DataKey constructor. And your isValid() method would look like:

private boolean isValid() {
    return !(userId == 0 && uuid != null
      && uuid.isEmpty() && deviceId != null
      && deviceId.isEmpty());
}

If-Statement vs Ternary operator:

    if (userId != 0) {
        this.flow = FlowEnum.USERFLOW;
    }
    else {
        this.flow = FlowEnum.DEVICEFLOW;
    }

You can shortcut this drastically by using a ternary operator. IMO this also makes your intent way more clear:

this.flow = (userId == 0) ? FlowEnum.DEVICEFLOW : FlowEnum.USERFLOW;

You can shorten this even further by adding a static import to your class:

import static fully.qualified.FlowEnum.*;

and then you get:

 this.flow = (userId == 0) ? DEVICEFLOW : USERFLOW;

But that one is personal preference, some people even see this as light obfuscation.

While we're at your enum. Currently it's no more than a glorified boolean. I will assume there could be more Flows, because if not you could just do:

this.isUserFlow = userId != 0;


Generic Linked List Implementation in Java

My answer only deals with the "testing" part of your question, not the review of the classes themselves.

If I can start with a question - are you expecting LLNode to be used by other classes?  Or is it only for use by DoublyLinkedList?  If it's the latter, then it's effectively private to DoublyLinkedList, whether you've declared it that way or not.  That is, it's not part of your library's API, and I wouldn't bother with separate tests for it.

Your tests for removeAt look like they're only checking that the size of the structure is correct at the end of the test, not that the correct nodes have been removed.  They really need some kind of assertion to make sure that the list has the right nodes in it afterwards.

The way you've tested exceptions is fine; although there are other ways of doing it.  I suggest you read up on the ExpectedException feature of JUnit, and see whether it's what you want to use.

Now for the controversial stuff - I've been shot down for this point of view before, but this is the voice of experience speaking.

It's hard, on reading your test, to tell what behaviour of the list has been tested, and what hasn't.  For example, you have a testRemoveAt; but without reading every line of the test, I can't tell which cases of the removeAt method have been tested - for example, (1) What if the argument is negative?  (2) What if the argument is greater than the number of things in the list? (3) What if the argument is valid? (4) What if the list is empty?.  I think you've tested (3) and (4), but not (1) and (2), but I'm not sure.

For this reason, I strongly recommend naming your tests after the behaviour that they test, NOT after the method that implements that behaviour.  This means you'll have more tests, and smaller ones, but you'll be able to see far more easily which behaviour has and hasn't been tested.  Also, in the event of a failure, it will be easier to see what has actually gone wrong.  So in this particular case, I would name the tests for removeAt something like -

@Test
public void removeAtThrowsException_withNegativeArgument(){
}

@Test
public void removeAtThrowsException_whenListIsEmpty(){
}

@Test
public void removeAtRemovesCorrectNodeFromList_whenArgumentLessThanSizeOfList(){
}

@Test
public void removeAtThrowsException_whenArgumentNotLessThanSizeOfList(){
}

As far as tests for equals go, you probably want quite a few cases.  Such as -

What happens if the argument is not a DoublyLinkedList?
What happens if the argument is a DoublyLinkedList with different elements
What happens if the argument is a DoublyLinkedList with the same elements in a different order?
What happens if the argument is a DoublyLinkedList with the same elements in the same order?
What happens if the argument is a DoublyLinkedList with equal elements (but not the same) in the same order?

Again, I recommend having each of these as a separate test method, with a descriptive name.  And the biggest benefit is that you can look at your test method names, and know which cases have and have not been tested, without having to read through the code.


Iterate over files and convert with a new name / directory

UUOC. pandoc takes the input file name as an argument. echo $file | pandoc -o outfile is equivalent to pandoc -o outfile $file. One process invocation down.
UUOS (sed in this case). bash has very rich string transformation features built in. For example, ${file%md} (see Parameter expansion section of man bash) will strip the md suffix form the filename. So consider

for file in *.md; do
    pandoc -o ../html/${file%md}html
done

Two more process invocations down.
If by any chance an .md filename contains funny characters (like whitespace), the substitution will produce unexpected results. It is safer to use double quotes, as in `"${....}".

PS: It might be beneficial to abandon the shell script altogether in favor of make, with a Makefile having a single stem rule

../html/%.html: %.md
    pandoc -o $@ $<


Here's some feedback (not an exhaustive list).

using namespace std;

Please stop doing this. when you add using namespace directives in header files, any file including that header will have potential namespace clashes (which is the problem namespaces are trying to prevent).

class Node
{
public:
    int nX; // (1)
    Node *next; // (2)
    Node(){ head = NULL; }  // (3)

Notes:

The only ways lines (1) and (2) are acceptable, are:

if instances of your class are valid regardless what you place in nX and next.

Client code example:

Node n;
n.nX = 1001; // is this valid?
n.next = n; // is this valid?

if Node class is moved from the global namespace to the private section of another class. That way, the outer class will protect the node's data.

Otherwise, nX and next should be private data, with getters to read the values and setters to validate and set the values.

Line (3) is a bad implementation for a constructor, because it leaves a new instance in a partially-initialized state (it should initialize nX, next and head, explicitly and in this specific order).

Better implementation:

explicit Node(int value = 0): nX(value), next(nullptr), head(nullptr) {}

Note regarding class API design:

You are implementing both a node (for an element of the list) and a list of nodes. You should have two classes instead of one, and the head pointer should be a member of the list, not a node:

class Node {
    int nX; Node* next;
public:
    // ... rest of node interface here
};

class List {
    Node *head;
public:
    List() {}
    const std::size_t size() const;
    void add_value_end(int value);
    // ... rest of interface here
};

Eventually, you should consider using node as an internal structure of the list:

class List {
    class Node { /* same as above */ };
    Node *head;
public:
    // same as above
};


Checking if a number is a perfect square (without Math)

You could make use of the fact that n² = the sum of the first n odd numbers (for integral n ≥ 0), rather than having to compute i * i every time through the loop.


Static variable in method vs private class property

I'd go with Option #3: extract $cache and getImmutable to a new class whose sole responsibility is providing the expensive data. Whether it caches it and how should be up to the new class. This new class will look just like Option #2 but be separated from the existing class that needs the data.

This provides encapsulation and increases testability.

Update

The ideal design that allows maximal flexibility must always be weighed against the current needs. If the former may give you 4 degrees of awesomeness but you only need 1 in the current application, you are probably better off going with a design that satisfies the latter until you need those extra features.

Encapsulation doesn't need to be applied at the class level in every instance. You can apply it at the method level until you need something more complex.

What would be more complex? One controller needs the data as a PHP model while another needs the JSON, but both may be required multiple times. In this case you'll get gains by caching each form separately. Now you'll want to separate the code to produce and transform the various data representations where the JSON producer can reuse the data-model producer.

By making the JSON controller depend on the JSON producer alone, that producer is free to reuse the data-model producer, hit the database directly, or use test data provided in a fixture for unit tests. Now you're ready to separate all these concerns.

Until then, however, a static variable hidden inside a controller method is sufficient for your needs while providing a basic level of encapsulation.

In other words, go with Option #1 and call it a day.


Run time is linear, and memory usage is constant (and small), so I don't think you're going to see much improvement in either.

You might be able to make some slight improvements by using pointers in unsafe mode (see https://stackoverflow.com/questions/13179554/is-it-faster-to-access-char-in-string-via-operator-or-faster-to-access-char-i), but unless you're processing a very large number of strings this is probably not necessary.  As always, profile before and after making any optimizations!

Stylistically, there are a few improvements that could be made:

Declare your variables in separate statements.
HighestValue should be highestValue.
In CharacterValue, you don't need to break when you're returning anyway.
It would be clearer to remove the blank line between the inner if and else.
You don't need the outer if/else for the length of the string; the code inside the main case would handle a length-1 string fine.
The way the logic works, the first item doesn't have to be handled as a special case, so this could be rewritten as a for loop, which would make it (for many people) easier to read.

And one functional one - your code doesn't currently handle the string being null or empty; it should either return 0 or throw an appropriate exception in that case, depending on whether you consider that to be valid input.

So for example:

    public static int RomanToInt(string s)
    {
        if (string.IsNullOrEmpty(s))
        {
            return 0;
        }

        int highestValue = 0;
        int number = 0;

        for(int currentIndex = s.Length - 1; currentIndex >= 0; currentIndex--)
        {
            int currentValue = CharacterValue(s[currentIndex]);

            if (currentValue >= highestValue)
            {
                number += currentValue;
                highestValue = currentValue;
            }
            else
            {
                number -= currentValue;
            }
        }

        return number;
    }

    private static int CharacterValue(char c)
    {
        switch (c)
        {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default:  return 0;
        }
    }


In order to resolve the client with a GORM/Hibernate query you basically need to persist the resolved client value.

Based on your resolveClient() method I'm assuming your domain class model goes something like this:

class SomeDomainClass {
    Call prevCall
    Client client

    def resolveClient() {
        if (prevCall && prevCall.client) {
            return prevCall.client
        } else {
            return client
        }
    }
}

class Call {
    Client
}

class Client { }

If you were dealing with two properties that were in the SomeDomainClass then you'd probably be able to use a derived property. But since one of the properties in an association, a derived property won't work. Instead, you can do this:

class SomeDomainClass {
    Call prevCall
    Client client
    Client resolvedClient

    def resolveClient() {
        prevCall?.client ?: client
    }

    def beforeInsert() {
        resolvedClient = resolveClient()
    }

    def beforeUpdate() {
        resolvedClient = resolveClient()
    }
}

The new property resolvedClient, which is maintained by the beforeInsert() and beforeUpdate() methods, takes care of saving the current resolved client to the GORM store (database). With that value persisted you can use it in GORM queries:

def instances = SomeDomainClass.where {
    resolvedClient == someClient
}.list()

On the Groovy side, it would still be best to use the resolveClient() method because the resolvedClient property can get out of sync if prevCall changes.

def client = instance.resolveClient()


Racing promises and consuming them in the order of their resolution time

Issues
Lost resolution
You are issuing promises without a guarantee of being able to handle all or some of the resolving promises.
This will happen if promises resolve before you start the for await loop.
The offending code is in the line this.forEach(p => p.then(v => this.#resolve(v), e => this.#reject(e)));
The calls to this.#resolve and this.#reject require that the asyncIterator is run so that this.#resolve and this.#reject are assigned functions. If not they are undefined when a promise resolves.
It is also possible for a promise to overwrite the previous promise's resolved value without the iterator getting to see the value.
For example:

if you delay the call to sink(); with setTimeout(sink, 4000) none of the promises are handled within the function sink. The results are lost and can not be retrieved

If the iterator awaits content that allows more than one of the iterateable promises to resolve between iterations.
Example the following function loses the second promise. (given your test data)

async function sink() {
    const p = new Promise(v=>setTimeout(v, 1200, "zz"))
    for await (const value of sortedPS){
       log(value);
       log(await p);
    };
};

Silencing errors!
Never silence errors that are not your responsibility.
You do this in the line:
super(...args.filter(p => Object(p).constructor === Promise)); // Make sure everybody is a Promise

Either throw an error or let the error happen naturally. If your code can not function correctly with the given arguments then throw
Example of vetting and throwing error:
constructor(...promises){
    super(...promises);
    if (promises.some(promise => !(promise instanceof Promise))) {
        throw new RangeError("Array can only contain Promises");
    }

Poor inheritance
You extend Array yet neglect to handle any of the inherited functions or properties.
For example one would expect that SortedPromisesArray.push would add a promise that will resolve. As it stands added promises are ignored.
Simple example of extending inherited function:
  push(...promises) {
      if (promises.some(promise => !(promise instanceof Promise))) {
          throw new RangeError("Array can only contain Promises");
      }
      this.#count += promises.length;
      super.push(...promises);
      promises.forEach(p => p.then(v => this.#resolve(v), e => this.#reject(e)));
  }

The same would apply to any of the inherited functions that modify the arrays content.
Arrays are independent of content
However this leaves the problem of behaviors that can not be extended without the use of a proxy. Eg sortedPS[sortedPS.length] = new Promise(...)
Without a proxy you are left with an object that has inconsistent behavior.
It is therefor not advisable to extend Arrays if behavior of the extended array is dependent on the content of the array.
Update
I have added an example RaceAll as a factory that creates an async iterate-able object that races an array of promises in order of resolution.
This is achieved by marking promises with ids and using the id of resolved promises to remove then from the race array.
It does not include any vetting, nor does it resolve rejected / failed promises (both can easily be implemented).
It does guarantee no promises are lost and does not require iteration before any promises are resolved.
function RaceAll(...promises) {
    var racing = promises.map((promise, id) => Object.assign(
            new Promise(r => promise.then(result => r({id, result}))), {id}
        ));
    return Object.freeze({
            async *[Symbol.asyncIterator]() {
                while (racing.length) {
                    const resolved = await Promise.race(racing);
                    yield resolved.result;
                    racing = racing.filter(r => r.id !== resolved.id);
                }
            }
        });
}


(codefights) check for almost increasing subsequence

Break the problem into parts.

public static int findDecreasingElement(int[] sequence) {
    for (int i = 1; i < sequence.length; i++) {
        if (sequence[i - 1] >= sequence[i]) {
            return i;
        }
    }

    return sequence.length;
}

This is mostly a simpler version of your method.  But it has a couple of differences:

If we change the i to start at 1, we don't need to subtract from sequence.length.  And while we have to subtract from i, we don't need to add to i.

This returns the number of increasing elements that were found.  Now we can

    int increasingCount = findDecreasingElement(sequence);
    if (increasingCount == sequence.length) {
        // the whole sequence is increasing
        return true;
    }

    // if increasingCount is 1, then we can't check index -1
    // but the desired relationship is true
    if (increasingCount == 1 || sequence[increasingCount - 2] < sequence[increasingCount]) {
        // the element at increasingCount - 1 is exceptionally big, so remove that
        return findDecreasingElement(sequence, increasingCount) == sequence.length;
    }

    if (sequence[increasingCount - 1] < sequence[increasingCount + 1]) {
        // The element at increasingCount is exceptionally small, so remove it
        return findDecreasingElement(sequence, increasingCount + 1) == sequence.length;
    }

    // neither removing at increasingCount - 1 nor increasingCount helps
    return false;

Now we have two simple problems.  We find the longest strictly increasing sequence from the start.  If that's the whole sequence, we're done.  If not, we check to see if we can delete either of the offending elements.  If we can, check if the remainder of the sequence is increasing.

To do that, we need a new method that is almost the same as our original method.

    public static int findDecreasingElement(int[] sequence, int start) {
        for (int i = start + 1; i < sequence.length; i++) {
            if (sequence[i - 1] >= sequence[i]) {
                return i;
            }
        }

        // if there are no decreasing elements, return the index of the end
        return sequence.length;
    }

And a helper method to replace our original method.

    public static int findDecreasingElement(int[] sequence) {
        return findDecreasingElement(sequence, 0);
    }

Now we have two method signatures but only one method doing the actual work.

These smaller methods are dead simple.  Only one if and it's pretty clear why it needs to be there.  No nesting at all.

The method that calls those methods has three if statements, but they aren't nested.

In terms of performance, this does the same linear scan as the original, just in two parts.  It scans up to the first decreasing element, then it tries to scan the rest of the array.  So except for those elements right around the decreasing element, it only scans each element twice (once to compare it to the previous element and once to compare it to the succeeding element).


Return whether the cards can be rearranged

The answer is "yes" it is UB. To fix it just rewrite the part as:
if(it->second==0)
{
    it = _m.erase(it);
}
else
{
     it++;
}


I was about to submit this when I saw that you had visited #perl6. I'll leave this post as is because it is supposed to help others that might one day read this as well as you.

TL;DR I recommend you: make sure you're ready for an immature compiler, ecosystem, doc, etc; use Rakudo Star and the Rakudo debugger; start small and take small steps, making each step work before moving forward; rely very heavily on #perl6 -- they welcome any and all comers, including "newbies" and lots of basic questions.

First, let me make sure you are not wasting your time due to wrong expectations. I am pretty sure there are currently only a handful of folk using P6 in production and they are doing so for only a small range of use cases. Powerful parsing is one of them, so what you are attempting is reasonable, but it's slow and you need to be willing to patiently deal with the many other frustrations that can result from P6's immaturity. If this hasn't put you off, welcome aboard! :)

Second, let me make sure I am not wasting your time. Your code doesn't compile using the tools I'm using. I used a procedure you can repeat to test your code with the latest Rakudo Perl 6 compiler HEAD:

I joined #perl6, the freenode IRC channel. (A very friendly channel. All are welcome.)
I tested code by entering a line of the form "m: ...". (Replace the "..." with code, or a suitable "pastebin" URL as explained below, otherwise you'll get a "Stub code executed" exception. An evalbot spots such lines, runs the code using the HEAD of the Rakudo compiler using the MoarVM backend, and displays the result.)
I ran your code privately (recommended if you don't want to "spam" the channel with attempts that aren't interesting to others) so you won't be able to see this in the public IRC log. To run code privately enter the command /msg camelia r: say $*PERL, switch to the "camelia" window, and enter lines there.
So I entered "m: https://gist.github.com/raiph/11084741" which attempted to compile a copy of your code. It failed to compile.

Third, let's radically improve your debugging options. One option when debugging grammars is to use the Grammar::Tracer module. This is occasionally useful but for most purposes there's a much better option: Rakudo's good-trending-great debugger. Use the debugger all the time unless you have a compelling reason not to. The Rakudo debugger is not available using the on channel evalbots I just discussed above; it requires that you install something. I recommend the Rakudo Star package unless you have a compelling reason to use something else. Rakudo Star includes the debugger, modules, and doc including info on how to start the debugger.

Fourth, start simple and build up from there, only making another small step forward when what you currently have works. For example, a first step might be:

say so '#define foo [blah]' ~~ rule { '#define' <ident> .* }

prints:

True

meaning the string on the left of the ~~ was "accepted" by the thing on the right.

The thing on the right is a rule which is one of several convenient forms of regex introduced by P6. The P6 regex engine never backtracks once it's matched an atom in a rule and it replaces appropriate spaces in your rule with implicit calls to the whitespace matching rule called <ws>. The above line is equivalent to:

say so '#define foo [blah]' ~~ regex { :ratchet '#define' <.ws> <ident> <.ws> .* }

(The . in <.ws> tells P6 to call the <ws> rule without saving the text it matched in the match object being built up by the processing of the regex.)


Style wise, the assignment currRes = currRes.next; happens no matter what, so lift it out of if-else clause:

            if (l1.val < l2.val)
            {
                currRes.next = l1;
                l1 = l1.next;
            }
            else
            {
                currRes.next = l2;
                l2 = l2.next;
            }
            currRes = currRes.next;

Correctness wise, the condition if (l1.val < l2.val) loses the stability: if the elements compare equal, the one from l2 is merged first. Consider if (l1.val <= l2.val) (or even if (l2.val < l2.val)) instead. It is not required by the problem statement, and it doesn't matter for ints. In real life however the stability is of utmost importance, and as an interviewer I'd definitely mark it.

On the bright side, a dummy head for the merged list is a right way to go.


Java generics, convert nested list to array

I'd use guard clauses to check whether the list parameter is null or not. Furthermore, the list.size() > 0 check looks unnecessary in the first two methods, the result will be same if you omit it.

Anyway, are you sure that null is an acceptable parameter here? Wouldn't it better to throw an exception in this case?

public static <E> int getNestedListMaxSize(final List<List<E>> list) {
    if (list == null) {
        return 0;
    }
    int result = 0;
    for (final List<E> innerList: list) {
        if (innerList == null) {
            continue;
        }
        result = Math.max(result, innerList.size());
    }
    return result;
}

In the getNestedListClass I'd use guard clauses too and a return instead of the break.

@SuppressWarnings("rawtypes")
public static <E> Class getNestedListClass(final List<List<E>> list) {
    if (list == null) {
        return null;
    }

    for (final List<E> innerList: list) {
        if (innerList == null || innerList.isEmpty()) {
            continue;
        }
        return innerList.get(0).getClass();
    }
    return null;
}

I think the return makes the code much easier to read and follow.

In the convertNestedList method

the dummy variable should have a meaningful name, for example innerListArray,
the default value of result[i] is null, so you don't have to set it to null explicitly if the inner list is null,
list.get(i) is called three times. It could have a local variable.

public static <E> E[][] convertNestedList(final List<List<E>> list) {
    final Class<?> clazz = getNestedListClass(list);
    if (clazz == null) {
        return null;
    }
    final E[][] result = (E[][]) Array.newInstance(clazz, list.size(),
        getNestedListMaxSize(list));

    for (int i = 0; i < list.size(); i++) {
        final List<E> innerList = list.get(i);
        if (innerList == null) {
            continue;
        }
        final E[] innerListArray = (E[]) Array.newInstance(clazz, innerList.size());
        result[i] = innerList.toArray(innerListArray);
    }
    return result;
}

The main method should be a unit test method with proper assert calls:

@Test
public void testConvertNestedList() {
    final List<List<String>> list = new ArrayList<List<String>>();
    list.add(new ArrayList<String>());
    list.get(list.size() - 1).add("0.0");
    list.get(list.size() - 1).add("0.1");
    list.get(list.size() - 1).add("0.2");
    list.add(new ArrayList<String>());
    list.get(list.size() - 1).add("1.0");
    list.get(list.size() - 1).add("1.1");
    list.get(list.size() - 1).add("1.2");
    list.get(list.size() - 1).add("1.3");
    list.add(new ArrayList<String>());
    list.get(list.size() - 1).add("2.0");
    list.get(list.size() - 1).add("2.1");

    final String[][] array = ListConvert.convertNestedList(list);

    // @formatter:off
    final String[][] expected = new String[][] {
            { "0.0", "0.1", "0.2" },
            { "1.0", "1.1", "1.2", "1.3" },
            { "2.0", "2.1" } };
    // @formatter:on
    assertArrayEquals(expected, array);
}

It helps detecting regressions.


Extract specific positions from a char array

I see some things that may help you improve your code.

Provide complete code to reviewers

This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.  Here's the test main I used for your code:

int main() {
    const char *input[2] = {
        "ughIuytLikeretC",
        "xxxExxxdwarxxxd",
    };
    const bool mask[] = {
        false, false, false, true, false,
        false, false, true, true, true,
        true, false, false, false, true,
    };
    char filt[100];
    char maskstr[100];
    // create the mask string
    pmask(mask, maskstr);

    printf("Orig: %s\nMask: %s\nFilt: %s\n", input[0], maskstr, filtArray(input[0], mask, filt));
    printf("Orig: %s\nMask: %s\nFilt: %s\n", input[1], maskstr, filtArray(input[1], mask, filt));
    for (int i = 0; i < 10000000; ++i) {
        int n = rand() > RAND_MAX/2 ? 1 : 0;
        printf("Orig: %s\nMask: %s\nFilt: %s\n", input[n], maskstr, filtArray(input[n], mask, filt));
    }
}

After it applies the function to two strings, it then iterates 10 million times, choosing one or the other test inputs randomly.  This is for testing timing.

Use const where practical

The filtArray function does not (and should not) alter either the passed input or mask arrays and so both of those should be declared const.

char *filtArray(const char input[], const bool mask[], char *filtered) {

Consider bounds checking

If the input strings have already been validated for length, the function you have is OK, but in general, it's good to make sure there is enough room to copy the masked characters.  If there isn't enough room, that's the recipe for a buffer overflow vulnerability and must be eliminated, either by the calling routine or by this one.

Consider a custom copy

If the same mask is used for billions of strings, it would probably make sense to do things differently.  For example, one alternative might look like this:

#include <string.h>

char *filtArray(const char input[], char *filtered) {
    memcpy(&filtered[1], &input[7], 4);
    filtered[0] = input[3];
    filtered[5] = input[14];
    filtered[6] = '\0';
    return filtered;
}

Note that the mask is no longer used in this version, because the code has implemented it implicitly.  This is less flexible but offers better performance.  For 10 million strings on my machine, your original version takes about 1.3 seconds, while the version shown here takes around 1.0 seconds (redirecting the output to /dev/null on a Linux machine).

Use pointers rather than indexing for speed

Pointers are generally a faster way to access elements than using index variables.  For example, your filtArray routine could be written like this:

char *filtArray(const char *input, const bool *mask, char *filtered) {
    char *beginning = filtered;
    for ( ; *input; ++input, ++mask) {
        if (*mask) {
            *filtered++ = *input;
        }
    }
    *filtered  = '\0';
    return beginning;
}

Because you're just beginning, this may seem strange to you, but this kind of use of pointers is a very common idiom in C.

Compilers are good, but not quite that good yet

Because there's a tendency to assume the compiler will take care of it, here's compiler output comparison of the two approaches using gcc for ARM using the on-line compiler explorer:  https://godbolt.org/z/Y0TeVX

As can be seen in this case, the generated assembly code for the pointer version is much shorter.  Shorter code is usually faster (and it is in this case according to my testing) but not always.  For those who are expert in compiler design: The typical improvement is as likely to be the elimination of extra live variables as for the use of pointers per se, but the effect is nonetheless real.

Measured timings

For each of the three variations, original, pointer, and memcpy, here are the measured times for 10 million iterations and the variances of each set of samples and the relative speed measured as the average speed compared with the average speed of the original expressed as a percentage.  With no optimization:

\$\begin{array}{l|c|c|c}
{\bf name}&{\bf avg (s)}&{\bf var (s)}&{\bf relative}\\
\hline
\text{original}&1.344&0.01853&100.00\% \\
\text{pointer}&1.244&0.01193&92.56\% \\
\text{memcpy}&0.998&0.01177&74.26\%
\end{array}\$

With -O2 optimization:

\$\begin{array}{l|c|c|c}
{\bf name}&{\bf avg (s)}&{\bf var (s)}&{\bf relative}\\
\hline
\text{original}&1.038&0.01462&100.00\% \\
\text{pointer}&1.000&0.00135&96.34\% \\
\text{memcpy}&0.948&0.00692&91.33\%
\end{array}\$

These results were on a 64-bit Linux machine using gcc version 8.2.1.  I look forward to seeing other measured timing results.  Time is user time as measured by time -f %U (See https://linux.die.net/man/1/time for man page).


Next multiple with only 1 and 0 as digit

I normally don't do C++ reviews, so I might be off on a few accounts, but here are some style and code review points.

Style and Code Review

Avoid cramped up statements – Mostly your code reads easily, but avoid stuff like if(bit%n == 0){, open it up to become if (bit % n == 0) {. Especially important since you seem to have decided on having the starting brace on the same line. It needs to stand out to be recognised. Along the same line of reasoning, add a space after commas like in the printf("...", getBitMultiple(n));
Aim for better names – Names like e, n and d are not really intuitive. Neither is bit or getBitMultiple, it is not a bit but a decimal number looking like a binary. Confusing. Maybe change bits into binaryLookingDecimals?
Add more comments – Parts of the code is unclear, like what you are aiming for in your functions, and where do you get your numbers from, and how does your while loop work
Avoid using globals – The main table of your code, bits, is a global variables. As it reads now, the generateBits() and getBitMultiple(n) are separate non-related functions. If however you add something like binaryLookingDecimals = generateBinaryLookingDecimals() and findMultiple(n, binaryLookingDecimals) they are clearly related

Edited: My solution review was based on a misunderstanding of the problem statement. As a foreigner I confused multiple/multiply/multiplicand, and thought you had done the same. Your code does however return the binary looking decimal which is a multiple of \$N\$ as requested, and that renders my previous solution void, which found the factor you need to multiply to \$N\$ to get a binary looking decimal.

The only comment I then have to your actual solution, is whether it is worth it to test whether the candidate is greater than \$N\$ before starting the modulo operation, but that has to be tested if it gives any significant speed increase. Most likely it is not worth it.

Thanks to Barry for correcting me regarding my mistake on the solution review


Code for calculating the books dispatched

There are some minor nits about the general code

Separate operators like >> with spaces, that makes the code much easier to read. Also you should separate language constructs like for or while with a space afterwards, to readily separate them from function calls.
You should use range based loops when you already have the vector fully initialized, it is much more concise.

int numBooks;
std::cin >> numBooks;
std::vector<int> books(numBooks);
for (auto &book : books){
    std::cin >> book;
}

The return 0; at the end is not necessary anymore with modern compilers.
You should prefer pre increment ++book over post increment book++, as the later involves a copy (at least for non trivial data types)
Actually your code itself is way to complicated. Rather than assigning a new vector you can just shrink the old one

int numTaken;
std::cin >> numTaken;
for (int book = 0; book < numTaken; ++book) {
    int bookId;
    std::cin >> bookId;
    std::cout << books[bookId];
    books.erase(bookId);
}

Full code

#include <iostream>
#include <vector>

int main() {
    std::ios_base::sync_with_stdio(false);
    size_t numBooks;
    std::cin >> numBooks;
    std::vector<int> books;
    books.reserve(numBooks);
    for (size_t book = 0; book < numBooks; ++book) {
        size_t bookId;
        std::cin >> bookId;
        books.push_back(bookId);
    }

    size_t numBorrowed;
    std::cin >> numBorrowed;
    for (size_t borrow = 0; borrow < numBorrowed; ++borrow) {
        size_t bookId;
        std::cin >> bookId;
        std::cout << books[bookId] << "\n";
        books.erase(bookId);
    }
}


Set of wrapper functions for POSIX signal APIs on Linux

static struct sigaction *
handle_signal(int sig,
              int flags,
              void (*handler)())
{

Two things here:

The signal handler function should have the signature void handler(int signum); [man page for sigaction] . Your compiler should — at the least — be warning you about assigning a function pointer of a different type further down.

The function returns a struct sigaction * containing the original disposition for the signal. None of the other functions shown accept a struct sigaction * as an argument, so it's not clear what you're doing with this information.
If you need this information elsewhere, I suggest passing in a struct sigaction * as an additional argument. The POSIX sigaction() API allows you to pass NULL as the third parameter, so this would leave it to the caller to decide whether or not they wanted to provide a pointer to a real struct sigaction. This also ties into the use of statically allocated structures which I address next.

static struct sigaction action;
static struct sigaction o_action;

You declare all of your <signal.h> structures with static storage class, so there is only one instance of each of them in the program's memory space. If the program using this API is multithreaded, and this API is called from multiple locations, you can overwrite the variables on one thread while they're being populated from another, causing you lots of confusion. Since the following code immediately zeros out their memory, you can remove the static from the declarations, so that they get allocated on the stack. That way if the function is called from multiple threads, they each get their own copy and don't conflict with each other.

/* init the sigaction structs */
memset(&action, 0, sizeof(action));
memset(&o_action, 0, sizeof(o_action));

/* setup our signal handler function to call when it fires */
action.sa_handler = handler;

/* initialize the signal mask */
sigemptyset(&action.sa_mask);

/* use the user passed in flags setting othersize init them */
if (flags != 0)
   action.sa_flags = flags;
else
   action.sa_flags = 0;

The else clause is taken if flags has the value 0, so action.sa_flags = 0 is equivalent to action.sa_flags = flags, so this whole if-statement could be collapsed to:
action.sa_flags = flags;

if (sigaction(sig, &action, &o_action) != 0)
   syserr();

return(&o_action);
}

Taken altogether, this function could be rewritten:
static struct sigaction *
handle_signal(int sig,
              int flags,
              void (*handler)(int),
              struct sigaction *o_action)
{
    struct sigaction action;

    memset(&action, 0, sizeof(action));
    /* Note: can't use sizeof(o_action) below because o_action is now a pointer */
    if(o_action != NULL)
        memset(o_action, 0, sizeof(action));

    /* setup our signal handler function to call when it fires */
    action.sa_handler = handler;

    /* initialize the signal mask */
    sigemptyset(&action.sa_mask);

    action.sa_flags = flags;

    if (sigaction(sig, &action, &o_action) != 0)
       syserr();

    return(o_action);
}

If you're using the original signal disposition to restore things to their defaults later on, you could potentially drop o_action altogether and install SIG_DFL as the handler for that signal.  Change the function to return void, only have the original three parameters, change the sigaction call to sigaction(sig, &action, &o_action) and remove the return statement at the end.

static struct sigaction *
ignore_signal(int sig)
{
    /* Code elided */
}

There's a lot of common code between this and handle_signal above; I'd suggest replacing the body of this function with a call to that function instead:
static struct sigaction *
ignore_signal(int sig)
{
    return handle_signal(sig, 0, SIG_IGN);
}

int
block_signal(int sig)
{
static sigset_t mask;
static sigset_t orig_mask;
int ret;

sigemptyset(&mask);
sigemptyset(&orig_mask);

sigaddset(&mask, sig);

ret = sigprocmask(SIG_BLOCK, &mask, &orig_mask);

return(ret);
}

You're not doing anything with the value of orig_mask after the return from sigprocmask(). This system call allows you to pass NULL [man page for sigprocmask], so I suggest you change it to:
ret = sigprocmask(SIG_BLOCK, &mask, NULL);

int
unblock_signal(int sig)
{
static sigset_t mask;
static sigset_t orig_mask;
int ret;

sigemptyset(&mask);
sigemptyset(&orig_mask);

sigaddset(&mask, sig);

ret = sigprocmask(SIG_UNBLOCK, &mask, &orig_mask);

return(ret);

}

Same advice about changing the sigprocmask() call as for block_signal() above. I also note that in the get_signal_mask() function below, you're calling your syserr() function if sigprocmask() fails. It seems to me that if you're exiting the program in that situation, you should also be doing it here where you're actually changing the mask, not merely querying its value.
Additionally, block_signal() and unblock_signal() differ only in the first argument to sigprocmask(), so I'd suggest refactoring the code in both functions into a single helper function that accepts the SIG_BLOCK or SIG_UNBLOCK argument.

sigset_t *
get_signal_mask()
{
static sigset_t orig_mask;

sigemptyset(&orig_mask);

/* null in set arg means return current mask */
if (sigprocmask(SIG_SETMASK, NULL, &orig_mask) < 0)
   syserr();

return(&orig_mask);

}

Again, you're returning a pointer to a statically allocated instance of sigset_t. On multithreaded programs, this can cause problems as already explained. I suggest changing it either to accept a sigset_t * argument, so that the caller must provide the instance to populate (this is the more C-like way of doing it):
sigset_t *
get_signal_mask(sigset_t *orig_mask)
{
    sigemptyset(orig_mask);
    /* null in set arg means return current mask */
    if (sigprocmask(SIG_SETMASK, NULL, orig_mask) < 0)
       syserr();

    return(orig_mask);
}

OR have the function return the sigset_t by value and remove the static from the declaration of orig_mask (this is the more C++-like way of doing it):
sigset_t
get_signal_mask()
{
    sigset_t orig_mask;
    sigemptyset(&orig_mask);

    /* null in set arg means return current mask */
    if (sigprocmask(SIG_SETMASK, NULL, &orig_mask) < 0)
       syserr();

    return(orig_mask);
}

Both methods are valid in both languages, so whichever you prefer.


Getting the smallest possible integer ratio between two numbers

You need to find the GCD and then divide both numbers by that.

Euclid's algorithm is the classic way to do this.

int gcd(int p, int q) {
    if (q == 0) return p;
    else return gcd(q, p % q);
}

void ratio(int a, int b) {
   final int gcd = gcd(a,b);
   System.out.println(a/gcd + " " + b/gcd);
}

If you want to swap a and b to have the biggest first then that's easy too

void ratio(int a, int b) {
   final int gcd = gcd(a,b);
   if(a > b) {
       showAnswer(a/gcd, b/gcd);
   } else {
       showAnswer(b/gcd, a/gcd);
   }
}

void showAnswer(int a, int b) {
   System.out.println(a + " " + b);
}


Handling combinations of optional parameters for an Angular filter pipe

Direction

My approach would be based on the Strategy design pattern. Each of the original if-elseif-elseif-... sections is now becoming an IRule object that represents the rule. This object does two things:

A) It defines whether it may or may not be applied to the given filter input;

B) It defines the application function (logic) itself.

In order to select a proper rule dynamically in run time, we need a registry of the rules which is implemented as a simple array.

Benefits

Implementation of a new "rule" becomes almost trivial: we'll need to create a rule object itself, and add it to a proper place in the list of registry entries, so that it's picked up.

Code

import { Pipe, PipeTransform } from "@angular/core";

const ALL = "Show all";
const BLANK = "";

/**
 * Represents a contract of a single rule.
 */
interface IRule {
    /**
     * A predicate that sayw whether the rule may or may not be applied to a value based on the filter.
     */
    isApplicableTo(filters: Object[]): boolean;

    /**
     * Implementation of rule applied to a value based on filter parameters.
     */
    applyTo(filters: Object[], value: any): boolean;
}

/**
 * The complete list of rules that your system supports.
 * NOTICE that the order of the rule is important.
 * If more than one rule is applicable to a filters object,
 * the very first applicable rule is applied.
 */
const RULES_REGISTRY: IRule[] = [
    new AllMatchingRegexRule(),
    new MatchingStatusRule(),
    new SomeMatchingRegexRule()
];

/**
 * Three sample rules based on your original code.
 */

class AllMatchingRegexRule implements IRule {
    isApplicableTo(filters: Object[]): boolean {
        const safeFilters = getSafeFilters(filters);
        return isAllFilter(safeFilters) && isNotBlankFilter(safeFilters);
    }

    applyTo(filters: Object[], value: any): boolean {
        return descriptionRegexMatched(filters[1], value);
    }
}

class MatchingStatusRule implements IRule {
    isApplicableTo(filters: Object[]): boolean {
        const safeFilters = getSafeFilters(filters);
        return isNotAllFilter(safeFilters) && isBlankFilter(safeFilters);
    }

    applyTo(filters: Object[], value: any): boolean {
        return statusMatches(filters, value);
    }
}

class SomeMatchingRegexRule implements IRule {
    isApplicableTo(filters: Object[]): boolean {
        const safeFilters = getSafeFilters(filters);
        return isNotAllFilter(safeFilters) && isNotBlankFilter(safeFilters);
    }

    applyTo(filters: Object[], value: any): boolean {
        return value.status === filters[0] && descriptionRegexMatched(filters[1], value);;
    }
}

// Reusable working horse lambdas (use in Rules)

const getSafeFilters = (filters: Object[]) => filters && filters.length >= 2 ? filters : new Object[2];

const descriptionRegexMatched = (pattern: any, value: any) => new RegExp(pattern, 'gi').test(value['part']['description']);

const statusMatches = (filters: Object[], value: any) => value.status === filters[0];

const isAllFilter = (filters: Object[]) => filters[0] === ALL;
const isNotAllFilter = (filters: Object[]) => !isAllFilter(filters);

const isBlankFilter = (filters: Object[]) => filters[1] === BLANK;
const isNotBlankFilter = (filters: Object[]) => !isBlankFilter(filters);

Consuming code (that uses the Rule registry)

Now your filter can be implemented like this:

@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform {

    transform(values: any, type: string, ...filters: Object[]): any {
        switch (type) {
            case 'MAINTENANCE_EVENT':
                if (filters.length !== 2) {
                    throw new SyntaxError('MAINTENANCE_EVENT requires exactly 2 filter parameters: <string>status and <string>description')
                }

                if (isAllFilter(filters) && isNotBlankFilter(filters)) {
                    return values;
                } else {
                    return values.filter(value => {
                        const ruleToApply = RULES_REGISTRY.find(rule => rule.isApplicableTo(filters));

                        if (!ruleToApply) {
                            throw new Error("Attempting to filter by properties not present in available <MaintenanceEvent>s");
                        }

                        return ruleToApply.applyTo(filters, value);
                    });
                }

            default:
                return values;
        }
    }
}

Disclaimer

I am very new to TypeScript so I may be using wrong idioms. The key in my answer is the design change, rather than implementation details.

P.S.

Notice that the same approach may be applied to type == 'MAINTENANCE_EVENT' 'OTHER_EVENT' .... And, speaking more generally, Strategy design pattern is almost always a working alternative to an if or switch. Of course, to get the benefits of the pattern, we need to write some boilerplate code (IRule + Rule registry), however it's a great trade of for the scenarios where there are a lot of rules, or the rules are frequently added/modified, or the rule selection strategy may change in run time.


For proper recursive 'style', you shouldn't use a for-loop inside the function. Each pass through the function should perform one test and then set up the next pass. This also frees you from needing to track the index as an argument.

Consider that:

contains("hello", "lo") ==
contains("ello", "lo") ==
contains("llo", "lo") ==
contains("lo", "lo")


Get all members from country depending on multiple tables

Here's a more compact formulation (SQL Fiddle):

SELECT DISTINCT user.name, address.country
    FROM orga2Address
        INNER JOIN orga2User
            ON orga2User.idOrga = orga2Address.idOrga
        RIGHT OUTER JOIN user
            ON user.id = orga2User.idUser
        INNER JOIN address
            ON address.id IN (user.idAddress, orga2Address.idAddress)
    WHERE address.country = 'DE';

The trick is, instead of UNION, perform a JOIN with more than one join path.  (We unfortunately need to use DISTINCT, but that is no worse than your UNION, which also de-duplicates results.)

In addition, I suggest:

formatting your code with better indentation.  In this example, the SELECT statement has a FROM clause and a WHERE clause.  The FROM clause has multiple JOINs, each of which has an ON clause.
using single quotes for string literals like 'DE', which is standard ANSI SQL.  Using double quotes for strings is a MySQLism, and it fails if SQL_MODE = 'ANSI_QUOTES' is in force.
avoid overdoing the `quotes`.  If you didn't need them in your CREATE TABLE statements, you don't need them in your query either.


Indententation

Normally code is indented between { and }

int main()
{
    // Start here
}

Namespace

Never Do this.

using namespace std;

If you had read any other C++ review on this board it would have told you not to do this. See: Why is “using namespace std” in C++ considered bad practice?.

There is a reason that the standard libraries are called std and not standard. Its to make prefixing them easy.

Rand

Though your use of srand() and rand() is perfectly valid. This version of the random number generated is now obsolete. You should look up how to use the new random number functionality provided by C++11.

https://stackoverflow.com/a/14009667/14065
https://stackoverflow.com/a/19666713/14065

Note:

int computerNumber = rand() % 3 + 1;

This is slightly biased against 3. Assume RAND_MAX is 32768.

If you rolled 32768 times. Then your distribution would be.

1 10923/32768
2 10923/32768
3 10922/32768  <- Notice this is one smaller.

Invalid:

} else {
    std::cout << "Congrats! You won!" << endl;
}

Do you really want to have an invalid choice. You have already enumerated all the valid choices. If you get to this point there is a serious error in your code. So you need to indicate this (so you can catch it in testing).

else
{
    throw std::runtime_error("Error");
}

Data Driven Programming

Rather than write code to decide the winner:

if(computerChoice == "rock" && userChoice == "rock") {
    std::cout << "It was a tie!" << endl;
} else if (computerChoice == "rock" && userChoice == "scissors") {
    std::cout << "The computer won! Better luck next time!" << endl;
} else if (computerChoice == "paper" && userChoice == "paper") {
    std::cout << "It was a tie!" << endl;
} else if (computerChoice == "paper" && userChoice == "rock") {
    std::cout << "The computer won! Better luck next time!" << endl;
} else if (computerChoice == "scissors" && userChoice == "scissors") {
    std::cout << "It was a tie!" << endl;
} else if (computerChoice == "scissors" && userChoice == "paper") {
    std::cout << "The computer won! Better luck next time!" << endl;
} else {
    std::cout << "Congrats! You won!" << endl;
}

Use a data structure. Assume you translate the choices into a number for each user.

0 -> rock
1 -> paper
2 -> scissor

// This array decides if who is the winner.
// 0 => Draw.
// 1 => Player 1
// 2 => Player 2
int winner[3][3] = {{0, 2, 1},
                    {1, 0, 2},
                    {2, 1, 0}};

// Then to decide the winner.
int theWinner = winner[player1Choice][player2Choice];

Advice

  In particular I couldn't find an efficient way to implement a play again feature.

To make things like retrying the code you need to start using functions so that you can logically compartmentalize your code.

int main()
{
    std::string name = getPlayerName();
    do
    {
        int player1 = getComputerMove();
        int player2 = getPlayerMove();
        displayWinner(player1, player2);
    }
    while(doesPlayerWantToContinue());
}


You are doing it wrong.

Why are you using WCF if you are only using it as an old timer ASMX service without using the extensibility points?

First things first - clean up

[ServiceContract]
public interface IWorkingService
{
    [OperationContract]
    Collection<Ergebnis> UpdateEntity(int entityId);
}

The service interface is the same as yours, but:

Why are you using Collection<T> as the return type? Use someting more generic.
Do not use primitives as service parameters, ever! Using primitives as parameters means that you cannot versionize your service, such as adding extra non-required properties.

public class WorkingService : IWorkingService
{
    private readonly NotStaticFacade _notStaticFacade;

    public WorkingService(NotStaticFacade notStaticFacade)
    {
        _notStaticFacade = notStaticFacade;
    }

    public Collection<Ergebnis> UpdateEntity(int entityId)
    {
        return _notStaticFacade.UpdateEntity(entityId);
    }
}

The service implementation is much more slimmer then yours because it's missing the logging stuff (be patient!). The important thing is that it isn't containing a parameter-less constructor because the service has a dependency: the NotStaticService (in your code this is the static CoreFacade). What does this mean? We will need a custom ServiceHostFactory because the default one cannot handle these kinds of situation, but don't worry; Ninject is with us!

Install-Package Ninject.Extensions.Wcf

The Ninject has an extension for WCF so install it via NuGet (remove App_Start directory after installation) and after that, create our own ServiceHostFactory:

public class WorkingServiceHostFactoryWithNinject :    NinjectServiceHostFactory
{
    private readonly IKernel _kernel;

    public WorkingServiceHostFactoryWithNinject()
    {
        _kernel = new StandardKernel(new WorkingServiceNinjectModule());

        // SetKernel is a static method in Ninject WCF!
        SetKernel(_kernel);
    }
}

Nothing fancy; we only telling the factory which IKernel instance we want to use. As you see, you will have a NinjectModule prepared to map the bindings.

public class WorkingServiceNinjectModule : NinjectModule
{
    public override void Load()
    {
        // what ever other binding is need
        Kernel.Bind<NotStaticFacade>().ToSelf();
    }
}

I'm only telling the kernel how to resolve the NotStaticFacade but this isn't necessary this way. We haven't finished yet because we haven't told the system to use our factory to build up our service. To do this, we need to open the *.svc markup (right-click on the file then View markup) and write into the directive the Factory attribute:

<%@ ServiceHost Language="C#" Debug="true" Service="CodeReview.WorkingService" CodeBehind="WorkingService.svc.cs"
        Factory="CodeReview.WorkingServiceHostFactoryWithNinject" %>

Save and close this.

Now we have a service with dependency injection and the only one real facade is our service.

WCF extensibility - IServiceBehavior, IErrorHandler

The WCF infrastructure has great possibilities for extending its capabilities, such as handling an error!

To do that we will create a new service behavior and we will use it for adding our error handlers to the service:

public class ErrorHandlerBehaviorWithNinjectKernel : IServiceBehavior
{
    private readonly IKernel _kernel;

    public ErrorHandlerBehaviorWithNinjectKernel(IKernel kernel)
    {
        _kernel = kernel;
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints,
        BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        var errorHandlers = _kernel.GetAll<IErrorHandler>().ToArray();

        if (!errorHandlers.Any())
        {
            throw new Exception("No errorhandler was found");
        }

        foreach (var channelDispatcher in serviceHostBase.ChannelDispatchers.Select(channelDispatcherBase => channelDispatcherBase as ChannelDispatcher))
        {
            foreach (var errorHandler in errorHandlers)
            {
                channelDispatcher.ErrorHandlers.Add(errorHandler);
            }
        }
    }
}

What can we see here? We are adding all IErrorHandler instance to all possible dispatchers to use it. IErrorHandler is coming from the WCF infrastructure. You need to create your own implementation of it like this:

public class ErrorLogger : IErrorHandler
{
    private readonly IAmLogger _logger;

    public ErrorLogger(IAmLogger logger)
    {
        _logger = logger;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        //nothing to do here
    }

    public bool HandleError(Exception error)
    {
        _logger.Fatal(error);

        return true;
    }
}

I have created the IAmLogger interface to fake your Log4Net stuff, nothing more:

public interface IAmLogger
{
    void Info(string info);
    void Fatal(Exception exception);
}

If you have created your IErrorHandler implementation, register it in your NinjectModule:

Kernel.Bind<IErrorHandler>().To<ErrorLogger>();

There are two ways to add an IServiceBehavior to a service: view attributes (then our class have to derive from Attribute) and programatically.
We will use the last one because of the IKernel dependency.

Let's bring up the factory again and extend it with overriding the CreateServiceHost method:

public class WorkingServiceHostFactoryWithNinject : NinjectServiceHostFactory
{
    private readonly IKernel _kernel;

    public WorkingServiceHostFactoryWithNinject()
    {
        _kernel = new StandardKernel(new WorkingServiceNinjectModule());

        // SetKernel is a static method in Ninject WCF!
        SetKernel(_kernel);
    }

    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        var serviceHost = base.CreateServiceHost(serviceType, baseAddresses);

        serviceHost.Description.Behaviors.Add(new ErrorHandlerBehaviorWithNinjectKernel(_kernel));

        return serviceHost;
    }
}

Now we are creating the ServiceHost and after that we are adding our behavior (ErrorHandlerBehaviorWithNinjectKernel) to it. That is how every exception in the system will be logged and we don't need to write anything into our service.

Logging operation calls - IOperationInvoker, IOperationBehavior

In WCF we can specify our own Operation invoker by implementing the IOperationInvoker interface and applying it to our operations via an IOperationBehavior instance inside a service behavior instance. (That's all, really!)

First create an IOperationLogger implementation:

public class OperationInvokerWithLogging : IOperationInvoker
{
    private readonly IAmLogger _logger;
    private readonly IOperationInvoker _invoker;
    private readonly DispatchOperation _dispatchOperation;

    public OperationInvokerWithLogging(IAmLogger logger, IOperationInvoker invoker, DispatchOperation dispatchOperation)
    {
        _logger = logger;
        _invoker = invoker;
        _dispatchOperation = dispatchOperation;
    }

    public object[] AllocateInputs()
    {
        return _invoker.AllocateInputs();
    }

    public object Invoke(object instance, object[] inputs, out object[] outputs)
    {
        _logger.Info(string.Format("Operation {0} called (Invoke)", _dispatchOperation.Name));
        return _invoker.Invoke(instance, inputs, out outputs);
    }

    public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
    {
        _logger.Info(string.Format("Operation {0} called (InvokeBegin)", _dispatchOperation.Name));
        return _invoker.InvokeBegin(instance, inputs, callback, state);
    }

    public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
    {
        _logger.Info(string.Format("Operation {0} called (InvokeEnd)", _dispatchOperation.Name));
        return _invoker.InvokeEnd(instance, out outputs, result);
    }

    public bool IsSynchronous { get { return _invoker.IsSynchronous; } }
}

This is mostly a stub for the real IOperationInvoker what comes from the WCF infrastructure (we will see it soon). The only additional mechism is the logging parts (with out IAmLogger instance!).

Let's create our IOperationBehavior implementation; this will map the IOperationInvoker to all of our operations:

public class LoggingOperationBehaviorWithNinjectKernel : IOperationBehavior
{
    private readonly IKernel _kernel;

    public LoggingOperationBehaviorWithNinjectKernel(IKernel kernel)
    {
        _kernel = kernel;
    }

    public void Validate(OperationDescription operationDescription)
    {

    }

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        dispatchOperation.Invoker = new OperationInvokerWithLogging(_kernel.Get<IAmLogger>(), dispatchOperation.Invoker, dispatchOperation);
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {

    }

    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {

    }
}

Only mapping the invoker, nothing more except that we are resolving the IAmInvoker with Ninject.

Now we need a service behavior to apply the operation behavior to our service like the error handling stuff:

public class ServiceLoggingBehavior : IServiceBehavior
{
    private readonly IKernel _kernel;

    public ServiceLoggingBehavior(IKernel kernel)
    {
        _kernel = kernel;
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints,
        BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (var operation in serviceDescription.Endpoints.SelectMany(endpoint => endpoint.Contract.Operations))
        {
            operation.Behaviors.Add(new LoggingOperationBehaviorWithNinjectKernel(_kernel));
        }
    }
}

More or less the same as above nothing new here, map it in our factory and lets see what we have got:

public class WorkingServiceHostFactoryWithNinject : NinjectServiceHostFactory
{
    private readonly IKernel _kernel;

    public WorkingServiceHostFactoryWithNinject()
    {
        _kernel = new StandardKernel(new WorkingServiceNinjectModule());

        // SetKernel is a static method in Ninject WCF!
        SetKernel(_kernel);
    }

    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        var serviceHost = base.CreateServiceHost(serviceType, baseAddresses);

        serviceHost.Description.Behaviors.Add(new ErrorHandlerBehaviorWithNinjectKernel(_kernel));
        serviceHost.Description.Behaviors.Add(new ServiceLoggingBehavior(_kernel));

        return serviceHost;
    }
}

Pretty clear stuff and still no extra code in our service implementation!

About unit testing

As the others mentioned above, we are not really unit testing service implementations because, as you see, it contains a lot of infrastructure stuff in it. These are small parts which can be tested but mostly it isn't worth it.

Now you only have to test your NotStaticFacade class and not the service itself because it's just a stub. Of course it can contain code parts which are needed to be tested (for example the service using EF entities and transforms them to DTO instances) but now you can test these thing simpler:

Create an interface for the NotStaticFacade so you can fake it out with a simple implementation and modify your service constructor to accept the interface (ICoreStuff or whatever) not the concrete implementation. If you created a stub for the interface you can have unit tests to check your service output.

And of course you can still have integration tests to check the whole service behavior and in those tests you can set up different or no logger for example.

I'm not sure the things above will work as the way they are because I haven't tested it, but the main implementation steps are covered in the code examples.


Using singleton pattern for a MySQL connection

First, on your premises.

First of all, no pattern would prevent PHP from making a connection to MySQL database on every web api call. Because PHP will die between different API calls, along with all its singletons, connections and any other stuff. So all you can prevent is reconnecting the MySQL database on every call to a database connection class.
No, it is frowned upon using singleton pattern to prevent reconnecting the MySQL database on every call to a database connection class. A more accepted approach is Dependency Injection.
Funny enough, due to a typo, this class would not prevent reconnecting the mysql. Had you error_reporting set to E_ALL, PHP would have signaled that you are trying to use a non-existent variable $connection every time getInstance() is called. Surely you wanted to call it as $this->connection instead.

Now to the code.

The intention is very good, especially I like getResult() and execute() methods that allow you to avoid that bind param hassle. However, there is evidently a duplicated code. Why not to make execute to return $statement? It will let you make getResult() as simple as

public function getResult(string $sql, iterable $params) : mysqli_result
{
    return $this->execute($sql, $params)->get_result();
}

And finally. I just noticed, halfway the review process, that your code is off topic, as it simply doesn't work. Mysqli is not PDO, you cannot bind your parameters in a loop. So you need to rework it. In order to help, here are two my articles:

How to properly connect to Mysql database using mysqli that will show you important options missed in your connection code
Mysqli made simple to show you how to bind parameters for mysqli dynamically


If I'm right it's not thread-safe. I suppose two browsers with the same username could login at the same time which means that the AuthenticateUser method runs parallel on two threads.

Suppose the following:

the user already has an invalid login attempt,
two new threads enter AddInvalidLoginToCache the same time,
invalidLoginThresholdFromConfig = 2.

A possible execution order is the following:

// InvalidLoginTimestamp.Count = 1, we already have an invalid login attempt
thread1: enters AddInvalidLoginToCache
thread2: enters AddInvalidLoginToCache
thread1: runs invalidLogin.InvalidLoginTimestamp.Add(DateTime.Now); // InvalidLoginTimestamp.Count = 2
thread2: runs invalidLogin.InvalidLoginTimestamp.Add(DateTime.Now); // InvalidLoginTimestamp.Count = 3
thread1: runs if (invalidLogin.InvalidLoginTimestamp.Count == 2)) // false
thread2: runs if (invalidLogin.InvalidLoginTimestamp.Count == 2)) // false

The result is that a lucky attacker will never be locked out.

The second problem is visibility. Since InvalidLoginTimestamp and invalidLogin are shared between threads you need some synchronization to ensure other threads will see modifications (not just stale data or invalid state).

C# multi-threading: Acquire read lock necessary?
How to synchronize the access to a List used in ASP.NET?

private readonly ObjectCache cacheInvalidLogins = MemoryCache.Default; //Cache to hold Invalid Login Attempts: {UserId, obj UserLogin}

I'd put the comment before the line to avoid horizontal scrolling:

//Cache to hold Invalid Login Attempts: {UserId, obj UserLogin}
private readonly ObjectCache cacheInvalidLogins = MemoryCache.Default;

Furthermore, I'd rename it to invalidLoginAttemptsCache. The cacheInvalidLogins name looks like a method name since it starts with a verb (cache...).

bool validCredentials = false;
... // other statements
try
{
    validCredentials = securityService.Authenticate(userName, password);

The boolean could be declared right before the first use with a smaller scope:

...  // other statements
bool validCredentials = false;
try
{
    validCredentials = securityService.Authenticate(userName, password);

Should I declare variables as close as possible to the scope where they will be used?

private void AddInvalidLoginToCache(string userName)
{
    ...
    cacheInvalidLogins.Set(userName.ToUpper(), invalidLogin, LockOutCachePolicyFromConfig());

The code calls this method with the uppercased username. I'd rename the parameter to upperCasedUserName and remove the .ToUpper() call.
This variable is never user, I guess you could remove it:

string clientId = userName.Split('\\')[0];

Username seems to be one word, I'd not capitalize the n.


Linked List class based implementation in Python

First, there are some awkwardnesses in your code:

You should not use next as a variable because, it is a built-in function.
The getContents function is useless, because contents is a public attribute.
Your print_list method is ill-formed, you need to use self.

You can simplify like this:

class Node:
    def __init__(self,contents=None, next_node=None):
        self.contents = contents
        self.next_node = next_node

    def __str__(self):
        return str(self.contents)

    def print_list(self):
        node = self
        while node is not None:
            print(node.contents)
            node = node.next_node
        print()

To test your code, you can use the Unit Testing Framework, for instance:

import unittest

class TestNode(unittest.TestCase):

    def test_construcor(self):
        node1 = Node("A")
        node2 = Node("C")
        node3 = Node("D")
        node4 = Node("B")
        # Define the pointers for each node (e.g. follow through A to B to C to D)
        node1.next_node = node4
        node4.next_node = node2
        node2.next_node = node3
        node1.print_list()
        self.assertEqual(node1.next_node.contents, 'B')

if __name__ == '__main__':
    unittest.main()


Undefined behavior from signed overflow
Technically, your first line causes undefined behavior:

int sum = x + y;

It should be written instead as:
int sum = (unsigned int) x + y;

In C, signed integer overflow is undefined behavior but unsigned integer overflow is not.  Your compiler probably will treat the two lines above identically, but to be safe you should use the unsigned add.
Save a couple of instructions
This line here could be optimized:

int mask = (~(x ^ y) & (y ^ sum) & (x ^ sum)) >> w;

to this:
int mask = (~(x ^ y) & (x ^ sum)) >> w;

If x and y have the same sign, then you only need to check one of them against sum instead of both of them.  This saves 2 assembly instructions when you compile it.


Solve binomial coefficient without lookup

A review of the first 5 lines
Only looking at the code related to the problem and ignoring the testing code as it looks haphazardly put together.
Thus

const MAX_BASES = 10;
const range = n => new Array(MAX_BASES).fill(0);
const binomialCoefficient = n => (Math.pow(n, 2) + n) / 2;
const baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i));
const toBase = n => baseMax.indexOf([...baseMax].reverse().find(max => n > max)) + 1;

Minor point
You should use the operator ** (Exponentiation) rather than the math function Math.pow . Both ** and Math.pow use the same pow function under the hood so there is no performance difference, however ** is cleaner.
The bad part
The only thing that is bad in your code, even assuming you are forced to lookup the values, is that every time you call toBase you recreate the array, reverse it, and then search it.
To get the correct value subtract the index from the arrays length. There is an edge case when the input is 0. That can be handled with a ternary.
You only need to reverse the array once.
 const baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i)).reverse();

Subtract the index from the arrays length to get the result you are after. The edge case n = 0 can be handled with a ternary.
 const toBase = n => !n ? 0 : baseMax.length - baseMax.indexOf(baseMax.find(max => n > max));

Rather than use Array.find you can use Array.findIndex This will save you having to search the array twice, once to find the value n <= max then again to find the index with Array.indexOf
Thus you get
 const toBase = n => !n ? 0 : baseMax.length - baseMax.findIndex(max => n > max);

And you don't need to reverse the array which makes it even simpler
 const baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i));
 const toBase = n => !n ? 0 : baseMax.findIndex(max => n <= max);

A functional solution.
The function (n ** 2 + n) / 2 is a quadratic \$\frac{1}2n^2 + \frac{1}2n + 0 = y\$
You can solve the quadratic when \$y=0\$ using \$\begin{array}{*{20}c} {x = \frac{{ - b \pm \sqrt {b^2 - 4ac} }}{{2a}}} \\ \end{array}\$
However as we change \$n\$ the solution we are after is no longer at \$y = 0\$
If we move the parabola down so that \$y\$ is at 0 for the value \$n\$ we are solving for we can then solve for any value of \$n\$
The quadratic to solve is \$\frac{1}2x^2 + \frac{1}2x - n = 0\$
\$ {x=\frac{{-\frac{1}2+\sqrt{\frac{1}4-4*\frac{1}2*-n} }}{{2*\frac{1}2}}}\$
which is
\$x=-\frac{1}2+\sqrt{\frac{1}4+2n} \$
Now we get \$x\$ for \$n\$ and round it up when \$x\$ is a fraction.
The rewrite
An thus the 5 lines become one line.
const toBase = n => Math.ceil(-0.5 + (0.25 + 2 * n) ** 0.5);


Tax Calculator using Java 8 and BigDecimal

The rounding doesn't work the way you expect it to work for division. From documentation:

  Returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().

The product of the salary and the tax rate has two digits after the decimal point. So does the quotient.
The getTaxRate method is unnecessarily long and complicated. You're trying to find the largest entry in a TreeMap such that is less than the given value. That's exactly what the lower method does.
Printing something inside the calculateTax method is a bad idea. It makes the code less reusable (what if I want to just calculate the tax without any logging?). And violates the single responsibility principle (it calculates the tax and prints something to standard output).
This kind of comments:

/*
 * scale > the number of digits to the right of the decimal point
 *
 * precision > the number of significant digits
 *
 * BigDecimal instances are immutable
 *
 */

is even worse than useless. It clutters the code with irrelevant information. The documentation for the BigDecimal class belongs to the BigDecimal class, not to a TaxCalculator.

There several other comments in your code that repeat parts of the TreeMap class documentation. They're also gibberish. Removing all these comments will make the code cleaner.
Adding doc comments for your TaxCalculator class and its public is a good idea. They should describe what it represents, what are the pre- and post-conditions of each method (for instance, what happens if I pass a negative salary? In your case, it's garbage in- garbage out. Document that. It's obvious from the method signature itself).
You might want to add proper input validation (for instance, you can throw the exception if the salary is negative).
You can also use the valueOf static factory method to convert integers to BigDecimal's: to me, BigDecimal.valueOf(100) looks better than new BigDecimal("100"). It can also reuse frequent values.