Sorting and slicing array, based on another "weight" array?

Your implementation seems fine.
The only improvement I see is to not preserve the ordering when you slice.
So instead of:

$arrAllowedKeys = array_slice($arrWeight, 0, self::METRICS_BREAKDOWN_LIMIT, true);

This is all you need:

$arrAllowedKeys = array_slice($arrWeight, 0, self::METRICS_BREAKDOWN_LIMIT);

The title of your question is "sorting and slicing array",
but the input array is not sorted.
During the process, only the calculated array of weights is sorted,
the original is not.

If the input is this:

$arr = array(
'apple' => array(1, 5, 3, 4, 0, 0),
'water' => array(0, 1, 2, 3, 4, 5),
'beer' => array(0, 0, 0, 0, 0, 0)
);

Then the output will be:

$arr = array(
'apple' => array(1, 5, 3, 4, 0, 0),
'water' => array(0, 1, 2, 3, 4, 5)
);

In other words, the input array is sliced, but not sorted.

What happens to elements with the same weight, around the self::METRICS_BREAKDOWN_LIMIT index? For example, if self::METRICS_BREAKDOWN_LIMIT = 1, and the initial array is this:

$arr = array(
'water' => array(1, 2, 3),
'apple' => array(1, 2, 3),
'beer' => array(1, 2, 3)
);

Which record will be in the result? It depends on whether arsort is using a stable sorting algorithm (not so easy to find in the docs of arsort). If arsort is stable, insertion order will be preserved, and the answer will be water. Otherwise it can be any of these. It would be a good idea to add a comment in the code about this.


Observation:
I don't like the design.
You are using a two phase initialization. You construct the object (thus constructor) and then call an init() function. Two phase initialization is a bad idea as you can't tell (or have to validate) the state of the object before it can be used.
A better technique is to simply use the constructor to initialize the object. If the constructor fails then the throw so the object never exists and can't be used incorrectly.
You also have an explicit close (closeSocket()) which is fine to an extent but you are forcing people to remember to call this function when you are done with the object. This is what a destructor is for.
You need to look up the concept of RAII.
{
    Website    site("Stuff"); // All resources allocated
}
// All resources for `site` are now released.

Design
What is the use of connectToSite(), is that not the init? Can you call read/write before calling this? If not then read/write are on the wrong object and connect should return you the appropriate object that has the read/write interface.

This is how I would want to use an object called "WebSite"
{
    // An abstract object that represents the site.
    // No actual underlying connection as connections are
    // usually to resources on the site not the actual site.
    Website    site("thorsanvil.com", 80);

    // Create a connection to a specific resource on the site.
    Connection c = site.open("Path");

    // Object was created successfully so we have
    // a valid connection to a server we can not communicate with.
    c.writeData("This is a message");
    std::string resp = c.read();
 }

From your interface. I would look to rename your class to "Connection" then the expectations for how to use the object may be more like.
 {
    // Create the socket and connect to the site.
    Connection   c("https://thorsanvil.com/MyResource");

    // Object was created successfully so we have
    // a valid connection to a server we can not communicate with.
    c.writeData("This is a message");
    std::string response = c.readData();
 }

Code Review:
You don't want to use C++ strings?
#include <string.h>

A URL?
  int init(std::string url)

Sure but the name of the class is "Website". A url is a lot more than just a website. There is a schema/host(hostname/port/user/password)/path/query/fragment. Would you not just pass a host and for the connection maybe a port.
Or you could pass the whole url but each new connection needs a new URL not just the website.

You are returning the status code here (on error):
  if((status = getaddrinfo(url.c_str(), "80", &hints, &servinfo)) != 0){
          return status;
      }

But here you are retuning -1
      if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
          return -1;
      }

Are you sure those error ranges do not overlap?
I think a better interface would be to throw an exception if something goes wrong.

This is not going to work for the generic URL.
  status = getaddrinfo(url.c_str(), "80" ....

The port is not always 80.
The default port is defined by the schema "http/https ..."
The default can be overridden by the url itself.

Example:
  https://thorsanvil.com:1222/Work

  Schema:   https
  Site:     thorsanvil.com
  Port:     1222             overrides default 443 for https
  Path:     /Work
  Query:    Empty
  Fragment: Empty

Really the above code should be:
  status = getaddrinfo(getHost(url), getPort(url), ....

What happens of connect() fails? Are you expecting the user to check the error code?
 int connectToSite(){
    return connect(sock, servinfo->ai_addr, servinfo->ai_addrlen);
 }

That's very C like interface and very error prone to use. We know that users of API don't always check error codes. Don't leak this ingormation. Make it explicit with an exception.

This is not how you use send() and recv() the return value indicates how much of the message was sent/recved. You need to repeatedly call this functions until the message is sent or there is an error.
 int sendToSite(std::string request){
    return send(sock, request.c_str(), strlen(request.c_str()), 0);
 }
 int recvFromSite(char buf[], int maxsize){
    return recv(sock, buf, maxsize, 0);
 }

Research
Have a look at this class:
https://github.com/Loki-Astari/ThorsSocket/blob/master/src/ThorsSocket/Socket.h


Don't throw Exception

throw new Exception("Need an equal count of xs and ys");

It forces client code to catch any subclass of Exception. In this case I would throw an ArgumentException.

The continue at the end of the last loop is redundant.

Here you're using double.Equals

if (delta[i] == 0)

From MSDN

  The Equals method should be used with caution, because two apparently
  equivalent values can be unequal due to the differing precision of the
  two values.

That link covers two techniques for dealing with this.

As far as I can tell, toFix can be removed. For example,

var toFix = new List<int>();
for (int i = 1; i < length - 1; i++)
{
    if ((delta[i] > 0 && delta[i - 1] < 0) || (delta[i] < 0 && delta[i - 1] > 0))
    {
        toFix.Add(i);
    }
}
foreach (var val in toFix)
{
    m[val] = 0;
}

Can be rewritten as

for (int i = 1; i < length - 1; i++)
{
    if ((delta[i] > 0 && delta[i - 1] < 0) || (delta[i] < 0 && delta[i - 1] > 0))
    {
        m[i] = 0;
    }
}


Parsing a text file into a pandas DataFrame

Disclaimer: I know this is a very liberal interpretation of a code review since it suggests an entirely different approach. I still thought it might provide a useful perspective when thinking about such problems in the future and reducing coding effort.
I would suggest the following approach using regex to extract all the numbers that match the format "12.34".
import re
import pandas as pd

with open("your_text_data.txt") as data_file:
    data_list = re.findall(r"\d\d\.\d\d", data_file.read())

result = [data_list[i:i + 4] for i in range(0, len(data_list), 4)]

df = pd.DataFrame(result, columns=["T1", "H1", "T2", "H2"])
print(df)
df.to_excel("your_table.xlsx", index=False)

This will of course only work for the current data format you provided. The code will need to be adjusted if the format of your data changes. For example: If relevant numbers may contain a varying number of digits, you might use the regex "\d+\.\d+" to match all numbers that contain at least one digit on either side of the decimal point.
Also please note the use of the context manager with open(...) as x:. Only code that accesses the object needs to and should be part of the managed context.


I would consider wrapping the conditions up inside a function:

def is_header(pattern):
    if pattern in header:
        pattern_index = header.index(pattern)
        if fields[pattern_index]:
            pattern_key = "path" if pattern == "url_slug" else "keyword"
            payload['seo_page[{}]'.format(pattern_key)] = fields[pattern_index]
        else:
            print("{} not defined for {}".format(pattern, fields[pattern_index])

Because the tests are essentially the same, you could create a common function and pass in the pattern to test against (url_slug or keyword). There is some extra hocus pocus to get pattern_key to be the right thing in order to point to the right key in your seo_page dict (I assume it is a dict?).


Password protected Joomla administrator folder with Python

My suggestions would be:

Rewrite ok() using python I/O rather than running echo in a subprocess. We're passing in arguments because they are no longer going to be global variables after some of the edits below.

def ok(passfile, htaccess, user):
    os.system("htpasswd -c %s %s" % (passfile, user))
    with open(htaccess, 'w') as f:
        f.write('AuthUserFile %s\n' % (passfile))
        f.write('AuthName Restricted\n')
        f.write('AuthType Basic\n')
        f.write('require valid-user\n')
    print "=" *40
    quit()

Consider using the python module https://pypi.python.org/pypi/htpasswd instead of calling htpasswd in a subprocess. For example:

import htpasswd

with htpasswd.Basic("/path/to/user.db") as userdb:
try:
    userdb.add("bob", "password")
except htpasswd.basic.UserExists, e:
    print e

Take all the top level lines outside any function and put them in a main() routine at the top of the file (after the imports). Like so (I'm also doing some tweaks here to make things more portable and pythonic):

#!/usr/bin/env python
import os
import pwd
import sys

def main(args):
    username = raw_input("Enter your cpanel username: ");
    try:
        pwd.getpwnam(username);
    except KeyError:
        print "User not found.";
        quit();
    print "=" * 40;
    user = raw_input("Enter the username you want to create for authentication: ");
    print "=" * 40;
    print "Your username will be "+ user +" for authentication";
    print "=" * 40;

    # Note we're building up our file paths without ever using '/' or
    # '\'. By letting python build our paths for us, they'll be portable
    homedir = os.getenv("HOME")
    passfile = os.path.join(homedir, ".pass_file")
    htaccess = os.path.join(homedir, "public_html", "administrator", ".htaccess")

    # If htaccess already exists, we ask user whether to overwrite.
    # If the user says "no", we say sorry and call quit().
    # If the user says "yes", we break out of the loop and call ok().
    # Otherwise, we keep telling the user to answer 'yes' or 'no'
    # until they do.
    #
    # If htaccess does not exist, I think we want to create it. The
    # original code did not address this case.
    if os.path.isfile(htaccess):
        while True
            ans = raw_input("File %s exists. Overwrite??" % htaccess);
            # re.findall() will return a list of regexp matches. If there
            # are no matches, the list is empty and the if evaluates to
            # False. Note the regexp handles mixed case and abbreviations.
            if re.findall('[Nn][Oo]?', ans):
                print "Sorry we didn't secure the administrator folder. :(";
                quit();
            elif re.findall('[Yy]?[Ee]?[Ss]?', ans):
                break
            else:
                sys.stdout.write("Please respond with 'yes' or 'no'.");
    ok(passfile, htaccess, user)
    quit();

Then at the bottom of the file,

if __name__ == '__main__':
    main(sys.argv)

By using a main() routine and calling it from the bottom of the file if __name__ contains the string '__main__', you can import this file into other files and reuse the code by calling the functions. With lines at the top level of the file, outside functions, those lines would get run if you ever imported the file. Following this convention consistently makes debugging and code reuse much easier.


Simulate single inheritance in c
  I wonder if my approach is good?

Function consistency

I'd expect ..._circle(Shape* this) functions to take Circle* this.  Let the draw() play with the pointer conversions.

void draw(void* this) {
  Shape* pthis = this;
  (pthis->pvtable->draw)(pthis);
}

void draw_circle(Circle* this) {
    printf("Drawing Circle with radius = %i\n",this->radius);
}

// No longer generate a warning
draw(mycircle);

Naming convention

For type Shape, code uses ..._shape, the undefined struct Shape and  Vtable.  I'd expect greater uniformity - perhaps Shape_init(), Shape_draw(), Shape_Vtable, etc.

For Circle, use Circle_draw(), Circle_init(), etc. and not ..._circle().

Avoid text case changes.

Avoid anonymous struct Shape

This problem hints that code is using C++ to compile C code.  Best to use C for C code.

Change typedef void(*pfct)(struct Shape*); to typedef void(*pfct)(Shape*); and move after typedef struct{ ... }Shape;

Missing companion free()

A companion to ..._init(), a ..._uninit() should exist.

Organization

Put Shape code in one place (or file) and Circle in another.

Consider allocating to the object, not the type

It is easier to code right, review and maintain.

// pshape = malloc(sizeof(Shape));
pshape = malloc(sizeof *pshape);

Error checking

Robust code checks memory allocation.

pshape = malloc(sizeof(Shape));
if (pshape == NULL) Handle_OutOfMemory();


Using prototype is useful for polymorphism. If you want to create another class, eg. ColourfulPoint, you can use this code:

ColourfulPoint.prototype = Object.create(Point.prototype);

to make your new class inherit all the methods of Point.
The first method (using only a constructor) is a way faster (at least in Firefox and Chrome) than the prototype one. Take a look at the test.
Unless you intend to create polymorphic classes, use the first one.


Never heard of Atomic design till today.Read the blog and a few chapters of the book. Nothing really new, just another analogy (re-branding) for the standard modular design methods.

To your code.

Its not at all DRY but the various settings are consistent and can easily be changed so that you minimize the repeated code and literals.

The following example reduces the repeated code but without knowing more about how these properties change per client/instance I cant add add anything regarding the design methods.

css() {
    const rules = {
        columns: "grid-template-columns: ##SET##;",
        rows: "grid-template-rows: ##SET##;",
        areas: "grid-template-areas: \"##SET##\";",
        gap: "grid-gap: ##SET##;",
        columnGap: "grid-column-gap: ##SET##;",
        rowGap: "grid-row-gap: ##SET##;",
    };
    const sizes = {
        default:" .grid { ##STYLE## }",
        small: "@media (max-width: 600px) { .grid { ##STYLE## } } ",
        medium: "@media (min-width: 600px) and (max-width: 992px) { .grid { ##STYLE## } } ",
    };
    var src, css = "";
    const rule = name => src[name] ? rules[name].replace("##SET##", src[name]) : "";
    for (const size of Object.keys(sizes)) {
        src = size === "default" : this : this[size];
        if (src) {
            css += sizes[size].replace("##STYLE##", Object.keys(rules).map(rule).join(""));
        }
    }
    return css;
}


Check if a binary tree is a subtree of another tree

The approach is fundamentally flawed. If you're going to do it this way, you need two methods:

public boolean equals(Node n1, Node n2) {
    if (n1 == n2) return true;
    if (n1 == null || n2 == null) return false;
    if (n1.data != n2.data) return false; // Should use .equals if Node.data isn't primitive
    return equals(n1.left, n2.left) && equals(n1.right, n2.right);
}

public boolean isSubtree(Node n1, Node n2) {
    if (n2 == null) return true;
    if (n1 == null) return false;
    return equals(n1, n2) || isSubtree(n1.left, n2) || isSubtree(n1.right, n2);
}

If you're worried about complexity, you might want to consider whether you can flatten your tree into a canonical (wlog) prefix-order string and use an advanced string matching algorithm.


Your code flattens the entire array of {} objects, indiscriminately flattening all properties. It does not mind, if there is only one single property, but it does not make sense semantically, especially if the array is named paintings.

Rather consider the resulting array a projection/mapping to a single property painting.

For a consistent array check and take only the painting property.

for (const p of paintings) {
  if ("painting" in p) {
    paintingsNew.artworks.push(p.painting);
  }
}

The extra if protects against undefined entering corrupted data.


Are 2 Django URLs pointing at 1 view unorthodox?

Why not separate the view functions?

# talk to lower_down
url(r'^pm/(?P<userprofile_pk>\d+)/$', 'private_message_down'),

# talk to higher_up
url(r'^pm/$', 'private_message_up'),

The view functions:

def private_message(src, dest):
    # Are they allowed to talk?
    if src.is_assoc_with(dest):
        return HttpResponseRedirect('/')

    feed_vars = {
        'dest_pk': dest.pk,
        'src_pk' : src.pk,
    }

    return render(request, 'talk/private_message.html', feed_vars)

def private_message_down(request, userprofile_pk):
    src = request.user.userprofile

    # TODO: profile actually exists?
    dest = UserProfile.objects.get(pk=userprofile_pk)

    return private_message(src, dest)

def private_message_up(request):
    src = request.user.userprofile
    dest = me.higher_up

    return private_message(src, dest)

I added a TODO for failure handling, I think you should wrap the .get lookup in a try-except UserProfile.DoesNotExist, for example:

from django.http import Http404

def private_message_down(request, userprofile_pk):
    src = request.user.userprofile

    try:
        dest = UserProfile.objects.get(pk=userprofile_pk)
    catch UserProfile.DoesNotExist:
        raise Http404

    return private_message(src, dest)

Also, you probably want to decorate private_message_* with @login_required (from django.contrib.auth.decorators import login_required).


if (z[i] == 0)
    for (j = 2 * i; j < 100000; j = j + i)
        z[j] = 1;

can be changed to

if (z[i] == 0)
    for (j = i * i; j < 100000; j = j + 2 * i)
        z[j] = 1;

as

k * i (with k < i) is already set to 1 by sieve k.
when j is odd, j + i is even and so already set by even sieve.

For readability, you may split into function and do some renaming, to have something like:

const int N = 100000;
const int SQRT_N = 316;

void shieve(char (&isNotPrime)[N])
{
    memset(isNotPrime, 0, N);
    isNotPrime[0] = 1; // 0 is not a prime
    isNotPrime[1] = 1; // 1 is not a prime
    // now remove all evens from 4 up
    for (int i = 4; i < N; i = i + 2) {
        isNotPrime[i] = 1; // remove evens
    }
    // now loop through remaing up to square root of max number
    for (int i = 3; i < SQRT_N; i = i + 2) {
        if (!isNotPrime[i]) {
            for(int j = i * i; j < N; j = j + 2 * i) {
                isNotPrime[j] = 1;
            }
        }
    }
}


The biggest problem I see here is that you are printing a warning message to System.out and then using a default value for something which sounds like an Exception.

Why allow negative values at all?

if (initialAge < 0) {
    throw new IllegalArgumentException("Initial age cannot be negative, was specified as " + initialAge);
}
age = initialAge;

This way it is always up to the caller to pass a valid age instead of the method defaulting to zero which will bring other problems. It is better to have your program break early because of a bug than to have a warning message be printed out which may indicate a bug.


In 8-puzzle finding nr of steps moving a tile to the right place

Concerns

This logic is complicated and long winded... so much so, that you cut a huge portion of it, or otherwise there is a big bug... You have the condition inside the while-loop:

   // If the tile needs to be moved upwards (row coord is smaller in
   // goal)
   if (goal[0] < current[0]) {

But there is no 'else' condition for that. Did you 'trim' that out?

What if the row is in the other direction? What if it is already in the correct row?

Incremental Suggestion

Generally, when presented with problems like this it often helps to generalize the problem....

For example, if you create a concept called a 'direction', which is a two-value pair, say an int[2] (keeping it consistent with your code). If the target is at coordinate [0,0] and the current position of the tile is at [2,2] then the direction is [-1,-1] (you need to be reducing the row/column coordinates by 1 to get to your target.

Then, your while loop can become:

int[] goal = findGoal(tileNr);
int[] current = findTile(tileNr);
int[] empty = findTile(0);
for (int[] direction = getDirection(current, goal);
           direction[0] != 0 || direction[1] != 0;
           direction = getDirection(current, goal)) {

    if (direction[0] != 0) {
        // find a way to move things in the row axis
        // do this by getting the empty space where we need to move to....
        ......
        // swap our tile with the empty space.
        empty[0] -= direction[0];
        current[0] += direction[0]; // update the current position.
    } else { // direction[1] must be != 0
        // find a way to move things in the column axis
        // do this by getting the empty space where we need to move to....
        ......
        // swap our tile with the empty space.
        empty[1] -= direction[1];
        current[1] += direction[1]; // update the current position.
    }
}
// to exit the loop, direction == [0, 0] ... i.e. we are at our target.

Bigger suggestion

In this case I would consider a significantly different data structure.... :

Create a Tile Object for each Tile.
The GameState instance will then just become a loose collection of Tiles.
Keep the tile location embedded in the Tile instance.
Treat the empty space as a tile, and the 'rule' is that the Empty tile is the only tile that can swap positions with it's neighbour.
You can embed the logic in to methods on the Tile to identify the tile position and directions.

Doing the above can reverse a lot of your game logic, but the benefit will be that you move the logic out of the main methods in to the object orientation....


How to combine items in List to make new items efficiently

The code you have posted looks ok, but could be improved.

Splitting code into methods is a good thing, but in this case it would have been better if you kept it in the IsMatch() method because you could return early. In its current form you are first creating all combinations of the splitted filename and then you check if the returned list contains the objectname.
If a parametername is a compound word you should name the parameter using camelCase casing. This means objectname and filename should be objectName and fileName.
Omitting braces {} although they might be optional can lead to hidden and therefor hard to find bugs. I would like to encourage you to always use them.
Calling ToList() on an array if you don't use any method of List<T> is superflous if the only intend is to iterate over the elements. But as you have a List<T> segments it would be more common to use the AddRange() method instead of Concat().
You should always validate the parameters which are passed to a public method.

I would create a method which returns an IEnumerable<string> which iterates over an string[] if the Length of the arrayelement is equal to a desired length the method yield's the arrayelement otherwise it builds combinations of the current arrayelement with the following arrayelements.

Because this method is returning an IEnumerable<string> which is executed in a deffered and by using the Any() method which returns as soon as the passed condition is true we would also return early.

I have taken the initial method from generate-combination-using-string-array-in-c-sharp and adjusted it to our needs

private static IEnumerable<string> CreateCombinations(string[] array,  int maxLength)
{
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i].Length == maxLength)
        {
            yield return array[i];
        }
        else
        {
            int length = maxLength - array[i].Length;

            foreach (string combination in array.Skip(i).Where(s => s.Length == length))
            {
                yield return string.Concat(array[i], combination);
            }
        }
    }
}

I would then extend the former IsMatch() method to take a char[] array as well. In this way you wouldn't need to touch the method again if e.g the separators should change.

This method would look like so

public static bool IsMatch(string fileName, string objectName, char[] splitChars)
{
    if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); }
    if (objectName== null) { throw new ArgumentNullException(nameof(objectName)); }

    var segments = fileName.Split(splitChars);

    return CreateCombinations(segments, objectName.Length).Any(s => s == objectName);
}

But it would look neater if we make an extension method out of the CreateCombinations method like so

public static IEnumerable<string> CreateCombinations(this string[] array, int maxLength)
{
    if (array == null) { throw new ArgumentNullException(nameof(array)); }
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i].Length == maxLength)
        {
            yield return array[i];

        }
        else
        {
            int length = maxLength - array[i].Length;

            foreach (string combination in array.Skip(i).Where(s => s.Length == length))
            {
                yield return string.Concat(array[i], combination);
            }
        }
    }
}

and the IsMatch() method would look like so

public bool IsMatch(string fileName, string objectName, char[] splitChars)
{
    if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); }
    if (objectName== null) { throw new ArgumentNullException(nameof(objectName)); }

    return fileName.Split(splitChars)
                   .CreateCombinations(objectName.Length)
                   .Any(s=>s==objectName);

}


Converting entire table to JSON data. Is there a better way?

Yes, there sure is. Effectively, what you seem to be doing can be reduced to this:

$stmt = $dbh->query("SELECT * FROM " . $table);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);

I'll explain how I got to those three lines above, simplifying your code step by step.
The inner loop just does not make sense:

foreach($val as $key2 => $val2){
    $temp[$key2] = $val2;
}
array_push($data, $temp);

What this does, is iterate over $val, which is either an iterable object, or an array. When doing so, you're creating a new array $temp, which is, essentially an array-version of $val. Of course, $temp is never "cleared", so the second time the inner loop is performed, $temp will be assigned new keys and values.
In short, suppose $temp looks like this, after the first iteration:

array('foo' => 123);

Then $data will look like this:

array(array('foo' => 123));

The second time, $temp might look like this:

array('bar' => 1234, 'foo' => 123);

Or, if $val had a key/property called foo, then $temp['foo'] will simply be reassigned to the new value, and $temp will look like

array('foo' => 'new value');

Either way, $data will look like:

array(array('foo' => 123), array('foo' => 'new value'));

But why the loop? Why don't you simply cast the $val to an array, and push it into the $data array?

foreach($result as $val)
{//you're not using the $key anywhere, so you can omit it
    array_push($data, (array) $val);
}

That's a hell of a lot shorter, isn't it? But you can simplify this even more. You're fetching the result as objects, only to convert it to an array. Why don't you just fetch the results as an array from the off? Simply change:

$result = $query->fetchAll(PDO::FETCH_CLASS);

To this:

$data = $query->fetchAll(PDO::FETCH_ASSOC);

You won't need the loops at all after this.
Just as an asside, fetching the results of a query is often done using a while loop. I'll save you the inner-workings-details, but last time I checked, a while loop was actually marginally more performant than a fetchAll call... The only way to be sure is to benchmark both versions, but I tend to prefer the following:

$data = array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $data[] = $row;
}

Ah well, the result is the same, anyway.

Other thoughts:
There are a couple of things you might want to consider, too:

$query = $dbh->prepare("SELECT * FROM " . $table);

Is not the safest way to go about your business: What is the value of $table? If it's a value that comes from the client-side, who's to say it doesn't contain an invalid table name? something like another_db.secret_table would make for the following query:

SELECT * FROM another_db.secret_table

Fetching data that possibly wasn't intended for the client to see. That's a security issue. And a big one at that.
Next, the variable $query is not the best name. PDO::prepare returns an instance of PDOStatement, which is a prepared statement, which isn't a query anymore. That's why you often see the return value of PDO::prepare being assigned to a variable called $stmt.

Either way, with a query without a WHERE clause, prepared statements only cause more overhead. You're better of executing it from the off. Prepared statements are there when you want to insert variables into a query:

$stmt = $pdo->prepare('SELECT * FROM tbl WHERE field = :fieldVal');
$result = $stmt->execute(array(':fieldVal' => $_POST['fieldVal']));

As an added bonus, you can re-use the same prepared statement over and over, to perform the same query a couple of times:

$stmt = $pdo->prepare('SELECT * FROM tbl WHERE field = :fieldVal');
$vals = array('foo', 'bar');
foreach($vals as $val)
{
    echo 'Executing query with value: ', $val, PHP_EOL;
    $result = $stmt->execute(array(':fieldVal' => $val));
    //process $result...
}

The code above will perform the same query twice, once for the value "foo" and once with the value "bar".


An example of transferring the C ++ class hierarchy to Golang. Is it done correctly?

This:
g := new(AbstractGenerator)
g.implementation = i
return g

Can be more simply written as:
return &AbstractGenerator{implementation: i}


Created a basic User Profile List using an API (React)

my two cents.

if what I'm writing is good enough to be considered for a Jr. React Dev position

This answer is completely subjective and depends on the company you're applying to. Each company has different expectations.
That being said, here are a list of improvements that I think (from my own personal experience) would make your profile stand out among other candidates for a job position.

Companies want developers with an understanding on the product. Did you simply implement the feature? Or did you go out of your way to think of important situations potential clients might encounter.

i.e.:

When you make API calls, did you use a spinner to let the user know that the list of users is being fetched from you API ?
Did you plan out/work on your design? Did you follow the design system?
Did you implement a global theme?

Avoiding writing pure text in your components, think ahead and start putting them in localized files so that you're one step ahead if the website needs translation.

Don't define a component within a component unless you don't have any other choice (i.e.: UserProfile / userProfile)

UserProfile (singular) returns a list of userProfile's? Doesn't seem right.

I think I would rename UserList --> Users / UserProfile --> UserList / userProfile --> UserProfile

Did you write tests ?


Is this non-recursive mergesort efficient and a good way to simulate the recursive version?

I have not looked into it too deeply to be able to fully answer your first question. Althought for you to get a picture of efficiency I would suggest to take the normal recursive merge sort and time it using System.nanoTime() and compare it with this version on the same array to be sorted. That could give you a picture about time complexity and regarding memory you would have to use a profiler. Simply jconsole can be enough in this case to see the memory consumption - careful with the GC kicking in when you don't want it.

Second question:
I am not saying that it would be a bad looking code but I have difficulties to understand it. I would suggest few improvements that can help the readability. For example the first one in the method partition - instead of having the whole code block in if (ar.size() > 1) I would suggest having if (ar.size() <= 1) then do return. This gets rid of one level of curly braces for the rest of the code block.

Another suggestion would be to use instance variable as least as possible, in this case loBound = 0, hiBound = 1 and ar. There is a "Brook's law for methods" that says that method should be passed necessary variables as parameters if possible, if not then accessing instance variables and so on. Besides it is some statement it is also improves readability if the method changes only parameters it got passed and not instance variables. You can better track what is being changed and returned in and from the method.

From where I am sitting the main downside of this code would be to come to it half year later and figure out what it does and if it does it right. I would say even the author of the code would have to take some time to figure it out.

I am sorry I might not help you with your first question. Hope the comments on the second one regarding the code style could be of use for you.


Know when to use which feature

C++11 offers range based for loops so you should use them instead of for_each with lambdas:

for(auto i: values) {
    if (0 == number % i.second) {
        out << i.first.c_str();
        found = true;
    }
}

As you can see this facilitates auto instead of the ugly decltype hack.

Don't overuse static

Why are all the functions declared static? Are they part of a class?
If so, why?

Design: Unnecessary complexity

I have troubles tracing the algorithm in your code.
If you would really want an enterprise solution I would try to integrate with standards like iterators and function(/functor) interfaces that can be passed into algorithms like std::transform.


Project Euler Problem #5 Solution in C++

Code Review
Despite its name, "stdafx.h" isn't a standard header.  It doesn't seem to be needed, as the code compiles and runs without it.
Your indentation is off - perhaps that's a result of how you inserted the code into the question?
The continue is redundant - there's no more code within the loop after the if/else, so it can be omitted.
The code assumes that a result will be found before int overflows.  Remember that INT_MAX may be as small as 32767; perhaps unsigned long may be a better choice, or one of the fixed-width types specified in <cstdint>, perhaps?
Your loop structure would be clearer if you separate out the test from incrementing smallest multiple.  That could look something like this (still using int as our type):
#include <iostream>
#include <climits>

static bool is_multiple_of_all(int n, int max)
{
    for (int i = 10;  i <= max;  ++i) {
        if (n % i != 0) {
            return false;
        }
    }
    return true;
}

int main()
{
    const int target = 20;
    for (int candidate = 2 * target;
         candidate <= INT_MAX - target;
         candidate += target)
    {
        if (is_multiple_of_all(candidate, target)) {
            std::cout << candidate;
            return 0;
        }
    }
    // not found
    return 1;
}

Algorithm
Project Euler problems tend to exercise your mathematical reasoning.  You're expected to find better methods than brute force search to find the solution.  (Hint: think about prime factors).


It would be nice if the code was ordered for exposed functions versus internal helpers. It looks like buildAutomaton is the exposed API along with the Automaton data type. However, buildAutomaton is the one function missing any comments or docs.

trans looks a lot like maybe from the Prelude/Data.Maybe.

Use explicit imports to make clear where your functions are coming from.


Hiding multiple elements' parent container (by child element id)

That is pretty close to the optimal way of doing it.

Personally I would go for

//Hide items
$("#item2, #item3, #item6").parent().hide();


Generating public/private RSA key pair programmatically, using it for JWTs

There isn't too much to see here because the key generation simply relies on RSA.generate(2048), but I wonder why you would need this code as it is exceedingly shallow.

Regenerating key pairs for signing at startup is utter nonsense because a key pair is next to useless if the public key isn't trusted by the receiving party.

Exporting the private key as unprotected PEM is also very dangerous. The method would fail if hardware support (a HSM) is ever used.

The inclusion of  payload.update(dict(iat=datetime.utcnow())) is undocumented. Although it may be expected for webtokens, a caller will want to know that this is performed. Undocumented side effects are a sure fire way of breaking the principle of least surprise.

Passing kwargs** without any validation doesn't give me a very warm feeling inside.

Slightly less of an issue maybe, but an RSA 2048 bit key provides a key strength of only 112 bits or so. You may want to consider at least 3072 bits.

This code is clearly related only to webtokens and RSA keys, even with a specific key size. So allowing an argument algorithm: str='RS256' may just allow a user to get the object instance in an invalid state, and not much more.


There is nothing wrong about being "too Java 6"!
First few notes about naming and naming convention:

username is, in fact, the email, so should be email
getCensoredUsername for the same reason should be getCensoredEmail but in Java get, by convention, is used only for getter or when you're applying very little logic; thus is better to use an "action-subject" type of name like censorEmail
Being Java a type language, calling a variable chars is not helpful, that should be emailChars or even just email if that is not colliding with other variables, the compiler will tell you the type.

Biggest problem though, is the data validation, you should check at least that email is not null.
Normally you would check that the email is "valid" but if you take a look at the email syntax you might notice that's almost impossible to do it without writing a formal parser (or using some library). So let's say we want just censor the "reasonably valid" emails.
Your approach to go char by char in the username part is not very flexible: what if tomorrow you want to have f****o.f*****i@gmail.com? You need to add other flags, and wouldn't be very enjoyable.
I suggest you to start from the censor method and build bottom up from that.
Here is my solution
  public static String hideLastChars(String name) {
    Objects.requireNonNull(name, "String should not be null");
    if (name.length() <= 1) {
      return name;
    } else {
      return name.charAt(0) + IntStream.range(1, name.length()).mapToObj(i -> "*").collect(Collectors.joining());
    }
  }

Now that we have our "logic" we need to do a bit of input validation.
  public static String censorEmail(String email) {
    Objects.requireNonNull(email, "Email should not be null");
    String[] splitEmail = email.split("@");
    if (splitEmail.length > 1 && splitEmail[0].length() > 0) {
      return censorUsername(splitEmail[0]) + "@" + splitEmail[1];
    }
    throw new IllegalArgumentException("Please provide a valid email");
  }

Now we know that the email is not null, it does contain a '@' and user is there.
We just need to apply our hideLastChars to each piece.
We have a little problem here because if you just split on each . you will end up losing trailing dots, for example in an email like john.doe....@gmail.com.
A solution is to use Lookahead regexp to split on each . but keeping it in the split result, this is the regexp: ((?<=\.)|(?=\.)), for example "john.doe...".split("((?<=\.)|(?=\.))") will return { "john", ".", "doe", ".", ".", "." }
Now we know how to map each piece and how to extract it.
  private static String censorUsername(String username) {
    return Arrays
        .stream(username.split("((?<=\\.)|(?=\\.))"))
        .map(scratch_1::hideLastChars)
        .collect(Collectors.joining(""));
  }

I suggest you to create a unit test to test the logic so every time you find a new email that creates problem you can add in the test and see what happens (What about p.g@curry.com?).
I've run few examples using your code and mine. Here's the result

INPUT
ORIGINAL
REVIEWED

name.surname@gmail.com
n***.s******@gmail.com
n***.s******@gmail.com

name.surname.p99@gmail.com
n***.s******.p**@gmail.com
n***.s******.p**@gmail.com

name.surname.p99.@gmail.com
n***.s******.p**.@gmail.com
n***.s******.p**.@gmail.com

@gmail.com
@*****.c**
Exception: Please provide a valid email

user.com
user.com
Exception: Please provide a valid email

user%example.com@example.org
u***********.c**@example.org
u***********.c**@example.org

"john..doe..."@example.org
"****..d**..."@example.org
"****..d**..."@example.org

" "@example.org
"**@example.org
"**@example.org

null
Exception: Cannot invoke "String.contains(java.lang.CharSequence)" because "username" is null
Exception: Email should not be null

...p...g...@gmail.com
...p...g...@gmail.com
...p...g...@gmail.com

p.g@curryfication.com
p.g@curryfication.com
p.g@curryfication.com


Check whether a number can be dialed on a phone keypad without diagonal moves

There are a lot of different traits you could optimize for.  I like to optimize for lines of code, so I'll try that.

You can simplify the testing by building a "graph" (2-dimensional array) of reachable numbers.  Each row and column index is a phone digit.  If the value at (i,j) is true, then j is reachable from i.

To do this, take all the numbers in each digit's row/column and create an array where those indexes have a value of 1.

The reachability graph looks like this:

The digit 6 can reach 3,4,5,6,9 and you can see that reachable[6][x] is true for x=3,4,5,6 or 9.

Then simply run through the list of numbers and test if reachable[current][next] is true.

I've assumed the rook can dial repeated numbers like 3333.  If no, you can test for that in the graph creation or during reachability testing.

function rookTraversal(rows, phoneNumber) {
    var cols=rows[0].map((col, i) => rows.map(row => row[i])),
        digits=phoneNumber.match(/(\d)/g),
        reachable=[];
    for (var row = 0; row < rows.length; row++) {
        for (var col = 0; col < cols.length; col++) {
            reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, [] );
        }
    }
    // console.log({reachable,digits});
    for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;
    return true;
}

var data = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

console.log(rookTraversal(data, '4631782'));
console.log(rookTraversal(data, '4853267'));


A reusable Previous/Next Contact Collection ViewModel class

A couple of comments:

It looks like the class only manages parties. This is nice SRP.
Use StyleCop, it makes code much easier to read and review.
Validate inputs, makes it much faster to find and fix bugs:

public PartiesViewModel(ObservableCollection<Party> parties)
{
    if (parties == null)
    {
        throw new ArgumentNullException(nameof(parties));
    }
    ...

Party = Parties.FirstOrCreateIfEmpty(); without knowing what this extension method does I don't love it as it requires me to navigate to another place in the code to see what it does. I guess it does something like this:

Party = Parties.FirstOrDefault() ?? new Party(...);

If this is the case I think you should drop the extension method.
Party.PropertyChanged += UpdatePartyShortNamesList;

I can't see that this subscription is updated anywhere. I would expect the subscription to be removed from the old party and added to the new party in the setter for Party. As it is now it is probably a bug and a memory leak.
public ObservableCollection<Party> Parties { get; set; } a public setter here suggests that the collection can be replaced (without notifying the view about it). I assume you want it to be a readonly property. This also applies to the command properties.

In C#6 you express this as:

public ObservableCollection<Party> Parties { get; }

Prior to C#6 this was slightly more verbose:

private readonly ObservableCollection<Party> _parties;

public PartiesViewModel(ObservableCollection<Party> parties)
{
    _parties = parties;
}

public ObservableCollection<Party> Parties
{
    get { return _parties; }
}

Being explicit about what is readonly is a very good habit as it makes code easier to reason about and lets the compiler catch more bugs.
I have a feeling that binding SelectedIndex can simplify things a lot.
The command methods CanPressPrev etc. shall probably be private as the commands are normally the exposed means to interact with the viewmodel.
About reuse, this class looks like a nice candidate for composing with. Inject it in other viewmodels where the contact list is needed.

This got long, ending here.


Getting a local file with file_get_contents

As @KIKO stated, this is a bit dangerous to use relative paths (here, contents/ which is ./contents) because if your php script becomes included or reused, relative path (.) may points to a different location.

You can create a constant or put that absolute path in a config file. At the end, you'll check that the absolute path given by user is beginning by the expected absolute path:

define('THIS_ROOT','/this/is/my/file/root/');

function path_check($path) {
   return strncmp(THIS_ROOT, realpath($path), strlen(THIS_ROOT)) == 0;
}

If the given $path does not exist, realpath will return false so this check manages both security and resource existence.


Comments

The comments such a This is Mean. are pointless.

And the comment

// To call/run this function we can type mean(Your array of numbers separated with commas ',');

is a bit strange. Are they targeting people who don't know basic JavaScript syntax? Then why mention commas, but not the brackets ([...]) needed for an array.

It probably would be a good idea to instead use a standard comment format for documentation such as jsdoc.

Sorting

The comparison function used for sorting ((a, b) => a - b) is pointless, because that is the default.

Mutating the input array

In median you are creating a copy of the input array with .slice() before sorting it, so that it isn't modified, which is a good thing. You should do the same in mode and range.

Validating the input

You should consider validating the input. mean, mode and range break or give unexpected results if you give them an empty array. It's probably best to check if they are receiving an array at all.


I'm only going to scratch the surface here, and leave more seasoned java reviewers take a stab at this one, for I've never written a line of java-8 - but some concepts transcend language barriers.

Naming in particular.

Signatures can, and should talk.

public void addView(String viewString, View view) {
    views.put(viewString, view);
}

public View getView(String viewString) {
    return views.get(viewString);
}

Take this line:

public void addView(String viewString, View view) {

The name viewString is pretty confusing. One has to look at how it's implemented to go "oh, that's a key for a hashmap!". How about this instead?

public void addView(String key, View view) {

Now there's no ambiguity whatsoever, and getView(String key) becomes crystal-clear.

Consistency is King

This is just a minor thing, but I'd prefer consistency in the choice of verbs used to describe an action. For example, if a form is a view and a form gets shown, then a view should be shown too, not opened:

public void openView(String viewString) {
    getView(viewString).showForm();
}

Would be

public void showView(String viewString) {
    getView(viewString).showForm();
}

Same with commands - if a command executes, I wouldn't want the verb run to refer to the same thing, I'd prefer it be consistent:

public void runControllerCommand(String commandString) {
    commands.get(commandString).execute();
}

Would be:

public void executeControllerCommand(String commandString) {
    commands.get(commandString).execute();
}

Single-letter identifiers

Don't. This:

ModelContainer(Controllerv2 c) {
    this.controls = c;
}

Is pretty darn confusing. Does c stand for controller, or for controls? Actually there seems to be something fishy going on here, "controls" is a nice name for a collection of controls, but you have it as ..a Controllerv2 (is there a Controllerv3? Avoid "versioning" classes like this, especially in the early development stages). Notice the puzzled expression in my face? ;)

Anyway, that c would probably be better of as controller.

Constructor arguments

I like this part - final makes your intent very clear:

private final Map<String, Model> models = new HashMap<>();
private final Map<String, ModelCommand> commands = new HashMap<>();
private final Controllerv2 controls;

ModelContainer(Controllerv2 c) {
    this.controls = c;
}

I'd push it a step further though, and provide a way to initialize the class with models and commands, like this:

private final Map<String, Model> models = new HashMap<>();
private final Map<String, ModelCommand> commands = new HashMap<>();
private final Controllerv2 controller;

ModelContainer(Controllerv2 controller, Map<String, Model> models, Map<String, ModelCommand> commands) {
    this.controller = controller;
    this.commands = commands;
    this.models = models;
}

And now the client code doesn't need to call AddCommand 20 times when there's that many commands to add.

Indentation

Your indentation is a little off, too. Whenever a code file ends like this:

}
}

You know something's gone wrong. I'd blame it on the Java-style braces but that's just the c# mug talking, just select all but the signature and last closing brace, and give that Tab button some lovin' ;)


Make it simpler, you can use read-only properties:

public class User
{
    public string FirstName { get; }
    public string Surname { get; }
    public string Email { get; }

    public User(string firstName, string surname, string email)
    {
        FirstName = firstName;
        Surname = surname;
        Email = email;
    }
}

Now let's consider to make it closed, I do not see any extension point then if you don't have any other requirement against this you should also mark it as not inheritable:

public sealed class User

What next? Make it safer. Your class and its ctor are public then you should validate parameters:

public User(string firstName, string surname, string email)
{
    if (firstName == null)
        throw new ArgumentNullException(nameof(firstName));

    if (surname == null)
        throw new ArgumentNullException(nameof(surname));

    if (email == null)
        throw new ArgumentNullException(nameof(email));

    FirstName = firstName;
    Surname = surname;
    Email = email;
}

If you're using C#7 then consider to use throw exceptions (see pgerchev's comment and t3schb0t's answer).

Class has not to be public? Remove public from its declaration. Constructor is not intended to be called outside your own assembly but class has to be public? Mark ctor as internal and assert  about its arguments.

Note about Debug.Assert: obviously this does not mean you won't need to validate somewhere these arguments (see also comments) when building in release mode, just that here you assume they're right. See also Exception Vs Assertion, consider pre/post-conditions not an alternative to validation but - sort of - run-time unit testing:

internal User(string firstName, string surname, string email)
{
    Debug.Assert(firstName != null);
    Debug.Assert(surname != null);
    Debug.Assert(email != null);

    FirstName = firstName;
    Surname = surname;
    Email = email;
}

Do you need any other validation (email has not to be empty and it has to be a valid e-mail address, for example)? Add them all there. Be careful with people's name validation (see David's linked post).

Anything else? Make it easier to debug:

[DebuggerDisplay("{FirstName} {Surname} ({Email})")]
public sealed class User

Last note: yes, there is an [ImmutableObject] attribute you may use to decorate your class but AFAIK it's used only by PropertyGrid control. You may add it as reminder (for you or for future readers) that class has to be immutable but nothing else.


I find this pretty nicely done and really hard to pick on.
But here's a little something.
Instead of writing this condition this way:

WHERE Posts.CreationDate <= @today
  AND Posts.CreationDate > @target_week

This is shorter and simpler:

WHERE Posts.CreationDate BETWEEN @target_week AND @today

Keep in mind though that's not exactly the same,
because if I remember correctly,
BETWEEN uses <= and >= conditions.
But even if so, it might not make a difference anyway in the case of this query.
(I confirmed with 1 week to go back, the results are identical.)

Btw, @Malachi pointed out an excellent article about range queries and their dangers.

A very minor nitpick, but in this column alias I would spell out the "dvote" nicely as "downvote":

  SELECT Votes.PostId AS dvote


How can I optimize my insert function for the cuckoo hash table?

For one thing, I would suggest using a better name for your helper-function, that describes what it does:

def _find_insert_path(...):

Note the leading underscore - this is Python convention for "don't call this directly from outside the class". Users should call insert, which doesn't have the underscore.

Second, you could use exceptions to do handle the case where the insertion depth is exceeded more cleanly. Alter _find_insert_path to do:

if displacements > self.maxDepth:
    raise KeyError("Maximum insertion path length exceeded.")

Which makes insert use:

try:
     min_insert_way = self._find_insert_path(key, [], 0)
except KeyError:
    self.excess.append(key)
    return -1
...

Note the call to _find_insert_path; this is an instance method, you don't need to call it on the class and pass the instance Cuckoo.method(self, ...) you can call it directly on the instance self.method(...).

This:

for i in range(0, len(self.funcs)):
    if self.table[self.funcs[i](key,self.size)] == None:
        return [i]

Is a pretty awkward way of looping over self.funcs, not least because the start argument to range already defaults to 0. Instead, use enumerate:

for i, func in enumerate(self.funcs):
    if self.table[func(key, self.size)] is None:
        return [i]

Note that I am testing for the singleton None with identity (is) not equality (==) per PEP-0008.

Your loop over min_insert_way is similarly awkward; creating and incrementing your own index is usually a sign you're doing something wrong. You could instead use:

for function_index in reversed(min_insert_way):

Fianlly, it seems odd that your helper function returns a list of indices for self.funcs. Instead, why not have it return the list of indices within self.table to which each item in turn is moved? Then you don't have to call the hash functions at all in insert, which becomes much simpler:

def insert(self, key):
    if self.find(key):
        return None
    try:
        path = self._find_insert_path(key, [], 0)
    except KeyError:
        self.excess.append(key)
        return -1
    for index in reversed(path):
        key, self.table[index] = self.table[index], key
    return path[-1]

Note the parallel assignment of key and the value at self.table[index]; this uses tuple packing and unpacking to replace three lines of code with one and remove the temporary variable replaced_element.

This will also make the loop I mentioned above even simpler; you don't even need enumerate:

for func in self.funcs:
    i = func(key, self.size)
    if self.table[i] is None:
        return [i]

You could also make it neater using default arguments:

def _find_insert_path(self, key, path=None, depth=0):
    if path is None:
        path = []
    ...

Now the call from insert is simply:

path = self._find_insert_path(key)


Bugs/Correctness

In the binary search, when a good value (that is when valid returns true) is found, your code doesn't save it before trying to optimize it further.

if valid(distances, mid, k):
    h = mid - 0.1 # Now the best value is lost.

The best way is to save the best distance you found so far.

if valid(distances, mid, k):
    best_so_far = mid
    h = mid - 0.1
...
return best_so_far

(v - distances[i-1]) / mid, now if the distance between the stations is 6 and mid is 3, the result will be 2, while you really only need to add 1 gas station. What you really wanna do is to get the ceiling of distance / mid which will give you the number of pieces of length mid, then subtract one to get the number of gas stations in the middle. So math.ceil(distance / mid) - 1.

Code Style

Overall I think the code is really clean, with clear variable names and good modularity.

The part that gets the max distance between every 2 elements

max_distance = 0
for i, v in enumerate(distances):
  if i > 0:
    max_distance = max(max_distance, v - distances[i-1])

Could be written in a more pythonic way as:

max_distance = max(a + b for a, b in zip(distances, distances[1:]))

The method name valid is not really readable, also the variable names mid and k are not expressive. So I would rename it to something like.

is_solvable(distances, distance_required, additional_stations)


Converting a list of lists to a list of objects

Here's a functional solution which I think is cleaner and makes what you are actually doing (essentially extracting columns from the data) more clear.

I put the explanation inline as comments:

function plotlyFormat(data) {
  var data = data.slice(0),         // make a copy
      headers = data.shift(),       // remove header row and save it
      x = column(data, 0);          // calculate the x property, same for all objects

  // Create the objects, each one's "y" data is just a column
  // of the original data

  return headers.map(function(name, i) {
    return {x: x, y: column(data,i), name: name}
  }).slice(1);

  // ^^^ the final "slice(1) above removes the first record,
  // since it's the "Marker" column, not an actual sample

  // simple utility function to extract a column from a nested array (matrix)
  function column(matrix, i) { return matrix.map(function(row) { return row[i] }) }
}

Just call the function on your input data, and it will return it in the format you want.

And an uncommented version, to see the character savings :)

function plotlyFormat(data) {
  var data = data.slice(0),
      headers = data.shift(),
      x = column(data, 0);

  return headers.map(function(name, i) {
    return {x: x, y: column(data,i), name: name}
  }).slice(1);

  function column(matrix, i) { return matrix.map(function(row) { return row[i] }) }
}


Conversion Helper with support for enumerations and Nullable - The Remix

As a good bit of time has passed, and no additional feedback seems to be incoming, I'm posting this answer so that I can close the loop on this question.

The only feedback I might give -- and it's a small optimization -- is to move this code:

Type nullableType = Nullable.GetUnderlyingType(originalType)

I think it would be slightly better to put it after the check to see if the value parameter's type equals the generic type parameter's type, as there exists a chance that the method will not need that variable at all if the types are equal.


In list->num you can count down with something like for i downfrom n.

(defun num->list (n)
  (loop for c across (write-to-string n)
        collect (parse-integer (string c))))

In above function you can just collect (digit-char-p c). The function returns the digit value as a number.


Create custom Queue class with O(1) Enqueue and O(1) Dequeue

This is your bottleneck in retrieving the new head at removal, which can not be avoided in a Singly-Linked structure, so it's \$O(n)\$.

while (temp.Next != head)  // Get the previous Node of the head
    temp = temp.Next;

Doubly-Linked

If you want fast removal \$O(1)\$, you can do so at the cost of slightly slower insertion. You'd need to augment the queue to a doubly linked queue:

var previous = head.Previous;
head.Previous = null;
head = previous;
head.Next = null;

Make sure at insertion, you'll set both Previous as Next references on the relevant nodes.

Circular Doubly-Linked

If you make the queue circular, you don't even need to store the tail, only the head. The tail would be head.Previous; In case of a single element, since it's circular, head.Previous would point to head. Make sure in iterators to terminate at head, instead of at null.


Number to word converter (1 to 99 inclusive)

The code is broken. If a number is greater than 20 and ends with 0, print1to20(num_b) will not do what it should.
Don't mix the logic with the output. I'd change the return type of your functions to std::string. It'll make the code more testable and reusable.
Don't just print something to std::cout in a case of an error. Throw an exception instead.
Declare each variable as late as possible:

int num_a, num_b; // num = (a)(b);
num_a = num - num%10;
num_b = num%10;

should be

int num_a = ...;
int num_b = ...;

Use more descriptive names. I have no clue what num_a mean. What is a? Something like first_digit and second_digit would be better (well the first one is not exactly a digit, so you can come with even better names).
There's no need to return 0 from the main function explicitly (sure, you can if you want to).
Write proper automated tests for your code to reduce the number of bugs (your bug is very likely to get caught by tests). In fact, you can check all possible valid inputs. There're only 100 of them.
There's nothing wrong in having stand-alone functions. There's no entity here, so I don't see the point of modeling this problem in terms of objects. A function from an int to its string representation is just a function.


@neo pointed out that dx can be calculated as (1 - r) * Math.cos(a - b).  Similarly, dy = (1 - r) * Math.sin(a).  However, when you take dy / dx, which is what Math.atan2(dy, dx) implicitly does with its arguments, the (1 - r) factor cancels out.  You can also see, using a geometric argument, that (x2, y2) is pointless (pardon the pun).

Therefore, Math.atan2(y1, x1) would work just the same as Math.atan2(dy, dx).

So far, your function can be simplified to the following.  Since you repurposed angle twice, I need to disambiguate them as alpha, beta, and theta for this discussion.

public static inline var ISO:Float = 0.45378560551; // (116-90) / 180 * PI=;

function convert(alpha:Float):Float
{
  var beta = alpha - Math.PI; // corrected angle

  // calculate new line, using isometic angle.
  var x1 = Math.cos(beta - ISO);
  var y1 = Math.sin(beta);

  var theta = Math.atan2(y1, x1);
  return theta;
}

But wait, there's more!  There's a mysterious correction from alpha to beta, and the cosine expression is complicated.

Let's start with Math.sin(beta).  That's Math.sin(-alpha), or -Math.sin(alpha).

It would be nice to say Math.atan2(Math.sin(alpha), something) instead of Math.atan2(-Math.sin(alpha), something).  Let's move the negation into the denominator then, for var theta = Math.atan2(Math.sin(alpha), -x1).

Can we simplify -x1?

-x1 = -Math.cos(beta - ISO)
    = Math.cos(beta - ISO + 180°)
    = Math.cos(alpha - 180° - ISO + 180°)
    = Math.cos(alpha - ISO)

So, your function simplifies to:

public static inline var ISO:Float = 0.45378560551; // = (116-90) / 180 * PI

function convert(angle:Float):Float
{
    return Math.atan2(Math.sin(angle), Math.cos(angle - ISO));
}

Not only is the code more efficient, it's also less mysterious: the transformation is taking the x-coordinate of each point as if it were rotated 26° clockwise!

I have to question the motivation behind this function, though.  This isn't an angle-preserving transformation, so why are you operating on an angle?  Normally, you transform points' coordinates using matrix multiplication.


Tools for transferring data from an API to a database

Styling and readability
Your indentation and use of whitespace is all over the place. Make sure to use consistent indentation. If you decide to add whitespace somewhere, use the same rules for whitespace elsewhere. In particular, pay attention to where you place your braces. Sometimes you put them on a new line, sometimes you do not. Sometimes you put the closing brace before a corresponding catch, sometimes you place a newline. Sometimes you indent it, sometimes you do not. Choose a style, and use it for all function definitions, for-loops, try-catch blocks etc.
Many connections
For each action you make a separate connection. You can improve the performance of your script by creating one connection, and make every query use that connection instead.
General bugs
file_get_contents(..) returns FALSE on failure. The documentation is not concise about this, but I assume that a timeout will cause it to fail. Your script should do something sensible in this case instead of trying to decode it as json.
json_decode(..) returns NULL if the result cannot be decoded properly (e.g. someone replaced the resource to "Use v.77.2 you silly goose") or the recursion limit is exceeded. You do not check for this condition.
If one of the inserts fails, do you really want to just ignore that insert and continue inserting? Do you really not want to retry it at the very least (in case of a failed connection for example).
Maintainability
You are using magic values in some places. The table name r_vehicle_manufacturer is one example of that. $url = manufacturerEndpoint; looks weird to me and might be an other one if that is your way of anonymizing the code.
This seems to be an (incomplete) class definition. I feel that the function to retrieve data from an api and the functions to interact with the database should not be in the same class.


Does anyone know why I am seeing the character 8 appended to the output of xor decrypted data?

The statement echo lol pipes lol\n\r to Python, which encodes the line breaks as ;_ which is decoded into an 8. Unfortunately echo -n doesn't work here but adding .strip() to the input data in the Python script fixes this issue.

PEP8 is Python's internal coding standards which specify how line breaks and code should be structured: https://www.python.org/dev/peps/pep-0008/ . The guide is very long; you can use autopep8 to auto-format the code.

    if raw:
        ret = xor(data, key)
        print(str(ret))
    else:
        if is_base64(data):
            # print('is base64')
            decoded = base64.b64decode(data).decode()
            ret = xor(decoded, key)
            print(ret)
        else:
            # print('is not base64')
            ret = xor(data, key)
            encoded = base64.b64encode(bytes(ret, "utf-8"))
            print(encoded.decode())

I would simplify the nested if-statements and add a return to print(str(ret)) then the is_base64 could be unindented, or I would set a variable called decoded to the final string to print, then print it out at the end of the if/elif loop.

is_base64(s) could just run base64.b64decode(data).decode() and return False if any exceptions were thrown during decoding instead of the regex.

I would remove the commented out code such as # print('is base64').


Calculate the difference between current date and age from personal ID

In this answer I'll just reveiw the way you calculate the age difference.
So first, I would like to mention, that you should really work with four-digit numbers for displaing years - if that's possible for you.

In the suggestion below you'll see, that I don't compare the years, months and days because comparing two timestamps is better!
So you just have to feed the is25YearsOld function with a yyyymmdd-date and it will tell if you are older/younger than 25.

function is25YearsOld(input) {
    // the date of birth of a 25 year old
    var dob25 = new Date();
    // setFullYear to the current year (eg. 2016) and subtract 25
    dob25.setFullYear(dob25.getFullYear() - 25);
    // set the time to midnight
    dob25.setHours(0);
    dob25.setMinutes(0);
    dob25.setSeconds(0);
    // get the unix-timestamp
    dob25 = dob25.getTime();
    // the user's date of birth
    var dob = new Date();
    // set the year, month and day accordingly to the input
    dob.setFullYear(parseInt(input.substr(0, 4)));
    dob.setMonth(parseInt(input.substr(4, 2)) - 1); // (-1) because month is zero-based
    dob.setDate(parseInt(input.substr(6, 2)));
    // set the time to midnight
    dob.setHours(0);
    dob.setMinutes(0);
    dob.setSeconds(0);
    // get the unix-timestamp
    dob = dob.getTime();
    // if the timestamp of requiredDateOfBirth is smaller than the one of dateOfBirth, the user is too young
    return dob25 >= dob;
}

// Oct 10, 2008
document.getElementById("test1").innerHTML = is25YearsOld("20081010") ? "You are old enough!" : "You are too young!";
// Oct 10, 1988
document.getElementById("test2").innerHTML = is25YearsOld("19881010") ? "You are old enough!" : "You are too young!";

2008-10-10:

1988-10-10:


Simple memory pool using no extra memory

I see a few things that might be changed.

mp_init

First, consider checking the passed *mp variable to see if it's NULL at least within the mp_init call.  Alternatively, you could also allocate that structure within the mp_init routine and return a pointer to it or NULL on error.

The initialization is more complex than it needs to be. Rather than make repeated calls to mp_release and do all of that pointer manipulation, you could use this:

char *ptr;
for (ptr = mp->memory; --slots; ptr+=size)
    *(void **)ptr = ptr+size;
*(void **)ptr = NULL;
mp->head = mp->memory;

mp_release

Within mp_release, there is no error checking.  This might be OK if we're looking for extreme performance, but it might be nice to have at least a debug version that checks that mem actually points to a slot.  For that to work, of course, you'll have to add at least one more variable to the structure to contain the size parameter.

mp_destroy

In mp_destroy it might be prudent to set mp->head = NULL so that any subsequent mp_get attempts will fail.


Detecting a certain amount of violet in an image

Try using HSV/HSL to represent color instead of RGB.

You can then define violet as some hue range, e.g. 250° to 310° and similarly for saturation and lightness/value.

Always use a using when you have tempoary disposable resources like a Bitmap

Variables in C# are camelCase:

Boolean colourFound = false;
Bitmap selectedImage = new Bitmap(picture.Image);
Color selectedPixel;

Try to limit the scope of variables, move the declaration of selectedPixel to where you currently assign it.


You can combine these 3 tricks to resolve your problem:

Create your images as string buffers using StringIO. In Python 2 you can import it by: import StringIO; while in Python 3 you can import it by running: import io then use io.StringIO.
Read your images from a string: im = Image.open(io.StringIO.StringIO(buffer))
You can share the images you are interested in across your three modules by making them global variables (How do I share global variables across modules?).


Highlighting partitions in distinct color

I would change this
for i in range(len(partitions)):
    items = list(partitions[i])   # convert from set
    for j in range(len(items)):
        edge_color_list[items[j]] = get_color((i+1)/len(partitions)

to:
for idx, partition in enumerate(partitions): # I personally do it your way
    items = list(partition)   # convert from set
    for item in items:
        edge_color_list[items] = get_color((idx+1)/len(partitions)
        # idx is the `i` from before

I referenced this.
There might be a linting plugin to help align your code towards being pythonic


NodeJS script to dump data from Redis to Elasticsearch

I can see two problems with your script:

You are doing sync stuff in async. It is not recommended. Async is recommended for asynchronous operations. You are using it to do synchronous stuff - in the async.mapLimit block. Neither JSON.parse nor sh.unique is asynchronous. It is critical that you under the difference. Please read async docs on synchronous operations
You are buffering all your keys into memory. I guess that is a smaller problem, but it is less efficient than using a readStream.

Please take a look at my implementation and feel free to use any parts of it

'use strict';

const redis = require('redis');
const bluebird = require('bluebird');
const request = require('request');
const elasticsearch = require('elasticsearch');
const fs = require('fs');
const _ = require('lodash');
const async = require('async');
const sh = require('shorthash');
const sleep = require('sleep');
const config = require('../config');
const readline = require('readline'); //handy wrapper for readStream

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

let client = redis.createClient({
    host: config.redis.url,
    port: config.redis.port
});

let ES = elasticsearch.Client({
    host: config.elasticsearch.url,
    requestTimeout: 30000000
});

const readLineStream = readline.createInterface({ //this stream will serve keys one per line
    input: fs.createReadStream('no-keys')
});

let keysBuffer = [];
readLineStream.on('line', (line) => { // you were splitting with '\n' I guess your input is key per-line
    if (line) { //check for empty lines
        keysBuffer.push(line);
        if (keysBuffer.length === 1000) {
            migrateKeys(keysBuffer);
            keysBuffer = [];
        }
    }
});

readLineStream.on('end', ()=>{
    if(keysBuffer.length >0){
        migrateKeys(keysBuffer); // remember to flush your local buffer
    }
});

function migrateKeys(chunkOfKeys) {
    client.mget(chunkOfKeys, (mgetError, replies) => {
        if (mgetError) {
            console.error(mgetError); // Consider returning early
        }
        console.log('MGET complete from Redis');
        console.log('We have ' + replies.length + ' documents');

        let parsedReplies = [];
        replies.forEach((reply)=> {
            try {
                let content = JSON.parse(reply);
                parsedReplies.push([{
                    index: {
                        _index: config.elasticsearch.index,
                        _type: 'article',
                        _id: sh.unique(content.url),
                        _timestamp: (new Date()).toISOString()
                    }
                }, content]); // no need to filter out replies with parse errors
            } catch (e) {
                console.error(e);
            }
        }); //using async for sync code is not recommended

        console.log('Export complete with ' + parsedReplies.length);

        ES.bulk({body: parsedReplies}, () => {
            console.log('Import complete');
        });
    });
}


There's a minor bug there:

        if (pos > 0) {
            max = pos;
        }

should test pos > max instead.

Use

max = Math.max(max, pos)

to make it shorter.

  I'd like to know if I can make rand.nextInt(2) == 0 an easier condition to understand?

Use rand.nextBoolean(). For a probability of exactly 50%, it's perfect.

For other probabilities, you can use

 rand.nextDouble() < probability

Another possibility is simply

pos += 2 * rand.nextInt(2) - 1;
max = Math.max(max, pos);

or

pos += rand.nextBoolean() ? 1 : -1;
max = Math.max(max, pos);

or

private static final int[] DELTAS = {+1, -1};

pos += DELTAS[rand.nextInt(DELTAS.length)];
max = Math.max(max, pos);

without any conditionals. You may consider it tricky, but it isn't. Obviously, my last solution shouldn't be used for such a simple case.

Concerning the computation of max it may be slightly less efficient since it gets executed even if the value decreases. But this doesn't matter unless you need to optimize heavily (your print is many orders of magnitude slower than this).


I prefer this style:

  def print_flight_options_status(invitation)
    return not_allowed         if invitation.group.travel_class == 'none'
    return not_needed          if invitation.refused_flight_options?
    return waiting_reservation if invitation.selected_flights?
    return not_sent_yet        if invitation.flight_options.empty?
    return rejected            if invitation.requested_more_flight_options?

    waiting_guest_input
  end

UPD

About second code-snippet. I think in this case you can use decorators (for example draper) for invitations, so:

def print_event_terms_status(invitation)
  InvitationDecorator.decorate(invitation).status_in_html
end

Where InvitationDecorator:

class InvitationDecorator < Draper::Base
  def status_in_html
    if invitation.event_terms_status.nil?
      "Aguardando"
    ...
  end
end


Welcome to the wonderful world of deadlocks. In a nutshell: No, your “solution” is not adequate. Here is some pseudocode detailing what the two threads are doing. Note that a synchronized method aquires a lock on the object it is called on.

THREAD 1                             |     THREAD 2
IF:                                  |     IF:
synchronized (gary) {                |     synchronized (alphonse) {
  // gary.canBow();                  |       // alphonse.canBow();
  gary.canBow;                       |       alphonse.canBow;
}                                    |     }
THEN:                                |     THEN:
synchronized (alphonse) {            |     synchronized (gary) {
  // alphonse.bow(gary);             |       // gary.bow(alphonse);
  alphonse.canBow = false;           |       gary.canBow = false;
  ...                                |       ...
  // gary.bowBack(alphonse)          |       // alphonse.bowBack(gary)
  synchronized (gary) {              |       synchronized (alphonse) {
    ...                              |         ...
  }                                  |       }
  alphonse.canBow = true;            |       gary.canBow = true;
}                                    |     }

We can see that gary and alphonse can be locked at the same time. Especially, the bowBack.canBow() can return true in both threads. Then, even when the canBow boolean is volatile, both objects can wait for each other in a deadlock (in Thread 1, alphonse is locked and waits for gary. In Thread 2, the other way round).

You can make this deadlock more likely by increasing the time between the bowBack.canBow() and bower.bow() calls:

public void run(){
   if(bowBack.canBow()) {
       Thread.sleep(100);  // exception handling omitted
       bower.bow(bowBack);
   }
}

To solve these issues, you could impose an order or hierarchy on the friends, so that locks are aquired in exactly the same order in all threads (e.g. always synchronize on alphonse before gary). You could also decide that only one friend may initiate a bow at any time, e.g. via a semaphore.

But your implementation doesn't work.


For some perspective on the LoD, read "The Law of Demeter Is Not A Dot Counting Exercise".  In particular the part under the heading "I Fought The Law and The Law Won".

I think in this instance that pages, paragraphs and lines are very logical subcomponents of documents.  These each have different but related behaviour.  The each also serve different purposes.

Forcing the document to handle interactions with subcomponents will - as you say - lead to clutter (and more chance of introducing troublesome issues).

The big thing about the LoD is that it aims to reduce coupling.  However adding methods to Document doesn't really reduce coupling as you're still writing code that says "do x to line y" - you're just asking Document to do it for you.

Don't get me wrong, the LoD is useful.  But like all principles it has to be used correctly to stay useful.

(Funnily enough a similar question with a similar answer as been asked at SO.)

Conclusion

In short I don't see any benefit for you in talking to Document rather than it's contained Pages, Paras, & Lines.  Frankly I don't think there's any ROI for you.


TargetLibraryInforWrapperPass seems to have one r too many.
Try using auto a bit more extensively. Almost always auto
Did you really mean '\1' or should that be '1' in the following line? Either way, use a character-literal to make it obvious it's not an error.

if (Name.startswith("llvm.") || (!Name.empty() && Name[0] == 1) ||
                                                             ^

The same applies to using namespace llvm; as to using namespace std;:
Don't do it. Read "Why is “using namespace std” considered bad practice?" for why.


This is the longest possible answer to the shortest problem...

How to make better loops in python

iterables
for loops
range
list comprehensions
Generator expressions

How to improve this particular code

what is the simplest way possible of writing it
what is the shortest way possible of writing it

How to make better loops in python

1. iterables

For loops can iterate over any iterables. What is an iterable? An iterable is a object we can iterate through.

More seriously, an iterable is an object that is itself a sequence of other objects. A list is an iterable, but it is not the only one as you will discover when you learn more about python.

2. for loops

A for loop can iterate over an iterable (in this case a list) like so:

for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
    print(i)

3. range

The previous example is ugly because:
1. Hard-coded values can't be easily changed and are prone to mistakes.
2. We stored the first 10 positive integers in memory which take 144 bytes but it isn't scalable as if I want the first 1000000 positive integer, I would need 9 mo of memory.

That's where range comes in, it is an iterable that doesn't take much space and is often used in loops:

for i in range(10):
    print(i)

note: in earlier versions of python, range created a list and was equivalent to the first example.

What if I only want the numbers between 22 and 42 and skip every odd number:

for i in range(22, 43, 2):
    # range(start, end, step) <- this is a comment
    print(i)

note: the range(22, 43) doesn't actually include 43

4. list comprehensions

But wait, I don't want a 5 in my range, how can I remove it ?

for i in range(10):
    if i==5:
        continue
    print(i)

The technical term for continue is "ugly".

What you can use instead is this:

for i in range(10):
    if i!=5:
        print(i)

Which is better, but isn't what I want to show you. What I want to show you is list comprehensions:

l = [n for n in range(10) if n!=5]
for i in l:
    print(i)

A list is an iterable remember. Well, I've created a list containing the first 10 number except 5.

5. Generator expression

Remember also that I've said that a list was a very bad choice due to the memory inefficiency. Well fortunately for us, we have a better solution, generator expressions:

l = (n for n in range(10) if n!=5)
for i in l:
    print(i)

What changed ? Parentheses ! As easy as that.

But wait, I want to do the table of 5. How can I do that ?

l = (n for n in range(10) if n!=5)
for i in l:
    print(i*5)

Yes, that works, but what if...

l = (n*5 for n in range(10) if n!=5)
for i in l:
    print(i)

Yep, that also works...

How to improve your particular code

1. what is the simplest way possible of writing it

for i in range(10):
    if i!=5:
        print(i*5)

2. what is the shortest way possible of writing it

print('\n'.join(str(n*5) for n in range(10) if n!=5))
or
print(*(n*5 for n in range(10) if n!=5), sep='\n')

As you learn more about python, you might be tempted to use the second one. But it isn't pythonic because it violates at least 6 of Tim Peter's commandment:

  Beautiful is better than ugly.<
  Explicit is better than implicit.
  Simple is better than complex.<
  Complex is better than complicated.
  Flat is better than nested.<
  Sparse is better than dense.<
  Readability counts.<
  Special cases aren't special enough to break the rules.
  Although practicality beats purity.
  Errors should never pass silently.
  Unless explicitly silenced.
  In the face of ambiguity, refuse the temptation to guess.
  There should be one-- and preferably only one --obvious way to do it.<
  Although that way may not be obvious at first unless you're Dutch.
  Now is better than never.
  Although never is often better than right now.
  If the implementation is hard to explain, it's a bad idea.
  If the implementation is easy to explain, it may be a good idea.
  Namespaces are one honking great idea -- let's do more of those!

import this to read it at home

Some techniques of looping might be more appropriate in certain cases, but at least now you know what those techniques are.


Destroying a process if it takes too much time

First, I'm not too sure how your code works... your timeout starts after you begin to read the stdout of the spun Process object for non-null lines, but if you read the Javadoc of BufferedReader.readLine() again:

Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

If my understanding of how the stdout pipelining done by the Process object is correct (wells, this being OS-dependent and what-not), I think the end of Process.getInputStream() is reached when the native process is disconnected. In most scenarios, said process would have completed too, unless we are talking about starting daemon processes.
In other words, the timeout check becomes a dummy step when it is reached, and thread.isFinished() will most likely return true, always.
Second, since you are already on Java 7 at least, you should be relying on a combination of ExecutorService and Future implementations to achieve your goal as they arguably have better semantics for performing timeout checks.
For example, since all you need is to run one background thread, you can use Executors.newSingleThreadExecutor():
ExecutorService service = Executors.newSingleThreadExecutor();

Then, since you do not require a return value, you can submit() a Runnable, and call the resulting Future's get(long, TimeUnit) method:
Runnable runnable = createRunnableForProcessHandling(shell);
Future<?> future = service.submit(runnable);
try {
    future.get(timeout, timeoutUnit);
    // completed within timeout
} catch (TimeoutException e) {
    // do something about the timeout
} finally {
    service.shutdown();
}

The alternative is to submit() a Callable to get perhaps the output of the native process as a List, for further processing:
Callable<List<String>> callable = getOutputLinesFrom(shell);
Future<List<String>> future = service.submit(callable);
try {
    List<String> outputLines = future.get(timeout, timeoutUnit);
    // do something with outputLines
} catch (TimeoutException e) {
    // do something about the timeout
} finally {
    service.shutdown();
}


The most efficient way to merge two lists in Java

Exception Handling

Your handling is not great.... this is a sign of poor forward planning:

    catch(FileNotFoundException e){}

And this is a sign of something almost as bad:

    catch(FileNotFoundException e){ System.out.print("No Such File");}
    System.out.print("Done!");
    }

The first time I read that, I got confused and thought the "Done!" println was part of the exception handling. You need to work on the indentation. Also, just printing "No such file" is not a very helpful exception handling.

Style

1-liner blocks are seemingly convenient  but in the long term can have negative impacts on maintainability. You have a lot of them, and they make reading your code hard.

Your code is also suffocating due to lack of whitespace. You need to put spaces around operators to help the code to breath.... yeah, that sounds alarmist, but it really helps.

    File newFile=new File("mixOfLists.txt");
    try{
    PrintWriter writer=new PrintWriter(newFile);
    for(int i=0; i<array.length; i++){
        writer.println(array[i]);
    }

should be:

    File newFile = new File("mixOfLists.txt");
    try{
        PrintWriter writer = new PrintWriter(newFile);
        for(int i = 0; i < array.length; i++) {
            writer.println(array[i]);
        }
        ....

Resources

You should use try-with-resources for your IO sources and sinks. As things stand at the moment, you don't close the readers properly.

Algorithm

You're reading both files in to their own sets, and then merging the sets, and then outputting the result.

A better solution would be to use the boolean return value from the add(...) method to determine whether the word has been seen before... consider:

        while(s.hasNextLine()){
            String line = s.nextLine();
            if(hash1.add(line)) {
                writer.println(line);
            }
        }

The above code can be used for both the input files, and only writes out the word if the word has not been seen before.

This way you have only one set, and you do the merge at the same time as the reading.

Also, you should be using Java 8 streams..... hmmm... that would be nice.


Simple decorator for creating and managing a database cursor

No, I don't think this is a good approach. Anyone who sees the declaration def findItem(cursor, item_id): will call the function with two arguments and scratch one's head to no end when it does not work.

You could just as well have cursor = createDefaultCursor() as the first line of each function that uses a cursor. The number of lines does not increase as you can omit the @needsNewCursor line.

Even better might be to create a context manager to deal with opening and closing a cursor and start each function with a statement like with new_cursor() as cursor:. A context manager also has an opportunity to deal with exceptions raised in the with block.

Anyway, when writing decorators, instead of assigning yourself decorator.__name__ = func.__name__ you can apply the functools.wraps decorator that also copies the docstring.

One more thing: in your example needsNewCursor is a decorator. You should choose a different name for the inner function.


You have a bug:

((im.get_size(), pygame.SRCALPHA)

You have one too many ('s.

Where did the number 50 come from in the range call?

Don't use magic numbers; set and use a variable, probably called picture_amount.

When you are using string formatting to put the number x into the image name string, you should be using %d or %i because those are for signed decimal (base 10) integers; %s is used for strings, which x is not.

After scrolling through some pygame documentation, your method for clearing all is a very good one for pygame. I am assuming that the excessive slowness is coming from having to paint the image to a surface every time.

A faster way to do this would probably be to use an image editing library so that you don't have to paint the image every time; you'd edit the image in the background.

I sifted through the PIL python imaging library and came across a convenient method call image.eval. This method will iterate through every pixel in an image, call a function (passed via argument) passing in the pixel information, and reset the pixel value based on the function output.

This may or may not be slower than what you are already doing.

Putting it all together:

from PIL import Image

for x in range(image_amount):
    im = Image.open("horse%d.bmp") % (x)
    Image.eval(im, lamda pix: 0 if p == im.getpixel((0,0))) # Sets the pixel value to 0... change this if you want.
    Image.save("horse%d", "PNG") % (x) # This could raise an IOException

I could not test this code at the time so if you see any errors, let me know.


Replicate / Sync files from source to destination with powershell only

Frankly, robocopy.exe is such a good tool for this job and has been a part of the base Windows install since Vista/2008 that I would just use that instead of reinventing the wheel (especially when you're replacing a top fuel dragster wrinkle slick with an iron-shod wooden wagon wheel).  Yes, robocopy only uses datetime (LastWriteTime) and file size (Length) to detect changes, but if that doesn't work you're doing something rather strange.  That and the fact that Compare-Object is an awful command to work with because extremely unclear exactly what it's doing.

However, from a quick look:

$SourceRootFiles = Get-ChildItem $SourceRoot -Recurse
$DestinationRootFiles = Get-ChildItem $DestinationRoot -Recurse

These will both ignore Hidden and System files without the -Force parameter.

$CompareObjects = Compare-Object -ReferenceObject $SourceRootFiles -DifferenceObject $DestinationRootFiles -ErrorAction SilentlyContinue -IncludeEqual

As far as I'm aware the above only compares file name.  At the very least, you'll want to specify the parameters you're comparing with Compare-Object.  It does not compare all properties like you might expect.  You've got to specify them:

$CompareObjects = Compare-Object -ReferenceObject $SourceRootFiles -DifferenceObject $DestinationRootFiles -ErrorAction SilentlyContinue -IncludeEqual -Property Name, LastWriteTime, Length

However, even then, Compare-Object isn't going to work here when files move within the directory structure.

Example:

# Create two directory trees
$SourceDir = mkdir DirectoryA
$DestDir = mkdir DirectoryB
$DestDirSub = mkdir "$DestDir\DirectoryC"

# Create some files in the SourceDir
Push-Location $SourceDir
0..9 | ForEach-Object {
    Set-Content -Path $_ -Value $null
}
Pop-Location

# Copy the files
Get-ChildItem -Path $SourceDir -File | Copy-Item -Destination $DestDir

# Move some files to a subdirectory
Get-ChildItem -Path $DestDir -File | Select-Object -Last 5 |  Move-Item -Destination $DestDirSub

OK, now lets get the list of files.  0-9 should be in DirectoryA, 0-4 in DirectoryB, and 5-9 in DirectoryB\DirectoryC.  Now do the comparison:

# Fetch file lists
$Source = Get-ChildItem -Path $SourceDir -Recurse
$Dest = Get-ChildItem -Path $DestDir -Recurse

# Do comparison
Compare-Object -ReferenceObject $Source -DifferenceObject $Dest -IncludeEqual -Property Name, LastWriteTime, Length

I get:

InputObject SideIndicator
----------- -------------
0.txt       ==
1.txt       ==
2.txt       ==
3.txt       ==
4.txt       ==
5.txt       ==
6.txt       ==
7.txt       ==
8.txt       ==
9.txt       ==
DirectoryC  =>

And that's why I hate Compare-Object.

You can't just specify -Property FullName, LastWriteTime, Length or Compare-Object [...] -Property * either, since it's got the root part of the path in the properties.  You'll need to do something like this:

# Normalize the source and destination paths
$SourcePath = $SourceDir.FullName.TrimEnd('\');
$DestPath = $DestDir.FullName.TrimEnd('\');

# Fetch file lists
$Source = Get-ChildItem -Path $SourcePath -Recurse | Select-Object -Property *, @{n = 'RelativeName';e ={$_.FullName.Substring($SourcePath.Length)}}
$Dest = Get-ChildItem -Path $DestPath -Recurse | Select-Object -Property *, @{n = 'RelativeName';e ={$_.FullName.Substring($DestPath.Length)}}

# Do comparison
Compare-Object -ReferenceObject $Source -DifferenceObject $Dest -IncludeEqual -Property Name, LastWriteTime, Length, RelativeName

Alternately, you could do something like this using Tuples as the key in a Dictionary:

$SourceTable = @{}
$Source = Get-ChildItem -Path $SourceDir -Recurse | ForEach-Object {
    $t = [System.Tuple]::Create($_.FullName.Substring($SourceDir.FullName.TrimEnd('\').Length), $_.LastWriteTime, $_.Length)
    $SourceTable.Add($t, $_.FullName)
}

$DestTable = @{}
$Dest = Get-ChildItem -Path $DestDir -Recurse | ForEach-Object {
    $t = [System.Tuple]::Create($_.FullName.Substring($DestDir.FullName.TrimEnd('\').Length), $_.LastWriteTime, $_.Length)
    $DestTable.Add($t, $_.FullName)
}

# Files in source and dest and could be filehashed
$SourceTable.GetEnumerator() | Where-Object { $DestTable.ContainsKey($_.Key) }

# Files in source and not in dest
$SourceTable.GetEnumerator() | Where-Object { !$DestTable.ContainsKey($_.Key) }

# Files in dest and not in source
$DestTable.GetEnumerator() | Where-Object { !$SourceTable.ContainsKey($_.Key) }

That will be really fast once it's loaded all the tables, but it's really pretty gross to set up.


Printing all primes < 1,000,000 to a text file

You are doing brute-force trial division, and not particularly smartly. For example, you only need to test odd candidate factors up to sqrt(number).

When you want to find many prime numbers, a much better algorithm to use is the sieve-of-eratosthenes. It involves just addition, no division, and skips processing of numbers that are already known to be composite.


Reverse in terms of fold-right and fold-left

Your implementation of reverse using fold-left is correct.

In the case of reverse using fold-right, you may use snoc (described below) in place of append.  It looks better and its complexity is no worse than that of append, so there is no loss in efficiency:

(define (snoc e lis)
  (if (null? lis)
      (cons e lis)
      (cons (car lis) (snoc e (cdr lis)))))

(define (reverse sequence)
  (fold-right (lambda (x y)
                (snoc x y)) null sequence))

... or even more succinct:

(define (reverse sequence)
  (fold-right snoc null sequence))

It is curious that SICP's definition of fold-left swaps arguments to op (but retains the correct ordering of arguments to op in fold-right), resulting in the use of a rather tedious (lambda (x y) (cons y x)) instead of a simple cons.  SRFI-1 gets the definitions of fold and fold-right correct, of course.


How to use this jQuery search filter more effective?

In the function searchFilt you are using a parameter value, similar to the block of code in the search function. You can just call the searchFilt function from within the search function and pass the variable value:

function search() {
    $("#myInput").keyup(function() {
        var value = this.value.toLowerCase();
        searchFilt(value);
    });
}

function searchFilt(value) {
    $("table").find("tr").each(function(index) {
        if (index === 0) return;
        var id = $(this).find("td").first().text();
        $(this).toggle(id.indexOf(value) !== -1);
    });
}

Note: you don't exactly use the code twice, inside the search function you have .toLowerCase() at the end of the line where you get the id.