Java TreeMap.floorKey() equivalent for std::map

Headers and namespaces
The function is missing a definition of map.  This is probably what you want:
#include <map>

using std::map;

Similarly, the main() needs:
#include <iostream>
using std::cout;
using std::endl;

That said, there's no good reason for std::endl in this code: an ordinary newline is sufficient, and we don't need the extra flushing behaviour of std::endl.
Naming
It's an error to use the typename key as the name of a parameter here:

template <typename key,typename value>
int floorKey(map<key, value> input, int key)

It's pretty idiomatic to use PascalCase for template arguments, to distinguish them from function parameters:
template<typename Key, typename Value>
int floorKey(std::map<Key, Value> input, Key key)

(I've also corrected the function to accept the correct type for the key argument).
There's a similar problem in main(), where we have a conflict between the type map and our identifier map.  This is one of the reasons I'd argue against bringing the type name into the global namespace.
Don't pass containers by value
We have a potentially large map, which we don't need to modify.  That suggests that it's better passed as a reference to a const object.  As we don't know the type of the key, we should probably assume that it's also better passed by reference (it could plausibly be a std::string, for example).  That gives us:
template<typename Key, typename Value>
int floorKey(const std::map<Key, Value>& input, const Key& key)

It's good that we used auto for the iterators begin and end, as it means that we don't need to change the body of the function to deal with them both now being const iterators.
Think about edge cases
What happens in this code when the input argument is an empty map?  We dereference input.first() without checking whether it's equal to input.end(), giving Undefined Behaviour at that point.
Algorithm
There's really no need to search for an exactly matching key if we then go on to call lower_bound() - we could just call upper_bound() instead, which will find the first key that's strictly greater than key, then decrement (if doing so is valid) to get the result:
auto it = input.upper_bound(key);

return it == input.begin()
    ? -1
    : (--it)->first;

Note that we have a problem here: if Key isn't a signed numeric type, then we can't return -1.  We really need a type-dependent value for this.  Better still, return a std::optional, so a defaulted value can be clearly distinguished from an actual result.

Modified code
#include <map>
#include <optional>

template<typename Key, typename Value>
std::optional<Key> floorKey(const std::map<Key,Value>& input,
                            const Key& key)
{
    if (auto it = input.upper_bound(key);  it != input.begin()) {
        return (--it)->first;
    } else {
        return std::nullopt;
    }
}

#include <iostream>

int main()
{
    std::map<int, int> map =
        {
         { 10, 100 },
         { 20, 200 },
         { 30, 300 },
         { 40, 400 },
         { 50, 500 },
         { 60, 600 },
         { 70, 700 },
         { 80, 800 },
        };

    std::cout << floorKey(map, 5).value_or(-1) << '\n'
              << floorKey(map, 9).value_or(-1) << '\n'
              << floorKey(map, 10).value_or(-1) << '\n'
              << floorKey(map, 11).value_or(-1) << '\n'
              << floorKey(map, 90).value_or(-1) << '\n';
}


What is wrong with my Genetic Algorithm?

your algorithm is not a genetic algorithm, it is a simple model of infection.

genetic algorithm normally uses at least the following concepts: inheritance, mutation, selection (or fitness).
see, e.g. here

if - for the sake of introductory understanding - you want to apply these concepts to your example:

inheritance:
conceptual: you need a genetic identity of your unit (the animal).
code: i.e. you need animals with state, different instances.
how: each animal inherits this genetic identity to the next generation when it is reproduced.
mutation:
conceptual: each generation is slightly different from the other.
code: each animal in a new generation has slightly different values than its parent.
how: apply some random modification.
selection of fitness:
conceptual: you select which units are reproduced for the next generation by the differences between the units. choose the fittest.
code: when assembling the new generation, choose only those units for reproduction that satisfy a certain fitness limit (e.g. the best 90%).
how: define a fitness-function which returns a value indicating relative fitness for each unit.

to put it together, you could make e.g. different herds of animals that have different starting values for the 'genetic' attributes (e.g. preferred_proximity_to_next_animal, skin_color, height, aggressiveness, etc
.).
Then, in your fitness function, you define how each of the attributes is connected to fitness, i.e. how they are related to the probability to get infected. then let the program run for a some of generations and see how at each iteration the global probability of infection decrease in relation to the genetic setup of your herd.

Like that you might find favourable combinations of attributes.
Generally, genetic algorithms are used in search-related problems.


Refactoring a loop with many boolean conditions

This won't make it shorter, but you might consider changing the condition checking to only do the actual check if needed instead of doing all of them at once, making you loose the advantage of the short-circuiting || operator.

E.g.

if (!isInbox()) continue;
if (!hasPing()) continue;
...

Another possibility, that is even less short, is to create a filtering iterator, e.g.:

class ValidHeaderIterator extends FilterIterator
{
    private $mailbox;
    private $pincall;

    public function __construct($headers, $mailbox, $pincall)
    {
        $this->mailbox = $mailbox;
        $this->pincall = $pincall;
        parent::__construct(new ArrayIterator($headers));
    }

    public function accept()
    {
        $header = $this->getInnerIterator()->current();
        return isInbox($header) && hasPin($header) && isAllowed($header);
    }

    public function isInbox($header)
    {
        return $header->to == $this->mailbox->address;
    }

    public function hasPin($header)
    {
        $pin = $this->getPin($header);
        return $pin !== false && is_numeric($pin);
    }

    public function getPin($header)
    {
        return substr($header->subject, 0, 5));
    }

    public function isAllowed($header)
    {
        return call_user_func($this->pincall,
                              $this->mailbox->address,
                              $header->from,
                              $this->getPin());
    }
}

The calling code would then look like:

foreach(new ValidHeaderIterator($headers, $mailbox, $pincall) as $header) {
    // do stuff
}


Print all permutations with some constraints

Nitpicks

public static void ans(int length, int d1, int d2, int d3) {

Any time that I see numbered variables, I want to replace them with a collection.  Since we know that there will be no duplicate values, I'd use a Set.

public static void generatePhoneNumbers(int length, Set<Character> disallowedDigits) {

Also, I find d an unclear name, so I switched to disallowedDigits which I find clearer.

I switched from int to Character as you are building a string.  We could just as easily be working with the letters of the alphabet as with numeric digits.

StringBuffer numbers = new StringBuffer();

This seems an ideal place to use a StringBuilder.

StringBuilder digits = new StringBuilder();

I also changed the name to digits, as that tells me that we're talking about one digit at a time rather than multi-digit numbers.

            if(!four || (four && soFar.charAt(0) == '4'))

You could just as well write

            if( ! four || soFar.charAt(0) == '4' )

If the string begins with a 4, then we don't care if none of the rest have a 4.

Fulfilling the Problem Statement

        String newRemaining = remaining.substring(0, i) + remaining.substring(i+1);

This is actively wrong given your problem statement:

  Print all valid phone numbers of length n subject to following constraints:
  1.  If a number contains a 4, it should start with 4
  2.  No two consecutive digits can be same
  3.  Three digits (e.g. 7,2,9) will be entirely disallowed, take as input

From #2, only consecutive digits can't be the same.  So you should not be removing digits from your remaining String.  Like length, that will be constant for all calls.

We can rewrite #1 to say:  only numbers that start with 4 can contain 4.  This effectively gives us different rules for 4 than other values.  Since we're supposed to generate all numbers, I'd suggest that we generate all numbers starting with 4 separately from other numbers.  Fortunately, #3 means that we already need a way to exclude digits from the set.

ans

Here's how I'd write the method that you called ans:

private final static char [] DIGITS = "0123456789".toCharArray();

public static void generate(int length, Set<Character> disallowedDigits) {
    Set<Character> allowedDigits = new TreeSet<Character>();

    for ( Character digit : DIGITS ) {
        if ( ! disallowedDigits.contains(digit) ) {
            allowedDigits.add(digit);
        }
    }

    if ( allowedDigits.contains('4') ) {
        printNumbers("4", allowedDigits, length);
        allowedDigits.remove('4');
    }

    for ( Character digit : allowedDigits ) {
        printNumbers("" + digit, allowedDigits, length);
    }
}

First, we define a constant to hold the possible digit values.  Then we make a new Set that masks out the disallowedDigits.  If 4 is allowed, then we generate all the numbers that start with 4 separately.  Then we remove 4 from the allowedDigits, as it won't be allowed in any of the other numbers.

printNumbers

    if(soFar.length() == length) {
        boolean four = false;
        boolean sameAdjDigits = false;

        for(int i = 1; i < soFar.length(); i++) {
            if(soFar.charAt(i-1) == soFar.charAt(i)) sameAdjDigits = true;
            if(soFar.charAt(i) == '4') four = true;
        }

        if(!sameAdjDigits) {
            if(!four || (four && soFar.charAt(0) == '4'))
                System.out.print(soFar + " ");
        }

        return;
    }

This whole section of code is unnecessary, except for one line (the print).  Instead of generating invalid strings and masking them out, just don't generate them in the first place.  That will save all subsequent recursive calls down that path.

    if(soFar.length() < length) {
        for(int i = 0; i < allowedDigits.length(); i++) {
            String newSoFar = soFar + allowedDigits.charAt(i);
            String newRemaining = allowedDigits.substring(0, i) + allowedDigits.substring(i+1);
            printNumbers(newSoFar, newRemaining, length);
        }
    }

I switched to a Set to hold the digits that can be used, so this is going to be a bit different.

private static void printNumbers(String soFar, Set<Character> allowedDigits, int length) {
    int lengthSoFar = soFar.length();

    if ( lengthSoFar < length ) {
        Character last = soFar.charAt(lengthSoFar - 1);

        for ( Character digit : allowedDigits ) {
            if ( ! digit.equals(last) ) {
                printNumbers(soFar + digit, allowedDigits, length);
            }
        }
    } else {
        System.out.println(soFar);
    }
}

First, we already took care of 4 in our generate function.  Here, it will either be in allowedDigits or it won't.

Second, we take care of the rule about consecutive digits by simply not starting the recursive generation in that case:  if ( ! digit.equals(last) ) {.

I put each number on its own line.  For all but trivial lengths, there are too many numbers to fit on a single line.

Note that soFar is the only parameter that changes from call to call.

Testing

This is a bit difficult.  Because we print the numbers to standard output, we can't run normal unit tests on them.  The simplest way to handle this is to direct the output to a file.  Then we can search the file for values that should or shouldn't be there.

For example, we should never have any of the following sequences:  00, 11, 22, 33, 44, 55, 66, 77, 88, 99, 00.  So search for those in the file.  If they don't exist, then you know that rule is working.

Search for lines containing the disallowedDigits.  There shouldn't be any.

Find all the lines in the file that contain a 4 and verify that 4 is the first digit of the number.  On Linux, that might be written something like

fgrep '4' < phone_numbers.txt | cut -c1 | sort | uniq -c

If there are any values other than 4, then you can look them up more specifically.

Also search for a few values that you construct, e.g. for a length of 8 where 7, 2, and 9 are disallowed, 40134568 should be in the list.  Also 86868686 should be there.


Find all anagrams to a given word from a text file

Use more functions

The current implementation is all in the main method.
Break the problem down to smaller pieces,
so that each function has a single responsibility, for example:

Read words from a text file into a List and return it
Convert a word to "normalized" form (sorted and lowercased)
Convert a list of words to a map of normalized form to list of anagrams
Read input and respond with the list of anagrams

Use interface types instead implementations

Instead of these:

ArrayList<String> words = new ArrayList<String>();
// ...

HashMap<String, ArrayList<String>> map = new HashMap<>();

It's better to use interface types in declarations, like this:

List<String> words = new ArrayList<>();
// ...

Map<String, List<String>> map = new HashMap<>();

And on the right-hand side, use the diamond operator <> when possible.

Use try-with-resources when working with resources

Instead of this:

Scanner s = new Scanner(new File("bg.txt"));

ArrayList<String> words = new ArrayList<String>();
while (s.hasNext()) {
    words.add(s.next());
}

// much much later...
s.close();

Write like this:

List<String> words = new ArrayList<>();
try (Scanner s = new Scanner(new File("bg.txt"))) {
    while (s.hasNext()) {
        words.add(s.next());
    }
}

Notice that s.close() is no longer necessary.
That also means you cannot "forget" to close a resource manually.

You can read more about this here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


Rust function to read the first line of a file, strip leading hashes and whitespace

Clippy returns a helpful suggestion:

warning: returning the result of a let binding from a block.
         Consider returning the expression directly.
         #[warn(let_and_return)] on by default
   |>
   |>     first_line
   |>     ^^^^^^^^^^
note: this expression can be directly returned
   |>
   |>     let first_line = String::from(first_line.trim());
   |>                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Don't ignore Results by using let _ =! You should always return them or use expect or unwrap.
The loop could be simplified by using take_while:

let last_hash = first_line.chars().take_while(|&c| c == '#').count();

However, treating one character as one byte is a bad idea because strings are UTF-8 encoded. UTF-8 is a variable-length encoding. You can use char_indices instead.
It's slightly more efficient to take a slice of the string, instead of drain and collect here. It avoids one extra allocation.
Change your function to accept any type that implements BufRead; this will allow you to write easier unit tests.
Actually add those unit tests!
There's no need to create a PathBuf, you aren't pushing path components on. You could just make a &Path, but most functions accept any type that can be converted to a Path (AsRef<Path>). &str implements that.
There's no need to take a reference to something being passed to println! or panic!. These macros automatically take a reference.

use std::fs;
use std::io::BufReader;
use std::io::prelude::*;

/// Get the title of a Markdown file.
///
/// Reads the first line of a Markdown file, strips any hashes and
/// leading/trailing whitespace, and returns the title.
fn title_string<R>(mut rdr: R) -> String
    where R: BufRead,
{
    let mut first_line = String::new();

    rdr.read_line(&mut first_line).expect("Unable to read line");

    // Where do the leading hashes stop?
    let last_hash = first_line
        .char_indices()
        .skip_while(|&(_, c)| c == '#')
        .next()
        .map_or(0, |(idx, _)| idx);

    // Trim the leading hashes and any whitespace
    first_line[last_hash..].trim().into()
}

/// Read the first line of the file into `title`.
fn main() {
    let path = "./example.md";

    let file = match fs::File::open(path) {
        Ok(file) => file,
        Err(_) => panic!("Unable to read title from {}", path),
    };
    let buffer = BufReader::new(file);

    let title = title_string(buffer);

    println!("The title is '{}'", title);
}

#[cfg(test)]
mod test {
    use super::title_string;

    #[test]
    fn top_level_heading() {
        assert_eq!(title_string(b"# This is a top-level heading".as_ref()),
                   "This is a top-level heading")
    }

    #[test]
    fn second_level_heading() {
        assert_eq!(title_string(b"## This is a second-level heading".as_ref()),
                   "This is a second-level heading");
    }

    #[test]
    fn fourth_level_heading() {
        assert_eq!(title_string(b"#### Let's jump straight to the fourth-level heading".as_ref()),
                   "Let's jump straight to the fourth-level heading");
    }
}

You should also investigate using a real Markdown parser to avoid nasty pitfalls.


Size of the largest connected component in a grid in Python

In programming challenges, proper performances improvement usually come from a smarter algorithm. Unfortunately, I have no algorithm better than the one you have implemented.

I have found a single trick to shave off some time.

Remove all the logic around seen

In all places where you access elements from grid and seen, we have basically: if grid[pos] and not seen[pos].

An idea could be to update grid in place to remove seen elements from it. From an engineering point of view, it is not very nice: I would not expect an function computing the size of the biggest connected components to update the provided input. For a programming challenge, we can probably accept such a thing...

We'd get:

def largest_connected_component(nrows, ncols, grid):
    """Find largest connected component of 1s on a grid."""

    def traverse_component(i, j):
        """Returns no. of unseen elements connected to (i,j)."""
        grid[i][j] = False
        result = 1

        # Check all four neighbours
        if i > 0 and grid[i-1][j]:
            result += traverse_component(i-1, j)
        if j > 0 and grid[i][j-1]:
            result += traverse_component(i, j-1)
        if i < len(grid)-1 and grid[i+1][j]:
            result += traverse_component(i+1, j)
        if j < len(grid[0])-1 and grid[i][j+1]:
            result += traverse_component(i, j+1)
        return result

    # Tracks size of largest connected component found
    component_size = 0

    for i in range(nrows):
        for j in range(ncols):
            if grid[i][j]:
                temp = traverse_component(i, j)
                if temp > component_size:
                    component_size = temp

    return component_size

Another idea in order to do the same type of things without changing grid could be to store "positive" elements in a set. This also remove the need to check for edge cases of the grid. The great thing is that we can populate that set with less array accesses. This is still pretty hackish:

def largest_connected_component(nrows, ncols, grid):
    """Find largest connected component of 1s on a grid."""

    def traverse_component(pos):
        """Returns no. of unseen elements connected to (i,j)."""
        elements.remove(pos)
        i, j = pos
        result = 1

        # Check all four neighbours
        for new_pos in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
            if new_pos in elements:
                result += traverse_component(new_pos)
        return result

    # Tracks size of largest connected component found
    elements = set()

    for i, line in enumerate(grid):
        for j, cell in enumerate(line):
            if cell:
                elements.add((i, j))

    return max(traverse_component(pos) for pos in set(elements) if pos in elements)

Edit: rewriting the solution to avoid the copy of elements, we have a slightly faster solution:

def largest_connected_component(nrows, ncols, grid):
    """Find largest connected component of 1s on a grid."""

    def traverse_component(pos):
        """Returns no. of unseen elements connected to (i,j)."""
        i, j = pos
        result = 1

        # Check all four neighbours
        for new_pos in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
            if new_pos in elements:
                elements.remove(new_pos)
                result += traverse_component(new_pos)
        return result

    # Tracks size of largest connected component found
    elements = set((i, j) for i, line in enumerate(grid) for j, cell in enumerate(line) if cell)
    largest = 0
    while elements:
        pos = elements.pop()
        largest = max(largest, traverse_component(pos))
    return largest


Constructing entities from API with foreign keys

Using .Single() on an unsorted list has O(n) cost. If you use a data structure with constant time lookups e.g. a Dictionary<int, Station> and a Dictionary<int, Line> instead you should see a performance improvement using key lookup:

Station = stations[Convert.ToInt32(data["FK_HALTESTELLEN_ID"])],
Line = lines[Convert.ToInt32(data["FK_LINIEN_ID"])]

As you're using Single, I assumed that the dictionary will definitely contain the entry.

I don't know how you're creating your Lists but there is the Enumerable.ToDictionary method which could be useful:

var stationsLookup = stations.ToDictionary(s => s.HaltestellenId);


My eyes hurt :(
I don't think you fully understand OO. Let alone the factory pattern.
The factory pattern is a pattern that helps us with creating objects. It is best used when creating an object takes a couple of steps or is very hard, for instance a constructors with many vars.
This is however not your problem. In fact, I don't really see a problem - a part from you not understanding OO.
You created a Factory that is responsible for creating objects. Yet the only thing it does, is call a function and catche an Exception.
This is not a factory.
What you are doing is creating objects that internally only call functions in the global scope. That is called abuse!
Back to your real question, the pattern:
What I think would be a good pattern to use is the Repository pattern. Before I explaing the repository pattern, let's first review your code:
<?php
if ($kb = Factory::make('KbArticle', $_GET['a'])) {
    $kb->echoNavTrail();
} else {
    die('failed constructor');
}
?>

Don't use the closing ?> tag. Just don't
Use coding standards (PSR-1 and PSR-2 )
Use Exceptions, don't just die.
Use better variable names

Better code would look like this:
<?php

try
{
    $whatEverAIs = $_GET['a']; //what is a?
    //we should check or A is of a correct value, int? string?

    $kbArticle = KbArticleFactory::make($whatEverAIs)
}
catch( Exception $e )
{
    print $e->getMessage(); //or log the exception or show a nice debug screen or ...
    die();
}

//still here? good, we now can use our $kbArticle
print $kbArticle->getNavigationTrail();

This code reads better, and gives us a better view of what is going on. We have a KbArticleFactory that returns a KbArticle. We create a KbArticle with variable $whatEverAIs. If it fails, we catch the exception and do what ever we want to do with it. If it succeeds, we simply continue with our magic.
The design is bad
Let's analyze our design. We have a Factory for KbArticle's that throws an exception if the KbArticle couldn't be created. If look deeper into your code, this means that you KbArticle wasn't found. and $a looks to be some kind of KbArticleId.
wow, I don't think you need to be einstein to notice something fishy in that explanation. Let's write down our problem.
We have a DataSource (SQL) with records in it. Every record is in fact a KbArticle. In stead of manually having to query the database all the time, we want some kind of interface that does all the queriyng for us, and returns a KbArticle object.
Enter the Repository pattern.
We have a repository:
<?php
interface RepositoryInterface {

    public function all();

    public function find($id);

    public function create($data);

    public function update($id, $data);
}

this gives us a set of methods to interact with things. So let's create our KbArticle interface:
<?php

//because we don't need extra methods for our KbArticleRepository (yet) we simply only extend our existing interface
interface KbArticleRepositoryInterface extends RepositoryInterface {}

So, let's create our repository:
<?php

class KbArticleRepository implements KbArticleRepositoryInterface
{
    public function __construct($dataSource)
    {
        $this->dataSource = $dataSource;
    }

    public function all()
    {
        $kbArticles = $this->dataSource($sql_for_all_articles);
        return $kbArticles;
    }

    public function find($id)
    {
        $kbArticle = $this->dataSource($sql_for_this_article);

        if ( is_null($kbArticle) )
        {
            throw new KbArticleNotFoundException();
        }

        return $kbArticle;
    }

    //...
}

We would then use this repository as follows:
<?php

$kbArticleId = $_GET['a'];
if ( preg_match('[0-9]+',$kbArticleId) === 0 )
{
    throw new Exception('a needs to be an int'); // let some other code handle the error
}

$sqlDataSource = new SqlDataSource();//get the datasource

$repository = new KbArticleRepository($mySqlDataSource);

try
{
    $kbArticle = $repository->find($kbArticleId);
}
catch (KbArticleNotFoundException $e)
{
    print 'Article not found';
    die();
}

//still here? good, we now can use our $kbArticle
print $kbArticle->getNavigationTrail();

Depending on how hard it is to create our KbArticle object. We can simply do it in our repository and return that object:
public function find($id)
{
    //...
    return new KbArticle($kbArticle);
}

Or we could delegate it to a factory:
public function __construct($datasource, $factory)
{
    //...
    $this->factory = $factory;
}

public function find($id)
{
    //...
    return $this->factory->make($kbArticle);
}

I hope this all makes a bit sense.


$params = (count($url > 0)) ? $url : "";

Is this really what you meant to say?  This looks like it should be

 $params = (count($url) > 0) ? $url : '';

The second version treats the $url variable as an array.  The previous code treats $url as an integer and then treats a Boolean expression as an array.  This is problematic because both count(false) and count(true) return 1.  Meaning that the first version is the same as $params = $url.

This was the only functional comment that I had on the code.  Everything else is just style.  It's possible that if you fleshed out a problem statement describing what the code is supposed to do that someone would have additional functional comments.

            if ($this->validateURL()) {
                $class = (isset($url[1])) ? $url[1] : $this->get('defaultController');
                unset($url[1]);
                $method = (isset($url[2])) ? $url[2] : $this->get('defaultMethod');
                unset($url[2]);
                $params = (count($url > 0)) ? $url : "";
                unset($url);

                if (class_exists($class)) {
                    $controller = $this->app->getInstance($class);
                } else {
                    exit("Class not found");
                }
                if (method_exists($controller, $method)) {
                    if ($params !== "") {
                        call_user_func_array(array($class, $method), $params);
                    } else {
                        $controller->{$method}();
                    }
                } else {
                    exit("Method not found");
                }
            } else {
                exit("URI chars not allowed");
            }

You could reduce your indentation by using early exits instead of if/else.

            if (!$this->validateURL()) {
                exit('URI chars not allowed');
            }

            switch (count($url)) {
                default:
                    $method = (isset($url[2])) ? $url[2] : $this->get('defaultMethod');
                    unset($url[2]);
                    // 3 or more fall through to 2
                case 2:
                    $class = (isset($url[1])) ? $url[1] : $this->get('defaultController');
                    unset($url[1]);
                    // 2 or more fall through to 1
                case 1:
                    $params = $url;
                    break;
                case 0:
                    $params = '';
                    break;
            }
            unset($url);

            if (!class_exists($class)) {
                exit('Class not found');
            }

            $controller = $this->app->getInstance($class);
            if (!method_exists($controller, $method)) {
                exit('Method not found');
            }

            if ('' === $params) {
                $controller->{$method}();
            } else {
                call_user_func_array(array($class, $method), $params);
            }

I also changed the order of the final if/else.  I try to avoid the if not else form.  An else is implicitly taking the logical not of the test expression.  So if the test expression is negative, this means that the else is the negative of a negative.  I often find it more readable if I reorder the clauses such that the test expression is positive.

I prefer to use single quotes if I can.  There's a slight performance benefit, but the chief advantage is that it is easy to see that no variable interpolation will occur.  With double quotes you have to examine the string to tell that.

I don't know that the switch version is better than what you had originally, but I wanted to include it as a possibility.  I find it a little clearer, but it is more code.  On average, it may give a very slight performance advantage.  Probably not enough to matter.


call it a "view model"  as its not really a model,  its just a model for the view you are showing.

ConfirmEmailViewModel  :)


According to my experience, web animations don't use CPU as such, but rather prefer the GPU at times for rendering. On phones, custom animations like yours will run without any moderation of fps, and so a lag is kinda expected. On top of it, js doesn't use parallel threads of course, so it won't even use the remaining core if they are available.

What I'd suggest is use some good library to run these. I remember using Three.js and it ran on my Lumia 520 at 8FPS but still without lag, as the animation was optimized for low FPS. The same ran on my PC at 60FPS smoothly just the same.

Hope this helps.


raw types

Try to avoid raw types. private Node fieldname should be private Node<T> fieldname, same for function returns and method arguments.

Bug

If I do this:

MyLinkedList<String> list = new MyLinkedList<>();
list.remove("foo");

I get a NullPointerException. This is because you first access data of the root, and then check what the size is. It should be the other way around (and checking if the root is null would be a bit clearer).

You also shouldn't set the data to null, you should remove the node, otherwise you have a root node that contains null (also, your list size is wrong from there on out).

It also doesn't make that much sense to first set the data, and then override the node. In that case, just remove the setting of the data.

remove non existing element

If a non existing element is removed, you could throw a NoSuchElementException (it's what Java lists do).

Setting values to null

next = null; this isn't necessary, you are returning right afterwards.

Naming

it is a bit uncommon to start a field name with _.
I would conform to the names of the List interface (getSize -> size, add(array) -> addAll(array).


Some notes:

Use 2 spaces for indentation, not 4.
key, numeral = digit: You can unpack block arguments: do |acc, (key, numeral)|.
Concating strings is costly, better build an array and finally join it.
You are using inject, which is great because it'a functional abstraction, but you are modifying num on each iteration, so it ends up being a weird mixture of functional and imperative style. I know it's a bit cumbersome, but conceptually it's better to keep also num in the accumulator.

I'd write:

digits.reduce(:output => [], :num => num) do |state, (key, numeral)|
  ocurrences, remainder = state[:num].divmod(key)
  {:output => state[:output] << (numeral * ocurrences), :num => remainder}
end[:output].join


Extracting small word parts (quadgrams) from text using R

Your loop approach works but seems a bit convoluted. For instance you could rewrite the for loop this way:

for (i in 1:number_of_characters) {

  end <- i + 3

  if (end <= number_of_characters) {
    temp <- substring(text, i, end)
    quad_gram_list <- append(quad_gram_list, temp)
  }
}

But anyway it's generally better to avoid loops in R.

Also note that:

you should use character(0) instead of ""[-1]
: is to be avoided because of undesired behaviour on edge cases. It's better to use seq_len().

Here are two alternative solutions:

1) Using base R:

unlist(lapply(seq_len(nchar(text) - 3), function(i) substring(text, i, i + 3)))
# [1] "hell" "ello" "llo " "lo w" "o wo" " wor" "worl" "orld"

2) Using tokenizers:

library(tokenizers)

tokenize_character_shingles(
  text,
  n = 4,
  strip_non_alphanum = FALSE,
  simplify = TRUE
)
# [1] "hell" "ello" "llo " "lo w" "o wo" " wor" "worl" "orld"


Building a Building - Is the building clean?

First of all, I would recommend using a data class. In order to do this, it's better to use List rather than Array (because Array does not support hashCode/equals)

data class Building (
    val name: String,
    val inputs: List<Resource>,
    val outputs: List<Resource>
)

Actually, considering that the order of elements doesn't matter you could use Set or any iterable data structure as well, but my experience is that List is usually the fastest to iterate through.

As for using the companion object, that's entirely possible and will be similar to static factory methods, but I like to go beyond that and have a completely separate factory class for this. The reasoning being that I don't want to tightly couple my Building with the actual data, what if I would like to have two entirely different games in the future that both use the Building ? What if I would like to let the user design their own buildings? Either way, I see many reasons to use a separate factory class/object than use the companion object.

In Kotlin it is as easy as defining an object BuildingFactory.

object BuildingFactory {
    fun woodcutter(): Building = Building(
        "Woodcutter",
        listOf(
            Resource(ResourceType.WOOD, 1),
            Resource(ResourceType.WORKFORCE, 3),
            Resource(ResourceType.MONEY, 10)
        ),
        listOf(Resource(ResourceType.PLANKS, 1))
    )
}

Then you can create instances as easy as BuildingFactory.woodcutter()

Another approach could be to have a configuration data file specifying the buildings available and reading from that file. Then construct a building based on a name.


Yes, and don't lock on typeof - highly unrecommended. Also you'll need to lock whatever's adding to the QUEUE so that the multithreaded Dequeue() does not race against it.

static protected void ThreadProcManager()
{
   lock (QUEUE)
   {
       if (QUEUE.Count > 0)
       {
           ThreadPool.QueueUserWorkItem(ThreadProc, QUEUE.Dequeue());
        }
    }
}

 static private void ThreadProc(Object stateInfo)
 {
     //Do the work...
 }


Instead of using the for loop with if flow control, you could use the arrays functions to convert all more functional.

As your code looks broken I wrote my refactoring in the following test:

'use strict';

// This is just to run the test
const request = {}
const response = {}

// This is a trivial oModule object
const M = {
    fn1: function() {
        return new Promise(() => console.log('fn1'))
    },
    fn2: function() {
        return new Promise(() => console.log('fn2'))
    }
}

// This is the oConfig object as you post in your OP
const C = {
    providers: [
    {
      "run": {
        "path": "command1",
        "function": "fn1",
      },
      "save": {
        "path": "test2",
        "function": "fn2",
      }
    }
  ]
}

// The proposed refactoring
const _run = (req, res, oModule, oConfig, urlPath, action) => {
    let aPromises = Object.keys(oConfig.providers[0])
        .filter(providerName => (providerName == action))
        .map(providerName => {
            let provider = oConfig.providers[0][providerName]
            return oModule[provider.function]
        })
        .filter(func => (typeof func === 'function'))
        .map(func => func(req, res))

    return Promise.all(aPromises)
}

// This run the test to
_run(request, response, M, C, '', 'run')

I used 2 different filter/map run to check the 2 checks on the 2 different objects oConfig and oModule.

I tested this with nodejs v4.4.4 on windows and it works without errors.

It print out:

fn1

I removed the var and use const or let.

It should be the same, not sure if it is more readable.

You never use urlPath so you can remove from arguments.

I didn't put any ; as they are not mandatory in javascript, but if you prefere to use feel free to put at the end of each expression.

Also, I hope that oModule[provider.function](req, res) returns a Promise or your code is blocking, but maybe is so.


Inside SendRequst you are calling SendRequest again, which will make your stack full of recursive calls.


It's normal for Java programs to be longer. I wouldn't care about the number of lines per se.
The main method does too much stuff:

It asks the user to choose the file
It reads the content of the file
It counts the number of occurrences
It prints them to another file

One method should be responsible for one thing. There're at least 4 different (very different) things here.

In fact, I believe that the first thing (and probably the second and the last thing, too) doesn't belong in the FrequencyCounter class. Why? It makes sense for the counter to count occurrences and do just it. It'll make it more reusable. Think what happens if you want to change the output format, the way the user choose the file or just use it as part of your different project.
I would redesign the FrequencyCounter it so that it has one method that takes a string and returns a map with different words and the number of their occurrences.
The reading/writing stuff and the user dialog belong to a different class. These are different concerns. So I'd create another class to handle file I/O and one more class to interact with a user as these things have nothing to do together. They can change independently and they don't need each other to work. They're separate entities.
You don't handle the case when the file is null (that is, when the user doesn't choose a file). A NullPointerException isn't very user-friendly.
This piece of code:

 if (counter.containsKey(word))
     counter.put(word, counter.get(word) + 1);
 else
     counter.put(word, 1);

can be simplified to counter.put(counter.getOrDefault(word, 0) + 1); unless you're using an older Java version.
If you plan to work with large files (really large, such that their content doesn't fit into main memory), you'll need to get rid of reading the entire file into a String. A more space-efficient solution would be to read it in chunks and process them separately (the words are normally short, so it can save a lot of memory). Sure, it makes the code more complicated (for instance, you'll need to carefully check when the word ends), so it's worth doing only if you plan to work with large amounts of data.
A method name is normally a verb. cleaner doesn't sound very good to me. I'd rename it to something like cleanWords. I'd also put cleaning one word into a separate method to make it more manageable. You can go even further and put all cleaning stuff into a separate class to increase the flexibility (it also makes sense from a design point of view: cleaning and counting are different responsibilities and they are pretty much independent).
The way you work with the output file is potentially dangerous: if such a file already exists, it'll be overwritten. I don't think that doing it silently is a good idea. There're a few different ways to deal with it: generating a different unique name, aborting the program or letting the user choose the output file. Either of them is better than replacing the content of the file silently.


You should give your drop down some limitations, so that it isn't taking up all sorts of space that it shouldn't be, I started with adding a width of 200 pixels to it, but I suggest you change it to something that works for you.

I also added a background color, because I would want my dropdown to be different from the surrounding page so that I knew it was an extension of another element on the page, again you should alter this according to your needs, but don't leave it white on a white background.

I also removed the top border for the drop down.  I am not much into the graphics of things. so mine doesn't look very pretty either, but you should make it so that the drop down looks like it is a drop down. or an Auto Suggest component

I assume that you are doing this just to learn JavaScript and not for an actual production site.

Just in the case that you are doing this for a production site I would recommend that you use jQuery and depending on the source of your suggestions AJAX as well.

AutoComplete Widget from jQuery-UI

in your JavaScript, give your Curly braces some space after the function declaration or the for loop declaration or the if declaration, you gave them space in your CSS, show the JavaScript braces the same courtesy.

Here are the changes that I made to your code.  all I did was alter the CSS and add spaces before the opening braces in your JavaScript.

You should also stick you either single quotes or double quotes, it runs like this, but it is often confusing to read.

var list = [
    {name: 'Afghanistan', code: 'AF'},
    {name: 'Åland Islands', code: 'AX'},
    {name: 'Albania', code: 'AL'},
    {name: 'Algeria', code: 'DZ'},
    {name: 'American Samoa', code: 'AS'},
    {name: 'AndorrA', code: 'AD'},
    {name: 'Angola', code: 'AO'},
    {name: 'Anguilla', code: 'AI'},
    {name: 'Antarctica', code: 'AQ'}
];

function Autocomplete(selector) {

    this.list = list;

    this.box = document.getElementById(selector);

    this.dropdown = null;

    this.init = function() {
        this.box.addEventListener('keyup', this.boxKeyUp);
        this.dropdown = document.createElement('ul');
        this.dropdown.setAttribute('class','drop');
        document.body.appendChild(this.dropdown);
        this.updateList();
    };

    this.updateList = function() {
        this.dropdown.innerHTML = '';
        var value = this.box.value;
        for(var i=0; i < this.list.length; i++) {
            var name = list[i].name.toLowerCase();
            var idx = name.indexOf(value);
            if(idx===0) {
                var item = document.createElement('li');
                item.appendChild(document.createTextNode(list[i].name));
                this.dropdown.appendChild(item);
            }
        }
    };

    this.boxKeyUp = function() {
        if(this.box.value===''){
            this.dropdown.style.display = 'none';
            return true;
        }
        this.updateList();
        this.dropdown.style.display = 'block';
    }.bind(this);

    this.init();

    return this;
}
var ac = new Autocomplete('inputbox');
input {
    width: 200px;
}

input, .drop {
    margin: 0;
    padding: 0;
    padding: 6px;
    font-size: 16px;
    font-family: "helvetica neue", helvetica, sans-serif;
}

.drop {
    display: none;
    list-style-type: none;
    list-style-position: inside;
    border-style: none groove groove groove;
    border-color: silver;
    border-width:5px;
    width: 195px;
    background-color: lightgray;
}
<input type="text" name="inputbox" id="inputbox">


Don't write a function to return a constant

You don't need uint_size(), as the returned value never changes (for a given target platform).  You can replace it with

#include <climits>
static const std::size_t uint_bits = CHAR_BIT * sizeof (unsigned int);

Don't require a call to init()

The constructor should fully initialize the object; just move the body of init() there instead.

Use integer operations on integers

Instead of using std::ceil to round up division, we can do this in integer arithmetic by adding one less than the divisor before dividing:

    elements_ = (bits + uint_bits - 1) / uint_bits;

Given that we know the number of bits, we can always compute the number of elements when we need it; you might consider the trade-off between storing and computing elements_.

Obey the Rule of Five (or Rule of Zero)

You allocate memory in the constructor, but don't provide copy/move constructors, nor an assignment operator, so you run the risk of double delete[].  The easiest fix is to use a standard container as the storage; you might also consider using a smart pointer to the storage.  As a last resort, you could manage the memory yourself, but I'd advise against that.

Use an unsigned type for indexing

You can avoid needing to check for negative index values by accepting an unsigned integer type in the methods.  I recommend std::size_t as the standard type usually used for that.

Return by value when possible

void size(int& bits) const;

is better written as

std::size_t size() const;

My version

Working replacement code:

#include <climits>
#include <stdexcept>
#include <vector>

class Bitarray1D {
    using Element = unsigned int;

    class Bit {
        Element& element;
        const Element mask;
    public:
        Bit(Element& element, Element mask) : element{element}, mask{mask} {}
        Bit(const Bit& other) : Bit{other.element, other.mask} {}
        operator bool() const { return element & mask; }
        Bit& operator=(bool b) { element = b ? element | mask : element & ~mask; return *this; }
        Bit& operator=(const Bit& other) { return this->operator=(bool(other)); }
    };

    static const std::size_t element_bits = CHAR_BIT * sizeof (Element);

    std::size_t bits;
    std::vector<Element> array;

public:
    Bitarray1D(std::size_t bits);
    ~Bitarray1D() = default;

    std::size_t size() const;

    Bit operator[](std::size_t index);

};

Bitarray1D::Bitarray1D(std::size_t bits)
    : bits{bits},
      array{}
{
    // rounded-up division
    array.resize((bits + element_bits - 1) / element_bits);
}

Bitarray1D::Bit Bitarray1D::operator[](std::size_t index) {
        if (index >= bits)
            throw std::out_of_range("Index out of range");
        return Bit(array[index / element_bits], 1u << (index % element_bits));
}

int main()
{
    Bitarray1D bits{15};
    bits[0] = 0;
    bits[2] = bits[1] = 1;
    return bits[0] + bits[1] + bits[2] != 2;
}


You should probably derive from std::runtime_error.
It takes a string in the constructor as the message and stored it for use with what() in a way that is safe even in low memory situations:

Your exception class is then simplified too:

class CurlException : public std::runtime_error
{
public:
   CurlException(std::string const& message): std::runtime_error(message) {}
                         //  ^^^^^^^ pass message by const reference.
   CurlException(CURLcode error): std::runtime_error(curl_easy_strerror(error)) {}
};

The use of exception specifications in C++ was an experiment that ultimitely showed it was a bad idea. The only useful specification was the no throw specification (and then only when you made sure it really was no-throw).

void SetOptions() throw (CurlException)
              // ^^^^^^^^^^^^^^^^^^^^^ Get rid of this bit.

In C++11 exception specifications have been deprecated.

The curl library is a C library. It only knows about C calling conventions. Thus you can NOT pass it C++ functions. If it works it is pure luck and definately non portable.

  res = curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION,
                          CppCurl::WriteDataCallback);

Even though CppCurl::WriteDataCallback is a static function there is no guarantee that static methods have the same calling convention as a C function. Future versions of the compiler may break your code.

You should do something like this:

 extern "C" size_t WriteDataCallback(void *ptr, size_t size, size_t nmemb, void* pInstance)
 {
      CppCurl*   obj = reinterpret_cast<CppCurl*>(pInstance);
      return obj->write_data(ptr, size, nmemb);
 }

Not a big deal but I would have used insert rather than +=.

      m_data += std::string(iter, iterEnd);

 // -- or.

      m_data.insert(m_data.begin(), iter, iterEnd);


I don't know what to think of the entire thing yet but...

public bool Succeeded => Error == null;
public bool Failed => !Succeeded;

I find this should be only one property bool Success.

I've watched video series and generally I think it's a new and interesting idea that I need to try out. Your solution is a good start especially with the implicit operators but I'm missing a few features.

I'm not so fond of using the Result as a parameter. It has another implicit operator for converting it into a value so using actual types for parameters is sufficient and it's easier to work with pure parameters rather than dealing with Results everywhere (but maybe it's just an example). It's also safer because I'm going to throw an exception if a result is in an invalid state so implicit casting it for the parameter would fail when a method is called and not later when a parameter is used. I find this is better because it indicates a bug before the call and not inside the method that uses a result.

public static implicit operator T(Result<T> result)
{
    if (result.Failed)
        throw result.Error;

    return result.Value;
}

I don't think this is a good implementation for this operator and I prefer getting the Value would throw like this

T Value => Success ? _value : throw new InvalidOperationException("Value isn't set because the result is in error state.");

informing me that I cannot use it because the Result is in an invalid state for it. This is the behaviour that I expect from this property and not some default value that I might use in case I forgot to check the Success flag.

After all I think I could also live with two flags for the result that I'd call

public bool Success => string.IsNullOrEmpty(Message) && Exception == null;

and

public bool Failure => !Success;

whether it should be Success or Succeeded or Failure or Failed is probably an entire new question for the English Language community but to me the former sounds better as it tells me whether the operation was a Success or a Failure and not if the Result succeeded. Well, tometo tomato ;-)

The current solution is prepared to work only with exceptions and to be used only in methods that can throw but if we wanted to make our API consistent then it should also be possible to use the Result for other methods that not necessarily throw but cannot continue because of some other reason so implementing factory methods like Ok and Fail and a custom message is not such a bad idea.

To me the perfect solution would go like this:

The non-generic Result can be created in a similar way as an exception this is with a message and an exception or with either one only. In case of a failure it returns either the exception's message or the custom one and could be used for methods that return void. For consistency reasons I turned the OK property into a Ok method.

public class Result
{
    protected Result(string message, Exception exception) { Message = message; Exception = exception; }
    protected Result(string message) : this(message, null) { }
    protected Result(Exception Exception) : this(null, Exception) { }

    public Exception Exception { get; }
    public string Message { get; }

    public bool Success => string.IsNullOrEmpty(Message) && Exception == null;
    public bool Failure => !Success;

    public static Result Ok() => new Result(nameof(Ok));

    public static Result Fail(string message, Exception exception) => new Result(message, exception);
    public static Result Fail(string message) => Fail(message, null);
    public static Result Fail(Exception exception) => Fail(null, exception);

    public override string ToString() => Success ? Message : (Exception?.Message ?? Message);

    public static implicit operator Result(Exception exception) => Fail(exception);
    public static implicit operator Result(string message) => Fail(message);
    public static implicit operator bool(Result result) => result.Success;
}

The generic implementation could provide a value:

public class Result<T> : Result, IEnumerable<T>
{
    private readonly T _value;

    protected Result(T value) : base(Exception: null) => _value = value;
    protected Result(string message, Exception exception) : base(message, exception) { }
    protected Result(string message) : base(message, null) { }
    protected Result(Exception exception) : this(null, exception) { }

    public T Value => Success ? _value : throw new InvalidOperationException("Value isn't set because the result is in error state.");

    public static Result<T> Ok(T value) => new Result<T>(value);

    public static new Result<T> Fail(string message, Exception exception) => new Result<T>(message, exception);
    public static new Result<T> Fail(string message) => Fail(message, null);
    public static new Result<T> Fail(Exception exception) => Fail(null, exception);

    public IEnumerator<T> GetEnumerator() => Enumerable.Repeat(Value, Success ? 1 : 0).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

    public static implicit operator Result<T>(string message) => Fail(message);
    public static implicit operator Result<T>(Exception exception) => Fail(exception);
    public static implicit operator Result<T>(T value) => Ok(value);
    public static implicit operator Result<T>((string Message, Exception Exception) t) => Fail(t.Message, t.Exception);
    public static implicit operator T(Result<T> result) => result.Value;

    public void Deconstruct(out string message, out Exception exception)
    {
        message = Message;
        exception = Exception;
    }
}

and it can also be use with methods that do not have to throw. Consider another version of the Div method:

static Result<int> Div(int a, int b)
{
    if (b == 0) return "Cannot divide by zero" ; else return a / b;
}

I have also added an implicit cast to bool so you can use the result in a boolean expression:

var n = Div(4, 0);
if (n)
{
    Console.WriteLine("Hooray, divided!");
}
else
{
    Console.WriteLine("This time it didn't work.");
}

and with the new anonymous tuples in C# 7 we can even do this:

public static Result<int> Div(int a, int b)
{
    try
    {
        return a / b;
    }
    catch (DivideByZeroException ex)
    {
        return ("Are you nuts?!", ex);
    }
}

or how about deconstructing it?

var result = Div(4, 0);
if (!result)
{
    var (message, exception) = result;
}


Check for req.file before using its properties
Return/reject early instead of nesting a big else clause
Since you're using ES2015 syntax do it consistently:

template strings via backticks
arrow functions in callbacks that don't utilize this of the callee
string methods with self-explanatory names like endsWith instead of regexps
let instead of var (there was one in your code)

Deduplicate reject+logger combo and writeIntoFile
Use single or double quotes consistently

return new Promise((resolve, reject) => {
    if (!req || !req.file) {
        __rejectAndLog('No file provided');
        return;
    }
    let numberOfFiles = 0;
    let filePath = path.join(req.file.destination, req.file.filename);
    logger.info(`Unzip filePath: ${filePath}`);

    yauzl.open(filePath, (err, zipFile) => {
        if (err) {
            __rejectAndLog(err);
            return;
        }
        zipFile.on('entry', entry => __processEntry(zipFile, entry))
            .once('error', __rejectAndLog)
            .once('close', () => {
                logger.info(`Unpacked ${numberOfFiles} files`);
                resolve();
            });
    });

    function __processEntry(zipFile, entry) {
        if (entry.fileName.endsWith('/')) {
            return;
        }

        zipFile.openReadStream(entry, (err, readStream) => {
            if (err) {
                __rejectAndLog(err);
                return;
            }

            let destinationFileName = './' + entry.fileName;
            let directoryName = path.dirname(destinationFileName);
            if (fs.existsSync(directoryName)) {
                __writeFile();
                return;
            }

            mkdirp(directoryName, (err) => {
                if (err) {
                    __rejectAndLog(err);
                } else {
                    __writeFile();
                }
            });

            function __writeFile() {
                writeIntoFile(readStream, destinationFileName, reject);
                numberOfFiles++;
            }
        });
    }

    function __rejectAndLog(err) {
        logger.info(err);
        reject(err);
    }
});

entry-processing function is extracted to make the zipFile flow more obvious
__ prefix is used for subfunctions following your naming of _unzip


It looks pretty clean. You are saving the values into variables so to avoid re-running the query.

A minor improvement would be to use click function instead of on('click') as it more readable.

For the toggle part, one can identify 2 phases when clicking:

change button text
animate the description

If you don't need to keep them separate you can remove the ternary operator (the expr1? expr2: expr3) and do:

showHide.click( function () {
    if (longDescription.is(':visible')) {
        showHide.text('Read More');
        shortDescription.fadeIn(inSpeed);
        longDescription.fadeOut(outSpeed);
    } else {
        showHide.text('Read Less');
        shortDescription.fadeOut(outSpeed);
        longDescription.fadeIn(inSpeed);
    }
});


HNews "ask section" page scraping Python script

This is how I would modify your script. Comments are inline. This version is PEP8-PyLint-PyFlakes approved. ;-)

#!/usr/bin/python

'''This script gets the headlines from hacker news ask section'''

import urllib2
import HTMLParser
# remove unused imports

class HNParser(HTMLParser.HTMLParser):

    # use class-level attribute instead of "magic" strings.
    tag_name = 'a'

    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self.data = []
        self.recording = 0

    def handle_starttag(self, tag, attribute):

        if tag != self.tag_name:
            return

        # clearer implicit loop, with no "break"
        if not any(name == 'href' and value.startswith('item')
                for name, value in attribute):
            return

        # no need to check if self.recording == 0, because in that case setting
        # self.recording = 1 is equivalent to incrementing self.recording!
        self.recording += 1

    def handle_endtag(self, tag):
        if tag == self.tag_name and self.recording:
            self.recording -= 1

    def handle_data(self, data):
        if self.recording:
            self.data.append(data)

def main():
    HOST = 'http://news.ycombinator.com/ask'
    parser = HNParser()
    f = urllib2.urlopen(HOST)
    rawHTML = f.read()
    parser.feed(rawHTML)
    try:
        # use fancy list indexing and omit last "Feature Request" link
        for item in parser.data[:-1:2]:
            print item
    finally:
        # close the parser even if exception is raised
        parser.close()

if __name__ == '__main__':
    main()


Is it effective to use get; set; to avoid redundant processes?

Is it best to initialize a static member once, in a static constructor. If that is not possible, then a lazy initialization can be done like this. (Similar code to yours, just using the null coalescing operator.)

private static string file_path_includes_;

public static string file_path_includes
{
    get
    {
        return
            file_path_includes_ ??
                (file_path_includes_ = HttpContext.Current.Server.MapPath("/_includes") + @"\");
    }
}


I figure HttpUtility.ParseQueryString is just incredibly robust, and you likely are missing something. But I can't spot anything in particular and it's likely that without deep research you won't be able to cover all the cases which were clearly studied and thought out in Microsoft's implementation. However, I think your implementation can be refactored to be easier to read and maintain by using regular expressions instead of brute force string splitting. I present the following in F# which hopefully you can translate easily enough to C# (the key functionality relies on the same .NET libraries available in both languages). I'm still new to regex writing myself, so I'm sure it's not as robust as it could be, but it seems to work well for all the typical cases I tested (generally assumes query string is not malformed, allows no query string, allows empty values but not empty keys, accounts for possible # delimiter after query string part):

open System
open System.Text.RegularExpressions
let uriParams uri =
    let matches = Regex.Matches(uri, @"[\?&](([^&=]+)=([^&=#]*))", RegexOptions.Compiled)
    seq { //create a sequence of key, value tuples extracted from the matches
        for m in matches do
            yield Uri.UnescapeDataString(m.Groups.[2].Value), Uri.UnescapeDataString(m.Groups.[3].Value)
    } |> dict // convert the sequence of key, value tuples into an immutable IDictionary

Update

I went ahead and translated to C#:

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

...

static Dictionary<string, string> GetParams(string uri)
{
    var matches = Regex.Matches(uri, @"[\?&](([^&=]+)=([^&=#]*))", RegexOptions.Compiled);
    var keyValues = new Dictionary<string, string>(matches.Count);
    foreach (Match m in matches)
        keyValues.Add(Uri.UnescapeDataString(m.Groups[2].Value), Uri.UnescapeDataString(m.Groups[3].Value));

    return keyValues;
}

Update 2

Here's a more functional C# version:

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;

...

static Dictionary<string, string> GetParams(string uri)
{
    var matches = Regex.Matches(uri, @"[\?&](([^&=]+)=([^&=#]*))", RegexOptions.Compiled);
    return matches.Cast<Match>().ToDictionary(
        m => Uri.UnescapeDataString(m.Groups[2].Value),
        m => Uri.UnescapeDataString(m.Groups[3].Value)
    );
}

Edit

I updated the regex to address the very important consideration of the # delimiter that @Visionary pointed out. That is probably the biggest thing missing from your own implementation functionality-wise.  Also, here is a list of some cases I tested (using the F# version):

uriParams "http://www.foo.com" // []
uriParams "http://www.foo.com?" // []
uriParams "http://www.foo.com?q=" // [("q","")]
uriParams "http://www.foo.com?q=search&doit=no" // [("q","search"), ("doit","no")]
uriParams "http://www.foo.com?q=search&doit=no&go=further" // [("q","search"), ("doit","no"), ("go","further")]
uriParams "http://www.foo.com?q=&doit=no" // [("q",""), ("doit","no")]
uriParams "http://www.foo.com?q=&doit=no&=&test&good=true" //[("q",""), ("doit","no"), ("good","true")]
uriParams "http://www.foo.com?q=search&doit=no#validationError"  // [("q","search"), ("doit","no")]
uriParams "http://www.foo.com?q=search&doit=no#validationError=true"  // [("q","search"), ("doit","no")]
uriParams "http://www.foo.com?q=se%20arch&do%20it=no" // [("q","se arch"), ("do it","no")]
uriParams "http://www.foo.com?q=search&doit=#validationError"  // [("q","search"), ("doit","")]


Your code is really good and I can't see any significant way to improve it. One minor improvement is to reduce the number of loops from 3 to 2:

protected function calculateWeightedAverage($ratings)
{
  $sum = 0;
  $rating = 0;

  $values = array_values($ratings);
  sort($values);

  $count = count($values);
  $out = (int) ($count / 3);
  $out2 = pow($out + 1, 2);

  for ($i=0; $i<$count; $i++) {
    if ($i < $out) {
      $weights[$i] = pow(($i+1),2)/$out2;
    } elseif ($i > $count-$out-1) {
      $weights[$i] = pow($count-$i,2)/$out2;
    } else {
      $weights[$i] = 1;
    }
    $sum += $weights[$i];
  }

  for ($i = 0; $i < $count; $i++) {
    $rating += $values[$i] * $weights[$i]/$sum;
  }

  return $rating;
}


Flagging employees whose spending is close to the budgeted amount

There's two ways you can go about this. Stick with your current way, or use SQL more.

Current way

I'd change your for loop to assign to one value.
I'd make a function that tells you if the values have the flag.
I'd use *value to tuple unpack into the write_cursor tuple.

And so would get something like:

from datetime import datetime as dt

def get_flag(employee_spend, higher, lower):
    _, amount, _, date, _, percent_diff = employee_spend
    return int(
        dt.strptime(date, "%d/%m/%Y") <= dt.now()
        and (
            amount > 500
            and percent_diff < int(higher)
            or amount < 500
            and percent_diff < int(lower)
        )
    )

def calculateEmployeeSpend(read_cursor, flag_higher_amount, flag_lower_budget):
    higher, lower = int(flag_higher_amount), int(flag_lower_budget)

    read_cursor.execute("SELECT distinct b.employee_id, b.amount, "
                "s.spend, b.date, b.amount - s.spend as spend_left,  "
                "100.0*(b.amount - s.spend) / b.amount As PercentDiff FROM employee_budget_upload "
                "As b JOIN employee_budget_spent As s ON  b.employee_id = s.employee_id where b.amount != 0")

    for employee_spend in read_cursor:
        flag = get_flag(employee_spend, higher, lower)
        write_cursor.execute(
            'INSERT OR REPLACE INTO employee_overall_spend VALUES (?,?,?,?,?,?,?,?)',
            (*employee_spend, dt.now().strftime("%d/%m/%Y"), flag)
        )

Use SQL

If you chose to use SQL I'd change it so that you pass higher and lower to the SQL query.
I'd move the flag logic into the SQL query.
I'd move the current time logic into the SQL query. I found how to get the current time from here.
I'd look into moving the SQL commands into their own files, so that they're easier to maintain.

I'm don't know SQL, but you could use something like:

CALCULATE_EMPLOYEE_SPEND_READ = '''\
DECLARE @curr_date DATETIME;
SET @curr_date = GETDATE();

SELECT
    e.employee_id,
    e.amount,
    e.spend,
    e.date,
    e.spend_left,
    e.percent_diff,
    @curr_date as curr_date,
    case when
        e.date <= @curr_date
        and (
            e.amount > 500
            and e.percent_diff < ?
            or e.amount < 500
            and e.percent_diff < ?
        )
        then 1
        else 0
    end
    as flag
FROM (
    SELECT distinct
        b.employee_id,
        b.amount,
        s.spend,
        b.date,
        b.amount - s.spend as spend_left,
        100.0 - 100.0*s.spend / b.amount as percent_diff
    FROM employee_budget_upload As b
    JOIN employee_budget_spent As s
    ON  b.employee_id = s.employee_id
    WHERE b.amount != 0
) as e
'''
CALCULATE_EMPLOYEE_SPEND_WRITE = 'INSERT OR REPLACE INTO employee_overall_spend VALUES (?,?,?,?,?,?,?,?)'

def calculateEmployeeSpend(read_cursor, higher, lower):
    read_cursor.execute(CALCULATE_EMPLOYEE_SPEND_READ, (int(higher), int(lower)))
    for employee_spend in read_cursor:
        write_cursor.execute(CALCULATE_EMPLOYEE_SPEND_WRITE, employee_spend)


Process string vector and change each string to uppercase

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

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).

Consider using standard algorithms

There is nothing wrong with your transformation of the words to uppercase, but it may be useful to consider an alternative using a standard algorithm.  In particular std::transform may be useful here:

for(string &s : stringVector){
    std::transform(s.begin(), s.end(), s.begin(),
        [](char c){ return std::toupper(c); });
}

Use a counter rather than the % operator

It's not really necessary to use the % operator here.  It may not make any difference for this particular application, but on many processors, the % operator requires more CPU cycles (and therefore time) while counting down is usually very fast.

Minimize the number of iterations through the vector

The code currently makes three passes through the data.  First, it gets the input, next it transforms to upper case, and finally it emits the opper case versions of the input words.  These could all three be done in a single pass, although doing so doesn't quite match the given instructions.  The advantage, however, is that now a std::vector isn't even needed any longer.  Written that way the program might look like this:

#include <iostream>
#include <string>
#include <algorithm>
#include <ctype>

int main()
{
    constexpr unsigned WORDS_PER_LINE = 8;
    std::string s;
    unsigned wordcount = WORDS_PER_LINE;
    while(std::cin >> s){
        std::transform(s.begin(), s.end(), s.begin(),
            [](int c){ return std::toupper(c); });
        std::cout << s << ' ';
        if (--wordcount == 0) {
            std::cout << '\n';
            wordcount = WORDS_PER_LINE;
        }
    }
    std::cout << '\n';
}

Omit return 0

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.


Algorithmically, your implementation seems fine. One improvement would be to initialize the sortedList to the first node right away. This necessitates some error checking up front, which I think is better style anyway.

I would also run a check for the current node being the new sorted head first. That way I can automatically assume that I'm inserting after the search position. That allows elimination of the previous variable.

But this is all stylistic stuff to make the logic flow easier to understand. As I said, I think your implementation functions perfectly well.

public static Node insertNode(Node node) {
    if (node == null)
        return null;

    // Make the first node the start of the sorted list.
    Node sortedList = node;
    node = node.next;
    sortedList.next = null;

    while(node != null) {
        // Advance the nodes.
        final Node current = node;
        node = node.next;

        // Find where current belongs.
        if (current.value < sortedList.value) {
            // Current is new sorted head.
            current.next = sortedList;
            sortedList = current;
        } else {
            // Search list for correct position of current.
            Node search = sortedList;
            while(search.next != null && current.value > search.next.value)
                search = search.next;

            // current goes after search.
            current.next = search.next;
            search.next = current;
        }
    }

    return sortedList;
}

See it run in JavaScript: http://jsfiddle.net/2LDGD/2/


You SHOULD consider migrating to Angular (aka Angular2, aka Angular5) from ANgularJS (version 1), as it's not developing and soon won't be supported anymore.
I guess nested promises would be much useful here (more details below).

Rewrite init() as follow

function init() {
  return mainService.get().then(function (response) {
    if (response) {

    }
    $scope.isLoading = false;
  });
}

And in main block instead of

mainService.post(alteredItems).then(function (response) {
  init();
})

Write:

mainService.post(alteredItems).then(function (response) {
  return init();
})

In this case your finally would be called AFTER bot async calls completed.

P.S. Consider using library cg-buisy https://github.com/cgross/angular-busy
It automates displaying of loading indicator and accepts promises. Used it a lot in production.


Find a list of Windows Services by given criteria

These are my suggestions:

Get rid of all the ugly and duplicate ifs by replacing them with two dictionaries where each one returns a Func.
Use Regex for all searching criteria by creating appropriate patterns or returning the SearchString if it's the pattern.

Example:

var propertygGetters = new Dictionry<SearchServiceBy, Func<Service, string>>
{
    [SearchServiceBy.ServiceName] => s => s.ServiceName,
    ...
}

var patternCreators = new Dictionry<SearchOption, Func<string, string>>
{
    [SearchOption.Equals] => s => $"^{s}$",
    [SearchOption.Contains] => s => $"{s}",
    [SearchOption.StartsWith] => s => $"^{s}",
    [SearchOption.EndsWith] => s => $"{s}$",
    [SearchOption.Regex] => s => s,
}

var getProperty = searchStringGetters[SearchServiceBy];
var createPattern = patternCreators[SearchOption];

var pattern = createPattern(SearchString);

return
    allServices
        .Where(service => Regex.IsMatch(getProperty(service), pattern))
        .ToList();

(warning: notepad programming)


Resolve alias' original item using bookmarkData

Memory management

The use of NSAutoreleasePool makes it apparent that this code is compiled  manual reference counting. That is error-prone, as you'll see now: Here

NSString *string = [[NSString alloc] initWithUTF8String:filepath];
NSString *relString = [[NSString alloc] initWithUTF8String:ref];
NSURL *actual = [[NSURL alloc] initByResolvingBookmarkData ...];

are objects allocated but never released. That makes several memory leaks on each invocation of the method.

The easiest fix would be to use automatic reference counting (ARC) instead. ARC is available since Mac OS 10.6, and there is no reason not to use it. You only have to adjust the compiler flags (i.e. do not pass -fno-objc-arc to the compiler) and replace (compare this)

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// ...
[pool drain];

by

@autoreleasepool {
    // ...
}

The compiler takes care of everything else and inserts retain and release calls where appropriate.

If – for whatever reason – switching to ARC is not feasible then you have to fix the above-mentioned issues. You can add the needed release calls, e.g.

NSString *string = [[NSString alloc] initWithUTF8String:filepath];
// ...
[string release];

or (perhaps simpler) create autoreleased objects (which are released on return of the function, when the autorelease pool is drained):

NSString *string = [NSString stringWithUTF8String:filepath];
NSURL *actual = [NSURL URLByResolvingBookmarkData ...];

string can also more simply be created as a “boxed C string”:

NSString *string = @(filepath);

Another error is here:

char resolved[100]; /*resolved path in C; need to get length of the string, not arbitrarily 100 */
strcpy(resolved, [actual fileSystemRepresentation]);
// ...
return tempPath;

because the function returns the address of a local variable, which is undefined behavior.

You can make the character buffer static: That seems to be what similar functions in the blender project do. The disadvantage is that subsequent calls to the function overwrite the buffer.

Or you can allocate a new string, and the caller has to release the memory eventually.

Error handling

The correct way to check for success or failure of Cocoa (Touch) methods is
documented in
"Handling Error Objects Returned From Methods" in the "Error Handling Programming Guide":

  Important: Success or failure is indicated by the return value of the
  method. Although Cocoa methods that indirectly return error objects in
  the Cocoa error domain are guaranteed to return such objects if the
  method indicates failure by directly returning nil or NO, you should
  always check that the return value is nil or NO before attempting to
  do anything with the NSError object.

In your case, the correct way to check for the success of

NSData *bmdata = [NSURL bookmarkDataWithContentsOfURL:url error:&error];

would be

if (bmdata == nil) {
    NSLog(@"Error: %@",error);
}

But NSLog()ing the error is not sufficient: You have to report the failure to the caller, e.g. by returning a nullptr:

if (bmdata == nil) {
    NSLog(@"Error reading bookmark data for %@: %@",url, error);
    [pool drain];
    return nullptr;
}

Note that (if you keep the manual reference counting) you must take care that the autorelease pool is drained on any return from the function.

The same error handling must be done when resolving the bookmark data, that is missing completely.

More remarks

relString and relativeURL are not needed, you can simply pass nil to the relativeToURL argument.
isStalePointer is not needed, you can pass &isstale directly to the bookmarkDataIsStale argument. Or pass nil is you are not interested in the outcome (at present, the staleness is not evaluated in your code).

File system paths conversions

The conversion from an NSURL back to a C string with

char resolved[100];
strcpy(resolved, [actual fileSystemRepresentation]);

suggests that the C strings represent “file system paths” and in that case the correct counterpart for the conversion from the given filepath to an NSURL is

NSURL *url = [NSURL fileURLWithFileSystemRepresentation:filepath
                                            isDirectory:NO
                                          relativeToURL:nil];

But a buffer with 100 characters may be too short: Either determine the needed length dynamically, or use MAXPATHLEN from the system include files. Also strcpy does not check if the target buffer is large enough (potentially causing a memory corruption). Better use

static char resolved[MAXPATHLEN];
if (![actual getFileSystemRepresentation:resolved maxLength:sizeof(resolved)]) {
    NSLog(@"File system path too long for %@", url);
    [pool drain];
    return nullptr;
}

Putting it together

Putting all the above suggestions together, the code (with manual reference counting) would be

const char *YourClass::resolveAlias(const char *filepath) const {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSURL *url = [NSURL fileURLWithFileSystemRepresentation:filepath
                                                isDirectory:NO
                                              relativeToURL:nil];
    NSError *error = nil;
    NSData *bmdata = [NSURL bookmarkDataWithContentsOfURL:url error:&error];
    if (bmdata == nil) {
        NSLog(@"Error reading bookmark data for %@: %@",url, error);
        [pool drain];
        return nullptr;
    }
    NSURL *actual = [NSURL URLByResolvingBookmarkData:bmdata
                                              options:NSURLBookmarkResolutionWithoutUI
                                        relativeToURL:nil
                                  bookmarkDataIsStale:nil
                                                error:&error];
    if (actual == nil) {
        NSLog(@"Error resolving bookmark data for %@: %@", url, error);
        [pool drain];
        return nullptr;
    }

    static char resolved[MAXPATHLEN];
    if (![actual getFileSystemRepresentation:resolved maxLength:sizeof(resolved)]) {
        NSLog(@"File system path too long for %@", url);
        [pool drain];
        return nullptr;
    }

    [pool drain];
    return resolved;
}

Further simplification

As of macOS 10.10 the NSURL class has a

+ (instancetype)URLByResolvingAliasFileAtURL:(NSURL *)url
                                     options:(NSURLBookmarkResolutionOptions)options
                                       error:(NSError * _Nullable *)error;

initializer, which both reads and resolves the bookmark data. The function then simplifies to (now with automatic reference counting):

const char *YourClass::resolveAlias(const char *filepath) const {
    static char resolved[MAXPATHLEN];
    @autoreleasepool {

        NSURL *url = [NSURL fileURLWithFileSystemRepresentation:filepath
                                                    isDirectory:NO
                                                  relativeToURL:nil];
        NSError *error = nil;
        NSURL *resolvedURL = [NSURL URLByResolvingAliasFileAtURL:url
                                                      options:NSURLBookmarkResolutionWithoutUI
                                                        error:&error];
        if (![resolvedURL getFileSystemRepresentation:resolved maxLength:sizeof(resolved)]) {
            NSLog(@"File system path too long for %@", url);
            return nullptr;
        }
    }
    return resolved;
}


Instead of adding data-properties to the body tag, and waiting for / relying on jQuery, just use an inline script:

<script type="text/javascript">
    var modules = /* echo the needed modules here */;
    for (var i=0; i<modules.length; i++)
        App[modules[i]]();
</script>


Semantics
In the languages that implement try, throw and catch the scope is generally larger than a single function. The scope of the exception handling is set by the try block and the catch block. The C goto is limited to the current function, to jump outside of the current function you need to use setjmp() and longjmp(). Your implementation does not seem to use setjmp() and longjmp().

Maintainability
Using a goto is generally decreasing maintainability, hiding a goto is a bad idea. If I have to maintain code that contains a goto I want to be able to immediately know that there is a goto and I want to be able to find the label immediately as well.

Performance
A reason to use goto is to improve performance. When goto's actually degrade performance that is another reason not to use them.


I have been working on this code to meet the best OOP standards for production.

I think your biggest problem here is that PriceCalculator does too many things:

Getting user input
Calculating the price per checkout item
Calculating the total price
Printing the bill

Let's try to split this up a bit first by introducing a BillRow for each line in your Bill to which we delegate to calculate the price per row .
class Bill
  def initialize(purchased_items:)
    @purchased_items = purchased_items
  end

  def total
    rows.inject(0) { |sum, x| sum + x.total }
  end

  def discounted_total
    rows.inject(0) { |sum, x| sum + x.discounted_total }
  end

  def rows
    @rows ||= fetch_rows
  end

  private

  attr_reader :purchased_items

  def fetch_rows
    count_items.map do |item, quantity|
      BillRow.new(name: name, quantity: quantity)
    end
  end

    def count_items
      purchased_items.inject(Hash.new(0)) do |quantity, item|
        quantity[item] += 1
        quantity
      end
    end
end

class BillRow
  attr_reader :name, :quantity

  def initialize(name:, quantity:)
    @name = name
    @quantity = quantity
  end

  def total
    @_total ||= quantity * item_price
  end

  def discounted_total
    @_discounted_total ||= calculate_discounted_total || total
  end

  private

   def calculate_discounted_total
    return unless sale_item

    ((quantity / sale_item['units'])) * sale_item['price']) + ((quantity % sale_item['units']) * item_price)
   end

    def sale_item
      @_sale_item ||= SaleItem.all[name]
    end

    def item_price
      Item.all[name]
    end
end

Bill.new(['milk', 'milk', 'bread'])

Additionally we will extract the display method to it's own class.
class BillPrinter
  def initialize(bill:)
    @bill = bill
  end

  def print
    print_header
    print_rows
    print_total
  end

  private

  def print_header
    puts "Item     Quantity      Price"
    puts "--------------------------------------"
  end

  def print_rows
    bill.rows.each do |row|
      puts "#{row.item_name.ljust(10)} #{row.quantity}           $#{row.total.round(3)}"
    end
  end

  def print_total
    puts "Total price : $#{bill.total.round(3)}"
    puts "You saved $#{(bill.total - bill.discounted).round(3)} today."
  end
end

bill = Bill.new(['milk', 'milk', 'bread'])
BillPrinter.new(bill: bill).print

I will skip getting the user input as this is can basically go to the main method.
Splitting the PriceCalculator into three classes has several advantages.

Easier to test: We can pass in data instead of user input
Classes are smaller and have only one responsibility
Easier to extend and maintain e.g. if we want to use it on a website instead the console we need to refactor the code (user input read from StdIn and bill printed to StdOut). Now we can just implement a HtmlBillPrinter for instance.
We can easier memoize data (efficiency)

The code is working but I wish to make this a more efficient code

In terms of efficiency, the biggest issue is that you calculate some values several times and look it up several times. This might be fine and the most important rule when making something more efficient is to first identify the bottleneck before jumping into optimize it. Readable code is usually preferred over complicated but efficient code.
To sum it up, I think the biggest improvements can be made in a better object oriented approach which allows you to more aggressively memoize values (https://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem/) as well as working with objects instead of e.g. arrays and hashes (BillRow vs [quantity, value]) which allows you to split out more readable methods too.
Edit:
As you mention 'production' I also just want to mention that you should NEVER use float for monetary values because they're not accurate (https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency). You should use integer and represent the price e.g. in cents. Even better would be to use a money gem (https://github.com/RubyMoney/money).
Another improvement would be to use objects in your SalesItem and Item classes.
class SaleItem
  @@sale_items = {}

  attr_reader :name, :units, :price

  def initialize(name:, units:, price:)
    @name = name
    @units = units
    @price = price
  end

  def initialize(name, units, price)
    @@sale_items[name] = new(name: name, units: units, price: price)
  end

  def self.all
    @@sale_items
  end
end
```


Parsing messages with fixed-width fields into Employee objects

Why is everything static? It's not necessarily wrong, but it may make integration into a larger project more ugly.

EDIT: Some background to this: A static utility class makes other classes that depend on it difficult to use and test. It basically breaks the principal called Inversion of control.

Instead of having a second class hard-code the reference to such a static "employee factory" like this, it is given an instance of a "employee factory class" (e.g. as a constructor argument). That way the "employee factory" can easily be replaced without touching the second class.

This is especially interesting when you want to test that second class. In that case you don't need to worry about setting up the real "employee factory" and making sure that it works. Instead you can give the second class a so called mock class, that just simulates the workings of the "employee factory" and, for example, just returns hard-coded, predetermined employees.

The conditional operator (? :) in boolMapper is unnecessary:

public static boolean boolMapper(char value){
    return value == 'Y';
}

As @gervais.b says, formatting the date string to include the hyphens is unnecessary. You can parse the date directly with the pattern yyyyMMdd. Also you shouldn't create a new DateTimeFormatter instance in each method call. Instead use an instance stored in a static constant field:

private final static DateTimeFormatter EMPLOYEE_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

public static LocalDate dateMapper(String value){
    return LocalDate.parse(value, EMPLOYEE_DATE_FORMATTER);
}

Don't unnecessarily abbreviate variable/class names. Use Employee instead of Emp, use dateOfBirth instead of dob, etc.

Considering you are converting dob and shiftNeeded to "proper" Java types, you should consider also consider converting gender, jobType and empLevel, which you currently store as a chars, into something more Java-esk, eg. enumerations.


Well, you could use Array.filter to filter the launches.

...
case 'filterLaunches':
  return Object.assign({}, state, {
    filteredLaunches: state.launches.filter(function(launch) {
      return action.location === launch.location.countryCode
    })
  }
default:
 return state;

The other question is, why not filtering inside the Component directly?

Because your next problem will be, that each time you add launches, you will have to filter them and copy again, and again.

So to not create duplicates, it's better to set the filter in the reducer and perform the filtering inside the render

So:

export default function(state = initialState, action) {
  case 'SET_LAUNCHES':
    return {...state, launches: action.launches };
  case 'SET_FILTER':
    return {...state, filter: action.filter };
  default:
    return state;
}

export function filterLaunches(launches, filter = {location: 'ES'} ) {
  const filterKeys = Object.keys(filter);
  return launches.filter((launch) => {
    return filterKeys.reduce((acc, key) => acc && launch[key] === filter[key], true)
  });
}

// Then in the component
import { filterLaunches } from '../launchesStore';

const LaunchesList = ({launches, filter}) => (

    {filterLaunches(launches, filter).map((launch) => (

Launch: {launch.name}

    ))}

);

export default connect(LaunchesList);

It's good to keep the filterLaunches function next to the reducer, because this function is very related to this part of the state and if you change the format like from an array to a map-by-id you would have to change that function only in one place.


Ah, the age old pragmatism vs. purism. While it sounds like you have a healthy amount of skepticism, I think this is actually one of the few instances where it's OK to use a global variable. The core of your problem is you need to share data (state) between two routes. A global variable is the simplest way of doing this if all you're doing is appending the number 4 each time.

Here's some things to consider:

Security: You mentioned security. Will any sensitive information be stored in global_list? If so, you should consider putting safegards in place (authentication and authorization) to make sure only the right people see the appropriate information. Also, if you store user input to the variable, be very careful how you use the data (SQL injection).
Persistence: Will state need to be maintained across webserver restarts? If everything is in a Python variable, it will be lost when you shut down the process. You may want to persist the data to a filesystem or database.
Resources: Are you going to be storing lots of information in this global variable? If so, the process may run out of memory, because the global variable is never garbage collected. The solution here is to store the data somewhere and generate aggregate data to use in the app instead (or do pagination).
Shared-state side effects: Anytime you share data, you have to be conscious of side effects caused by altering this data. If two routes are reading/writing from the same variable, one route could do something that breaks the other route.

More on resources:

For instance, if you store 1KB every time the / route is loaded and get 1M visitors a month, you'd be up to 1GB of memory just for global_list in around 1 month. 1KB is a lot of data, and you probably don't need all of this information to do your calculation in /test. Instead, you could aggregate the data by using global_list as a running total for the full set of data stored elsewhere (a database or filesystem).

If you're doing more than simply presenting a count of records in /test, and you need whole (or partial) records, then you can do pagination. Let's say you're presenting a list of the records in global_list. In this case, /test could simply return the first 10 records by default, but allow the user to see more pages by providing a page parameter. So if the user wants to see records 31-40, they could request /test?page=4


The trick is not to loop to determine how many extra elements there is to add but to calculate them. A little mathematical consideration can show that you need to add 19 * marks.length - 2 * total elements.

So a faster solution would be:

public static int need(int[] marks) {
    int total = 0;
    for (int x : marks)
        total += x;

    return Math.max(19 * marks.length - 2 * total, 0);
}

If the number of extra steps to add with the result of that calculation is negative, it means the input array already satisfied the condition and we can return 0.

Here are the result of a small JMH benchmark comparing the code in your question and the above code. The two codes are given a random array of integers between 0 and 10, with a size going from 100,000 to 100,000,000 (Windows 10, JDK 1.8.0_66, i5 3230M @ 2.60GHz).

Benchmark             (arraySize)  Mode  Cnt     Score    Error  Units
StreamTest.testNeed        100000  avgt   30     8,208 ±  0,218  ms/op
StreamTest.testNeed       1000000  avgt   30    78,823 ±  0,834  ms/op
StreamTest.testNeed      10000000  avgt   30   798,294 ±  7,651  ms/op
StreamTest.testNeed     100000000  avgt   30  8038,244 ± 77,131  ms/op
StreamTest.testNeed2       100000  avgt   30     0,037 ±  0,004  ms/op
StreamTest.testNeed2      1000000  avgt   30     0,621 ±  0,179  ms/op
StreamTest.testNeed2     10000000  avgt   30     4,143 ±  0,090  ms/op
StreamTest.testNeed2    100000000  avgt   30    41,597 ±  1,499  ms/op

This shows a tremendous improvement! The code is at least 100x faster.

@Warmup(iterations = 10, time = 1000, timeUnit = TimeUnit.NANOSECONDS)
@Measurement(iterations = 10, time = 1000, timeUnit = TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(3)
public class StreamTest {

    private static final Random RANDOM = new Random();

    @State(Scope.Benchmark)
    public static class ArrayContainer {

        @Param({ "100000", "1000000", "10000000", "100000000"})
        private int arraySize;

        private int[] marks;

        @Setup(Level.Iteration)
        public void setUp() {
            marks = RANDOM.ints(arraySize, 0, 10).toArray();
        }

    }

    public static int need( int[] marks ){
        double average = 0, total = 0;
        int extras = 0;

        for( int x : marks )
            total += x;

        average = total / marks.length;

        if( average >= 9.5 )
            return 0;

        while( average < 9.5 ){
            extras++;
            total += 10;

            average = total / ( marks.length + extras );
        }

        return extras;
    }

    public static int need2(int[] marks) {
        int total = 0;
        for (int x : marks)
            total += x;

        return Math.max(19 * marks.length - 2 * total, 0);
    }

    @Benchmark
    public int testNeed(ArrayContainer c) {
        return need(c.marks);
    }

    @Benchmark
    public int testNeed2(ArrayContainer c) {
        return need2(c.marks);
    }

}


Pure bash program for auto-filling a template file with ENV variables

Make the template variable name extraction more strict

The Awk command extracts the template variable names using the pattern /{{ (.*) }}/.
This leaves some room to human errors.
For example excess whitespace, as in {{  MY_VAR   }}.
This can be especially frustrating for trailing whitespace, which will be invisible when printing the list of missing variables.
I think it would be good to strip whitespaces after {{ and before }}.

But that's not quite enough. Consider such line in the input:

hello there {{ MY_VAR1 }} foo bar {{ baz }}

Although using multiple variables is explicitly unsupported,
this blows up in the face of the user in a nasty way:

$ MY_VAR1=foo/bar/bazo MY_VAR2=bar bash script.sh input.txt
a.sh: line 19: MY_VAR1 }} foo bar {{ baz: bad substitution
a.sh: line 33: MY_VAR1 }} foo bar {{ baz: bad substitution
hello there {{ MY_VAR1 }} foo bar {{ baz }}
some other stuff
some other stuff
foo: {{ MY_VAR2 }}
{{ MY_VAR2 }} is the value of MY_VAR2

The error messages are unfortunately incomprehensible.

Since the template variable names are expected to take values from shell variables,
it would make sense to enforce a stricter pattern.

Even if the script is not intended to handle sophisticated scenarios,
I think it should handle such user mistakes more gracefully.

Consistency

The Sed command replacing template variable names with values uses the pattern \\{\\{ *${var} *}}.
This is not consistent with the one in the Awk command,
because of stripping the whitespace.
As mentioned earlier, I would adjust the Awk command to make it consistent.

Error handling

In the example above with a user mistake,
the script continued to execute even after the error.
To catch such issues and terminate the program early I recommend adding this line at the very beginning:

set -euo pipefail

Beware of some gotchas

/ in the template variable names and values will break the Sed command.

As for the names, a more strict handling as mentioned earlier will prevent this issue.

As for the values, / appearing in the values doesn't sound too crazy,
because I can easily imagine wanting to insert path strings.
So I think it's a legitimate concern that would be good to address.

Usability

The limitation to one template variable per line seems a bit artificial.

Currently the script fails fast when the user mistakenly tries to use multiple per line, that's a good behavior to preserve.
(I'm pointing this out because if you simply enforce more stricter checking on the name patterns, this fail-fast behavior may no longer be the case.
And if I had to choose between cryptic failures, and quietly ignored missed template variables, I would prefer cryptic failures.)