Generic Doubly Linked-list implementation in C++

Identifiers that start with a double underscore, or a single underscore followed by a capital letter, are reserved for use by the implementation. Your use of __T could conflict with this use.
Spacing is important. The blank line between template <typename __T> and the following class List line makes it harder to recognize the class as a template class.
What is the purpose of the current member? It is unnecessary.
c_size should probably be std::size_t, not unsigned long long. Because it is a private typedef, users of your class cannot access the type and can only declare a variable to hold the returned value using auto.
You don't declare the copy constructor, copy assignment operator, move constructor, nor move assignment operators. This will cause problems with assignments of one List object to another.
insert_head and insert_back are very similar functions, but have been written somewhat differently. The implementation for insert_back can be made shorter by making it similar to insert_head. In particular, the assignment to new_node->prev can be done before the if (using new_node->prev = tail;, because when head is NULL, tail should also be), while the common tail = new_node; can be done after.
first, last, and size should also have the const modifier (e.g., constexpr c_size size() const.
remove_all will crash because you access current->next after delete current, nor do you delete the first (head) element.


Once you have the length of the integer portion, you can use the fx format specifier to get the correct number of decimals, which would clean up the string building part.

 return quantity.ToString("f" + (8 - length));

That should clean up the code some.

As I started typing that, I figured I'd check for edge cases too - since STR is filled with them (eg., it includes the negative sign in the length, returns ** if it overflows, etc.). You're handling the ** case, but a couple of edge-case values fail:

 Input       | Expected  | Actual
 999999999.5 | ********* | 1000000000
 123456789   | 123456789 | ArgOutOfRangeException
 123456789.5 | 123456790 | ArgOutOfRangeException
 -123456789  | ********* | ArgOutOfRangeException

I'd advise that if you're looking for 100% compatibility with STR here, you'll probably want some extensive unit tests.

Here's what I came up with that handles the edge-cases I threw at it, but I don't expect it's bullet proof either. Main changes are using the format specifier, and using .ToString to get the number of digits before the decimal place instead of Log10.

 public static string GetCustomStringQuantity(double quantity) {
    const int LENGTH = 9;
    // Include negative sign, just like STR()
    int numberOfIntDigits = Math.Round(quantity, MidpointRounding.AwayFromZero).ToString().Length;
    if (numberOfIntDigits == LENGTH) return quantity.ToString("f0");
    if (numberOfIntDigits > LENGTH) return new string('*', LENGTH);

    int numberOfDecimals = LENGTH - numberOfIntDigits - 1; // include 1 for the decimal place
    return quantity.ToString("f" + numberOfDecimals); // uses MidpointRounding.AwayFromZero
}


Associating a lock/mutex with the data it protects

I confess that I think your approach looks painful. As you can see from the other answers, it's insufficient to protect your data outside the container class. And there's confusion in your example code as to whether Protected is the container or ThreadSafeCache is the container. I think instead that you need to revisit the principle of encapsulation. When you have a collection that requires multi-threaded updates and access, you protect that collection with a wrapper class. The wrapper encapsulates the underlying collection in its entirety. Think "private". If you don't want to expose the lock, then you don't expose an iterator/enumerator. Rather, you do something similar to the List's ForEach method:

public void ForEach(Action<T> t){
   lock(_items) foreach(var item in _items) t.Invoke(item);
}


python: generate a 'diff' dictionary out of two nested dictionaries

To start I'd change the way that you find vd. Instead of looping through the dictionary and checking the keys are the same, just do a lookup of the key.
This may raise a KeyError, and so you'll want to put a guard in for that.

However the rest of your code needs to change.
First if we have a look at your for i in vi1 loop.
You have the comment Check if lists contains only None, but you're making that list?
Don't do this. Ever.
And so I would move the if and else out of that loop:

for i in vi1:
    if i not in vd1:
        ls_uninst.append(i.split()[0])
    elif i in vd1:
        ls_uninst.append(None)

if all(x is None for x in ls_uninst):
    answer[ki] = {}
    answer[ki]['to_uninstall'] = [None]
else:
    ls_final = [x for x in ls_uninst if x is not None]
    answer[ki] = {}
    answer[ki]['to_uninstall'] = ls_final

From this we can see that the for loop should probably be a comprehension, and I'm saying this now [None] is horrible, so I'm removing that from here.
Which would result in:

ls_uninst = [i.split()[0] for i in vi1 if i not in vd1]

After this, you should be able to see that if not vi1 is true not ls_uninst is true too, and so you can merge these ifs.
Resulting in something like:

for kd1, vd1 in vd.iteritems():
    ls_uninst = [i.split()[0] for i in vi1 if i not in vd1]
    answer[ki] = {}
    if ls_uninst:
        answer[ki]['to_uninstall'] = ls_uninst
    else:
        answer[ki]['to_uninstall'] = [None]

The if can then become either a ternary, or you can use or. I think or is quite nice here.
But to be honest, you should just remove this if.

You should now have something that looks like:

def diff(installed, deploy):
    answer = {}
    for ki, vi in installed.iteritems():
        try:
            vd = deploy[ki]
        except KeyError:
            continue
        for ki1, vi1 in vi.iteritems():
            for kd1, vd1 in vd.iteritems():
                ls_uninst = [i.split()[0] for i in vi1 if i not in vd1]
                answer[ki] = {}
                answer[ki]['to_uninstall'] = ls_uninst or [None]
    return answer

This only uses the last vi1 and vd1 to create this list.
So you should use itervalues instead.
Also I'd use all of the values, not just the last.
This can be done by flattening vi.itervalues,
I'd do this by using itertools.chain.from_iterable, but ultimately it's up to you.
I'd also change vd1 to a set.
And all of this results in:

from itertools import chain
flatten = chain.from_iterable

def diff(installed, deploy):
    answer = {}
    for ki, vi in installed.iteritems():
        try:
            vd = deploy[ki]
        except KeyError:
            continue
        vi1 = flatten(vi.itervalues())
        vd1 = set(flatten(vd.itervalues()))
        ls_uninst = [i.split()[0] for i in vi1 if i not in vd1]
        answer[ki] = {}
        answer[ki]['to_uninstall'] = ls_uninst or [None]
    return answer


Consider your system in three parts:

Core OS (all files on ec2)
Your App (I would keep the core app files on ec2 - reasons below - but your way would work)
Data (I would have only "data" on EFS)

Answer Part 1: php.ini lives with the OS.
Reasons:

Major: If you want to upgrade to a newer PHP without downtime, you create new EC2s with new OS one at at time and swap them in to your ELB: this can't use the shared php.ini as you propose.
Medium: Changes to php.ini won't bite instantly you may need to start http/fcgi to get traction - you still need to visit each server to restart.

Answer Part 2: The actual application files also live on ec2, and only data on EFS.
Reasons:

Major: Similar to above, you can update one at a time by swapping servers with new code in.
Medium: Security; it's safer to create the application instances and "lock in" the files, than rely on files on EFS that may have been connected to another EC2 by mistake.
Medium: Testing: you can attach your EC2s to a different data store / different ELB for testing before connecting to live.
Medium: If your EFS fails (it happens!) your application can still respond and say "Sorry - please come back later".
Medium: You want to have the EC2 in different AZs so much faster
Minor: Slightly faster if they all share the same AZ.
Downside: Updating the application is a bigger pain, but you can script this too.

How:
The great news is that you already have this scripted. Split your deploy into slightly smaller stages:
a) Create your BaseAMI (includes the OS, PHP as you have scripted above). This only changes when you do a major OS update.
b) Using your BaseAMI, you can then create a GoldenAMI which has your application on top. (Run minor OS updates at this point to maintain security if your Base AMI is older). This Golden AMI will be near identical for all EC2s
c) Using Auto-Scale Groups (ASG), use GoldenAMI as your base, and tweak if needed using userdata properties of the ASG.
When you release new code, you launch stage (b) and create new GoldenAMI and use that for the ASG. Kill the old servers and the new ones magically appear = no downtime.
If you really need to update php.ini (which will be rare), then start again at stage (a) to build the BaseAMI, then Golden AMI and swap servers in one at at time.
To "cheat" (shortcut) when updating, deploy your application code to S3, have each EC2 check S3 (or notified via SNS when updates happen) and it can pull down the code and self update. But ensure your security is rock-solid tight if you do this (as you would if putting the application code on EFS).

Regarding MySql,

you can't share like that at all as files need to be exclusively opened;
having data live on a single disk is not "HA";
having data live on EFS is slow.

Use the RDS solutions provided by AWS and you can add redundancy to your heart's content (multiple AZs, failovers, backups). It may cost a bit more, but HA will.


Validation of a couple of model classes using FluentValidator

I see two possibilities here.

1. Use extension methods

You can define a static class BranchModelValidationRules with extension methods for AbstractValidator<T> with methods like this:

public static void ValidateBranchName<T>(this AbstractValidator<T> validator)
    where T : BranchAddModel
{
    validator.RuleFor(x => x.BranchName)
        .NotEmpty()
        .Length(0, 128);
}

2. Extract a common base class

Create a class BranchModelValidatorBase:

public abstract class BranchModelValidatorBase<T> : AbstractValidator<T>
    where T : BranchAddModel
{
    public BranchModelValidatorBase()
    {
        RuleFor(x => x.BranchName)
            .NotEmpty()
            .Length(0, 128);  //up to 128 length of string is allowed.

        RuleFor(x => x.ServiceTypeId)
            .NotEmpty();  //mandatory

        RuleFor(x => x.TimezoneId)
            .NotEmpty();  //mandatory
    }
}

Create concrete validators by extending the base class:

public class BranchAddModelValidator
    : BranchModelValidatorBase<BranchAddModel>
{
    public BranchAddModelValidator()
    {
        // Create future add-specific rules here.
    }
}

public class BranchEditModelValidator
    : BranchModelValidatorBase<BranchEditModel>
{
    public BranchEditModelValidator()
    {
        RuleFor(x => x.BranchId)
            .NotEmpty();

        RuleFor(x => x.IsActive)
            .NotEmpty();
    }
}

Update

Regarding your comment about a more generic Name property: define an interface, for example like this:

public interface IModelWithName
{
    string Name { get; set; }
}

A matching extension method class might then look like this:

public static class ModelValidationRules
{
    public static void ValidateModelName<T>(this AbstractValidator<T> validator)
        where T : IModelWithName
    {
        validator.RuleFor(x => x.Name)
            .NotEmpty()
            .Length(0, 128);
    }
}

You can then reuse this method in any validator class that validates models implementing the interface. Alternatively you could create a validator for IModelWithName with just a single rule. Then use a matching set of validators for actual model validation.


Consuming an ASP.NET Web API call in an MVC controller

Testing?

Then create a simple unit test and test your API controller or your business layer classes directly.
If you want to create an integration test or need a cleaner solution in production code read further.

Wrapping the API calls

This is just a disposable wrapper around the WebClient which can be easily reused.

public abstract class WebClientWrapperBase : IDisposable
{
    private readonly string _baseUrl;
    private Lazy<WebClient> _lazyClient;

    protected WebClientWrapperBase(string baseUrl)
    {
        _baseUrl = baseUrl.Trim('/');
        _lazyClient = new Lazy<WebClient>(() => new WebClient());
    }

    protected WebClient Client()
    {
        if (_lazyClient == null)
        {
            throw new ObjectDisposedException("WebClient has been disposed");
        }

        return _lazyClient.Value;
    }

    protected T Execute<T>(string urlSegment)
    {
        return JsonConvert.DeserializeObject<T>(Client().DownloadString(_baseUrl + '/' + urlSegment.TrimStart('/')));
    }

    ~WebClientWrapperBase()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(false);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_lazyClient != null)
        {
            if (disposing)
            {
                if (_lazyClient.IsValueCreated)
                {
                    _lazyClient.Value.Dispose();
                    _lazyClient = null;
                }
            }

            // There are no unmanaged resources to release, but
            // if we add them, they need to be released here.
        }
    }
}

Creating a "strongly typed proxy":

class StudentDashboardClient : WebClientWrapperBase
{
    public StudentDashboardClient()
        : base("http://localhost/webapi/api/StudentDashboard/")
    {
        //just for compatibility
    }

    public StudentDashboardClient(string baseUrl)
        : base(baseUrl)
    {
    }

    public User GetUserRecord(string userName)
    {
        return Execute<User>("GetUserRecord?userName=" + userName);
    }
}

And then passing to your controllers where it's needed:

public class HomeController : Controller
{
    private readonly StudentDashboardClient _studentDashboardClient;

    public HomeController(StudentDashboardClient studentDashboardClient)
    {
        _studentDashboardClient = studentDashboardClient;
    }

    public ActionResult Index()
    {
        return View(_studentDashboardClient.GetUserRecord("jBob"));
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _studentDashboardClient.Dispose();
        }
        base.Dispose(disposing);
    }
}

Note that the controller now have a parameterless constructor so you will need a solution to instantiate controllers this way for example a DI framework with MVC support like Ninject.

What you gain? Cleaner code.


Rather than system() you should popen().
The difference is that system runs the command in a sub process with no access to this processes, while popen runs the command in a sub processes but provides accesses to the input and output streams of the sub processes.
This will allow you to run the sub-processes and stream input to the processes directly (from the input field you provided for standard input) and then read output from the processes and write it to the output field in your user interface.
FILE*  proc = popen(command);
std::string inputFromUser = getUserInputFromUI();
// Using fwrite() correctly left to user.
// You need to check for errors and continue etc.
fwrite(inputFromUser.c_str(), 1, inputFromUser.size(), proc);

char  buffer[100];
std::size_t size;
while((size = fread(buffer, 1, 100, proc)) != 0) {
    // Check for read errors here.
    sendToUserInterface(std::string(bufffer, buffer + size));
}

pclose(proc);

Sorted of related you don't need to save your pythong script as a file. The python command accept the - as a name which means read the script from the standard input rather than from the named file.
So you can run the python command (with popen()) then write the script you want to execute to the input stream of the file produced.
This will remove the need for any intermediate files.


Python, numpy, optimize module to handle big file

1. The MemoryError

I can't reproduce the MemoryError. Here's the test I ran:

def make_test(n=10**7, output_file='targets.csv'):
    with open(output_file, 'w') as f:
        for _ in range(n):
            f.write('56.08401,55.19490,25.49292\n')

>>> make_test()
>>> import os
>>> os.stat('targets.csv').st_size
270000000

That's 270 megabytes of data, and it loads fine for me:

>>> import csv, numpy as np
>>> targets = np.array([(float(X), float(Y), float(Z)) for X, Y, Z in csv.reader(open('targets.csv'))])
>>> targets.shape
(10000000, 3)

So I don't really know what is going wrong for you. Can you provide the exact text of the error message and its traceback? There might be more information there.

Regardless of the cause of the MemoryError, Janne is right to suggest that using numpy.loadtxt to get the data directly from the file (with no intermediate Python list) would be better:

targets = np.loadtxt('targets.csv', delimiter=',')

However, numpy.loadtxt is still quite slow, and if this is a bottleneck for you then you should investigate pandas:

>>> from timeit import timeit
>>> timeit(lambda:np.loadtxt('targets.csv', delimiter=','), number=1)
18.912313379812986
>>> import pandas
>>> timeit(lambda:pandas.read_csv('targets.csv', delimiter=',').values, number=1)
0.5977518488653004

2. Other comments on your code

The PPM format specification says that width is given before height, but you have:

ppm.write("P3" + "\n" +  str(height) + " " + str(width) +"\n" + "255" + "\n")

Is that right? Do you really intend to transpose your image?
It's conventional to place a comment before the code that it describes. So instead of:

ppm.write("P3" + "\n" +  str(height) + " " + str(width) +"\n" + "255" + "\n")
# write PPM file header

most Python programmers would write it like this:

# Write PPM file header: see <http://netpbm.sourceforge.net/doc/ppm.html>
ppm.write("P3\n{} {}\n255\n".format(width, height))

You haven't managed to vectorize all your code. Everything up to the computation of bcoords is vectorized and will run fast, but then you have a loop over the data where you pick a random vertex corresponding to each target. This loop runs in slow Python code and so is going to be the bottleneck in your application.

See §3 below for how this part of the code can be vectorized, using
numpy.cumsum to find the cumulative sums of the barycentric coordinates, numpy.random.uniform to generate random samples for each target, and numpy.argmax to pick the vertex.
Similarly, writing the output colours to the PPM would be faster if you used numpy.savetxt to write them all at once (instead of one at a time as at present).
You compute all four barycentric coordinates for each target using the recipe from scipy.spatial.Delaunay:

bcoords = np.c_[b, 1 - b.sum(axis=1)]

but in fact you don't need the fourth coordinate since you are only going to use the cumulative sums of these coordinates, and the fourth cumulative sum is always 1.
The format of colorlist.csv is quite inconvenient, with a mixture of two types of data (colours and vertices) using a mixture of spaces and commas as delimiters:

255 63 127,35.5344302104,21.380721966,20.3661095969

Where does this file come from? If it's under your control, could you generate it in a more convenient format, for example as one file containing colours and another containing vertices? Or if you have to generate it as a single file, then could you consistently use either spaces or commas as delimiters?
Where do the targets come from? Your code implies that you have exactly one target for each pixel of the image MAP.tif, so is it the case that the targets are generated by processing this image in some way? If so, shouldn't you just generate the targets directly from MAP.tif instead of via the intermediate targets.csv?

3. Revised code

Here's the dithering algorithm, fully vectorized:

import numpy as np
import scipy.spatial

WHITE = np.array([[255, 255, 255]], dtype=np.uint8)

def dither_colors(vertices, colors, targets, default_color=WHITE):
    """Randomly dither targets onto vertices and return array of
    corresponding colors.

    Input:
    vertices:      Points in 3-space. shape=(N,3), dtype=float
    color:         RGB colors for each point. shape=(N,3), dtype=uint8
    targets:       Points in 3-space. shape=(M,3), dtype=float
    default_color: RGB color for targets not found in convex hull of
                   vertices. shape=(1,3), dtype=uint8

    Output:
    Array of colors. shape=(M,3), dtype=uint8

    Works by triangulating vertices, getting a complex of tetrahedra.
    For each target, randomly pick one of the vertices of the
    tetrahedron it is found in (weighted according to how close the
    target is to that vertex), and assign the color of that vertex to
    the target. Targets that are not found in any tetrahedron get
    assigned default_color.

    """
    N = len(vertices)
    assert vertices.shape == (N, 3)
    assert colors.shape == (N, 3)
    M = len(targets)
    assert targets.shape == (M, 3)
    assert default_color.shape == (1, 3)

    # Compute Delaunay triangulation of vertices.
    triangulation = scipy.spatial.Delaunay(vertices, furthest_site=False)

    # Find the tetrahedron containing each target (or -1 if not found)
    tetrahedra = triangulation.find_simplex(targets)

    # Affine transformation for tetrahedron containing each target
    U = triangulation.transform[tetrahedra, :3]

    # Offset of each target from the origin of its containing tetrahedron
    V = targets - triangulation.transform[tetrahedra, 3]

    # First three barycentric coordinates of each target in its tetrahedron.
    # The fourth coordinate would be 1 - b.sum(axis=1), but we don't need it.
    B = np.einsum('ijk,ik->ij', U, V)

    # Cumulative sum of barycentric coordinates of each target.
    Bsum = np.c_[B.cumsum(axis=1), np.ones(M)]

    # A uniform random number in [0, 1] for each target.
    R = np.random.uniform(0, 1, size=(M, 1))

    # Randomly choose one of the tetrahedron vertices for each target,
    # weighted according to its barycentric coordinates
    W = np.argmax(R <= Bsum, axis=1)

    # Get the color corresponding to each vertex just chosen.
    C = colors[triangulation.simplices[tetrahedra, W]]

    # Mask out the targets where we failed to find a tetrahedron.
    C[tetrahedra == -1] = default_color

    assert C.shape == (M, 3)
    return C

And here's a function that handles the input and output:

def dither_image(width, height,
                 vertices_file='colorlist.csv',
                 targets_file='targets.csv',
                 output_file='output.ppm'):
    """Read colors and vertices from vertices_file. Read targets from
    targets_file. Dither each target to a randomly chosen nearby
    vertex; output the colors for the dithered vertices to output_file
    as a PPM with the given width and height.

    """
    vertices = np.loadtxt(vertices_file, usecols=(1, 2, 3), delimiter=',')
    colors = np.loadtxt(vertices_file, usecols=(0,), delimiter=',',
                        converters={0:lambda s:s.split()}, dtype=np.uint8)
    targets = np.loadtxt(targets_file, delimiter=',')

    C = dither_colors(vertices, colors, targets)

    # Write output as image in PPM format.
    # See <http://netpbm.sourceforge.net/doc/ppm.html>
    with open(output_file, 'wb') as ppm:
        ppm.write("P3\n{} {}\n255\n".format(width, height).encode('ascii'))
        np.savetxt(ppm, C, fmt='%d')

4. Emacs bug

In the course of preparing this answer, I discovered a bug in the way Emacs handles PPM images on OS X, which I reported as bug #16683.


Security and efficiency for profile picture upload

what happens if I upload a .exe file? or even a .txt file? Your application will give errors. Always have a fallback for if some hack0r uploads a non-picture to your application. Use the default: statement in your switch cases for that and hand back an error when they try to upload a non-image or a image you don't support (e.g. svg).

You talk about security and number of files in one directory, why is there a correlation between these two? The only restriction you have on the number of files per directory depends on the Filestructure format.

I would however create a directory per user instead of storing all the images in the same directory.


I see a minor issues with the code: you are locking every time, no matter if it's needed on not. I would implemented GetFromCache like this

public T GetFromCache<T>(string key, object cacheLock, Func<T> defaultValuePredicate, TimeSpan duration)
{
    object result = _cache[key]; // using object as T may be value type and _cache may return null

    if (result == null || !(result is T))
    {
        lock (cacheLock)
        {
            result = _cache[key];  // rechecking value from cache as another thread may already initialize it
            if (result == null || !(result is T))
            {
                result = defaultValuePredicate();
                if (!Equals(default(T), result))
                {
                    _cache.Add(key, result, null,
                            DateTime.Now.Add(duration),
                            System.Web.Caching.Cache.NoSlidingExpiration,
                            System.Web.Caching.CacheItemPriority.Default,
                            (cacheKey, value, reason) =>
                            Debug.WriteLine(string.Format("{0} Dropped from cache becasue {1}", cacheKey, reason)));
                }
            }
        }
    }

    return (T)result;
}

It's a little more code (+1 if statement) but it doesn't lock thread every time you access it.


Extract name, address and phone number from some web pages using multiprocessing

Proper use of a Pool p should include p.close() and p.join() (in this order).

Cases of the websites not responding should be handled. Requests should have a timeout, the timeout exception is caught, and non-200 should be handled as well.

Other than that, the script is correct for a one time extract of a few pages, but will need to be extended if you intend to produce a high volume daemon. If that is the case, usage of Pool can be questionnable and has multiple alternatives, such as using Scrapy framework scheduler or using a celery broker for high-level handling of workers (this will avoid your workers to crash entirely on exceptions, among a few other benefits).


If/else that contains HTML blocks, which contain additional PHP functions

A few suggestions.

Instead of writing styles in same file use an external style sheet
Also you can restructure it like:

 <!doctype html>

 <title>test</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

 <?php
     if ($_SERVER['REQUEST_METHOD'] !== 'POST')
     {
 ?>

You didn't come here through a Post.

<?php
     }
     else
     {
         if(isset($_POST['a']))
         {
            $status = "HTML-blocks that contain PHP such as ";
            switch ($_POST['a'])
            {
                case "1":
                  $status .= "word1";
                break;
                case "2":
                  $status .= "word2";
                break;
                default:
                  $status .= "other";
            }
        }

        if(isset($_POST['b']))
        {
            $status .= "and ";
            switch ($_POST['b'])
            {
                case "1":
                  $status .= "word3";
                break;
                case "2":
                  $status .= "word4";
                break;
                default:
                  $status .= "other";
            }
        }
        echo $status;
 ?>

 <?php
    }
 ?>


Sum over selected numpy.ndarray column and write to a file

I will assume that all of the ?_? lists are empty when you start.  Here are my suggestions:

Rather than using lists, I would just make the ?_? variables numpy arrays.  You can slice the values you want from dos2 using syntax like s_u = dos2[:int(ldata[2]), [3,5,7]].
Your indexing is really slices with a step size of two.  So [3, 5, 7] is 3:9:2, [4,6,8] is 4:10:2, [9,11,13,15,17] is 9:19:2, and [10,12,14,16,18] is 10:20:2.  Numpy is much faster with these sorts of slices rather than using the direct indexing you are using since with these slices numpy can avoid making a copy.
Since everything is done in steps of 2, I think it would make it even easier to first reshape dos2 to a 3D array, where the last dimension determines whether it is a ?_u or ?_d variables.  Then you can use unpacking to put the columns in the right place.
You can use np.column_stack to combine all of your 1D arrays into one big 2D array.  This can then be written in one step using np.savetxt.
Better yet, you can use a slice for the last index of atom to end up with all 2D arrays, then just hstack them to get one big array.  This avoids having to unpack at all.
I prefer the arr.sum() syntax of np.sum(arr) since I think it makes the flow easier to follow for people who read left-to-right.

So here is how I would implement what you are doing (with comments and dummy data):

# Dummy test data
dos2 = np.random.random((1000, 19))
atom = np.random.random((2, 1000, 2))
ldata = [None, None, '100', '1.1']

# We re-use this value several times, so put it in a variable
maxind = int(ldata[2])

# Extract the part of dos2 we want, and reshape it so the last index
# determines whether it is a ?_u (index==0) or ?_d (index==1) value
dos2_r = dos2[:maxind, 1:19].reshape(-1, 9, 2)

# Extract the part of atom we want
# We use slicing instead of indexing for the last index to keep it 2D
atom_p = atom[0,:maxind,:1]-float(ldata[3])

# Slice out the parts of dos2 we want
s_ud = dos2_r[:, 0, :]
p_ud = dos2_r[:, 1:4, :].sum(axis=1)
d_ud = dos2_r[:, 4:, :].sum(axis=1)

# Combine the arrays into one big array
cols = np.hstack([atom_p, s_ud, p_ud, d_ud])

# Write to a file
np.savetxt('dos.dat', cols, delimiter=' ')

Edit:

OP asked my to explain how the slicing is working.  I think the easiest way to explain is to walk through a toy example.  Lets start with a 2D array. That I think makes it easy to follow what is going on:

>>> dos2 = np.vstack([np.arange(12)+100*i for i in range(20)]).T
>>> print(dos2)
[[   0  100  200  300  400  500  600  700  800  900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900]
 [   1  101  201  301  401  501  601  701  801  901 1001 1101 1201 1301 1401 1501 1601 1701 1801 1901]
 [   2  102  202  302  402  502  602  702  802  902 1002 1102 1202 1302 1402 1502 1602 1702 1802 1902]
 [   3  103  203  303  403  503  603  703  803  903 1003 1103 1203 1303 1403 1503 1603 1703 1803 1903]
 [   4  104  204  304  404  504  604  704  804  904 1004 1104 1204 1304 1404 1504 1604 1704 1804 1904]
 [   5  105  205  305  405  505  605  705  805  905 1005 1105 1205 1305 1405 1505 1605 1705 1805 1905]
 [   6  106  206  306  406  506  606  706  806  906 1006 1106 1206 1306 1406 1506 1606 1706 1806 1906]
 [   7  107  207  307  407  507  607  707  807  907 1007 1107 1207 1307 1407 1507 1607 1707 1807 1907]
 [   8  108  208  308  408  508  608  708  808  908 1008 1108 1208 1308 1408 1508 1608 1708 1808 1908]
 [   9  109  209  309  409  509  609  709  809  909 1009 1109 1209 1309 1409 1509 1609 1709 1809 1909]
 [  10  110  210  310  410  510  610  710  810  910 1010 1110 1210 1310 1410 1510 1610 1710 1810 1910]
 [  11  111  211  311  411  511  611  711  811  911 1011 1111 1211 1311 1411 1511 1611 1711 1811 1911]]

This has 12 values in the first dimension and 20 in the second, so it has some extra data rows and columns.  I chose this particular array since, as you can see, for value xyy or xxyy, the x or xx value is the column number and the yy value is the row number.  This makes it easy to keep track of what the manipulations are doing.

Let's make maxind = 10 for simplicity.  So the first thing I do is slice out the data you don't want.  You never use the first column, and you never use past the 18th column.  Also, you never use past maxind rows.  So I throw out everything besides that.  I will call the result dos2_p.  Note that with slicing, for arr[0:n] the 0 is implied so it can be written as arr[:n], and for arr[n:len(arr)] the len(arr) is implied so it can be written as arr[n:].  arr[:] means "everthing", and arr[:, n] means "everything from dimension 0 and the nth index of dimension 1".  arr[..., n] means "the nth index of the last dimension and everything from the rest of the dimensions, however many that might be"

>>> maxind = 10
>>> dos2_p = dos2[:maxind, 1:19]
>>> print(dos2_p)
[[ 100  200  300  400  500  600  700  800  900 1000 1100 1200 1300 1400 1500 1600 1700 1800]
 [ 101  201  301  401  501  601  701  801  901 1001 1101 1201 1301 1401 1501 1601 1701 1801]
 [ 102  202  302  402  502  602  702  802  902 1002 1102 1202 1302 1402 1502 1602 1702 1802]
 [ 103  203  303  403  503  603  703  803  903 1003 1103 1203 1303 1403 1503 1603 1703 1803]
 [ 104  204  304  404  504  604  704  804  904 1004 1104 1204 1304 1404 1504 1604 1704 1804]
 [ 105  205  305  405  505  605  705  805  905 1005 1105 1205 1305 1405 1505 1605 1705 1805]
 [ 106  206  306  406  506  606  706  806  906 1006 1106 1206 1306 1406 1506 1606 1706 1806]
 [ 107  207  307  407  507  607  707  807  907 1007 1107 1207 1307 1407 1507 1607 1707 1807]
 [ 108  208  308  408  508  608  708  808  908 1008 1108 1208 1308 1408 1508 1608 1708 1808]
 [ 109  209  309  409  509  609  709  809  909 1009 1109 1209 1309 1409 1509 1609 1709 1809]]

As you can see, each rows start with the 1?? value and end with the 18?? value, which means it starts with columns 1 and ends with column 18, and the maximum ?yy value is 09, which means it ends with row 9.

Now I want to make it so the even rows are in one dimension, and the odd rows are in another.  I can do that with reshape.  It can take some trial-and-error to get the reshape to work the way you want.  I don't actually have a good conceptual way to do this, I just create a dummy example like this and try different things until I get the layout I want.  In this case, we want to set the last dimension to have a shape of 2, the first to have the same shape as currently (maxind), and we can let numpy figure out the second dimension (although we know it should be 9).

>>> dos2_r = dos2_p.reshape(maxind, -1, 2)
>>> print(dos2_r[..., 0])
[[ 100  300  500  700  900 1100 1300 1500 1700]
 [ 101  301  501  701  901 1101 1301 1501 1701]
 [ 102  302  502  702  902 1102 1302 1502 1702]
 [ 103  303  503  703  903 1103 1303 1503 1703]
 [ 104  304  504  704  904 1104 1304 1504 1704]
 [ 105  305  505  705  905 1105 1305 1505 1705]
 [ 106  306  506  706  906 1106 1306 1506 1706]
 [ 107  307  507  707  907 1107 1307 1507 1707]
 [ 108  308  508  708  908 1108 1308 1508 1708]
 [ 109  309  509  709  909 1109 1309 1509 1709]]
>>> print(dos2_r[..., 1])
[[ 200  400  600  800 1000 1200 1400 1600 1800]
 [ 201  401  601  801 1001 1201 1401 1601 1801]
 [ 202  402  602  802 1002 1202 1402 1602 1802]
 [ 203  403  603  803 1003 1203 1403 1603 1803]
 [ 204  404  604  804 1004 1204 1404 1604 1804]
 [ 205  405  605  805 1005 1205 1405 1605 1805]
 [ 206  406  606  806 1006 1206 1406 1606 1806]
 [ 207  407  607  807 1007 1207 1407 1607 1807]
 [ 208  408  608  808 1008 1208 1408 1608 1808]
 [ 209  409  609  809 1009 1209 1409 1609 1809]]

See that index 0 of the last dimension has all the odd columns, while dimension 1 has all the even columns.

Now let's do a min in this case instead of a sum.  The semantics are the same, but it is easier to follow in my opinion.  We will take the min of dimension 1, which is what used to be columns, but now is the columns split into even and odd:

>>> dos2_m = dos2_r.min(axis=1)
>>> print(dos2_m)
[[100 200]
 [101 201]
 [102 202]
 [103 203]
 [104 204]
 [105 205]
 [106 206]
 [107 207]
 [108 208]
 [109 209]]

As you can see, it preserves the row number, and it preserves whether the column is even or odd, but it collapses across even columns and odd columns.

Now let's split it the way it is split in your code:

>>> ms_ud = dos2_r[:, 0, :]
>>> mp_ud = dos2_r[:, 1:4, :].min(axis=1)
>>> md_ud = dos2_r[:, 4:, :].min(axis=1)
>>> print(ms_ud)
[[100 200]
 [101 201]
 [102 202]
 [103 203]
 [104 204]
 [105 205]
 [106 206]
 [107 207]
 [108 208]
 [109 209]]
>>> print(mp_ud)
[[300 400]
 [301 401]
 [302 402]
 [303 403]
 [304 404]
 [305 405]
 [306 406]
 [307 407]
 [308 408]
 [309 409]]
>>> print(md_ud)
[[ 900 1000]
 [ 901 1001]
 [ 902 1002]
 [ 903 1003]
 [ 904 1004]
 [ 905 1005]
 [ 906 1006]
 [ 907 1007]
 [ 908 1008]
 [ 909 1009]]

So you can see it takes the same columns you did in your original, but keeps them in a single 2D array.  And it greatly simplifies the code and speeds up the computation as well.


Run time complexity of printing a binary tree level by level

Your algorithm is plain \$O(n)\$. If you double the number of nodes, your runtime doubles. If you double the number of nodes at the current level, you also double the total number of nodes (or are you planning an unbalanced tree?).

Your algorithm is OK, but there are some deviations from the classics...

The use of a queue here is not quite right, or, rather, the way you are using it is not taking advantage of its queue features. In fact, you are using it as a List, and not a Queue. A Queue should be using the methods add, remove and element (or offer, poll, and peek). You are using the iterate method though instead.

Also, instead of emptying the queue, you create a new one, and throw the old one out. This is inefficient.

A more traditional implementation of the algorithm will use a single queue, and add a 'marker' in the queue to indicate the end of a 'row' in the tree.

Consider using 'null' as a marker, to show you have reached the end of the row, as follows:

queue.add(root);
queue.add(null);
while (!queue.isEmpty()) {
    Node n = queue.remove();
    if (n == null) {
        // end of a row
        System.out.println();
        // which also means we have no more kids to add, so
        // if there is more data, we mark the next end of the *next* row:
        if (!queue.isEmpty()) {
            queue.add(null);
        }
    } else {
        System.out.print(n.value + "  ");
        if (n.left != null) {
            queue.add(n.left);
        }
        if (n.right != null) {
            queue.add(n.right);
        }
    }
}

Sometimes people use a special marker instance instead of null, perhaps something like:

private static final ENDOFROW = new Node(-1);

Then, instead of the null check, you can do:

if (n == ENDOFROW) {

and you can 'add' an ENDOFROW instance as well instead of the null.


Partial implementation of parsing a config-file and command line options

It is good practice to set all of the instance attributes you need in __init__; moving across the contents of build_parser into __init__ would only add three lines!

It seems a bit... roundabout, in places. For example, __init__ calls parse_args which calls parse_command_line_args which calls the root_parser's parse_args. At the very least, I would roll the call to self.root_parser.parse_args into parse_args, as then you aren't going back and forth between method names as you follow the logic through.

There is an unexplained "magic string" in the middle of it all:

#I must ensure that 'Bob' is in the list of names
if 'Bob' not in args.names:
    args.names.append('Bob')

The comment just says what the code is doing, but doesn't explain why, so it's redundant. In general, you have no explanations of the logic - docstrings would be helpful.

Some of those functions seem like implementation detail, rather than functionality you want to expose, so I would prefix the names with underscores to indicate private-by-convention, e.g. _add_person_parser and _add_other_parser.

I would make _possible_config_file_keys = ('names', 'ids') a class attribute of Parser, and indicate it as constant using the style guide naming conventions, i.e.

class Parser(object):

    POSSIBLE_CONFIG_FILE_KEYS = ('names', 'ids')

    ...

You only seem to use pprint for testing, so I would move that import into the if __name__ == '__main__': block. Also, there should be a blank line between standard library and third-party imports:

import argparse

import yaml

Do you not need to check_args in cases where you don't parse_config_file? Again, some documentation to explain that logic would be helpful.


Use class constants to store values that will remain the same and are unchangeable

Your HTTP method verbs are better off set as class constants than class properties since they will remain the same and are unchangeable. (i.e. constant)

private $POST = 'POST';
private $PUT = 'PUT';
private $GET = 'GET';
private $DELETE = 'DELETE';
private $PATCH = 'PATCH';

becomes

const POST = 'POST';
const PUT = 'PUT';
const GET = 'GET';
const DELETE = 'DELETE';
const PATCH = 'PATCH';

You can then refer to them using self

self::POST

No need for an empty constructor

If your contractor doesn't have any code in it you could, and should omit it. It's just noise otherwise. You can always add it if the constructor definition changes.

Be sure to use docblock comments for your class properties

Not just class methods should have well written docblock comments, so should your class properties.

/**
 * @var string The body of the HTTP request
 */
private $body;

Follow PSR coding standards

The PSR coding standards exist to ensure a high level of technical interoperability between shared PHP code. They also ensure conformity for projects with multiple developers.

PSR-2  says that:

  Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.
  and
  Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.

Class HttpRequest{

becomes

Class HttpRequest
{

and

public function post($url, $header, $options, $body){

becomes

public function post($url, $header, $options, $body)
{

Use type hinting to variable types in class methods

From the manual:

  Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated

To use your code as an example, you can declare that $url must be a string and $header and $options must be arrays. This will be enforced by PHP at run time and prevent obvious and non obvious errors from occurring.

public function get($url,$header=array(), $options=array()){

becomes

public function get(string $url, array $header=[], array $options=[])
{

(I used shortened array syntax [] versus the more verbose array() for brevity.)

Use return type declarations

Just like you can enforce that class method parameters are a certain data type, you can also enforce the value returned by that method is a certain data type. Since all of your methods are stubs I'll pretend your HttpRequestget() method returns a Boolean to use as an example.

public function get(string $url, array $header=[], array $options=[]): bool
{

Now my calling code will know that a Boolean, and only a Boolean value, will be returned by that method.

When doing comparisons use === whenever possible

Unlike == which compares values only, === compares both values and type. This strict comparison helps to avoid error, and attacks, that occur when PHP encounters a comparison of two variables of different types it will coerce one of the variables into the type of the other variable in order to do the comparison.

For example

1 == '1'  // true
1 === '1' // false

How much does this matter? It depends. If you get into a situation where you are getting numbers as strings but you are trying to use them as numbers, for something like sorting, you can get unexpected results if your check only checks value instead of type. And those of us who remember phpBB remember when it was subject to a slew of high profile vulnerabilities many of which were resolved simply by using a stricter comparison. So, yes, it matters.


all combinations of all sizes less than N

You can rewrite your implementation much succintly:

import java.util.Arrays;
import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {
        final int N = 4;

        int globalLineNumber = 1;

        for (int n = 1; n <= N; ++n) {
            int[] combination = IntStream.range(0, n).toArray();
            System.out.println("Combination size: " + n);
            int lineNumber = 1;

            do {
                System.out.printf("[%3d] %3d: %s\n",
                                  globalLineNumber++,
                                  lineNumber++,
                                  Arrays.toString(combination));
            } while ((combination =
                      generateNextCombination(combination, N)) != null);
        }
    }

    public static int[] generateNextCombination(int[] combination, int n) {
        if (combination[combination.length - 1] < n - 1) {
            combination[combination.length - 1]++;
            return combination;
        }

        for (int i = combination.length - 2; i >= 0; --i) {
            if (combination[i] < combination[i + 1] - 1) {
                combination[i]++;

                for (int j = i + 1; j < combination.length; ++j) {
                    combination[j] = combination[j - 1] + 1;
                }

                return combination;
            }
        }

        return null;
    }
}

The above produces the following output:

Combination size: 1
[  1]   1: [0]
[  2]   2: [1]
[  3]   3: [2]
[  4]   4: [3]
Combination size: 2
[  5]   1: [0, 1]
[  6]   2: [0, 2]
[  7]   3: [0, 3]
[  8]   4: [1, 2]
[  9]   5: [1, 3]
[ 10]   6: [2, 3]
Combination size: 3
[ 11]   1: [0, 1, 2]
[ 12]   2: [0, 1, 3]
[ 13]   3: [0, 2, 3]
[ 14]   4: [1, 2, 3]
Combination size: 4
[ 15]   1: [0, 1, 2, 3]

Basically, you are given \$N\$ - the number of all possible items you can choose. Also, you are given \$n\$ - the number of \$N\$ items you actually put in a combination. Now, you have a simple class method for producing the next \$n\$-combination. Whenever all \$n\$-combinations where generated, return null in order to signal that you are done with them, after which increment \$n\$, generate the first lexicographic combination, and keep generating until null.

Hope that helps.

Addition

Of course, instead of combination and null you could return true or false depending on the case whether the input combination was successfully "incremented" towards the next combination or not.


The most pythonic way (IMO) to check if two words are anagrams of each other is to check if the number of times each letter appears in each words is the same. For this you can use collections.Counter:

from collections import Counter

>>> Counter("test")
Counter({'e': 1, 's': 1, 't': 2})

With this we can re-write your function to :

def anagrams(word, words):
    result = []
    counter_word = Counter(word)
    for other_word in words:
        if Counter(other_word) == counter_word:
            result.append(other_word)
    return result

This is a lot more readable. in addition, here are some more comments on your code itself:

source = copy.deepcopy(list(i)) is not needed. Since strings are immutable, just doing list(i) would have been fine.
In if(j in source): there are two things:

Python has an official style-guide, PEP8, which is well worth a read. It recommends not using parenthesis in if (and while) statements, so this should be if j in source
in is \$\mathcal{O}(n)\$ for lists and strings, so this is actually quite an expensive way to do it. The better way is using a dictionary (collections.Counter is a dictionary plus some nice stuff).

In for i in wordList, again, PEP8 has something to say, it should be word_list, or even easier words. Also i is not a good name.

Depending on what you want to do afterwards with the anagrams, you could also make this a generator (which you can iterate over and which continuesly yields anagrams):

def anagrams(word, words):
    counter_word = Counter(word)
    for other_word in words:
        if Counter(other_word) == counter_word:
            yield other_word


When a C or C-related programmer sees char* they're going to naturally think of passing in a C-string. In my opinion, it's absolutely fine to do that. If you want to invoke an array of characters in C, I'd do it like this:

char ConsoleIO::GetNextChar(string prompt, char[] choices, int numChoices)

But, you're in C++ so you should use a std::vector<char> and then don't pass in numChoices, like this:

char ConsoleIO::GetNextChar(string prompt, std::vector<char> const& choices)

Also, you have a bug. You aren't ever deleteing buffer, which means it's leaking.


Is there a better way to call the same method with different parameters?

I think you could create a new saveToDB method that requires a Dictionary<string, XmlNodeList> inside this new method you could cycle through the Keys (string) and for each one call the current saveToDB(string, XmlNodeList).

Yes, it only move your problem: you've to prefill the dictionary, but I really think there's no other options... at one point you HAVE to enumerate your datas.


A slice of a list is a new list, so this code constructs five lists:

start = fields[0:i]
middle = fields[i:k]
middle = middle[::-1]
end = fields[k:]
newFields = start + middle + end

This is probably faster:

newFields = fields[:]
newFields[i:k] = fields[k-1:i-1:-1]

Instead of adding fields one by one in the code below, you could change Route to accept the list of fields in the constructor.

newRoute = Route(route.scout)
for field in self.twoOptSwap(route.fields, i, k):
    newRoute.addField(field)

Note also that after reversing a segment of the route, a complete recalculation of cost is not necessary. You only need to consider how the cost changes where the segments join, assuming cost does not depend on direction of travel.
Instead of

for element in xrange(len(route.fields)):
    i = element + 1

simply

for i in xrange(1, len(route.fields) + 1):

Instead of a while loop

k = i + 1
while k <= len(route.fields):
    ...
    k += 1

a for loop

for k in xrange(i + 1, len(route.fields) + 1):


Umm. What about

import Data.Bits
hanoi :: Int -> [(Int, Int)]
hanoi n = map (\x -> ((x .&. (x-1)) `mod` 3, ((x .|. (x-1)) + 1) `mod` 3)) [1..shift 1 n]
main = print $ hanoi 5

?


Codility cyclic rotation solution in PHP

You could use array functions. They simplify and speed up the handling of arrays. See: http://php.net/manual/en/ref.array.php

So your code could become:

function rotateArray($inputArray,$rightShiftCount)
// shift all elements of the array to the right a number of times
{
  // extract the part of the array to move to the front
  $partToMove = array_splice($inputArray,-($rightShiftCount % count($inputArray)));
  // return extract part followed by what was left of the array
  return array_merge($partToMove,$inputArray);
}

This function does not check its arguments, if needed you can add that.

Notice that I have used sensible names for my variables instead of $A and $K. This is intentional.


I'm leaning toward Angle2...

  I also feel the calculations are probably small enough to not worry about

I infer that doing the calcs in the constructor is trivial as well - no problematic user-perceived lag, hesitation, slowness.

Communicating through design

How would I interpret - make an initial guess about - design, intent, and use from what I see here?

... so when calling all of them, they get recalculated multiple times.

By doing something so obviously avoidable, there must be a reason. Somewhere.

Lazy loading, generally, suggests

the operation is time, CPU, whatever consuming to some degree
doing it all at once certainly is an issue
instantiation and/or re-calculation are not intrinsically inter-dependent.
angle is being mutated because there is no logic avoiding re-calc on every call.
an object is in a valid state with all, some, or none of the calculations done.

Client doesn't need guard code all over the place
Client does not have to know any particular call order.

If the client must know call order & all the involved properties to do it, why is Angle1 even a class?

Doing it all in the constructor suggests

This object is immutable
I'm guaranteeing valid state.
angle is not mutated
client code will be just that much cleaner, easier

  however, still prefer the first code. It is cleaner. Easier, for me, to read.

You should write code that is "cleaner, and easier" to use.

Conclusion: Angle2 is better.


Reversal of singly linked list in JavaScript

"I want to do it by less code."

It's relatively easy: you keep another variable that denotes the head of the new list. Then, you remove the head node of the input list and make it a new head node of the new list being constructed:

function reverse(head) {
    new_head = head;
    old_head = head.next;
    new_head.next = null; // Terminate cycle.
    while (old_head) {
        current = old_head;
        old_head = old_head.next;
        current.next = new_head;
        new_head = current;
    }
    return new_head;
}

Usage

function node(val) {
    this.val = val;
    this.next = null;
}

a = new node(1);
b = new node(2);
c = new node(3);

a.next = b; b.next = c;
a = reverse(a); // Don't forget to store the new head node.

Hope that helps.


You've actually run into a big gotcha here. Scheme doesn't actually specify the order to evaluate operands. This can be a problem for code with side effects, especially if you aren't careful to encapsulate the order you expect explicitly. Any time you see an exclamation mark at the end of the function, pay attention to ensure a correct and defined semantic order.

(define (pop-print)
  (display (stack-pop! stack))
  (newline))

Something like this is fine, as (define ...) creates an implicit begin in the syntax. (define (x a) (zig a) (zag b)) gets transformed into something closer to (let ((x (lambda (a) (begin (zig a) (zig b)). cond has a similar effect.

However ...

(define (add)
  (stack-push! stack
           (+ (stack-pop! stack)
          (stack-pop! stack))))

is also fine, because order doesn't matter, but we aren't sure which pop will get its number first. Divide and subtract may randomly behave incorrectly, especially on different Scheme implementations.

Your swap is so close though, but to be right it would have needed to use a begin and a let* instead of the normal let. The Star version behaves as if you explicitly nested each sequential binding, whereas let is allowed to make bindings in any order. begin likewise forces text-order sequential evaluation.

(define (swap)
  (let* ((first (stack-pop! stack))
         (second (stack-pop! stack)))
    (begin (stack-push! stack first)
           (stack-push! stack second))))

Here's a method of forcing order via nested lambda notation, as every time you invoke a function, you're creating a new binding environment.

(define (two-args f) ;takes a function as an argument
 (lambda () ;explicitly return a function of zero arguments
   ((lambda (x)
            ((lambda (y)
                     (stack-push! stack (f y x)))
                                  ; the deeper term has priority
             (stack-pop! stack))
    (stack-pop! stack))

And then define the functions in terms of above

(define add      (two-args +))
(define subtract (two-args -))
(define multiply (two-args *))
(define divide   (two-args /))

And a little trickier

(define swap
  (two-args (lambda (y x)(begin (stack-push! stack x)
                                y))

Why are you initializing the words hash table every time though the repl? You could initialize it at creation like so...

(define words
  (let ((temp (make-hash-table))
    (begin
      (hash-table-set! temp "bye" '(quit))
      ...
      temp)))

As for the exception handler, I can't comment as I don't know that much about them in Scheme.


Your three catch blocks and two returns do the same thing as each other.  You only need one of each.

$update is referenced outside of try, should be defined there too.

$current_public_ip is just another name for $data[ 'ip_address' ].  It's not any shorter or clearer and doesn't resemble its other name very closely.

$previous_public_ip isn't an IP address, it's an object that contains an IP address and other stuff.  It would be clearer to simply name it $previous, which lets you drop the redundant string_ from $string_previous_public_ip.  _public can go too.

public function update()
{
    $update = false;
    $status = 500; // default
    try {
        $data = array();
        $previous_ip = null;
        $data[ 'ip_address' ] = $this->getGateway()->fetchPublicIp($this->getIp());
        $previous = $this->getGateway()->getLastRecord();
        if ( isset($previous->ip_address) ) {
            $previous_ip = $previous->ip_address;
            $data[ 'id' ] = $previous->id;
        }
        if ( $data[ 'ip_address' ] != $previous_ip ) {
            $update = $this->updateOrCreate($data);
        }
        $status = 200;
    } catch ( \Exception $e ) {
        // return default status (500)
    }
    return response()->json([ 'updated' => $update ], $status);
}


No, this is not the correct way to do it. I would recommend that you read JavaFX Transitions documentation.

I personally could not get your code to work properly (Using Java 8, but that should not matter as Java is always backwards compatible). The rectangle showed on the screen, but it did not move at all.

I got this exception:

Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
at javafx.scene.Scene.addToDirtyList(Unknown Source)
at javafx.scene.Node.addToSceneDirtyList(Unknown Source)
at javafx.scene.Node.impl_markDirty(Unknown Source)
at javafx.scene.shape.Shape.impl_markDirty(Unknown Source)
at javafx.scene.Node.impl_transformsChanged(Unknown Source)
at javafx.scene.Node$13.invalidated(Unknown Source)
at javafx.beans.property.DoublePropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.DoublePropertyBase.set(Unknown Source)
at javafx.scene.Node.setLayoutX(Unknown Source)

One I fixed that problem to make it run on the JavaFX thread, the rectangle still did not move an inch pixel.

About the cleaniness of your code:

public class RectangleMover extends Timer

extends Timer is a very bad smell here. There's absolutely no reason to extend Timer. Use a timer as a field inside your class instead. Prefer composition over inheritance.

Speaking of Timer, you could say that it is more or less deprecated, it is often better to use a ScheduledExecutorService. However, if you do the animation properly, you will not need a Timer or ExecutorService at all.

I do like how you're using your boolToInt method (just a shame that I can't the results of it does not seem to be working). I also like how you have separated your methods overall.

I just don't like that your code does not seem to be working for me...


Circular dependency in utility functions

Circular dependency

Although I find this circular dependency fishy, I don't know how to remove it. Maybe it's not possible.

However, as long as the circular dependency exists,
it would be better if the two functions were defined in the same file.
I don't like having them in separate files because:

It can be misleading, suggesting that one file is usable without the other, but it's not
The elementArrayFinderGetMethods and the conditions on it in is-element-finder violates the encapsulation of isElementArrayFinder

Readability

Symmetry helps readability.
In isElementFinder you use early return on callee,
but not in isElementArrayFinder.

You could further reduce the nesting by lifting a callee.object condition to one level higher:

  if (callee.object && callee.property && (callee.property.name === 'all' || callee.property.name === '$$')) {
    if (callee.object.type === 'Identifier') {
      return callee.object.name === 'element'
    }

    if (callee.object.type === 'CallExpression') {
      return isElementFinder(callee.object) || isElementArrayFinder(callee.object)
    }
  }

The callee.property && (callee.property.name === 'all' || callee.property.name === '$$') condition could be a good candidate to extract to a helper method.


Sum two integers, unless they are the same, in which case return double their sum

The existing answers mostly have just said is is wrong here. Which it undoubtedly is.
The reason it's bad to use here is if you pass 257 and above, or -6 and below, you may get incorrect output.
The best way to show how it's bad is to ask you what the output of the following are:

sum_double(2, 2)
sum_double(1 + 1, 2)
sum_double(257, 257)
sum_double(256 + 1, 257)

Simple! Surely it's 8, 8, 1028 and 1028, right?
No, it's actually, 8, 8, 1028 and 514.
This is known and expected behaviour:

  The current implementation keeps an array of integer objects for all integers between -5 and 256,
  when you create an int in that range you actually just get back a reference to the existing object.

Other than that both are fine, and I wouldn't really fret over which is 'better', this is as both are clear and understandable.
Which is all your code needs to be.
A function that would be un-pythonic, as it's not clear could be:

def sum_double(a, b):
    return (a + b) * ((a == b) + 1)


When creating matrices, you can use the more concise syntax

int[][] m = {
  { 1, 2, 3 },
  { 2, 3, 5 },
  { 3, 4, 7 }
};


Singleton model for modifying future .chart elements

I think you are overdoing the underscores, you will find that conflicts will be rare.

Furthermore, I can understand that you want to centralize the iteration over the chart elements, but why would you want to do that recursively, it does not make much sense to me.

If you drop underscores and opt out of recursive iteration, your iterator becomes simpler:

  //Applies the supplied function for each chart element in the collection.
  var applyFunction = function ( f )
  {
    $charts.each(function (){ f($(this)); });
  };

This could be converted to a for loop as per your comment

  //Applies the supplied function for each chart element in the collection.
  var applyFunction = function ( f )
  {
    for( var i = 0, length = $charts.length; i < length ; i++ ){
      f( $charts[i] );
    }
  };

Then, colorArgumentButtons becomes simpler as well:

  // Colors all argument buttons.
  my.colorArgumentButtons = function (color)
  {
    applyFunction( function( $chart )
    {
      $chart.find('button').css('background-color', color);
    });
  };

You will notice that I reduced the comments to a one line comment. When you have almost as much lines of comment as code, then you are doing it wrong.

A minor side note on

selector = typeof selector !== 'undefined' ? selector : settings.chartSelector;

this could simply be

selector = selector || settings.chartSelector;

All in all, I refactored the code into this ( untested ):

var SuperHappy = (function (parent, $) {

  var my = parent.Chart = parent.Chart || {},
      // default settings
      settings = {
        autoFind: true,
        chartSelector: '.chart'
      },
      // jQuery vars
      $charts = $();

  //Applies the supplied function for each chart element in the collection.
  var applyFunction = function ( f )
  {
    $charts.each(function (){ func($(this)); });
  };

  my.init = function (options)
  {
    settings = $.extend(settings, options);
    if (settings.autoFind) {
      my.findCharts();
    }
  };

  /// Colors all argument buttons.
  my.colorArgumentButtons = function (color)
  {
    applyFunction( function( $chart )
    {
      $chart.find('button').css('background-color', color);
    });
  };

  // Finds all chart elements.
  my.findCharts = function (selector)
  {
    selector = selector || settings.chartSelector;
    $charts = $(selector);
  };

  return parent;

})(SuperHappy || {}, jQuery);

jQuery(document).ready(function ($) {
    SuperHappy.Chart.init();
    SuperHappy.Chart.colorArgumentButtons('#f00');
});


Project Euler 6: Sum square difference in Functional Programming (FP)

DISCLAIMER: I don't think this is actually an "answer" answer. Please consider it as a side note, because your code generally looks good to me. I also admit, this answer is highly subjective compared to other my answers.. My purpose here is to provide a point of view rather than persuade that something needs to be fixed in the original code.

[Non-functional] alternative

In a real-life scenario, if num input was huge, you might not be able to create a range array via new Array(num).

Number.MAX_VALUE
// ---> 1.7976931348623157e+308

new Array(Number.MAX_VALUE)
// VM234:1 Uncaught RangeError: Invalid array length
//    at <anonymous>:1:1

Chrome:

Instead of that you could rewrite your range function as a generator function (at a "cost" of it not being an arrow function anymore):

function* range(num) { for (let counter = 1; counter <= num; counter++) yield counter; }

Unfortunately, this is also less functional on its own (notice that the code uses a let variable...). Worse than that, you can only

either manually iterate over it via IterableIterator<> interface (requires a variable);
or use for (let _ of range(Integer.MAX_VALUE) { ... } which isn't looking functional;
or try materialize it into an array via spread operator [...range(Integer.MAX_VALUE)] (which will not work, for the same exact reason I'm mentioning the generator function).

I wish there was a commonly known first-class concept of a Range in JavaScript...

Naming Things

The only thing that pokes my eyes is variable naming. IMHO, you can do better than acc, val, or i. For example, the following is more readable, since real words are being used and the function is more explanatory.

const range = mapFunction =>
  rangeLength =>
    Array.from(new Array(rangeLength), mapFunction);

and

const summer = (subTotal, currentNumber) => subTotal + currentNumber;

summer is better than sum because a) sum as a word denotes the result of summation rather than something that encapsulates the summation logic; b) reads better in the usage. In fact, you can even write const sum = someArray.reduce(summer), or if you prefer better consumer readability over function name -- const sum = someArray.reduce(withSummer).

I know, these are tiny details, but for the reader they make a difference. Once mentioned it in another answer already -- I've witnessed a situation where in an inline function a developer interpreted acc as account. Silly? Yeah, but who cares when one needs to work on Friday evening to fix a bug?


Re-implementing an Array Class in Python

Seems like cheating to re-implement a list using a list... I feel like the real challenge would be doing so without a list of any sort, say creating a linked list or a tree or something like that. That might be pedantic, but it'd clarify what your limitation are and thus what efficient solutions are available versus what you're making needlessly hard for yourself because it's fun.

Most of your functions are going to be very expensive because you're constantly copying memory around. A more common approach is to over-allocate space and then keep two values, "length" and "_allocated". The first is how many valid elements your array contains; the second is how much space you've reserved to store values. When you want to append X to your array, you can just assign X to self.array[self.length] and then increment self.length. If that would take you beyond what you've allocated, only then you do the expensive act of allocating a new chunk of memory (in your case, the [None] * (length + 1) line) and copying the data. To minimize the number of copies, it's common practice to double the length of the array each time you resize it (maybe up to some maximum, at which point you add on new 4K element blocks or whatever rather than multiplying, to prevent running out of memory prematurely). When inserting, then, you'd just need to shift the later values rather than copy everything; similarly, when popping values off, just decrement self.length to mark that last element as unimportant and available to be overwritten.

To complement that approach, if you want to optimize for mid-array insertions and deletions, you can maintain a parallel bit-array of which values are valid and which aren't. Iterating through the array becomes trickier (you need to zip the values with the validity flags and only return the valid ones), but deleting an item becomes cheaper since you only need to find the element and mark it as deleted (no shifting required), and inserting an item only requires shifting things until you find an unused element that can be overwritten instead of shifted.

Caching the length of the array is a good idea in general (though not necessary if you don't over-allocate). It requires extra code and care to keep synchronized with the rest of the array, but checking a list's length is a very common thing for users to want to do, and the O(N) computation each time can get painful.

As a general Python'ism, I'd say use def __len__ instead of def len and implement __get_item__, as well as any other magic methods that generally correspond to an array. For reference see this documentation page, and consider that most people think of an array as some combination of a "Collection" and "[Mutable]Sequence"


Good: Use if-elseif

You are calling 4 if statements with your code even if the 1st one is true. These are all mutually exclusive statements so use if-elseif

for (var i=0; i<choices.length; i++) {
    if (choices[i]=="A") {
        total+=1;
    } else if (choices[i]=="B") {
        total+=2;
    } else if (choices[i]=="C") {
        total+=3;
    } else if (choices[i]=="D") {
        total+=4;
    }
}

Better: Use a switch statement

for (var i=0; i<choices.length; i++) {
    switch (choices[i]) {
        case 'A':
            total += 1;
            break;
        case 'B':
            total += 2;
            break;
        case 'C':
            total += 3;
            break;
        case 'D':
            total += 4;
            break;
    }
}

Best: Convert the character to its numeric equivalent using its ASCII value

for (var i = 0; i < choices.length; i++) {
    //omitted validation that character is a legal value...
    total += choices[i].charCodeAt(0) - 64;
}


Optimizing multiplication of two polynomials in GF(2^32)

For the time output in main():

Use std::clock_t as opposed to clock_t in C++.
You could have another variable, endTime, for the ending time.
The computed time could also have its own variable, elapsedTime, to be printed.
Only the clock time needs to be cast to a double, not the macro as well.  You should also use static_cast<>() as this is C++.

Example with changes:

std::clock_t startTime = std::clock();

// ...

std::clock_t endTime = std::clock();

double elapsedTime = static_cast<double>(endTime - startTime) / CLOCKS_PER_SEC;

std::cout << elapsedTime;

But, since you're using C++11, consider utilizing the <chrono> library instead. Unlike <ctime>, it is more C++-oriented but still contains some <ctime> aspects.

Side-notes:

For std::time, 0 can be replaced with nullptr in C++11.
Consider renaming N to something more descriptive.  Using a constant in place of a magic number is nice, but you can increase readability by using a better name.
Since only your test program uses those first four libraries, they should just be in that file.
You don't need those typedefs in your first file; they are already defined in <cstdint>.

Specific questions:

  Currently, I am using many temporary variables. I could try to help the compiler by removing many of them, but this way the code should be more readable and easier for someone to modify.

I would rely on the compiler to handle this, as it should be able to optimize them out.  But you're right; readability and maintainability are also important.  They can always be adjusted accordingly.

You can also maintain these two things by:

avoiding single-character variable names
keeping variables as close in scope as possible

You seem to do well with the second point, but not so much the first.  I've already addressed this in the side-notes, but this is a problem throughout the first file.  By using more descriptive names, it'll be much easier for others to understand your code and make any needed modifications.


Benchmarking of SQL data crunching using a common datum

There is a bug in your second version. Here is one row from the result:

1;0;2;0

That is, Serial_Number 1 has zero ones, two twos, and zero threes.

But let's do a quick sanity check:

select count(*) from seeded
where serial_number = 1 and status = 'one';

This query returns 100000.

There are also rows with the same Serial_Number, which I think is not what you want.

I think you want a query like this:

select
    seeded.Serial_Number,
    sum(case when seeded.Status = 'one' then 1 else 0 end) as ones,
    sum(case when seeded.Status = 'two' then 1 else 0 end) as twos,
    sum(case when seeded.Status = 'three' then 1 else 0 end) as threes
from seeded
group by seeded.Serial_Number;

This takes ~2.1s on my machine.

Just for fun, let's look at what pgAdmin's EXPLAIN visualisation looks like for this query

versus the 30m query


Allow adding errors and warnings and remove both after a while with seperate timers

Try this collection to hold your messages. It should do exactly what you are looking for - just create couple instances for errors and warnings.
public class MessageCollection : ObservableCollection<string>
{
    public MessageCollection()
    {
        Timer = new Timer(Callback, this, 5000, 5000);
        CollectionChanged += MessageCollection_CollectionChanged;
    }

    Timer Timer { get; }

    void MessageCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        Timer.Change(5000, 5000);
    }
    static void Callback(object state)
    {
        var that = (MessageCollection)state;
        if (that.Any())
        {
            that.CollectionChanged -= that.MessageCollection_CollectionChanged;
            that.RemoveAt(that.Count - 1);
            that.CollectionChanged += that.MessageCollection_CollectionChanged;
        }
    }
}


I'd say, if it's the Presentation and Container Components pattern as described by Dan Abramov, then yes, you've pretty effectively nailed it. (Though Dan no longer advocates this pattern!!)
Suggestions/Review
AddForm
items prop is really the text state in the parent component, it doesn't need the entire state object. (If it does then name it more accurately!) What's used is just the input value, so value is a better descriptor.
export const AddForm = ({ value, onSubmit, onChange }) => {
  console.log(value);
  return (

      <form onSubmit={e => onSubmit(e)}>
        Add new todo:
        <input
          type="text"
          id="name"
          onChange={e => onChange(e)}
          value={value}
        />
        <button
          className="btn waves-effect waves-light"
          type="submit"
          name="action"
        >
          Add item
        </button>
      </form>

  );
};

Usage: <AddForm value={this.state.text}  ...  />
TodosContainer
The handlers are all arrow functions, they already have the this of the class bound to them, so there isn't need to bind them in a constructor. In fact, if all the constructor is doing is setting the initial state, then you don't really need the constructor either as you can simply set initial state with a state instance variable.
Instead of
constructor(props) {
  super(props);
  this.state = { items: [], text: '' };
  this.handleChange = this.handleChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
  this.removeItem = this.removeItem.bind(this);
}

Simply
state = { items: [], text: '' };

State updates
When any next state depends upon current state, like incrementing counters, or adding values to arrays, you should get into the habit of using functional state updates, and also not referencing this.state within the state update.
State and Lifecycle
setState
handleSubmit can be improved
handleSubmit = (e) => {
  e.preventDefault();
  const newItem = {
    text: this.state.text,
    id: Date.now(),
  };
  if (this.state.text) { // <-- if text is truthy, i.e. non-empty string
    this.setState(prevState => ({
      items: prevState.items.concat(newItem),
    }));
  }
}

State updates are also asynchronous, so don't try to console.log it after requesting the state update. Use a component lifecycle like componentDidUpdate to log state after the update (or for class-based components, you can use the setState 2nd parameter callback function, but for simplicity sake stick to the lifecycle functions.).
removeItem handler can be improved
removeItem = (id) => {
  this.setState(prevState => ({
    items: prevState.items.filter(item => item.id !== id),
  }));
}


Apply smiley replacement filter to Pandoc but not in code segments

There's a much shorter way to express the same functionality, but I'm not sure you'll immediately find it to be clearer.

import Data.List (intercalate)
import Data.List.Split (splitOn)
import Text.Pandoc.JSON

main :: IO ()
main = toJSONFilter smile

smile :: Inline -> Inline
smile (Str s) = Str . intercalate "☺" . splitOn ":-)" $ s
smile x = x

I think the insight you missed is that the Block constructor CodeBlock contains no Inlines, so you can trust the Walkable typeclass machinery to ignore them if your smiley making code only works on Inlines. That eliminates the entire applyExceptOnCodeBlock function.

Similarly it isn't necessary to include a case for Inline's Code constructor, constructors like Code and Math contain their own raw strings and are safely ignored. Pandoc's datatypes are already structured to divide prose text from markup making it easy to define transformations by only matching on the things you do want to modify.


Bookmarklet to go to YouTube channel RSS feed

Is this the simplest way to find an element with a specific attribute value?

"simple" is subjective. It could mean anything, like lesser lines, fewer keystrokes, lesser complexity. To me, what I consider simple is code that's short, concise and one that I can understand without running the code.

  Does this work with recent browsers other than Firefox?

With regards to the code, I don't see why not. However, I'm not sure how bookmarklets work with browsers these days. That part you might want to check.

  Does it use any non-standard/deprecated features?

Nothing out of the ordinary. You might want to check MDN or Kangax's compatibility table for more info about what APIs are available to which browsers.

  Are there any YouTube pages this does not work on, where it should?

Not something you'd normally ask in Code Review. That's up to you to find out.

You could substitute array.forEach with find. That way, it bails out on the first item found and not go through the entire array.

Next, you can use template literals instead of string concatenation. It's much more concise and lessens the chance that you'll miss a quote or a + somewhere.

Next, your logic has a lot of if statements. You could try to invert the logic and bail out early. You can also split your logic into functions, that way you can maintain extraction methods with clear separation. Then call them in sequence with || between. That way, the script uses the return value of first call that returns a value, or tries the next if the previous fails. Same conditional effect without the use of if and a lot of nested code.

Something along these lines:

javascript:(function(){
  const slice = Array.prototype.slice;

  function getUrlFromRss(){
    const links = slice.call(document.getElementByTagName('link'));
    const link = links.find(l => l.getAttribute('type') === 'application/rss+xml');
    return link ? link.getAttribute('href') : '';
  }

  function getUrlFromMeta(){
    const metas = slice.call(document.getElementsByTagName('meta'));
    const meta = metas.find(m => m.getAttribute('itemprop') === 'channelId');
    const id = meta ? meta.getAttribute('content') : '';
    return id ? `https://www.youtube.com/feeds/videos.xml?channel_id=${id}` : '';
  }

  const url = getUrlFromRss() || getUrlFromMeta() || '';

  if(!url) return console.log(`Could not find a channel RSS feed from ${location.href}`)

  location.href = url;
})();


Calculate the value of an arithmetic term written in Polish Notation

To start at the end:

  Generally: Is everything done in a good way and fashion?

It looks quite good, kudos!

Structurally, there's one thing that's not quite right, though: You're declaring currentChar and right in the function's scope, you really don't need to. The currentChar you've declared never gets used; the argument in the forEach callback shadows it (and it's not necessarily a character - it could be "12312"). And right doesn't have to be in that scope either, it can just be local to the callback.

And you could technically use reduce instead of forEach with a closed-over stack, but that's not so bad.

I also have some more notes, but also I'm nit-picking quite a bit. I had to find something to write, y'know?

Your documentation seems fine. The exact flavor of documentation syntax is more or less up to you (JS doesn't have a strong convention), so the JavaDoc-like syntax is fine. Would also have accepted a regular comment without the @-keywords, so long as the important parts are covered.

You might consider some comments in the function body, though. There isn't much need for it here admittedly, but just to say that it's not just about commenting the API but also the code.

The regex validation seems fine too, but it doesn't catch malformed syntax, only illegal tokens. A string like ",,," wouldn't trigger anything, nor would a string like "3,+".

The latter ("3,+") returns NaN, which is sort of OK. You can evoke the rule of "Garbage in, garbage out" and blame the caller. At least they're getting a Number back (yes, NaN - not a number - is in fact a Number. Go figure.)

The former input, however, returns an empty string. Since no operations have been performed, the final stack.pop() will be an empty string. So here, you're not even getting a number. That seems less correct.

Ideally, you would complain if the function reaches the end with something other than 1 element in the stack, since that would imply that the RPN expression wasn't "balanced". In fact, your third example suffers from this; the stack ends at [2, 23.1666...], but you report the 23.166... as the answer despite the expression not being fully parsed.

It would also be nice to allow (and ignore) whitespace in the string, just to make input a little flexible. A more readable input string might be beneficial to users (I tested your code, and kept putting in spaces after commas out of habit).

There's another thing your code doesn't handle: Anything with decimals. Since you can't use . in the string, you're limited to integers. That's a bit harsh. You could also consider allowing other legal JS number formats like 0x3 hex, 0b1010 binary, or 3.14e3, but that's more just an exercise for you. eval should already handle them fine, but your regex will complain.

Last bit about validation: I'd throw a TypeError if the input isn't a string. More accurate than a generic Error certainly.

That's mostly smaller stuff, and easily fixed or left as-is. The only thing I'd do very differently would be to not use eval. If you instead define the operators as functions, you:

get rid of eval, which is always nicer in my opinion
you can implement operators that don't take 2 operands such as factorial
you can easily implement more operators (right now, you'll have to change both the regex and the array in the loop)

And if you store your functions in an object, you get quicker lookup than with indexOf (not that that really matters that much).

For instance:

function rpn(expression) {
  // define our operators as functions
  const operators = {
    '+': (a, b) => a + b,
    '-': (a, b) => a - b,
    '*': (a, b) => a * b,
    '/': (a, b) => a / b,
    '^': Math.pow
  };

  // check input type
  if (typeof expression !== 'string') {
    throw new TypeError(`No valid parameter given. Expected string but got ${typeof expression}.`);
  }

  // evaluate the expression, ignoring whitespace
  var stack = expression.replace(/\s/g, '').split(',').reduce((stack, term) => {
    if (operators.hasOwnProperty(term)) {
      const op = operators[term];

      // check stack depth
      if (stack.length < op.length) {
        throw new Error("Stack underflow");
      }

      // grab n elements from the stack, where n is the number of arguments
      // that the operator function takes
      var operands = stack.splice(-op.length);

      // perform the operation and push the result
      stack.push(op.apply(null, operands));
    } else {
      var number = term * 1; // coerce the term to a number

      // check that the coercion produced something numeric
      if (Number.isNaN(number)) {
        throw new Error(`The term '${term}' is neither numeric or a recognized operator`);
      }

      stack.push(number);
    }

    return stack;
  }, []);

  if (stack.length !== 1) {
    throw new Error("Incomplete expression"); // find something better to say
  }

  return stack[0];
}


Calculate the weekday from a date (M-D-Y)

If you're allowed to use library functions, split already exists as part of cl-ppcre.

There's a pretty rich set of date/time functions in the Lisp core that make this trivial. If it's for learning purposes, by all means, go ahead and do it by hand. But if you're thinking "What's the best way to get the day-of-week in Lisp?", that's actually ridiculously simple.

(defun day-of-week (day month year)
   (nth-value 6 (decode-universal-time (encode-universal-time 0 0 0 day month year 0))))

Re-arrange order of argumnents to taste. Monday is 0 by default, so you'd need to re-jig your format directive. If you need to be able to handle dates before 1900, there's a more robust version at the Common Lisp Cookbook.


Repeatedly open and close a PDF document to perform various operations

IMO there is a problem with the try...catch statement. If an exception is thrown you'll have to deal with communicating the error to the client. You can't rethrow it because then the Save() and Close() aren't called, so you'll have to have a kind of logging or event to notify through and that could make it all unnecessarily complicated. Besides that: if an exception is thrown, you may not want to save the document in an unknown state, but you should close it anyway.

You can handle that in the following way:

  try
  {
    perform(loadedDocument);
    loadedDocument.Save();
  }
  finally
  {
    loadedDocument.Close();
  }

Here the document is only saved if the process went well, but closed in any case. And the caller can handle the exception as needed.

Alternatively you can make a wrapper like:

  class PdfDocumentExecuter : IDisposable
  {
    private PdfLoadedDocument document;

    public PdfDocumentExecuter(string fileName)
    {
      document = new PdfLoadedDocument(fileName);
    }

    public void Execute(Action<PdfLoadedDocument> action)
    {
      action(document);
      document.Save();
    }

    public T Execute<T>(Func<PdfLoadedDocument, T> function)
    {
      T result = function(document);
      document.Save();
      return result;
    }

    public void Dispose()
    {
      if (document != null)
      {
        document.Close();
        document = null;
      }
    }
  }

called as:

  using (PdfDocumentExecuter executer = new PdfDocumentExecuter("path"))
  {
    annotations = executer.Execute(Build);
  }


BFS' shortest path unweighted directed graph

Advice 1

for(V v: adjlist.keySet()){
    dist.put(v, null);
    prev.put(v, null);
}

This is \$\Theta(N)\$ and you don't really need it (see below). Also, TreeMap orders the keys (nodes) in a balanced binary search tree, which runs insertion/search/removal in worst case \$\Theta(\log n)\$ time, and you don't need it either: just use a HashMap with \$\Theta(1)\$ access, reading and writing.

Advice 2

In order to get rid of the initialization for in the above advice, you can do:

public int shortestPathLength(V source, V target) {
    Map<V, Integer> dist = new HashMap<V, Integer>();
    Map<V, V> prev = new HashMap<V, V>();
    Queue<V> q = new LinkedList<>();

    dist.put(source, 0);
    prev.put(source, null);
    q.offer(source);

    while(!q.isEmpty()){
        V u = q.poll();
        if(u == target)
            return tracebackPath(u, prev);
        q.remove(u);
        for(V neighbor: adjlist.get(u)){
            if (!dist.containsKey(neighbor)) {
                dist.put(neighbor, dist.get(u) + 1);
                prev.put(neighbor, u);
                q.offer(neighbor);
            }
        }
    }

    return 0; // Target not reachable from source.
}

List<V> tracebackPath(V target, Map<V, V> prev) {
    List<V> s = new LinkedList<V>();
    V u = target;
    while(prev.get(u) != null){
        s.add(u);
        u = prev.get(u);
    }
    return s.size();
}

Advice 3

if(u == target)

Beware. I suggest you implement equals for whatever node type you use and change the above to

if (u.equals(target))

Advice 4

Since you need to map nodes to values in the HashMap s, you need to override a hashCode() as well in the graph node class.

Concluding

Suppose both target and source nodes are very close to each other. My implementation will return very fast because it does not have to run that nasty for loop.

Hope that helps.


Yet another OpenGL Shader: the Builder pattern and lifetime management

Your implementation is very OOPy and I'd call it a good rendering of the builder pattern. Your usage example makes for a nice "fluent" API, BUT, I would personally not buy it.

The reason why 99% of the implementations out there are just reinventing OpenGL in a OOP way is because everyone takes the sorter path of a bottom up approach. They look at the API and see: Humm, so it looks like we have this glShaderSource thingy, so my class will need an addShaderSource method...

If they'd take a top down approach instead, they would first consider if exposing an addShaderSource method of sorts is even necessary.

First basic constraint of a GL shader program is that it requires at least two stages: Vertex and Fragment. So it doesn't even make sense for a shader program to exist without these two stages.
Linking the program is also a low-level implementation detail that I'd avoid exposing to the interface whenever possible. Again, a shader that fails to link is useless and an unlinked object should not be allowed to propagate.

Take all that into account and what should come to you is the good ole factory function. It receives all the required inputs and return a valid object or fails in your favourite way (return null, exception, error code, etc) without leaking intermediate incomplete objects.

//
// Creates and links the shader or returns a null to indicate failure.
// You could also do a lot more for error handling, like throwing and exception
// with the compiler info log or returning the info log as an optional output parameter.
// I usually integrate this kind of stuff with a log system, so that's where my shader info log goes.
//
std::unique_ptr<GLShaderProgram> createGLShaderProgram(const std::string & vertexFilename, const std::string & fragmentFilename);

Now suppose you'd like to support more shader stages rather then the minimal Vertex+Fragment pair, like Geometry shader or Compute shaders. There are many ways to do it, but sticking to our previous example, I'd personally introduce a helper structure in this case:

struct ProgramStage
{
    enum Type
    {
        Vertex,
        Fragment,
        Geometry,
        // ... what have you ...
    };

    Type type;
    std::string filename; // This could also be a source code string instead if it suits you.
};

std::unique_ptr<GLShaderProgram> createGLShaderProgram(const std::vector<ProgramStage> & stages);

I hope the above snippets made the idea clear to you. The point is not to just try to wrap OpenGL in a class, but take a step back and actually consider what is really needed, which is avoiding the propagation of incomplete objects (I'd also add to that a simple and clean interface!). Your builder pattern doesn't do that. If the user forgets to add a mandatory stage, BAM!, incomplete state.

Now lets look at the rest of the code.

Move operator is broken:

GLShaderProgram &operator=(GLShaderProgram &&other)
{
    programId_ = other.programId_;
    other.programId_ = 0;

    if (other.programId_ != 0) {
        glDeleteProgram(other.programId_);
    }

    return *this;
}

Look closely to it in isolation for a few seconds. Do you realize the bug? other.programId_ is set to zero, then you test if it is non-zero in the next line to delete it. That if check is always false. But there is another less obvious error there. programId_ from this object gets overwritten, so you are officially leaking that handle if it contained a valid object.

You'd better just scrap that operator and rewrite a new one using the copy and swap idiom.

glDeleteShader != glDeleteProgram:

~GLShaderProgram() {
    glDeleteShader(programId_);
}

I'm fairly confident that the member programId_ is a shader program, not a shader object/stage, so it is being deleted by the wrong function. This is undefined behavior at best. You should be using glDeleteProgram, that was probably a typo, since in other places you use the correct function. Blame OpenGL for using goddamned integers for everything!

Make deleteAttachedShaders a member of something?

If that function is not useful elsewhere, then it should be made a static member of one of your classes.


Read Space Delimited Text File to Standardized Data Type

First off, I'm going to have to complain about your taste in function names, which will probably be unproductive and just lead to hurt feelings on both sides. Yes, it's that function f. I don't mind so much if small inner functions defined with letfn have names like f, but to my eye, something declared at the top level of namespace—private or no—should have a more descriptive name. I would probably not define f as a top-level function at all; see below for more on that. It's also confusing that you call the top-level function f, then also call the function passed as a parameter to get-data by the name f and then go ahead and pass f as the parameter f in data-in.

I kind of don't like that you expect the output of data-in to be a vector of vectors, but you depend on the function passed as a parameter to get-data to return a vector instead of putting that logic inside data-in. If I had a top-level private function that's only used once and seems too specific to ever be useful again, like f, I would consider making it an anonymous function that gets passed in the one time it's used. So I would probably rewrite data-in like this:

(defn data-in
    [filename]
    (vec (get-data filename #(vec (map edn/read-string
                                       (clojure.string/split % #" ")))

Or, if you're uncomfortable with the shortcut syntax for anonymous functions (it can get pretty hairy), like this:

(defn data-in
    [filename]
    (vec (get-data filename (fn [line] (vec (map edn/read-string
                                             (clojure.string/split line #" ")))

Now data-in is longer and a bit uglier. But this way, all the logic for data-in is in data-in. You expected data-in to return a vector of vectors, but as it was before, data-in relied on f processing each line into a vector, so the logic of one function was spread across multiple functions.

Notice how the whole thing is now separated into a general portion, the get-data function, which could be useful again later on when you need to read some lines from a file, process them in some way, and return them in a sequence; and a specific portion, data-in, that contains all that bits which are only relevant to the problem you have right now.

Pursuant to that, I don't really like that get-data is private. It seems like a perfectly good, general, widely useful function. For example, suppose we have a CSV file with columns a, b, and c, separated by spaces. Then we could write:

(get-data "MyCSV.csv" #(let [{a 0, b 1, c 2} (clojure.string/split % #" ")]
                            {:a a, :b b, :c c}))

and instead of a sequence of vectors, we'd get back a sequence of maps with keys :a, :b, and :c. This usage is totally unrelated to your original intention for this code, but it shows how generally useful the function is—so why make it private and hide it where no one can access it? Let it out and see what uses people can find for it.

Finally, for such a small program it probably doesn't matter, but one of my favorite features of Clojure is docstrings. I would write one for any function I was publicly exposing:

(defn data-in
    "Returns a vector of vectors of elements from the given file."
    [filename]
    (vec (get-data filename #(vec (map edn/read-string
                                       (clojure.string/split % #" ")))

Then anyone can call up a REPL, load your namespace, and type (doc data-in) to read the documentation.


Consolidating a dictionary from nested dictionary

If your dictionary always has the structure {key: {key: int}}, i.e. the values of the inner dictionaries are all integers, this can be easily achieved using collections.Counter.update:

from collections import Counter

def consolidate(d):
    consolidated = Counter()
    for sub_dict in d.values():
        consolidated.update(sub_dict)
    return dict(consolidated)

if __name__ == "__main__":
    all_guests = {'Alice': {'apples': 5, 'pretzels': 12},
                  'Bob': {'ham sandwiches': 3, 'apples': 2},
                  'Carol': {'cups': 3, 'apple pies': 1}}
    print(consolidate(all_guests))
    # {'apple pies': 1, 'apples': 7, 'cups': 3, 'ham sandwiches': 3, 'pretzels': 12}

Note that Python has an official style-guide, PEP8, that recommends using lower_case both for functions and for variables. I also put this code into a function, so it is reusable, and only called it with the test case under a if __name__ == "__main__": guard to allow importing from this module without executing the test case.


Finding points with the shortest distance

For starters, this code should use a Point class, consisting of an x and y location. Your variable points would then be Point[] rather than a two dimensional array. The Point class should have a method for reading values, printing values and calculating the distance between two points.

Then, using the Point class, your code would be dramatically simpler and easier to read. It might even be easier to write from scratch rather than try and fix what you have.