Given {origin, destination} objects, find all the paths from a place to another

So first a quick refactor of the input object.
const Links = links => links.split(",").map(link => ({origin: link[0], dest : link[1]}));

So now links as created using Links("ab,bc,ac"); which is easier to deal with.

Cycles never end.
This problem is not as simple as it first appears.
All path finding algorithms need to be aware of the paths that lead in circles.
Your problem "ab,ac,bc,bd,dc,de" and the solutions for this are "abc", "abdc", and "ac". but if we change the last link to "da" we create a circular link. Your code will follow "abdabdabdab...." and so on until the call stack overflows.
In most recursive problems where you encounter a cyclic reference you can easily avoid the endless recursion by simply tracking the objects you have already referenced. Ending the recursion when you find a link that has already been traveled.
But your problem requires ALL paths  which complicates the problem (Actualy impossible as cyclic links create infinite paths).
Consider the links "ab,ac,bc,bd,dc,da"
It has the following solutions

ab, bc
ab, bd, dc
ab, bd, da, ac
ac

If we marked all traveled then 3 would mark link ac as traveled and thus block solution 4.
Note: that the solutions include as many links as possible  without repeating.
The following is not a valid solution as "ad" is repeated

ab, bd, da, ab, bc

Currently your function crashed when presented with cyclic links.
Back to your code.
Now lets inprove your code. The code is too complex and very hard to read.

function getDestinations(origin, destinationEnd) {
  let destinations = payloads.filter(payload => payload.origin === origin);
  destinations = destinations.map(destination => {
    const destinationsRecursive = getDestinations(destination.destination, destinationEnd);
    if (destinationsRecursive.length) {
      return Object.assign({}, destination, {
        next: destinationsRecursive
      });
    } else if (destination.destination === destinationEnd){
      return Object.assign({}, destination, {
        end: true
      });
    }
  })
  destinations = destinations.filter(destination => destination !== undefined)
  return destinations;
}

Refactoring.

Some bad naming needs fixing

payload becomes links and you use destination to mean a link, we can abbreviate destinationEnd as dest and getDestinations makes more sense as getPaths with destinationsRecursive better called paths

Some redundancies to remove

Links filter, map, filter can be chained.
Also Object.assign is a bit noisy you can use {...obj} to do the same.
So now the function looks like
function getPaths(origin, dest) {
    return links
       .filter(link => link.origin === origin)
       .map(link => {
           const paths = getPaths(link.dest, dest);
           if (paths.length) {
               return {...link, more: paths};
           } else if (link.dest === dest){
               return {...link, end: true};
           }
      })
      .filter(link => link !== undefined);
}

Which is a lot more readable.
Performance
Now the problem of performance. map, and filter are both slow and use more memory than is needed. Each recursive call does not release memory until you exit, which happens at the end of the searches.  Plus all the paths that are not part of the solution that you filter out each iteration
A quicker solution using a simple loop and changing when you create the new path  so you don't need to hold paths that go no where.
function solvePaths(start, end, paths = []) {
    for (const link of links) {
        if (link.origin === start) {
            if (link.dest === end) {
                paths.push({...link, end : true});
            } else {
                const tryPath = solvePath(link.dest, end);
                if (tryPath.length) { paths.push({...link, more: tryPath}) }
            }
        }
    }
    return paths;
}

This avoids creating endless copies of the of the links array, via the filter and map methods. It also solves the problem of paths that fail.
Now to fix the cyclic reference problem
To do this you need to track the traveled path to each destination.
I have created a stack that tracks the current path links "traveled". When end points are found the current links are popped of the traveled stack so that the links are free to be use for another path to the destination.
The code is in the example below.
Well I think it works, it stops the crash, whether it finds all solutions may need some very in depth research which is beyond the scope of this answer.
UPDATED code snippet
I wanted to be sure that the function worked so did some more testing, and while I was doing it I realized that a further improvement could be made.
The problem is that each step requires the entire array of links to be iterated, checking if each link has the correct origin.
That can be offloaded to the creation of the links array. Using a Map indexed by origin allows the main loop to only loop over the links with the correct origin ( links.origins(start) returns a pre-existing array of links with origin start). This is a significant performance increase.

function createLinks(links) {
    const byOrigin = new Map();
    links = links.split(",").map(link => {
        const origin  = link[0];
        const linkObj = {dest : link[1], origin};
        const origins = byOrigin.get(origin);
        if (!origins) { byOrigin.set(origin, [linkObj]) }
        else          { origins.push(linkObj) }
        return linkObj;
    })
    links.origins = origin => (origin = byOrigin.get(origin)) ? origin : [];
    return links;
}

function solvePath(start, end, links) {
    const traveled = [];
    return (function solvePath(start, end, paths = []) {
        for (const link of links.origins(start)) {
            if (!traveled.includes(link)) {
                if (link.dest === end) { paths.push({...link}) }
                else {
                    traveled.push(link);
                    const more = solvePath(link.dest, end);
                    if (more.length) {  paths.push({...link, more}) }
                    traveled.pop();
                }
            }
        }
        return paths;
    }) (start, end);
}

function show(paths, trek, treks = []){
    for (const path of paths) {
        if (path.more) { show(path.more, (trek === null ? path.origin : trek) + "> "+ path.dest,treks) }
        else {  treks.push((trek ? trek : path.origin) + "> "  + path.dest) }
    }
    return treks;
}

const _$ = (type,props)=>document.body.appendChild(Object.assign(document.createElement(type),props));

const theMap = "AB,AC,BC,BD,DC,DE,EC,DA,ED,EG,GD";
_$("div",{textContent : "Links : " + theMap});
show(
    solvePath("A","C",createLinks(theMap))
    ,null
).forEach(path=>_$("div",{textContent : path}))


First of all it is useless to use __set or __get if you're trying to access the non existing property that might also cause a cyclic request of the method.  Instead you should have  an array that contains the values  now second thing if you will have the property inside the object the __set or __get methods won't be called. So you should fix those and it should work.  If needed I will post a code with the fix

<?php
interface INotifyPropertyChanged
{
    function PropertyChanged($name);
    function RegisterChangeCallback($callback);
}

abstract class NotifyPropertyChanged implements INotifyPropertyChanged
{
    public $changes;
    public $trackChanges;
    private $callback;
    protected $values = array();
    public function PropertyChanged($name)
    {
        if( $this->callback != null){
            call_user_func($this->callback, $name);
        }

        if( !isset($this->changes))
            $this->changes = Array();

        if( !in_array($name, $this->changes))
            $this->changes[$name][] = $this->$name;
    }

    public function RegisterChangeCallback($callback)
    {
        $this->callback = $callback;
    }

    public function __set($name, $value)
    {
        $previousValue = $this->$name;
        if( $this->trackChanges && $previousValue !== $value) {
            $this->PropertyChanged($name);
        }
        $this->values[$name] = $value;
    }

    public function __get($name)
    {
    if(array_key_exists($name,$this->values)){
        return $this->values[$name];
        }
        return null;
    }
}

class SampleClass extends NotifyPropertyChanged
{
}

$class = new SampleClass();
$class->name = "value";
$class->trackChanges = true;
$class->name = "test";
$class->name = "test2";
var_dump($class->changes);

the above code results which also allows you to have all changes

array(1) {
    ["name"]=>
    array(2) {
        [0]=>
        string(5) "value"
        [1]=>
        string(4) "test"
    }
}


Synchronized block over concurrent collections

It looks like you are trying to re-invent the CopyOnWriteArrayList.

By the way, Vector is very old fashioned, but I guess you are working with legacy code.  The code also does not use generics.  CopyOnWriteArrayList started with Java 5, so might not be able to use it if you are stuck with an older Java version.


It mostly looks fine. Some things I would change:

var userName = document.forms["register"]["username"].value;
var passWord = document.forms["register"]["password"].value;

I would extract the repetition here to get the form. This makes the code cleaner and makes it simpler if you change the name of the form.

var form     = document.forms["register"];
var userName = form["username"].value;
var passWord = form["password"].value;

Here

if (userName == null || userName == "") {

You could just use

if (!userName == null) {

One last thing is that you probably want to check and remove leading and trailing spaces in the user name (and possibly in the password). There is a built in trim method you can use if you're not targeting IE8.


There's no reason to use bind; you don't rely on this anywhere in the code, so it doesn't matter what the this-context is.

Secondly, the "original" way to iterate objects in JavaScript is to use a for...in loop. However, it will also iterate inherited properties, so it's good practice to check if the key's the object's own key by using hasOwnProperty. The basic construction looks like so:

var key;
for(key in object) {
  if(!obj.hasOwnProperty(key)) continue; // skip inherited properties
  // ... do something
}

Thirdly, due to the way JavaScript expresses a NaN (Not A Number) value, it turns out that typeof NaN === 'number'. Of course, it doesn't really matter here since Math.round(NaN) is still NaN.

Point is, this would probably be one of the simplest implementations:

var key;
for(key in cmd) {
  if(obj.hasOwnProperty(key) && typeof cmd[key] === 'number') {
    cmd[key] = Math.round(cmd[key]);
  }
}


Selecting all posts created by user that actual user follows

Let's focus on the selecting.

class MyPage(ListView):
    model = Post

    def get_queryset(self):
        posts = []
        for user in self.request.user.followers.all():
            for post in Post.objects.filter(author=user.followed):
                posts.append(post)

        return posts

This is a bit convoluted: you're performing a lot of queries (depending on how many followers a user has). Ideally you'd like to perform just one query.

Also, get_queryset looks like it will return a queryset, instead of a list.

class MyPage(ListView):
    model = Post

    def get_queryset(self):
        return Post.objects.filter(author__followers__follower__id=self.request.user.id)

Should work just as well, and returns an actual queryset. (I'm not sure if I got the exact syntax right, please look at https://docs.djangoproject.com/es/1.9/topics/db/queries/#spanning-multi-valued-relationships if it does not work).


By looking at values in your series of if's, you can make an array ([]), then calculate which index to pick:

var convert = {
    toCompass: function(degrees)
    {
        return ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'][Math.round(degrees / 11.25 / 2)];
    }
}

alert(convert.toCompass(140));      // SE

JSFiddle demo


Quoting page 173:

  Another obvious generalization is to allow the walker to move in three dimensions [...] For this simulation we have restricted the steps to be of unit length along either ±x, ±y, or ±z.

I think the author meant that at each time step the walker will walk in one of three random directions (x or y or z), not all three. Without making drastic changes to your code, you could replace this section:

 if (runif(1)<0.5) x <- x+1 else x <- x-1
 if (runif(1)<0.5) y <- y+1 else y <- y-1
 if (runif(1)<0.5) z <- z+1 else z <- z-1

with the following:

  direction <- sample(c("x", "y", "z"), 1)
  if (direction == "x") { if (runif(1)<0.5) x <- x+1 else x <- x-1 }
  if (direction == "y") { if (runif(1)<0.5) y <- y+1 else y <- y-1 }
  if (direction == "z") { if (runif(1)<0.5) z <- z+1 else z <- z-1 }

With this change, the slope is approximately 1, as shown in Figure 7.11.


You can use list unpacking to transform :

        takeaction = state_table[current_state][a][1]
        current_state = state_table[current_state][a][0]

into the more concise :

        current_state, takeaction = state_table[current_state][a]

. Also, it shows that the type you should be using to convey current_state and takeaction should probably be something more like a tuple than like a list.

The pythonic way to loop is not to use range and len but just to go through your iterable with for i in my_iterable:. If you do need the index, enumerate is what you need.

   for a in range(len(event_list)):
        if z in event_list[a]:
            takeaction = state_table[current_state][a][1]
            current_state = state_table[current_state][a][0]

becomes :

for i,event in enumerate(event_list):
    if z in event:
        current_state, takeaction = state_table[current_state][i]
        break

Remove whatever code is not needed.

elif takeaction == 5: # strip whitespace from the input outside of quotes
        pass
    else:
        pass # should raise error, since the state table includes more actions than are define

is roughly the same as nothing. If you want to ensure the value is correct, you can use assert.

From PEP 8 :

  For example, do not rely on CPython's efficient implementation of
  in-place string concatenation for statements in the form a += b or a =
  a + b. This optimization is fragile even in CPython (it only works for
  some types) and isn't present at all in implementations that don't use
  refcounting. In performance sensitive parts of the library, the
  ''.join() form should be used instead. This will ensure that
  concatenation occurs in linear time across various implementations.

Remove duplicated logic :

        takeaction = state_table[current_state][a][1]
        current_state = state_table[current_state][a][0]

and

   takeaction = state_table[current_state][-1][1] # this sets takeaction to the value when the test character does not match any event
    current_state = state_table[current_state][-1][0] # this sets current_state to the value when the test character does not match any event

are quite similar and probably can be factorised out.

Do not repeat yourself (bis) : you do not need to define the state table twice. Just do it once and for all and everything should be ok :

state_table = [
    [(1,0), (0,1), (5,0), (0,3), (0,4), (0,5), ( 2,0), (0,0), (6,0), (0,0), (0,0)], # normal state
    [(0,0), (1,0), (1,0), (1,0), (1,0), (1,0), ( 1,0), (1,0), (1,0), (1,0), (1,0)], # double-quote comment
    [(2,0), (2,0), (2,0), (2,0), (2,0), (2,0), ( 3,0), (0,0), (2,0), (2,0), (2,0)], # inside bracketed table reference
    [(3,0), (3,0), (3,0), (3,0), (3,0), (3,0), ( 4,0), (2,0), (3,0), (3,0), (3,0)], # inside double-bracketed table reference
    [(4,0), (4,0), (4,0), (4,0), (4,0), (4,0), (-1,0), (3,0), (4,0), (4,0), (4,0)], # inside triple-bracketed table reference (I don't think this exists)
    [(1,2), (0,2), (5,2), (0,0), (0,2), (0,5), ( 2,2), (0,2), (0,2), (0,2), (0,2)], # found left-paren; only wrap and insert if not empty, like =row()
    [(6,0), (6,0), (6,0), (6,0), (6,0), (6,0), ( 6,0), (6,0), (6,0), (0,0), (6,0)], # inside curly-braced array
]

Final result :

This is what my code is like at the end. I am too lazy to change the string concatenations for a better solution. Also, I'm still not quite happy with the multiple if statements but I have nothing better to suggest at the moment.

#!/usr/bin/python

# input_text = editor.getSelText()
input_text = '=HLOOKUP(TablePeriods[[#Headers],[YearMonth]],TablePeriods[[#All],[YearMonth]],MATCH([@Date],INDIRECT("TablePeriods[[#All],["&[@Account]&"]]"),-1))'

# initialize the state table
# event list and corresponding state table
event_list =     [ "\"",   "&",   "(",   ")",   ",", "\n\r\t ", "[",   "]",   "{",   "}"    ] # last event is anything that doesn't match one of the other actions
state_table = [
    [(1,0), (0,1), (5,0), (0,3), (0,4), (0,5), ( 2,0), (0,0), (6,0), (0,0), (0,0)], # normal state
    [(0,0), (1,0), (1,0), (1,0), (1,0), (1,0), ( 1,0), (1,0), (1,0), (1,0), (1,0)], # double-quote comment
    [(2,0), (2,0), (2,0), (2,0), (2,0), (2,0), ( 3,0), (0,0), (2,0), (2,0), (2,0)], # inside bracketed table reference
    [(3,0), (3,0), (3,0), (3,0), (3,0), (3,0), ( 4,0), (2,0), (3,0), (3,0), (3,0)], # inside double-bracketed table reference
    [(4,0), (4,0), (4,0), (4,0), (4,0), (4,0), (-1,0), (3,0), (4,0), (4,0), (4,0)], # inside triple-bracketed table reference (I don't think this exists)
    [(1,2), (0,2), (5,2), (0,0), (0,2), (0,5), ( 2,2), (0,2), (0,2), (0,2), (0,2)], # found left-paren; only wrap and insert if not empty, like =row()
    [(6,0), (6,0), (6,0), (6,0), (6,0), (6,0), ( 6,0), (6,0), (6,0), (0,0), (6,0)], # inside curly-braced array
]

# initialize the state, parenthesis depth, and output text
current_state = 0
paren_depth = 0
output_text = ""

# define the tab and new line characters
TAB_CHAR = "\t"
NEW_LINE = "\r\n"

for z in input_text:
    for i,event in enumerate(event_list):
        if z in event:
            break
    else:
        i = -1
    current_state, takeaction = state_table[current_state][i]
    if current_state == -1:
        current_state = 5 # -1 is an error and should be handled with some sort of error operation
    if takeaction == 0: # just pass the characters along
        output_text += z
    elif takeaction == 1: # place character at same depth as only one on line
        output_text += NEW_LINE + TAB_CHAR*paren_depth + z + NEW_LINE + TAB_CHAR*paren_depth
    elif takeaction == 2: # previous character was a left paren and this one is not a right-paren
        paren_depth = paren_depth + 1
        output_text += NEW_LINE + TAB_CHAR*paren_depth + z
    elif takeaction == 3: # character is a right paren not immediately following a left paren
        paren_depth = paren_depth - 1
        output_text += NEW_LINE + TAB_CHAR*paren_depth + z
    elif takeaction == 4: # character is a comma, so start a new line at the paren depth
        output_text += z + NEW_LINE + TAB_CHAR*paren_depth
    else:
        assert(takeaction == 5) # strip whitespace from the input outside of quotes
        pass # should raise error, since the state table includes more actions than are defined

# editor.replaceSel(output_text)
print(output_text)


Divs of any kind are a bit of a "lesser evil" -- they carry no semantic info, and should be used only when (1) you need an element there and (2) there's no semantic equivalent.

In this case, you do have a semantic equivalent.  You have rows, columns, headers...data that must be arranged in those rows/columns and have those headers or it doesn't make sense...what you have here is a bona fide table.  And it should be coded as one, rather than as a list of divs.  ("Tables bad, CSS good" applies to layout tables, not tables in general.  If you have tabular data, putting it in a table just makes sense.)


I question the following comment:

    # Should be quite fast since list is sorted.
    if prime_to_check_against * multiplier in list_of_ints:
        list_of_ints.remove(prime_to_check_against * multiplier)

Why will this be fast, due to the sorted list?  x in list doesn't understand that the list is sorted, nor does the remove(x).  No binary searching will be done; just a straight linear search.  Not fast.

I also question the following comment:

    # List was not modified.. Nothing to remove.
    if original_list_length == len(ints):
        break

Just because no multiples of 29 may remain in the list does not necessarily mean there are no multiples of 31!  The proper stopping condition is when you reach sqrt(upper_bound).

You are attempting to remove numbers you've already removed:

multiplier = 1
while prime_to_check_against * multiplier < list_of_ints[-1]:
    multiplier += 1
    if prime_to_check_against * multiplier in list_of_ints:
        list_of_ints.remove(prime_to_check_against * multiplier)

When you remove multiples of 13, for instance, you are starting by removing 13*2, and 13*3, and 13*4, and so on.

But you have already removed all the multiples of primes lower than 13.  You should start at 13*13,

    multiplier = prime_to_check_against
    while prime_to_check_against * multiplier <= list_of_ints[-1]:
        if prime_to_check_against * multiplier in list_of_ints:
            list_of_ints.remove(prime_to_check_against * multiplier)
        multiplier += 1

Finding and then removing.  You are searching the list twice: once to check if it exists, a second time to find it in order to remove it.

Instead, you could simply removed the item.

    try:
        list_of_ints.remove(prime_to_check_against * multipler)
    except ValueError:
        pass # it wasn't there

Even numbers as a special case.

ints = [2] + list(range(3, upper_bound, 2)) # Generate initial list of odd integers

# Initial prime for bootstrap
prime = 3
iteration_count = 1

And then, instead of increasing the multiplier by 1, you can increase it by 2, so you'd search 13*13, 13*15, 13*17, ...

        multiplier += 2

Skip all of the multiplications, and just increment by 2*prime_to_check_against

    multiple  = prime_to_check_against * prime_to_check_against
    increment = prime_to_check_against * 2
    while multiple <= list_of_ints[-1]:
        try:
            list_of_ints.remove(multiple)
        except ValueError:
            pass
        multiple += increment

Or more pythonically:

    for multiple in range(prime_to_check_against * prime_to_check_against,
                          list_of_ints[-1]+1, 2*prime_to_check_against):
        try:
            list_of_ints.remove(multiple)
        except ValueError:
            pass

Instead of populating a list with all of the candidate numbers, and then removing multiples of prime numbers from the list, which involves expensive list manipulations, you could:

create a bytearray(upper_bound) to store prime/not-prime flags
flag all multiples of prime numbers, as you find them, as not-prime
use list-comprehension to extract the indexes which are flagged as prime

Using a bytearray is very efficient memory-wise, and indexing into the bytearray to set or test a flag is a very fast \$O(1)\$ operation.

I'm trying to decide whether to post my 10-lines of code for the sieve here, or let you attempt it based on the above hints.  Let me know if you need it.


Script for a multi-user webapp database connection

Lets tackle your code point by point:

Security:

In terms of problems with security, I only see 1 problem:

There isn't any kind of encryption on your code.
From what I can see, you connect to a database that has all the password stored in plain text.
Any attacker that puts his hand on your file .dbinc.cred.inc.php will be very happy!

You can use the mcrypt list of function.
For documentation, you can check here: http://php.net/manual/en/ref.mcrypt.php

Edit:

As @EliasVanOotegem pointed out on his comment, the collation isn't being set.
Appending ';charset=latin1' to the string should do it.

If you are using a verson prior to 5.3.6, this will be ignored.
Instead, you must run $dbh->exec("set names latin1");
Source: https://stackoverflow.com/a/4361485
Luckly, PHP has a function to solve this kind of issue: version_compare().
The version can be checked like this: version_compare(PHP_VERSION, '5.3.6', '<')
Documentation: http://php.net/manual/en/function.version-compare.php

Now, you may ask: why not utf8?
The reason is that the default collation for most servers is in fact latin1_swedish_ci.
This means that a password like aç$%dKeä would be returned as scrambled data.
When you try to connect to the other database, using mysqli_*, the connection would be always rejected because the password would be different.

The code itself:

On the code itself, I see some problems too.

Lets make some sections for it.

The try{} block:

Inside the try{} block, you have the following code:

foreach ($statement as $row) {
   $user_db = $row['user_db'];
   $user_db_user = $row['user_db_user'];
   $user_db_pass = $row['user_db_pass'];
}

This code isn't wrong, but this is useful when you fetch multiple rows from the database.
Another thing is that you only use this code to assign the variables to the values from the database.
You should use the list() constructor, using also the $statement->fetch() method.
The above code can be rewritten into this:

list($user_db,$user_db_user,$user_db_pass)=$statement->fetch(PDO::FETCH_NUM);

Documentation:
list() constructor: http://php.net/manual/en/function.list.php
method $statement->fetch(): http://php.net/manual/en/pdostatement.fetch.php

The catch{} block:

Inside the catch block, you are using a print and on the next line you have an empty die().
Removing the print and placing the text on the die() will have the same effect.
This code:

  catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "
";
die();
}

Becomes:

catch (PDOException $e){
    die('Error!: ' . $e->getMessage() . '
');
}

This is not a real issue, but you are concatenating an empty string on the PDO initialization.
Here is the code:

$dbh = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE . '', USER_ONE, PASS_ONE);

Right after DB_ONE, you can remove that concatenation.

Outside the try ... catch{}`:

Outside the try ... catch{} block, you have this line:

$dbh = null;

This line, at the most, should be moved inside the try{} block, which is where you initialize the PDO object.

Other observations:

Your indentation is a little broken.
Indentation allows us to understand better where a block starts and finishes, and what is inside it.

This is just an observation, just for the paranoid people.

You fetch the data from the database but you don't free the result set.

You should run $statement->closeCursor(); after you fetch your data.
You can check the documentation here: http://php.net/manual/en/pdostatement.closecursor.php

After you don't need your variables, you should use unset just to free the memory, deleting the variables $statement and $dbh.
This way, I believe, you can skip the line $dbh = null; which is the example given in the php documentation, on the link: http://php.net/manual/en/pdo.connections.php (go to example #3).

Another thing I noticed is the absence of the php tags.

Almost at the end of the code, you have this echo:

echo " ";

The language attribute is deprecated and can be safely dropped. (Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-language )
This was useful in the times when VBScript was used for Internet Explorer, to diferentiate both languages.
Nowadays, you don't need this.
Another thing is that the value of the attribute isn't between quotes.
If you are paranoid about this, you can use the type attribute.
You can set the value text/javascript, being the final code like this:

echo '';

Documentation about the type attribute:  https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-type

The final code (security apart, reflecting the edit):

Applying all the changes, the final code will look like this:

<?php

    include('.dbinc.cred.inc.php');

    try {

        $dbh = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE . ';charset=latin1', USER_ONE, PASS_ONE);

        if(version_compare(PHP_VERSION, '5.3.6', '<'))
        {
            $dbh->exec('set names latin1');
        }

        $statement = $dbh->prepare('SELECT user_db, user_db_pass, user_db_user, user_name FROM databases WHERE user_name = :name');
        $statement->execute(array('name' => $_SESSION['user_name']));

        list($user_db, $user_db_user, $user_db_pass) = $statement->fetch(PDO::FETCH_NUM);

        $statement->closeCursor();

        unset($statement, $dbh);

    }
    catch (PDOException $e){
        die('Error!: ' . $e->getMessage() . '
');
    }

    $sql = new mysqli(HOST_ONE,$user_db_user, $user_db_pass,$user_db);
    $sql -> set_charset('utf8');
    if ($sql->connect_errno)
    {
        echo '';
    }

?>

As a micro-optimization, I swapped the quotes.
In terms of real-world usage, using "" would make a negligible difference.
Use the quotes that you prefer, I simply prefer to save some CPU cycles.

Thanks to @EliasVanOotegem for spotting the safety issue regarding the lack of a specification on the used collation to connect to the database.
This is a serious issue because it changes the way that the parameters are escaped and avoids the use of special characters to 'nullify' the escapes, allowing other commands to run.
You can see how this attack is performed in here: http://hakipedia.com/index.php/SQL_Injection#Filter_Bypassing


Pythonic sieve of Erasthotones that saves results to file

First off, the general naming style in Python is snake_case for functions and variables, and PascalCase for classes. On the note of style, you should also have two blank lines between top-level functions/classes/code blocks.

Secondly, are you sure that you want to be using len( ... ), rather than len ( ... ) - 1, as you did here: if index < len(primes):? The len function "counts" the objects in the list starting at 1, not 0, which means if you're using it to get indexes, it'll be off by one.

Other than that, there's not much else that really needs to be improved here! Good job!


Link two databases through the java application

Your solution is fine if you only have a couple of tables to copy.
If you have a whole database you could export the entire database to a SQL dump and them run that whole script in the new database manually.

If you need to do transformation to the data, then you can look into Oracle ETL tools.


Seems a bit needlessly complicated and not exactly async at all. You're just forcing an async call to be synchronous with .Wait(). Proper way is to use async "all the way down":

[HttpPost]
[Route("api/v1/upload")]
public async Task<HttpResponseMessage> Post([FromUri]string filename)
{
    try
    {
        using (Stream requestStream = await this.Request.Content.ReadAsStreamAsync())
        using (Stream fileStream = File.Create("./" + filename))
        {
            await requestStream.CopyToAsync(fileStream);
        }

        return new HttpResponseMessage { StatusCode = HttpStatusCode.Created };
    }
    catch (IOException)
    {
        throw new HttpResponseException(HttpStatusCode.InternalServerError);
    }
}


Check if a given integer is power of two

Code organization

There is nothing in the description and the posted code to justify storing the result of the "is power of 2" calculation in a class.
It would be better to simply return it.
The code is also simple enough that you could collapse the if-else chain to a single line:

public static boolean isPowerOfTwo(int num) {
    return num > 0 && (num & (num - 1)) == 0;
}

Testing

I suggest to look into proper unit testing methods,
for example JUnit4 which comes bundled in most IDEs.
The tests you wrote in main would look like this using JUnit4:

private boolean isPowerOfTwo(int num) {
    return Solution.isPowerOfTwo(num);
}

@Test
public void minus1_should_not_be_power_of_2() {
    assertFalse(isPowerOfTwo(-1));
}

@Test
public void zero_should_not_be_power_of_2() {
    assertFalse(isPowerOfTwo(0));
}

// ... and so on


The only style-based comment I have is that we usually don't use upper case names/letters for parameters or local variables.


Optimizing Miller-Rabin Primality Test in Python

One obvious change to make is that mr_check_one(n) does a much more expensive loop than necessary. Here is a much simpler and faster version.

def mr_check_one(n):
    m = n - 1

    n = n - 1
    k =  1
    while n % 2 == 0:
        k += 1
        n /= 2

    return(m / 2**k)

Also, your second function seems really broken. You allegedly loop over a, but in your first time through you redefine a, reset i and return before going through the loop more than once.


First of all, you should use std::underlying_type_t<Cont::value_type> instead of int and please don't use UPPER for template parameters (UPPER is mostly for preprocessor, sometimes used for constants and/or static variables), rather use PascalCasing, e.g. Container.

Your implementation looks good to me otherwise, but you know it can only be used with containers with member push_back. If you want to create it from initializer_list, then it would be something different (e.g. EnumRangeInitList). You may find some inspiration in std::integer_sequence.


Natural merge: mergesort that uses already sorted subarrays

Tests and bugs

Your code looks mostly good. Before trying to go and change the code to see what can be improved. I usually try to write a few simple tests. This is even easier when you have a reference implementation that can be compared to your function. In your case, I wrote:

TESTS = [
    [],
    [0],
    [0, 0, 0],
    [0, 1, 2],
    [0, 1, 2, 3, 4, 5],
    [5, 4, 3, 2, 1, 0],
    [5, 2, 3, 1, 0, 4],
    [5, 2, 5, 3, 1, 3, 0, 4, 5],
]

for t in TESTS:
    print(t)
    ref_lst, tst_lst = list(t), list(t)
    ref_lst.sort()
    natural_merge(tst_lst)
    print(ref_lst, tst_lst)
    assert ref_lst == tst_lst

which leads to a first comment: the empty list is not handled properly and the function never returns.

Improving merge

The case elif len(aux_lo) or len(aux_hi) seems complicated as we check if aux_lo just after. Things would be clearer if we were to split in two different cases:

    if len(aux_lo) and len(aux_hi):
        a[i] = aux_lo.popleft() if aux_lo[0] < aux_hi[0] else aux_hi.popleft()
    elif len(aux_lo):
        a[i] = aux_lo.popleft()
    elif len(aux_hi):
        a[i] = aux_hi.popleft()

Also, we could reuse the fact that in a boolean context, list are considered to be true if and only if they are not empty to write:

for i in range(lo, hi):
    if aux_lo and aux_hi:
        a[i] = aux_lo.popleft() if aux_lo[0] < aux_hi[0] else aux_hi.popleft()
    elif aux_lo:
        a[i] = aux_lo.popleft()
    elif aux_hi:
        a[i] = aux_hi.popleft()

Improving find_next_stop

You don't need so many parenthesis.

You could store len(a) - 1 in a variable in order not to re-compute it every time.

The name _stop is pretty ugly. I do not have any great suggestion for an alternative but end seems okay-ish.

More tests... and more bugs

I wanted to add a few tests to verify an assumption... and I stumbled upon another issue.

Here is the corresponding test suite:

TESTS = [
    [],
    [0],
    [0, 0, 0],
    [0, 1, 2],
    [0, 1, 2, 3, 4, 5],
    [5, 4, 3, 2, 1, 0],
    [0, 1, 2, 2, 1, 0],
    [0, 1, 2, 3, 2, 1, 0],
    [5, 2, 3, 1, 0, 4],
    [5, 2, 5, 3, 1, 3, 0, 4, 5],
    [5, 2, 5, 3, 1, 3, 0, 4, 5, 3, 1, 0, 1, 5, 2, 5, 3, 1, 3, 0, 4, 5],
]

Taking into account my comments and the fix you tried to add in the question, we now have:

from collections import deque

def merge(a, lo, mi, hi):
    aux_lo = deque(a[lo:mi])
    aux_hi = deque(a[mi:hi])

    for i in range(lo, hi):
        if aux_lo and aux_hi:
            a[i] = aux_lo.popleft() if aux_lo[0] < aux_hi[0] else aux_hi.popleft()
        elif aux_lo:
            a[i] = aux_lo.popleft()
        elif aux_hi:
            a[i] = aux_hi.popleft()

def find_next_stop(a, start):
    upper = len(a) - 1
    if start >= upper:
        return start

    stop = start + 1
    if a[start] <= a[stop]:
        while stop < upper and a[stop] <= a[stop+1]:
            stop += 1
    else:
        while stop < upper and a[stop] >= a[stop+1]:
            stop += 1

        end = stop
        while start < end:
            a[end], a[start] = a[start], a[end]
            start += 1
            end -= 1
    return stop

def natural_merge(a):
    upper = len(a) - 1
    if upper <= 0:
        return
    lo = hi = 0
    while True:
        lo = hi
        mi = find_next_stop(a, lo)
        if lo == 0 and mi == upper:
            return
        hi = find_next_stop(a, mi)
        if mi == hi == upper:
            lo = hi = 0
        else:
            merge(a, lo, mi, hi)

TESTS = [
    [],
    [0],
    [0, 0, 0],
    [0, 1, 2],
    [0, 1, 2, 3, 4, 5],
    [5, 4, 3, 2, 1, 0],
    [0, 1, 2, 2, 1, 0],
    [0, 1, 2, 3, 2, 1, 0],
    [5, 2, 3, 1, 0, 4],
    [5, 2, 5, 3, 1, 3, 0, 4, 5],
    [5, 2, 5, 3, 1, 3, 0, 4, 5, 3, 1, 0, 1, 5, 2, 5, 3, 1, 3, 0, 4, 5],
]

for t in TESTS:
    print(t)
    ref_lst, tst_lst = list(t), list(t)
    ref_lst.sort()
    natural_merge(tst_lst)
    print(ref_lst, tst_lst)
    assert ref_lst == tst_lst

More improvements in find_next_stop

We have a while loop but we can compute the number of iterations we'll need: it corresponds to have the distance between start and stop. We could use a for _ in range loop to perform this. It has pros and cons but one of the key aspect is that we do not need to change start and stop, thus we don't need to copy the value in a variable.

    for k in range((1 + stop - start) // 2):
        i, j = start + k, stop - k
        a[i], a[j] = a[j], a[i]

More improvements in natural_merge

A few steps can be used to re-organise the function:

see that we can move the assignment lo = hi from the beginning of the loop to the end of the loop with no impact
realise that it is already done in the first branch of the test already so move it to the else block exclusively
see that the initialisation of hi is not required anymore
notice that the condition mi == upper is checked in 2 places (with the same value of mi and upper and that if lo != 0, we see that mi == upper directly leads to find_next(a, mi) returning upper and thus ending with mi == hi == upper and thus to the assignment lo = hi = 0.

At this stage, we have:

def natural_merge(a):
    upper = len(a) - 1
    if upper <= 0:
        return
    lo = 0
    while True:
        mi = find_next_stop(a, lo)
        if mi == upper:
            if lo == 0:
                return
            lo = hi = 0
        else:
            hi = find_next_stop(a, mi)
            merge(a, lo, mi, hi)
            lo = hi

We can go further:

the assignment hi = 0 has no effect
we can reorganise conditions

We'd get

def natural_merge(a):
    upper = len(a) - 1
    if upper <= 0:
        return
    lo = 0
    while True:
        mi = find_next_stop(a, lo)
        if mi != upper:
            hi = find_next_stop(a, mi)
            merge(a, lo, mi, hi)
            lo = hi
        elif lo == 0:
            return
        else:
            lo = 0

Interestingly, removing lo = hi leads a much more efficient code on my benchmark: the function returns much more quickly (because we always have lo == 0, we get out of the loop as soon as mi == upper) and the list is still fully sorted.

def natural_merge(a):
    upper = len(a) - 1
    if upper <= 0:
        return
    while True:
        mi = find_next_stop(a, 0)
        if mi == upper:
            return
        hi = find_next_stop(a, mi)
        merge(a, 0, mi, hi)

This looked surprising at first but thinking about it, it looks like this may be the way this algorithm is supposed to be.


The D says "depend on abstractions, not concrete types" - that doesn't mean to box your value types into object!

In fact, this:

private int _pin;

Contradicts this:

if (pin.ToString().Length != 4)
{
    throw new ArgumentException("Pin must be exactly 4 digits long integer", "pin");
}

If your pin is meant to work like a string, then it should be stored as a string. If my pin is 0072, I have a 4-digit pin, but you're storing it as 72 and throwing an ArgumentException at me.

Exposing object in your public API is horrible practice - nobody knows what you're expecting to receive! Worse, there's no XML documentation on your public members, so the only way to find out, is to dig into your code.

Come to think about it, with respect to the I of SOLID, I think your interface should look like this:

public interface IPinAuthorization
{
    bool Validate(SecureString pin);
}

And a PIN shouldn't be that easy to modify. Consider making the type immutable, and asking for the current PIN before accepting a new one:

public interface IModifiablePin
{
    IPinAuthorization Modify(SecureString current, SecureString @new);
}

You could have a more secure PinAuthorization implementation like this:

public class PinAuthorization : IPinAuthorization, IModifiablePin, IDisposable
{
    private readonly SecureString _pin;

    public PinAuthorization(SecureString pin)
    {
        ValidateInternal(pin); // see comments below
        _pin = pin;
    }

    private void ValidateInternal(SecureString pin)
    {
        if (pin.Length != 4)
        {
            throw new ArgumentException("PIN must be 4 digits.", pin);
        }

        // further validation logic would break the security of the string.
        // this is an indication that it's not this type's responsibility
        // to know how to validate itself.
    }

    public bool Validate(SecureString pin)
    {
        return pin == _pin;
    }

    public IPinAuthorization Change(SecureString current, SecureString @new)
    {
        if (_pin != current)
        {
            throw new ArgumentException("Invalid PIN.", current);
        }

        return new PinAuthorization(@new);
    }

    public void Dispose()
    {
        _pin.Dispose();
    }
}

Now, if you want to implement some FingerprintAuthorization, you can make it implement IPinAuthorization and validate against a SecureString-encoded finger print (however you want to do that), and the type will not be implementing IModifiablePin, since you don't change your finger prints. Or do you? Well, at least you have the flexibility of doing either. At a glance though, it seems the class has so little responsibility, that it possibly wouldn't even need to be reimplemented or adapted in any way.


Finding and pasting images into a specific cell

I'm not sure I can make it faster but hopefully can make it a bit elegant.
Let's start

First of all, use Option Explicit for all your VBA work. This will make your life easier once you use VBA more.

Error handling
Great you use it, unfortunately not correctly. Your label will never be hit

ErrNoPhoto:

You have to tell your code you want to handle errors

On Error Goto ErrNoPhoto

A cosmetic change I changed and mainly moved the code for selecting folder to a separate method, just to make it clear

Private Function GetFolder() As String

    Dim selectedFolder  As String
    With Application.FileDialog(msoFileDialogFolderPicker)
        .InitialFileName = Application.DefaultFilePath & "\"
        .Title = "Select the folder containing the Image/PDF files."
        .Show

        If .SelectedItems.Count > 0 Then
            selectedFolder = .SelectedItems(1)
            If Right$(selectedFolder, 1) <> Application.PathSeparator Then _
                selectedFolder = selectedFolder & Application.PathSeparator
        End If

    End With
    GetFolder = selectedFolder

End Function

One of the biggest change I made in your code is changing the way how you go through cells. This can be one of the most slowly operation in VBA.

I always try to convert it to an array which is "million" times faster than going directly through cells. You will see significant difference if you go through huge numbers of cells. I'm not sure you will see the difference in your code but this is one of the best practice.

Set wks = ActiveSheet
' this is not bulletproof but for now should work fine
lastRow = wks.Cells(1, "B").End(xlDown).Row
data = wks.Range(wks.Cells(1, "B"), wks.Cells(lastRow, "B")).Value2

this will load data from cells from column B, from cell B1 to Bn where n is the last row found by this

lastRow = wks.Cells(1, "B").End(xlDown).Row

this will give you an opportunity to use For Next loop instead While.
I didn't find anything important I could change in the insert picture logic except one thing that I removed all the Selection command from your code which should again make it a bit faster.

At the end this is what was in my VBE
Inserting 800 images took about 7 seconds

Option Explicit

'********************************************************************************
'Picture
'
' Purpose:  Looks for Image names posted in column B in the file folder and
'           then resizes the images and pastes them in Column A
'
' Inputs:   -none-
'
' Outputs:  -none-
'
' Created:  06/03/2015  proxy
'
' Modified: .
'
'********************************************************************************
Sub Picture()

    Const EXIT_TEXT         As String = "Please Check Data Sheet"
    Const NO_PICTURE_FOUND  As String = "No picture found"

    Dim picName             As String
    Dim picFullName         As String
    Dim rowIndex            As Long
    Dim lastRow             As Long
    Dim selectedFolder      As String
    Dim data()              As Variant
    Dim wks                 As Worksheet
    Dim cell                As Range
    Dim pic                 As Picture

    On Error GoTo ErrorHandler

    selectedFolder = GetFolder
    If Len(selectedFolder) = 0 Then GoTo ExitRoutine

    Application.ScreenUpdating = False

    Set wks = ActiveSheet
    ' this is not bulletproof but for now should work fine
    lastRow = wks.Cells(1, "B").End(xlDown).Row
    data = wks.Range(wks.Cells(1, "B"), wks.Cells(lastRow, "B")).Value2

    For rowIndex = 1 To UBound(data, 1)
        If StrComp(data(rowIndex, 1), EXIT_TEXT, vbTextCompare) = 0 Then GoTo ExitRoutine

        picName = data(rowIndex, 1)
        picFullName = selectedFolder & picName & ".jpg"

        If Len(Dir(picFullName)) > 0 Then
            Set cell = wks.Cells(rowIndex, "A")
            Set pic = wks.Pictures.Insert(picFullName)
            With pic
                .ShapeRange.LockAspectRatio = msoFalse
                .Height = cell.Height
                .Width = cell.Width
                .Top = cell.Top
                .Left = cell.Left
                .Placement = xlMoveAndSize
            End With
        Else
            wks.Cells(rowIndex, "A").Value = NO_PICTURE_FOUND
        End If

    Next rowIndex

    Range("A10").Select

ExitRoutine:
    Set wks = Nothing
    Set pic = Nothing
    Application.ScreenUpdating = True
    Exit Sub

ErrorHandler:
    Range("B20").Select
    MsgBox Prompt:="Unable to find photo", _
           Title:="An error occured", _
           Buttons:=vbExclamation
    Resume ExitRoutine

End Sub

Private Function GetFolder() As String

    Dim selectedFolder  As String
    With Application.FileDialog(msoFileDialogFolderPicker)
        .InitialFileName = Application.DefaultFilePath & "\"
        .Title = "Select the folder containing the Image/PDF files."
        .Show

        If .SelectedItems.Count > 0 Then
            selectedFolder = .SelectedItems(1)
            If Right$(selectedFolder, 1) <> Application.PathSeparator Then _
                selectedFolder = selectedFolder & Application.PathSeparator
        End If

    End With
    GetFolder = selectedFolder

End Function


I have no idea what you code is doing, it doesn't look like any normalization I've seen. I'd offer a more specific suggestion on restructuring if I understood what you are doing.

You:

Put a in a counter
Put that counter's values into a set
sort the keys of the counter

I'd look for another approach that doesn't involve so much moving around.

if not previousCount == count:

better as

if previousCount != count:

EDIT

Counter.most_common returns what you are fetching using sorted(c, reverse=True)
itertools.groupby allows you group together common elements nicely (such as the same count)
enumerate can be used to count over the elements in a list rather then keeping track of the counter

My code:

c = Counter(a)
length = len(set(c.values()))
counter_groups = itertools.groupby(c.most_common(), key = lambda x: x[1]))
normalisedValueCount = {}
for i, (group_key, items) in enumerate(counter_groups)
    for key, count in items:
        normalisedValueCount[key] = (i+1)/length


Some small comments

    let tuple = handleChar c lines builder
    let newLines = fst tuple
    let newbuilder = snd tuple
    getLines newLines newbuilder

can become

    let newlines,newbuilder = handleChar c lines builder
    getLines newLines newbuilder

although, if you aren't using getLines anywhere else, there is a good argument for making it

handleChar c lines builder |> getLines

by makeing getLines take its argument in tupled form.

The magic number 10 appears a few times, so I would add a literal like

[<Literal>]
let newline = 10

and then you can pattern match against it.

Also,

Lines @ [s]

is bad as @ is very slow.  You are better to use

s::Lines

and then reverse the list at the end.

Your format for reading the characters recursively should be fine as it will get optimised as a tail-call.

Of course, your entire program could be replaced by:

let rec procinput lines=
    match Console.ReadLine() with
    | null -> List.rev lines
    | "" -> procinput lines
    | s -> procinput (s::lines)


List of binary numbers: How many positions have a one and zero

I only see a few micro optimisations:

Iterate the list instead of a range, so that you don't have to do another lookup with list[i+1]
Use more assignment operators, such as &=, |= and >>=
It is not needed to use lst[1] in andnumber = lst[0] & lst[1]. It can be just andnumber = lst[0]

So:
def count_mixed_bits_v2(lst):
    andnumber = ornumber = lst[0]
    for value in lst:
        andnumber &= value
        ornumber |= value
    xornumber = andnumber ^ ornumber
    result = 0
    while xornumber > 0:
       result += xornumber & 1
       xornumber >>= 1
    return result

This visits the first list value again (in the first iteration), even though it is not necessary. But that probably does not really hurt performance, and keeps the code simple.


Using Concurrent Dictionary and Lazy to cache expensive query results and only run query once in a threadsafe manner

What you have will work, but there are a few incremental improvements.  Rather than using TryAdd you can use GetOrAdd which returns the value for that key.  This will save you a lookup (and also remove a race condition where the key is removed between calls by another thread).

Also note that, currently, you're caching any errors that you get, and continuing to serve them out.  If you're okay with that, or aren't worried about it, then okay.

You should do some tests to be sure, but it may be faster to use the overload of GetOrAdd that accepts a function, rather than a value.  This will allow you to construct the Lazy only when a new one is needed, rather than on every call.  Constructing a Lazy isn't that expensive (it doesn't need to actually compute the value after all) but this is likely still a win in most situations.


Implementing a generic and covariant Set in Scala

The this: Repr[A] is not absolutely necessary, but it you omit it, you're encoding a sort of weird type constraint:
that the class is not necessarily a Repr, but its insert[B] must produce a Repr[B] (who's insert[C] produces a Repr[C], and so on).
I can't think of a realistic situation where having or not having the self-type would prevent or lead to a bug, so IMO it doesn't actually matter much.
Your recursive higher-kinded type signature is absolutely fine, and in fact very closely mirrors that of SetLike from the standard collection library.

There is at least one alternative: making it a typeclass. Here's what it might look like:

trait CovariantSet[S[+_]] {
  def isEmpty[A](xs: S[A]): Boolean
  def contains[A, B >: A](b: B)(xs: S[A])(implicit order: Ordering[B]): Boolean
  def insert[A, B >: A](b: B)(xs: S[A])(implicit order: Ordering[B]): S[B]
}

sealed trait CustomSet[+A]
case object Leaf extends CustomSet[Nothing]
case class Node[+A](value: A, left: CustomSet[A], right: CustomSet[A]) extends CustomSet[A]

object CustomSet {
  implicit val customSetIsCovariantSet: CovariantSet[CustomSet] = new CovariantSet[CustomSet] {
    override def isEmpty[A](xs: CustomSet[A]): Boolean = xs == Leaf

    override def insert[A, B >: A](b: B)
                                  (xs: CustomSet[A])
                                  (implicit order: Ordering[B]): CustomSet[B] = xs match {
      case Leaf => Node(b, Leaf, Leaf)
      case Node(v, l, r) => order.compare(b, v) match {
        case 0 => xs
        case i if i < 0 => Node(v, insert(b)(l), r)
        case _ => Node(v, l, insert(b)(r))
      }
    }

    @tailrec
    override def contains[A, B >: A](b: B)
                                    (xs: CustomSet[A])
                                    (implicit order: Ordering[B]): Boolean = xs match {
      case Leaf => false
      case Node(v, l, r) => order.compare(b, v) match {
        case 0 => true
        case i if i < 0 => contains(b)(l)
        case _ => contains(b)(r)
      }
    }
  }
}

The idea is that the data structure (the CustomSet) can be defined separately from the evidence that it has an instance for the CovariantSet typeclass (customSetIsCovariantSet). Whether or not you think it's simpler is a matter of opinion, but it does at least avoid the recursive type.

You can then enrich CovariantSets for convenience:

object CovariantSet {
  implicit class Ops[S[+_], A](xs: S[A])(implicit ev: CovariantSet[S]) {
    def isEmpty: Boolean = ev.isEmpty(xs)
    def contains[B >: A](b: B)(implicit order: Ordering[B]): Boolean = ev.contains(b)(xs)
    def insert[B >: A](b: B)(implicit order: Ordering[B]): S[B] = ev.insert(b)(xs)
  }
}

I would also probably make the Node constructor private, so users can't construct a malformed (out of order) tree.

Your larger and more fundamental design problem is that the data structure doesn't make sense unless the Ordering is fixed (or at least its compare operation doesn't change its mind about values already in the Set).

Here are a couple problematic examples of where this can go wrong:

Leaf.insert(1).insert(2).contains(2) // true. great, working as expected

Leaf.insert(1).insert(2).contains(2)(Ordering.Int.reverse) // false. your data structure is broken

Leaf.insert(1).insert(2)(Ordering.Int.reverse).contains(2) // false. your data structure is broken

There are a couple ways around this I can think of, the first more practical than the second:

Implement a covariant HashSet instead. Every object in Scala has a hashCode: Int and an equals(other: Any): Boolean method, which is all you need.
Store an Ordering[A] in the Set. Whenever you implicitly pass in a new Ordering[B], also implicitly pass in an object that proves that the new Ordering[B] agrees with every decision the old Ordering[A] has already made.


Unused: we don't use j, and we don't need to include <stdbool.h>, <stdlib.h> or <time.h>.
We have two loops - one that reads input into message[] and one that converts and outputs the content of message[].  We can avoid the storage by combining the two loops into one:
while ((ch = getchar()) != '\n') {
    ch = toupper(ch);

    switch (ch) {
        /* ... */
    }

There's a couple of fixes needed above.  Firstly, we need to check that ch is not EOF, or we'll loop indefinitely if the input stream is closed before the first newline.  ch needs to be an int value here, as the distinction between a character and end-of-file is lost when we narrow to char.
Secondly, ch holds values of a (possibly signed) char, but toupper() (like all the <ctype.h> functions) works on an int representation of unsigned char value.  Fixing those gives us:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
    ch = toupper((unsigned char)ch);

Instead of the switch, we might consider a table-driven approach.  That would work something like this:
char conversions[UCHAR_MAX];
/* identity mapping for most chars */
for (unsigned i = 0;  i < sizeof conversions;  ++i) {
    conversions[i] = (char)i;
}
/* exceptions */
conversions['S'] = '5';
conversions['O'] = '0';
conversions['I'] = '1';
conversions['E'] = '3';
conversions['B'] = '8';
conversions['A'] = '4';

int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
    putchar(conversions[toupper(ch)]);
}

Finally, puts() is simpler than printf() for simple strings ending in newline, and we don't need to return 0 from main().

Modified code
#include <ctype.h>
#include <limits.h>
#include <stdio.h>

int main(void)
{
    char conversions[UCHAR_MAX];
    /* identity mapping for most chars */
    for (unsigned i = 0;  i < sizeof conversions;  ++i) {
        conversions[i] = (char)i;
    }
    /* exceptions */
    conversions['S'] = '5';
    conversions['O'] = '0';
    conversions['I'] = '1';
    conversions['E'] = '3';
    conversions['B'] = '8';
    conversions['A'] = '4';

    printf("Enter a message: ");

    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF) {
        putchar(conversions[toupper(ch)]);
    }

    // Finish the sentence
    puts("!!!!!!!!!!!!!!");
}


go

First just a blanket statement about names. Since this is
a golfing challenge you should pick short names for
varibles, helper functions, etc. Of course, that makes
things less readable, but there are some conventions that
Haskellers follow:

go         - names a local helper function
xs, ys, zs - a list
(x:xs)     - xs is the tail of a list whose head is x
x'         - a value related to x

Some people complain about the heavy use of single letter
variable names in Haskell, but when used judiciously I think
it actually aids readability.

skips

You can perform filter, fst and unzip all in a single
list comprehension like this:

skips' n root@(_:xs) = [ x | (x,k) <- zip root [0..], mod k n == 0] ++ ...

Also, note that you define devidedByIndex, but you only call it once.
In a situation like that you can always inline the definition where it is used,
and that's what we've done here by putting the mod k n ... expression
directly into the list comprehension.

localMaximum

You have three cases which return the same value, so just put the
last case first and use a default pattern for the others:

localMaxima (x:y:z:xz) = ...
localMaximum _ = []

Next, because we're golfing, you can avoid the otherwise clause and
duplicating the recursion call like this:

localMaxima (x:y:z:zs) = (if x < y && y > z then [y] else []) ++ localMaximum ...

histogram

There are two sub-problems:

Computing the counts
Building the picture.

Let's start with #2, and say we have the counts in a list ns, i.e. the counts
for the example is [0,1,2,3,4,5,4,3,2].

A quick way to create the row for the k-th level is:

row k ns = [ if n >= k then '*' else ' ' | n <- ns ]

and then we just need to stack those lines together:

(row 9 ns) ++ "\n" ++ (row 8 ns) ++ "\n" ++ ... (row 1 ns) ++ "\n"

Perhaps this gives you some ideas on how to improve the code.

In your computeElements, again note that your helper count is only used once,
so for golfing purposes you can inline it:

countElements n = map (\x -> length (elemIndices x n)) [0..9]

Also, compare:

elementIndices x n          - 16 non-space chars
[ y | y <- n, y == x ]      - 13 non-space chars

Since you only interested in the length both will work.

Finally, whenever you have map (\x -> ...) [...] it's the same as
a list comprehension:

map (\x -> .A.) [.B.]  = [ .A. | x <- [.B.]]

and the list comprehension is shorter by a few characters.

import ...

The exercise encourages you to look for standard library functions to help
you reduce your code size.

Here are some library functions which might be applicable to these problems:

tails :: [a] -> [[a]]
sort :: Ord a => [a] -> [a]
group :: Eq a => [a] -> [[a]]
unlines :: [String] -> String


Copy a FileInputStream to a file, either as text or as a string of bytes

Please note I am not an expert in Java, I do know something about object oriented programming.

Java is an object oriented programming language. To write good object oriented programs it's best to keep 5 programming principles in mind. Together these 5 principles are called SOLID programming. The 5 programming principles are

The Single Responsibility Principle
The Open-closed principle
The Liskov substitution principle
The Interface segregation principle
The Dependency inversion principle

The single responsibility principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

This program violates the single responsibility principle in 2 ways, first the function main() is included in the class and second the write() function is too complex (does too much) and should be simplified.

The function write() might be better named copy(). It should do only one thing, which is copy the input file to the output file. There could be 2 copy() functions, one for text and one for strings. The decision on which way to write to the output file should be outside the copy functions.

Opening and closing the files should be outside the write function. The program should only open the input file once and possibly reset it to the beginning the second time.

The ByteStreamTest constructor could open the input file.
There could be a Boolean member of the ByteStreamTest class that is either public and gets modified by main() or private with accessor functions.


Two variants of a picture database initialization routine

For me, there's two main things that drive extracting into a function.

Is there scope for reusing the functionality?
Would a function make the code easier to follow?

Looking at your code, it doesn't seem like the functions that you've implemented have much scope for reuse.  Whilst they could make your code easier to follow, I don't think they do, primarily because the names don't really describe what they do.  I find getting names right to be hard work, but well named methods make code a lot easier to follow.

Your method names that you've introduced are:

db_create_helper
    finish_initialization
    write_to_file

They don't tell me anything about what it is you're expecting the methods to do.

An alternative might be something like this:

initialize_db_file
    build_db_header
    write_db_header
    write_db_metadata

These names aren't perfect either, I don't really know what 'metadata' represents and if it should really be part of the header, which is why I've split your write_to_file in to two, however I've tried to name the methods so that they convey what it is I think the methods are doing.  This makes the top level method more meaningful, describing the process of initializing the db file.

As far as method length goes, methods that are too long are a red flag, because they usually mean that too much is being done in one place and the method is likely to be hard to follow.  However, I'm Ok with one line methods, as long as the name for the method actually conveys the intent better than the line it hides.


Length of the integer part of a double in C without math.h

You say it "works fine" in all your tests, but you didn't show us the tests.

Unfortunately, it failed the very first test I wrote:

#include <gtest/gtest.h>

TEST(length, zero)
{
    EXPECT_EQ(1, length(0));
}

Of the next batch, one_minus fails for the same reason:

TEST(length, one)
{
    EXPECT_EQ(1, length(1.0));
}

TEST(length, one_plus)
{
    EXPECT_EQ(1, length(1.0 + 1e-12));
}

TEST(length, one_minus)
{
    EXPECT_EQ(1, length(1.0 - 1e-12));
}

TEST(length, two)
{
    EXPECT_EQ(1, length(2.0));
}

TEST(length, two_plus)
{
    EXPECT_EQ(1, length(2.0 + 1e-12));
}

TEST(length, two_minus)
{
    EXPECT_EQ(1, length(2.0 - 1e-12));
}

TEST(length, ten)
{
    EXPECT_EQ(2, length(10.0));
}

TEST(length, ten_plus)
{
    EXPECT_EQ(2, length(10.0 + 1e-12));
}

TEST(length, ten_minus)
{
    EXPECT_EQ(1, length(10.0 - 1e-12));
}

We can fix this by adding a simple check before the first division:

if (number < 0) number *= -1;
if (number < 1) return 1;

Let's add some more tests:

TEST(length, zillions)
{
    EXPECT_EQ(36, length(1.0e35));
}

TEST(length, negative_zillions)
{
    EXPECT_EQ(36, length(-1.0e35));
}

Now we just need some tests for invalid inputs (infinities, NaNs, etc) and we're golden.

Let's look at the implementation now:

while (number > 1) {
    result++;
    number /= 10;
}
return result + (number == 1);

We can avoid adding number == 1 if we include that case within the while loop:

while (number >= 1) {
    result++;
    number /= 10;
}
return result;

And our tests prove we haven't broken it.

We might now want to improve speed for large numbers: consider our zillions test that loops 36 times.  We could shorten that, at a very small cost to lower numbers by first looping (say) 6 digits at a time:

int result = 0;
while (number >= 1e6) {
    result += 6;
    number /= 1e6;
}
while (number >= 1) {
    result++;
    number /= 10;
}
return result;

When I try this, it initially shows promise, but then fails the zillions tests with an off-by one error.  Is there a subtle difference in rounding between repeatedly dividing by ten and repeatedly dividing by a million when you're dealing with inexact numbers?  Actually, the problem is with our constant - 1.0e35 is most closely represented as 99999999999999999997871448567840768, so we suffered a rounding error in our test - it happened that sequential division by ten introduces a rounding error that compensates for this, and we wrongly pass!

Which brings me neatly to the alternative implementation.  The most convenient tool for measuring digits in the integer part isn't in <math.h> at all - it's in <stdio.h>!  We can ask printf to measure the length for us:

#include <stdio.h>

int length(double number)
{
    /* "unround" the number, as printf rounds to nearest */
    number += .5 - (number > 0);
    /* format the sign, then subtract one, so we don't count
       minus as a digit */
    return snprintf(NULL, 0, "%+1.f", number) - 1;
}

Note that I've left the handling of NaNs and infinities in this version as an exercise...


Well, what you do not actually test is: Are the login parameters passed to the LoginService correctly? In your example, you are simply assuming that the next login will fail or succeed, but you do that completely ignoring the actual parameters.

Especially for the successfull test I would use the actual expected parameters instead of anyString. For the not successfull test you could do the same, return a result with false if the login data is the expected value (otherwise it will be null).

This way you don't just test the way the LoginRestService handles the responses from the LoginService, but also that the LoginRestService gives the correct parameters to the LoginService in the first place, eliminating one possible cause of errors.


Two strings to one containing distinct letters

First of all, you can work directly with chars instead of creating one char Strings.

Second of all, looking at the challenge description

  Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters, - each taken only once - coming from s1 or s2.

you disregard an important part - there is a small number of possible unique characters in the input Strings. You can use that information to your advantage and eliminate the need to explicitly sort the output String.

For example, you can use an int array of length 26 to indicate for each letter of the abc whether it is present in one of the input Strings.

You can populate the array by iterating once over each of the input Strings.
Then you can iterate once over that array and add to the output String the characters corresponding with indices of the array for which the value > 0.

This would reduce your time complexity from O(nlogn) to O(n).

public static String longest(String s1, String s2) {
    int[] chars = new int[26];
    for (char c : s1.toCharArray()) {
        chars[c-'a']=1;
    }
    for (char c : s2.toCharArray()) {
        chars[c-'a']=1;
    }
    StringBuilder result = new StringBuilder(26);
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] > 0)
            result.append ((char)(i+'a'));
    }
    return result.toString();
}


Return union and complement of three sets

This code has two limitations, as I see it:

in treating in a single go the combination of three sets, it gives rise to a high cyclomatic complexity: a dozen if statements (including the while) in a single function. This circumstance limits the readability and maintainability of the code. It also makes it less extensible to more general cases.
the assumption that B is a subset of A and C is disjoint from either is very particular, and likely to limit the reuse of the code elsewhere.

As a minor point, the assertions stop the program in case a problem is detected but they do not indicate which test fails, or if other tests would have failed, which comes in handy in debug.
The input vectors are assumed to be sorted in increasing order. If that were not the case, one could do that first, and increase the generality of the code further.
Leaving aside for a moment the possible generalization of the code, by splitting the operation into a subtraction of B from A and a subsequent addition of C, the complexity drops drastically. Instead of a single pure function with 55 lines of code (header and declarations excluded) and 12 branching points (if and while), one can write three pure functions, with 2, 11, and 21 lines of code and only 0, 2, and 3 branching points, respectively:
program test_complement_union

    implicit none(type, external)

    call assert( "t1", all([3, 5]       == complement_union([1, 2, 3], [1, 2], [5]      )))
    call assert( "t2", all([2, 3, 4]    == complement_union([1, 2, 3], [1]   , [4]      )))
    call assert( "t3", all([1, 3, 5]    == complement_union([1, 2, 3], [2]   , [5]      )))
    call assert( "t4", all([1, 4, 5, 6] == complement_union([1, 2, 3], [2, 3], [4, 5, 6])))

  contains

    !> Merge C into A and remove values that are in B.
    !> The result can be written with set notation as A ∪ C / B.
    !> Preconditions (not tested!):
    !>      1. B is a subset of A
    !>      2. A and C are disjoint
    !>      3. B and C are disjoint
    !>      4. A, B, and C are sorted.
    pure function complement_union(A, B, C) result(D)
      integer, intent(in) :: A(:), B(:), C(:)
      integer :: A_B( size(A) - size(B) )
      integer :: D  ( size(A) + size(C) -size(B) )
      A_B  = subtract_subset(A,B)
      D    = union_disjoint_sets(A_B,C)
    end function complement_union

    !> Subtract a proper ordered subset from a given ordered set
    pure function subtract_subset( A, B ) result( C )
      integer, intent(in) :: A(:), B(:)
      integer :: C ( size(A) - size(B) ), iA, iB, iC
      iC = 0
      iA = 1
      !.. All elements of B are expected to be found in A
      do iB = 1, size(B)
         !.. Copies the elements of A between consecutive
         !   occurrences of B elements
         do while( A(iA) /= B(iB) )
            iC = iC + 1
            C(iC) = A(iA)
            iA = iA + 1
         enddo
         !.. Skips the B element
         iA = iA + 1
      enddo
      !.. Copies the elements of A past the last element of B
      if( iA <= size(A) ) C(iC+1:) = A(iA:)
    end function subtract_subset

    !> Computes the union of non-empty disjoint ordered sets
    pure function union_disjoint_sets( A, B ) result( C )
      integer, intent(in) :: A(:), B(:)
      integer :: C( size(A) + size(B) )
      integer :: iA, iB, iC, nA, nB
      nA = size(A)
      nB = size(B)
      iA = 1
      iB = 1
      iC = 0
      C  = 0
      !.. Takes an element from either A or B
      !   until one of the sets is empty
      do while( iA <= nA .and. iB <= nB )
         iC = iC + 1
         if( A(iA) <= B(iB) )then
            C(iC) = A(iA)
            iA = iA + 1
         else
            C(iC) = B(iB)
            iB = iB + 1
         endif
      end do
      !.. Copies to C the residual elements in
      !   the remaining non-empty set
      if( iA <= nA )then
         C(iC+1:)=A(iA:)
      else
         C(iC+1:)=B(iB:)
      endif
    end function union_disjoint_sets

    subroutine assert(msg,cond)
      use, intrinsic :: iso_fortran_env, only : OUTPUT_UNIT
      character(len=*), intent(in) :: msg
      logical         , intent(in) :: cond
      write(OUTPUT_UNIT,"(a)",advance="no") msg//" - "
      if( cond )then
         write(OUTPUT_UNIT,"(a)") "passed"
      else
         write(OUTPUT_UNIT,"(a)") "FAILED"
      endif
    end subroutine assert

  end program test_complement_union

If the restrictions on the three sets, A, B, and C are removed, except for their being ordered, in general, the size of ( A U C ) / B will be different from size(A)-size(B)+size(C). Furthermore, ( A / B ) U C /= ( A U C ) / B. Let's consider the latter operation, which is a bit more challenging. If one does not want give up automatic arrays, then I think there is no alternative to having trailing "empty" entries in the result (e.g., zeros). Even in this case, it is best to split the work into functions that provide two disjoint sets to be merged. The subtraction here is more complicated because in general B would not be a subset of A and C may have elements in common with both B and A. Therefore, one must first figure out the A/B, C/B and C/B/A, by means of a difference function, and then merge the result, which is simple, since the sets are disjoint :
$$( A \cup C ) / B = ( A / B ) \cup ( ( C / B ) / A ) $$
where $$( A / B ) \cap ( ( C / B ) / A ) = \varnothing$$
Here's a sketch of the idea
program test_complement_union

    implicit none(type, external)

    call assert( "t1", all([3, 5, 0, 0]       == complement_union([1, 2, 3], [1, 2], [5]      )))
    call assert( "t2", all([2, 3, 4, 0]       == complement_union([1, 2, 3], [1]   , [4]      )))
    call assert( "t3", all([1, 3, 5, 0]       == complement_union([1, 2, 3], [2]   , [5]      )))
    call assert( "t4", all([1, 3, 5, 0, 0, 0] == complement_union([1, 2, 3], [2, 9], [1, 2, 5])))

  contains

    !.. Assumes input vectors are sorted (!)
    !   If that is not the case, the vectors should
    !   be sorted into auxiliary arrays
    !..
    function complement_union(A, B, C) result(D)
      integer, intent(in) :: A(:), B(:), C(:)
      integer :: A_B(size(A))
      integer :: C_B(size(C))
      integer :: C_AB(size(C))
      integer :: D (size(A) + size(C))
      A_B  = difference(A,B)
      C_B  = difference(C,B)
      C_AB = difference(C_B,A_B)
      D    = union_disjoint_sets(A_B,C_AB)
    end function complement_union

    !.. Computes the difference between the two sets,
    !   generating a set with the same size as the first
    !   with trailing zeros for the erased fields.
    function difference( A, B ) result( C )
      integer, intent(in) :: A(:), B(:)
      integer :: C ( size(A) ), iA, iB, iC, nA, nB, nC
      nA=count(A/=0)
      nB=count(B/=0)
      if(nB==0)then
         C=A
         return
      endif
      iC=0
      iB=1
      nC=nA
      outer: do iA = 1, nA
         do while( B(iB) < A(iA) )
            iB = iB + 1
            if( iB > nB) exit outer
         end do
         if( B(iB) == A(iA) )then
            nC=nC-1
            cycle outer
         endif
         iC = iC + 1
         C(iC) = A(iA)
      enddo outer
      if( iB > nB ) C(iC+1:nC) = A(iA:nA)
      if( nC < size(A) ) C(nC+1:) = 0
    end function difference

    !.. Computes the union of disjoint sets
    pure function union_disjoint_sets( A, B ) result( C )
      integer, intent(in) :: A(:), B(:)
      integer :: C( size(A) + size(B) )
      integer :: iA, iB, iC, nA, nB, nC
      nA = count( A /= 0 )
      nB = count( B /= 0 )
      nC = nA + nB
      iA = 1
      iB = 1
      iC = 0
      C  = 0
      do while( iA <= nA .and. iB <= nB )
         iC = iC + 1
         if( A(iA) <= B(iB) )then
            C(iC) = A(iA)
            iA = iA + 1
         else
            C(iC) = B(iB)
            iB = iB + 1
         endif
      end do
      if( iA <= nA )then
         C(iC+1:nC)=A(iA:nA)
      else
         C(iC+1:nC)=B(iB:nB)
      endif
    end function union_disjoint_sets

    subroutine assert(msg,cond)
      use, intrinsic :: iso_fortran_env, only : OUTPUT_UNIT
      character(len=*), intent(in) :: msg
      logical         , intent(in) :: cond
      write(OUTPUT_UNIT,"(a)",advance="no") msg//" - "
      if( cond )then
         write(OUTPUT_UNIT,"(a)") "passed"
      else
         write(OUTPUT_UNIT,"(a)") "FAILED"
      endif
    end subroutine assert

  end program test_complement_union

PS:
For folks not familiar with the simple syntax of modern Fortran, I suggest the following quick modern Fortran tutorial.


Getting the individual digits of a number

I would suggest a third approach that extends the conversion-to-string approach: conversion to List of Character

The benefits of this is that you can utilise Java 8 collection stream feature to perform filtering, aggregation and other functions on the elements.

for instance, your example can be expressed as such (edited following @h.j.k's comment):

    long num = 123456789;
    String s = String.valueOf(num);
    long count = s.chars()
            .mapToObj(i -> (char)i)
            .filter(ch -> ch.equals('1'))
            .count();


Count number of occurences of a digit in the range

In addition to this, you should specify validation for n ( digit ).
Also, it may be better to group validations into separate function.

void check_input(int min_left, int max_right, int digit) {
  if (max_right <= min_left)
    throw std::invalid_argument("right is <= left, expected right > left");
  if (min_left < 0)
    throw std::invalid_argument("left < 0, expected left > 0");
  if (digit <= 0)
    throw std::invalid_argument("digit <= 0");
    //throw std::invalid_argument("number <= 0");
  if (digit > 9)
    throw std::invalid_argument("digit > 9");

  ////number:
  //if (digit > max_right)
  //  throw std::invalid_argument("number > right limit");
}

int count_digit_entries(int min_left, int max_right, int digit) {
//...
}

int main() {
  int left_limit, right_limit, num;
  std::cout << "Enter left limit, right limit and the number(Only positive numbers)\n";
  std::cin >> left_limit >> right_limit >> num;

  check_input(left_limit, right_limit, num);

  int result = count_digit_entries(left_limit, right_limit, num);

  std::cout << "\nTotal: " << result << "\n";
}

You may want to find not only digits but a whole numbers.

//...

#define DEBUG
#ifdef  DEBUG
#define debug(x) x
#else
#define debug(x)
#endif

int count_digit_entries(int min_left, int max_right, int search_number) {
  int count = 0;

  int mod = 10;
  while(search_number / mod > 0) mod = mod * 10; // 279 -> 1000

  for (int current_number = min_left, right = max_right; current_number < right; ++current_number) {
    int copied_current_number = current_number; // 542793

    while (copied_current_number >= search_number) {
        // 542793 - 279 % 1000    >0
        // 54279 - 279 % 1000     =0

      if ( ( (copied_current_number - search_number) % mod ) == 0 ) {
        debug(std::cout << current_number << " ");
        ++count;
      };
      copied_current_number = copied_current_number / 10;
      // 542793 -> 54279

    };
  };

  return count;
};

Output:

Enter left limit, right limit and the number(Only positive numbers)
0 1000 25
25 125 225 250 251 252 253 254 255 256 257 258 259 325 425 525 625 725 825 925
Total: 20


You have implemented a 'huge' data structure to solve the problem. In this case though, the solution is to use a relatively simple case of memoization. If you work backward from the end of the array, you can use what you have already learned for previous values.....

... in essence, you can use the subsequent NGE's to bootstrap your way to calculate the current cell's NGE.

private static int[] computeNGE(int[] tocompute) {
    if (tocompute == null) {
        throw new NullPointerException();
    }
    if (tocompute.length == 0) {
        return new int[0];
    }
    if (tocompute.length == 1) {
        return new int[]{-1};
    }
    int[] indices = new int[tocompute.length];
    int[] nge = new int[tocompute.length];
    nge[tocompute.length - 1] = -1;
    indices[tocompute.length - 1] = -1;
    for (int i = tocompute.length - 2; i >= 0; i--) {
        int j = i + 1;
        while (j != -1 && tocompute[j] <= tocompute[i]) {
            j = indices[j];
        }
        indices[i] = j;
        nge[i] = j == -1 ? -1 : tocompute[j];
    }
    return nge;
}

The above solution will have close to an \$O(n)\$ time complexity, because, the worst case is a 2-times iteration through the data.


Partitioning an array based on a condition in Javascript

Using TypeScript/ECMAScript 6 syntax it can be achieved this way. I am not sure whether it's more or less elegant compared to the original variant, but

It does the job;
Requires only one run;
Can be further chained with map () or other functions.

const [small, large] =                             // Use "deconstruction" style assignment
  [12, 5, 8, 130, 44]
    .reduce((result, element) => {
      result[element <= 10 ? 0 : 1].push(element); // Determine and push to small/large arr
      return result;
    },
    [[], []]);                                     // Default small/large arrays are empty

More options can be found in various StackOverflow questions.


I would consider using get(cache_key) within obj_setattr, rather than re-implementing it.

Another thing to look at would be to use a decorator to activate the lock, instead of writing the with every time. This would scale better in case you want to do some preprocessing / postprocessing later in time.


For simply counting word occurrencies, yes:

package main

import (
    "fmt"
    "regexp"
)

func get_words_from(text string) []string{
    words:= regexp.MustCompile("\\w+")
    return words.FindAllString(text, -1)
}

func count_words (words []string) map[string]int{
    word_counts := make(map[string]int)
    for _, word :=range words{
        word_counts[word]++
    }
    return word_counts;
}

func console_out (word_counts map[string]int){
    for word, word_count :=range word_counts{
        fmt.Printf("%v %v\n",word, word_count)
    }
}

func main() {
    text := "I am learning Go! Go is a nice language to learn."
    console_out(count_words(get_words_from(text)))
}

Supposing, splitting by \w+ gives in most cases, what you want.

Another solution would be (\\b[^\\s]+\\b). Depends on your demands.

Go play with it!


STOP USING __ its reserved for the implementation.

Basically stop using underscore until you know the rules.
This code is basically all broken because of this. You code technically is all undefined.
We told you this before. STOP IT.

BUG:

vector(const _Myt &_Rhs)
    : __size(_Rhs.__size), __capacity(_Rhs.__size + 20), __data(_Alloc().allocate(_Rhs.__size))

You are only allocating size space. But your capacity is 20 bytes larger.
Why 20 bytes? Should this not be 20 objects 20 * sizeof(_Ty)

BUG:

You use the allocator construct routines when you are doing placement new. This means the space has not been constructed before. If the location has already got an element in it you must copy over it using the copy constructor.

Thus in

_Myt &push_front(const value_type &_Value)

This line:

   _Alloc().construct(&__data[0], _Value);

You are constructing into location 0 a new object without calling the old objects destructor. If your type is anything non trivial this will screw up any memory management.

BUG

bool empty()
{
    return !__data;  // Both constructors allocate memory.
}                    // So this will never be true.

I think you mean

    return size != 0;

You have a potential leak situation in your reserve().
You provide the strong exception gurantee. BUT if the copy fails (with an exception) then you will leak the buffer. You need to hold the buffer in a smart pointer until you swap so that if there is an exception you gurantee that you deallocate the unused buffer.


Efficient way of code reuse for finding the largest prime factor

Usually, splitting your code into different smaller functions is a good idea as it makes things easier to read, to reuse and to test.

However, this comes at a (cheap) price as far as performances are concerned because functions calls are not for free (nor are function definitions).

Now, for additional advices, whenever you want to compare performances of functions, it might also be a good idea to return what they compare. It's not good having a fast function if it doesn't return the right thing. By using assert, you could ensure you get notified quickly whenever something goes wrong.

This being said, I'd like to run and comment your code but I don't have a python3 handy and it seems that it is the version you are using so I'll try to do this later :-)


Scroll listener - about code style guidelines and standards

Code style guidelines are available from a number of places. The 'old faithful' official Java ones have been pulled down, for some reason. Oh, they have been restored and are available in an archive format.... There are two other references that are commonly used for Java code style:

Original Java code style - Archived.
Google's Java code style
Eclipse/IntelliJ/Netbeans default formats (built-in guides).

This StackOverflow question seems particularly relevant: Official Java Code Guidelines/Conventions.

What all of these guides have in common is, and is contrary to your code, is:

don't put each parameter to the method on its own line. The limiting factor is the number of characters, not the number of parameters, on the line. This is true for both when you declare the method, and call the method.
never start a line with a close-parenthesis ). The close-parenthesis goes at the end of the previous line.
conditions in an if-block should be grouped where convenient, and line-breaks, if any, should be at logical breaks in the conditions. On the other hand, you are too generous with line-breaks in your conditions... !( on it's own line is bizarre.
when splitting long lines (string constants, long conditionals), put the 'operator' at the start of the next line, not the end of the previous one. For example, you have:

 mAdapter.isFiltered() &&
 mAdapter.isEmpty()

and that should be:

  mAdapter.isFiltered()
  && mAdapter.isEmpty()

Really, there are only a few areas of real controversy in Java code style guidelines:

indentation using tabs, or spaces: all code-style guidelines I have read for Java indicate that spaces should be used. For example, the Official (old) Java spec: "Four spaces should be used as the unit of indentation", and the Google spec "Each time a new block or block-like construct is opened, the indent increases by two spaces."

For some reason (and I am not sure why), a number of IDE's ship using tabs as the default indentation mechanism (I'm looking at you, Eclipse).

The amount of indentation is often site-specific, whether 2 or 4 spaces. Personally I am happy with either (as long as it is consistent), but I prefer 4.

Tabs vs. Spaces can become a battle of cultures, and it is seldom resolved without someone feeling upset.... but, when working as a team, using a version-control-system, you have to decide on one system, and then you have to be consistent with all developers. Messing with indentation after the fact is a very messy process in a version-control system.
End-of-line open-brace {, or new-line brace: this is one of those style things that is hotly debated, but Java conventions are clear. Brace at the end of the line. The thing is, that many other languages recommend a brace on the next line, especially 'punctuated' C languages like C, C++, C#. Because people often write in multiple languages and they like their habits to be the same in both, they often code Java with a brace on the next line. For Java, this is wrong though, even if it is inconvenient for those folk. Java has lines like:

if (condition) {
    .... do something....
}

the C* languages put the brace on the new line:

if (condition)
{
    .... do something....
}

Let's be clear on this one. A lot of people use newline-brace, but, in Java, that is not right, even if it is somewhat common.

Further, there are arguments for, and against the brace style, but it's a pointless argument. As much as there may be meaningful arguments about one, or the other, the consistency of usage is more important than any one argument.
indentation of switch-blocks: for some reason, there is a lot of inconsistency in switch-block indentation. I prefer the case/default blocks to be indented 4 from the switch, and the code for the case indented 4 from the case (Google style agrees with this indentation of the case, but uses 2 spaces). For example:

switch (somefowl) {
    case DUCK:
        System.out.println("Duck!");
        break;
    case GOOSE:
        System.out.println("Goose!");
        break;
    default:
        System.out.println("What?");
}

Many people, and some IDE defaults, do not indent the case/default (and the original Java guidelines use this style), and the code looks like:

switch (somefowl) {
case DUCK:
    System.out.println("Duck!");
    break;
case GOOSE:
    System.out.println("Goose!");
    break;
default:
    System.out.println("What?");
}

It's not a big deal. But, again, be consistent.
Braced 1-liners: One additional controversy is braces around 1-liners. You often see code like:

if (badDog)
    return "Sit! Stay!";

all code style guidelines recommend using braces even on 1-liners, and the code should look like:

if (badDog) {
      return "Sit! Stay!";
}

Google has this to say:

  Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement

The Java style guide says this:

  Note: if statements always use braces {}. Avoid the following error-prone form:

if (condition) //AVOID! THIS OMITS THE BRACES {}!
    statement;

In general I use Eclipse. The best thing for consistency in a team is for the whole team to use the same IDE for their code, and to install the same code-style 'rules'. Then, it becomes 'easy', you just type (in eclipse): Ctrl-A and Ctrl-Shift-F. Doing that, with your code, in my Eclipse, produces:

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {
    super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
    if (mUpdateFixedHeader
            && !(mAdapter.isFiltered() && mAdapter.isEmpty())
            && mDateHeader != null) {
        mDateHeaderTextView.setText(mDateHeaderLabel
                .concat(((MeetsListAdapter) mAdapter)
                        .getSectionForPosition(firstVisibleItem)));
    }
}

That looks about right, to me. No change needed.

When I auto-format your class, I get:

public abstract class AbstractListFragment<T> extends AbstractFragment
        implements OnItemClickListener, OnScrollListener, SearchListener {
    ...
}

Which also looks right to me.

Finally, for the above code formatting, I 'turned off' the Eclipse option to 'don't join lines'. Eclipse will 'collapse' lines when auto formatting. I often add additional empty lines in my code to make the code look like paragraphs. I want the auto-formatter to keep these empty lines, so I tell it not to format them out.

If I were to write this code, I would add some 'paragraphs' in to the code manually, and it would look like:

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {

    super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);

    if (mUpdateFixedHeader
            && !(mAdapter.isFiltered() && mAdapter.isEmpty())
            && mDateHeader != null) {

        mDateHeaderTextView.setText(mDateHeaderLabel
                .concat(((MeetsListAdapter) mAdapter)
                        .getSectionForPosition(firstVisibleItem)));

    }
}


Accessing a String value from multiple threads without synchronization

Your code is not synchronized at all at the moment.  There are two major mistakes:

You are only synchronizing in the thread(s) which are writing the value, but are never synchronizing on the threads reading the value.  You must always synchronized on all threads that read/write a value which is shared between thread.  Absolutely nothing is synchronized if you only synchronize on read or only on write.
You use synchronize(myValue), but you keep changing myValue, so you are synchronizing on different objects over time, which basically means no synchronization.

By the way, it is possible that you made some tests and everything seemed synchronized.  However, you should be aware that those tests would fail on other cpu's, or could fail on your machine if you tried them enough time.

More general comments:

Your whole class MetricsUpdater can be dropped for a volatile String myValueSynchronized.  Note however that this only work with references to immutable Objects (such as String), or raw types.
To answer your question "Does it even need to be synchronized at all if all of the other threads are only allowed to read it?"
NO!
You could forgo synchronization however if the value was final and unmodifiable.


Find the largest odd number (follow-up code)

Be careful of changing back and forth from ' and ". I can see that you probably used the double quotes just so you could include an apostrophe, but I think it's best to stay consistent and use them throughout since you never need to print any "'s later in the program.

print "You'll be asked to enter 10 integers."
print "The program will look for odd numbers, if any."

Also, you don't need to keep the list of odd_numbers if all you want is the highest one. So you could just directly get the max value:

max_value = max([item for item in numbers_entered if item % 2 == 1])

And this way, you don't even need to build a list. You can instead pass something called a generator expression directly to max. It's like a list comprehension, but it doesn't create a full list. It can be used in both for loops and functions that lake lists, like max does.

However, this would raise a ValueError if you had no odd numbers in the list, as max can't take an empty sequence. But you could just use this as your test instead of if odd_numbers.

try:
    max_value = max(item for item in numbers_entered if item % 2 == 1)
    print "The largest odd number entered was {}.".format(max_value)
except ValueError:
    print "No odd number was entered."