Cool program!

I have put my review of the code on JsFiddle.

A basic synopsis of what I thought to improve:

Everything constant about the map, ship, lasers, and keycodes is all in one place to improve scalability.
I used object literals and array literals instead of new Object() and new Array() because using them is shorter and and makes things easier to manipulate.
The keydown and keyup event handlers were refactored to eliminate duplicate code.
The createLaser and drawLasers methods were refactored. I removed some drawing code from createLaser because it didn't seem to do anything, and I removed calculations in drawLasers that were redundant with createLaser.
I added code in drawLasers to remove lasers from the array that are no longer on the map. I also removed or rearranged drawing code that didn't do anything or was being called too many times. I removed the clear() function because it didn't seem to do anything.
I changed statements of form x = x + y, x = x - y and x = x + 1 to x += y, x -= y, and x++, respectively.
I changed one instance of the form array.push(x); array.push(y); to array.push(x,y);
I renamed lazer to laser because I kept typing laser and it caused bugs that here hard to find. You can rename it back, if you are accustomed to typing lazer.

Here is a copy of the revised code:

console.log("Game starting...");

var ship = {
    name: "Enterprise",
    x: 125,
    y: 120,
    width: 50,
    height: 40,
    left: false,
    right: false,
    up: false,
    down: false,
    fire: false,
    firerate: 5,
    cfirerate: 0,
    moveInterval: 5,
    color: "#000000"
},
    map = {
        width: 300,
        height: 300,
        color: "#808080",
        drawInterval: 30
    },
    laser = {
        height: 20,
        moveInterval: 6,
        color: "#FF0000"
    },
    lasers = [],
    keys = {
        left: 37,
        up: 38,
        right: 39,
        down: 40,
        fire: 90 //Z
    },
    getKey = function(key) {
        for (var i in keys) {
            if (keys.hasOwnProperty(i)) {
                if (keys[i] === key) {
                    return i
                };
            }
        }
    },
    eventValues = {
        keyup: false,
        keydown: true
    },
    types = {
        right: 1,
        left: 2
    };

var world = document.getElementById('world');
var cxt = world.getContext("2d");

$(document).bind('keydown keyup', function(e) {
    var key = getKey(e.keyCode);
    ship[key] = eventValues[e.type];
});

function createLaser(type) {
    var x = ship.x;
    if (type === types.right) {
        x += ship.width;
    }
    var y = laser.height + ship.y;
    return {
        type: type,
        x: x,
        y: y,
    }
}

function drawWorld() {
    cxt.fillStyle = map.color;
    cxt.fillRect(0, 0, map.width, map.height);
}

function drawLasers() {
    cxt.beginPath();
    cxt.strokeStyle = laser.color;
    for (var i = 0; i < lasers.length; i++) {
        var lsr = lasers[i];
        if (lsr.y < -laser.height) {
            lasers.splice(i, 1);
            continue;
        }
        cxt.moveTo(lsr.x, lsr.y);
        cxt.lineTo(lsr.x, lsr.y - laser.height);
        cxt.stroke();
        lsr.y -= laser.moveInterval;
    }
}

function drawShip() {
    if (ship.left) {
        ship.x -= ship.moveInterval;
    }
    if (ship.right) {
        ship.x += ship.moveInterval;
    }
    if (ship.up) {
        ship.y -= ship.moveInterval;
    }
    if (ship.down) {
        ship.y += ship.moveInterval;
    }
    if (ship.fire) {
        if (ship.cfirerate === 0) {
            lasers.push(createLaser(types.left), createLaser(types.right));
            ship.cfirerate = ship.firerate;
        }
    }
    if (ship.cfirerate !== 0) {
        ship.cfirerate--;
    }

    cxt.beginPath();
    cxt.strokeStyle = ship.color;
    cxt.moveTo(ship.x, ship.y + (ship.height / 2));
    cxt.lineTo(ship.x + (ship.width / 2), ship.y);
    cxt.lineTo(ship.x + ship.width, ship.y + (ship.height / 2));
    cxt.stroke();
}

function gameLoop() {
    drawWorld();
    drawShip();
    drawLasers();
}

setInterval(gameLoop, map.drawInterval)

If you see anything that you think is weird, or have a question about what I did, just ask me about it.


Instead of talking about the algorithm, I will review what can be done better even if I don't understand the algorithm. Actually, I will review what can be done better so that I can understand the algorithm:

First of all, don't use macros to define your constants. Since you are using C++11, you can make them constexpr variables instead and use them as array indices too if needed:

constexpr unsigned int outputSize = 20000;
constexpr unsigned int samplesPerThread = 5000;
constexpr unsigned int numThreads = 16;

constexpr unsigned int maxCalcIter = 60000;
constexpr unsigned int minCalcIter = 40000;

You are using std::sqrt but your forgot to include the header <cmath>. While it has probably been included by some other header, it is not guaranteed by the standard thus not including it may cause your program to fail to compile with some implementations.
By the way, try to always std::-qualify the functions from the standard library. Unless you are explicitly using argument-dependent lookup of course.
This line is not really readable:

for (unsigned int j = maxCalcIter; (ReS*ReS + ImS*ImS < 4)&&(j--); ){

It would be better as:

for (unsigned int j = maxCalcIter; (ReS*ReS + ImS*ImS < 4) && (j > 0); --j){

You may have heard that iterating from max to zero is faster, but in most of the cases, this is at best a micro-optimization. The "natural" ordering is from 0 to max and that's what readers will expect. Generally speaking, choosing a good algorithm and good data structures will help you more than micro-optimizing. Worse: if micro-optimizations are done too early when they are not needed, it will hinder readability.

Considering that step is incremented for each iteration of the loop, you can put the incrementation in the for too:

for (unsigned int j = 0 ;
     (ReS*ReS + ImS*ImS < 4) && (j < maxCalcIter) ;
     ++j, ++steps)
{ /* ... */ }

By the way, with modern caches and processors, iterating forward may be significantly faster than iterating backwards if your iterator is used to access memory. Therefore, I expect the last loop of your function to be faster (and more readable) if you iterate forward instead of backwards since the index j is actually used to access memory.
Now, let's see your main function too: if you don't write any return statement in main, the compiler will automagically add return 0;. Unless you also intend to return error codes, not writing return 0; may be a way of documenting that your program cannot return error codes.
You are allocating memory manually in the following line:

float *outImg = new float[outputSize*outputSize];

You should avoid manually allocating memory since it can lead to memory leaks if you forget to delete it later (hint: your forgot). You can always use an std::vector to create a dynamic array and you can access its underlying memory thanks to the method data().

Even better: you know the size of the allocated memory at compile-time. Therefore, you can use an std::array instead. This class allocates its memory on the stack, which means that iteration and some other operations may be faster. Avoid using one if your array is so big that it could blow the stack though (well, in your case, I guess that it would blow the stack).
You are using threads.push_back(std::thread(/* ... */)) to create new threads and add them to threads. You can use emplace_back to create them directly into the vector instead. Your code will even be shorter:

threads.emplace_back(/* ... */);


Fully qualified class names are rarely written in the body of the code; they are almost always imported instead.

If you want to close the Scanner, use a try-with-resources block.  It calls close() even in the case of an intervening exception, and it is easier to see where the Scanner is valid.

temp is nearly never a good variable name.  Even n would be better: it's a conventional variable name for some kind of integer.

It would be good practice to suppress the default constructor by defining a private Factorial() {} constructor.

calculateFactorial would be better named factorial, and it should probably be public.

Are you really going to compute the factorial of a number larger than Long.MAX_VALUE?  You'll run into problems with stack overflow from recursion.  (You should use iteration instead.)  Even if that worked, you would still be dealing with numbers so large that I'm not sure BigInteger could handle.


Not a lot shorter, but a bit...

float ticks = (float)(1.0f/(float)subControl.decorator.ticks);
newValue = subControl.value + subControl.inverted ? ticks : - ticks;

if (subControl.inverted && newValue > 1)  {
    newValue = 0;
} else if (!subControl.inverted && newValue < 0){
    newValue = 1;
}

You could make it even shorter if the you are restricting the values to just 0 and 1.

EDIT: you say in a comment, that it should be between 0 and 1, so...

if (newValue > 1)  {
    newValue = 0;
} else if (newValue < 0){
    newValue = 1;
}

Which is fewer characters if not fewer lines, and imo clearer in intent.


Trivial

Use 1- instead of (- ... 1).

Avoid very long lines (Emacs will indent for you).

Do not use cond when a single if without progn would do.

Memory

Use nconc instead of
append when possible to avoid
unnecessary consing (in your case, splice allocates a fresh list, so
its result can be passed to nconc).

Catastrophic

Whenever you use nth, you are
using the wrong algorithm.

Optimal search is linearithmic: O(n*log(n)).

Insert search is quadratic: O(n^2).

Your implementation is O(n^3):

nth is O(n)
slice is O(n^2) (calls nth * recursion).
splice and move are also O(n^2) (call slice).
find-ordered-index is O(n).
insertion-sort is O(n^3) (calls move * recursion).


Fetching categories and subcategories from database

In no particular order:

Your id_parent field is nullable, and you use this fact to flag the category as having no parent.  This forces you to treat the field differently id_parent is NULL verse id_parent = ....  If you used a magic number, such as 0 to represent no parent, you could treat top level and child categories similarly.

You use a prepared statement, but create the SQL dynamically with "... where id_parent = {$array[$i][0]}".  This is poor design.  Use prepared statements with bound parameters to prevent SQL injection & gain efficiency.

When you query your table, you retrieve all columns of data, but you are only using the name column and the 0th column.  Use "select id, name from..." to just retrieve the data you are going to use.  Not only do you gain efficiency, you document the code with the fields you will be using, and gain resilience against table structure changes that change the column indices.

The name column and the 0th column??  Be consistent; don't mix names and column numbers.

You are querying your SQL table multiple times, once for each possible category parent.  With n categories, you query the table n+1 times!  With such a small table, it would be better to query the table once, store the data in in-memory arrays, and then print the data from the in-memory arrays.

Why return 1;?  Nothing is returned when the function exits normally.  You could just return;.  Or better, reverse the test, put the print loop in the then clause, and don’t have any embedded returns!

Your SQL table should list id as primary key and possibly id_parent as foreign key references cat(id).

Sample code:

Building up the category ($cat) array with a single SQL query:

$stmt = $pdo->prepare("select id, name, id_parent from cat");
$stmt->execute()
$result = $stmt->fetchAll();

$root_id = NULL;
$cat = [$root_id => [ 'name' => '', 'children' => []]];

# Create $cat[id] entries for each row in table, with empty children list
foreach($result as $row) {
    $cat[$row['id']] = [ 'name' => $row['name'], 'children' => [] ];
}

# Add each item to its parent's children list
foreach($result as $row) {
    $cat[$row['id_parent']]['children'][] = $row['id'];
}

Displaying the categories from in-memory array:

function showCat($cat, $id) {
    echo $cat[$id]['name'];
    $children = $cat[$id]['children'];
    if ($children) {
        echo "
";
        foreach($children as $child_id) {
            echo "
";
            showCat($cat, $child_id);
            echo "
";
        }
        echo "
";
    }
}

showCat($cat, $root_id);


Efficiently detect datacenter based on server hostname

There are a few things which I think will simplify your code a lot, and it all centers around your Enum.

Firstly, there is no need in your enum to have the BY_CODE_MAP system. Remove it. You can very efficiently (and with the identical results) use the method:

    public static String forCode(int code) {
        return (code >= 0 && code < values().length) ? values()[code].name() : null;
    }

The values() array in an enum will always be indexed in the same order as the ORDINAL of each Enum.

The second thing, is that you should only be calculating the Datacenter location once for each JVM. Having it as a method which is called potentially multiple times, each time interrogating the java.net.* layer for hostnames, is inefficient.

I suggest you add a static initializer method to your Enum that 'knows'.

Consider the following changes to your enum, and replace the logic in your code:

private String getCurrentDatacenter(){
    DatacenterEnum us = DatacenterEnum.getCurrentDatacenter();
    return us == null ? null : us.name();
}

Then, your Enum will look like (I have commented out the code I think is redundant):

import java.net.InetAddress;
import java.net.UnknownHostException;

public enum DatacenterEnum {
    DC1, DC2, DC3;

//    private static final Map<Integer, DatacenterEnum> BY_CODE_MAP = new LinkedHashMap<Integer, DatacenterEnum>();

//    static {
//        for (DatacenterEnum rae : DatacenterEnum.values()) {
//            BY_CODE_MAP.put(rae.ordinal(), rae);
//        }
//    }

    public static String forCode(int code) {
        return (code >= 0 && code < values().length) ? values()[code].name() : null;
//        return BY_CODE_MAP.get(code).name();
    }

    private static final DatacenterEnum ourlocation = compareLocation();

    private static DatacenterEnum compareLocation() {
        String ourhost = getHostName();
        for (DatacenterEnum dc : values()) {
            String namepart = "." + dc.name().toLowerCase() + ".";
            if (ourhost.indexOf(namepart) >= 0) {
                return dc;
            }
        }
        return null;
    }

    private static final String getHostName() {
        try {
            return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
        } catch (UnknownHostException e) {
            // s_logger.debug(LogLevel.ERROR+"\t"+e.getStackTrace().toString());
            return "localhost";
        }
    }

    public static DatacenterEnum getCurrentDatacenter() {
        return ourlocation;
    }

    public static void main(String[] args) {
        System.out.println(DatacenterEnum.getCurrentDatacenter());
    }

}

If you ever have additional datacenters, you can simply add a new name to the enum and the rest will work. Also, you can add values that are not the same naming convention... for example, if you add the ENUM "EU1" for your first european datacenter, it will match aaa.eu1.xxx.yyy


Your code is a good start, but it is not finished yet. You still need to do:

character literals
string literals
floating-point literals
hexadecimal int literals
int literals containing underscores

I suggest you pick a copy of the current C standard and read through chapter 6, which contains the definitions for all these lexemes. Along with the reading, start to write unit tests for each of the lexeme rules, especially the edge cases.

Your current code is well-structured, and you will be able to write the full lexer keeping the structure the same. I've written a very similar lexer in my pkglint project, and the corresponding unit tests in lexer_test.go in the same directory. Reading this code will bring you up to speed with your own lexer. To see how I use the lexer, look for NewLexer in the code.

One aspect where my lexer differs from yours is that my lexer only remembers the remaining input string, whereas your lexer remembers the complete input string plus the current index. I chose my data structure since it uses the least amount of memory possible. Taking a subslice is an efficient operation in Go, therefore I haven't been bitten my the extra memory access that l.rest = l.rest[1:] needs (it updates both the start and the length of l.rest. Your code is more efficient in that it only increments the index.


Nesting is not necessary, you can iterate instead...

But first:

naming the input String string can be confusing. Of course it's a string, what is it used for though?
there is no need to escape the values inside the [...] construct. the pattern: "\\d+[:.,]\\d+" is just fine, and more readable.
you should be pre-compiling and then reusing the patterns, instead of re-compiling them every time.

Consider the following:

private static final Pattern[] patternorder = {
        Pattern.compile("\\d+[:.,]\\d+"),
        Pattern.compile("\\d{3,}")
};

private static String[] findNumbers(String input) {
    for (Pattern pat : patternorder) {
        Matcher match = pat.matcher(input);
        if (match.find()) {
            return new String[] {
                input.substring(0, match.start()),
                input.substring(match.start(), match.end()),
                input.substring(match.end()),
            };
        }
    }
    return new String[]{input, "", ""};
}


// Initialize a new, empty LList, in dynamically allocated memory.
LList *llist_new(LList **self) {

Its odd to return the new list as a return value and by reference.

    *self = malloc(sizeof (LList));
    if (self == NULL) { return NULL; }

Doing this check after you've already dereferenced self seems kinda pointless. Maybe you meant *self?

    (*self)->front = NULL;
    (*self)->back = NULL;

    return *self;
}

// Append a value to the LList.  Creates a new node.
void llist_add(LList *self, void *v) {
    LLNode *node = malloc(sizeof (LLNode));
    assert(node != NULL);

    node->data = v;
    node->next = NULL;

    // Put this node at the back of the list.
    if (self->front != NULL) {

I'd add a comment to explain what having self->front NULL means.

        self->back->next = node;
        self->back = node;
    } else {
        self->back = node;
        self->front = node;
    }
}

// Iterate over the LList to locate a node, and then remove it from the list.
void llist_remove(LList *self, LLNode *node) {
    LLNode *iter_node = self->front;
    LLNode *prev_node = NULL;

    while (iter_node != NULL) {
        if (iter_node == node) {
            if (prev_node != NULL) { prev_node->next = iter_node->next; }
            else { self->front = NULL; }

I think putting the blocks on the same line like this makes it harder to read. I also think it fail if you delete the first node.

            free(iter_node);
            return;
        }
        prev_node = iter_node;
        iter_node = iter_node->next;
    }

}

// Insert a value after a particular node.
void llist_insert(LLNode *node, void *v) {
    LLNode *next = node->next;
    LLNode *new_node = malloc(sizeof (LLNode));

    new_node->data = v;
    new_node->next = next;

Why did you have the next local variable. It doesn't seem to have helped make the code clearer.

    node->next = new_node;
}

void llist_destroy(LList *self) {
    LLNode *iter_node = self->front;

    while (iter_node != NULL) {
        LLNode *next = iter_node->next;
        free(iter_node);
        iter_node = next;
    }

    free(self);
}


Conway's Game of Life in Python, saving to an image

Style

Your code reads nice, you made a good job following PEP8, except for the 2 imports on the same line and a line exceeding 80 characters.

Other than that you’re missing Python's higher-level constructs and your logic is slightly off.

List comprehension

Creating the grid

Building a list using append in a for loop is considered an anti-pattern in Python. You should use a list-comprehension instead:

# No
l = []
for i in range(X):
    l.append(get_data(i))

# Yes
l = [get_data(i) for i in range(X)]

In case you want a list of lists (as you do for grid) you can easily combine them:

grid = [[random.randint(0, 1) for _ in range(WIDTH)] for _ in range(HEIGHT)]

Note the use of _ to show that we won't use the iteration variable and that we are only interested in repeating the same operation a certain amount of time.

Counting neighbours

You can use almost the same syntax than list-comprehensions to create generator expressions: simply change the surrounding brackets into parenthesis. The difference being that generator expressions won't produce the results at once and store them in memory. Instead, they will be generated as needed but you’ll be able to read them only once.

This is perfect when you don't need to store an intermediate list just to iterate once over it. For instance, if we were to feed a list into the sum function, and that list was built using a list-comprehension, it's probably better to use a generator expression instead.

And that's what is better to count neighbours of a given cell: use the sum builtin with a generator expression. It will also help removing that annoying bug of yours in that big if that tries to remove the current cell out of the count. Instead you’re only counting the neighbours that are in the corner of the surrounding square (I means, those which have neither x2 == 0 nor y2 == 0.) Instead of trying to come up with broken conditions, you’d better of adding the 9 cells and then removing the value of the current one.

So, how do we turn these for loops into generator expressions:

# Assuming NEIGHBOURS = range(-1, 2)
n = sum(
    sum(row[(x+x2) % WIDTH] for x2 in NEIGHBOURS)
    for row in grid[(y+y2) % HEIGHT] for y2 in NEIGHBOURS
)

Here I used a subexpression within the main expression, pretty much like I did with the two for loops that created grid. Setting NEIGHBOURS = range(-1, 2) is also a good idea as it adds meaning and removes duplication.

To get the actual number of neighbours, you just need to substract grid[y][x] from that.

Iterations

In Python we don't like to iterate over a sequence using indexes. We have constrcuts that allow us to directly iterate over elements and it’s faster to do so. But sometimes, like here, you also need the indexes (to update the original data-structure, for instance.) In such case, it's prefered to use enumerate instead of range(len):

for y, row in enumerate(grid):
    for x, cell in enumerate(row):
        data[x, y] = ALIVE if cell else DEAD

Same logic for each ROUND.

You can also note the use of the ternary operator to simplify the logic a bit. Speaking of that…

Logic simplification

Using the ternary was a first step but I think that the following construct reads good as well:

DEAD_OR_ALIVE = (
    (0, 0, 0),
    (0, 64, 255),
)

...

for y, row in enumerate(grid):
    for x, cell in enumerate(row):
        data[x, y] = DEAD_OR_ALIVE[cell]

It might also be a little bit faster (even though I didn't time it).

Handling birth and death of cells can also be simplified: a neighbour's count of 3 will either keep the current cell alive or create a new one in the current slot: grid[y][x] = 1 in both cases; a count of 2 will leave the current slot untouched; and anything else will kill the current cell:

for y, row in enumerate(grid):
    for x, cell in enumerate(row):
        n = ...
        if n == 3:
            grid[y][x] = 1
        elif n == 2:
            pass
        else:
            grid[y][x] = 0

Logic management

One thing that I don't quit get is why you create the image at the beginning of the program only to populate it after all computation is done. You could create it near the end and have related bits of logic near of each other.

Better, you could wrap each logical piece of stuff into it's own function to ease testing and reusability (you can import you file in an interactive shell and call your functions from there with varying parameters.) Doing that you could simplify your constants by using default values for parameters.

You can also improve the overall layout by adding an if __name__ == '__main__' clause to wrap the remaining of your top-level code into.

Proposed improvements

import PIL.Image
import random

WIDTH = 1366
HEIGHT = 768
ROUNDS = 10
NEIGHBOURS = range(-1, 2)

def random_grid(width=WIDTH, height=HEIGHT):
    return [
        [random.randint(0, 1) for _ in range(width)]
        for _ in range(height)
    ]

def compute_next_generation(grid, width=WIDTH, height=HEIGHT):
    for y, row in enumerate(grid):
        for x, cell in enumerate(row):
            neighbours = sum(
                grid[(y+yy) % height][(x+xx) % width]
                for yy in NEIGHBOURS
                for xx in NEIGHBOURS
            ) - cell
            if neighbours == 3:
                grid[y][x] = 1
            elif neighbours == 2:
                pass
            else:
                grid[y][x] = 0

def convert_grid_to_image(grid, dead_or_alive=((0, 0, 0), (0, 64, 255))):
    image = PIL.Image.new('RGB', (len(grid[0]), len(grid)))
    canvas = image.load()
    for y, row in enumerate(grid):
        for x, cell in enumerate(row):
            canvas[x, y] = dead_or_alive[cell]
    return image

if __name__ == '__main__':
    print("Creating grid")
    grid = random_grid()
    for i in range(ROUNDS):
        print("Starting round", i + 1, "of", ROUNDS)
        compute_next_generation(grid)

    print("Creating image")
    img = convert_grid_to_image(grid)
    print("Saving image")
    img.save("gofl.png")


It Your solution being slow is not too much a matter of language here.
I will try highlighting ruby related things you could improve to make it more readable on one hand,
and algorithmic flaws on the other hand.

Ruby

Here I will point out some of the ruby code that could be improved. Note that this will not help
your solution to be much faster since it is mostly an algorithmic problem you have here.

Find Set

Your find_set method seems fine. It is a O(n) method. You have to go through every set to find
the one which includes the node you want. The #include? method of a set is constant in time, and
that is a good use of set here.

Make Set

Your make_set method could be made shorter and cleaner. For instance:

def make_set(n)
  Set.new((1..n).map { |i| Set.new([i]) })
end

Map + Inject

I would not recommand using #map and then #inject as it will create an intermediate array, and
because you can have all in the #inject, like:

vertices.inject(0) { |sum, set| set.size + 1 + sum }

And by the way, you can get rid of to_a since sets accept the #inject and #map methods too.

Method name

You should use snake case: roadsAndLibraries becomes roads_and_libraries.

Algorithmic enhancements

Unneeded computation

Itseems to me you don't need any computation if the road is more expensive than the library.
You can move this to the top of your roadsAndLibraries method.

return n * c_lib if c_road > c_lib

Sets lookup

The main issue with your solution here is probably the lookup you do for each edge. You parse the
whole set of vertices for each city. This is expensive. You could try having a constant lookup
here that would help getting the connected component of a vertice on O(1).

You can use 2 arrays here. One for storing the connected components, like you already do. But
instead of storing them in a set, you can store them in an array, so they have an associated index.
Let's call it components.

And then the second array can be the lookup, we will call it component_index. For each node, you
store the index of its connected component. That way, all find_set has to do is to take the
stored index: components[component_index[a]] for city a.

Your main loop could look like:

cities.each do |a, b|
  first_set = component_index[a]
  second_set = component_index[b]
  next if first_set == second_set
  merge_components(component_index, components, first_set, second_set)
end

Merging components

Where the algorithm will spend time is when we merge components together. Here you will have to
update component indexes. What you have to see here is that it will be performed much less often
than the lookup, especially in case of strongly connected components, where first_set and
second_set of the main loop will be equal.

To merge 2 components, I would put the nodes of the smallest component into the largest one, to
avoid updating too many indexes. And then I would update the indexed component so that it contains
all nodes.

def merge_components(component_index, components, first_set, second_set)
  to = first_set
  from = second_set
  to, from = from, to if components[to].size < components[from].size

  components[from].each do |i|
    component_index[i] = to
  end
  components[to].merge components[from]
end

In case memory is a problem, you probably don't need to store the sets themselves, but only their
size, since you know that they will never overlap, and that the size of the merged set is always
the sum of the sizes of the 2 sets. But by doing so you have to loop through all nodes when
updating components, which can be much longer.

Building Cost

Last thing to change: how we compute the cost of the solution. We will need the final connected
components. This can be extracted like:

final_component_index = component_index.uniq

Then the MST cost would be

  roads_cost = c_road * final_component_index.inject(0) { |sum, x| components[x].size - 1 + sum }

And the final cost

  final_component_index.size * c_lib + roads_cost


I think this can be done a lot more concisely. You need a function to recognize bytes until the end of the array, one to convert them to integers and one to pull it all together:

def get_bytes(f):
    for line in f:
        yield from re.findall(r'0x\d{2}', line)
        if line.rstrip().endswith(";"):
            break

def convert_str_to_bytes(s):
    return int(s, 0).to_bytes(1, 'big')

def convert_arrays(file_name):
    with open(file_name) as f:
        while True:
            arr = b''.join(map(convert_str_to_bytes, get_bytes(f)))
            if arr:
                yield arr
            else:
                return

if __name__ == "__main__":
    print(list(convert_arrays('c_like_code.txt')))
    # [b'\x02\x00\x04\x00\x11\x01\x06\x04\x0112019061020190610\x010']


Consider documenting this function with something like doxygen. At a quick glance, your function can be interpreted two different ways: Print out fib(0), fib(1), ..., or print out all Fibonacci numbers less than or equal to max_num. Documentation will clarify that.

max_num will never be negative. It is defined as an unsigned int, which means it can never hold a negative value. So this:

if (max_num < 0)
{
    fprintf(stderr, "Please, enter a non-negative number\n");
    return;
}

will never happen. (Try calling fib(-2), see what happens)

(Optional) Put size_t count = 0 inside the loop if you can? (You may have to add -std=c99 or something like that to make it work)

for (size_t count = 0; count <= max_num; count++)
{
    printf("%lu\n", fib_num);
    fib_num += fib_temp;
    fib_temp = fib_num - fib_temp;
}


Better way to fetch JSON data from a server from iOS app

NSURLSession was designed from the ground up to be as similar to NSURLConnection as possible, so that those accustomed to using the latter will have no problem transitioning to the former.  Meanwhile, NSURLSession has a lot of major advantages over NSURLConnection.

First of all, we can get rid of all the code for dispatching on a background thread.  NSURLSession works on background threads automatically unless we specify otherwise.

We still have to create our NSURLRequest.  I don't know any way around this.

But once we've got our request set up, and remember, all of this is outside the GCD block, we just do this:

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithRequest:request
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    // do stuff

}] resume];

As you can see, it's quite similar to NSURLConnection.  We replace // do stuff with the stuff we want to do when the request is complete (completion handler).  We have our data, our response, and our error all in this block.

A lot of the new power from NSURLSession comes from the NSURLSessionConfiguration object.  Using NSURLSessionConfiguration, we can easily set up downloads/uploads to happen in the background (when our app is not open).  We can specify to only run on Wi-Fi and not use cellular data as setting a BOOL.  We can set a BOOL to tell the OS to only try doing our background uploads/downloads when the device is on Wi-Fi and plugged into a power source.

NSURLSessionConfiguration also has an HTTPAdditionalHeaders property, which is an NSDictionary object containing additional headers that should be sent with requests using this configuration.

There's a lot more information about NSURLSessionConfiguration here.


Python program for "0-1 knapsack problem"

The code is well written in terms of style and readability, there is only a few things we could improve there.

The algorithm is also optimal for runtime, but the memory usage/allocation could be improved a little which could speed things up.

Readability

Variable naming: some of the variables are not very descriptive:

grid which represents the dynamic-programming array, it needs a comment
either way but maybe best_value is better.
items usually means the actual array, since it represents the count, it's
better to name it items_count. Actually, this variable is not needed since
the function could use len(weights) or len(values)

You could use a named-tuple (or just tuple) to group the item weights and values.

Algorithm

You can reduce the 2d array to a 1d array saving the values for the current iteration. For this to work, we have to iterate capacity (inner for-loop)
in the opposite direction so we that we don't use the values that were updated in the same iteration (you can try the other way and see what goes wrong).

Incorporating these changes we get the following code:

from collections import namedtuple
from timeit import timeit

Item = namedtuple('Item', ['value', 'weight'])

def knapsack(capacity, items):
    # A DP array for the best-value that could be achieved for each weight.
    best_value = [0] * (capacity + 1)
    # The previous item used to achieve the best-value for each weight.
    previous_item = [None] * (capacity + 1)
    for item in items:
        for w in range(capacity, item.weight - 1, -1):
            value = best_value[w - item.weight] + item.value
            if value > best_value[w]:
                best_value[w] = value
                previous_item[w] = item

    cur_weight = capacity
    taken = []
    while cur_weight > 0:
        taken.append(previous_item[cur_weight])
        cur_weight -= previous_item[cur_weight].weight

    return best_value[capacity], taken

items = [Item(60, 10), Item(100, 20), Item(120, 30)]
capacity = 50

print(knapsack(capacity, items))
print('knapsack() Time: ' + str(
      timeit('knapsack(capacity, items)',
             setup = 'from __main__ import knapsack, capacity, items')))

This change resulted in a good improvement in runtime. On my machine, it decreased the execution time (1,000,000 iterations) from 37s to 24s.


It looks fine. Simple but gets the job done. A few things to look into:

GL_TEXTURE_CUBE_MAP_TYPES constant array could be moved to the source file, to hide that implementation detail, assuming it is not meaningful outside the class. I would also use a different name. It looks too much like an OpenGL constant, so it might be misleading. ALL_UPPERCASE is also usually associated with macro names. Not the case here.
This #include <alpha/CubeMap.h>, it should probably be between quotes, since it is a local header file of your project.
Since you are storing all those pos...File parameters of the constructor into std::strings, you might as well take an array of strings, or even a vector/array to be more C++-strict. Or at least replace the char*s by strings.
The correct signature of the assignment operator is:

CubeMap& operator = (const CubeMap& other) = delete;
^^^^^^^^

Returning a reference to the class type. Even though deleted, declare it properly to make sure the compiler recognises it as the default assignment op.
To avoid having to write the lengthy and error prone (sizeof(GL_TEXTURE_CUBE_MAP_TYPES) / sizeof(GL_TEXTURE_CUBE_MAP_TYPES[0])) you can use std::array (C++11), which has a size() method, or define a template function to make it less verbose:

template<class T, std::size_t N>
constexpr std::size_t arrayLength(const T (&)[N])
{
    return N;
}

That assert(0) in the error case after stbi_load seems a bit haphazard. If the image fails to load on "release", you'll pass a null pointer to glTexImage2D. That will still allocate a texture image with undefined contents. That's not really helpful to the user. The error is already being logged, so you could either set a default placeholder image to visually signify the error, or simpler, just throw an exception and let the caller decide what to do.
That 31 is very hardcoded in assert(unit >= 0 && unit <= 31). There's actually a maximum value you can query with glGetInteger, which I don't recall now, but it is quite large, so you can indeed be lazy and use a constant instead if you want. But it would still be better to define a MaxTextureUnits somewhere to make the value self-explanatory for the non-OpenGL versed.


The main problem I see with this is that you are assuming a few things:

I am running Linux - Are you? The production server might, but are you locally running linux as well? Maybe, but will the next collaborator/developer?
My Linux distro supports find - That also may or may not be true. Some distros will have that built in, some will not.

You are tying yourself to a specific environment, that's not good. A better approach would be to make sure that the class file sits under the path you expect it to, relatively to a file you know where it is relatively to the project.


Best practice to load settings to the web application

I can't claim to be familiar with Electron, but after looking at the documentation and an example on github, it appears that an electron convention is to use app.on/app.once

var electron = require('electron') // http://electron.atom.io/docs/api
var path = require('path')         // https://nodejs.org/api/path.html
var url = require('url')           // https://nodejs.org/api/url.html
var window = null
// Wait until the app is ready
electron.app.once('ready', function () {
  // Create a new window
});

In general, Javascript developers can subscribe to the readystatechange event as you have done, as well as use document.addEventListener() to subscribe to the DOMContentLoaded event:

document.onreadystatechange = function(){
  console.log('document readystate: ',document.readyState);
}
document.addEventListener('DOMContentLoaded',function() {
  console.log('DOM Load: document readystate: ',document.readyState);
})

You might find this SO post interesting...


char *
itoa(int n)
{
    static char out[WIDTH + 1];

    for(char *outp = out + WIDTH - 1; outp >= out; --outp, n /= 10)
        *outp = '0' + n % 10;

Nice bounds-check (outp >= out). This ensures that you don't overrun your buffer when given a very large integer. However, since out-1 is not a valid pointer value, outp >= out is an incorrect bounds-check for the same reason that

int decr(int x) {
    int y = x - 1;
    if (y > x) return 0;  // oops, overflow happened
    return y;
}

is an incorrect overflow-check.

Your bounds-check code also has another similarity to the above overflow-check code: When overflow happens, you return an in-range value that the caller might reasonably confuse for a valid result of the function. When itoa(x) returns "42", does it mean that x was 42, or does it mean that x was 1042 and overflow happened? It would be much better to say, if overflow happens, we return NULL.

Of course you'll have to express that "if" without if. ;)

itoa returns char*, but you don't expect the caller to modify the pointed-to chars, so you should declare it as returning a pointer to non-modifiable chars: const char*. Const is a contract.

Similarly, static char *FBSTR[4] should be static const char *FBSTR[4].

static const char *FBSTR[4] = {"", "Fizz", "Buzz", NULL};

would be much clearer to the human reader; it shows that you didn't miscount the number of array elements. In fact, you might even write

static const char *FBSTR[] = {"", "Fizz", "Buzz", NULL};

although the downside of that is that the number of indices is actually really important to your algorithm, so I can see a valid argument for keeping the 4 in this case.

fputs(FBSTR[1 * (n%3 == 0)], stdout);
fputs(FBSTR[2 * (n%5 == 0)], stdout);
fputs(FBSTR[3 * (n%3 > 0 && n%5 > 0)], stdout);
putchar('\n');

I did puzzle this out, but printing all those empty strings feels like a strange way to go about it. Why not simply

int idx = 1*(n%3 == 0)
        + 2*(n%5 == 0)
        + 3*(n%3 != 0 && n%5 != 0);
fputs(FBSTR[idx], stdout);
putchar('\n');

In which case you can combine the fputs and putchar into

puts(FBSTR[idx]);

If you think it would be easier to understand, you could even rewrite the index computation using bitwise operations:

const char *FBSTR[] = {itoa(n), "Fizz", "Buzz", "FizzBuzz"};
int idx = (n%3 == 0) + 2*(n%5 == 0);
puts(FBSTR[idx]);

To avoid reinventing the wheel, you could replace itoa(n) with snprintf(somelocalbuffer, sizeof somelocalbuffer, "%d", n). However, for this toy example, itoa does have a more ergonomic interface; and reinventing the wheel isn't necessarily a bad thing.


Improving performance of function to multiply vector with a matrix?

Throw out the works and use Numpy. Seriously. Rolling your own matrix multiplication is fun and educational, but pretty much immediately reaches its limit if you care about performance. There is no universe in which a native Python implementation of low-level matrix operations will out-perform a well-written C library that has FFI to Python.


Keystrokes are (almost) free. It's not like decomp looks any better than decompose. (Moving forward, I'm going to assume you made the rename.)
Your count() function is cute. For extra fun, you could replace it with Array.reduce() (which you may know as foldl):

decompose(n, n).reduce(function(accumulator, value) {
    if (typeof accumulator[value] === "undefined") {
        accumulator[value] = 0;
    }
    accumulator[value]++;
    return accumulator;
}, []).map ...

(The logic can be reduced to prev[cur]++ || (prev[cur] = 1) or prev[cur] = prev[cur] + 1 || 1 if desired.)
It's worth mentioning that comparisons against undefined are typically done with ===.
You've got a redundant else in decompose().
You can use switch(true) syntactic sugar to make decompose() prettier:

function decompose(composite, factor) {
    switch(true) {
        case composite == 1:
            return [];
        case factor == 1:
            return [composite];
        case composite % factor == 0:
            return decompose(factor, factor - 1).concat(decompose(composite / factor, factor));
        default:
            return decompose(composite, factor - 1);
    }
}

or alternatively, chained conditional operators (commonly called ternary operators):

function decompose(composite, factor) {
    return composite == 1 ? [] :
           factor == 1 ? [composite] :
           composite % factor != 0 ? decompose(composite, factor - 1) :
           decompose(factor, factor - 1).concat(decompose(composite / factor, factor));
    }
}

decompose(n, n) is ugly. Maybe you rewrite the contract of decompose to int (maybe int) -> array?
You're replacing only the first instance of ^1. You'll want to do .replace(/\^1/g, "") instead.
factor(1) doesn't return 1 as expected. You can fix this by switching your first two ifs.
factor(0) recurs infinitely.
You're using a lot of functions at the end there.

Here's my rendition. It's a little bit less elegant with the return... oh well. I'm using a utility function when to avoid potentially ugly ternary nesting. The double reduce bugs me but I can't think of a better way right now.

function factor(n) {
    function when(condition, string) {
        return condition ? string : "";
    }

    function decompose(composite, factor) {
        return factor === undefined ? decompose(composite, composite) :
               factor <= 1 ? [composite] :
               composite <= 1 ? [] :
               composite % factor != 0 ? decompose(composite, factor - 1) :
               decompose(factor, factor - 1).concat(decompose(composite / factor, factor));
    }

    return decompose(n).reduce(function(accumulator, value) {
            accumulator[value] = accumulator[value] + 1 || 1;
            return accumulator;
        }, []).reduce(function(accumulator, value, index) {
            return accumulator + when(value, " * " + index + when(value > 1, "^ " + value));
        }, "").substr(3);
}


Creating a function with limited number of args in python

In all programming language, it is better that a function's name is a verb, or start with a verb. In your case, I would use create_result() instead of creating_result().

One this transformation is done, you would think of a better name for this function as it is quite too generic in its meaning. create_car() would be better and more meaningful in your context.

For the parameters you are passing, they should be written following the snake_name convention. Meaning, for example, carColour becomes car_color, carPrice becomes car_price, ... and so on.

More important: Regardless of the purpose of the parameters you are passing to the creating_result() function, their number is quite much which thing should lead to creating a class and use them as instance attributes.


There are a few general improvements I would suggest for readability and clarity and apply throughout.

Use docstring to document your functions, modules and classes.
Since Python 3, you can now use type hints for your function and method signatures, and use static code analysis tools. This also makes the code easier to read for humans.

Applying these to your cube function, you would get something like this:

def cube(number: int) -> int:
    """Return the cube of a number,
    i.e. the number to the power of 3."""
    return number ** 3

Note that I renamed the x argument to a more descriptive number argument. What the above means is that the function expects number to be an integer, and that the function should return an integer.

Another problem I see with this function is that it does not check for correct input. If you type cube("hello") then the program just crashes with an error TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'. It would be better to handle the error. There are at least two ways to do this.

Using isinstance:

def cube(number: int) -> int:
    if not isinstance(number, int):
        return TypeError("{0} is not an integer".format(number))
    return number ** 3

Using try and except:

def cube(number: int) -> int:
    try:
        return number ** 3
    except TypeError as err:
        return TypeErrorTypeError("{0} is not an integer".format(number))

Using the latter, you could also just except TypeError as err and return err which will return the normal error listed above.

You can also use assert which will instead raise an AssertionError if the type is incorrect, for instance assert(isinstance(number, int)). This is particularly useful when setting up tests for your code.

I personally find that the first method is simpler to use, and you can use it to check multiple types at once, but the latter is the standard way to handle something that may cause an error. Choose whichever is more appropriate for the situation.

Applying the same ideas to map_it, this is slightly more complicated since the type hints have to be imported from typing library. Again, I renamed x to a more descriptive name elem.

from typing import Callable, Sequence, Iterable

def map_it(func: Callable, seq: Sequence) -> Iterable:
    """Applies a given function to a sequence and yields the result."""
    for elem in seq:
        yield func(elem)

You could also test using instanceof here if you liked, which may or may not be necessary depending on your use cases.

Your greet function can also have type errors, if you call it with a non-string type, e.g., greet(42). The simple fix for this (and I recommend to use it any time you need to put variables/arguments into strings) is to use .format() instead of +'ing string and values.

from typing import Callable

def greet(name: str) -> Callable:
    """Returns a callable greeting with given name."""
    def print_message() -> None:
        """Callable to print a greeting to stdout."""
        print("Hello, {0}!".format(name))
    return print_message

One more thing, I noticed your code is peppered with # line comments, in general comments like that should only be used to clarify or explain why something is done, in most cases they are not needed as the code speaks for itself.


A few quick tips:

premature optimization is the root of all evil
use a profiling tool
premature optimization is the root of all evil
Don't echo markup, close php, write markup, open php tag again
premature optimization is the root of all evil
Dont query the DB, if you might have to change header('Location:...') a few lines further down. If you're going to have to redirect, do so ASAP.
premature optimization is the root of all evil
Avoid globals, they're error prone, hellish to debug and generally evil, but not as evil as premature optimization
premature optimization is the root of all evil

All in all, there's not enough code yet to squeeze any meaningful performance gain out of it. Not by altering the code alone, anyway.
If you do decide to use a profiling tool, also look into caching (google APC), and try your hand at bytecode caching. See how many ms you can shave off that way, but always remind yourself of one thing:

premature optimization is the root of all evil


Are all these steps necessary with prepared statement?

More or less, they are... I was using get_result and fetching object more often, but if you want to have the results bound directly to variables, your code is what you need.

By the way, consider using some ORM. I'm using Doctrine2 for my PHP stuff and I'm very satisfied with it


for of loop that stops at last object of array

It hit me,

function returnSuggestedColleaguesWithExpertiseHeight(): number {
    let height = element[0].clientHeight;
    const childElements = <[HTMLElement]>element[0].children;
    for (let i = 0; i < childElements.length - 1; i++) {
        height -= Math.ceil(childElements[i].clientHeight);
    }
    return height;
}


The first solution that comes to mind is to take advantage of the powerful list comprehension and abuse the xrange function:

def reverse(some_list):
    return [some_list[n] for n in xrange(len(some_list) - 1, -1, -1)]

The above is nothing more than the usual reversed for loop that you may find in other languages (like C / C++) as:

for (int i = array.length - 1; i >= 0; i--)
{
    // Do something ...
}

Details about the range function can be found here but basically, all you have to know about it is its prototype:

  range(start, stop[, step])

which is very descriptive.

I'd go with this instead of your solution because it looks cleaner and I don't see any reasons of why it'd be slower or harder to understand.


Filter column and row according to regex in header

Your approach is basically reasonable, but you aren't taking advantages of Python's more powerful features, or any of the more interesting parts of the standard library.

re.search

A minor point to start with. You're making a regex like so:

prog=re.compile(".*"+regex+".*")

Presumably so that you get an unanchored match (i.e., one which can start at any point in the string).

re has a method re.search which will do unanchored matching by default; you can anchor the match to the start of the string with ^, as you would expect. See search() vs. match() in the documentation.

Manipulating whole data structures

There are a number of specific points below, but the broad thrust of them is that you will have a much nicer time doing large-scale operations on whole data structures, rather than fiddling around with indexes and individual elements. This is true in most languages, but one of the strengths of Python is the rich set of data structures and operations which are available built-in or in the standard library.

itertools.compress

There is a wonderful module in the standard library called itertools. This library is my first thought in Python whenever I want to do something involving sequences of any kind, and it contains a little function called compress which will do a lot of the work for your program.

Basically, you give compress a sequence of data items and a sequence of selectors, and you get back a sequence of those data items for which the selector is true. So in your example, matching your regex against the columns would give you the "selector":

[False, True, False, True, False]

(I'll mention how to generate this simply in a moment). You would then want to modify this to also pass through the row header, so you have the selector:

[True, True, False, True, False]

then, doing itertools.compress for a randomly-selected row:

itertools.compress(['a', 2, 9, 6, 1], [True, True, False, True, False])

=> ['a', 2, 6]

you can then just print that list to print the (filtered) row.

Note that you could also do this filtering yourself, using a list comprehension; however, itertools has the twin advantages of being common (hence readable) and carefully optimized (hence fast).

join

Once you can easily generate lists containing exactly the elements you want to output, you don't have to fiddle around doing print('\t', tokens[col], end='') and similar; you can just do:

print('\t'.join(tokens))

(assuming you have already filtered your tokens using compress or similar).

List comprehensions

List comprehensions are one of Python's most pleasant features. They're far too large a topic for me to sensibly explain in an answer here; that link will give you a good introduction, and there are many other articles and introductions around.

Roughly speaking, list comprehensions (and their cousins, generator expressions) are a nice syntax for creating sequences from sequences, doing "something" (transforming, selecting, etc.) on the way.

For example, you could write a list comprehension like this:

[reg.search(t) for t in tokens]

If reg is [a|c], and tokens is ['', 'a', 'b', 'c', 'd'], this will produce:

[False, True, False, True, False]

which you will recall is exactly what you need to feed to compress to filter to just those columns. (Actually, it will produce a list of Nones and regex match objects, but those evaluate to False/True in a boolean context, so don't worry too much about that).


Rather than using \d, you might want to limit the matcher to valid ranges.

\d{2}:([0-5]\d:){2},\d{3}

would match either of the timestamps and it would prevent someone from entering

11:88:88,888 --> 12:99:99,999


Code issues that decrease readability and maintainability

Plenty of loops.
Non-meaningful variable names: n, l, o.

We can declare the following helper methods:

private static string CreateDigitsString(int length)
{
    char[] buffer = new char[length];
    for (int i = 0; i < buffer.Length; i++)
    {
        buffer[i] = (char)('1' + Math.Abs(buffer.Length / 2 - i));
    }
    return new string(buffer);
}

private static string CreateLine(int length, int spaces)
{
    return new string(' ', spaces) + CreateDigitsString(length - 2 * spaces) + new string(' ', spaces);
}

Then use it like:

const int N = 5;
const int TotalRows = N * 2 - 1;

for (int row = 0; row < TotalRows; row++)
{
    Console.WriteLine(CreateLine(TotalRows, Math.Abs(N - row - 1)));
}

Another approach
In the 2-dimensional loop (i, j) we can calculate the distance between the current cell and the center of the diamond as follows:

int rowDistance = Math.Abs(row - N + 1);
int colDistance = Math.Abs(col - N + 1);

Let's output the colDistance for cells that are within rowDistance + colDistance <= N - 1, and space - otherwise.

const int N = 5;
const int TotalSize = N * 2 - 1;

for (int row = 0; row < TotalSize; row++)
{
    for (int col = 0; col < TotalSize; col++)
    {
        int rowDistance = Math.Abs(row - N + 1);
        int colDistance = Math.Abs(col - N + 1);
        Console.Write(rowDistance + colDistance <= N - 1 ? (char)('1' + colDistance) : ' ');
    }
    Console.WriteLine();
}


Security

  I'm concerned about security and I'm not the best.

You use prepared statements, secure random numbers, and didn't make any other giant mistakes (from what I can tell), so that is already very good.

Still, there are two issues:

you definitely want to set these cookies as httpOnly (it may somewhat mitigate XSS attacks).
you definitely want to hash the token in the database (use proper hashing such as bcrypt). Otherwise, once your database is compromised, an attacker can login as anyone that has an active remember me token. [your sha256 doesn't count here, an attacker can still just pass the value in the db]

And two minor points:

do you need the token in the session? It doesn't seem so to me, so I wouldn't store it. It shouldn't happen, but session data may leak, eg on shared hosts, so if it's not necessary, I wouldn't store secret information in them.
the feasibility of remote timing attacks is still somewhat disputed, but it's not that far fetched. With your code, it's highly unlikely that anything may happen, but still, ideally, your code should be secure against it, and I'm pretty sure that your SELECT isn't. If you use bcrypt as suggested, you get a timing safe string compare for free. Otherwise, see eg here (it also links to some more information on proper remember me mechanisms).

Misc

rememberMe isn't named all that good. It's not a function used to remember me, but a function used to check if I am remembered. So isRemembered would be more fitting. Something like authenticateCookie or similar might also work.
two spaces indentation is not enough, it makes your code hard to read. Use at least 4 spaces. If that leads to too long lines, reduce your nesting.
you should share one connection across your code (for performance reasons).
your rememberMe function may do a bit too much. It verifies the validity of a remember me token, but it also loads user info and saves it in the session. I would probably separate the second task into its own function.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char table[] = "0123456789abcdef";

This constant should be static const char table[]. Just as a general rule, so that it doesn’t conflict with other variables in other files that are also called table.

int main(int argc, char* argv[])
{
  int flip = argc - 2;
  unsigned char* ubin = argv[1];

Using argc and argv before range checking them is dangerous in general. In this case it works, but it means that ubin could be NULL here. This code looks suspicious.

  unsigned int nibble = 0;
  int i = 0;

Bad variable name i. It should rather be nbits, since it contains the number of bits in the current nibble.

  int nothing = 1;

  if((argc != 2) && (argc != 3 || strcmp(argv[2], "-f") != 0)){
    fprintf(stderr, "Usage: %s 00001111 [-f]\n", argv[0]);
    return EXIT_FAILURE;
  }

  printf("%s", "0x");

A simple printf("0x") would be clearer.

  while(*ubin){

Instead of this while loop, write a for loop: for (ubin = argv[1]; *ubin != '\0'; ubin++) {. Then you don’t need to write the ubin++ multiple times.

    if((*ubin != '0') && (*ubin != '1')){
      ++ubin;
      continue;
    }

    nibble <<= 1;
    nibble |= *ubin - '0';

    if(++i == 4){
      i = 0;
      if(flip)
        nibble = ~nibble & 0xf;

An alternative would be nibble ^= 0xf;.

      putchar(table[nibble]);
      nibble = 0;
      nothing = 0;
    }

    ++ubin;
  }

  if(nothing)
    putchar('0');

  putchar('\n');

  if(i)
    fprintf(stderr, "Error: %d bits were discarded, min unit is a nibble\n", i);

In case of an error, the return value should be EXIT_FAILURE, not 0.

  return 0;
}

But apart from all these comments, the program looks fine. You did the argument checking correctly and strictly. When your program gets more options, you should consider using the getopt library for parsing the command line. But for now, it is fine.

It is unusual to have the options after the remaining arguments; -f 00001111 is more common than 00001111 -f.

The main algorithm is clean and simple. I especially like the error handling at the end. There are too many other programs that just don’t do this.


The WebService interface with a CreatePDF method is good like that.
The private GetQuery method is an implementation detail that should not be exposed.

But there's something else you can do to test GetQuery.
You can move that logic outside to a different class,
whose main responsibility will be to build query strings.
Then the method will be public, naturally, and you can implement unit tests for it.

The query string builder class can become a collaborator of WebService:
implementations of WebService can call it from their GetQuery methods to build query strings correctly,
with the comforting thought that the utility class is properly unit tested.


Can you store the content in the CSV file in the memory?It will be more effective to read from the memory than the disk.

Maybe the CSV file will also be store in the memory cache by OS, but you can do it your self to make it more reliable.

Of course it's only when there is enough memory you can do this.

OK, from your code, I think maybe you just need to read all line[1] in and then scan it.

partNOs=[line.split("\t")[1] for line in upload]
for partNO in partNOs:
    if partNO in similar and similar[partNO] in partNOs:
        upload.write("blabla")

This assume that: what you write to file 'upload' will not match similar keys and values. Because it read the file and use the 'cache' before write into it.


Simplifying a LINQ expression that finds the largest date smaller than another date

Is this what you are looking for?

skew.CalibrationDate.Date == db.Skew
    .Where(s => s.CalibrationDate.Date <= date.Date)
    .Max(s => s.CalibrationDate.Date)

Max will return the maximum value itself, not the object with the maximum date.


Can use Generics for Node to provide something for more then just ints.

class Node<T> {
    Node prev;
    Node next;
    T data;

    public Node(T data) {
        this.data = data;
        prev = null;
        next = null;
    }
}

then same for your linked list implementation.

class LinkedList<T> {
    Node<T> head;

    ...

    public void insert(T d) {
        if (head == null) {
            head = new Node<T>(d);
            return;
        }

    ...

Can make T extends Comparable and use comparable interface to compare if they are less/greater than


Instead of testing the value of the HTML element, pass the season number in as a variable, and then you can use some of that simplifcation magic we used before:

function seasonChange() {

    var seasonNum = document.getElementById('selectseason').value;
    var first_episodes = [
        "1 - Death Has A Shadow",
        "1 - Peter, Peter, Caviar Eater",
        "1 - The Thin White Line"
    ];

    for (var i = 1; i <= first_episodes.length; i++){
        if (document.getElementById('selectseason' + seasonNum + 'episode').value == first_episodes[i - 1]) {
            document.getElementById('season' + seasonNum + 'episode1').style.display = 'inline-block';
        }
        var showOrNot = (seasonNum == i ? 'block' : 'none');
        document.getElementById('season' + i + 'episodes').style.display = showOrNot;
        document.getElementById('s' + i + 'buttons').style.display = showOrNot;
    }

}

This uses the season numbers, to test whether its the one you're switching into or not.

One suggestion I'd make though is that, instead of the first_episodes variable, I'd use a database script, in PHP or something similar, to hit the database for the different episodes/seasons.

That way you can totally move this to the automated paradise you want.


I believe you could reduce it to \$O(n\log{n}+m\log{n}+n m)\$ if you want.

Sort the inputs, then iterate over the tests and for each one, do a two variable iteration over the inputs, where you start as close to the test value/2, and move one index in the increasing direction and the other in the decreasing direction depending on whether the sum is less than or greater than the test value.

This is somewhat confusing, so a partial implementation is:

def one_test(sorted_array, test_value):

    index1 = index_just_under(sorted_array, test_value/2)
    index2 = index1 + 1

    while (index1>=0) and (index2 < len(sorted_array)):
        sum = sorted_array[index1] + sorted_array[index2];
        if sum == test_value:
            return True
        if sum > test_value:
            index1 = index1 - 1
        else:
            index2 = index2 + 1

    return False

Function index_just_under would be an \$O(\log{n})\$ method to find our initial cut point.  It returns the number of entries in the array below the second parameter, minus 1.  Given a sorted array, a binary search can be used.

The rest of this one_test function is \$O(n)\$.  This function is executed \$m\$ times, and the initial sort is \$O(n\log{n})\$.

While this might be a poor savings of the two input arrays are the same size, if tests array is much smaller, this could be a big saving.

If you start the indexes at the 0 and len(sorted array) - 1, you might be able to eliminate the index_just_under() call, reducing the time by \$O(m\log{n})\$.  On the other hand, it would eliminate any early-outs in the \$O(n m)\$ loops.  Effectiveness could depend on your expected number ranges.


Convert query string into object in JavaScript

I suggest you use the standard query string syntax to avoid future problems. Because the weirder this query string gets, the more cases you'll have to add to this piece of code. And when a case that's not covered in your code appears, it will unexpectedly break your code.

Also, this used to be the way to parse query strings (i.e. split by &, loop through the items, split by =). Now, there is a built-in API, URLSearchParams, that parses query strings for you. It exists for both browser JS as well as NodeJS. It exposes several methods as well as methods that return iterables, which allow you to loop through the items.


Get XML elements with a particular attribute value

I think you could use the null-conditional operator for x.Attribute("attrName").Value and swap arguments of String.Equals to avoid the NullReferenceException as follows:

IEnumerable<XElement> elems =
     xmlDoc.Descendants("elemName")
     .Where(x =>
         filename.Equals(
             x.Attribute("attrName")?.Value,
             StringComparison.OrdinalIgnoreCase
         )
     );


C program to convert string to floating point

Thanks for including a test program - that's always valuable!

However, I'm going to change it, to parse a battery of test cases instead of reading from stdin:

#include <stdio.h>
int main(void)
{
    static const char *const strings[] = {
        /* these should parse fully */
        "12",
        "12.0",
        "08",                   /* not octal! */
        "+12.34",
        ".34",
        "\t \n2.",
        "1e0",
        "1e+0",
        "1e-0",
        "1.e4",
        ".1e-4",
        "-5e006",
        "-5e+16",
        "-.05",
        "-.0",
        "-1e6",
        /* these should parse only the initial part */
        "5c5",
        "10ee5",
        "0x06",                 /* not hex! */
        "--1" ,
        "-+1" ,
        "1e--4" ,
        "-1e.4",
        "1e 4",
        "1e-g",
        "", "foobar",           /* both 0 */
        " e5",                  /* also 0 */
        "-1e6",
        /* overflow/underflow */
        "1e500000",
        "1e-500000",
        "-1e500000",
        "-1e-500000",
    };

    static const int max = sizeof strings / sizeof strings[0];
    for (int i = 0;  i < max;  ++i)
        printf("%20s = > %.9g\n", strings[i], extended_atof(strings[i]));
}

(I changed the function name to extended_atof() so as to be safely distinct from the standard library atof().)

Your implementation passes all these tests.  Now we can look at refactoring.

Remove duplication

The things that we parse in multiple places are:

optional sign + or -
digit sequences

So perhaps we can refactor each of those into a function?  Instead of using an integer index into the supplied string, I prefer to just move the string pointer, and eliminate the need for i:

/* return true for positive, false for negative,
   and advance `*s` to next position */
static bool parse_sign(const char **s)
{
    switch (**s) {
    case '-': ++*s; return false;
    case '+': ++*s; return true;
    default: return true;
    }
}

Let's make use of that in the function:

double extended_atof(const char *s)
{
    /*skip white space*/
    while (isspace(*s))
        ++s;

    int sign = parse_sign(&s) ? 1 : -1; /*The sign of the number*/

    double value = 0.0;
    while (isdigit(*s))
        value = value * 10.0 + (*s++ - '0');

    if (*s == '.') {
        ++s;
    }

    double power = 1.0;
    while (isdigit(*s)) {
        value = value * 10.0 + (*s++ - '0');
        power *= 10.0;
    }

    if (tolower(*s) == 'e') {
        ++s;
    } else {
        return sign * value/power;
    }

    bool powersign = parse_sign(&s); /*The sign following the E*/

    int power2 = 0.0; /*The number following the E*/
    while (isdigit(*s))
        power2 = power2 * 10.0 + (*s++ - '0');

    if (powersign) {
        while (power2 != 0) {
            power /= 10;
            --power2;
        }
    } else {
        while (power2 != 0) {
            power *= 10;
            --power2;
        }
    }

    return sign * value/power;
}

It's slightly shorter, and it still passes all the tests.

Let's see if we can read digit strings in a function, and replace the three places we do that.  We'll make it update a count of how many digits wore parsed, so we don't lose leading zeros in the fractional part:

double extended_atof(const char *s)
{
    /*skip white space*/
    while (isspace(*s))
        ++s;

    int sign = parse_sign(&s) ? 1 : -1; /*The sign of the number*/

    double value = parse_digits(&s, NULL);

    if (*s == '.') {
        ++s;
        int d;                  /* digits in fraction */
        double fraction = parse_digits(&s, &d);
        while (d--)
            fraction /= 10.0;
        value += fraction;
    }

    value *= sign;

    if (tolower(*s) == 'e') {
        ++s;
    } else {
        return value;
    }

    bool powersign = parse_sign(&s); /*The sign following the E*/

    int power2 = parse_digits(&s, NULL); /*The number following the E*/

    double power = 1.0;
    if (powersign) {
        while (power2 != 0) {
            power /= 10;
            --power2;
        }
    } else {
        while (power2 != 0) {
            power *= 10;
            --power2;
        }
    }

    return value/power;
}

Tests still pass; what's next?

if (tolower(*s) == 'e') {
    ++s;
} else {
    return value;
}

This can be reversed, and if we're returning, it doesn't matter what we do to s:

if (tolower(*s++) != 'e')
    return value;

Here's some near-duplicate blocks:

double power = 1.0;
if (powersign) {
    while (power2 != 0) {
        power /= 10;
        --power2;
    }
} else {
    while (power2 != 0) {
        power *= 10;
        --power2;
    }
}

Dividing by 10 is the same as multiplying by 0.1, so we can move the test into the loop:

double power = 1.0;
while (power2 != 0) {
    power *= powersign ? 0.1 : 10;
    --power2;
}

We could go further, and capture powersign ? 0.1 : 10 into a variable.  We can also eliminate the power variable from here, and multiply value directly:

const double exponentsign = parse_sign(&s) ? 10. : .1;
int exponent = parse_digits(&s, NULL);

while (exponent--)
    value *= exponentsign;

Final version

Here's what I finished up with:

#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>

/* return true for positive, false for negative,
   and advance `*s` to next position */
static bool parse_sign(const char **const s)
{
    switch (**s) {
    case '-': ++*s; return false;
    case '+': ++*s; return true;
    default: return true;
    }
}

/* return decimal value of digits,
   advancing `*s` to the next character,
   and storing the number of digits read into *count */
static double parse_digits(const char **const s, int *const count)
{
    double value = 0.0;
    int c = 0;
    while (isdigit(**s)) {
        value = value * 10.0 + (*(*s)++ - '0');
        ++c;
    }
    if (count)
        *count = c;
    return value;
}

double extended_atof(const char *s)
{
    /*skip white space*/
    while (isspace(*s))
        ++s;

    const bool valuesign = parse_sign(&s); /* sign of the number */
    double value = parse_digits(&s, NULL);

    if (*s == '.') {
        int d;                  /* number of digits in fraction */
        ++s;
        double fraction = parse_digits(&s, &d);
        while (d--)
            fraction /= 10.0;
        value += fraction;
    }

    if (!valuesign)
        value = -value;

    if (tolower(*s++) != 'e')
        return value;

    /* else, we have an exponent; parse its sign and value */
    const double exponentsign = parse_sign(&s) ? 10. : .1;
    int exponent = parse_digits(&s, NULL);
    while (exponent--)
        value *= exponentsign;

    return value;
}

/* Test program */
#include <stdio.h>
int main(void)
{
    static const char *const strings[] = {
        /* these should parse fully */
        "12",
        "12.0",
        "08",                   /* not octal! */
        "+12.34",
        ".34",
        "\t \n2.",
        "1e0",
        "1e+0",
        "1e-0",
        "1.e4",
        ".1e-4",
        "-5e006",
        "-5e+16",
        "-.05",
        "-.0",
        "-1e6",
        /* these should parse only the initial part */
        "5c5",
        "10ee5",
        "0x06",                 /* not hex! */
        "--1" ,
        "-+1" ,
        "1e--4" ,
        "-1e.4",
        "1e 4",
        "1e-g",
        "", "foobar",           /* both 0 */
        " e5",                  /* also 0 */
        "-1e6",
        /* overflow/underflow */
        "1e500000",
        "1e-500000",
        "-1e500000",
        "-1e-500000",
    };

    static const int max = sizeof strings / sizeof strings[0];
    for (int i = 0;  i < max;  ++i)
        printf("%20s = > %.9g\n", strings[i], extended_atof(strings[i]));
}

There's still an opportunity for a small improvement: an extremely long fractional part could overflow double (this problem existed in your original).  Instead of returning a large value from parse_int(), you could consider always returning a fractional value in the range [0...1), and use the number of digits to scale up the integer parts.  Then we'd just end up with lost precision at the lower end.  That would look like:

static double parse_digits(const char **const s, int *const count)
{
    double value = 0.0;
    double increment = 0.1;
    int c = 0;
    while (isdigit(**s)) {
        value += increment * (*(*s)++ - '0');
        increment /= 10;
        ++c;
    }
    if (count)
        *count = c;
    return value;
}

The corresponding uses would be:

double extended_atof(const char *s)
{
    /*skip white space*/
    while (isspace(*s))
        ++s;

    int d;                  /* number of digits */
    const bool valuesign = parse_sign(&s); /* sign of the number */
    double value = parse_digits(&s, &d);
    while (d--)
        value *= 10;

    if (*s == '.') {
        ++s;
        double fraction = parse_digits(&s, NULL);
        value += fraction;
    }

    if (!valuesign)
        value = -value;

    if (tolower(*s++) != 'e')
        return value;

    /* else, we have an exponent; parse its sign and value */
    const double exponentsign = parse_sign(&s) ? 10. : .1;
    double exponent_f = parse_digits(&s, &d);
    while (d--)
        exponent_f *= 10;

    unsigned long exponent = exponent_f;
    while (exponent-->0)
        value *= exponentsign;

    return value;
}


PDO Is this registration secure and well coded?

I don't really like the kind of a review that is popular on this site which only states that your code has some problems but doesn't really offer any solution or improvement.

Given for some problems listed it's really hard to find a plausible solution, I would prefer an answer where author at least tries to provide a solution, so it will be sort of a sanity check for the problem stated.

Now to your code. It is pretty secure but not well coded. For me, the main problem here is the code repetition. For some reason each value is accessed and duplicated through many different variables. Why not to keep just one variable initialized at the top?

Also, empty() is never needed when a variable is deliberately set. You can always use a variable itself for the purpose.

The PDO code could be also improved, in two ways

Positional placeholders are less verbose and there is no real use fro the named placeholder of only one variable is  going to be used.
Such a manual error handling (i.e. if($stmt = $pdo->prepare($sql))) is useless and harmful at the same time. An error message like "Oops! Something went wrong." would help noone. Please read my exhaustive explanation on the PHP error reporting for the details.

So here is the 1st tier refactoring, just to make your code tidy and meaningful:

<?php
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // why not to define a variable already with a value?
    $username = trim($_POST["username"]);
    $email = trim($_POST["email"]);
    $password = trim($_POST["password"]);
    $confirm_password = trim($_POST["confirm_password"]);

    // I would rather make errors an array than separate variables;
    $error = [];

    // Validate username
    if(!$username){
        $error['username'] = "Please enter a username.";
    } else{
        $sql = "SELECT id FROM users WHERE username = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$username]);
        if($stmt->rowCount()){
            $error['username'] = "This username is already taken.";
        }
    }

    // Validate password
    if(!$password){
        $error['password'] = "Please enter a password.";
    } elseif(strlen($password) < 6) {
        $error['password'] = "Password must have at least 6 characters.";
    }

    // Validate confirm password
    if(!$confirm_password){
        $error['confirm_password'] = "Please enter confirm password.";
    } elseif ($password != $confirm_password){
        $error['confirm_password'] = "Password did not match.";
    }

    // Check input errors before inserting in database
    if(!$error){
        $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash

        // Prepare an insert statement
        $sql = "INSERT INTO users (username, email,  password) VALUES (:username, :email, :password)";

        $stmt = $pdo->prepare($sql);
        // Bind variables to the prepared statement as parameters
        $stmt->bindParam(":username", $username);
        $stmt->bindParam(":email", $email);
        $stmt->bindParam(":password", $param_password);

        $stmt->execute();
        header("location: login");
        die;
    }
}

Just keep in mind that refactoring is an endless process, you can improve any code. but better to do it gradually, in order for you to understand every change as opposed to adding some cargo cult code mindlessly.


Since you're using bash (I assume a recent version of bash), you can use some advanced features, like associative arrays and indirect variables

#!/bin/bash

# If no argument is passed, act on all partitions.
if (( $# == 0 )); then
    a=t b=t c=t
else
    for arg; do
        if [[ $arg == a|b|c ]]; then
            declare $arg=t
        else
            echo "ignoring argument '$arg'"
        fi
    done
fi

declare -A uuids=( [a]=1234 [b]=3456 [c]=5678 )

for dest in a b c; do
    if [[ ${!dest} == t ]]; then
        sudo mount /dev/sb$dest "${uuids[$dest]}"
    fi
done

Note that the [ command acts differently when given different numbers of arguments. With just a single argument (such as [ $a="t" ]), you'll get a success exit status if the argument is not empty (and the string "$a=t" is not empty no matter the value of $a). You have to put spaces between all the operators and operands for [ and test and [[.


Integrating the Ace embeddable code editor for editing HTML, CSS, and JavaScript

Isolate what varies, and abstract out what's repeated:

$(function () {

ace.require("ace/ext/language_tools");
ace.require("ace/ext/emmet");  // I moved this out of html block, not sure if that matters

//Html editor
var htmlCallback = makeEditorCallback('html', false);
$('.editor_html').each(htmlCallback);

//CSS editor
var cssCallback = makeEditorCallback('css', true);
$('.editor_css').each(cssCallback);

//javascript editor
var jsCallback = makeEditorCallback('javascript', true);
$('.editor_js').each(jsCallback);

function makeEditorCallback(mode, useAutoComplete) {
  return function() {
    var type     = $(this).attr("data-key"),
        textarea = $('textarea[name="' + type + '"]').hide(),
        editor   = ace.edit(this),
        options  = useAutoComplete ?
                   {
                     enableBasicAutocompletion: true,
                     enableSnippets: true,
                     enableLiveAutocompletion: true
                   } : {};
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/" + mode);
    editor.setOptions(options);
    editor.getSession().setValue(textarea.val());
    editor.getSession().on('change', function() {
      textarea.val(editor.getSession().getValue());
    });
  }
}
});

This code is untested, but the basic idea is what's important.  You should be able to make any tweaks or changes that you need.

Also, note that you weren't using the index argument, so I removed it.


How to speed up interval lookup for a piecewise defined function?

It'll take some testing to be entirely certainly, but a few possibilities to consider:

if (x >= *cache && x < *(cache + 1)) {

I'd try replacing this with:

if (static_cast<unsigned>(x-*cache) < static_cast<unsigned>(*(cache+1) - *cache)) {

[Technically, unsigned is a place-holder here. It should really be something like std::make_unsigned<input_type>::type. That is, if the input is (say) long long, you want unsigned long long, not just unsigned int.]

This basically replaces two comparisons (that must be executed serially, thanks to && imposing a sequence point) with one plus a little extra math. The math can typically be done in parallel, and the branch becomes more predictable as well.

if (x < *begin || x > *end) {
    outside = true;
} else {
    outside = false;

I'd at least try just assigning the result of the comparison:

outside = x < *begin || x > *end;

Again, you can try the same "trick" as above, and get something like:

outside = static_cast<unsigned>(x-*begin) <= static_cast<unsigned>(*end-*begin);

As before, this replaces two relatively unpredictable comparisons with one relatively predictable one.

if (n_ < 64) {
[3%]    position = std::find_if(begin, end, std::bind2nd(std::greater_equal<argument_type>(), x)) - 1;
    } else {
        position = std::upper_bound(begin, end, x) - 1;
    }

If you're spending significantly more time in the linear search than the binary search, I'd try reducing the cut-off between the two, perhaps to 32 instead of 64.

As with any micro-optimization, none of these is really guaranteed to be effective. It's even possible your compiler may be incorporating one or more of them into the code it generates, so they'll do no good at all, or even that its optimizer won't recognize the resulting patterns in the code as well, so they could actually hurt performance. The only real way to find out is some testing and profiling.


Using raw types (generic types without type parameter) is a major violation:

List list = new ArrayList();

Never ever do this. In any case, as @JS1 already pointed out in comments,
this list in your implementation is unused anyway. (another major violation)

Declare variables in the smallest scope possible.
For example,
you could declare front inside the for statement,
and total inside the body:

for (int back = 0, front = 0; back < A.length && front < A.length; ) {
    front = back + 2;
    int total = A[front - 1] - A[back];

You could also convert the inner while loop to a for loop,
and declare the variable i inside the statement.


Importing Excel file to a database just once

Some notes:

AFAIK there is no consensus whether to write spaces or not after { and before }. But, definitely, always put an space after :.
This first line is too long. < 80/100 chars is more advisable. When writing hashes, it's easy: one line per pair. Much easier to read.
# if existed then return or continue the remaining: This comment is repeating the code, so it's not really conveying much.
Questions: Where does row come from? what does iterate_data_rows return?
Answering your question about the if, you have two options (you wrote the intermediate, which is not advisable):

One-line guard: return false if ImportHistory.where(q_param).exists?
Move the rest of the code within the else (I like this one).

I'd write:

def import_excel_to_database(xls_file_path)
  q_param = {
    report_type: report_type,
    item: product,
    exchange: exchange,
    product_exchange: row[0],
    date: row[2],
    # timestamp_utc: row[2].strftime('%Q').to_i,
  }

  if ImportHistory.where(q_param).exists?
    false
  else
    ImportHistory.create(q_param)
    xls = Roo::Excel.new(xls_file_path)
    xls.default_sheet = xls.sheets[0]
    columns = get_columns(xls.row(1))
    iterate_data_rows(xls_file_path, xls, columns)
  end
end


Avoiding code repetition

As pointed out in some of the other answers, getting a double value from the keyboard can be abstracted into its own method to avoid code repetition:

private static double getDouble(Scanner scanner, String metric) {
    System.out.println("Enter " + metric);
    double result;
    while (!scanner.hasNextDouble() || (result = scanner.nextDouble()) <= 0) {
        System.out.println(metric + " must be a positive number.");
        scanner.next();
    }
    return result;
}

try-with-resources

If you are on Java 7 and above, you should use try-with-resources for efficient handling of the underlying I/O resource:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        double weight = getDouble(scanner, "Weight (kg)");
        double height = getDouble(scanner, "Height (m)");
        System.out.println("Your BMI is: " + /* calculation */);
    }
}

Units

It's important to note that BMI is expressed in units of \$\frac{kg}{m^2}\$, so you should definitely display the units of measurement too. Otherwise, you'll need extra methods to perform the conversion to kilograms and meters. :)

Comments

Simply put, comments should explain the why, not how. Most of your comments now are just descriptive, i.e. on the how, which is already apparent in the code. Comments are sometimes seen as redundant as they are prone to being outdated. Therefore, comment sparingly, and only when you really need it to explain something that is non-obvious. Even so, try to make the code 'obvious' first. :)


Displaying the grid

Personally, I would move displaying the grid into a separate function, such as display_grid:

def display_grid() -> None:
    for row in game:
        print(row)

This removes the need to keep having to write the loop over and over.

Picking the player

Another personal preference is that I would have the user input both the row and column as the input, and just split what they inputed to get the values. Removes the need to have multiple input calls, and makes the game a little easier to play.

def pick_player(current_player: int) -> (int, int):
    row, col = input(f"Player {current_player} Turn!\nEnter row and column of choice: ").split()
    if row.isdigit() and col.isdigit():
        row, col = int(row), int(col)
        if game[row - 1][col - 1] == 0:
            game[row - 1][col - 1] = current_player
        else:
            print("Position already taken! Skipping turn!")
        return row, col

Checking the board

Instead of having three separate functions to check the board, you should group all the conditionals into one function. Now, I did a bit of fixing and this function, check_win, checks all the ways the game can be won.

def check_win():
    return any([
        game[0][0] == game[1][1] == game[2][2] != 0,
        game[0][2] == game[1][1] == game[2][0] != 0,
        any([row.count(row[0]) == len(row) and row[0] != 0 for row in game]),
        any([len(set([game[i][j] for i in range(3)])) == 1 and game[0][j] != 0 for j in range(3)])
    ])

You can use any to determine if any of the elements in an iterable are True. The last line in this functions does the vertical checking. Spent a good deal trying to make this one line, and it looks pretty good. Basically, the set call removes all duplicates and retains the single values. For example, set([1, 1, 2]) results in {1, 2}.

With this information, if the length of the set is one, and the single value isn't 0, then a winner has been found. That's all that line is doing.


Like Kennebec's original answer, the code is inconsistent in its identification of different versions of browsers. For example, Internet Explorer 9 will appear as MSIE 9.0 while Internet Explorer 11 (which despite forsaking the family name still wields the trident of its ancestors) will appear as Internet Explorer 11. Since you have direct control over the name returned for a trident-detected version of IE, why not return "MSIE" instead of "Internet Explorer"?

Super minor nitpick: you misspelled "guarantee" in the code comments.


I think the for loop can show the "breaking condition" like this:

for (uint i = 0; (newPort = GetPortData(i)) != null; i++) {
    ports.Add (newPort);
}


Generalized PHP function for editing data in a table

Simply put, this code fails a lot best practices also contains massive security issues.
Suggestion to improve for best practices:

  $GLOBALS["HTTP_POST_VARS"] is deprecated in favor of $_POST

So you looping over $GLOBALS["HTTP_POST_VARS"] and $_POST is redundant and bad mojo. Just looping over $_POST will accomplish the same thing. Same goes for $GLOBALS["HTTP_GET_VARS"] and $_GET.

  You should be passing in the $link object as parameter.

Since there is no code intended to change the database connection conditionally (the connect parameters are always the same). This prevents your scripts creating multiple database connection resources and destroying them (more memory and time consuming). Also passing in the database resource as parameter to the function is a type of dependency injection which makes your code testable should you want to in the future. Since this also appears to be in a class, consider creating the database connection in the __construct and use that single instance.

  Using sessions in favor of $GLOBALS

Pretty much any use of $GLOBALS is considered bad practice. I'm sure there are a few exceptions to the rule. But there you should definitely not be using is for storing data in a scopeless fashion. This is what sessions are for.

  removeQuotes() is never called on $fldname or $fldval

As you can imagine this a serious security issue leaving your script open to SQL Injection attacks.

  Use mysql_real_escape_string in favor of home made sanitising functions i.e. removeQuotes()

There is a lot more to safe escaping query parameters that remove slashes. And in my experience home made sanitising functions often quietly fail when you have mixed string and number parameters.

As a matter of readability and style I would make to following suggestions, I know these are subject matters but there are common ways of doing things.

  Substitute the use of string concatenation

$query.="`".$field."`=";
$query.="'".$this->removeQuotes($$field,$lang_flag)."' , ";
... more concatenation ...
$query = substr($query,0,-2);

for array joining

$queryParams[] = "`".$field."`='".$this->removeQuotes($$field,$lang_flag)."'";
... more array filling ...
$query = join(',', $queryParams);

General WTFs

  This is doing nothing at all $query  ;

And code that does nothing is very bad mojo.

  Call count() once.

This is not really an issue, doing something like this

for($p=0;$p

In actual fact calls count() on every iteration of the loop, even though the return value will never change. It causes the interpreter to do more work than necessary, although I suspect during compilation to byte code this would be optimised automatically. This could be substituted for:

// only call count() once
$count = count($arr_types);
for($p=0;$p<$count;$p++)

  Don't nest unnecessarily.

Don't nest conditionals (if/else/switch) and loop(while/for) unnecessarily. It makes for messier code, code that's harder to read and follow mentally, and importantly difficult to test.

if(isset($$field))
{
     $query.="`".$field."`=";

     $query.="'".$this->removeQuotes($$field,$lang_flag)."' , ";
 }
 else
 {
     if(isset($GLOBALS["$field"]))
     {
         $query.="`".$field."`=";
         $query.="'".$this->removeQuotes($GLOBALS["$field"],$lang_flag)."' , ";
     }
 }

The above code is exactly equal to the following, notice less nesting.

if(isset($$field))
{
     $query.="`".$field."`=";

     $query.="'".$this->removeQuotes($$field,$lang_flag)."' , ";
 }
 else if(isset($GLOBALS["$field"]))
 {
         $query.="`".$field."`=";
         $query.="'".$this->removeQuotes($GLOBALS["$field"],$lang_flag)."' , ";
 }

Personal preference

  This is completely subjective, but something to think about.

if(stristr($k,$arr_types[$p])!="")

equal to

if(stristr($k,$arr_types[$p]) == true)

equal to

if(stristr($k,$arr_types[$p]))

  Considering the above, this:

while (list($k,$v)=each($_GET))
{
    for($p=0;$p < count($arr_types);$p++)
    {
        if(stristr($k,$arr_types[$p])!="")
        {
            $k = str_replace($arr_types[$p],"",$k);
        }
    }
    ${strtolower($k)}=$v;
}

Is exactly the same as:

while (list($k,$v)=each($_GET))
{
    $count = count($arr_types);
    for($p=0; $p<$count; $p++);
    {
        $k = str_replace($arr_types[$p],"",$k);
    }
    ${strtolower($k)}=$v;
}

Which would you rather test and/or work with?


How to remove code duplication that difference only a few lines?

Based on your code as that is what we are reviewing a couple of suggestions.

Pass in a delegate that handles the changeable part
Use Template method pattern to implement the changing parts
Use composition and DI to inject the different elements

Example: Using delegates

private void DoMethod12(Action doMyAction)
{
    DoX();
    doMyAction();
    DoY();
}

public void Method1()
{
    DoMethod12(_ =>
    {
        var input = GetA();
        DoA1();
        DoA2(input);
    });
}

public void Method2()
{
    DoMethod12(_ =>
    {
       var input = GetB();
       DoB(input);
    });
}

Example 2: Template pattern

public abstract class MyDo
{
    protected abstract DoMyAction1();
    protected abstract DoMyAction2();

    public void Method1()
    {
        DoMethod12(doMyAction);
    }

    public void Method2()
    {
        DoMethod12(doMyAction2);
    }

    private void DoMethod12(Action doMyAction)
    {
        DoX();
        doMyAction();
        DoY();
    }
    private void DoX()
    {
    }
    private void DoY()
    {
    }
}

public class MyDoer : MyDo
{
    protected override DoMyAction1()
    {
           var input = GetA();
           DoA1();
           DoA2(input);
    }

    protected override DoMyAction2()
    {
       var input = GetB();
           DoB(input);
    }
}

Example 3: DI and composition

public interface IMyDoer
{
    void MyMethod1();
    void MyMethod2();
}

public class MyDoer
{
   private MyDoer _doer;

   public MyDoer(IMyDoer doer)
   {
      _doer = doer;
   }

    public void Method1()
    {
        DoMethod12(_doer.MyMethod1);
    }

    public void Method2()
    {
        DoMethod12(_doer.MyMethod2);
    }

    private void DoMethod12(Action doMyAction)
    {
        DoX();
        doMyAction();
        DoY();
    }

    private void DoX()
    {
    }
    private void DoY()
    {
    }
}

These written in notepad so no guareentee on exact syntax although hopefully they can give some ideas.