Parse a simple key=value config file in C

Interface
I'm not overly fond of the interface you've defined to the function. I think trying to combine reading integers and reading strings into a single function makes it more difficult to use. For most C code, I think the old guiding principle of UNIX ("do one thing, and do it well") provides excellent guidance. As such, I'd probably have two separate functions, one for reading a string, the other for reading a number.
I haven't tested it to be sure, but at first glance it also looks like if you ask to read a number, it does a poor job of signalling failure. For example, if your file has: foo=0 and you try to read foo as a number, it'll set the number to 0, and return 0. But if the file contains foo=Joe instead, it looks to me like it'll do exactly the same.
I'd prefer that if it couldn't convert the rest of the line after the = to a number that it return 1 to indicate that it has failed.
Memory Allocation
Since you only use our left and right inside of your function, and free them again before returning, there's probably no need to allocate them on the heap. You can just allocate them as local arrays, and use them. The obvious exception to this would be if you were targeting a tiny micro-controller that might well have less than 256 bytes available on the stack. In that case, however, you usually won't have a file system either, so the entire function becomes irrelevant.
Standard Library
I think judicious use of fscanf can simplify the code quite a bit.
For reading a string, it seems like the obvious interface would be to just return the value part of the pair, and if it's not found, return a NULL pointer:
char *read_string(FILE *file, char const *desired_name) {
    char name[128];
    char val[128];

    while (fscanf(file, "%127[^=]=%127[^\n]%*c", name, val) == 2) {
        if (0 == strcmp(name, desired_name)) {
            return strdup(val);
        }
    }
    return NULL;
}

When reading a number, we probably need something closer to your original interface, with a return value to indicate success/failure, and receive a pointer to an int where we write the value (if it's found):
int read_int(FILE *file, char const *desired_name, int *ret) {
    char *temp = read_string(file, desired_name);

    char *stop;
    *ret = strtol(temp, &stop, 10);
    int ret_val = stop == NULL || *stop != '\0';
    free(temp);
    return ret_val;
}

Note that as it stands right now, the return value reflects converting the entire remainder of the line (everything after the =) to the desired number. If part of it can be converted, that part will be written to the destination, but the return will still indicate failure. For example, if you had foo=1234abcd, attempting to read foo as a number would give you 1234, but return 1 because the abcd part couldn't be converted.
It would also be possible to simply ignore any trailing garbage, so foo=1234abcd would read the 1234 part, and return 0 to signal success:
int read_int(FILE *file, char const *desired_name, int *ret) {
    char *temp = read_string(file, desired_name);

    char *stop;
    *ret = strtol(temp, &stop, 10);
    int ret_val = stop == temp;
    free(temp);
    return ret_val;
}

In this case, we just need to check that at least one character was converted, in which case stop will have be advanced at least one character after the input.


There are couple of things that might have been done better...

Initilize the dictionary form a static constructor or call the method to initialize the field. The method should not access it internally but return a dictionary as a result. The field itself should be readonly.
foreach could be used to iterate the stringToEncode.
Names of internal variables could be better:

Convert sounds like a method name. The dictionary should be named Conversions.
nums should be digits
sb should be called encoded

TryGetValue could have been used instead of ContainsKey
The dictionary is case-insensitive only because you put all letters there. Instead you should use the StringComparer.OrdinalIgnoreCase and make the dictionary <string, char> but this would be inconvenient. You could create your own IEqualityComparer<char>. This will cut in half its size .
I wish more var (optional)
I wish more LINQ

Things that are already good:

I find using a dictionary was a good choice.
The use of a Stack to reverse the order is very clever.
Using StringBuilder for efficiency is definitely a good choice either.

When we apply all suggestions the code could look like this:

Creating the IReadOnlyDictionary which returns a result and uses a couple of additional helper variables. No for loops.

// pre processed conversions for letters
private static readonly IReadOnlyDictionary<char, char> Conversions = BuildConversionDictionary();

private static IReadOnlyDictionary<char, char> BuildConversionDictionary()
{
    var conversions = new Dictionary<char, char>(CaseInsensitiveCharComparer);

    var alphabet = Enumerable.Range('a', 'z' - 'a' + 1).Select(x => (char)x);
    var vowels = new char[] { 'a', 'e', 'i', 'o', 'u' };
    var consonants = alphabet.Except(vowels);

    // consonants are replaced with previous letter b->a, c->b, etc
    foreach (var c in consonants)
    {
        conversions.Add(c, (char)(c - 1));
    }

    // y goes to space
    // space goes to y
    conversions['y'] = ' ';
    conversions[' '] = 'y';

    // vowels are replaced with number: a->1, e->2, etc
    foreach (var (c, i) in vowels.Select((c, i) => (c, i + 1)))
    {
        conversions.Add(c, (char)('0' + i));
    }

    return conversions;
}

The alternative equality comparer (here I'm using a helper-factory from my libraries):

private static IEqualityComparer<char> CaseInsensitiveCharComparer =
    EqualityComparerFactory<char>.Create
    (
        (x, y) => StringComparer.OrdinalIgnoreCase.Equals(x.ToString(), y.ToString()),
        obj => StringComparer.OrdinalIgnoreCase.GetHashCode(obj.ToString())
    );

The refactored encode (which should be Encode). What has changed here is that I first check for digits. If it's not one and we have some then dump the stack to the builder and clear it, othewise do the rest. Below the loop we have to dump it once again in case there are some digits left at the end.

public static string Encode(string stringToEncode)
{
    if (string.IsNullOrEmpty(stringToEncode)) throw new ArgumentException(nameof(stringToEncode));

    // our return val (efficient Appends)
    var encoded = new StringBuilder();

    // used for reversing the numbers
    var digits = new Stack<char>();

    // iterate the input string
    foreach (var c in stringToEncode)
    {
        if (char.IsDigit(c))
        {
            digits.Push(c);
            continue;
        }

        if (digits.Any())
        {
            encoded.Append(digits.ToArray());
            digits.Clear();
        }

        if (Conversions.TryGetValue(c, out var converted))
        {
            encoded.Append(converted);
            continue;
        }

        // something else, undefined
        encoded.Append(c);
    }

    // "dump" what's left
    encoded.Append(digits.ToArray());

    return encoded.ToString();
}

I think you cannot do anything else having only 60 minutes.


This looks pretty good, not much room for improvement I think. LinkedIn's JavaScript is calling linkedInApplySuccess, correct? All you have to do is specify data-success-callback, or something similar, in your HTML?

The only minor thing I would do is instead of sending just the job ID, send the entire JSON object. As long as resources aren't an issue, it's always best to capture all data and disregard the stuff you don't use rather than only collect the stuff you're currently using; this is because requirements change, and in the future you may want to do something with the data you've been ignoring. For instance, you may want to calculate how many people are applying for jobs with the position "Chief Weasel Wrangler".

You can alter your code to something like this:

$.post("/php/cv_db/ajax_log_linkedin_application.php", {application: jsonReturnObj});

(application refers to "job application" not "computer application" – maybe too ambiguous)


The accepted answer in the linked question uses a cirucular linked list, which is the data structure that most closely represents this situation. That answer shows how to do that implementation, so I'll instead focus on the approach you look to be taking, which can be equally valid if it produces equivalent results.

public static void main(String[] args) throws Exception {

Why does your main method throw Exception? This is useless and potentially confusing. Your code does not encounter any expected exceptions, so why are you telling the reader to expect one? The exception you are telling them to expect is any exception, which is itself completely unhelpful. If your program encounters an uncaught exception, it will die just the same. Drop the throws Exception.

int numberOfGuys = 100;

Here, this is fine, but many people would probably just move it outside the method as static final int NUMBER_OF_GUYS = 100; since it is essentially a constant (unless you are planning to vary it with input in another iteration of the program).

MyObject[] objetList = new MyObject[numberOfGuys];

Two major issues here. First is naming. MyObject is a terrible name that tells the reader nothing of the nature of this class. A better name might be Gunman or Shooter, etc. For the variable name, objetList is also a terrible name. First, it looks very close to objectList, which increases the possibility of misspellings. It also says little to the nature of the variable, and what it does say is wrong. The suffix "List" might be interpreted to mean that this is a List object, but it is not. A better name might be gunmen or shooters (preferably matching off of the class name of the objects it holds).

The second major issue is the data structure chosen. We know that we will be removing elements from this structure, but we also know this is not efficient with a primitive array. Either we delete by using nulls, having to check that condition through the loop, or we delete by making a copy of the array, sans an element, each time we remove an element. A data structure built for this type of scenario is a List. There are several to choose from, each giving a potentially different performance profile, but we can just pick one to start and change that later if performance demands are not met.

for(int i=1;i<numberOfGuys+1;i++) {
    objetList[i-1] = new MyObject(i);
}

First, spacing is important. It is much harder to read code that does not have spacing around operators and such. Second, you perform excess operations that confuse what the loop is doing. Rather than start at one, go to numberOfGuys + 1, and insert at index objetList[i-1], start at 0. It would look more like this:

for(int i = 0; i < numberOfGuys; i++) {
    objetList[i] = new MyObject(i + 1);
}

boolean oneElementLeft = false;
while(!oneElementLeft) {
    ...
    if(objetList.length==1) {
        oneElementLeft = true;
    }
}

(SPOILER: Read all the way through this part before changing the code.)

This code tells a story, but it has a lot of noise in it. We test against a boolean, and exit out of the loop if it changes. We will only change that boolean based on a boolean test (objetList.length == 1) checked at the end of the loop. We already have a loop structure that does this more succinctly: the do-while loop! We could rewrite it so that we just have do { ... } while(objetList.length != 1); So much cleaner! And wrong. The story this code tells is misleading, and is in fact buggy. If objetList.length is already 1, we don't want to do anything! What we want is a simple while loop without the need for the flag:

while(objetList.length > 1) {
    ...
}

for(int i=0;i<objetList.length;i++) {
    if(i != objetList.length-1 && (i+1)%2==1) {
        objetList[i+1]=null;
    }
    if(i == objetList.length-1 && objetList[i] != null) {
        objetList[0]=null;
    }

}

Again, spacing.

These conditionals do not really tell a clear story. First of note, (i+1)%2 == 1 is asking if i plus one is odd. What it is really asking, though, is if i is even, or the same thing more succinctly, i % 2 == 0. (You will also see this written as i & 1 == 0 on occasion). Looking more generally, though, we are nulling the odd elements, and the first element if the list is an odd length. The conditionals don't come out and say this clearly, though. We check if we are at the end of the list every iteration, and do something when we reach the end only under certain special conditions. It is not totally clear that the condition is when the list is an odd length, either. More clearly, we can write:

for(int i = 0; i < objetList.length - 1; i += 2) {
    objetList[i + 1] = null;
}

if(objetList.length % 2 == 1) {
    objetList[0] = null;
}

Also note the vertical spacing used here. We often need space in both directions to make code the most readable.

List<MyObject> newList = new ArrayList<MyObject>();
for (MyObject myObject:objetList) {
    if(myObject != null) {
        newList.add(myObject);
    }
}
objetList = new MyObject[newList.size()];
for(int i=0;i<newList.size();i++) {
    objetList[i] = newList.get(i);
}

Here the code is basically just shuffling array data. This is the biggest indicator that a primitive array is the wrong data structure to be using.

I wrote the following version that accomplishes the same thing in a similar (non-circular) manner. It can probably be improved by using an iterator inside of it, but it suffices on its own.

Main class:

public class Main
{
    public static final int NUMBER_OF_GUNMEN = 100;

    public static void main(String[] args) {
        List<Gunman> gunmen = new ArrayList<>(NUMBER_OF_GUNMEN);
        for(int i = 1; i <= NUMBER_OF_GUNMEN; i++) {
            gunmen.add(new Gunman(i));
        }

        while(gunmen.size() > 1) {
            for(int i = 0; i < gunmen.size(); i++) {
                Gunman killer = gunmen.get(i);
                Gunman killed = gunmen.remove((i + 1) % gunmen.size());
                System.out.println(killer.getNumber() + " kills " + killed.getNumber());
            }
        }

        System.out.println("\n" + gunmen.get(0).getNumber() + " lives another day...");
    }
}

Gunman class:

public class Gunman
{
    private int number;

    public Gunman(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }
}


Some general comments first.

There's no need to make your throws in strings for the outcomes - you can use tuples instead. e.g.

self.outcomes = { (2,):False, (5,5):True }

If you pass a "wrong" set of dice throws (say \$[4,5]\$), you'll have an exception raised which isn't dealt with (and should probably be a test?).
pop removes the last element, which means you process them in reverse order - which differs from what the casual reader might expect (\$[7,5]\$ = 7 first, then 5).

You may want to look at generators which would provide a nice interface to a throw. In this case, what about:

class DiceThrow:
    def __init__( self, rolls = None ):
        self.rolls = rolls
    def First( self ):
        return self.__next__()
    def __iter__( self ):
        return self
    def __next__( self ):
        if self.rolls is not None:
            if len( self.rolls ) == 0:
                raise StopIteration
            r = self.rolls[0]
            self.rolls = self.rolls[1:]
            return r
        return randrange( 1, 13 ) # may be better as randint( 1, 12 )

This can then be called as follows:

game.play( DiceThrow( [5,7] ) )
game.play( DiceThrow() ) # for a random set of throws

and used:

def play(self, dice_throw):
    comeOut = dice_throw.First()
    print( "began game with %d"%comeOut )
    if (comeOut,) in self.outcomes:
        return self.outcomes[(comeOut,)]
    for point in dice_throw:
        print( "next roll is %d"%point )
        state = (comeOut,point)
        if state in self.outcomes:
            return self.outcomes[state]
    print( "Bad rolls!" )


Finding as many perfect numbers as possible

The biggest improvement to this code is to use a prime generator that uses an efficient sieve. I will use the one here in my answer, as it is really fast.

from itertools import count
                                     # ideone.com/aVndFM
def prime_sieve():                   # postponed sieve, by Will Ness
    yield 2; yield 3; yield 5; yield 7;  # original code David Eppstein,
    sieve = {}                           #   Alex Martelli, ActiveState Recipe 2002
    ps = prime_sieve()               # a separate base Primes Supply:
    p = next(ps) and next(ps)            # (3) a Prime to add to dict
    q = p*p                              # (9) its sQuare
    for c in count(9,2):                 # the Candidate
        if c in sieve:               # c's a multiple of some base prime
            s = sieve.pop(c)         #     i.e. a composite ; or
        elif c < q:
             yield c                 # a prime
             continue
        else:   # (c==q):            # or the next base prime's square:
            s=count(q+2*p,2*p)       #    (9+6, by 6 : 15,21,27,33,...)
            p=next(ps)               #    (5)
            q=p*p                    #    (25)
        for m in s:                  # the next multiple
            if m not in sieve:       # no duplicates
                break
        sieve[m] = s                 # original test entry: ideone.com/WFv4f

This function gives two advantages: first, it is much more efficient, but it also makes the rest of the logic easier. Instead of going through odd numbers, testing if they are prime, and if they are using them, the logic becomes simply

def calculate_perfects():
    yield 6
    primes = prime_sieve()
    for prime in primes:
        if is_mersenne_prime(prime):
            yield 2**(2*prime-1)-2**(prime-1)

This is not a lot faster because almost all of the time is spent in is_mersenne_prime, but it is cleaner and about 1% faster.

If we want actually faster performance, however, we need to look at is_mersenne_prime. Profiling reveals that 25% of the time is spent in the for i in range(prime-2) line. This is unfortunate, as there is very little to do to speed this up. However, the other 75% is in s = (s*s - 2) % mersenne_prime. While this initially appears to be a dead end, it isn't quite. It is probably obvious that the expensive operation here is the mod call, and thanks to some number theorists much smarter than me, it turns out that k % 2^n-1 is the same as k & 2^n + k>>n mod n. Since this only uses bitwise opps, it is much faster. below is an implementation.

def mod_mersenne(n, prime, mersenne_prime):
    while n > mersenne_prime:
        n = (n & mersenne_prime) + (n >> prime)
    if n == mersenne_prime:
        return 0
    return n

if we call this in is_mersenne_prime, it is over 3x as fast as before. Here is the updated is_mersenne_prime code

def is_mersenne_prime(prime):
    mersenne_prime = 2**prime - 1
    s = 4
    for _ in range(prime - 2):
        s = mod_mersenne((s*s - 2), prime, mersenne_prime)
    return s == 0

On my computer this takes 5.2 instead of 16.4 seconds to generate the first 16 perfect numbers.

The next improvement we can get comes from using multiple processes. Each time is_mersenne_prime is run, it is run with information that doesn't depend on any other run. As such, we can test several numbers at a time. Here is the code that does this.

from itertools import count, compress
from multiprocessing import Pool

def calculate_perfects():
    yield 6
    primes = prime_sieve()

    pool = Pool(processes=8)
    while True:
        next_primes = [next(primes) for _ in range(8)]
        is_mersenne = pool.map(is_mersenne_prime, next_primes)
        for prime in compress(next_primes, is_mersenne):
            yield 2**(2*prime-1)-2**(prime-1)

This code is a little uglier, two lines longer, but can calculate the first 20 mersenne primes in 2.3 seconds (1.5 on pypy3)

More speedups can be found by not running the test if 2**prime-1 has an easily findable small factor. Such factors must take the form 2*k*prime+1, and factor in (1, 7) mod(8).factor will be in (1,7) at specific points depending on whether prime=4n+1 or 4n-1. The following code checks for these factors, and is a good first check before Lucas-Lehrer

def has_small_factor(prime, limit):
    """ Does 2**prime-1 have a factor less than 2*prime*limit? """
    step = 2 * prime
    if prime % 4 == 1:
        wheel = cycle((0,0,1,1))
    else:
        wheel = cycle((1,0,0,1))
    for factor in compress(range(1 + step, step*int(limit), step), wheel):
        if factor%15 in (3, 5, 9):
            continue
        if pow(2, prime, factor)-1 in (0, factor):
            return True
    return False

At this point the slowest thing about our code is that we have to multiply large numbers together. The good news is that gmpy2 has a library that makes this faster. Importing it and modifying the code to be mersenne_prime = 2**mpz(prime) -1, yields a 3x speedup (although it doesn't work well with pypy). At this point my laptop can find the first 24 perfect numbers in 33 seconds.


Python script that make my .bash_aliases file MUCH more readable and clear

print
f-Strings are a great and convenient tool for including variables and calculations in strings. I'd say they're generally not needed when printing only variables. For example
print(f'{bcolors.WARNING}{line}{bcolors.ENDC}')

could become
print(bcolors.WARNING, line, bcolors.ENDC, sep='')

However I'm not sure which of the two is more pythonic, I personally prefer the latter for readability.
You could also consider pulling out formatting into seperate variables to increase readability.
HEADER_FORMAT = "".join((bcolors.HEADER, bcolors.UNDERLINE, bcolors.BOLD, "{}", bcolors.ENDC))

print(HEADER_FORMAT.format(line))

in vs. startswith
I'd recommend using str.startswith instead of str in str for checking prefixes.
if r'##' in line:

becomes
if line.startswith(r"##"):

This is less error-prone and conveys your intentions more explicitly, without the need to look at the source file. As there aren't any escape characters in your prefixes, you also don't need to make it a raw string. You can simply drop the r:
if line.startswith("##"):


Read and output a json object with the least server processing expenditure possible

The code can be slightly improved, but it won't make much of a difference overall. This whole approach seems a bit weird. Why does the JSON file exist in the first place?

Here is the 'improved' version:

<?php

// read the json file on the server
$txt = file_get_contents("json");

// get the id of the application
$id = filter_input(INPUT_GET, "id", FILTER_SANITIZE_STRING);
if (isset($id)) {
    // decode json
    $json = json_decode($txt, true);
    // remove all other ids from the list
    $appInfo = $json["ids"][$id];
    unset($json["ids"]);
    $json["ids"][$id] = $appInfo;
    // encode and return json
    echo json_encode($json);
}
else {
  // simply echo the content
  echo $txt;
}

I sanatized the input by using filter_input(). That's not really needed, but always a good idea. I also simplified the code a bit more.

This is only a tiny piece of code, so there's not much I can do. I have a feeling that more could be achieved if we knew why you do this in the first place. What is this JSON used for?

=============================================

I couldn't resist proposing the code below for the "filechanger".

<?php

// read the json file on the server
$txt = file_get_contents("json");
// decode json
$json = json_decode($txt, true);
// get all application information
$appInfos = $json["ids"];
// write the to separate files
foreach ($appInfos as $appId => $appInfo) {
    // set application info
    unset($json["ids"]);
    $json["ids"][$appId] = $appInfo;
    // create file name
    $filename = str_replace(" ", "_", $appId) . ".json";
    // encode and save json
    file_put_contents($filename, json_encode($json));
}


Looks good overall. Only a few minor quibbles:

Comments. Always a good idea. Write some.
What's with the show-and-immediately-hide-excert stuff in the ready event handler? I have no idea (I no comments to help me).
Don't "outdent" when inside a block (i.e. function or control flow construct). Your var declarations should be indented like anything else.

function () {
  // indent
  // everything
  // inside
  // the function
}

Don't put a linebreak right after var; put the first variable on the same line.
Personally, I indent following declaration lines by 4 spaces, to make them line up:

var textW = $headline.width(),
    parentW = $parent.width(),
    ratio = parentW / textW;

// more code

Tools like jslint yell at me for doing that, but I find it makes things more readable.
Combine your declarations. In fitheadliner you have 3 groups of var declarations in a row. I understand the grouping - it makes sense - but I'd either use a separate var for each line, or one big chunk. If you want to keep the grouping, you can separate declaration and assignment, e.g.:

function fitHeadings() {
  $(".bigHeadline").each(function() {
    var $headline, $parent,
        textWidth, parentWidth, ratio,
        originalSize, newSize;

    $headline = $(this);
    $parent = $headline.parent();

    textWidth = $headline.width();
    parentWidth = $parent.width();
    ratio = parentWidth / textWidth;

    originalSize = parseFloat($headline.css('font-size'));
    newSize = originalSize * (0.99 * ratio);

    $headline.css("font-size", newSize);
  });
}

A couple of notes to the above:

I've assigned $headline first, to avoid calling $(this) twice to also get the $parent.
I've added a zero to 0.99 because why not? Yeah, the shorthand works, but it really doesn't do anything. Writing 0.99 is a perfectly natural way to write a number.
Oh, and I've renamed the function to use camelCase to separate the words, and change headings to Headlines, since a) it's plural, and b) they're headings, not "headliners".

Of course, some might say you're overdoing the variable declarations for something rather trivial. This would work just as well:

function fitHeadlines() {
  $(".bigHeadline").each(function() {
    var $this = $(this), $parent,
        ratio = $this.parent().width() / $this.width(),
        newSize;

    newSize = 0.99 * ratio * parseFloat($headline.css('font-size'));
    $headline.css("font-size", newSize);
  });
}

By the way, why multiply by 0.99? Again, comments would be nice.
A more jQuery-esque way to attach the same event handler to multiple elements would (in most situations) be to attach the handler to a common parent object, and use the selector as a filter:

$(document).on('click', 'img.moreInfo', function(event) {
  // handle click
});

Also, a more jQuery-esque way to write a document ready handler is to just say:

$(function () {
  // this is run on document ready
)};

Be consistent with your whitespace. You have:

( function( $ ) {

and:

$( document ).ready(...)

but then you have:

$(window).resize(...)

I'd stick the latter; the other ones are maybe a bit to "spacey".


For simple 10 lines 10 programs you can get away with this:

using namespace std;

Anything bigger and it starts to be a pest more than a help. Thus it best not to get into the habit of using it. Anyway it is simpler even in this case just to prefex cout with std:: (that is why standard is named std to make it short and easy to use).

You don't initialize the value of j in your class.

int j;

Thus any usage is undefined behavior.

You have two options:

Add a constructor that initaizes j
Always force zero-initialization of your class.

In anything but this trivial program I would go with (1) and add a constructor. But just to show zero initialization the alternative is:

 Test  t = Test();  //  The () brackets at the end of Test() force zero initialization;

Note: The equivalent for new is

 Test* t = new Test();  // force zero-initialization (when no constructor)
 Test* t = new Test;    // Use default-initialization (un-initialized)

Note 2: Normally you would think you could do this:

 Test  t(); // Unfortunately this is a forward declaration of a function.

Note 3: But you can get around the problems of (2) by using extra braces.
        As pointed out last time I tried to answer a question like this.

 Test  t(()); // Unfortunately this confuses people and maintainers have been
              // known to try and take out the extra braces. With mixed results.
              // This is why I still prefer method 1

 Test t = Test(); // This may look like there is an extra copy.
                  // But every compiler implements the optimization to do construction
                  // in place.
              // Thus I prefer method 1 (ie this method)

Described here: https://stackoverflow.com/questions/5914422/proper-way-to-initialize-c-structs/5914697#5914697

For such a simple class I don't think you need to worry about the safe bool idium. This just protects your class from being used in places where arithmatic would be done:

 Test t;
 int x = 5 + t;  // Here we get conversion to bool
                 // which is then converted to int (0 or 1)
                 // The safe bool idium would protect you from this:

To use it do this:

 operator bool() { return j%26; }

 // Remove the above and replace with

 operator void*() {return j%26 ? &j /* or this the value is not important as long as it is not NULL */ : NULL; }


There are some major issues with your approach, the major one being that it is going to terribly break down for really large numbers. But if you want to go with it, here are a couple of improvements:

Don't use a dictionary. If your indices are consecutive integers, then a list is the right data structure.
You already know that most of your entries are going to be False, so why not initialize those in bulk and worry only about setting the Trues?

def is_power_of_two(n):
    sieve = [False] * (n + 1)
    pot = 2
    while pot < len(sieve):
        sieve[pot] = True
        pot *= 2
    return sieve[n]

The name sieve is taken from the approach being somewhat similar to the sieve of Erathostenes algorithm.

In your case you can take things one step further, and rather than storing the full array, store only the indices of the True entries:

def is_power_of_two(n):
    pots = [2]
    while pots[-1] < n:
        pots.append(pots[-1]*2]
    return pots[-1] == n

If you look at that code, you don't really need to store the whole array, since you are only using the last value. So you can get the same time complexity, \$O(\log n)\$, but with constant space, by doing:

def is_power_of_two(n):
    pot = 2
    while pot < n:
        pot *= 2
    return pot == n

Of course the proper, fast way of checking if a number is a power of two is with a little bit twiddling hack that give \$O(1)\$ performance:

def is_power_of_two(n):
    return not n & (n - 1)


Extract a list of users from a text file

There are quite a few possible improvements.

You should open files with the with keyword, this way they get closed no matter what (you don't even close your file).

if 'user' and 'password' in lines: does not mean what you think it does. All non-empty strings are truthy in Python, so if "user" is always True. So you only really check that the line contains "password". Fortunately you don't have any lines containing "password", but not "users", so this bug has not yet become obvious.

The easiest fix for this would be using this:

if "user" in lines and "password" in lines:
    # Stuff

In summary, I would re-write your code like this:

with open("haproxyfile.txt") as f:
    users = [line.split()[1] for line in f
             if line.strip().startswith("user") and "password" in line]

print users

Note that I omitted the "r" parameter to open, because read-only is the default mode. I also used str.startswith to check if it starts with a string. The strip is probably needed, to get rid of the whitespace at the beginning of your lines. If that is a copy&paste error as well, omit it.

I also wrote it as a list-comprehension and used the fact that you can directly iterate over a file.


Alignment
This will be an easy win - use aligned_alloc instead of malloc. This is only guaranteed to be available in the standard library as of C11, which you should be using anyway.
Exponential reallocation
This:
        // gracefully extend buffer size
        nofs++;
        buf = realloc(buf, BUF_SIZE*nofs*sizeof(char));

reallocates with linear growth. Memory is cheap and CPU time is expensive, so reallocate with exponential growth instead. Choosing a growth factor is a little more involved, but growth factors of 1.5 or 2 are not uncommon.
Inner assignment
Remove the assignment-in-condition from this:
while (isspace(cc=getchar())) ;

It does not make anything faster, and is a nasty bit of C syntax that makes code more difficult to read, maintain and debug.
Use a for
int i=1;
while (!isspace(cc=getchar())) {
    // ...
    i++;
}

can be
for (int i = 1; !isspace(cc); i++) {
   // ...
   cc = getchar();
}

noting that an initial getchar() would need to precede this loop.


C++ Solution for ProjectEuler Problem #5

Code review

To start with, some points about your code:

using namespace std; is something I consider a code smell. It doesn't save much time and I find it clearer to see exactly where cout etc. are coming from. Additionally, it clutters your namespace although I myself haven't run into name collisions with the STL being an issue before.
It looks like your condition to exit the while loop is tempDivMax == divMin. Use this rather than while (true) to make it clearer what behaviour is intended.
You are also performing two iterations inside a single loop: num is being incremented from 1 until it succeeds and tempDivMax is being decremented until it equals divMin. Split these into separate loops! The code will be clearer to read and will be just as fast. The outer loop I would turn completely into a for loop for (; tempDivMax != divMin; ++num) { ... } and but the inner one I would make a while loop while (tempDivMax > divMin && num % tempDivMax == 0) { ... } since the long condition expression makes for some rough reading when condensed into a for loop.
Finally, define your constants before your working variables and declare them as const. I would even do this outside of the main function.

This leaves you with:

#include <iostream>

const int DIV_MIN = 1;
const int DIV_MAX = 20;

int main() {
    long long num = 1;
    int tempDivMax = DIV_MAX;
    for (; tempDivMax > DIV_MIN; ++num) {
        tempDivMax = DIV_MAX;
        while (tempDivMax > DIV_MIN && num % tempDivMax == 0) {
            --tempDivMax;
        }
    }

    std::cout << num << std::endl;
    return 0;
}

A "more elegant" solution...

== Obligatory code below is untested ==

I'd imagine they're looking for something like this?

For something to be divisible by a number, it must have at least that number's prime factors. Furthermore, in any given number below 20, there can be a maximum of $$\lfloor{log_p(20)}\rfloor$$ copies of the prime factor $$p$$

The following snippet calculates the product of these.

#include <iostream>

const int DIV_MAX = 20;
const int[] PRIMES = {2, 3, 5, 7, 11, 13, 17};

int main() {
  int result = 1;
  for (int p : PRIMES) {
    int tmp = 1;
    while (tmp < DIV_MAX) tmp *= p;
    result *= tmp;
  }

  std::cout << result << std::endl;
  return 0;
}


Data representation

My critique starts here:

data Tree a = EmptyTree | Node a (Tree a) (Tree a)

Why is a node forced to have 2 sub-trees? Given a graph like this:

    B1 - C1
     |    |
A - B2 - C2
     |    |
    B3 - C3

you cannot represent B2 properly. I'd use

data Tree a = EmptyTree | Node a [Tree a]

for an arbitrary number of subtrees. Even the EmptyTree constructor might turn out to be unnecessary.

Try to rewrite your code with that, and see that the code duplication in the shortestPath2 definitions is reduced.

Use let and pattern matching

In an expression like

(c + fst (shortestPath2 right), pt : snd (shortestPath2 right))

you calculate shortestPath2 right twice and calls to fst and snd can often be avoided with pattern matching.

let (cs,pts) = shortestPath2 right in (c + cs, pt : pts)

Layout

path1 = (Node (50, 'A') (Node (30, 'C') (Node (90, 'D') (Node (0, 'E') EmptyTree EmptyTree) EmptyTree) EmptyTree)
                                       (Node (5, 'C') (Node (0, 'E') EmptyTree EmptyTree) EmptyTree))

is very hard to scan this by the eye. Only whitespace change, and it looks like this:

    where path1 = (Node (50, 'A')
                      (Node (30, 'C')
                          (Node (90, 'D')
                              (Node ( 0, 'E') EmptyTree EmptyTree)
                               EmptyTree)
                           EmptyTree)
                      (Node (5, 'C') -- should be 'D'
                              (Node (0, 'E') EmptyTree EmptyTree)
                               EmptyTree))

You actually have 'C' twice as successor to 'A'.
Change path1 to a top-level definition to access it in ghci. Then type let (Node _ a b) = path1 and then a and b into ghci. The latter should be 'D', just a typo.
The data representation is confusing me! The data is a graph, and graphs distinguish between edges and nodes. A,... are nodes, the numbers in between are edges. I would not group them like (50, 'A'). I hope someone else can give you a good pointer here.

BTW path1 is a misnomer. It is not a path. "BDCE" might be a path. path1 is a graph rolled out to a tree (without loops)?

Algorithmic

  I used a Node data structure (compliments of LYAH's previous chapter) to recurse through the shorter left or right sides.

You are technically right. It only scans then next section of the path and uses the shorter one. Your algorithm is greedy and does not find the global optimum. Change the 90 into 31, the shortest path should be "BDF", but your output of test3 does not change.

In General

At first I was confused, because I'd expect a function like

`shortestPath from to path1`

where from and to are origin and destination nodes. In your code, the destination is not coded at all. The problem states get from A or B to E or F, but single nodes are enough:

You can insert a virtual node

`london = Node ('V',0) path1 path2`

and you test function looks like

test4 = shortestPath2 london where
        --path1 = -- see above
        --path2 = -- see above
        london = Node (0,'V') path1 path2

Which looks better than test3.

Conclusion

I will address the biggest problem - that you algorithm does not find the optimum - in a later edit (or leave it for someone else to answer).


N-layered application structure in ASP.NET MVC 5

It's looking really good.  Some things I might consider that aren't necessary but could help move the code to some better abstractions and hence allow for easier unit testing of features include.

Abstracting your service away from UI related actions by removing the dependency on HttpContextBase.  It looks like all you are using it for is to obtain the IAuthenticationManager so I would pass that into your Login/Logout methods instead.

interface IAccountService
{
    bool Login(IAuthenticationManager authenticationManager, string userName, string password);
    bool Logout(IAuthenticationManager authenticationManager);
}

public bool Login(IAuthenticationManager authenticationManager, string userName, string password)
{
    var user = userManager.Find(userName, password);

    if (user != null) {

        authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        authenticationManager.SignIn(userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie));

        return true;
    }

    return false;
}

public void Logout(IAuthenticationManager authenticationManager)
{
    authenticationManager.SignOut();
    // NOTE:  Now you will have to do the session clear in your controller using this approach
        }

If you were using a DI framework you could consider following the DIP by injecting your service into your controller.  There are many DI frameworks out there (Autofac, Unity, Ninject just to name a few).  This would further abstract your controller away from the service implementation details.

// Account service supplied via Constructor injection
public AccountController(IAccountService accountService)
{
    service = accountService;
}

I noticed you have a base service.  I like this approach but I think I would consider again using Dependency injection (or DI) to provide this to your service so that you can provide another level of abstraction and possibly remove your services need for this.  Hence your base service might turn into something like.

// all services inherit this to expose the DbContext
public abstract class BaseService
{
    protected AppDbContext db { get; private set; }

    protected BaseService(AppDbContext dbContext)
    {
        db = dbContext;
    }
}

public AccountService(AppDbContext dbContext) : base(dbContext)
{
    userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(dbContext));

}

  NOTE:  If concerned that using Dependency injection means this
  wouldn't work, don't be.  Constructor injection is a walk in the park
  for these frameworks.

As your base service is likely to never make sense just by itself I would consider making it an abstract class to enforce implementation of the service through child classes.
In the past I have liked to abstract my dbContext away behind an interface to help with further abstracting my services and provide for a final piece of the abstraction puzzle.  So in your case a simple example of this would be:

interface IDbContext
{
   IDbSet<User> Users { get; set; }
}

class AppDbContext : IDbContext
{

}

By doing this you can now inject your context into your services as an interface.  Hurrah!


Well, you created a good code so far. Your lamda is OK. But there are some things about naming which could be improved

About the API setRolesByUserId, it is OK to accept userId as long. But about role, it could be better to change the Set to Set, and i think you're about to update for List of user, hence the name should change to updateUserWithRoleSet.
IMHO, It is totally OK to update one user at once => updateUserWithRole(long userId, Set<Role> roles>


Rearrange characters of a string into a palindrome, if possible

All that is technically required of a palindrome is that exactly one or zero of the character counts are odd and the rest are even. Then from this character count information you can reconstruct all of the palindromic words. Here is some python code to compute this method:

from collections import Counter
from itertools import permutations, repeat

def get_palindromes(word, ignore_case=True):
    if ignore_case:
        word = word.lower()
    char_counts = Counter(word)
    num_odd_counts = sum(int(c % 2 != 0) for c in char_counts.values())
    if num_odd_counts > 1:
        return []
    odd_char = '' if num_odd_counts == 0 else [
        c for char, count in char_counts.items() if count % 2 == 1][0]
    even_chars = [rep_char for char, count in char_counts.items()
                  for rep_char in repeat(char, count / 2) if count % 2 == 0]
    return [perm_word + odd_char + perm_word[::-1]
            for perm_word in set(
                    ''.join(char_perm)
                    for char_perm in permutations(even_chars))]

If there are no palindromes this function will return an empty list, but you can obviously return any value you like in this case.


Most performant way to check if elements are overlapping

I figured out a way thru trial and error. I'll post this here for anyone else who could use it.

// dismiss -- just creating less CSS
const randomColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
document.querySelectorAll('.label').forEach((x, i) => {
  document.querySelectorAll('.label')[i].style.background = "#" + ((1 << 24) * Math.random() | 0).toString(16);
});

//function to check for overlapping
function overlayCheck() {
  let points = document.querySelectorAll('.label');
  let rightPos = (elem) => elem.getBoundingClientRect().right;
  let leftPos = (elem) => elem.getBoundingClientRect().left;
  let topPos = (elem) => elem.getBoundingClientRect().top;
  let btmPos = (elem) => elem.getBoundingClientRect().bottom;

  for (let i = 0; i < points.length; i++) {
    for (let j = 0; j < points.length; j++) {
      let isOverlapping = !(
        rightPos(points[i]) < leftPos(points[j]) ||
        leftPos(points[i]) > rightPos(points[j]) ||
        btmPos(points[i]) < topPos(points[j]) ||
        topPos(points[i]) > btmPos(points[j])
      );

      if (isOverlapping && j !== i) {
        points[i].innerHTML = `${points[i].innerHTML} C`;
      }
    }
  }
}
overlayCheck();
.parent {
  position: relative;
  display: flex;
}

.label {
  height: 75px;
  left: 0;
  width: 100px;
  margin-left: 10px;
  background-color: orange
}

.cover {
  width: 220px;
  position: absolute;
  left: 0;
  height: 50px;
  bottom: 0;
}

Label 1

Label 2

Label 3

Label 4

Label 5

Label 6


Formatting

Format your code better. Put a space after the colon after properties. Don't put multiple properties in one line.

Use of SASS

Put your colors and lengths into variables so you can reuse them at other places, when they are supposed to be identical.

Why are the numbers not rounded? There is probably no visible difference between 1.073rem and 1.083rem and they probably could even be rounded to 1.1rem. If you are calcualting the values from something, then use SASS to do the calculations.

CSS itself

The buttons don't have a left margin.

The font-size either also belongs into the mixin, or removed entirely.

The mixin buttonShape shouldn't be repeated in the :hover/:active/ :focus rules.

If the rules .ui-button:enabled:hover, .ui-button:focus and .ui-button:enabled:active are supposed to be identical, then join them into one rule.

Unless you are explicitly declaring rules for disabled buttons the addition of the :enabled pseudo-class does not make sense.

Design

From a design and usability stand point it's not a  great idea to have :hover, :focus and :active all look the same.


The first thing I would note is that you should point out non obvious features of your implementation. The nice thing that is not immediately obvious is that when all external references are gone the object is automatically deleted from the make_one()::values set.

This is not really a requirement of a flyweight.
But a nice little trick here.

So if the automatic deletion is required then the answers to the question are:

  Can I avoid requiring enable_shared_from_this?

No. I don't think so.

You could re-invent some reference counting model but that seems a lot of work in comparison to simply using the standard libraries.

As an alternative, You can get around it slightly by using std::set<std::weak_ptr<T>> the trouble here is that even though the resource would be cleaned up the actual space for the resource would be maintained after the object is destroyed.

If on the other hand automatic deletion is not required.

  Can I avoid requiring enable_shared_from_this?

Yes. there are simpler ways that this could be written if there is no requirement to delete upon all external references going away. Now if you want it again it will still be there.

template<class T>
T const& make_one(const T& value) {

    static std::set<T> values;

    auto result = values.insert(value);
    return *(result.first);
}

  Can I make it thread safe without too much trouble?

Yes simply add a lock on the make_one()

  Any other ideas for improvement.

You could add the ability to move an object into your make_once() rather than copy it each time. Even better would be to allow the construction of T from its parameters.

// Move an object in your set
template<typename T>
std::shared_ptr<const T> make_one(T&& value)

// Emplace a value in your set
template<typename T, typename... Args>
std::shared_ptr<const T> make_one(Args&&... value)


Codility: An activity selection problem about scheduling two enemies to watch movies at a festival

Your code is probably around the best it can be performance wise. And so there's not much point splitting hairs finding anything better.

However you should be able to find something that uses less memory. Something about \$O(L + K)\$ rather than \$O(M^2)\$
I'd split finding indexes, and sums into two separate functions.
Your code, to me, looks slightly wrong.

range(l_start + L, len(movies) - K + 1)

Should probably be:

range(l_start + L, len(movies) - K)

Finally I'd split your code into two more functions, one that performs the sum, and then one that performs the max.

And so I'd change your code to:

def _solution_indexes(movies, K, L):
    for k in range(movies - K):
        for l in range(k + K, movies - L):
            yield k, l

    for l in range(movies - L):
        for k in range(l + L, movies - K):
            yield k, l

def solution_(movies, K, L):
    for k, l in _solution_indexes(len(movies), K, L):
        yield sum(movies[k:k + K]) + sum(movies[l:l + L])

def solution(movies, K, L):
    return max(solution_(movies, K, L), default=-1)


Pass class property as parameter to extension method

I'd suggest:

public static class AttributeExtensions
{
    public static string GetMyAttributeNameOfProperty<TClass>(string propertyName)
    {
        var propertyInfo = typeof(TClass).GetProperty(propertyName);
        return propertyInfo?.GetCustomAttribute<MyAttribute>()?.Name ?? default;
    }
}

Usage:

var awesome = AttributeExtensions.GetMyAttributeNameOfProperty<Matrix>(nameof(Matrix.AwesomeName));
Console.WriteLine(awesome);

Note:  The above isn't an extension method.  The below code is.

public static class AttributeExtensions
{
    public static string GetMyAttributeNameOfProperty<TType>(this TType me, string propertyName) where TType : Type
    {
        var propertyInfo = me.GetProperty(propertyName);
        return propertyInfo?.GetCustomAttribute<MyAttribute>()?.Name ?? default;
    }
}

Usage:

var awesome = typeof(Matrix).GetMyAttributeNameOfProperty(nameof(Matrix.AwesomeName));
Console.WriteLine(awesome);

Both output:

  awesome_name

Benefits:

Does not use an Expression or even the namespace
System.Linq.Expressions
Won't throw an exception (returns null if property or attribute doesn't exist)
Using nameof makes refactoring safe in the event you rename class properties
Does not use Func<TClass, object> or similar
Does not require an instance of Matrix (or any other type since it's generic)

Either way works and is really a matter of preference.  There are pros and cons to using extension methods.


Efficient use of regular expression and string manipulation

When using the re module, make sure to use strings marked with a leading 'r' as I do in the code below. This tells the interpreter to not try and interpolate any escaped strings.

By using findall to test for matches too we end up with more succinct code that still does exactly what we want in a clear fashion.

By putting the logic in a function you get the ability to write unit tests or do something other than print the result.

Using an exception for the failure cases makes the code clear and is more Pythonic in style.

Here is how I would have coded it.

import re
import sys

cpp = re.compile(r"(_[a-z]*)")
java= re.compile(r"([A-Z]+[a-z]*)")

class InvalidStyle(Exception):
    pass

def style_transform(input):
    if input[0].isupper():
        raise InvalidStyle(input)

    m = cpp.findall(input)
    if m:
        # import pdb; pdb.set_trace()
        if any(re.match(r"^[A-Z_]$", w) for w in m):
            raise InvalidStyle(input)

        pos = input.find(m[0])

        return input[:pos] + "".join(w.capitalize() for w in m)

    m = java.findall(input)
    if m:
        # import pdb; pdb.set_trace()
        pos = input.find(m[0])
        words = [input[:pos]] + [w.lower() for w in m]
        return "_".join(words)

    if input.lower() == input:
        return input
    else:
        raise InvalidStyle(input)

if __name__ == "__main__":
    if len(sys.argv) == 2:  # allows for debugging via pdb
        fp = open(sys.argv[1])
    else:
        fp = sys.stdin

    for line in fp.readlines():
        line = line.strip()
        if not line:
            continue

        try:
            print style_transform(line)
        except InvalidStyle as e:
            # print e, uncomment to see errors
            print "Error!"


Welcome to Stack Review, it seems me there is no much space for improvement, just some little tips:
class Ipv4Address {
    String ipAddress;
    boolean state;
    List<Ipv4Address> connections;

    //setters and getters
}

Probably you included your Ipv4Address class inside the NumberOfDevices class file but for a cleaner code better create a Ipv4Address class file separated. If you have defined setters and getters, you can encapsulate fields into the class using the private access modifier like below:
public class Ipv4Address {
    private String ipAddress;
    private boolean state;
    private List<Ipv4Address> connections;

    public Ipv4Address(String ipAddress) {
        this.ipAddress = ipAddress;
        this.state = false;
        this.connections = new ArrayList<>();
    }

    //getters and setters
}

No much to say about NumberOfDevices; in its numberOfDevices method you have the following code :
public static int[] numberOfDevices(String[][] connections, String [] toggleIps) {
    int count =0;
    int [] result = new int[toggleIps.length];
    if(connections.length>0) { // already a given contaraint that the length of toggle IPs is >=1

       Map<String,Ipv4Address> ip = new HashMap<>();
       for(int i=0; i<connections.length; i++) {
          Ipv4Address ip1, ip2;

          if(!ip.containsKey(connections[i][0])) {
            ip.put(connections[i][0], new Ipv4Address(connections[i][0]));
          }
          if(!ip.containsKey(connections[i][1])) {
            ip.put(connections[i][1], new Ipv4Address(connections[i][1]));
          }

          ip1=ip.get(connections[i][0]);
          ip2=ip.get(connections[i][1]);

          ip1.addConnection(ip2);
          ip2.addConnection(ip1);

     }

      //other lines
}

You can rewrite this part of your method using a foreach construct like below:
public static int[] numberOfDevices(String[][] connections, String[] toggleIps) {
    int[] result = new int[toggleIps.length];

    if (connections.length == 0) { return result; }

    Map<String, Ipv4Address> map = new HashMap<>();

    for (String[] connection : connections) {

        for (String c : connection) {

            if (!map.containsKey(c)) {
                map.put(c, new Ipv4Address(c));
            }
        }

        Ipv4Address ip1 = map.get(connection[0]);
        Ipv4Address ip2 = map.get(connection[1]);
        ip1.addConnection(ip2);
        ip2.addConnection(ip1);
   }

   //other lines
}


First three general remarks:

range does not need an explicit start argument, it defaults to 0. range is basically range(start=0, stop, step=1), only stop is needed
if takes an expression as argument which just has to evaluate truthy or falsey. There is no need for parenthesis, unless chaining multiple expressions over multiple lines or doing some complicated and/or logic.
you should consistently use 4 spaces per indentation level (your class only has 2 in the outer level).

Your setting up of the board can be simplified with a list comprehension:

self.board = [[random.random() for _ in range(w)] for _ in range(h)]

Here I used _ as an unused loop variable, as customary in Python.

I would also save h and w in the class for later use.

In Game.next_gen:

if (n == 1 or n == 0):
    c = 0
elif (n == 3):
    c = 1
elif (n == 2):
    pass
else:
    c = 0

is equivalent to:

if n == 3:
    c = 1
elif n != 2:
    c = 0

I would make two helper functions calculating neighbours that are alive:

def neighbours(self, x, y):
    p = -1, 0, 1
    for dx, dy in itertools.product(p, p)
        if dx == dy == 0:
            continue
        _x, _y = x + dx, y + dy
        if 0 <= _x < self.h and 0 <= _y < self.w:
            yield _x, _y

def alive_neighbours(self, x, y):
    return sum(self.board[n_x][n_y] > 0 for n_x, n_y in self.neighbours(x, y))

Here I used the boundaries to make sure that neighbours only serves points inside the grid (and used itertools.product to make it easier to construct dx and dy). Then getting the sum of all alive neighbours just sums over the values, since in self.board empty cells have a value of zero, while alive cells a value greater than zero.

This simplifies next_gen to:

def next_gen(self):
   board_next = [[0 for _ in range(self.w)] * self.h]
   for x in range(len(self.board)):
       for y in range(len(self.board[x])):
           n = self.alive_neighbours(x, y)
           cell = self.board[x][y]
           if n == 3:
              cell = 1
           elif n != 2:
              cell = 0
           board_next[x][y] = cell
   self.board = board_next[:]

Your show function can be simplified using str.join:

def show(self):
   for row in self.board:
       print("".join("X" if cell else "#" for cell in row))

The time.sleep(0.5) I would put in start to make it possible to show the generation without delay if necessary.

I would put the code calling your class into a if __name__ == "__main__": guard to allow importing your class from another module:

if __name__ == "__main__":
    os.system('clear')
    game = Game(3, 3, 3)
    game.board = [
      [0, 0, 0],
      [1, 1, 1],
      [0, 0, 0]]
    game.start()


Internal method to calculate the distance between all nodes in Kruskal's Importance (Driver) Algorithm

You can use comprehensions.

A comprehension is a special way to write a for loop, or nested for loops.
This is a functional part of the language and is derived from set-builder notation.
If we look at Wikipedia we'll see:

\$S = \{2 \dot{} x | x \in \mathbb{N}, x^2 > 3\}\$

In imperative Python this would be:

from itertools import count

S = []
for x in count(0):
    if x ** 2 > 3:
        S.append(2 * x)
...

Ignoring the inability for this function to complete, that's a bit long winded.
Instead we can use a list comprehension:

S = [
    2 * x
    for x in count(0)
    if x ** 2 > 3
]

This allows us to write what would be multiple indentations of code in one line.
And so take the code:

for i in range(l):
    for j in range(l):
        if i != j:
            # Do stuff

Using comprehensions we can change it to:

for i, j in [
        (i, j)
        for i in range(l)
        for j in range(l)
        if i != j]:
    # Do stuff

This allows a large reduction in the amount of tabs.
As we can just use two comprehensions.

for i, j in [
        (i, j)
        for i in range(l)
        for j in range(l)
        if i != j]:
    pij[i,j] = self.pcor_squared(np.array([ndarr[:,i], arr, ndarr[:,j]]))
    for m in [m for m in range(l) if m != i and m != j and m > j]:
        pijm[m,i,j] = self.pcor_squared(np.array([ndarr[:,i], arr, ndarr[:,j], ndarr[:,m]]))

I'd like to point out two ways to improve on this.
As we are currently using list comprehensions that build an entire list before using the first item we can change them to generator comprehensions.
This is as simple as changing the [] to ().
This would allow us to use the list \$\{2 \dot{} x | x \in \mathbb{N}, x^2 > 3\}\$, for example:

import itertools

S = (2 * x for x in itertools.count(0) if x ** 2 > 3)
print(list(itertools.islice(S, 10)))

The second way to improve the above is to move the two checks m != j and m > j into the range.
This would change the range to range(j + 1, l) and just leave the m != i.

And so you can get:

for i, j in (
        (i, j)
        for i in range(l)
        for j in range(l)
        if i != j):
    pij[i,j] = self.pcor_squared(np.array([ndarr[:,i], arr, ndarr[:,j]]))
    for m in (m for m in range(j + 1, l) if m != i):
        pijm[m,i,j] = self.pcor_squared(np.array([ndarr[:,i], arr, ndarr[:,j], ndarr[:,m]]))


Raising an assertation error if string is not an email

class EmailParser(object):

    def __init__(self, message):
        assert isinstance(message, basestring)

In python, we typically don't check types. Basically, we prefer duck typing. Let the user pass whatever they want.

        parsed_message = email.message_from_string(message)

        if self._is_email(parsed_message):
            self.email_obj = parsed_message
        else:
            assert False, 'The supplied string is no email: %s' % parsed_message

As Janne mentioned, this is not a good use of an assertion.

    def __str__(self, *args, **kwargs):
        return self.email_obj.__str__()

You shouldn't call __str__ methods directly. Use the str() function.

    def _is_email(self, possible_email_obj):
        is_email = False

        if isinstance(possible_email_obj, basestring):
            is_email = False

This is useless, because the only possible outcome is to set is_email to False which it already is. Furthermore, you know this has to be a Message object since it was returned from message_from_string so why are you checking whether it's a string? You know its not.

        # I struggled a lot with this part - however, I came to the conclusion
        # to ask for forgiveness than for permission, see Zen of Python and
        # http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610923#610923
       try:
           if '@' in possible_email_obj['To']:
               is_email = True

       except TypeError, e:
           is_email = False

In what circumstances can this possibly happen?

       return is_email

Don't needlessly set boolean flags. Just return True or False directly.

Better yet, raise an exception with details on what exactly is wrong rather than returning false and raising a generic exception later.


Implementation of a singleton HttpClient with generic methods

General remarks

The naming and the design are ok. The only thing that could be improved is the

 HttpClientBase

It's not a base class so you shouldn't call it like this. I suggest HttpClientService.

Timeout = TimeSpan.FromMilliseconds(15000);

Or simply TimeSpan.FromSeconds(15);

Singleton

There are of course mutliple patters for creating a singleton but the one you chose is probably the right one Singleton by Jon Skeet clarification

Concurrency

  I have doubts about its performance or if it would crash on simultaneous calls.

I don't see actually anything that could be further optimized. You call only core APIs that should already do their best.

The methods don't share any data with each other so there is no risk in calling them in parallel.


Performing redirects based on taxonomy terms associated with nodes

function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {

      switch ($op) {

        case 'view':

            if( (arg(1) == 0)){ } //do not execute on homepage. if there are no aruments after the base url in arument one is thedelimagazine.com/argument1, if this is 0 then do nothing.

You get an extra pair of parens, and it would be easier to to check for arg(1) ~= 0 rathern the have an empty if block.

          else {

            $region = getRegion(); //get current region from deli.mmodule

            $national = 'national'; //store string 'national' in variable

Don't write dumb comments. Assume the reader understands PHP. Your comment should explain why you want to do that, not reiterate the code.

            $count = count($node->taxonomy);//nstores number of key/value pairs in array,  if two terms are selected with the node/post then count == 2

            $terms = array();//initialize terms to array
            foreach($node->taxonomy as $term) {
              $terms[$term->name] = $term->name; //prints array of individual terms

            }

That was a lot of pointless empty lines.

        /*case 1 new england*/

        //if there are less than 9 terms  and more than 2 and new england is in the array redirect to new england
        if( $count < 9 &&  $count > 2 && in_array('newengland', $terms) && $region != 'newengland')

Again, your comment simply tells me what I could have already gotton from the code. But I'm left thinking: WHAT? What's the deal with the number of terms? What am I checking in the array? What has $region got to do with it?

        {
          $link = 'http://newengland.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');
              drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);

Keep your indentation consistent.
            }
            /END case 1 new england/

Don't put end comment like that. I can already see the case is ending thanks to the } and your indentation.

          /*case 2*/
              if($count == 2 && in_array('national', $terms) && is_numeric(arg(1))) { //if there are 2 terms in taxonomy && national is one of them & the first argument in url is a number such as thedelimagazine.com/12345 (before alias redirect)

Again, don't repeat your code in the comments. Explain why your code is doing that.

              unset($terms['national']);        //remove national from array
              $value = array_shift($terms) ;//set value to the other term left. in array
              if($value == 'los angeles') {//fix for los angelas, because in deli module taxonomy term and subdomain are different only for los angeles

See those are the comments that are helpful, because it explains what so special about los agenles.

                $value = 'la';
              }

              if($region != $value) { //if region does not already = term (would cause redirect loop)

Here I'd just say // avoid redirect loop

                  $link = 'http://' . $value . '.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');//go to term left in $value

                  drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);//drupal redirect function

This looks pretty much the same as the last case. You should refactor the code.
                  }
                }

            /* ++ END case 2++*/

            /* ++case 3 national+++*/
            else {

        if($count > 10  && in_array('national', $terms)  && $region != 'national' ) {    //if there are moer than 10 terms and national is in the array $terms, and the current region does not already =national
              $link = 'http://national.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');//then set $link to national.thedelimagazine.com.  drupl get path alias gets the path to the node and node id and converts it to clean readable urls that i implemented last year.
              drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);     //go to the $link
        }
             /* ++ END case 3 national++*/

             }
         }
          break;
      }
    }

It's been so long so I read the matching pieces of code that I have no idea what these pieces much up to. That a sign that your code is overly complicated.

Here is a quick reworking of the code:

<?php
    // return the region that the user should be on for this node
    function determine_region($node)
    {

        $taxonomy_count = count($node->taxonomy);

        // I doubt this is neccesary, I don't know what
        // $node->taxonomy is, but perhaps you can use that rather
        // then copying the data into an array.
        $terms = array();
        foreach($node->taxonomy as $term) {
            $terms[$term->name] = $term->name;
        }

        // I really have no idea what the logic behind the region is
        if($taxonomy_count == 2 && in_array('national', $terms) && is_numeric(arg(1)))
        {
            $region = array_shift($terms);
            // los ageneles needs special case
            if($region == "los angeles")
            {
                $region = 'la';
            }
            return $region;
        }
        else if($taxonomy_count > 2 && $taxonomy_count < 9 && in_array('newengland', $terms)
        {
            return 'newengland';
        }
        else if($taxonomy_count > 10 &&  in_array('national', $terms) )
        {
            return 'national';
        }
        else
        {
            // none of the cases fit, we'll just keep the current region
            return getRegion();
        }

    }

    // redirect the user to a particular region and node
    function send_redirect($region, $node)
    {
        $link = 'http://' . $region . '.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');//go to term left in $value
        drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);
    }

    function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
        // if viewing something other then the home page, consider redirecting
        if($op == 'view' && arg(1) != 0)
        {
            $correct_region = determine_region($node);
            // redirect to correct region if necessary.
            if( getRegion() != $correct_region )
            {
                send_redirect($correct_region, $node);
            }
        }
    }
?>

I think you'll find my version easier to follow. I've divided to task into pieces so that each piece can be simpler.

  This code performs 301 redirects based on the taxonomy terms
  associated with the node, as 301 redirects can adversely effect page
  load time, how could this be best optimized.

The solution is not to do 301 redirects. Telling the browser to go download another page will make loading the page slower. Nothing you can do in your code will change that. All you can do is not tell them to go download another page. Do you really need to redirect the user to a different subdomain? Maybe you do, but if you can get away without doing it, don't do it.


Complex if statements in authentication method

Two suggestions on how to keep this code maintainable:

use early exits
keep conditions atomic (one if checks for one thing)

Example:

function findLoggedInUser()
{
    if (($userData = $this->httpSession->getParameter('user')) && isset($userData['id'])) {
        // User found in current http session
        return $this->userMapper->findById($userData['id']);
    }

    $httpSessionData = $this->httpCookie->getParameter('usess');
    if(!$httpSessionData) {
        $this->httpCookie->destroy('usess');
        return null;
    }

    if(!isset($httpSessionData['uid'], $httpSessionData['sno'], $httpSessionData['token'])) {
        $this->httpCookie->destroy('usess');
        return null;
    }

    $user = $this->userMapper->findById($httpSessionData['uid']);
    if(!$user) {
        $this->httpCookie->destroy('usess');
        return null;
    }

    $httpSession = $this->httpSessionMapper->findByUserAndSeriesNo($user, $httpSessionData['sno']));
    if(!$httpSessionData) {
        $this->httpCookie->destroy('usess');
        return null;
    }

    if (!password_verify($httpSessionData['token'], (string) $httpSession->getTokenHash()) {
        $this->httpSessionMapper->deleteAllByUser($user);
        $this->httpCookie->destroy('usess');
        return null;
    }

    // EVERYTHING'S FINE, DO THE JOB

    // Generate new http session entity tokens
    $token['raw']  = new Token(CryptoCharGen::numeric(60));
    $token['hash'] = new TokenHash(password_hash((string) $token['raw'], PASSWORD_BCRYPT, ['cost' => 4]));

    // Update and persist http session entity with new token
    $httpSession->setTokenHash($token['hash']);

    $this->httpSessionMapper->update($httpSession);

    // Issue new http cookie usess with updated http session recovery data
    $this->httpCookie->setParameter('usess', [
        'uid'   => (string) $httpSession->getUser()->getId(),
    'sno'   => (string) $httpSession->getSeriesNo(),
    'token' => (string) $token['raw']
        ], 60 * 60 * 24 * 90);

    // User has been found
    return $httpSession->getUser();
}

This way, the code remains readable and flexible for future modifications.


Small script to re-create a file indefinitely

Unless you really want to reinvent the wheel, you could use FileUtils.touch for this:

  FileUtils.touch

  Updates modification time (mtime) and access time (atime) of file(s) in list. Files are created if they don’t exist.

For example:

require 'fileutils'

PATH = "C:/folder/to/file/test1.txt"
SLEEP_TIME = 30

loop do
  FileUtils.touch(PATH)
  sleep(SLEEP_TIME)
end


You should be using a CancellationToken, which can be generated like:

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;

Pass this token to the method you wish to potentially cancel and keep a reference outside the method.  Then, from the calling method you can check token.IsCancellationRequested at periodic intervals and return, or if you wish to throw, you can call token.ThrowIfCancellationRequested().  To signal a cancellation, you call source.Cancel(), which propagates through to the token and signals a cancellation request.  You can also set it up to automatically cancel after a certain amount of time when you create the CancellationTokenSource.


First let us nitpick a little bit.

MoveVehicle would be a nice name for a method but for a class it isn't choosen well. A class name should be made out of a noun or a noun phrase. So for instance VehicleMover or VehicleController would be a much better name for this class.

The method in question

public void FixedUpdate()
{
    foreach(KeyValuePair<KeyCode, Vector3> keyMapping in this.keyMappings)
    {
        if(Input.GetKey(keyMapping.Key) && this.IsGrounded())
        {
            Vector3 objectForce = keyMapping.Value * this.accelerationForce;
            this.rigidBody.drag = objectForce.sqrMagnitude / this.dragDividend;
            this.rigidBody.AddForce(objectForce);
        }
    }
}

here I would suggest to use var rather than KeyValuePair<KeyCode, Vector3> which would make your code a little bit cleaner and its obvious that it will be a KeyValuePair<TKey,TValue.

Otherwise your code looks nice and tidy. Good job.

I don't know Unity3D at all, so I don't know if it is possible to switch the public float accelerationForce; to a public property. If this is possible, I would suggest inside the setter to change all the values of the Dictionary so they represent the objectforce. This would involve a second kind of collection or some constants to hold the currently predifined values of the current Dictionary.

If it is likely that the accelerationForce is called less often than the FixedUpdate() method this will speed the whole thing up.


Thread-safe bounded buffer FIFO queue using C++11

If the allocation in the ctor throws, the dtor will have to contend with an uninitialized owning raw pointer. In other words, you have Undefined Behavior.

The minimal fix would be value-initializing m_queue before trying to allocate the memory. Moving the allocation into the ctor-init-list would not work, as constructing a std::condition_variable can throw.

The better fix would be using a std::unique_ptr<T[]>, and maybe allocating the memory with a back-port of C++14 std::make_unique, though assigning in the ctor-body would then also work.
delete [] pointer; and if(pointer) delete [] pointer differ in exactly one point:
The second is longer.

Not that you should have any raw owning pointers.
You know remainder (%) is a fairly expensive operation? And the dividend is in the range [0, divisor] inclusive.
You can suppress the notification of writers if the buffer wasn't full before the call to dequeue().
Likewise, you can suppress the notification of readers if the buffer wasn't empty before dequeue().
You should direct debug-output to std::cerr instead. Which would obviate the need for manually flushing with std::endl.

Of course, the debug-output should be removed from the release version.
Strictly speaking, one of m_front, m_rear is superfluous because you also have m_count.
It's a curious decision to make m_rear always point to the last object you enqueue()d, instead of past it, and thus adjusting it before you actually copy the object. It means that enqueue() depends on copy-assignment of T not throwing for correctness.
Your decision to use different names for the std::unique_lock in enqueue() and dequeue() threw me for a loop. For a moment I thought there was a reason for them, namely two different mutexes. Better change that...


Python implementation of Conway's Game of life with Pygame

In your generate function, numpy.random.randint can do everything you need. I'd suggest renaming the function to generate_grid and just returning the generated grid.
In your display and check functions, the grid parameter knows its own size - you don't need to pass that in.
In display, your alive and dead colors could be in a tuple. Then you could index the tuple by [0] or [1] (the value of the cell) to determine the color:

rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)

rects.append(pygame.draw.rect(window, Colors[grid[x][y]], rect)

Pretty much everything with a dot (.) or an expression should be cached inside display.

pgrect = pygame.Rect
rappend = rects.append
drawrect = pygame.draw.rect

Your x/y loop can be replaced using np.apply_over_axes
The scipy.signal.convolve2d function will do most of the heavy lifting for you in terms of neighbor counting &c


Browser freeze - How to handle or optimize 50,000 rows in one HTML select element more than several times?

50k is simply too many for a drop-down list. Use AJAX-based autocomplete input boxes or split the list to smaller parts, for example by state. I think the users also don't like it, it's really hard to scroll or search in a so huge drop-down list.


From a short review;

You are definitely looping indeed over every entry 4 times
This belongs in a well named function
Other than that, it is very straight forward and understandable

I was thinking that people don't live all that long, you could easily build a lookup table for every possible age. This could speed this up quite a bit.
So something like this;

const dataset = [
  {name: 'Paul', age: 10},
  {name: 'Marcus', age: 5},
  {name: 'Jennifer', age: 1},
  {name: 'Linda', age: 53},
  {name: 'Mary', age: 4},
  {name: 'Rose', age: 40},
  {name: 'Peter', age: 2},
]

const buckets = [[0, 10], [10, 20], [20, 30], [30, 60]]

function createAgeBuckets(dataset, buckets){
  const start = 0, end = 1;
  const out = {}, ages = [];

  //Create age range
  for(const bucket of buckets){
    bucketRange = `${bucket[start]}-${bucket[end]}`;
    out[bucketRange] = {res: [], count: 0};
    for(let age = bucket[start]; age < bucket[end];age++){
      ages[age] = out[bucketRange];
    }
  }

  //Create bucketses
  dataset.forEach(person => {
    ages[person.age].res.push(person);
    ages[person.age].count++;
  });

  return out;
}

console.log(createAgeBuckets(dataset, buckets));


First of all, there are at least three buggy things:

select variable is declared inside the do... while loop, so the condition in while is checked against another one (probably, a field in the class?). So, the loop won't work as expected!
copy-paste is evil. The calls fileHolder.create("image"); are repeated in two different conditionals. The "txt" option is not used. Please pay more attention to the things you write and do not copy-paste such elementary things.
the Scanner is not closed after its usage, which is desirable, as for any other items that use I/O.

For the rest, the code seems quite straightforward, rigid and repetitive, hence difficult to maintain. It contains many if - else if clauses that smell bad.

Of course, the whole story may be refactored with patterns usage. But I don't think that the state pattern suits well here. It'd be better refactored with the command pattern.

All the menu actions (create, remove, rename and their dependent ones) may be wrapped into separate objects, which associate the expected keys (1,2,3..), the text and other necessary stuff and sugar.

For example, a (very short) version of Menu class could be like this:

class Menu {

  private final String action;
  private final Consumer<String> consumer;

  Menu(String action, Consumer<String> consumer) {
    this.action = action;
    this.consumer = consumer;
  }

  void execute() {
    this.consumer.accept(action);
  }
}

And it would be initialized and used:

Menu create = new Menu("create", (a) -> fileHolder.create(a));
// to trigger the execution:
create.execute();

But for this very concrete and short example of code I would consider decomposing it into patterns as a sort of overkill.

There is some job to do about the original straightforward approach, so let's just try to improve it.

The input numbers are read several times using the Scanner object. They should also be validated, so a dedicated method would be very useful:

// int minValue may also be defined if necessary
private static int askUserForNumberInput(Scanner scanner, String prompt, int maxValue) {
  System.out.println("please select menu item");
  System.out.println(prompt);
  int value = scanner.nextInt();
  while (value < 1 || value > maxValue) {
    System.out.println("invalid menu item, please try again");
    // java.util.InputMismatchException should also be caught
    // to intercept non-numeric input
    value = scanner.nextInt();
  }
  return value;
}

The frame for the main logic would look like this:

try (Scanner scanner = new Scanner(System.in)) {
  final int mainMenuSelection = askUserForNumberInput(scanner, "1-create, 2-remove, 3 - rename", 3);
  switch (mainMenuSelection) {
    // cases
  }
}

And there is not a single if - if else in the cases any more:

case 1: {
  String[] createActions = { "image", "txt" }; // to be extracted to constants
  int createOption = askUserForNumberInput(scanner, "1-image, 2-txt", 2);
  fileHolder.create(createActions[createOption - 1]);
  break;
}
case 2: {
  int removeIndex = askUserForNumberInput(scanner, "1-file from pc1, 2-file from pc2, 3-file from pc3", 3);
  fileHolder.removeFile("pc" + removeIndex);
  break;
}
case 3: {
  System.out.println("please type new name");
  String newName = scanner.next();
  fileHolder.rename(newName);
  break;
}


2-factor authentication code generator in Python 3

Code quality

Each import should have its own, seperate line:

import hmac
import base64
import struct
import hashlib
import time
import pyqrcode
import random
import sys
import os

Top-level functions should be seperated using two blank lines:

def foo():
    foobar()

def bar():
    foobar()

A lot of your comments should actually be docstrings.

Security

Don't use the random module for security purposes. Skimming through the documentation, red banners warn you not to use it for security purposes and instead to use the secrets module. Note that secrets is only part of the standard library in Python 3.6 and upwards. If you need to run this on other versions of Python, which is quite likely, make use of random.SystemRandom (or os.urandom() directly).
Use getpass.getpass() instead of plain input() for gathering secrets like passwords or private codes. [getpass documentation]

General recommendations

Since pyqrcode isn't part of the standard library, you may want to wrap import pyqrcode in a try:/except: statement:

try:
    import pyqrcode
except ModuleNotFoundError:
    print("Couldn't import pyqrcode.")
    sys.exit(1)

If you plan to release this as a module, it's a very good idea to add documentation (docstrings, as well as a README for quick reference), so others understand how the code works and how they should use it.


Project Euler 22: Assigns scores for names that are imported from text file

Reading the file: you declare the BufferedReader as an instance variable while it is only used locally. Don't do that: variables should always have the smallest scope possible. In addition, resources should normally be closed in the same scope that opens them (which brings me to the point that you never close the buffered reader.)

Furthermore, you put the opening and reading in two different try-catch constructs. That makes no sense. If the first fails, you cannot expect the second to work.

Thus, using "classic" code, you should put it together as a try-with-resources block, which automatically closes the opened resource, something like this:

try (BufferedReader reader = new BufferedReader(new FileReader(location))) {
    String name;
    while((name = reader.readLine()) != null) { // classic construct ;-)
        names.add(name);
    }
}
catch(IOException e) {
    // Do something useful. Especially, do NOT continue program
    // execution, as you don't have any data anyway!
}

But as this is 2017 and the library is quite mature, you should really simply use java.nio.Files:

Files.readAllLines(Paths.get(location))

is all you need.

There are quite a few more problems in your code (especially the mixup of static and instance variables), but alas my time is limited right now.


Callback functions to select the tab to the left in Google Chrome

Some of the Chrome APIs are implemented using callbacks. This means that these methods are potentially async. Code doesn't run in the order they're written, you have been warned.

The closest you'll get to sequentially written async code is by using Promises. In simple terms, these are objects that hold some state, and when a certain state is attained (resolve or reject), the attached handlers get executed.

The beauty lies in then which when returned a promise, attaches the next chained then to that promise instead. This makes the next then appear to wait for the previous async operation. However, when returned a non-promise value, it uses that value as the resolved value for the next chained then. The ability make the code appear to wait, the ability to alter the resolved values as well as carry values through makes Promises powerful.

I think Chrome should have support for Promises already. Here's an example where a we wrap the chrome.tabs.query in a promise, and when it succeeds, it resolves the promise.

function promiseQuery(options){
  return new Promise(function(resolve,reject){
    chrome.tabs.query(options, resolve);
  });
}

function promiseUpdate(tabId,options){
  return new Promise(function(resolve,reject){
    chrome.tabs.update(tabId,options,resolve);
  });
}

function tabLeft(){

  promiseQuery({'active':true, 'currentWindow': true})
  .then(function(tabs){
    // This function executes when the promiseQuery resolves

    // Get the current index
    var activeIndex = tabs[0].index;

    // We fire another query. But instead of returning a promise, we can chain a then
    // to alter the resolved value.
    return promiseQuery({'currentWindow': true})
      .then(function(tabs){
        return{
          length : tabs.length,
          activeIndex : activeIndex
        }
      });
  })
  .then(function(data){
    // This executes with data being the altered resolved value

    var targetIndex = ((data.activeIndex === 0) ? data.length : data.activeIndex) - 1;
    return promiseQuery({'index': targetIndex});
  })
  .then(function(tabs){
    // same here
    var tabId = tab[0].id;

    // As long as you return a promise
    return promiseUpdate(tabId, {'active': true});
  })
  .then(function(){
    // Done
  });
}

For now, it still looks like a jumble. However, you can now pull out functions and just hand references to then. There's no more problem with persisting values in an outer scope since you can just pass them through the then chain.

function promiseQuery(options){
  return new Promise(function(resolve,reject){
    chrome.tabs.query(options, resolve);
  });
}

function promiseUpdate(tabId,options){
  return new Promise(function(resolve,reject){
    chrome.tabs.update(tabId,options,resolve);
  });
}

function initialCall(){
  return promiseQuery({'active':true, 'currentWindow': true})
}

function activeAndLengthQueries(){
  var activeIndex = tabs[0].index;
  return promiseQuery({'currentWindow': true})
    .then(function(tabs){
      return{
        length : tabs.length,
        activeIndex : activeIndex
      }
    });
}

function targetTabQuery(){
  var targetIndex = ((data.activeIndex === 0) ? data.length : data.activeIndex) - 1;
  return promiseQuery({'index': targetIndex});
}

function tabUpdateFunction(){
  var tabId = tab[0].id;
  return promiseUpdate(tabId, {'active': true});
}

function doneFunction(){

}

function tabLeft(){
  initialCall()
  .then(activeAndLengthQueries)
  .then(targetTabQuery)
  .then(tabUpdateFunction)
  .then(doneFunction);
}

Breaking down an operation into promises has no fixed rule. However, I write down the code in the sequence I want (just a flat list of things to do). Then run though them again. This time, if you see an async operation, that ends a then (notice how the previous example ends with return somePromiseGeneratingFunction). Do that operation and return it's promise. The sequence will continue in the next then.


Code A Primitive Calculator ( x3,x2,+1) Using Dynamic programming

Edit
I realized that my distinction between bottom-top and top-bottom might have caused some confusion. Going top to bottom and bottom to top is the exact same thing, just switched the starting and end points. I just made a habit of thinking about it differently. It's an unnecessary distinction (sorry for any confusion). But the general algorithm is the same.
More detailed explanation:
Just as explained below, you can start at 96234. You check the ways to get to 96233. There is only one way (subtract 1) so it is automatically the least moves. The numbers of moves it takes is 1 + number of moves takes to get to 96234, which is 0. So you store 1 into 96233. You do the same thing for 96232, 96231...
...You get to 32078, you check the paths to get there, /3 from 96234, /2 from 64156, -1 from 32079. The paths each have moves 1, 32079, and 64156 respectively. You store the smallest into the current slot.
Eventually, you get to 1, and you compare the values stored at slots 2,2,and 3. You return the lowest one + 1.
Previous Answer
Shouldn't you be going from bottom to top? Your code is doing exactly what you're telling it to do. You check if n%2==0 first, before you ever do n=n-1. That works most of the time, but as you can see, sometimes n-1 is less moves.
You won't be able to know which is the best operation if you go from top to bottom.
Instead, you should start at 1, and calculate the least amount moves it takes to get to 2,3,4... all the way to 96234. This is still of O(n), and memory wise, it is O(n) although I think you can get it down with a trick (not sure).


Since in both instances HTML is the same, it could be extracted to another function;
target.value appended to the URL needs to go through EncodeURIComponent() to avoid bugs, surprises and even XSS;
topTenShows has actually only 9 shows. Second argument of .slice() is exclusive;
It would be better to listen to input event instead of keydown. Right now, when you type, the last character doesn't make it into request.

Rewrite

const app              = document.querySelector('#app'),
      inputSearchField = document.querySelector('.inputSearchField'),
      apiEndpoint      = 'https://api.tvmaze.com',
      noImagePath      = 'design/icons/No_image_available.svg';

/**
 * For each object representing one show, creates HTML source and sets them all as content of #app
 * @param  {object} shows Array containing objects representing API results
 * @return {string}       HTML that got set as content of #app (unused)
 */
const buildShowsHTML = shows => {
  app.innerHTML = shows.map(obj => {
    const show = obj.show || obj;
    const img = show.image ? `<img src="${show.image.medium}"/>` : `<img class="fallbackImage" src="${noImagePath}"/>`;

    return `

          ${img}

${show.name}

`;
  }).join('');
};

/**
 * Gets top 10 shows from the input array of objects
 * @param  {object} arr Array containing objects representing API results
 * @return {object}     Array of top 10 shows
 */
const getTopTenShows = arr => arr
  .filter(show => show.rating.average)
  .sort((a, b) => a.rating.average > b.rating.average ? -1 : 1)
  .slice(0, 10); // tar element [0 – 10) i arrayen

// Show top 10 shows upon load
fetch(`${apiEndpoint}/shows`).then(resp => resp.json()).then(getTopTenShows).then(buildShowsHTML);

// Show the search results on user input
inputSearchField.addEventListener('input', event => {
  const input = encodeURIComponent(event.target.value);
  fetch(`${apiEndpoint}/search/shows?q=${input}`).then(resp => resp.json()).then(buildShowsHTML);
});
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width"/>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
  <title>Demo</title>

  <input class="inputSearchField"/>


Sublime Text plugin to modify text before it's pasted

If your intention is to escape certain characters by prefixing them with backslashes, you would be better off with a function that performs that specific task, rather than a generalized function that accepts a dictionary of replacements.

In general, performing multiple substitution passes over a string is a bad idea.  Certain substitution dictionaries could result in non-deterministic behaviour, depending on the order in which the substitutions are performed.  In fact, you have just that problem:

If the _ escape is performed before the \ escape, then _ would become \_, then \\_.
If the \ escape is performed before the _ escape, then _ would remain _, then become \_.

You could overcome that problem by specifying the substitutions using a collections.OrderedDict, but I still recommend against it on principle.  Escaping / unescaping is always better done using a single left-to-right pass.


How to optimize the code to save data at GAE datastore?

def add_country(country, country_name):
  if country and country_namef and country_name != '':

I assume that country_namef is a typo. If so, there is no point in checking country_name != '' because empty strings are already considered False

    return Country.get_or_insert('i'+str(country), country_name=country_name)
  else:
    return None

def add_city(city, city_name, country):
  if country and city and city_name and city_name != '':

As before, empty strings are false, so you are checking that twice

    return City.get_or_insert('i'+str(city), city_name=city_name, parent=country)
  else:
    return None


Your code at the current state looks very slow. Partition sort (or quicksort as it is generally known) is supposed to be faster than Bubble Sort. With my quicksort and bubble sort code, here is what I get for a 1000-element array:

Time taken (ns): 612535
Sorted List: ...
Time taken (ns): 5819902
Sorted List: ...

This is because quicksort is \$O(n \log n)\$ while bubble sort is \$O(n^2)\$.

How I would do quicksort:

Select a pivot
Create two pointers, one at the front and one at the back
Move first pointer up until there is a value greater or equal to the pivot
Move second pointer down until there is a value less than or equal to the pivot
Swap and advance both pointers
If the pointers have not passed each other, go to step 1. Otherwise, continue
Repeat recursively for each subarray

Code:

private static final Random RANDOM = new Random();

public static void quickSort(int[] array) {
    quickSort(array, 0, array.length);
}

private static void quickSort(int[] array, int begin, int end) {
    if (end - begin < 2) {
        return;
    }
    if (end - begin == 2) {
        // Optimization: array length 2
        if (array[begin] > array[end - 1]) {
            swap(array, begin, end - 1);
        }
        return;
    }
    int splitIndex = partition(array, begin, end);
    quickSort(array, begin, splitIndex);
    quickSort(array, splitIndex, end);
}

private static int partition(int[] array, int begin, int end) {
    int pivot = array[RANDOM.nextInt(end - begin) + begin];
    begin--;
    while (begin < end) {
        do {
            begin++;
        } while (array[begin] < pivot);
        do {
            end--;
        } while (array[end] > pivot);
        if (begin < end) {
            // Make sure they haven't crossed yet
            swap(array, begin, end);
        }
    }
    return begin; // TODO check
}

private static void swap(int[] array, int begin, int end) {
    int temp = array[begin];
    array[begin] = array[end];
    array[end] = temp;
}

The results:

Time taken (ns): 507845
Sorted Array: ...


You can of course use the Arrays.stream() (twice, because it's a 2D array)

Something along these lines:

private Stream<Pixel> stream() {
  return Arrays.stream(pixels).flatMap(Arrays::stream);
}


The code can be simplified a bit.

In the sequence:

if not node:
    return
if node and not node.left and not node.right:
    return prefix*10+node.value

...the if node part of the second condition is redundant. Since this is preceded by if not node: return, the second condition will never be reached unless if node evaluates to true.

For the if not node.left and not node.right, I'd apply DeMorgan's theorem, to get if node.left or node.right, and switch the controlled statement with the other.

By having it return 0 for an empty tree as @Zondo suggested, we can simplify a bit more: rather than checking whether node is there before summing it, we can just sum it, and if nothing is there, it returns 0, which doesn't change the sum.

With those and @Zondo's suggestions, we end up with something like this for the sum routine:

def sum(node, prefix = 0):

    if not node:
        return 0

    p = prefix * 10 + node.value

    if node.left or node.right:
        return sum(node.left, p) + sum(node.right, p)

    return p

Another possibility that might be worth considering would be to get a little closer to the single-entry, single-exit "ideal" that used to be advocated in structured-programming:

def sum(node, prefix = 0):

    if not node:
        return 0

    p = prefix * 10 + node.value

    if node.left or node.right:
        p = p + sum(node.left, p) + sum(node.right, p)

    return p

It would be pretty easy to transform this into a true single-entry, single-exit form, but I don't see it as a real improvement (and even what I've done above might be open to some question).