turning the digits of a number into an array

You can use the standard C function sprintf(buffer,"%d",x) to get an array of digits. In this case, the buffer will contain big-endian representation of x, so the conversion to a digit from each char will be something like this

for(int i = 0; buffer[i] != '\0' && i < sizeof(buffer);++i)
  digits[i] = buffer[i] - '0';

This work if x is positive.

But if you want to make your own implementation of splitting a number into digits, you should analyze the problem:

What is the base - is it always 10?
How many digits could be - is it always int, i.e. mostly 32-bit?

The answer for first question is to have the base parameter int base = 10 or 2 or 3 or 8 or any you want.

The answer for second question is ceil( log(|x| + 1) / log(base) ) + 1. The +1 for the minus sign. Or if you didn't want to care about maximum of digits use char digits[128] - more than enough even for 64-bit integer.

So, how to fill digits?

// int x - somewhere
unsigned base = 10;

char digits[128];
char isNegative = 0;
int digit = 0;

unsigned tmp = x; // this fix INT_MIN problem thanks chux - Reinstate Monica for note
if(x < 0) {
  isNegative = 1;
  tmp = -x;
}
if(x == 0) {
  digits[0] = 0;
  digit = 1;
} else {
  for(digit = 0; tmp > 0; ++digit) {
    digits[digit] = tmp % base;
    tmp /= base;
  }
}

At least you got little-endian representation of x on base as digits[i], where 0 <= i < digit and isNegative for the minus sign


Transfer the cell formatting in a legend to a dataset in another sheet

Your naming isn't great, you should use variable names to describe what they do

Dim i As Integer
Dim j As Integer
Dim mapToFill As Range
Dim legend As Range
Dim targetDestination As Range
Dim targetSource As Range

What is LegTra3 - I can't tell what that's supposed to mean at all.

Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names.

Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.

Instead of hard-coding cells, if they are static, assign them a named range property. e.g. instead of Sheets("mySheet").Range("A1:A10") you can have mysheet.Range("MyNamedRange").


One consumer and two producers using threads

Logging after an infinite loop

The only way that this:

while True:
    time.sleep(1)
    message = random.randint(1, 101)
    logging.info("Producer_1 got message: %s", message)
    queue_1.put(message)
    event_1.set()

is going to terminate is on an exception. That in itself isn't a bad thing - stop iteration exceptions are a common pattern in Python. However, it means that this line:

logging.info("Producer_1 Exiting")

can by definition never execute. You might want to try:

try:
    while True:
        time.sleep(1)
        message = random.randint(1, 101)
        logging.info("Producer_1 got message: %s", message)
        queue_1.put(message)
        event_1.set()
finally:
    logging.info("Producer_1 Exiting")

main method

Putting code in this block:

if __name__ == "__main__":

doesn't remove it from global scope. For that, you need to add a main function.


You can use sets to whittle down the possible GCFs.

for i, argument in enumerate(sys.argv[1:]):
    factors = set(n for n in range(2, int(argument) + 1) if int(argument) & n is 0)
    print argument, factors
    if i is 0:
        possible_gcfs = factors
    else:
        possible_gcfs &= factors
print "gcf is:", max(possible_gcfs | {1})

Better, use reduce:

def get_factors(x):
    factors = set(n for n in range(2, int(x) + 1) if int(x) % n is 0)
    print x, ':', factors
    return factors

possible_gcfs = reduce(set.intersection, map(get_factors, sys.argv[1:]))
print "gcf is:", max(possible_gcfs | {1})

Or if you don't need it to print out the factors of each number you can make it a bit more efficient by noting that the GCF must be no larger than the lowest of the arguments entered.

arguments = map(int, sys.argv[1:])
possible_gcfs = range(2, min(arguments) + 1)
for argument in arguments:
    possible_gcfs = [n for n in possible_gcfs if argument % n is 0]
print "gcf is: ", max(possible_gcfs + [1])

... but this can again be simplified using reduce and noting that the gcf is associative

def gcf(a, b):
    a, b = int(a), int(b)
    return max(n for n in range(1, min(a, b) + 1) if a % n is 0 and b % n is 0)

print "gcf is:", reduce(gcf, sys.argv[1:])

(And as a comment pointed out there are plenty of other solutions posted to earlier questions and you could use fractions.gcd.)


This is very nice for a beginner!

Instead of matching against files in the filesystem as a glob like this:

if [[ ! $BACKUP_DEV_NODE =~ /dev/* ]]; then

It would be better to use the -e flag to check if the path exists or not:

if [[ ! -e $BACKUP_DEV_NODE ]]; then

It's better to avoid any of the flags of echo,
because they don't work consistently in all systems.

In these examples you don't need any flags:

echo -e "Input 1 to backup, 2 to restore, anything else to quit"
echo -e ""

You could simplify these as:

echo "Input 1 to backup, 2 to restore, anything else to quit"
echo

If you find yourself needing any of echo's flags,
look into printf instead.

In here:

select hn in $MOUNT_POINT/*_backup;
do
    echo "Picked hostname folder: $HOSTNAME_VAR"
    echo "Select appropriate username folder"
    select un in $HOSTNAME_VAR/home/*;
        do
            echo "Picked username folder: $USERNAME_VAR"
            FULL_PATH=$USERNAME_VAR
            break
        done
    break
done

You're not using hn.
Another thing, the do...done of the inner select is over-indented, which is not  consistent with the rest of the code.

The default exit code is that of the last operation.
So unless you want to forcefully exit with 0 after a failed operation,
you shouldn't need exit 0, you can write simply exit.

Instead of this:

echo $(date) >> $FULL_PATH/homefolder_backup.log

You could simply redirect the output of date itself:

date >> $FULL_PATH/homefolder_backup.log

The double-quotes here are unnecessary:

echo "Syncing"
echo "Done"


Determine the height of a Tetris game's board after a sequence of moves

The first thing I did was use Black to reformat the code - yours is pretty good, but there are some minor style complaints I had (generally around the lack of whitespace in a few places). Additionally, PEP8 defines the naming conventions in python - generally, prefer_this notThis.
Lastly, all of your methods should have docstrings. I haven't added this b/c it isn't as pertinent to the code review, but it is good practice in general.
From there, I thought about your actual approach. At a high level you:

Create a new instance of the object
Pass it a string, parse the string, and process each token
Attempt to fit pieces
Clear full rows

None of that is inherently bad, but I think it can be tightened up a bit.
User Input
Right now you don't have any validation of the user inputs - we're being very trusting that the values that are provided will be usable. We probably want to do this validation
Additionally, I don't think that the Tetris class should be responsible for handling the comma-delimited string - it should just take a piece and a position, and something else should be responsible for taking the input and translating it into arguments. If you're feeling friendly, a @classmethod might be appropriate. Lastly, I think this class method should return the board, not the height, so I added a new height property to the class. I ended up with something like this:
pieces = {
    "I": ((True, True, True, True)),
    "Q": ((True, True), (True, True)),
    "T": ((True, True, True), (False, True, False)),
    "Z": ((True, True, False), (False, True, True)),
    "S": ((False, True, True), (True, True, False)),
    "L": ((True, False), (True, False), (True, True)),
    "J": ((False, True), (False, True), (True, True)),
}

@classmethod
def add_pieces(cls, user_input):
    board = Tetris()
    for piece in user_input.split(","):
        if len(piece) > 2:
            raise ValueError(f"Piece {piece} is malformed")
        piece_id = piece[0]
        drop_position = piece[1]
        if not Tetris.is_valid_piece(piece_id):
            raise ValueError(f"Piece {piece_id} is not a valid Tetris piece")
        if not Tetris.is_valid_drop_location(drop_position):
            raise IndexError(
                f"Drop location {drop_position} is not a valid board location"
            )
        board.add_piece(piece_id, drop_position)
    return board

@classmethod
def is_valid_piece(cls, piece_id):
    return piece_id in cls.pieces

@classmethod
def is_valid_drop_location(drop_position):
    try:
        int(drop_position)
    except ValueError:
        return False

    return drop_position >= 0 and drop_position < 10

@property
def height(self):
    return self.board.length

You'll also notice that I moved Tetris.pieces into a class attribute instead of an instance attribute - this is because it should be the same everywhere. I also changed 0/1 to True/False because it is a binary value (I think an enum is probably best to be explicit, e.g. boardState.FULL and boardState.EMPTY). Lastly, I changed from nested lists to nested tuples - this is because tuples are immutable, and you never need to change the shape definition.
OOP
I wonder if it is worthwhile making a separate class to represent the pieces, and then you can do something like TetrisPiece.fitsAtLocation(board, location). I haven't fully thought about what this would look like or if it is actually better, but it might be a nice way to encapsulate that functionality.
This would also be a convenient way to extend this to handle rotations as well, as you would just do TetrisPiece.rotate(Direction.LEFT) and handle it all under the hood.
If you want to extend this to a full game, then instead of just having a "drop position" you also need a relative location on the board, handling T-spins, etc. The more complicated this gets, the more I think a separate class is going to improve readability.
General nitpicks

doesThePieceFit seems really weird - I get how it works, but you should definitely introduce some constants to replace the magic method, and maybe consider if there is a better way to model the data.

In particular, perhaps we should store the block state for a different shape in reverse order (e.g. bottom-to-top instead of top-to-bottom)?

removeFullRows creates a list, then sorts it - I think you can probably come up with a different approach for this
addPieceAt has the same magic as doesThePieceFit - is there a way that we can either combine their functionality, or use a common helper method?
addPiece I think you can use for-else to handle this a bit more elegantly than using the ternary, but my mood on the for-else swings every time I use it


ES6 classes and ReactJS: implementing propTypes

I think you're just supposed to do this:

CallerDetailsPanel.propTypes = { callerData: React.PropTypes.object }

This feels a little backwards, but the React team has done this with the hope that in the future, with ES7, you will be able to use a syntax that looks something like this:

class CallerDetailsPanel {
  static propTypes = { callerData: React.PropTypes.object }
  render() {
    return (
      <div className='caller-details-panel'>
        <CallerCard person={this.props.callerData.owner} />
        <CallerCard person={this.props.callerData.user} />
      </div>
    )
  }
}


Firstly, I assume you have something like #define __in up the top. This is sort of a Microsoft-ism, and really isn't needed in most of these parameter sets. When you're passing types that are neither pointers nor references, it's pretty obvious that they're input values. To me, it's simply extra clutter which makes the code harder to read and provides no benefit.

Secondly, this seems like an extremely memory heavy way of doing what is basically a map. You allocate space for m_SizeX * m_SizeY elements, but if the table is sparse, a majority of that space is going to go unused.

Thirdly, you should be passing and returning certain values by (const) &. For example, in your set method should probably be:

void set(unsigned int x, unsigned int y, const T& val)

And your get method should be:

T& get(unsigned int x, unsigned int y)

This should also have a const overload:

const T& get(unsigned int x, unsigned int y) const

Note that if you haven't initialized a value, it will happily return you whatever junk happened to be there when new allocated the memory. This is probably not what you want - you should likely have it return either a default value or error.

If I were to write this, I'd utilize a std::map and something like the following:

#include <map>
#include <utility>

template <typename T>
class Table2D
{
private:
    std::map<std::pair<unsigned, unsigned>, T> table;

public:
    T& operator()(unsigned x, unsigned y)
    {
        std::pair<unsigned, unsigned> p = std::make_pair(x, y);
        return table[p];
    }

    const T& operator()(unsigned x, unsigned y) const
    {
        std::pair<unsigned, unsigned> p = std::make_pair(x, y);
        return table[p];
    }
};

This code assumes you want a default T() value (which will be 0 for all numeric types) to be inserted if it doesn't exist. Utilizing operator() returning a T& allows us to set and get values utilizing the same method:

Table2D<unsigned int> ui_2DTable;
ui_2DTable(10, 20) = 50;
std::cout << ui_2DTable(10, 20) << "\n";

Further, if we do something like:

std::cout << f_2DTable.get(10, 10) << "\n";

We'll simply return a default value. Currently, this will return something from a random bit of memory, and causes undefined behaviour, which is bad.

Finally, your code can cause undefined behaviour if the user tries to utilize the copy constructor or copy assignment operator. That is:

Table2D<unsigned int> ui_2DTable( 50, 50 );
ui_2DTable.set( 10, 20, 50 );
Table2D<unsigned int> ui_construct(ui_2DTable);
Table2D<unsigned int> ui_copy = ui_2DTable;

will have the pointer m_2DTable pointing to the same memory in all 3. If one goes out of scope, the memory will be deleted, while the others will still try to access it - if you're lucky, this will crash. I won't go into complete detail on how to fix this, but you can read about the so called "Rule of Three" here. Suffice to say, the version using std::map doesn't suffer from this problem (one of the nice benefits of standard containers is this comes "for free").


lib is not really lib, but your project's dependencies. Normally you'd call it vendor

tests -> test. This one is just a convention.

I took a quick look at your code and the first thing I saw was snake_case. JS/jQuery convention is to use CamelCase.


I would probably refactor these things:

Return Type Declaration

You're using argument type declaration, which is a good thing. You can even take it one step further and add a return type declaration as well:

: array

This will force the function to return an array. So the final definition will look like this:

public function filter(string $path, string $extension) : array {

Return Values

I would return an array in any case. If no matches where found this array would simply be empty:

return $results;

Check-ups

I would test a few things:

Is the directory available?
Is the directory readable?
Is the extension empty?

If any of these test fail, throw an Exception with a message describing the error. So, other parts have to worry about the validity of the arguments.

An example test for readability of an existing directory:

if (!is_readable($path)) {
    $message = 'The directory "' . $path . '" is not readble.';
    throw new \Exception($message);
}

Case Sensitivity

Currently your code will fail if you look for PDF but the file is called example.pdf. Use strtolower to get rid of this problem:

$extension = strtolower($extension);
$pathinfoExtension = strtolower(pathinfo($fileInfo, PATHINFO_EXTENSION));

FilesystemIterator

Currently you're using glob to iterate over the files. Alternatively use a FilesystemIterator. It has the advantages1:

increases readability
it skips dot files .|.. (as opposed to an DirectoryIterator)
it's extensible

Result

The final result would look like this:2

class DirectoryFilter {
    public function filter(string $path, string $extension) : ?array {
        $results = [];

        if (!is_dir($path)) {
            $message = 'The directory "' . $path . '" doesn\'t exist.';
            throw new \Exception($message);
        }

        if (!is_readable($path)) {
            $message = 'The directory "' . $path . '" is not readble.';
            throw new \Exception($message);
        }

        if (!$extension) {
            $message = 'An empty string is not a valid extension.';
            throw new \Exception($message);
        }

        $extension = strtolower($extension);

        $iterator = new FilesystemIterator($path);

        foreach ($iterator as $fileInfo) {
            $pathinfoExtension = strtolower(pathinfo($fileInfo, PATHINFO_EXTENSION));

            if ($extension == $pathinfoExtension) {
                $results[] = $fileInfo->getFilename();
            }
        }

        return $results;
    }
}

var_dump( (new DirectoryFilter())->filter(__DIR__, 'php') );

Further Thoughts

To reduce the amount of false-positives, like files that have a wrong extension, you should probably use some sort of MIME-type guesser. A good one, based on the PECL-extension, is the one included in the Symfony framework. The guesser uses two components: FileBinaryMimeTypeGuesser and FileinfoMimeTypeGuesser. The Symfony source code is a good starting point to go more into detail:

http-foundation / File / MimeType / MimeTypeGuesser.php

1 You can find more details in the answers of this question "What exactly are the benefits of using a PHP 5 DirectoryIterator over PHP 4 “opendir/readdir/closedir”?".

2 I removed all comments/PHPDoc to keep the answer compact.


First off, you should standardize your names, Key and value don't follow the same naming rules, or if they do, they're not apparent to me.
And so I'd recommend that you name your things in lower_snake_case, to adhere to PEP8.

After this I'd use str.strip rather than str.split.
And use a list comprehension to change both the key and value without having to duplicate the code, which can remove the key and value variables altogether.
This can leave you with:

item = [i.strip() for i in line.split('=')]
CQ_options[item[0]] = item[1]

If you want to stick with using key and value however, you need to make sure that line.split('=') will only return two items. You can make sure it'll return a max of two items with the optional parameter, and since we'd already error if there's not at least a single =, then you can use:

key, value = [i.strip() for i in line.split('=', 1)]
CQ_options[key] = value


Is there a way to optimize this aggregate postgreSQL statement by using CASE?

Naming conventions

I think your aliases are pretty cryptic.

This:

from schema.records tt

That:

from CTERatio c, hist h

It's better to use aliases that mean something. tt, c, h... think of Mr. Maintainer going back over your code having to make changes to it.

I will compliment you on re-labeling column names words, words2, words3. Those are pretty bad column names and your re-labeling makes them much more meaningful.

Indenting/Formatting

Your CTEs are beautiful in how they are formatted. Your final select statement, not so much.  How about this:

select
    c.playerid as player,
    c.champid as champion,
    c.roleid as rolee,
    round(c.ratio, 2) as ratio,
    round(c.kdar, 2) as kdar,
    round(c.win, 2) as win,
    round(c.ratio - h.ratio, 2) as ratiochange,
    round(c.kdar - h.kdar, 2) as kdarchange,
    round(c.win - h.win, 2) as winchange

Performance

This aggregate is expensive, especially used twice:

having count(*) > 2

This means the SQL engine will have to scan the whole table for each column to see if the count is greater than 2. Try to find a unique column to COUNT() on rather than the whole table, like having count(c.playerid) > 2

You have many sum() and round() aggregates, can we cut down on them somehow? It's hard to give specifics since we don't know what the data looks like, but try to limit those as much as you can.

Both of your CTEs seem identical. I'm curious as to why you are selecting the same dataset twice. You could do a self join instead.

Here is how I would write this script, bearing in mind I don't know what the data looks like:

with CTERatio as (
-- calculate ratio
select
    rec.playerid,
    rec.champid,
    rec.roleid,
    sum(rec.words) as kills,
    sum(rec.words2) as deaths,
    sum(rec.words3) as assists,
    sum(rec.words)/sum(rec.words2) as ratio,
    (sum(rec.words)+sum(rec.words3))/sum(rec.words2) as kdar,
    avg(rec.complete) as win
from schema.records as rec
group by rec.playerid, rec.champid, rec.roleid
having count(*) > 2
order by ratio desc

),
-- join ratio to itself to find highest ratio
select
    cte_r1.playerid as player,
    cte_r1.champid as champion,
    cte_r1.roleid as rolee,
    round(cte_r1.ratio, 2) as ratio,
    round(cte_r1.kdar, 2) as kdar,
    round(cte_r1.win, 2) as win,
    round(cte_r1.ratio - h.ratio, 2) as ratiochange,
    round(cte_r1.kdar - h.kdar, 2) as kdarchange,
    round(cte_r1.win - h.win, 2) as winchange
from CTERatio as cte_r1
  inner join CTERatio as cte_r2
    on cte_r1.playerid = cte_r2.playerid
    and cte_r1.champid = te_r2.champid
    and cte_r1.roleid = cte_r2.roleid
order by cte_r1.ratio desc
;


After reviewing your code, I'll point out that:

It would be better if you used more descriptive variable names. It improves readability and might even help you better understand your own code, ex:

int width = sc.nextInt(); // or whatever it represents

Always use curly braces for if and for statements, even if they wrap around a single statement. Shorter code isn't faster, but makes it easier to introduce bugs. You never pay a penalty for extra curly braces or parentheses, so use them as much as you want to clarify intention. For example this snippet can be ambiguous:

for (int i = 0 ; i< y ;i++)
    System.out.print("*");
w=w+1;
y=y-2;

Did you mean

for (int i = 0 ; i< y ;i++) {
    System.out.print("*");
    w=w+1;
    y=y-2;
}

or

for (int i = 0 ; i< y ;i++) {
    System.out.print("*");
}
w=w+1;
y=y-2;


Check if a binary tree is a binary search tree or not

Some quick notes:

Respect "Egyptian Braces" for your block structures (if, while, ...) i.e., the opening brace should be on the same line as the signature statement. The style you used (opening brace on a new line) is ordinarily used for C#, not Java.
Node could and should be as immutable as possible:

class Node {
    final int data;
    Node left;
    Node right;
    Node (int x) {
        data = x;
    }
}

isBST is not a good class name. Class names are usually nouns. I'd suggest (as was already in the currently deleted other answer) BinarySearchTreeUtil.
getMin and getMax are factually only correct if you assume that the Tree is actually a BST. Only checking for those two is not a sufficient indicator, though. A BST is only fully a BST if each and every node satisfies the condition you propose. Your code does not check for that.

You should instead verify that each subtree is a BST recursively. Aside from that you're also assuming that the BST is ordered with the smaller elements to the left. It's also correct for a BST to be ordered with smaller elements to the right. Your code doesn't deal with that either.

Overall your code does not correctly solve the problem. To remedy this I strongly suggest you invest some time into unit-testing your code. Furthermore, you're disregarding conventions about bracing (but you're consistent so it's somewhat acceptable), as well as class-names (that's not acceptable).


Merging and sorting overlapped intervals

I can't see the point in having the Create method here, there's no reason why a constructor can't throw an exception in C#. I'd just get rid of Create and move it all into the constructor (making it public).
The name IsOverlapped sounds a bit odd to me. Is is present tense and Overlapped is past tense. Maybe something like IsOverlapping or even just Overlaps.
You have a typo here: "Begin cannot me more than end". me should be be.
If you have access to expression-bodied members, they can reduce noise IMO:
public bool Overlaps(Span other) => other != null && Start <= other.End && End >= other.Start;

You'll notice that I've also put a null check for other in there at the same time.
You should rewrite Merge to call TryMerge internally:
public Span Merge(Span other) =>
    TryMerge(other, out var mergedSpan)
        ? mergedSpan
        : throw new ArgumentOutOfRangeException(nameof(other), "Spans must overlap");

I really value conciseness and I'm happy with throw expressions so I like this kind of pattern. If you don't, this version would also be fine:
public Span Merge(Span other)
{
    if (!TryMerge(other, out var mergedSpan))
        throw new ArgumentOutOfRangeException(nameof(other), "Spans must overlap");
    return mergedSpan;
}

Note: there's no need to check for null here as we now do that in Overlaps.
Your Normalise method looks good to me. It's a simple algorithm and easy to read.


A quick braindump:

PacketDeserializer#deserialize  is overcommented. Most comments restate what the code says. Try commenting as little as possible, but as much as necessary.
PacketDeserializer could benefit from not hardcoding the mapping between the type strings and classes. Consider passing a Map<String, Class<? extends Data>> as constructor parameter and replacing typeToClass with a map.get
Lastly you should also avoid rawtypes. Class without generics specification is a rawtype.

Continuing that thought, you really want a different name than Foo for the "PacketHandler" you pass in to Packet#handle. You should consider going so far as to extract the responsibility of handling the package into a separate class. A Packet should not know how to handle itself. It's originally just a data-holder, nothing intelligent :)


Abstracting the process of finding the index of the maximum in Python

I just want to find the index of the "best" item.

This can be written very shortly and readably using enumerate, first class functions and list indexing.

def index_of_max_value(items):
    return max(enumerate(items), key = lambda x: x[1])[0]

Explanation:

I create a list that contains the numbers and their indexes, the index is first, the number second.

>>> list(enumerate([4,7,4,8]))
[(0, 4), (1, 7), (2, 4), (3, 8)]

I ask the item that has the biggest value when a function I decide is applied to it, I do so by passing the function as the key argument, when functions are passed around like this they are first class citizens

>>> max(["rg","gu","sd"], key = lambda s: sum(map(ord,s)))
'gu'

For example in the above I asked which of the strings had the most ASCII value.

key = lambda x: x[1]

Means that I want the pair (index,number) that has the biggest 'second' item (remember zero indexing).

[n] gives you the n-th item of a list, I ask the '0-th' (first) item that is the index.

I hope that you like my alternative shorter solution, if you have any doubts, fell free to ask.


Simple State Machine and Transition Table

First there are a few things about design

Does you machine has something like 'error' that is not handled (e.g. by throwing an exception) or you have only 'outcomes' that handled in the same matter.

Do you expect branches in the FSM? Is it possible for an fsm method to fail? If possible how it is handled? E.g. ignored (say we rely on caller to retry on timer), raise failure event and queue it for execution, use return value as a guard to branch in state machine method.

Do you expect your code to maintained over 20+ years period?

After many attempts to make better existing FSMs, making my own, trying different frameworks and making my own frameworks too, I came to a trivially simple conclusion (aka 'dumb' FSM pattern): each event should be represented by a function and each function should contain a switch by state; or every state should be represented by a function and every function should contain a switch by event.

In the long run this is the cheapest solution. E.g. if you do not have branches/failure one can write a simple table driven fsm, however, once we got the first branch we need to either make it way more complicated or throw it away and rewrite using the 'dumb' approach


Determine if an image is opaque or transparent

I don't know how good the C# compiler and runtime optimize this code out of the box, so here is what I would try:

Load bitmap.Width, bitmap.Height and bitmapData.Stride into local variables.
Swap the two for loops, making x the inner loop. Memory accesses are now linear instead of jumping around (to see this, print the array index in your current code).

Side node: You should check whether your code works correctly on big-endian platforms. The + 3 looks suspicious. You could use a uint * instead of the byte * and test the pixel value like this: (p[x + stride * y] >= 0xFF000000.


There are couple of points that I'd suggest:

Be sure to always include types for top-level functions. Without them, the code becomes very quickly unreadable. For example, would you know what ins does and what is its type, if you didn't write it yourself? In many cases you can immediately judge what a function does just looking at its name and its type.
If you do

  | x < e  = ...
  | x == y = ...
  | otherwise = ...

you're performing the comparison twice. In most cases this shouldn't be a problem, but if writing

case compare x e of
  LT -> ...
  EQ -> ...
  GT -> ...

will compare only once, and also allows the compiler to do more optimizations.
This isn't a problem, just a note: Be aware that fastInsert trades speed for lazyiness. If you examine the root of the tree returned by a fastInsert call, the tree must be examined to check if it contains the inserted element or not. Under most circumstances you wouldn't mind that.
There is no need for ins to take Maybe (Tree e) as the argument, only to apply >>= on it. Most monadic functions take pure arguments and return a monadic one.
It's often convenient to use functions from Control.Applicative to lift pure functions/values to monadic computations. In particular pure, <$> and <*>. See also Functor, Applicative and Monad.

I wasn't sure what error handling you have in mind, as these operations should never fail.

The updated program:

import Control.Applicative
import Data.Maybe

data Tree e = Leaf | T (Tree e) e (Tree e) deriving Show

empty = Leaf

insert :: (Ord e) => e -> Tree e -> Tree e
insert x Leaf = T Leaf x Leaf
insert x tree@(T l e r) = case compare x e of
  EQ -> tree
  LT -> T (insert x l) e r
  GT -> T l e (insert x r)

ins :: (Ord e) => e -> Tree e -> Maybe (Tree e)
ins x Leaf = return $ T Leaf x Leaf
ins x tree@(T l e r) = case compare x e of
  EQ -> Nothing
  LT -> (\l' -> T l' e r) <$> ins x l
-- you could also write a point-free version, if you like,
-- which better preserves the order of arguments
--  LT -> T <$> ins x l <*> pure e <*> pure r
  GT -> T l e <$> ins x r

fastInsert :: (Ord e) => e -> Tree e -> Tree e
fastInsert x t =
  fromMaybe t $ ins x t


HackerRank - Birthday Cake Candles and the counting loop

The algorithm is to count the number of elements in the array that are equal to the max of the array.  Let the code express that.  Both the original code and the procedural accepted answer are a clutter of bookkeeping details.

function birthdayCakeCandles(n, ar) {
    const max = Math.max(...ar)
    return ar.filter(x => x === max).length
}


Can I change the below into 1 setter and 1 getter method?

You could use magic getters and setters, but you probably shouldn't (see the top-rated answer in that question; additionally, with the primitive approach, you would make all your private fields accessible from the outside).

You should also ask yourself if you even need setters. If the properties of the object never change after construction, you should make it immutable, as immutable objects are easier to handle (you know that they never change).

  I would like to use the rand() function for match ID can I do this inside the setter function of setMatchId or should it be done outside of the class?

You should not add a method setMatchId() that doesn't accept an argument, but just generates the id. Setters should set something, not generate something.

On the other hand, a method such as regenerateMatchId would be perfectly acceptable (although I'm not sure why you would want the id to be random).

  When I upload the class to a db I assume I would need to create a new method and code the DB upload inside the method or should this be done outside of the Class

By "upload to the db", you mean save in the database? Basically, you would have three options:

add the "save to db" method to this class
create a MatchDAO which saves matches to the db
use an ORM such as doctrine

Misc

class names should ideally start with an upper-case letter (see for example PSR-1)
your indentation is off, as is your vertical whitespace
what does the p in your argument names stand for? It's unclear, I would just remove it.


String tokenization and replacing a numbered field

Don't use the expensive string.format where string.char can do it all.
You should accept a string (of length 1) as separator in tokenize and puttok, and have a default.
Swapping the middle two arguments of puttok allows you to default the replacement to "".
Your second conditional is useless, as it will always be taken: The first one results in a runtime-error if N is not a number.
I wonder why you don't use an early return there anyway?
First removing an element and then inserting a different one at the same index is really inefficient, resulting in a need to move all higher-numbered elements first down and then back.
Just replace it already:

tokens[n] = token

Try for better names, so you don't need to explain so much in comments:

tokenize(C, strng) => explode(delimiter, text)
puttok(text,token,N,C) => replace_token(text, which, replacement, delimiter)
-- Switched the middle two parameters of puttok/replace_token


Project Euler, #4: Incorrect Results on 7-digit numbers

def main(n):
    """return the largest palindrome of products of `n` digit numbers"""
    strstart = "9" * n
    multic = int(strstart)

Firstly, for two such short lines you'd do better to combine them. multic = int("9" * n). However, even better would be to avoid generating strings and then converting to ints. Instead, use math. multic = 10**n - 1

    multip = multic -1

Guessing what multip and multic mean is kinda hard. I suggest better names.

    top = multic

    while multic > top * .9:

You should almost always use for loops for counting purposes. It'll make you code easier to follow.

        while multip > multic * .9:
            multip -= 1
            if isPalin(multic * multip):
                return multic, multip, multic*multip
        multip = multic
        multic -= 1

def isPalin(n):

Use underscores to seperate words (the python style guide says so) and avoid abbreviations.

    n = str(n)
    leng = len(n)

This assignment doesn't really help anything. It doesn't make it clearer or shorter, so just skip it

    half = n[:leng/2]
    if n[leng/2:] == half[::-1]:
        return True
    return False

Why split the slicing of the second half in two? Just do it all in the if. Also use return n[...] == half[..] no need for the if.

if __name__ == '__main__':
    main(3)

Here is my quick rehash of your code:

def main(n):
    """return the largest palindrome of products of `n` digit numbers"""
    largest = 10 ** n - 1
    for a in xrange(largest, int(.9 * largest), -1):
        for b in xrange(a, int(.9 * a), -1):
            if is_palindrome(a * b):
                return a, b, a * b

def is_palindrome(number):
    number = str(number)
    halfway = len(number) // 2
    return number[:halfway] == number[:-halfway - 1:-1]

if __name__ == '__main__':
    print main(3)

Your link on 7-digit numbers is to a post discussing integer overflow in Java. Integer overflow does not exist in Python. You simply don't need to worry about that.

The challenge asks the answer for a 3 digit problem, so I'm not sure why you are talking about 7 digits. Your code is also very quick for the 3 digits so I'm not sure why you want it faster. But if we assume for some reason that you are trying to solve the problem for 7 digits and that's why you want more speed:

My version is already a bit faster then yours. But to do better we need a more clever strategy. But I'm not aware of any here.


Recommend a uniform and more indented style.  E.g.

for(i=0;i<n;i++)
{
    sum+=power(x,n-i)*a[i];
}

Both a[11] and if(... n>10) rely on the same value.  Also to avoid undocumented magic numbers, consider the following (also the same for x and a[]):

#define n_MAX (10)
#define n_MIN (0)
int a[n_MAX + 1];
if(n<n_MIN || n>n_MAX) return 0;

unsigned long long int sum serves little value in protecting against numbers larger than INT_MAX as power() is the most likely candidate to overflow.  (Strictly speaking, it is not even known that LLONG_MAX is greater than INT_MAX.)  So if you want a larger range, re-write power() as unsigned long long power(int x, int y), otherwise leaving sum as int is OK.

Else suggest for marginal range improvement:

sum += (unsigned long long) power(x,n-i) * a[i];

BTW: should not it be:

unsigned long long int sum = 0;  //( 0 not 1)

Note: Stated objective says "It is not necessary to validate the inputs.".  Still I like the testing you have done.  Possible that the final reviewer (teacher?) may object to unneeded code.  Could wrap in an #if DEBUG macro...
Faster way to do power()
See no reason for x<0 test in if(x < 0 || y < 0) return 0;.  Could be

if (y < 0) return 0;

Do power() with unsigned rather than int as " function named power( ) that takes two positive integers x and y".
@Constructor comment leads to an excellent suggestion.  Calculate sum with a loop that does the below.  No need for a power function.  Running sum can be unsigned long long and code gets great range.  Its faster & simple.

// sum = (((a[n]*x + a[n-1])*x + a[n-2])*x + .... )*x + a[0];

// Something like
unsigned long long sum = 0;
for (int i=n; i>=0; i--) {
  sum *= x;
  sum += a[i];
}

Lastly, even the array a is not needed:

#include<stdio.h>
int main() {
  int n;
  unsigned x, a;
  unsigned long long sum = 0;
  scanf("%d%u", &n, &x);
  while (n-- >= 0) {
    scanf("%u", &a);
    sum *= x;
    sum += a;
  }
  printf("%llu", sum);
  return 0;
}


How should I efficiently delete elements from a PHP array?

Your code is just fine, exactly how I would do it.

There isn't much to discuss really, it's kind of simple. It's as effective / efficient as it could be, and fairly readable.


You don't need line continuation characters inside brackets.

After splitting up your reduce lines, line_profiler says most of your time is actually in

(p2grid[0:n] * 3*Bgrid[0:n] / (p2 * (p2grid[0:n] + Bgrid[0:n]**2))) * dq[0:n]

and

(3*Bgrid[i:] / (p2grid[i:] + Bgrid[i:]**2)) * dq[i:]

Extracting those outside of the loop and pulling a division out of the sum:

t2 = dq * 3 * Bgrid / (p2grid + Bgrid**2)
t1 = t2 * p2grid

for i, p2 in enumerate(p2grid):
    # If lower and upper limit of an integral are the same, set to 0
    if i > 0:
        int1 = np.add.reduce(t1[:i+1]) / p2
    else:
        int1 = 0

    if i < N - 1:
        int2 = np.add.reduce(t2[i:])
    else:
        int2 = 0

    # Write new values to buffer variable
    Bgrid_new[i] = C * (int1 + int2)

gives a good speed boost.

You can also simplify the logic to:

val = 0

if i > 0:
    val = np.add.reduce(t1[:i+1]) / p2

if i < N - 1:
    val += np.add.reduce(t2[i:])

Bgrid_new[i] = C * val

But then note you have a sliding summation; you can do this beforehand with numpy.add.accumulate.

    t2 = dq * 3 * Bgrid / (p2grid + Bgrid**2)
    t1 = t2 * p2grid

    val1_accumulate = np.add.accumulate(t1)
    val2_accumulate = np.add.accumulate(t2[::-1])[::-1]

    for i, p2 in enumerate(p2grid):
        # If lower and upper limit of an integral are the same, set to 0
        val = 0

        if i > 0:
            val = val1_accumulate[i] / p2

        if i < N - 1:
            val += val2_accumulate[i]

        # Write new values to buffer variable
        Bgrid_new[i] = C * val

This is much faster.

Now this loop can probably be vectorized.

Bgrid_new = np.zeros_like(Bgrid)
Bgrid_new[+1:] += val1_accumulate[+1:] / p2grid[+1:]
Bgrid_new[:-1] += val2_accumulate[:-1]
Bgrid_new *= C

All in all, this seems to be a factor of 300-400 faster. You can do other optimizations like

dq = np.zeros_like(p2grid)
dq[1:] = np.diff(p2grid)

and removing the call to copy, but it should already be fast enough.

Then you should focus on cleaning up the code. Spacing is important as are appropriate variable names (snake_case and not-single-letter names). The trick is to make comments redundant:

num_grid_points = 1000 # Number of grid points

Note how the comment can now be removed.

Here's an attempt at a cleaner version. I've also added a couple more speed improvements, because I'm a hopeless addict:

def solver(alpha = 2.):
    uv_cutoff = 1
    num_grid_points = 1000
    max_iterations = 100

    # The grid on which the function is evaluated
    p2_grid = np.logspace(-10, 0, num_grid_points, base=10)

    dq = np.empty_like(p2_grid)
    dq[0], dq[1:] = 0, np.diff(p2_grid)

    b_grid = np.ones(num_grid_points)

    c = alpha / (4 * np.pi)

    for iteration_num in range(max_iterations):
        t2 = 3 * dq * b_grid / (p2_grid + b_grid*b_grid)
        t1 = t2 * p2_grid

        t1_cumsum = np.add.accumulate(t1)
        t2_cumsum = np.add.accumulate(t2[::-1])[::-1]
        t1_cumsum[0] = t2_cumsum[-1] = 0

        b_grid_new = c * (t1_cumsum / p2_grid + t2_cumsum)

        # Calculate relative error (take the maximum)
        max_error = np.max(np.abs((b_grid - b_grid_new) / b_grid_new))

        b_grid = b_grid_new

        if max_error < 10**-4:
            break

    print "Finished in", iteration_num + 1, "iterations, relative error:", max_error
    return p2_grid, b_grid / np.sqrt(uv_cutoff)

I'm not really sure how to rename these, though, because I'm not familiar with the maths.


This code is very nice and easy to follow along with.

You should check the return value of socket.socket to make sure that the socket was created successfully

Usually, the name given to an error in a try/catch(or except) statement is something along the lines of "err", not "msg".

You should pass an error code to sys.exit so that external programs will know if there were any errors during the execution of the program.

In the while loop of clientthread, you use True to specify an infinite loop.

However, in the while loop just below that function, you use 1. You should stay consistent and use True for that one.

Instead of just printing the data, add a short message before it so the purpose of the number is more easily understood in output.

Example:

print 'Client data: ' + data

I don't believe that the s.close call at the end of your code will actually run.

This may not be necessary, as the socket may close automatically, but I would set up a signal handler to close the socket when someone tries to exit the program. You can use the signal library.

I came up with something like this:

def close_socket():
    s.close()
    sys.exit(0) # success

Then, right before your final while loop:

signal.signal(signal.SIGINT, close_socket)


Translating Dijkstra's Algorithm from Python to C++

Avoid translating Pythonisms

  Dijkstra's algorithm really exploits nested dictionaries and weak typing which I used as an excuse to try out std::optional.

No, Dijkstra's algorithm does not require nested dictionaries nor weak typing. Maybe the Python implementation you are translating used these things, but maybe just because it was convenient in Python.

I strongly advise you to try to write idiomatic C++ code, not idiomatic Python translated to C++. What is convenient in Python might not be the best fit for C++, especially not when it comes to performance. I recommend you try to implement Dijkstra's using a priority queue.

Furthermore, putting everything into main() is bad practice. It's better to organize your code into functions and classes as appropriate, and that's true even in Python.

Use of typedefs

It's always a good idea to give a name to things, including types, that you use in multiple places in your code. However, in this case I think it would be better to create a class WeightedGraph that contains all the information about a graph with weighted edges. Then you can add member functions to this graph to add and remove vertices and edges, and a member function get_shortest_path() that uses Dijkstra's to calculate the shortest path between two given vertices and returns the list of vertices.

Use of std::optional

While it's possible to use std::optional here to represent the parent of a vertex, it might not be necessary. If you represent vertices by their name, then an empty string for the name might be used as the equivalent of None. And a more idiomatic C++ implementation of this algorithm would probably store each vertex's parent vertex using a pointer, in which case the nullptr would be the equivalent of None.


Performs calculation with operators given in an unknown order

I find this task rather bizarre, but anyway…

The function signature should probably be

int simpleInterpreter(int value, const std::vector<char> &operations, const std::vector<int> &args)

Instead of writing separate index++; statements, I'd roll them into a post-increment operator:

value *= args[index++];

To be clear that index refers to the args vector, I'd rename index to argIndex.


Split a number into equal parts given the number of parts

In general, building a list using a loop of the form

some_list = []
for …:
    some_list.append(…)

… would be better written using a list comprehension.

Each interval always has two elements: a start time and an end time.  These two-element lists would be better represented as tuples instead of lists.  (Tuples have a connotation that they have a fixed length, whereas lists can grow to arbitrary lengths.)

Finally, I'd package the code into a function.

def intervals(parts, duration):
    part_duration = duration / parts
    return [(i * part_duration, (i + 1) * part_duration) for i in range(parts)]


Polling script to determine the continuous time a user has been connected

Structure of your Javascript is tightly coupled with your logic, decoupling will allow change without major changes.

a) Move you Ajax initialization [xmlHttp] to a usable function.

b) UnIntended display of UserId req.send("data=<?php echo $user->id; ?>"); as plain text inside your javaScript is security risk

c) Refactor your client script and least packit(dean edwards works ok) and compress it.

d) Using a comet based server is Best solution to this rather than polling the server at defined intervals. I would recommend you learn APE Project

another point! you can do it this way, when user navigates away from page ask them a few seconds to send ajax request. You have login time and now you have leaving time , calculate Hit rate yourself.
Also using LocalStorage will be viable option too


for (int i = n;;) {
    if (i == 0) {
        break;
    }

This look very odd instead you can do

for(int i = n; i > 0;){

Asserts are kinda useless in java, they only work when the jvm is started with the -ea flag (or you do some reflection). instead just test and throw the IllegalArgumentException in the public method and remove the obvious assertions that would throw anyway.


Multiple permission checks in web app automated tests

So, thing is, it's GREAT that you made the individual tests. Imagine this method with all those tests inlined. That'd be... really bad. So that part is good. But like you say, something is off.

Now, one way you could look at this is that you don't really need to test everything. That depends on what an implementation means, but someone has read rights if they can read a file. Whether or not they can write... it doesn't matter. But, that depends on your business requirements, so such a simplification may not apply.

Another thing you could do is apply semantic grouping. Combine checks that are in the same category.

There seems to be 3 groups:

Read access, which is the ability to read any file (canCopyMultipleItems, canDownloadMultipleItems, canDownload, canViewDetails, canCopy).

Create+Read access, which is read + append to directory. (canCreateNewFolder, canAddLink)

Write access, which is read + create + write. (canMoveMultipleItems, canDeleteMultipleItems, canEdit, canMove, canHide, canDelete).

If you are only interested in verifying that someone has "at least" these rights, this is easy, you can make three groups of checks (each of them including the previous) and return the appropriate value.

If, however, you're only allowed to have the exact matching set of rights, then the check becomes harder, I'd dare say that what you have right now is the fastest code you could have; any faster is going to be faster because of a redesign.

From a readability perspective, all I'd do is this:

Wrap each grouping we just mentioned in two separate functions:

hasAny<group>Right and hasAll<group>Rights.

Then you can use them like so:

public boolean hasPermissions(String permissions, File file) {

    if ("Read Only".equals(permissions)) {
        return hasAllReadRights(file) && !hasAnyCreateRight(file) && !hasAnyWriteRight(file);
    } else if ("Read and Add Only".equals(permissions)) {
        return hasAllReadRights(file) && hasAllCreateRights(file) && !hasAnyWriteRight(file);
    } else if ("Full Access".equals(permissions)) {
        return hasAllReadRights(file) && hasAllCreateRights(file) && hasAllWriteRights(file);
    } else {
        throw new UnsupportedOperationException("Unsupposrted permission");
    }
}

Perhaps even name "create" "add" instead.

That all said, you... clearly have a design issue going on. A string goes in, and based on that you're doing checks? Huh?

First, stringly typed code should be replaced with Enums. Second, having to check every single time if the user has a set of general rights is ... weird. These should be migrated to a different place; then all you're interested in is if the user has generic read rights, + the few things that are file specific. If instead you're relying on class variables in these "generic" checks (like canDownloadMultipleItems), then... well... then I still think it's worth splitting these checks up into "generic" and "file-specific" checks; if you're ever going to be looping over a directory, you'll want to be checking the generic parts only once, and not all the time.

Also, there's a typo in your exception. "Unsupposrted permission" -> "Unsupported permission"


Initialize all variables: fp, c, file etc.

your downloadAndOpen function has some issues

You do a system call to download (asynchronous call), but you do no attempt to wait for it to finish - instead you directly try to open it. If for some reason the download takes longer then it will fail. If your function fails you get a crash since you do not handle the return value of fopen.

I think the better approach would be to split it in two functions, one which does the download and returns when the file is there, alt. timeout with error code. Second part to open the file and returning the file pointer.

E.g.

int downloadFile( int pageNumber ); // return 1 - file downloaded 0 - failed
FILE* openFile( int pageNumber ); // NULL - file not found

Then add some checks to make sure they succeeded before you proceed.

if (downloadFile(pageNumber))
{
  FILE* fp = openFile(pageNumber);
  if (fp != NULL)
  {
   ...

You are a bit inconsistent with your if statements, sometimes you use braces sometimes not, sometimes the starting brace is on the same line as the if statement sometimes under the if. It makes the code harder to read. Choose one way and stick with that.

I am also not sure why you pass FILE** fp to download(), since you do not open some other file in there it is enough to pass the file pointer itself download(FILE* fp)

Global variables; bad, especially if they are not really used by several functions e.g. length1 is only used in main().

Comments; good to have. especially when I read such a line

for ( int i = 22; i <= 151; i++ )

It would be interesting to know why you start at 22.

EDIT:

I see you have some of my comments already in your todo list, anyway I will keep them here as well.


Flow control with try catch to reduce redundancy

In cases like this, I like taking a default-unless-better approach... Consider this re-working of your code to do the same thing in a different order.

The basic premise is:

set up a default value (or null if it is a complicated thing to do).
do the hard work which may be missing dependencies or may fail
if the hard work completes successfully, return that result.

The reason this works well is because you can exit from the hard work at any point, and have the default standing by to continue.....

... also, as an exercise, use the try-with-resources and new NIO2 features in Java7

// set up the default value...
SomeValue result = null;
Path path = Paths.get("./data.txt");
if (Files.isRegularFile(path)) {
    try (SeekableByteChannel channel =
            Files.newByteChannel(path, StandardOpenOptions.READ)) {

        // do the work required for your file....
        ...

        // after everything is successful... set the result:
        result = new SomeValue(....real arguments ....);
    } catch (IOException ioe) {
        System.out.println("FileNoFoundException: " + e.getMessage());
    }
}
result == null ? new SomeValue(defaults...) : result;

Additionally, there is no reason, if you are in a method that builds these things, that you can't return immediately with the right answer.

Often if you are doing things like the above, it indicates that what you are doing should be in a sub-method, with an early-return when you have a successful setup, and a default return value when things fail.


It's not exact translation of your code, but still :) I've just tried!

Unfortunately, it's not a github project, so I don't have an access to the excel sheet, so I can't really run and test it. But, anyways, ideas are:

Utilization of toString() java method
Using of lazy properties allows to 'cache' the URL easily. It's also possible because all of the Books properties are immutable.
Extension method download() doesn't really belong to a book, but, instead,
can easily download any URL
I used require(), though, it's not really correct, since it throws an exception, instead of gracefully exiting the app. I used it, just to demonstrate it, nothing more.

And, probably, something else. Please, tell me what you're thinking!

data class Book(
    val title: String,
    val author: String,
    val edition: String,
    val year: String,
    val category: String,
    val url: String
) {
    constructor(row: Row) : this(
        row.getCell(0).stringCellValue, row.getCell(1).stringCellValue,
        row.getCell(2).stringCellValue, row.getCell(4).numericCellValue.toString(),
        row.getCell(11).stringCellValue, row.getCell(18).stringCellValue
    )

    override fun toString() = "$title, $edition - $author"

    val downloadURL by lazy {
        val canonicalURL = Jsoup.connect(url).get().select("link[rel=canonical]").attr("href")
        val pdfRelativeURL =
            Jsoup.connect(canonicalURL).get().select("""a[href^="/content/pdf/"]""").attr("href")
        URL("https://link.springer.com${pdfRelativeURL}")
    }
}

fun URL.download(to: Path): Path {
    Files.createDirectories(to.parent)

    Channels.newChannel(openStream()).use { inChannel ->
        FileOutputStream(to.toFile()).channel.use { outChannel ->
            print("Saving $this to $to... ")
            outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE)
            println("DONE.")
        }
    }

    return to
}

fun main(args: Array<String>) {
    require(args.size == 2) { "Please pass <full_path_to_springer_excel_file> and <full_path_to_download_folder" }

    val (excelPath, downloadFolder) = args
    val excelFile = WorkbookFactory.create(File(excelPath))

    // drop(1): skip the first row because it contains the headers
    val books = excelFile.getSheetAt(0).drop(1).map { Book(it) }

    books.map { book ->
        val path = Paths.get(downloadFolder, book.category, "$book.pdf")
        book.downloadURL.download(to = path)
    }
}
```


Displaying different tutorials about OneNote

while (Data.ItemList.Count > 1)
{
    Data.ItemList.RemoveAt(1);
}

I'm not exactly sure what ItemList is, but I would implement a Clear method to do this. If it's not your code, write an extension method.

As for your actual question, it's very similar to the switch smell and could probably be solved the same way.

if (version == "Phone")
if(version == "WStore")
if (version == "2013")

Sometimes you're taking an identical action, sometimes your not. So, you could definitely start with extracting the duplicated logic out into a private method, but I would also consider a better OOP approach.

I don't really have enough context to show you how I would go about that, but the general gist is you should have a base class that implements the "default" behavior of your class. Then, you would implement a child class for each each of these different versions. The child class would override the appropriate behavior.


NetBuffer - buffer specialized for socket read / write

One of the benefits of circular buffers is that they can be filled up to the entire size of the buffer, with completed fields being extracted from the head of the buffer immediately freeing up space.  This isn't the case for your buffer.  Space in the buffer is never freed until the entire buffer has been read, so if partial fields are consistently read there is a risk the buffer will get to a full state.

dataTail

You've declared your other access methods, including data as const.  Is it a mistake to not declare dataTail as const?  It's not entirely clear to me why a client would need to have a pointer to the bit of the buffer you haven't used.  Or are you expecting the client to actually write to the dataTail, without amending the tail_ afterwards?!?

push

Your extended push seems like it has a bug (or allows a very strange use case):

bool push(size_t const len, const void *ptr = nullptr){
    if (len == 0)
        return false;

    if (capacity() < len)
        return false;

    if (ptr)
        memmove(&buffer_[tail_], ptr, len);

    tail_ = (size_type) (tail_ + len);

    return true;
}

If ptr is null, then no bytes are added to the buffer, however the tail is still incremented as if data had been written.  So effectively, whatever is already in the buffer is added instead.  Having ptr default to null suggests this might be expected behaviour but it seems very odd.

print

print may be a debug method, however its output is confusing.  As you pop from the buffer, you're reducing the number of characters from the buffer that are displayed however you're still printing from the start of the buffer.  This gives the impression that pop is actually removing from the tail, rather than the head.  You should probably be printing from the head instead:

printf("h: %3u | t: %3u | ad: %3zu | ac: %3zu | %.*s\n",
        head_, tail_,
        size(), capacity(),
        (int) size(), data());


You don't need to use recursion here,  commands and args array have the same size you can simply loop through it.

long result=value;
for (int i=0; i<commands.length;i++) {
   result = calc(result, commands[i], args[i]);
}

And you need to check size of arrays before use, to prevent ArrayIndexOutOfBoundsException

if (commands.length != args.length)
    return -1;

P.S. You work with int, but result can be larger than Integer.MAX_VALUE, therefore use long type for result


Some quick remarks:

pid, dateofvisit, stamp, type are all properties and thus should follow Microsoft's naming guidelines. Moreover "pid" is fairly meaningless, why not call this "PetId" as well?
testTypes does not convey its actual contents.
Using an int to indicate a type is meaningless. I don't know what a test of type "1" is, or a "2". You should translate this into an enum with meaningful values.
WRT // columns are the number of tests in every TestTable: why do you need this? Can't you just count the entries in the property Tests?
Why is GetTable(Test test, ref TestTable table, int index) a public method? I doubt this is re-used elsewhere. Please apply the correct access modifier to a method, class, property, field etc.

I find your logic hard to understand. I've tried to rewrite it, based on what I think is happening, and this is what I came up with:

    public IEnumerable<TestTable> TestHistoryItems()
    {
        IEnumerable<Test> tests = // get data

        var testTables = new List<TestTable>();

        foreach (var testType in new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 16 })
        {
            var relevantTests = tests.Where(x => x.Type == testType).ToList();

            if (!relevantTests.Any())
            {
                continue;
            }

            testTables.Add(GetTestTable(relevantTests));
        }

        return testTables;
    }

    private TestTable GetTestTable(IReadOnlyCollection<Test> tests)
    {
        var sampleTest = tests.First();
        return new TestTable
        {
            TestName = sampleTest.TestTypeName,
            Type = sampleTest.Type,
            Rows = sampleTest.TestDatas.Count,
            Tests = tests
        };
    }

You could even reduce the first method even more:

    public IEnumerable<TestTable> TestHistoryItems()
    {
        IEnumerable<Test> tests = // get data

        return new[] { 3, 4, 5, 6, 7, 8, 9, 10, 16 }
            .Select(testType => tests.Where(x => x.Type == testType).ToList())
            .Where(relevantTests => relevantTests.Any())
            .Select(GetTestTable)
            .ToList();
    }

To me, this looks a lot clearer: I see there's a list of test types you filter on, and based on that you make a List of TestTables for each type that has actual tests.

Again: I'm not 100% sure this is what you're doing, and that's because of the convoluted way your code works. And that is a major problem: good code can almost be "read" as a story. When I need to spend time trying to figure out that index is actually a test type that you've re-purposed, etc., that's a waste of time and energy.


File path unified in Windows/MacOS/Linux

There are a couple of things that bother me:

1) I don't think you have properly implemented relative and absolute paths. At least in Windows: absolute path = working directory + relative path. Your class only does this conversion correctly, if working directory is root directory, which is almost never the case in .Net. I don't know how things are in Linux, but from Windows perspective this is a surprising behavior. It should be either well documented or fixed.

2) You assume that 1:1 two-way conversion always exists. But does it? Windows is not case sensitive, Linux is. Windows has one letter volumes, Linux does not. Those are just a few differences off the top of my head. You  can replace slashes all you want but that won't give you volume information.

3) How would you add macOS to current implementation? AFAIR, it is very much like Linux, but not exactly the same, is it? To me it looks like you would have to pretty much rewrite the entire thing. This is a good indication that overall design can be improved.


I think WinJS already provides this:

WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise.

See also  http://msdn.microsoft.com/en-us/library/windows/apps/br229729.aspx

If you wish to continue with your own function, then you should review how promises ought to work, I don't think you are using the promises object the way it was intended.


Enumerate multi-subsets for a multiset in Python

It's a good idea to divide code into functions — this makes it easier to document, test and reuse the code. Here it would make sense to have a function defined like this:

def sub_multisets(elements):
    "Generate the sub-multisets of the iterable elements."
    # code goes here

Then you could call sub_multisets(s.split(',')) or whatever in the main program.
The code in the post omits one of the sub-multisets, namely the empty sub-multiset.
Wherever you have code using defaultdict(int), consider using collections.Counter instead. This is a specialized data structure for counting things. Here you could write:

A_counts = Counter(s.split(','))

with no need for a loop.
To compute the Cartesian product of some collections, use itertools.product. Here we need something like:

product(*[range(n + 1) for n in A_count.values()])

For example:

>>> A_count = Counter('aab')
>>> list(product(*[range(n + 1) for n in A_count.values()])
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

which are the sub-multiset counts required.
To build the sub-multiset, we can use the Counter.elements method, for example if we have the counts (1, 1) we can write:

>>> tuple(Counter(dict(zip(A_count.keys(), (1, 1)))).elements())
('a', 'b')

Another way to do this would be to use itertools.repeat and itertools.chain:

>>> tuple(chain.from_iterable(repeat(k, n) for k, n in zip(A_count.keys(), (2, 1))))
('a', 'a', 'b')

but I think the Counter.elements approach is slightly simpler.

Putting all this together:

from collections import Counter
from itertools import product

def sub_multisets(elements):
    """Generate the sub-multisets of the iterable elements.
    For example:

    >>> [''.join(s) for s in sub_multisets('aab')]
    ['', 'b', 'a', 'ab', 'aa', 'aab']

    """
    counts = Counter(elements)
    for sub_counts in product(*[range(n + 1) for n in counts.values()]):
        yield Counter(dict(zip(counts.keys(), sub_counts))).elements()


Duplicate detection and reporting in a BST

General

Your code style here is good, the variable names are nice and descriptive, and the algorithm you implement is easy to identify and follow. This is good-looking code. There are a few of nit-picks:

the TreeNode class should be a 'static' class ... private static ... because it has no reason to keep a reference to the outer class.
Your TreeNode.item should be final even though it is an internal class. final variables make for more apparent logic.
this is an opinion thing, but I prefer there to be getter/setter methods even on internal classes. With modern IDE's like Eclipse, IntelliJ and NetBeans, there really is no 'lazy' excuse for it. I prefer methods like node.getRight() instead of node.right
your method print() should have a better name like printDuplicates()

Algorithm

The solution you have for this problem appears to work. The algorithm relies on passing a token around, and relies on first walking the right-edge of the tree to create a 'stop-gate'. These two items detract from the solution. There are 'simpler' ways to do this recursive problem without the overheads you have. Consider the functions:

public void printDuplicates() {
    printDuplicatesHelper(root, 0, 0);
}

private void printDuplicatesHelper(final TreeNode node, final int parentval, final int parentcount) {
    if ((node == null || node.item != parentval) && parentcount > 1) {
        System.out.printf("Item %d was duplicated %d times\n", parentval, parentcount);
    }
    if (node == null) {
        return;
    }
    // make sure the parentcount is 0 going left.
    printDuplicatesHelper(node.left, 0, 0);
    printDuplicatesHelper(node.right, node.item, node.item == parentval ? (parentcount + 1) : 1);
}

The above functions also do an in-order scan of the data. The difference is that the recursion is designed to go past the leaf node, and to treat the null node as if it was the end of a duplicate streak. By doing it this way, and by pushing the duplicate-detecting values down with the recursion, you can detect the end-of-duplicates in a much easier pattern.

I created a 'main method' that compares the above code with yours:

 public static void main(String[] args) {
     TreeNode left = new TreeNode(null, 1, new TreeNode(null, 1, null));
     TreeNode right = new TreeNode(
              new TreeNode(null, 5, new TreeNode(null, 5, null)), 6, new TreeNode(null, 6, new TreeNode(null, 6, null)));
    TreeNode top = new TreeNode(left, 3, right);

    DuplicateCountInBST tree = new DuplicateCountInBST();
    tree.root = top;
    tree.print();
    tree.printDuplicates();
}

And the results I get from running the two calls are:

1 : 2
5 : 2
6 : 3
Item 1 was duplicated 2 times
Item 5 was duplicated 2 times
Item 6 was duplicated 3 times


Code to find the proper index comparing 3 values for max one

I think it's easier to follow the second version. I've extracted out some helper variables:

    final int b = array[i][j + 1];
    final int c = array[i + 1][j];
    final int d = array[i + 1][j + 1];

    if (d > b && d > c) {
        i = i + 1;
        j = j + 1;
    } else if (b > c) {
        j = j + 1;
    } else {
        i = i + 1;
    }

It seems a little bit readable for me but to be honest I'm not completely satisfied with the result.


Chaining async functions of a module without Promises

You're basically starting to rewriting promises. I think there are pros and cons:

For your solution:

Its a little simpler. I would have created a wrapper function around queue.push to make it clearer and easier to modify. You could also make this into a re-usable base class. Lastly, I'm not sure why you create and refer to me everywhere instead of just referring to SCOPE.
It's your own code so if it doesn't do what you want you can change it.
You don't need to wait/hope someone will implement a feature you need.

For promises:

Promises has more functionality (Promise.all, catch, race) and you can have multiple thens attached to a promise.
Thousand's of people have reviewed the Promise code for bugs.
Other developers will know what promises are but have to learn your code.


Get the value of the name attribute of each element with class="class"

Pure JS vs jQuery

Pure JavaScript will be significantly faster as you can see by this jsPerf which pits document.getElementByClassName vs the jQuery selector. Here are the results for Chrome 25:

$('.class') - 4355 operations per second
getElementsByClassName('class') - 94636 operations per second

As you can see, for this simple operation the jQuery option is approximately 22 times slower than the pure-JavaScript equivalent. You can easily see why this is the case by checking out the jQuery development source, since the jQuery 'selector function' is so general it needs to do a lot of checks to see what the input is before it can act upon it.

Pure JS implementation

I've left the jQuery click event in as it looks like you already have a dependency on jQuery so no point changing the way you're hooking up your events.

jsFiddle

$("#Button").click(function() {
    var items = document.getElementsByClassName('class');
    for (var i = 0; i < items.length; i++)
        alert(items[i].name);
});

getElementsByClassName

Also note that I used getElementsByClassName. It is pretty important to choose the ideal selector if you care about performance. Since we care about all elements with a certain class we can immediately dismiss the others like getElementsByTagName and querySelectorAll and opt for the function that was built for finding elements of a particular class.

jQuery implementation

This would be my implementation using jQuery, notice that I didn't bother getting the jQuery object for this (ie. $(this)) because the plain JavaScript attribute is much easier in this case.

jsFiddle

$("#Button").click(function() {
    $(".class").each(function() {
        alert(this.name);
    });
});


I would go with the chunk method:

cars.chunk { |c| c[:speed]>320 ? :above_320 : :the_rest }.to_h

Though it's important to underline that chunk doesn't work if the array is not ordered (by speed in this case). In that case we need to prepend it with sort_by:

cars.sort_by {|car| car[:speed]}.chunk { |c| c[:speed]>320 ? :above_320 : :the_rest }.to_h

(Moreover, if we want to order the hash keys, like in the example, we need to call sort after chunk):

cars.sort_by {|car| car[:speed]}.chunk { |c| c[:speed]>320 ? :above_320 : :the_rest }.sort.to_h


Case insensitively removing a substring, efficiently

Regular expressions make your life really easy when solving such exercises:

public static String withoutString(String base, String remove) {
    return Pattern.compile(Pattern.quote(remove), Pattern.CASE_INSENSITIVE).matcher(base).replaceAll("");
}

I explain this code a little:

Pattern.compile(Pattern.quote(remove), Pattern.CASE_INSENSITIVE): Creates a regular expression pattern containing the string you want to have removed. Pattern.quote(remove) takes care of special characters that may be interpreted as a regular expression (such as: *, \, +, (), [] etc.). The flag Pattern.CASE_INSENSITIVE makes sure, that the case of the characters don't matter.
.matcher(base): returns a Matcher that holds all matches of the regular expression in the string base.
.replaceAll("");: replaces all matches that have been found with an empty string, effectively removing them.

You may have noticed, that I made this method static because it does not access any fields or methods that are non-static. This is always advised unless it really needs to be non-static for some reason.


Based on the code that you've supplied, here's my take on some small changes in responsibility.

First of all, the NSManagedObject subclass.

You can write this by hand (as I think you have done) but I prefer to have Xcode generate this subclass automatically from the xcdatamodeld file (this option is found in the 'Editor' menu).

Note that in the latest version of Xcode, this file isn't added to your project, but actually added to the 'DerivedData' folder so unless you go looking for it you'll probably never see it.

If you find it and open it up, it will probably look something like this this:

import Foundation
import CoreData

@objc(User)
public class User: NSManagedObject {

    @NSManaged public var name: String?
    @NSManaged public var email: String?
    @NSManaged public var authToken: String?
}

Second, an extension that contains some methods that are specific to working with JSON objects.

Instead of a class function to create a User object, I'd use a failiable initializer init?() that returns nil if an instance could not be created.

I'd also create some way to reference your string keys so that you're not typing them by hand each time. This could be a struct, or just a bunch of static let statements. I prefer the struct because it puts all the keys in a similar namespace that helps organize your code, but also helps with auto completion when you're typing out the keys.

import SwiftyJSON

extension User {

    // prevent accidental typos when working with string keys
    struct Keys {
        static let name = "name"
        static let email = "email"
        static let authToken = "auth_token"
        static let user = "user"
    }

    // convenience initalizer for making `User` from a JSON object
    convenience init?(in context: NSManagedObjectContext, with json: JSON?) {
        guard let json = json else { return nil }

        email = json[Keys.email].stringValue
        authToken = json[Keys.authToken].stringValue
    }

    // updating existing instance with data from a JSON object
    func update(from json: JSON?) {
        guard let json = json[Keys.user] else { return }

        name = json[Keys.name].stringValue
        email = json[Keys.email].stringValue

    }
}

Finally, I'd remove any code that calls save() on your context from within the User object, and have this in the controller. I'd probably also remove the code that fetches a User and also have this moved into  the view controller.

Personally, I'd also not call save() on the object when it's newly created, and instead defer that until some later time (such as when the view controller is exiting).

import UIKit

class ViewController: UIViewController {

    var context: NSManagedObjectContext?

    func someMethodThatCreatesUser() {

        guard let context = context else { return }

        let json: JSON?  // ... grab json
        guard let user = User(in: context, with: json) else { return }

        // do something with the user...
    }

    func someMethodThatGetsExistingUser() -> User? {

        guard let context = context else { return nil }

        let request: NSFetchRequest<User> = User.fetchRequest()
        // `fetchRequest()` is auto generated by Xcode, if you create
        // your own managed object subclasses you'll need to do some
        // additional work here.

        let users = try? context.fetch(request)
        return users?.first

    }

    deinit {
        guard let context = context else { return }
        context.perform {
            try? context.save()
        }
    }

}


Shorthand for isset($var['foo']) ? $var['foo'] : ''

Now three years later we have the Null Coalesce Operator in PHP7:

 $val = $var['foo'] ?? '';

http://3v4l.org/Kcb2A


Cellular automaton (Conway's Game of Life) in python

I'm on my phone, so I can't write anything too elaborate. I'll just make some notes:

I don't think you're making good use of functions here. For the most part, you have everything tucked inside of update. I think that function is far too large, and doing too much explicitly. I would, for example, create a function called should_live or something similar that is passed the cell's current state and number of neighbors, and returns if the cell should be alive the next tick or not.

You do break some of that functionality off into a local function neighbors, but I don't think it's ideal the way you've done it. I would make that an external function, and I would call it n_neighbors or count_neighbors or something similar to make it clearer that it's a function that counts neighbors, not a collection of neighbors. You could also clean up that long list comprehension guard by creating a is_inbounds function that checks if a point is i bounds or not.

I'd also rename update, as is isn't actually updating anything. It's gathering information then returning a decision.

I would not have code top-level like you have it here. Having the code run just because you loaded it will get annoying if you ever change your workflow to involve a REPL. I would tuck the routine into a main function, then maybe call that function from a if __name__ == "__main__" block.

In short, I'd break your code up more and be more cautious when it comes to naming.


First of all your indentation is a bit wacky. Sometimes you indent by 4 spaces, sometimes by 2 (which is the default in the ruby community) and sometimes not at all (for example you didn't indent the call to attr_accessor or the contents of the initialize method). You should fix that.

attr_accessor :tileSprite, :attribute
# ...
def tileSprite
    @tileSprite
end

def attribute
    @attribute
end

No need to call attr_accessor and define the getter methods yourself. Do one or the other.

def array2D(width,height)
  a = Array.new(width, MapTile.new(123,0))
  a.map! { Array.new(height, MapTile.new(123,0)) }
  return a
end

Creating an array containing a default value and then mapping over that array to replace the default value makes very little sense. Why assign a default value at all if you throw it away right after?

Also it's a very bad idea to make the inner arrays all contain a reference to the same map tile. This just screams for you to introduce hard to find bugs. As a guide line you should never use the 2-argument version of Array.new with a mutable value as its argument. Use the block-version instead.

Also it's customary in ruby to not use explicit return statements in the last line of a method.

Here's how I'd write the array2d method:

def array2D(width,height)
  Array.new(width) do
    Array.new(height) do
      MapTile.new(123,0)
    end
  end
end


Parse webpage and save fetched images to a directory

Few minor issues:

It will be cool if you support URL parameter with protocol (HTTP/HTTPS):

doc = Nokogiri::HTML(open("http://#{url}"))

For URL manipulations you can use standard tools - URI::HTTP/URI:HTTPS instead regexps:

name = img_src.match(/^http:\/\/.*\/(.*)$/)
img_srcs[index] = "http://#{url}/#{img_src}" unless   img_src.match(/http:\/\//)

This is a little unsecure operation, you should escape name:

File.open("#{path}/#{name}", "wb")

You ignore links with HTTPS protocol:

img_src.match(/http:\/\//)

This is not the Ruby way:

img_srcs.each_with_index do |img_src, index|
  img_srcs[index] = "http://#{url}/#{img_src}" unless   img_src.match(/http:\/\//)
end
img_srcs

A little simpler

img_srcs.map do |src|
  src.match(/http:\/\//) ? "http://#{url}/#{src}" : src
end

You load page uneffiсiently:

image = open(img_src)

So for every image temp file created.  This may not be an efficient way.

open("http://stackoverflow.com/questions/1878891/how-to-load-a-web-page-and-search-for-a-word-in-ruby").class
=> Tempfile


First, your indentation is half-indentation. It should be four spaces instead of two. Try putting your code into JSFiddle's TidyUp function to see how to better format.

You can improve the following block by swapping the logic and not initialising last_item:

You also don't need a === check, == will do for integers.

function lastHeadingAtLevel(heading, level) {
  if (level !== 0) {
    // Recurse through lists until you hit the required level.
    var last_item = getLastHeading(heading);
    last_item = lastHeadingAtLevel(last_item, level-1);
    return last_item;
  }
  // No recursion required.
  return heading;
}

by applying those changes, you get the following:

function lastHeadingAtLevel(heading, level) {
    if (level == 0) {
        // No recursion required.
        return heading;
    }
    // Recurse through lists until you hit the required level.
    var last_item = getLastHeading(heading);
    return lastHeadingAtLevel(last_item, level - 1);
}

Instead of string concatenation (can be slow), you should use an array join instead (faster):

var id_name = id + '-' + level + '-' + title.replace(/\s+/g, '-').toLowerCase();

into:

var id_name = [id, level, title.replace(/\s+/g, '-').toLowerCase()].join('-');

In the following block, keys is an array, so instead of a for loop, use a forEach loop:

  for (var i = 0; i < keys.length; i++) {
    if (keys[i].startsWith('#')) {
      continue;
    }
    if (parseInt(keys[i], 10) > last_element) {
      last_element = parseInt(keys[i], 10);
    }
  }

which could transform it into the following:

var lastElement = -1;
Object.keys(heading).forEach(function(key){
    if (key.startsWith('#')) {
        continue;
    }
    if (parseInt(key, 10) > lastElement){
        lastElement = parseInt(key, 10);
    }
});

However, in fact, you don't even need to do that.

Using a polyfill, you can access the last item:

if (!Object.prototype.last){
    Object.prototype.last = function(){
        return this[Object.keys(this)[Object.keys(this).length - 1]];
    };
};

Now just access it like: {'a': 1, 'b': 2, 'c': '3'}.last();


Code with iterators and standard algorithms, and you'll see your coding style improve dramatically:

finding the beginning of a group of Bs can be done with std::find: auto b = std::find(first, last, 'B');
finding the end of a group of Bs can also be done with std::find: auto e = std::find(b, last, 'W');
computing the distance between the two is the job of std::distance: auto nb_bs = std::distance(b, e).

So combining all that we get:

#include <vector>
#include <algorithm>

template <typename Iterator>
auto groups_of_bs(Iterator first, Iterator last) {
    std::vector<int> result;
    while (true) {
        first = std::find(first, last, 'B');
        if (first == last) break;
        auto w = std::find(std::next(first), last, 'W');
        result.push_back(std::distance(first, w));
        if (w == last) break;
        first = std::next(w);
    }
    return result;
}

Now the only thing left is to display the size of the vector, and then its elements:

#include <string>
#include <iostream>

int main() {
    std::string test{"BBWBWB"};
    auto res = groups_of_bs(test.begin(), test.end());
    std::cout << res.size() << '\n';
    for (auto i : res) std::cout << i << ' ';
}


Few things to consider.

Why are you writing your own implementation of something that already exists, long history of reliable use with well defined behaviour (fun/assignment - sure, generally - waste of effort likely to lead to problems)?

What if input, from, or to are null, or not valid (not \0 terminated), OR overlap in any way (will it work)?

from and to, might imply to some people replace from here, to there.  Names are important - look for things that are self-evident.  Perhaps matchToReplace and replaceMatchWith - a bit wordy, but hopefully less ambiguous.

What happens if from is empty - what is the sensible result (document it)?

Don't you need to malloc one more than the desired length (for the terminating \0) [didn't read the algorithm carefully enough sorry].

Make sure you have test cases checking all the above, but also confirming that when you copy 0 length things, or 1 - that everything is copied properly.

Documenting - what tool are you using to publish it?  Certainly doesn't hurt to put a comment before - but remember what people are looking at is the headers - for the declaration, not the implementation (generally at least).


Just a few things in no particular order:

Don't use long as a variable name. It's a reserved word in Javascript and can cause confusion.
If you're going to disable the country input in your form, you should probably just put the US keyword straight in your code. That is if you don't intend on enabling it.
You set ctryiso = $("#ctry").val() and then test ctryiso !== ''. Since you hard coded the country value in, that will always be true. Therefore, unnecessary test.
You don't need to initialize your lastQuery and lastResult to null. Any falsy value will do just fine in JS, including undefined.
If you look at the jQuery source code you'll see that the .click() simply calls another method and passes the values on. You can save a few function calls if you just call that other method directly.

Like so:

$('#search').click(function (e) {
    //Do stuff
}

//Do this one instead
$('#search').on('click', function (e) {
    //Do stuff
}

The 'click' can be replaced with any event of you're choosing. This gives you enormous power and control when setting up custom events.


Accessing files in a child directory in Python 2.7.x

I suggest a generator:

def children_files(dir):
    onlyfiles = (f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f)))
    for f in onlyfiles:
        file_path = os.path.relpath(f)
        yield os.path.join(dir, file_path)

It is simpler to write (no append) and faster as files will be read just as needed.


Finding maximum Collatz sequence between 1-1000000

Your program is non-portable, since an int is only guaranteed to hold numbers up to 32767.  I would change your data type to unsigned long long; otherwise, collatz(159487) will overflow.

Your while condition is clumsy.

while(1)
{
    if(x == 1)
        break;
    …
}

should just be

while (x != 1)
{
    …
}

The key insight is that if you already know, for example, the value of collatz(37), then collatz(74) is just 1 + collatz(74 / 2), and you can reuse the previously computed result.  Therefore, your collatz() function should have access to the results vector — either

pass it in by reference, or
make the vector an instance variable, and the function a method of the class.

It turns out that recursion works quite well for this problem: every chain will terminate in a few hundred steps, so your function call chains will be at most a few hundred frames deep.  Using recursion allows you to cache the result for every number along the chain, which you can't do using iteration.

#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

int collatz(unsigned long long n, std::vector<int> &results) {
    int c;
    if (n == 1) {
        return 1;
    } else if (n < results.size() && results[n]) {
        return results[n];
    } else if (n % 2 == 0) {
        c = 1 + collatz(n / 2, results);
    } else if (n >= (std::numeric_limits<unsigned long long>::max() - 1) / 3) {
        throw std::overflow_error("Overflow");
    } else {
        c = 1 + collatz(3 * n + 1, results);
    }
    if (n < results.size()) {
        results[n] = c;
    }
    return c;
}

int main() {
    const unsigned long long N = 1000000ULL;
    std::vector<int> results(N);
    int max = 0, max_i;
    for (unsigned long long i = 1; i < N; ++i) {
        results[i] = collatz(i, results);
        // std::cout << "collatz(" << i << ") = " << results[i] << std::endl;
        if (max < results[i]) {
            max = results[i];
            max_i = i;
        }
    }
    std::cout << "Max: " << max_i << " with " << max << " steps" << std::endl;
    return 0;
}

By packaging your code into a class, you can let main() not worry about some of the details:

template <typename T>
class Collatz {
  public:
    Collatz(T limit) : limit(limit), results(limit) {}

    int operator[](T n) {
        int c;
        if (n == 1) {
            return 1;
        } else if (n < results.size() && results[n]) {
            return results[n];
        } else if (n % 2 == 0) {
            c = 1 + (*this)[n / 2];
        } else if (n >= (std::numeric_limits<T>::max() - 1) / 3) {
            throw std::overflow_error("Overflow");
        } else {
            c = 1 + (*this)[3 * n + 1];
        }
        if (n < results.size()) {
            results[n] = c;
        }
        return c;
    }

    const T limit;

  private:
    std::vector<int> results;
};

int main() {
    Collatz<unsigned long long> collatz(1000000ULL);
    int max = 0, max_i;
    for (unsigned long long i = 1; i < collatz.limit; ++i) {
        // std::cout << "collatz(" << i << ") = " << collatz[i] << std::endl;
        if (max < collatz[i]) {
            max = collatz[i];
            max_i = i;
        }
    }
    std::cout << "Max: " << max_i << " with " << max << " steps" << std::endl;
    return 0;
}


Unnecessary file operations

This is horribly inefficient:

k = 0
while k <= (num_lines-1):
    name = random.randrange(1, 1000)
    fullName = str(name) + ".jpg"
    with open('links.txt', 'r') as f:
        lines = f.readlines()[k]
        urllib.request.urlretrieve(lines, fullName)
        print(lines+fullName+'\n')
    k += 1

Re-reading the same file num_lines times, to download the k-th!

Btw, do you really need to write the list of urls to a file?
Why not just keep them in a list?
Even if you want the urls in a file,
you could keep them in a list in memory and never read that file, only write.

Code organization

Instead of having all the code in a single function that does multiple things,
it would be better to organize your program into smaller functions,
each with a single responsibility.

Python conventions

Python has a well-defined set of coding conventions in PEP8,
many of which are violated here.
I suggest to read through that document,
and follow as much as possible.


Sensor logger for Raspberry Pi in a stratospheric probe

Do not call main recursively. You are setting yourself up for stack overflow. Consider instead

def main():
    while True:
        try:
            your_logic_here
        except Exception as e:
            your_logging_here

Testing for counter == 4 is better done in a loop:

    for _ in range(4):
        handle_acceleration
    handle_the_rest

An unattended controller should handle exceptions more diligently. For sure, you want to act differently for the exceptions raised by sense (if any) vs exceptions raised by writing to the file.
Regarding battery, avoid binary-to-text conversions. Store your data as binary, and convert them to CSV offline, after the Pi safely returns.


This is a pretty literal translation of the algorithm. Let's first review the code itself and then check how we could reimagine it in python:

I'm not sure why there is a declaration for is_prime or isPrime respectively. It can be inlined, making the code look as follows:

for i in range(2, (number - 1)):
    if (number % i) == 0:
        return False
return True

This uses some minor formatting simplifications, like dropping extraneous parentheses.
The next step is then to actually optimize the program.
In this instance, using xrange over range is preferred, since you don't need to store the whole list of numbers before iterating over it, which is what range does. Note that this only applies for python 2.x, since xrange is not available for python 3.x
Mathematically it's proven, that the first prime divisor of a non-prime number appears before (or athat tip to jwodder) the square root of said number. This can vastly reduce your searchspace:

for i in xrange(2, math.sqrt(number) + 1):

Peilonrayz correctly added in a comment that the full code can be reformulated as a generator-comprehension using all, which is basically the "most python-y" implementation I've seen yet:

all(number % i for i in range(2, int(number ** 0.5) + 1))

Overall the code is stylistically fine. The Docstring could use a bit of love and the algorithm chosen doesn't lend itself well to python's idea of generators (research this concept, it's key to writing idiomatic and fast python).

Finally: Your java code looks messy to me, since it doesn't conform to the standard egyptian bracing style and is very spacious vertically.
In the end this seems to boil down to personal preference of vertical space in code.


Dynamic way to use string/array as index of object in javascript

Yes, it's fairly straightforward to do this without using eval. For example, a statement like obj['a']['b']['c']['d'] = 'value'; can be rewritten as a series of smaller steps:

var temp = obj;
temp = temp['a'];      // member access
temp = temp['b'];      // member access
temp = temp['c'];      // member access
temp['d'] = 'value';   // assignment

Now, it shouldn't be too hard to see how those member access statements can be rolled into a loop, if you have an array of indexes (which you do).

A few other notes:

It's good to see descriptive names, but change_object_using_path_string strikes me as a bit too long and unwieldy. What about something like set_path_value?
You may want to use some more spacing between function parameters (param1,param2 vs param1, param2) and operators (a+b vs a + b). This makes individual parts stand out more, making the code a little easier to read.


JavaScript card game and hand evaluation

Your sorting of cards to buckets takes a lot of code, which is because the names of your buckets don't match with the names of cards. The cards have just numeric values (10, 11), while buckets are named with words (ten_bucket, j_bucket). I would represent the cards as such:

{kind: 3, suit: "club"},
{kind: 10, suit: "heart"},
{kind: "K", suit: "spade"},
{wild: true},

And then I could write a much simpler algorithm for putting them to buckets:

var wilds = [];
var kinds = {3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], J:[], Q:[], K:[]};

hand.forEach(function(card) {
    if (card.wild) {
        wilds.push(card);
    } else {
        kinds[card.kind].push(card);
    }
});

I'm also handling the wild cards as a completely separate category, which makes it much easier to check if we have three-of-a-kind:

for (var k in kinds){
    if (kinds.hasOwnProperty(k)){
        if (kinds[k].length + wilds.length >= 3) {
            // Yes, we have a three-of-a-kind
        }
    }
}

Checking for runs

A basic check for runs is quite simple. You just loop through all the buckets in order and check for the longest sequence without holes:

function longest_run() {
    var count = 0;
    var max_run = 0;
    ["3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"].forEach(function(k) {
        if (kinds[k].length >= 1) {
            count += 1;
        } else {
            if (count > max_run) {
                max_run = count;
            }
            count = 0;
        }
    });
    return max_run;
}

But taking the wild cards into account complicates the whole thing considerably. Now it really becomes a question of combinatorics. A brute-force approach would be to try using the wildcards in each of the empty positions. This can be optimized of course, but I suggest you turn to StackOverflow with this question - some math-minded people might be able to provide you with a better algorithm over there.


Testing distance between characters in a string

I would recommend using a regular expression.  Regex is designed for solving pattern matching and string manipulation problems. Although it can look esoteric and terse it is well worth the effort to learn since it is very powerful and fairly ubiquitous.  It is very likely your programming language/shell/editor of choice supports a flavor of regex.

var str = prompt("Please enter a string: ");

function test(str){
  return /a\w{3}b/.test(str) || /b\w{3}a/.test(str);
}

console.log(test(str));


Making an atomic transaction out of several operations

You can remove repeated code if you record all your actions for executions and then execute them all at once with some generic exception handling. The idea is below.

Sorry for some possible lapses, didn't write in C# for quite some time. However I hope that you'll find the whole idea to be helpful.

  EnumResult TransactionThatRollsBack()
    {
         var undoLog = new SmartStack();
         undoLog.Push(() => MoveInventory(inv,dest,src), EnumResult.1);
         undoLog.Push(() => NotifyReportingOfUnMove(inv, user), EnumResult.2);
         undoLog.Push(() => RemoevUserFromSweepstakes(user), EnumResult.3);

         undoLog.execute();
    }

    class SmartStack {
       SortedDictionary<Action, EnumResult> actions;

       void push(Action a, EnumResult r) {
         actions.add(a, r);
       }

       void execute() {
         Stack<Action> completedActions = new Stack<Action>();
         foreach(KeyValuePair<Action, EnumResult> pair in actions) {
             try {
               pair.Key.Invoke();
               completedActions.push(pair.Key);
             }
             catch(Exception ex) {
               for (Action a in completedActions) {
                   Undo(a);
               }
               return pair.Value;
             }
         }
       }
    }