The algorithm itself looks solid, and your code looks good!  I just wanted to provide some general style tips for Java.

First, why are you performing the core of your logic in the test1 constructor?  That's highly irregular for Java.  A constructor in general should only perform processing to initialize values unique to each instance of the class.  It would be much more object-oriented to either move all that code directly into your main(String[] args) method or into a different static method.  Having a test1 instance doesn't even make sense here.

Second (and much less importantly), you are breaking with several Java style conventions.  I'm assuming you come from a Python background, because your code "feels" very Pythonic.  That's not a bad thing, but they're two very different languages.  Python attempts to always be short and to the point, while Java emphasizes verbosity and long, descriptive names for things.  As such, here are a few tips to make your code more Java-esque (if you care):

Class names should have each word capitalized, like in ThisTestClassName.  So yours should be Test1 and Stats.
Class names and variable names are also generally not abbreviated.  So for example, your stats class would likely be called Statistics.
Likewise, your method names would likely be renamed to something more descriptive.  While anyone with a statistics background will know what you mean by stddev, it's standard for Java methods to be unabbreviated verb phrases.  So it would be more appropriate to rename this method as getStandardDeviation().  Believe it or not, this really does make a difference in code readability.  For example, when scanning your code, I was very confused by this line at first (Math.sqrt(var(a))) because it seemed like you were trying to do some odd JavaScript casting of a at a glance.  A more descriptive method name like getVariation() would have easily avoided that confusion.
To a lesser degree the "make things more descriptive" points from above apply to variable names as well, though it's much more common (if still frowned upon) to see this in local scope variables.  For example, your code gets a little obfuscated in your test1() constructor because you use at least four variables which are only one letter: i, k, r, and s.  In theory, with well-chosen variable names, I should be able to understand what the code is trying to do at any point without much surrounding context.  That's the goal of making "self-documenting code".

And finally, one small tip which might clean up your code a little bit concerning this line:

for (Double s : dmap.values().toArray(new Double[dmap.size()]))

Here you can actually just use .toArray(new Double[0]) if you feel that would make your code less wordy.  As you can see in the documentation, you don't actually have to pass in an array of the appropriate size to the toArray() method; it only uses your array for infer the type to return to you.  So by just initializing an empty, zero-length array like this, you may be able to improve code readability a bit (and performance by just a small amount, by saving on memory allocation).  There's no consensus or standard on this.  Just personal preference.


These answers are fantastic, but seem to be focusing on one side of your question.  I'm going to focus on object orientation.

I reviewed your code with a couple basic concepts in mind, namely polymorphism and encapsulation.

Polymorphism

Where are your objects?  A rock, paper, and scissors could all be objects, could they not?  And, most importantly, they are all the same kind of object.  They are all "pieces" of the game.

Here's a pseudo-example:

class Rock inherits from Element
    type = 'rock'
    def compare(Element)
        if type == 'paper'
            return 'LOSE'
        elsif type == 'scissors'
            return 'WIN'
        else
            return 'TIE'

Although this is a potential solution, my example is going to go in a different direction simply for the fact that if you wanted to add more elements then you'd have to touch the existing code (re: Chris' example of RPSLS).

Encapsulation

A great programming muscle to exercise is encapsulation.  The two main areas, in this example, are to hide the user interface from the game code.

The user interface shouldn't care about the inner-workings of the game.  The game shouldn't care how it's displayed.  What if you wanted to change the interface to something more graphical?  Right now, your code relies on the console to know about the pieces of the game and how it works.

Example

So, let's return to Chris' example again.  The elements of this game are something that may change quite often.  How can you handle this to make future programming easier?

One solution is to store the "data" of the game elsewhere and dynamically create objects.

The following is Python code to materialize the ideas I've written about here.

Here's code for an abstracted piece of the game, an element:

# The goal for an element is to just know when it wins, when it loses, and how to figure that out.
class Element:
    _name = ""
    _wins = {}
    _loses = {}

    def get_name(self):
        return self._name

    def add_win(self, losingElementName, action):
        self._wins[losingElementName] = action

    def add_loss(self, winningElementName, action):
        self._loses[winningElementName] = action

    def compare(self, element):
        if element.get_name() in self._wins.keys():
            return self._name + " " + self._wins[element.get_name()] + " " + element.get_name()
        elif element.get_name() in self._loses.keys():
            return None
        else:
            return "Tie"

    def __init__(self, name):
        self._name = name
        self._wins = {}
        self._loses = {}

Games have players:

# The player's only responsibility is to make a selection from a given set. Whether it be computer or human.
class Player:
    _type = ''
    _selection = ''

    def make_selection(self, arrayOfOptions):
        index = -1
        if (self._type == 'Computer'):
            index = random.randint(0, len(arrayOfOptions) - 1)
        else:
            index = int(raw_input('Enter the number of your selection: ')) - 1
        self._selection = arrayOfOptions[index]
        return self._type + ' selected ' + self._selection + '.'

    def get_selection(self):
        return self._selection

    def __init__(self, playerType):
        self._type = playerType
        self._selection = ''

Game code:

# A game should have players, game pieces, and know what to do with them.
class PlayGame:
    _player1 = Player('Human')
    _player2 = Player('Computer')

    _elements = {}

    def print_result(self, element1, element2):
        val = element1.compare(element2)
        if (val != None):
            print "YOU WIN! (" + val + ")" # win or tie
        else:
            print "You lose. (" + element2.compare(element1) + ")"

    def fire_when_ready(self):
        counter = 1
        for e in self._elements.keys():
            print str(counter) + ". " + e
            counter = counter + 1
        print ""
        print "Shoot!"
        print ""

        print self._player1.make_selection(self._elements.keys())
        print self._player2.make_selection(self._elements.keys())

        element1 = self._elements[self._player1.get_selection()]
        element2 = self._elements[self._player2.get_selection()]

        self.print_result(element1, element2)

    def load_element(self, elementName1, action, elementName2):
        winningElementObject = None
        newElementObject = None

        if (elementName1 in self._elements):
            winningElementObject = self._elements[elementName1]
            winningElementObject.add_win(elementName2, action)
        else:
            newElementObject = Element(elementName1)
            newElementObject.add_win(elementName2, action)
            self._elements[elementName1] = newElementObject

        if (elementName2 in self._elements):
            losingElementObject = self._elements[elementName2]
            losingElementObject.add_loss(elementName1, action)
        else:
            newElementObject = Element(elementName2)
            newElementObject.add_loss(elementName1, action)
            self._elements[elementName2] = newElementObject

    def __init__(self, filepath):
        # get elements from data storage
        f = open(filepath)
        for line in f:
            data = line.split(' ')
            self.load_element(data[0], data[1], data[2].replace('\n', ''))

The console code, the user interface:

if __name__ == "__main__":
    print "Welcome"
    game = PlayGame('data.txt')
    print ""
    print "Get ready!"
    print ""
    game.fire_when_ready()

And the data file, data.txt:

scissors cut paper
paper covers rock
rock crushes lizard
lizard poisons spock
spock smashes scissors
scissors decapitates lizard
lizard eats paper
paper disproves spock
spock vaporizes rock
rock crushes scissors

The goal for my answer was to show you how you can use some object oriented concepts in solving your problem.  In doing so I also left some unresolved problems.  One big one is that the player and game objects are still coupled to the user interface.  One way to nicely resolve this would be through the use of delegates.


MVC controller and action that handles favorite items in a session-based list

A few thoughts.

Consider building a result or response class to:

provide better structure around the returned result
provide possible re-use in other controllers
and clean up this code.

For example:

// instantiation
$result = new Result();

// usage
$result->setSuccess(true);
$result->setEntity($entity);

You could have this class implement JsonSerializable interface so you can pass it directly to JsonResponse() for serialization.  This also allows you to do things like add validation that setters are passed valid values (i.e. boolean for setSuccess())

You have a number of cases where you could remove else blocks and code nesting if you invert your conditionals.

For example:

    if (in_array($entity, $this->validEntites)) {
        $result['entity'] = $entity;
    } else {
        $result['success'] = false;
    }

can become:

   $result['success'] = false;
   if (in_array($entity, $this->validEntites)) {
        $result['entity'] = $entity;
   }

or:

  if(!in_array($entity, $this-.validEntities)) {
      $result['success'] = false;
      return JsonResponse($result);
  }
  $result['entity'] = $entity;

Similarly:

if($result['success']) {
    // nested code
}

could become:

if(!$result['success']) {
    return JsonResponse($result);
}
// rest of code, now without nesting

Look for opportunities to remove code paths and complex nesting by getting rid of unnecessary else blocks (many of which truly are unnecessary) and exiting early by inverting conditions.  The fewer code paths you have in your code, the less fragile, easier to test, and easier to maintain it will be.

I think if you clean those things up, you will probably save 40% of the lines of code in this method. So it might not look like there is "too much" happening in this single method.  That being said, I think you could possibly fork the execution path along the lines of $action value , and hand off to protected/private class methods to finish that particular work.

For example:

switch($action) {
    case 'remove':
        return $this->removeFavorite(...);
    case 'add':
        return $this->addFavorite(...);
    default:
        $result['success'] = false;
        return JsonResponse($result);
}

This would allow to more easily unit test those individual methods that represent some subset of logic on dealing with "favorites".

Similarly, you could perform all your upfront Request validation in a separate method as well to where you are getting towards something more like this in your main method.

Ex:

public function handleFavoritesAction(Request $request) {
    // here $result could be Result object as suggested above
    $result = $this->validateRequest($request);
    if($result->isSuccess === false) {
       return JsonResponse($result);
    }
    $action = $request->get('action');
    switch ($action) {
        // switch as shown above
    }
}

With regards to your documentation, I find many of your comments to be unnecessary. I think you generally have meaningfully named variables and appropriate use of vertical whitespace between logical sections of code to where comments become superfluous.  Especially, if you consider breaking this main method into several other well-named methods, you should not have much need to comment this code.


You can make DbContext protected property in your base implementation, so you don't have to declare it in every single derived class.
You might want to consider extracting Insert and Delete methods to separate interface, because often you want to make some of your repositories readonly.

Implementation may look like that:

interface IRepository<T>
{
    IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
    IQueryable<T> GetAll();
    T GetById(int id);
}

interface IEditableRepository<T> : IRepository<T>
{
    void Insert(T entity);
    void Delete(T entity);
}

class ReadOnlyRepositoryBase<T> : IRepository<T>
{...}

class EditableRepositoryBase<T> : ReadOnlyRepositoryBase<T>, IEditableRepository<T>
{...}

this way you can distinct readonly repositories from non-readonly at compilation time.
Passing dbContext to every repository is not normally an issue, because usually in addition to your repositories, you also implement factory object, which creates your repositories for you, so you don't have to call constructor explicitly. This factory can be made a singleton, so you can access it at any point in your code. Alternatively, you can register your repositories in some container, or you can use both approaches.
If you are familiar with inversion of control and dependency injection (because there is definitely a learning curve), your best bet is to use a container.

Here is an example (using Castle Windsor):

public class RepositoryFactory : IDisposable
{
    private IWindsorContainer _container;

    public void Open()
    {
        _container = new WindsorContainer();

        //register dependencies
        _container.Register(Component.For<DbContext>().ImplementedBy<DbContext>());

        //register repositories
        _container.Register(Component.For<ICustomersRepository>().ImplementedBy<CustomersRepository>());
    }

    public TRepository GetRepository<TRepository>() where TRepository : class
    {
        return _container.Resolve<TRepository>();
    }

    public Dispose()
    {
        if (_container == null) return;
        _container.Dispose();
        _container = null;
    }

    public void Close()
    {
        Dispose();
    }
}

Then you can use it like this:

var f = new RepositoryFactory();
f.Open();
var rep = f.GetRepository<ICustomersRepository>();
f.Close();

Alternatively, you can implement your own container using reflection to instantiate your repositories, or you can use a dictionary. Or w/e, really. This implementation is obviously no singleton, but nothing stops you making one, if you feel like it.

Apart from that, your implementation looks fine to me. I didn't quite get your first issue though.


I think the answer depends on the scope of your constants.

If you're trying to keep the constants the same across your handful of classes, i.e., you have many class definitions and they all use ABOVE and BELOW, and ABOVE and BELOW always have the same value, then you should pull them out. You could put them into a base class and create subclasses from that base class:

class myBaseClass(object):
    ABOVE = 1
    BELOW = 0

class mySubclass(myBaseClass):
    """ ABOVE and BELOW will be available here """
    pass

If the scope is greater than that, say module-level then put the definitions in the module __init__.py

Greater still?  Then maybe move them to a settings file.

Otherwise if the scope is where you currently have it then it's ok as-is.

The line:

my_var = my_class.find_thing_in_direction(MyClass.ABOVE, 3)

puzzles me because you're referring to the constant of the Class when the instance already has it itself. It's not wrong, just differs from my reaction to use the object's own attributes:

 my_var = my_class.find_thing_in_direction(my_class.ABOVE, 3)

If you go the way of a base class, have a look at ABCs


The proper way to prime a generator for accepting values is to send an initial None value.
Yield will simultaneously return a value to the caller, and accept a value sent from the caller.
Using those two facts, you could rewrite the code like:
...

def coroproperty(method: Callable) -> property:

    ...

    def setter(self, value: Any) -> None:
        coro = method(self)
        coro.send(None)
        with suppress(StopIteration):
            coro.send(value)

    ...

class Circle:

    ...

    @coroproperty
    def diameter(self):
        self.radius = (yield self.radius * 2) / 2

    ...

Side-effects
Wasted time and computation.  Setting the diameter, circumference and/or area first involves computing those quantities, which is unnecessary.
You could circumvent that by accepting a new value before returning the value.
    @coroproperty
    def diameter(self):
        diameter = yield None
        if diameter is not None:
           self.radius = diameter / 2
        else:
           yield self.radius * 2

The getter would need to call next(coro) twice, ignoring the first returned value: None.
If you desired a property which could store None, you'd need to create and use your own sentinel value.

Assignment to diameter, even if not changing the value, will change the radius.  In this example, it is changed from an int to a float:
>>> c.radius = 100
>>> c.radius
100
>>> c.diameter = c.diameter
>>> c.radius
100.0

Add in sqrt, and multiplication & division by π, and accuracy can be lost:
>>> c.radius = 1_000_000_000_000
>>> c.area = c.area
>>> c.radius
999999999999.9999


Avoid mysterious bit-shifting
return ~output + 1;

Is the same as:
return - (output + 1) + 1;

And as:
return - output;

But the last one is way more obvious than the first one.
Do not hide variable declarations
int ASCIICodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  _Bool negative = 0;

If I look at the above line, the least thing in my mind is that a variable is defined after that list.
If a user has a small screen or a big font size he will be very puzzled when he will see you use negative without seeing its definition.
Just use a newline, they are free:
int ASCIICodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
_Bool negative = 0;

Make variables as local as possible
I used x++ to express that I will skip the first character:
if (x[0] == '-')
{
    negative = true;
    x++;
}
else if (x[0] == '+')
{
    x++;
}

This allows me to make count local.
Using for loops when practical
The outer of your loops is a do while, but looking around I found all three components of a for loop, just shuffled into the code.
A for loop will give it more organization:
for (int count = 0; x[count] != 0; count++)
{
    for (int i = 0; i < base; i++)
    {
        if (ASCIICodes[i] == x[count])
        {
            output = output * base + i;
            break;
        }
    }
}

Simplify the initial conditional
Assigning a boolean to negative directly and using a || conditional looks shorter and simpler:
We go from:
_Bool negative = 0;
int count = 0, output = 0;
if (x[0] == '-')
{
    negative = 1;
    count = 1;
}
else if (x[0] == '+')
{
    count = 1;
}

to:
bool negative = x[0] == '-';

if (x[0] == '-' || x[0] == '+')
{
    x++;
}

While preserving identical functionality.
it's vs its

... How to choose between it's and its?
This is actually really easy, do you mean "it is" or not?

Use it's when you mean it is.
// Each element is the ASCII for it's index.

Here you should write its because you mean possession, intended as a property of the element.
Saying that:
// Each element is the ASCII for it is index.

Makes no sense.
So the correct comment will be:
// Each element is the ASCII for its index.


Yes, that's pretty good. It's essential to include use strict at the top of every Perl program you write, and use warnings is preferable to -w on the command line. You should also avoid capital letters in identifiers for lexical variables, as they are reserved for use in global identifiers such as package names

I would write something more Perlish like this

#!/usr/bin/perl

use strict;
use warnings;

use XML::Mini::Document;

use constant OUTFILE => 'D:/Test.xml';

sub rand_letter { chr(ord('A') + rand(26)) }

my $new_doc = XML::Mini::Document->new;
my $root    = $new_doc->getRoot;
my $header  = $root->header('xml');
$header->attribute(version  => '1.0');
$header->attribute(encoding => 'UTF-8');

my $records= $root->createChild('records');

my $sequence = 1000;

for ( 0..9 ) {

    my $record = $records->createChild('record');

    my ($random_name, $random_desc);
    $random_name .= rand_letter for 1 .. 6;
    $random_desc .= rand_letter for 1 .. 15;

    $record->createChild(ID   => ++$sequence);
    $record->createChild(Name => $random_name);
    $record->createChild(Desc => $random_desc);
}

open my $fh, '>', OUTFILE or die $!;
select $fh;
print $new_doc->toString;


Flattening multiple nested node readline questions

Also, I was looking for an answer how to flatten (and automate) calls to rl.question(). In my solution I used Promises - chained - to display questions sequentially.

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const QUESTIONS = {
    action1: ['A1: Question 1', 'A1: Question 2', 'A1: Question 3'],
    action2: ['A2: Question 1', 'A2: Question 2', 'A2: Question 3']
}

let askQuestions = (actionKey) => {
    return new Promise( (res, rej) => {
        let questions = QUESTIONS[actionKey];

        if(typeof questions === 'undefined') rej(`Wrong action key: ${actionKey}`);

        let chainQ = Promise.resolve([]); // resolve to active 'then' chaining (empty array for answers)

        questions.forEach(question => {
          chainQ = chainQ.then( answers => new Promise( (resQ, rejQ) => {
                rl.question(`${question}: `, answer => { answers.push(answer); resQ(answers); });
            })
          );
        });

        chainQ.then((answers) => {
            rl.close();
            res(answers);
        })
    });
};

let handleError = (err) => {
    console.log(`ERROR: ${err}`);
}

let doSomethingwithAnswers = (answers) => {
    return new Promise( (res, rej) => {
        console.log('OUTPUT:');
        console.dir(answers);
    });
}

askQuestions('action1')
    .then(doSomethingwithAnswers)
    .catch(handleError);

Output:

A1: Question 1: a
A1: Question 2: b
A1: Question 3: c
OUTPUT:
[ 'a', 'b', 'c' ]

If you want the action to be chosen by the user, add these functions:

let showInterface = () => {
    return new Promise( (res, rej) => {
        console.log('Select action (enter action name):')
        console.log('-'.repeat(30));
        Object.keys(QUESTIONS).forEach(actionKey => {
            console.log(`${actionKey}`);
        });
        console.log('-'.repeat(30));
        res();
    });
};

let askQuestionForActionKey = () => {
    return new Promise( (res, rej) => {
        rl.question('Action key: ', actionKey => res(actionKey));
    });
}

And change main procedure to:

showInterface()
    .then(askQuestionForActionKey)
    .then(askQuestions)
    .then(doSomethingwithAnswers)
    .catch(handleError);

Now output shoud be like:

Select action (enter action name):
------------------------------
action1
action2
------------------------------

Action key: action1
A1: Question 1: a
A1: Question 2: b
A1: Question 3: c
OUTPUT:
[ 'a', 'b', 'c' ]

In case of error (e.g. enter non-existent action 'action3'):

Select action (enter action name):
------------------------------
action1
action2
------------------------------
Action key: action3
ERROR: Wrong action key: action3

It's very easy to apply this solution to your problem. Just define your questions as:

const QUESTIONS = {
    sequence: ['Thing One', 'Thing Two', 'Thing Three']
};

Your callback with answers:

let doSomethingwithAnswers = (answers) => {
    return new Promise( (res, rej) => {
        console.log('Make stuff with answers:');
        console.dir(answers);
    });
}

And the procedure may be unchanged - when a user has the ability to select a set of questions (actions):

showInterface()
    .then(askQuestionForActionKey)
    .then(askQuestions)
    .then(doSomethingwithAnswers)
    .catch(handleError);

Output:

Select action (enter action name):
------------------------------
sequence
------------------------------
Action key: sequence
Thing One: a
Thing Two: b
Thing Three: c
Make stuff with answers:
[ 'a', 'b', 'c' ]

Or if you want to apply to concrete questions set just use:

askQuestions('sequence')
    .then(doSomethingwithAnswers)
    .catch(handleError);

Output:

Thing One: a
Thing Two: b
Thing Three: c
Make stuff with answers:
[ 'a', 'b', 'c' ]

I hope it will be useful :)
Enjoy!


Don't expose fields, even if they're readonly:

public readonly T Value;
public readonly int BufferSize;

Instead expose properties:

public T Value { get; private set; }
public int BufferSize { get; private set; }


Append a incrementing number to a slug username

Searching for the slug duplicate in the database can be done in a more fast and straightforward way, by using = operator instead of like, and not using orderBy;
To be on the safe side, it's worth to make searches in a loop, incrementing the $next on each step;

So, it might look like this:

protected function create(array $data)
{
    $slug = $maybe_slug = strtolower($data['first_name'] . '.' . $data['last_name']);
    $next = 2;

    while (User::where('slug', '=', $slug)->first()) {
        $slug = "{$maybe_slug}.{$next}";
        $next++;
    }

    return User::create([
                'first_name' => $data['first_name'],
                'last_name' => $data['last_name'],
                'slug' => $slug,
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
    ]);
}


Renaming PDF files based on given rules in a text file

For now I'll just throw up a few random thoughts.

The first thing I would do with rename_files_with_instrument_name is get rid of its reliance on the global FOLDER variable. Take a directory path as an argument, or shove it in a class and make the folder a parameter to the class's __init__ method which gets stored in an instance variable. That should immediately make it easier to write tests for rename_files_with_instrument_name; just pass in a folder and check that you get the results you expect.

The second thing I would do with rename_files_with_instrument_name is try and shorten the name a little. It's very long. Something like add_instrument can be good enough in context, but even rename_with_instrument is an improvement.

Going inside rename_files_with_instrument_name, using bald except is usually a bad practice. I gave an example case where bald except is bad in my answer to another question. If you think an exception might be thrown, it's better to name the specific exception. Also, make sure the situation where the exception gets raised is actually exceptional (an error or some situation which some code outside the function should handle). It looks a little like you're handling a normal, expected case in your except block—the case where the root filename is shorter than three characters. It's better to handle those with if. Not only is it easier to understand, it's also actually faster; catching exceptions is fairly time-consuming in most languages.

However, you don't actually need a conditional here; if you try to take a slice of a string which is longer than the entire string, the entire string just gets returned. That is:

>>> s = "ab"
>>> s[:30]
"ab"

So you can just write, without the try block, if root[:2] in instrument_map.

It's also usually good to avoid continue if you can. Sometimes you can't, and in those cases, don't contort yourself. But I think you can here. It looks like you could just write:

if extension.endswith(".pdf"):
    # All the code to construct a new filename


Alternative way to extract the most recent file using LINQ

This should do it:

var selectedFileInfos = listFileInfo
    .Where(x => {
        var filename = Path.GetFileNameWithoutExtension(x.FullName);
        return specialProcList.Any(y => filename.Contains(y);})
    .OrderByDescending(x => x.Name)
    .GroupBy(x => Path.GetFileNameWithoutExtension(Regex.Replace(x.Name, @"[\d]", String.Empty))
    .Select(x => x.First());

But be careful: file numbers should be padded with zeros. 0001, 0900, 0999, 1000, 1001. If they are just normally numbered with 1, 900, 999, 1000 etc., even your code will fail.


I think your naming scheme is good and on first sight its very easy to see what the code does without having to study it too much.

However, if I would pick on something I would say:

Remove the unnecessary whitespace, ex. if ( condition ), or self.getUserInfo( userId ). This is of course a matter of taste, but I find it more consistent with regular coding style to not 'bloat' with whitespace.
optparser was deprecated in 2.7: http://docs.python.org/library/optparse.html
in parser.add.option() you could remove the word "show" from the dest name and rather do the following, hence eliminating the need for all the declarations of show_display_name and still keep easy code readability.

...
parser.add.option(parser.add_option("-r", "--reputation", action="store_true", dest="reputation", default=False, help="Show user's reputation")
(show, args) = parser.parse_args()

fetch = StackOverflowFetcher()
if(show.reputation) : print fetch.getUserReputation(show.userId)

I don't really see what the point of the following line which sets everything to true, it seems a bit weird since you use store_true as action if the option parsed is set.

if ( (not show_display_name) and (not show_view_count) and (not show_reputation) ):
show_display_name = show_view_count = show_reputation = True


UPenn Homework 3: localMaxima :: [Integer] -> [Integer]

The implementation can be much simpler.  The main insight I can offer is to use map and filter instead of Maybe and writing your own accumulate.  In addition,

Instead of writing case l2 of …, use pattern matching.
Look for library functions that you can take advantage of.  (Here, I've used tails from Data.List.)
In keeping with the "wholemeal programming" goal, use higher-order functions instead of recursion.
Higher-order functions also let you use point-free style, which lowers your mini-golf score.

I suggest using where instead of let … in … because the former encourages top-down strategic thinking.  You want to write a "one-liner", and add supporting details only if necessary.

import Data.List (tails)

localMaxima :: [Integer] -> [Integer]
localMaxima = map (!!1) . filter isLocalMax . tails
  where
    isLocalMax (a:b:c:_) = a < b && b > c
    isLocalMax _         = False

In addition to being shorter, this implementation is more maintainable.  You can tell at a glance what map (!!1) . filter isLocalMax . tails does, but reverse (accumulate l []) is mysterious.  Furthermore, because isLocalMax is not intertwined with accumulate, you can trace the execution by inspecting tails xs, then (filter isLocalMax . tails) xs, etc.


Authentication via LDAP and authorization via JDBC

By using a framework like Spring Security you have all you cicle already defined and your task is just to customize the parts you need that should be integrated with your application and need some logic for that.

First of all I would raise here a good practice that Spring developers don't follow.
In documentation you always found code like:

@Autowired
private UtilisateurService utilisateurService;

That is good for Spring to show you a cool and quick short way to inject stuff in your class avoiding boilerplate code.

Said that, it is not good in production code.

You should, instead, write a proper construction method for a mandatory dependency:

private UtilisateurService utilisateurService;

@Autowired
public ADAuthenticationJDBCAuthorizationProvider(ActiveDirectoryLdapAuthenticationProvider adDelegate, UtilisateurService utilisateurService) {
    this.adDelegate = adDelegate;
    this.utilisateurService = utilisateurService;
}

Or a setter if the dependency is not mandatory:

private UtilisateurService utilisateurService;

@Autowired
public void setUtilizateurService(UtilisateurService utilisateurService) {
    this.utilisateurService = utilisateurService;
}

The reason to do so is to expose your dependencies to the user of your class, instead of hiding.

You should just hide your data in the classes, not the dependencies.

Showing up all dependencies make your code easy to use and test.

Another point I would like to rise is in your UserDetailsService implementation:

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    final String name = username.toLowerCase();
    Collection<GrantedAuthority> authorities = utilisateurService.loadRolesFromDatabase(name);
    final boolean isActive = utilisateurService.isActive(name);

    return new User(username, "", isActive, true, true, true, authorities);
}

I think you should avoid to instantiate here a UserDetails object.

Instead you should have a builder that initialize the object as needed for you:

public class User implements UserDetails {
    // ... code ...

    public static User from(String userName, boolean isActive, List<GrantedAuthority> authorizations) {
        User user = new User(userName, "", isActive, true, true, true, authorizations);
    }
}

...

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    final String name = username.toLowerCase();
    Collection<GrantedAuthority> authorities = utilisateurService.loadRolesFromDatabase(name);

    return User.from(username, utilisateurService.isActive(name), authorities);
}

In this way you can ensure to have just valid users, and you have a single point in your code where you handle what a valid user is.


First, there are some errors that need to be fixed in order for your code to compile:

size_t needs to be std::size_t, or alternatively there needs to be an using std::size_t; declaration.
no matching function for call; you need to specify the template instantiation of the structure based on the "depth" as well as the function:

// WRONG:
unroll<N/2, ForwardIterator, Function>(f, it);
// FIXED:
unroller<N/2>::template unroll<ForwardIterator, Function>(f, it);

From a style perspective, I'd change the order of the template parameters to reflect the order in which the typenames appear in the parameter list (first the Function, then the ForwardIterator).

Then there's one thing that's a bit odd: Functions in the standard library which accept function objects (like std::sort, std::transform, ...) generally accept those function objects by value. This is done (probably) because that allows those functions objects to have mutable state. Your unroller accepts only references to constant function objects. That makes it (a bit) harder to have mutable state in the function object, like when you get one returned by some function:

auto make_that_function_object() {
    bool flag = true;
    return [flag](int n) mutable {
        if (flag) std::cout << n << ' ' << std::flush;
        flag = !flag; };
}

The lambda returned by above function cannot be used with your unroller. To fix it (as a user of your unroller), you need another (non-mutable) lambda which references the original one:

auto original = make_that_function_object();
auto wrapper = [&original](int n) { original(n); };

You could also solve this by accepting non-const references, though I'm not sure whether that's really better. (Accepting the function object by value does not solve the issue because then any changes to the internal state cannot be transferred "back up" the call chain or past "major" iterations of the top level loop.)


You can simplify your code to a great extent by using a Map<String, Integer> instead of List<String>. The map would store the mapping from each word to it's count in the array.

You can modify your code like so:

String str = "I am a Boy I am a";
String[] splitStr = str.split(" ");

Map<String, Integer> wordCount = new HashMap<>();
for (String word: splitStr) {
    if (wordCount.containsKey(word)) {
        // Map already contains the word key. Just increment it's count by 1
        wordCount.put(word, wordCount.get(word) + 1);
    } else {
        // Map doesn't have mapping for word. Add one with count = 1
        wordCount.put(word, 1);
    }
}

And then simply iterate over the map, and print the key: value pair:

for (Entry<String, Integer> entry: map.entrySet()) {
    System.out.println("Count of : " + entry.getKey() +
                       " in sentence = " + entry.getValue());
}


Determine if an array is the reverse of a second array

The first comment, is that it would be preferable to factor this into a dedicated method, like areReversed(int[] array1, int[] array2). It would clarify the intention of the code. And, as it turns out, this will point out some improvements about the method itself.

It is currently modifying in-place the first array, in order to reverse it. If you now consider the code to be in a method, you could have

int[] array1 = new int[] { 1, 2, 3, 4, 5, 6 };
int[] array2 = new int[] { 6, 5, 4, 3, 2, 1 };
areReversed(array1, array2); // OK, prints that they are reversed versions
// some code
areReversed(array1, array2); // What? Now it prints that they aren't reversed?!

Calling the method a second time with the same arguments would not have the same result. This would be very surprising, especially so that one doesn't expect that method to behave in such a way. It is always preferable to adhere to the principle of least astonishment.
We want to know whether the two arrays are reversed, and we may want to do more than printing a String if it is the case. Make the method return a boolean that the calling code can use.

The insight is that you do not need to reverse an array, and determine whether the two are equal, for this. First of all, if they don't have the same length, there is no need to do anything, it is already known for sure that the result is false. Then, you can directly compare the arrays, by traversing one in a given direction and the other one in the opposite direction.

B   A   C            B   A   C            B   A   C
|                        |                        |
----x----                x                ----x----
        |                |                |
C   A   B            C   A   B            C   A   B

 Step 1               Step 2                Step 3

The upper part goes from left to right, and it compares elements with the lower part going from right to left. If there's a mismatch at any point, we know the arrays are not reverse of each other. And since we know they have the same length, all element of both arrays will have been considered.

A simple code to do this would be

public boolean areReversed(int[] array1, int[] array2) {
    if (array1.length != array2.length) {
        return false;
    }
    int length = array1.length;
    for (int i = 0; i < length; i++) {
        if (array1[i] != array2[length - i - 1]) {
            return false;
        }
    }
    return true;
}

That you can later use with:

if (areReversed(array, tempArray)) {
    System.out.println("yep,reversed");
} else {
    System.out.println("nope,not reversed");
}

You'll note that this implementation somewhat takes care of the concern you had with the code: "breaking the loop and setting a boolean value". In fact, there is no boolean variable: we return directly from the method once we know for sure what to return. The return inside the loop is really for optimization purposes; once a mismatch is encountered, there is no need to process further the arrays, since it is known that the result can only be false at that point. This is also what the initial break was doing.

Small final note. Instead of

int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
int[] tempArray = new int[] { 6, 5, 4, 3, 2, 1 };

you could just have

int[] array = { 1, 2, 3, 4, 5, 6 };
int[] tempArray = { 6, 5, 4, 3, 2, 1 };

which is a bit more concise, and makes the array declaration a tad more readable.


Divide and conquer algorithm for max binary gaps

Bug

What will be the value of merge_step([array], [array], result)? Nothing.
The solution will be incorrect for 0 and 1.

Algorithm

Converting an integer to binary string, and then converting that to a list of integers (zeros and ones), and then slicing dicing lists is very inefficient.

A much more simple and efficient approach is to count the sequences of unset bits:

longest = 0
current_len = 0

while num > 0:
    if num & 1:
        if current_len > longest:
            longest = current_len
        current_len = 0
    else:
        current_len += 1
    num >>= 1

return longest

The reason why the time complexity of this is \$O(\log n)\$ is that we're counting bits, which grows much slower than the value of \$n\$.

Doctests

As I pointed out in the previous review, I strongly recommend to use doctests to verify your implementation.


Note: I run it with ./generator.bash 4 > x && vim x so stdout is not printed to the terminal, but I'm not sure if this is neccessary. I'm thinking that somewhere terminal history could be stored.

I don't think this is necessary.
If anything, you might forget to remove x,
which could be a security risk.

Avoid seq

seq is not a standard tool, and a native alternative exists:

for ((i = 0; i < n; i++)); do ...; done

Extract constants out of loops

This statement is executed in each iteration of the loop:

lines=$(cat $words | wc -l)

But the content of the $words file is likely constant,
so it's safe to compute this once, before entering the loop.

Unnecessary cat

The cat command is unnecessary with wc, it's better to redirect input:

lines=$(wc -l < "$words")

Double-quote variables in command line arguments

Although the content of $words doesn't contain spaces,
as a good practice it's good to double-quote it when using as program arguments, for example instead of:

awk "NR==$line" $words

Write:

awk "NR==$line" "$words"

Arithmetic context

Instead of this:

line=$((random % lines))

You can write simpler:

((line = random % lines))


Handling large amount s of ajax/POST commands

To answer the specific question: if you know the arguments in advance (as you should), you can loop over them and add them to an arguments-array instead.

Always, ALWAYS, validate input. Not just to check that it is there but also that it confirms to expectations.


Imputing values with non-negative matrix factorization

In the while loop, the first call you make to nmf_model.fit_transform() is superfluous and can be removed.  You aren't even using the results of the transformation calculation.  The next line, where you have W = nmf_model.fit_transform(X_imputed.values) is doing all the work.  Removing this line halves the number of model fits and speeds things up by ~twofold.
You don't need to assign H outside/before the while loop.
If minimization of code lines is the goal, you can avoid assigning to temporary variables and just put the expression that you would have used to define the variable in the code line that uses it.  I did that for H in the while loop.  It is more compact but probably harder to understand.
You don't seem to need to full pandas module, so that import can be removed.
I didn't change anything in my code below, but why are you squaring nmf_model.reconstruction_err_?  According to the docs this error is the Frobenius norm of the difference matrix (X - WH), so it will always be positive even without squaring.

This is a tad more compact and significantly faster (because of item 1):

from pandas import DataFrame
import numpy as np
from sklearn.decomposition import ProjectedGradientNMF

# Example data matrix X
nrows, ncols = 200, 150
toy_vals = np.random.random(nrows*ncols).reshape((nrows, ncols))
toy_vals[toy_vals < 0.9] = np.nan
X = DataFrame(toy_vals, index=range(nrows), columns=range(ncols))

# Hiding values to test imputation
X_imputed = X.copy()
msk = (X.values + np.random.randn(*X.shape) - X.values) < 0.8
X_imputed.values[~msk] = 0

# Initializing model
nmf_model = ProjectedGradientNMF(n_components=5)
nmf_model.fit(X_imputed.values)

# iterate model
while nmf_model.reconstruction_err_**2 > 10:
    W = nmf_model.fit_transform(X_imputed.values)
    X_imputed.values[~msk] = W.dot(nmf_model.components_)[~msk]
    print nmf_model.reconstruction_err_


This seems pretty nice. I have just some nitpicks about this part:

postfixs = [".isf", ".ISF"]
if os.path.splitext(binaryfile)[-1] not in postfixs:
    raise ValueError("File type unkown.")

Nitpicks:

I generally don't like repeating the same thing in lowercase and uppercase versions. I prefer to use lowercase, and convert untrusted input to lowercase. However, that will make this check less strict: iSF and ISf also become valid extensions, which you might not want.
I'd spell out "postfixs" as "postfixes", or better yet, use the more common term "extensions"
Instead of a list of allowed extensions, I'd use a set. Although in this example you surely won't be hitting performance issues, it's a matter of principle and habit

So I'd write this as:

extensions = set([".isf"])
if os.path.splitext(binaryfile)[-1].lower() not in extensions:
    raise ValueError("File type unknown.")

As for the rest, this seems pretty clean to me. I especially like the assert statements documenting your assumptions.


Best method to further execute the DRY principle and/or raise performance in my script? (client login/signup system)

This code appears to be fairly clean and reduced well to me, I don't see much in the way of any DRY violations, but if you're looking for any places for tightening up your code:

If you can use the newer javascript goodies, then use array destructuring assignment and object shorthand assignment

Given

function usp(parent) {
  return [parent.username.value, parent.password.value];
}

Then

const [user, pass] = usp(create);
database.push({ user, pass });

and use '==' with caution as it isn't strictly equal, it will attempt a type coercion, i.e. '5' == 5 is true, where as '===' won't, i.e. '5' === 5 is false. As a rule, you will almost always want to use '===', only reach for '==' when necessary.

Comparison operators

const [user, pass] = usp(log);
for (const x of database) {
  if (x.user === user && x.pass === pass) {
    ...
  }
}

Looping through any data structure has an O(n) complexity, there's nothing really you can do here, but this is completely fine as any increases in data size is a linear increase in processing.


Do you want unsigned int or do you want std::size_t?

unsigned int edit_distance(const vector<string> &s1, const vector<string> &s2)

It comes down to what you are trying to convey.
The use of string and vector suggests you are doing using namespace std; try not to do this. Prefer to qualify your types: std::string and std::vector.

Personally, I prefer const on the right. But it's only a preference thing.

Only declare one variable per line:

    const size_t len1 = s1.size(), len2 = s2.size();

Come up with better names. d is not very descriptive.

    vector<vector<unsigned int>> d(len1 + 1, vector<unsigned int>(len2 + 1));

I would prefer std::size_t here:

    for(unsigned int i = 1; i <= len1; ++i) d[i][0] = i;


Transforming elements of std containers from other std containers

Some things to note :

As you said there are std::min(m,n)/2; rings.
the ring R(r, p) has 2*(r+p-2) elements.
the top left of the ring has always coordinates (x,x). This is visible in your code :) j = ring_i; v_ring.push_back(mat[ring_i][j]);
Your code is using a relatively efficient amount of memory for the in-place transformation, and running in O(m*n) time, which is the best possible.
A performance improvement will be to use a single vector for the data in the matrix such that m(x,y) = m.data[x * cols + y]

Can we do it differently ?

Given the local coordinates system where (0, 0) is the top left of the ring

A coordinate (i,j), 0<=i<w, 0<=j<h, j == 0 || i == 0 on a side of a ring, can be moved by one position using the function

std::pair<int, int>
rotated_local_next(int i, int j, int w, int h)
{
   if(j == 0) //top , special case top-right
   {
        return i == w-1 ? std::make_pair(i, ++j) : std::make_pair(++i, j);
   }
   if(i == w-1) //right, special case bottom-right
   {
        return j == h-1 ? std::make_pair(--i, j) : std::make_pair(i, ++j);
   }
   if(j == h-1) //bottom, special case bottom-left
   {
        return i == 0 ? std::make_pair(i, --j) : std::make_pair(--i, j);
   }
   if(i == 0) //left, special case top-left
   {
        return j == 0 ? std::make_pair(++i, j): std::make_pair(i, --j);
   }

   // cannot happen
   throw std::exception{};
}

You can now implement in matrix coordinates

std::pair<int, int>
rotated_matrix_next(int x, int y, int ring_i, int height, int width )
{
     auto local_point = rotated_local_next(x-ring_i, y-ring_i, width-2*(ring_i), height-2*(ring_i));
     return std::make_pair(local_point.first + ring_i, local_point.second + ring_i);
}

All you need to do now is to implement iterators satisfying MoveAssignable and MoveConstructible. The beginning of your ring is the element at positing ring, ring, which is also the end of the ring.

struct RingView
{
    //ring start at 0
   RingView(std::vector<std::vector<int>>& mat, int ringnumber)
   : matrix(mat)
   , rows(mat.size())
   , cols(mat[0].size())
   , ring(ringnumber)
   {}

   std::vector<std::vector<int>>& matrix;
   int rows;
   int cols;
   int ring;

    class ring_iterator : public std::iterator<std::forward_iterator_tag, int>
    {
    public:

        ring_iterator(RingView* v = nullptr, int xpos = 0, int ypos = 0)
        : view(v)
        , x(xpos)
        , y(ypos)
        {}

        ring_iterator(const ring_iterator& other) = default;
        ring_iterator(ring_iterator&& other) = default;
        ring_iterator& operator =(ring_iterator const&) = default;
        ring_iterator& operator=(ring_iterator&&) = default;
        virtual ~ring_iterator() = default;

        RingView* view;
        int x;
        int y;

        // Forward
        ring_iterator& operator++() {
            auto posnext = rotated_matrix_next(x, y, view->ring, view->cols, view->rows);

            x = posnext.first;
            y = posnext.second;
            return *this;
        }

        ring_iterator operator++(int) {
            auto posnext = rotated_matrix_next(x, y, view->ring, view->cols, view->rows);
            ring_iterator next_iter = *this;
            next_iter.x = posnext.first;
            next_iter.y = posnext.second;
            return next_iter;
        }

        bool operator==(const ring_iterator& other) const {
            if(view == nullptr ){
                return other.view == nullptr;
            }
            return view->ring == other.view->ring && x == other.x && y == other.y;
        }

        bool operator!=(const ring_iterator& other) const {
            return !(*this == other);
        }

        // usually required
        int& operator*() {
            return view->matrix[x][y];
        }
        int* operator->() {
            return &(view->matrix[x][y]);
        }
    };

    ring_iterator begin()
    {
        return ring_iterator(this, ring, ring);
    }

    ring_iterator end()
    {
        return begin();
    }

    int size() const
    {
        return 2*(rows+cols -2) - 4 * ring;
    }
};

Now you can rotate the matrix using the view. To be able to rotate in both directions (positive for clockwise, negative counter-clockwise) we use

r' = (r % view.size() + view.size()) % view.size();

void rotate_mat (Matrix &mat, int r){
    auto n_rings = std::min(mat.size(),mat[0].size())/2; // Number of rings
    for(auto ring_i=0; ring_i<n_rings; ++ring_i){
        RingView view(mat,ring_i);
        int r_modulo = (r % view.size() + view.size()) % view.size();
        auto next_location = view.begin();
        std::advance(next_location, r_modulo);
        std::rotate(view.begin(),next_location,view.end());
    }
}

Full code : https://ideone.com/I3vg5v


num_to_alpha =\ is not Pythonic.  If a statement is “incomplete”, there is no need to add a trailing \ to indicate the line is continued.  An “incomplete” statement is one which contains unclosed {, [, or (, so this line could be written without the trailing \ simply by moving the { up to the previous line:

num_to_alpha = {
    1: 'one', ...

The if 0 < n < 21 or n == 100 or n == 1000: test could be written more simply as if n in num_to_alpha:.  This would also handle many other simple cases where the number exists in the num_to_alpha dictionary.

You compute mod = n % 10, and then go on to test if n % 10 != 0:.  You could simply test the already computed value if mod != 0:, or since non-zero values are Truthy, if mod:.

You are testing for values which cannot possibly be true due to early tests.  For instance, once a number is above 100, you test:

if n % 100 == 0:
    return ...

This is followed by:

if not n % 100 == 0 and ...:

If n % 100 evaluated to True, the first return statement would have been executed.  Testing not n % 100 == 0 doesn’t add any value.

At the end of the function, you explicitly check if n <= 0 or n > 1000: and return the empty string.  And if THAT test fails ... what happens?  None will be returned?  If the number passed any of the above tests, and explicit return statement would have already returned the desired string, so if the end of the function is reached, does it matter what the return value is?  Could you not unconditionally return ''.  Or better: raise ValueError()

DRY: Don’t Repeat Yourself

You code is repeating the same tests.  Is the number between 1 and 20?  Are the last 2 digits of a 3 digit number between 1 and 20?

If you structured your function in the following manner, you’d repeat yourself less, and find it easy to extend into ten thousands, hundred thousands, millions and beyond:

Start with an empty string
If n >= 1000

add num_to_alpha[n // 1000] and “thousand” to the string,
n = n % 1000

If n >= 100

add num_to_alpha[n // 100] and “hundred” to the string,
n = n % 100

If n > 0 and the string is not empty,

add “and” to the string

If n > 20,

add num_to_alpha[n // 10 * 10] to the string
n = n % 10

If n > 0

add num_to_alpha[n] to the string

Return the resulting string

Since you aren’t really using the returned strings, but eventually just counting the number of letters in the resulting string, you could optimize the function to not use strings at all.  Just store the number of letters of each number in the dictionary:

num_to_length = {
    1: 3, 2: 3, 3: 5, 4: 4, ...
}

and add 8, 7, and 3 instead of the strings “thousand”, “hundred” & “and”.


I didn't change much.
I think you're correct in having getters as well as methods such as 'canViewPage'.
The Methods 'canViewPage' and 'hasPermissions' are just wrappers around the 'UserGroup' class, the logic is in 'UserGroup'. It makes sense to create wrappers around 'UserGroup', for example if you want to have also Permission based solely on the User(Example a root user) then you would just have to change these Methods. If you had invoked the Methods directly on the 'UserGroup' - not over the 'User' - you would have to go over all these places. Pherhaps it would be Usefull to have a 'Permissions' class, wich would have a constructor or factory method, where you could give an 'User' as Argument.

<?php
/* The class for constructing any user's information
*/

class User {

    protected $userId, $email, $userGroup;

    protected function getEmail() {
        return $this->email;
    }

    protected function getUserId() {
        return $this->userId;
    }

    public function __construct($userId, $email, $emailGroup) {
        $this->userId = $userId;
        $this->email = $email;
        // You never use userGroup directly, you can just
        // put the object as membervariable, so you don't
        // have to instantiate the object twice
        $this->userGroup =  new UserGroup($emailGroup);
    }

    // Method for checking whether user can view a specific page
    public function canViewPage($pageId) {
        /*
        if(condition){
            return true;
        else
            return false;
        is equals
        return (bool) condition
        */
        return (bool) $this->userGroup->canViewPage($pageId);
    }

    // Method for checking permissions
    public function hasPermissions($alias) {
        /* alias is the name of the permissions. ie can-book
        * create usergroup object based on current user's usergroup */
        return (bool) $this->userGroup->hasPermissions($alias);
    }

}

class UserMapper {
    // database connection
    private $db;

    public function __construct(\PDO $db)
    {
        $this->db = $db;
    }

    public function findByUserId ($userId) {
        $userObject = new User();
        $q = $this->db->prepare("SELECT userId, email, userGroup FROM user WHERE userId = :userId");
        $q->bindValue(":userId", $id);
        $q->setFetchMode( PDO::FETCH_INTO, $userObject);
        $q->execute();
        $q->fetch(PDO::FETCH_INTO);
        return $userObject;

    }
}
?>

I don't understand your Second Questions, pherhaps you made some typos?
You have '$getUserGroup', but use '$getUserGroupMapper' and you give the method 'findByUserId' a UserGroup.

EDIT:
Now I understand. If you have a lot of UserGroups, I think it would be good. If you have just around 5 UserGroups, I thinks it would be too much

Your main program is good, for being an example.


Basic problems with input

Your code will blow up if there are fewer than two fractions in the input.  Even @janos's solution (which can cope with only one fraction) fails if there are no fractions in the input.  Is that reasonable, especially given that the sum of no numbers at all is 0?

Your code also fails on any badly formatted input but there's enough else to talk about to leave that for another day.

Style

apply method

It's common practice in Scala, with types like your Fraction, to add an apply method to dispense with the need for new.  It can be added directly to the class or in a companion object.

object Fraction {
  def apply(c: BigInt, d: BigInt) = new Fraction(c, d)
}

With the apply method added, Fraction(1,2) will return Fraction = 1 / 2 with no need for new.  It's a minor convenience, in the case of your simple class, but feels more natural.

Note: It would also be very useful to add an unapply method, for pattern matching.  Ask if you need details.

Implicit conversions

This is not necessary for the scope of your current, simple code but if you intend to do more with your Fraction, it may be useful to be able to add fractions and integers and get fractions as a result).  If you add one simple method to your class...

  def + (i: Int): Fraction = this + (new Fraction(i, 1))

then Fraction(1, 2) + 1 will return Fraction = 1 / 2.  However, 1 + Fraction(1, 2) will not work, because Int has no + method which takes a Fraction parameter.  This can be fixed by creating an Int-wrapping class which does have such a method and creating an implicit conversion which can turn an Int into such a class.  To make this magic optional rather than an unexpected surprise, put them into a companion object, thus:

object Fraction {
  def apply(c: BigInt, d: BigInt) = new Fraction(c, d)
  // Implicit classes added in Scala 2.10
  implicit class FractionalInt(i: Int) {
    def + (that: Fraction) = that + i
  }
}

Now anybody using your Fraction code can choose to do import Fraction._, after which 0 + Fraction(1,2) will return Fraction = 1 / 2

Pattern matching in explicit recursion

As Janos said, the best solution is a higher-order function but if you are going to do explicit recursion, pattern matching is often much more expressive and clean, as in

def sumFractions(fractions: Array[Fraction]): Fraction =
  fractions match {
    Array() => new Fraction(0, 1)
    Array(x) => x
    Array(x, y) => x + y
    Array(x, y, _*) => sumFractions((x + y) +: (fractions drop 2))
  }

Note that

This copes with 0 or 1 entries
I could have left the third match out and it would still work

This style is more expressive and less fragile than your imperative implementation.

Make functions generic

Later I'm going to argue that arrays are no benefit at all anywhere in your current code, but my point now is that sumFractions should not dictate that it be passed an array. janos's solution only really requires a Seq - and so does your explicitly recursive solution, as discussed elsewhere in this answer.

Janos's solution could be rewritten as

def sumFractions(fractions: Seq[Fraction]) : Fraction =
  fractions.reduceLeft(_ + _)

and nothing would break, because in Scala Array implements the Seq trait.  Any Seq-derived type will have reduceLeft, so there is no reason for this function to demand one.  That gives you much more freedom in the rest of your code.  If you decide to switch from arrays to sets or lists, this function does not then have to be rewritten.

Note: my pattern-matching variant on your explicitly recursive function can also be rewritten to be more generic.  Can add an example if you want.

sumFractions is redundant

Your class deals with a particular representation of rational numbers.  I've already mentioned that it might be useful (via implicits) to make them work with integers.  However, if you go further and do the work to make Fraction part of Scala's Numeric type class, then pretty much anything you can do with a sequence of Int (or Double or other numeric types) can be done with a sequence of Fraction.  If you do that work, you can simply replace sumFractions with fractions.sum.  Here's one way how

/* This could be placed inside the companion object
implicit object NumericFraction extends Numeric[Fraction] {
  def plus(x: Fraction, y: Fraction): Fraction = x + y
  /* Actually, there's a whole extra bunch of abstract
   * methods that you have to implement - see later
   */
}

Once this is done, assuming fractions is a sequence of Fractions (Seq[Fraction], List[Fraction], Array[Fraction] or whatever) then you can throw away sumFractions and simply use

fractions.sum

But there's more.  To actually make Fraction numeric, you have to implement the rest of the type class.  Here's an extended version of the companion object, which does just that, without adding any more methods to your original class:

object Fraction extends Numeric[Fraction] {
  def apply(c: BigInt, d: BigInt) = new Fraction(c, d)

  implicit object NumericFraction extends Numeric[Fraction] {
    // Required by scala.math.Numeric
    def fromInt(x: Int): Fraction = Fraction(x, 1)
    def minus(x: Fraction, y: Fraction): Fraction = x + negate(y)
    def negate(x: Fraction) = Fraction( - x.counter, x.denominator)
    def plus(x: Fraction, y: Fraction): Fraction = x + y
    def times(x: Fraction, y: Fraction): Fraction =
      Fraction(x.counter * y.counter, x.denominator * y.denominator)
    def toDouble(x: Fraction): Double =
      x.counter.toDouble / x.denominator.toDouble
    def toFloat(x: Fraction): Float =
      x.counter.toFloat / x.denominator.toFloat
    def toInt(x: Fraction): Int = (x.counter / x.denominator).toInt
    def toLong(x: Fraction): Long = (x.counter / x.denominator).toLong
    // Required by scala.math.Ordering
    def compare(x: Fraction, y: Fraction) =
      (x.counter * y.denominator) compare (y.counter * x.denominator)
  }
}

Once that is done, you get to do all this:

scala> val fractions = List(Fraction(1,2), Fraction(1,3), Fraction(1,4))
fractions: List[Fraction] = List(1 / 2, 1 / 3, 1 / 4)

scala> fractions.sum
res1: Fraction = 13 / 12

scala> fractions.product
res2: Fraction = 1 / 24

scala> fractions.min
res3: Fraction = 1 / 4

scala> fractions.max
res4: Fraction = 1 / 2

scala> fractions.sorted
res5: List[Fraction] = List(1 / 4, 1 / 3, 1 / 2)

I did this using a companion object, which is easier because it doesn't require modification of the original class. This is the conventional way in which type classes are used.  Although I have been able to implement all the Numeric abstract methods using only your + method, it would be useful to add native /, *, - methods to Factor and rewrite the implicit type class instance to call them.

The important point is that what I have shown you is really very little extra work and immediately gives you the use of many built in functions from the collections api.

Arrays are not appropriate here

Did you use arrays simply because you aren't very familiar with pattern matching but understand pulling elements from an array?  There really is almost no benefit at all to using arrays here.  Arrays only offer an advantage where random access is needed to a collection of fixed size.  Your use of the collections is entirely sequential

sumFractions

As covered above, sumFractions need specify nothing more than Seq[Fraction as input.  The reduceLeft solution will use the appropriate, optimised implementation of whichever sequence you pass in.  Even with explicit recursion (example provided on demand), the solution can be generalised to Seq without demanding by default all the copying required by Array.

Even if you choose to optimise the file input and parsing step with parallel collections, sumFractions need not know.

LinesArray not necessary

Any sequence (and other collections) can be mapped over.
As explained, sumFractions does not need an array.  Even if it did, you could convert to an array at the end of input processing.  Also, consider that some of the lines may be invalid.  You may choose either to halt at the first error or discard invalid lines; in either case, converting to an array first would be a waste of effort.

Parsing

Ah, now, split does offer a simple way to parse the input lines.  If you want to handle only perfectly formatted lines (not even permitting whitespace) and halt/crash on bad ones, it will do the job.  Although your current implementation actually does tolerate some possible bad lines.

Processing the input

Halting on the first error

Efficiency

You perform a series of maps.  Each one creates a complete new collection before the next is applied.  If the first line is poorly formatted and there are 20000 lines in the file, your first map will split all 20000 lines before crashing when it cannot parse that first line.  Worse, if the first line is "1/0", which is well formatted but not a valid Fraction, the code will split 20000 lines, then parse 20000 Array[String]s and only then halt on the first invalid input.

The solution is to start with lines.view.  A view is a lazy version of the collection.  If you apply a transformation (e.g map or filter), what you receive is not a transformed collection but a new view with all the original items, each of which will not be transformed until you access it.  If you apply a second transformation, you receive yet another view, still with the original items but now with with two transformations which will be applied in sequence (in other words, they have been composed into a new function) to each item as you access it.  And so on.

So if we change your code to

val fractions = lines.view splitLines parseInts makeFractions

(for simplicity, assume we have created 3 functions which implement your 3 transformations) then fractions will still be untransformed in reality, waiting to apply all 3 transformations to any item you ask for.  So if you then do

`sumFractions(fractions)` // A SeqView is still a Seq

or (if you've implemented the Numeric type class for Fraction)

fractions.sum

then it will start by applying all 3 transformations to the first line.  If that line is "3/0", the program will halt without touching the rest, saving a lot of time.

Catching more bad lines

Your code will tolerate "1/2/3" or "1/2/ gibberish" as input lines, converting them both to Fraction(1,2).  That is because it asks for the first two elements  This can be avoided with pattern matching and a partial function.  So the second, parseInts transformation could be rewritten with

map { case Array(x, y) => Array(x.toInt, y.toInt) }

or

map { case ar@Array(x, y) => ar map { _.toInt } }

Because this uses a partial function, if any input line does not split into an array of precisely 2 items then the program will throw a MatchError.

Pattern matching this way is expressive and succinct enough to combine the second and third transformations.  So we could replace both parseInts and makeFractions with

map { case Array(x, y) => new Fraction(x.toInt, y.toInt) }

Although this may give you concise code at the expense of flexibilty, particularly if you want to report meaningful errors (more later on that).

Regex rather than Split

Regexes offer at least three possible advantages

The option to tolerate whitespace in your input
Powerful pattern matching
Easier error reporting

val fractionLine = """(\d+)/(\d+)""".r

creates a pattern which is even more useful than split "/" because it only matches properly formatted lines with genuine numbers in them.  Optionally,

val fractionLine = """\s*(\d+)\s*/\s*(\d+)\s*""".r

accepts harmless whitespace.  The first transformation could be rewritten as

map { case fractionLine(x, y) => Array(x, y) }

the first two as

map { case fractionLine(x, y) => Array(x.toInt, y.toInt) }

or all three to

map { case fractionLine(x, y) => new Fraction(x.toInt, y.toInt) }

Again, combining these functions may be concise but may hinder debugging or error reporting.

Meaningful errors

A simple way to provide better error reporting is to turn the partial functions into complete functions, raising errors when no match is made.  So the regex version of the first transformation could become

map {
  case fractionLine(x, y) => Array(x, y)
  case s => throw new MyException("Invalid input line:'" + s + "'")
}

Similarly, the second transformation could throw an exception if the input doesn't match Array(x, y) and the third could complain if the divisor is 0.

Another way to add useful information to error reporting would be to add zipWithIndex as a new, first transformation so that the number of the line in the file is available.

Note that combining two or three of the transformations into one would make the error-handling pattern matching more complex and fragile, although not combining them would make it more complex to report the line number and line content if the failure was in the later transformations.

There are more functional ways to deal with errors but that's a more complex topic.


Find the common characters between two strings without using set operations

With your restrictions, yes, that seems fairly idiomatic.  I am not aware of a good bitset implementation yet -- wrapping java.util.BitSet wouldn't work that well, since a clojure version would want to be persistent.  That said, your restrictions are not idiomatic at all.  Presumably, you don't want to use clojure.set/intersection (and completely trivializing the problem), but something like

(defn find-matching-chars [s1 s2]
  (distinct (filter (into #{} s1) s2)))

really would be far more idiomatic.  I could see using something like your BitSet code if find-matching-chars was actually causing significant performance issues, but short of that, some form of collections manipulation really is the idiomatic way to solve this issue.

In all honesty, my probable course in a situation like this would be to build filter and linked lists from scratch if I couldn't use the built-in versions, but at this point, I am probably straying away from idiomatic code myself.


Validation of uploading images and adding records to the database

validate_file

I would get rid of your validate_file function. Generally, I'm a big supporter of creating as many functions as possible, as it makes code easier to read, reuse, and test.

But in this case, there are two problems: 1) It handles two somewhat different functionalities (does the file already exist, and was there an error on upload) and 2) It's named poorly (likely because of point 1)): It's not really clear what the function does, because "validate" is such a general term. If I read something like that, I would at a minimum also expect a file extension check, a mime type check, maybe a check for an acceptable file name, a check if it's really an image, etc.

File Check

It doesn't seem that you have any actual checks on the uploaded file, so it seems that a user could just upload eg a PHP file and gain code execution.

You should definitely check the file extension, and if you can move the uploaded file outside the web root, and perform some kind of check on the file itself.

Error Handling and Function signature

Throwing exceptions is fine, but I wouldn't return a string error message on failure (the "no value" return). It's difficult to handle (and it leaves you with the unnecessary if error check, and nesting which makes it a bit hard to follow when what is happening).

Your function signature also doesn't seem all that clear. add is quite generic (uploadImage would be better), and it doesn't accept arguments, but works on global variables directly (I would pass them on).

The return value is also quite unclear, and the function itself sometimes prints stuff, which makes it difficult to use. I would let the calling code show responses (if you must, the alternative would be to show all responses in this function, instead of sometimes returning a string).


I find it amusing that you have written _TWO_PI out to 89 digits of precision. The ratio of the circumference of the observable universe relative to the size of a hydrogen atom is just 40 digits, which means that you couldn't possibly need any more precision than that for any physical calculation.  In any case, you're quantizing it to a uint16_t, which gives you less precision than a float, so even long double is overkill.

You could use one of these suggestions for the value of π.  In any case, you should never use an identifier with a leading underscore — names with one underscore are reserved for standard libraries, two underscores for the compiler.


Move semantics:

The makeScopeGuard() function accepts the lambda by r-value ref; but passes a normal ref to the constructor of ScopeGuard.

template <typename Lambda>
ScopeGuard<Lambda> makeScopeGuard(Lambda&& func)
{
    return ScopeGuard<Lambda>(func);
}

You should either update ScopeGuard to take the function by r-value ref or change the makeScopeGuard() take a normal ref (to be consistent).

Personally I would pass the r-value ref through to the ScopeGuard.

template <typename Lambda>
ScopeGuard<Lambda> makeScopeGuard(Lambda&& func)
{
    return ScopeGuard<Lambda>(std::move(func)); // Need the move here
                                                // a named value is not an r-value ref.
}

Also need to update ScopeGuard

ScopeGuard(Lambda&& func)
    : committed_(false)               // Please one line per variable
                                      // Just like in normal code
                                      // were you declare one variable per line.
    , valid_(true)
    , rollbackFunc_(std::move(func))  // Need the move again.
{}

No Except

Normally the move operators are marked noexcept. Unless you have a good reason not to I would continue that norm.

ScopeGuard(ScopeGuard&& other) noexcept
ScopeGuard& operator=(ScopeGuard&& other) noexcept

Move by swapping.

The easiest way to move something is to swap it.

// Now we could implement this with a swap.
// But this seems trivial enough So this is fine.
ScopeGuard(ScopeGuard&& other) noexcept
    : committed_(other.committed_)        // One variable per line please.
    , valid_(other.valid_)
    , rollbackFunc_(other.rollbackFunc_)
{
    // Disabled the moved from.
    other.valid_ = false;
}

ScopeGuard& operator=(ScopeGuard&& other) noexcept
{
    // Here we are doing a copy (why not invoke the copy constructor)?
    // Followed by marking it `false`.
    committed_ = other.committed_;
    valid_ = other.valid_;
    rollbackFunc_ = other.rollbackFunc_;
    other.valid_ = false;
    return *this;
}

I would write like this:
I personally think it is easier to read like this.

ScopeGuard(ScopeGuard&& other) noexcept
    : committed_(false)
    , valid_(false)
    , rollbackFunc_([](){})
{
    swap(other);
}

ScopeGuard& operator=(ScopeGuard&& other) noexcept
{
    swap(other);
    other.valid_ = false;
    return *this;
}

void swap(ScopeGuard& other) noexcept
{
    using std::swap;
    swap(committed_,    other.committed_);
    swap(valid_,        other.valid_);
    swap(rollbackFunc_, other.rollbackFunc_);
}

Abuse of mutable

mutable bool committed_;

Not sure I like this. Is this because you have a const value and want to get around the constness of the object?

Mutable objects are meant to represent objects that are not part of the full state of the object. i.e. a cached or computed part of the state that can be re-calculated.

committed_ is very much part of the objects main state. So I would not mark it mutable.

That of course means you have to remove the const off the commit method.

void commit()       { committed_ = true; }
              ^^^^^ removed const

It is changing the state so its not really a const method.

Commit

There seems to be no way to call commit!!!

SCOPE_EXIT([f](){ baz(f); })

// how do I call commit on the above?
// I could use my editor to find the line number, but thats very fragile.
// And probably not what you intended to do.

bar(5); // It worked no exception
// So here I would expect to call commit.

If you can not call commit() then you should remove it from the class.

I would just get rid of the macors. Then your users can do:

auto guard = makeScopeGuard([](){revertStuff();}
// DO WORK HERE

// WORK DONE
guard.commit(); // no exceptions so we commit and don't need to revert.

An example working with correct move semantics fo the pedants:

#include <cstdio>
#include <cstdlib>
#include <memory>
#include <functional>
#include <iostream>

class ScopeGuard
{
public:
    ScopeGuard(std::function<void()>&& func)
        : committed_(false)
        , valid_(true)
        , rollbackFunc_(std::move(func))
    {}

    ~ScopeGuard() noexcept
    {
        if (valid_ && !committed_)
            rollbackFunc_();
    }

    ScopeGuard(const ScopeGuard&) = delete;
    ScopeGuard& operator=(const ScopeGuard&) = delete;

    ScopeGuard(ScopeGuard&& other) noexcept
        : committed_(false)
        , valid_(false)
    {
        swap(other);
    }

    ScopeGuard& operator=(ScopeGuard&& other) noexcept
    {
        swap(other);
        return *this;
    }

    void swap(ScopeGuard& other)
    {
        using std::swap;
        swap(committed_,    other.committed_);
        swap(valid_,        other.valid_);
        swap(rollbackFunc_, other.rollbackFunc_);
    }

    void commit() const { committed_ = true; }

private:
    mutable bool          committed_;
    bool                  valid_;
    std::function<void()> rollbackFunc_;␣
};

ScopeGuard makeScopeGuard(std::function<void()>&& func)
{
    return ScopeGuard(std::move(func));
}

#define MY_CONCATENATE_NX(A, B) A ## B
#define MY_CONCATENATE(A, B) MY_CONCATENATE_NX(A, B)

#define SCOPE_EXIT(f) auto MY_CONCATENATE(EXIT, __LINE__) = makeScopeGuard(f);

int foo(const char*) noexcept {std::cout << "food\n";return 0;}
bool bar(int) noexcept {std::cout << "bar\n";return true;}
void baz(int) noexcept {std::cout << "baz\n";}

int main() {
    int f = foo("/dev/random");
    if (!f)
    {
        return EXIT_FAILURE;
    }
    SCOPE_EXIT([f](){ baz(f); })
    int b = 1;
    bar(b);
    baz(f)
}


long both;

Using a long for storing a cast pointer can be both wasteful and too little. Just use the dedicated uintptr_t. Even if your implementation might not be fully up to C99 (MS greets), it probably has <stdint.h> and the typedef.

pStNode newNode = (StNode *) malloc(sizeof(StNode));

The above line demonstrates three bad ideas:

More pieces to keep track of means more complexity, which is bad. Thus hiding pointers behind typedefs is a bad idea, unless that pointer-type is never dereferenced, and is thus the one true type used.

Casting a void* is superfluous and error-prone.
See "Do I cast the result of malloc?
".

Don't use sizeof(TYPE) unless unavoidable. Getting it right even if the types aren't obscured is error-prone. Just use sizeof *pointer.

pStNode get(pStNode headNode, int index)

There is a type uniquely suited as an index: size_t. Alternatively, if you want something signed, you might be interested in ptrdiff_t. Though yes, if your use-case guarantees few enough nodes, int might work.

You really should encapsulate your list somehow. Currently, you are creating a one-off in main().
Also, cleanup should be possible without terminating the program.

If you use at least C99, main() has an implicit return 0;.


Construct binary tree from inorder and preorder traversal

Algorithm

When inorder and preorder both have a single element,
it must be the same value,
and the left and right parts in inorder are empty.
Therefore the special treatment for size(inorder) === 1 && size(preorder) === 1 is unnecessary,
you can simply drop that condition and the algorithm remains correct.

Performance

Although the implementation is elegant,
using building blocks common in functional programming,
slicing and dicing arrays is not very efficient in JavaScript.
The performance could be improved by using indexes of sub-array ranges.
It will be ugly, but fast.

Naming

l is the worst variable name ever.
Depending on your font,
it may be difficult to discern from 1 or |.
In this example, I would spell out left and right for the tree branches, naturally.


Naming
Java classes start with a capital letter and do not use underscores, so rock_paper should be RockPaper. Java uses camelCase, not snake_case, for all variable names except constants (static finals), so user_choice should be userChoice.
Spacing
The convention in java is to include whitespace before and after operators such as +, =, != or ==, so count_win=0 should be countWin = 0. Curly braces should be on the same line as an if or else.
Variable Declarations
You declare a new Random() inside your loop, so you might wind up making 19 Random objects, when you only need one. Declare it outside the loop. Conversely, you declare user_choice and computer_choice outside the loop, but they're only used inside. They should have the smallest possible scope.
Branching
You're branching (using if conditional statements) a lot to look up the name of a numeric selection. If you've learned about arrays, you could use a String[] of choices to simplify that lookup. There are a ton more branches to determine who wins. You only need one comparison to determine if there's a tie, and then only three specific checks to see if the user wins. Otherwise, the computer wins.
Making all those changes might look something like this:
import java.util.Random;
import java.util.Scanner;

public final class RockPaperScissors {

    private static final String[] CHOICES = { "rock", "paper", "scissors" };

    public static void main(final String[] argv) {
        final Random random = new Random();
        final Scanner keyboard = new Scanner(System.in);

        int computerWins = 0;
        int userWins = 0;

        System.out.println("\n Let us play Rock Paper Scissors \n");
        while (computerWins <= 10 && userWins <= 10) {

            /* Read user input and determine choice */
            System.out.println("\n Enter your choice 0 for rock, 1 for paper, or 2 for scissors \n");
            final int userChoice = keyboard.nextInt();
            if (userChoice < 0 || userChoice > 2) {
                System.out.println("Incorrect choice");
                continue;
            } else {
                System.out.println("\n Your choice was \n" + CHOICES[userChoice]);
            }

            /* Randomly generate computer input */
            final int computerChoice = random.nextInt(3) + 1;
            System.out.println("\n The computer choice was \n" + CHOICES[computerChoice]);

            if (userChoice == computerChoice) {
                System.out.println("Tie");
                continue;
            }

            if (userChoice == 0 && computerChoice == 1
                    || userChoice == 1 && computerChoice == 2
                    || userChoice == 2 && computerChoice == 0) {
                System.out.println("\nThe user wins!");
                userWins++;
            } else {
                System.out.println("\nThe computer wins!");
                computerWins++;
            }
        }
    }
}

Review Note: I intentionally don't close the Scanner because I'm assuming that hasn't been covered yet.


class Array
  def chunk(chunk_size)
    self.each_with_index.with_object(Array.new(size / chunk_size) { [] }) do |(elt, ind), result|
      result[ind / chunk_size] << elt
    end
  end
end

You reinvented Enumerable#each_slice! It returns an enumerator, which is fine for your code. Simply write ARGV.each_slice(2).map do |char, color| instead of ARGV.chunk(2).map.

ARGV.length % 2 == 1

Change to ARGV.length.odd?.

'Run with -h to see usage.'

Doesn't work.

colors = Hash[
    ARGV.each_slice(2).map do |char, color|
      color = ChunkyPNG::Color.from_hex(color)
      [char, color]
    end
]

I'd use to_h instead of Hash[] and inline color, to make the code shorter:

colors = ARGV.each_slice(2).map do |char, color|
  [char, ChunkyPNG::Color.from_hex(color)]
end.to_h

text << $_.chomp.chars until $stdin.gets.nil?

Instead of creating many arrays of characters, simply store the strings. Remove the call to .chars and iterate over a string using row.each_char.with_index. This makes the code a little faster.

raise ArgumentError, "No valid color provided for `#{char}`" if colors[char].nil?
image[x, y] = colors[char]

ChuckyPNG already throws an ArgumentError if the color is nil. You can remove your check for this, which may improve performance. (If you need to catch this error, you can wrap the loop with a begin-rescue block)


continue

Both your continue statements fall back to the end of the loop anyway, so they are redundant.

    user_number = input('\nNow pick a number card (2-9) ')

In the other place you correctly used raw_input. The difference is that input executes the given string as an expression, which is seldom what you want (and usually unsafe).

Nothing else really. The \ns at the start of all your strings are a bit ugly, and some people prefer using empty print statements to indicate extra empty lines.


Monkeypatching builtin open and File Mock-Up for unit testing

from io import StringIO

class MockFile(StringIO):
    """Wraps StringIO, because of python 2.6: clumsy name-property reset"""

    name = None #overwrite TextIOWrapper-property - part 1/2
    _vfs = {} #virtual File-System enables to "re-read" already written MockFiles

Storing files here causes them to be persistent between unit tests.

    def __init__(self, name, mode = 'r', buffer_ = None):
        self.name = name #overwrite TextIOWrapper-property - part 2/2
        if self._vfs.has_key(name):
            buffer_ = self._vfs[name]

I'd use buffer_ = self._vfs.get(name, buffer_)

        super(MockFile, self).__init__(unicode(buffer_))

What _buffer is None at this point? Won't that have strange effects?

        __enter__ = lambda self: self
        __exit__ = lambda self, exc_type, exc_value, traceback: None
        read = lambda self, size = None: super(Mockfile, self).read(size)

None of these lines of code do anything. They assign to local variables which are thrown away at the end of the function.

    def write(self, data):
        super(MockFile, self).write(data)
        self._vfs[self.name] = self.getvalue()

I wouldn't update self._vfs for every write. I'd put that in a close function. That way your tests fail if you forget to invoke close.

def replace_builtin(builtinname, replacementobj):
    import __builtin__
    builtin_func = getattr(__builtin__, builtinname)
    setattr(__builtin__, builtinname, replacementobj)

    def decorator_factory(func):
        def decorator(*args, **kwarg):
            return func(*args, **kwarg)

        #attach the original name and function to the decorator:
        decorator.replaced_builtin = (builtinname, builtin_func)
        return decorator
    return decorator_factory

I'm having real trouble figuring out how you would use this function.

UPDATE:

from io import StringIO

class MockFile(StringIO):
    """Wraps StringIO"""
    _vfs = {} #virtual File-System
    name = None #overwrite TextIOWrapper-property - part 1/2
    def __init__(self, name, mode = 'r', buffer_ = ''):
        self.name = name #overwrite TextIOWrapper-property - part 2/2
        if self._vfs.has_key(name):
            buffer_ = self._vfs.get(name, buffer_)

No need for the if. The second parameter to get is a default. Using get replaces checking for the key.

        super(MockFile, self).__init__(unicode(buffer_))

    def read(self, size = None):
        return super(MockFile, self).read(size)

    def write(self, data):
        super(MockFile, self).write(data)

These functions just call the superclass which happens anyways. So why include them?

    def close(self):
        self._vfs[self.name] = self.getvalue()
        super(MockFile, self).close()

def replace_builtin(builtinname, replacementobj):
    """makes it possible to mock the built-in functions like open.
    >>> @replace_builtin('open', MockFile)
    >>> def test_whatever(self, *args, **kwargs)
            with open(filename, 'r') as file:
                self.content = file_.read()
    """
    import __builtin__
    builtin_func = getattr(__builtin__, builtinname)

    def decorator_factory(func):
        def decorator(*args, **kwarg):
            setattr(__builtin__, builtinname, replacementobj)
            result = func(*args, **kwarg)

Bad things will happen if an exception is thrown by the function. I'd use a try/finally block here.

            setattr(__builtin__, builtinname, builtin_func)
            return result
        #attach the original name and function to the decorator:
        decorator.replaced_builtin = (builtinname, builtin_func)
        return decorator
    return decorator_factory


I might be a little bit late to the party, but better late than never, right?
Type signatures
Your central functions fromList and eval don't have type signatures. This forces the user to check Value and StepData's definition. Better add them:
eval :: Ord a => StepData a
eval = ...

fromList :: (Ord a, Monoid b) => [(a, a, b)]-> StepData a b
fromList  = ...

Remove dead code
merge isn't used in your code. It's dead code and not used in your instance at all. Better remove it.
Make sure the code compiles
That wasn't an issue back in 2013, but nowadays Semigroup is a superclass of Monoid, and you need to implement it too.
Don't encode Bool twice
eval's sol can be simplified a lot if we just use not around the condition:
eval (StepData xs) t = y
  where (_,_,y) = head $ dropWhile sol xs
        sol (a,b,_) = not (a <= Value t && Value t < b)

The function also gets easier to understand if we use filter instead, as we don't need to deal with double negation (drop and not):
eval (StepData xs) t = y
  where (_,_,y) = head $ filter sol xs
        sol (a,b,_) = a <= Value t && Value t < b

Document requirements of data
fromList needs a proper sorted list. That's not documented anywhere and neither enforced in its type nor its logic. We might end up with StepData [(Value 3, Value 1, Maybe 3)] or StepData [(Value 3, Value 4, Maybe 3),(Value 1, Value 2, Maybe 3)], as the list is only maped.
Instead, use foldMap and make sure that the values are ordered properly:
fromList = foldMap go
  where
    go (a, b, y)
      | a < b     = StepData [(Value a, Value b, y)]
      | otherwise = StepData [(Value b, Value a, y)]


Getting the outliers of both dates and values

Some notes:

I know many programmers like it, but this kind of perfectly aligned code looks pretty weird to me. Maybe my problem is that it's usually a sign that there is a repeated pattern that could be abstracted but has been prettified instead.
maxDate = []. Using imperative programming in JS/CS is very common, indeed, but I'd definitely take a functional approach when doing maths or logic (not that I know of any coding that does not deal with maths or logic ;-)).
(d) -> d[0]: Note that you can de-structure arrays: ([x, y]) -> x.
_.map maxDate, (d) -> d[0]. In my opinion list-comprehensions are more declarative than maps that use lambdas: (d[0] for d in maxDate).
Don't reuse variables: Those 4 accumulators hold two completely different structures in the course of the computation, that's not a good practice. Not even in imperative programming.

As I said, I'd write it in functional style, inmutable variables all the way through. It's a pity that CS has no real list-comprehensions and the results of nested loops must be flattened, but we'll have to live with it (_.flatten(xs, true) comes in handy as a one-level flattener). It would look something like this (you say you really need the modified series, so I'll use mash from my mixin):

nested_date_value_pairs =
  for key, pairs of series
    for [date, val] in pairs when val isnt null
      [date, if val is 0 then nearZero else val]
modified_series = _.mash(_.zip(_.keys(series), nested_date_value_pairs))
dates_values = _.zip(_.flatten(nested_date_value_pairs, true)...)
[[minDate, maxDate], [minVal, maxVal]] = ([_.min(xs), _.max(xs)] for xs in dates_values)


... for formatting a String into USD ...

A string is not the appropriate type to hold a monetary amount. What would your
extension method return if called on the string "abc" or "?" ? A price is a number
and should be stored as such. Possible choices are

An integer holding the price in units of the smallest denomination (e.g. cents), or
A Decimal which represents a base-10 number with up do 38 decimal digits.

Creating a textual representation of a number is the job for a
NumberFormatter.
It has options to specify the desired number of fractional digits, and even
has a dedicated .currency
style.

Using a number formatter has several advantages over “manually” formatting the price,
such as:

It chooses the appropriate style according to the user's locale.
It puts the currency symbol at the correct position.
It rounds the number to the correct number of decimal places.

Formatting a US dollar currency value is as simple as

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = "USD"

let usPrice: Decimal = 1234.56
let displayString = formatter.string(for: usPrice)!
print(displayString)

This produces the string $1,234.56 if the user's locale is "en_US".
On my device (with a german locale) it produces 1.234,56 $.


Looks pretty good to me. You are taking advantage of the standard library, are following the relevant style guides and you even have tests, good job!

Personally, I am more in favor of using import from, at least for well-known standard library functions and maybe for utility functions that are used everywhere throughout a project. This way you can more often fit the code on one line easily, making it more readable.

from itertools import islice
from collections import deque

One small improvement is that your initial slice can be one larger, the argument behaves just like a range or slice argument and is exclusive of the end (i.e islice(x, 4) takes the first four elements since it is analogous to x[0:4], x[:4] and range(0, 4)). However, this way you need to deal with the last element in a special way, so YMMV:

def sliding_window_iter(iterable, size):
    """..."""
    iterable = iter(iterable)
    window = deque(islice(iterable, size), maxlen=size)
    for item in iterable:
        yield tuple(window)
        window.append(item)
    if window:
        # needed because if iterable was already empty before the `for`,
        # then the window would be yielded twice.
        yield tuple(window)

This also reveals one behavior which you should at least be aware of (which seems to be the case, since you have a test for it). Arguable, sliding_window_iter([1, 2], 3) could yield (1, 2), i.e. the function maybe shouldn't swallow any data. In any case, the chosen behavior should be documented in the docstring.


If your data is strictly integer values, you can use user.x_count in range(...) to test whether or not the user.x_count value is a member of the range(...) set.  Ie)

def getUsers(user_array):
    group1 = sum(1 for user in user_array if user.x_count in range(1, 11))
    group2 = sum(1 for user in user_array if user.x_count in range(11, 51))
    # ... etc ...

This unfortunately will require several passes through your user_array data, so will not work if that data is ephemeral, such as iterator or generator based.

A more complex method will categorize the user.x_count value into a group value, and then increment the appropriate group counter.  bisect will find an insertion index in a sorted array, so we can leverage this to turn a user.x_count into a group based on its corresponding insertion index.  This will function properly if floating point values are encountered.

import bisect

def getUsers(user_array):
    thresholds = (0, 10, 50, 100, 200, 500, 1000)
    groups = [0] * (len(thresholds) + 1)

    for user in user_array:
        groups[bisect.bisect_left(thresholds, user.x_count)] += 1

    return groups[1:]

Notice there are no more group-specific variables, like group1.  Instead, all counters are created based on data, allowing you to add additional groups without modifying lines of code; you just modify data.


regarding:
if (!isdigit(*str) && !isspace(*str))

the isdigit() handles 0...9, so catches if any of the passed in char array is not numeric.
The && !isspace(*str))  has nothing to do with numeric values