Writing multiple if tags that compare two variables

Indentation?
At first I thought it was a mere copy/paste error, but the pattern is throughout the code you submitted, so I have to mention it: it's not the braces you indent, it's what the braces encompass!

    static void Main(string[] args)
        {
        int previousNumber = 0;
        AskNumber(previousNumber);
        }

Should be:
    static void Main(string[] args)
    {
        int previousNumber = 0;
        AskNumber(previousNumber);
    }

Curly braces define a scope. In C#, convention is to place the scope-opening brace on the next line, so this:

void CompareNumber() {

Should be:
void CompareNumber()
{

Speaking of braces:

Is there a more concise way of doing this, making it look neater? (Except for omitting the curly brackets)

Omitting the curly braces does not make code look neater. Proof being this very confusing snippet:

        if (wantToPlay == "y")
            AskNumber(0);
        else
            Environment.Exit(0);
        }

I had to scan the entire method twice to figure out that the last } was in fact closing the scope of the method.
By opposition:
        if (wantToPlay == "y")
        {
            AskNumber(0);
        }
        else
        {
            Environment.Exit(0);
        }
    }

Is brutally in-your-face crystal-clear. Notice the position of the last brace, which closes the method scope. The readability problem stems from the extraneous indentation of scope-delimiting braces - this doesn't suffer the exact same issue:
        if (wantToPlay == "y")
            AskNumber(0);
        else
            Environment.Exit(0);
    }

You should always delimit scopes with braces. if/else statements denote a scope - that scope wants its braces.
Same with loop constructs:

        while (previousNumber == randomNumber)
            randomNumber = new Random().Next(1, 11);

Should be:
        while (previousNumber == randomNumber)
        {
            randomNumber = new Random().Next(1, 11);
        }

The Good
You use descriptive naming. This is often understated - descriptive names are your best friend. They reduce bug-proneness of your code all by themselves, and make code easier and more enjoyable to read. Since programming is 80% reading and 20% writing, enjoyable reading means enjoyable programming.
Good job!

The Bad
The syntax for an if condition goes if ([bool-expression]), where [bool-expression] is any expression that evaluates to true or false. Can you spot the redundancy here?

if (int.TryParse(Console.ReadLine(), out numberTyped) == true)

That's right. TryParse returns a bool that's a perfectly valid [bool-expression] - in fact, anytime you're comparing a Boolean value (or expression) to a Boolean constant for the sake of getting a Boolean expression, you are needlessly repeating yourself... redundantly.
Just do this instead:
if (int.TryParse(Console.ReadLine(), out numberTyped))

Method names should start with a verb. Always. void InvalidNumber() is a bad name, because it doesn't say anything about what it actually does - it doesn't return a number, and doesn't intake one either. Without looking at how it's implemented, it's pretty confusing.

Console applications exit when the Main method executes to its closing brace. I have never used Environment.Exit(0) in any application I've written - in fact, this call is like a "red button", a forceful, ugly way to kill your application (and throw the body in a container in the back alley) rather than letting it gracefully exit through the front door.
You're going to have to restructure things up in order to make that happen though.

CheckNumber shouldn't have the 0 and 10 hard-coded like this; there should be constants defined for the lower and upper bounds, and the AskNumber method should be using them as well - that way if you ever need to change the 10 to a 100, there's only 1 place you'll need to change it.
AskNumber shouldn't be creating a new Random() every time. There should be one single instance of Random that the program uses whenever it needs a random number.
There's a lot more to say about this code, I'll let other reviewers chip in ;)


Style

Read the PEP8 style guide!

Functions and variables should be snake_case
Conditions should be on the next line if a: ... is bad style
Conditions don't need parenthesis while (a) is the same as while a:
Avoid temp variables

Algorithm

Your first 2 guard clauses seem very unnecessary

When I remove them, the code still works.
Consider writing docstring/tests or both with the doctest module

Alternative Code

You could use re.findall(substring, string) for counting the occurrence,

OR string.count(substring) making this practically a one-line

import doctest

def beautiful_binary_string(b):
    """
    Returns the steps to make a binary string beautiful

    >>> beautiful_binary_string("0101010")
    2

    >>> beautiful_binary_string("01100")
    0

    >>> beautiful_binary_string("0100101010100010110100100110110100011100111110101001011001110111110000101011011111011001111100011101")
    10
    """
    return b.count("010")

if __name__ == '__main__':
    doctest.testmod()


Duplicated Ids!!!

I notice in the comments there is mention of more than 1 element with the same Id and that getElementById will only return one element, which is correct for the majority of browsers depending on the version.

Even if getElementById acted the same across browsers As a developer intentionally using duplicated Id is VERY BAD! as it will force the browser into Quirks Mode
 effecting performance, layout and can effect how search engine bots crawl your site.

Though Google does say...

  “Although we do recommend using valid HTML, it’s not likely to be a factor in how Google crawls and indexes your site.”

... from SEJ 6 Reasons Why Google Says Valid HTML Matters that links to Google Browser Compatibility support page

This is not a guarantee and not something you should trust your sites SEO on.

The simple and safe rule is. NEVER duplicate Id's!!!

Your code

Ignoring the above and looking at your code without regard to the DOM and that getElementById can return an array you can improve the code (readability and maintainability [1.]) as follows

function queryDOM(selector) {
    const VALIDATOR = /[a-z0-9!@#$%^&*)(+=._-]/i, NS = "http://www.w3.org/1999/xhtml";
    const type = selector[0], query = selector.slice(1);
    if (type === ".") { return [...document.getElementsByClassName(query)] }
    if (type === "#") { return [document.getElementById(query)] }
    if (! VALIDATOR.test(selector)) { throw new RangeError('Invalid Selector') }
    return [...document.getElementsByTagNameNS(NS, selector)];
}

or for the code newbies that need the spacing

function queryDOM(selector) {
    const VALIDATOR = /[a-z0-9!@#$%^&*)(+=._-]/i;
    const NS = "http://www.w3.org/1999/xhtml";
    const type = selector[0];
    const query = selector.slice(1);

    if (type === ".") {
        return [...document.getElementsByClassName(query)];
    }

    if (type === "#") {
        return [document.getElementById(query)];
    }

    if (! VALIDATOR.test(selector)) {
        throw new RangeError("Invalid Selector");
    }

    return [...document.getElementsByTagNameNS(NS, selector)];
}

Reasoning

As a function declaration rather than a function expression so that the function is accessible at any time after parsing.
Extract the first character and remaining query in one spot to avoid logic/code duplication.
Remove the redundant else and supporting code to reduce noise.
Use ES6+ spread operator ... (AKA spread syntax) to create arrays from iteratable objects.
Use the simpler bracket access for single character in string rather than the more verbose String.startsWith which is meant for sub strings longer than one character.
Use String.slice rather than String.substring
Renamed function to hold to camel-case convention of upperCase acronyms and rearranging to stop clash with JS convention of PascalCase only functions used with the new token (Note your function will work as new DOMSelector())
Renamed argument to not imply its an array (plurals only for arrays or array like objects)
Throw a range error more suited to the error type (Really should not be throwing for this type of issue)
Remove the global flag from the RegExp
Removed redundant ^, $, + and back slashes inside the [] from RegExp
Added case insensitive flag to RegExp
Declared RegExp as a constant to take out of the statement to make it more readable.
As you include capitals in the validation of the selector I assume you are unaware that getElementsByTagName first converts the query string to lowercase. Thus I changed the function to use getElementsByTagNameNS

The getElementsByTagNameNS which namespace (NS) to use is not known from your code and thus the example assumes "http://www.w3.org/1999/xhtml". Warning quirks mode will effect the namespace.

Additionally

The function has a failure if the selector argument is not a string. As the function does throw I assume you only use it inside a try catch block and you handle the error when it occurs.

Why the complications!

As your code relies on some assumptions that are flawed and do not compile with valid HTML I can not approve the above as worthy of anything but as an example of what not to do.

The code should use querySelectorAll and covert its iteratable return to an array. I would also drop the "DOM" in the name (what else could you be querying?) and include a node to focus the query.

Also removing the validation as query string can be used to search attributes that may conflict with the validation.

function query(str, node = document) { return [...node.querySelectorAll(str)] }

Or if you control code placement and use the "use strict" directive you can use an arrow function expression to assign a named constant to prevent accidental overwriting of the function.

"use strict"; // << Must be at top of code.
const query = (str, node = document) => [...node.querySelectorAll(str)];

This is not at all replacement of jQuery

BTW

A reminder. NEVER duplicate Id's!!!

See I added 3 exclamation points and made it bold to indicate how important this warning is.

Notes

[1.] Readability and maintainability are highly subjective quantities and as such reflex my view only. I have 40Years of experience (35 as a professional) if that counts for anything.


Joining url path components intelligently

I'd suggest the following improvements (in descending order of importance):

Extract your redundant generator expression to a function so it only occurs once. To preserve flexibility, introduce default as an optional parameter
This makes the comment redundant because first is a self-documenting name (you could call it first_or_default if you want to be more explicit), so you can remove that
Rephrase your docstring to make it more readable: normalize  and with a slash don't make sense together
PEP 8 suggests not to align variable assignments, so does Clean Code by Robert C. Martin. However, it's more important to be consistent within your project.

def url_path_join(*parts):
    """Normalize url parts and join them with a slash."""
    schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))
    scheme = first(schemes)
    netloc = first(netlocs)
    path = '/'.join(x.strip('/') for x in paths if x)
    query = first(queries)
    fragment = first(fragments)
    return urlunsplit((scheme, netloc, path, query, fragment))

def first(sequence, default=''):
    return next((x for x in sequence if x), default)

If you're looking for something a bit more radical in nature, why not let first handle several sequences at once? (Note that unfortunately, you cannot combine default parameters with sequence-unpacking in Python 2.7, which has been fixed in Python 3.)

def url_path_join(*parts):
    """Normalize url parts and join them with a slash."""
    schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))
    scheme, netloc, query, fragment = first_of_each(schemes, netlocs, queries, fragments)
    path = '/'.join(x.strip('/') for x in paths if x)
    return urlunsplit((scheme, netloc, path, query, fragment))

def first_of_each(*sequences):
    return (next((x for x in sequence if x), '') for sequence in sequences)


The average amount of time required to travel between two points in a torus-like space

Don't write using namespace std;.
The constants including pi are provided in a standard header already.  If you did need to define a constant,  use constexpr.
double deltaa;
if (k == 0) {
        deltaa = 1;
      } else {
        deltaa = 0.5;
      }

That is much clear to write as:
const double deltaa = k==0 ? 1 : 0.5;

which also allows you to initialize the value in the declaration and make it const.
The block for deltaa and deltab are the same except for the parameter.  You should make a small inline function for that.
total = total + 0;

Why?
total = total + res;

Better to write total += res;

Generally:
Use const where you can.  Initialize variables in the statement where you declare them.
In addition to using const, which may allow the optimizer to better figure such things out on its own, consider hoisting subexpressions out of the loop.  For example pi * k does not change inside the nested loop so compute it once in the outer loop only.
Express your comments as preconditions (e.g. assert or Expect statements).

for (double i = 0; i < size; i++) {
    series_res[i] = sumSij(half_a, half_b, xvec[i], yvec[i], a, b, coeff);
  }

Why is i of type double?  It's an index into the NumericArrays.
I see a call to sumSij but no call to sumAll.  The code is not complete, and doesn't agree with your comment (unless the former calls the latter, but I don't know how).


You should separate these magic numbers into a new data structure. Then have some code run over it. This will be much nicer to read.

For example:

function getAward($year, $commends) {
    $commendationsNeeded = [
        7 => [
            "Bronze" => 300,
            "Silver" => 600,
            "Gold" => 900,
            "Platinum" => 1200,
            "Diamond" => 1500
        ],
        8 => [
            "Bronze" => 250,
            "Silver" => 550,
            "Gold" => 850,
            "Platinum" => 1100,
            "Diamond" => 1300
        ]
    ];
    $maxScore = 0;
    $maxAward = "None";
    foreach ($commendationsNeeded[$year] as $award => $needed) {
        if ($needed <= $commends && $maxScore < $needed) {
            $maxScore = $needed;
            $maxAward = $award;
        }
    }
    return $maxAward;
}

echo getAward(7, 700); // Prints "Silver"


String tokenizing with arbitrary token count in C

I see some things that I think could help you improve your code.

Use the required #includes

The code uses malloc which means that it should #include <stdlib.h>.  It also uses strtok which is in string.h.

Don't leak memory

This code calls malloc several places but doesn't match each one with a call to free.  This means that the routines are leaking memory. Specifically, just before the call to free(tokens); in main, you need to also free the individually allocated memory:

for (size_t j = 0; j < tokens_wanted; ++j) {
   free(tokens[j]);
}

Use const where practical

The comment about making a copy of line to prevent it from being changed suggests that it should be declared const in the parameter list:

int get_tokens(const char *line, char **tokens, size_t number_of_tokens) {

Also, the delimiter string should also be const and probably also static.

Consider a different interface

In the current code the return value of get_tokens isn't used.  It also prints and exits the program in some circumstances.  Instead, I'd advice changing the interface in a couple of ways.  First, I'd recommend that the caller make a copy of the string if necessary.  This makes the code cleaner and simpler and allows the caller to perhaps do something other than simply abruptly halting the program if an empty string is found.  Second, I'd suggest that because strtok operates by modifying the passed string, there really isn't a need to allocate more memory and copy.  Instead, I'd recommend that the pointers returned can simply point to the passed string.  The much-simplified version might look like this:

void get_tokens(char *line, char **tokens, size_t number_of_tokens) {
    static const char *delimiter = " ";
    for (size_t i = 0; i < number_of_tokens; ++i) {
        tokens[i] = strtok(line, delimiter);
        line = NULL;
    }
}

This works nicely and is much simpler.  If fewer than the requested number of tokens is found, the remaining tokens pointers are set to NULL. The calling function might look like this:

int main() {
    const size_t line_length = 100;
    char line[line_length];
    get_line(line, line_length);

    size_t tokens_wanted = 2;
    char **tokens = malloc(tokens_wanted * sizeof(char**));
    if (tokens == NULL) {
        perror("out of memory!");
        return 1;
    }
    get_tokens(line, tokens, tokens_wanted);
    for (size_t i=0; i < tokens_wanted; ++i) {
        printf("token[%lu] = \"%s\"\n", i, tokens[i]);
    }
    free(tokens);
}

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


So much to say, in so little space. This could be answered in so many ways, mainly due to why you need to model the cards. Without a proper context, the requirements will change and can thusly change the entire model. So lets pretend you're aiming to build one (or several) card game(s).

Separation of Concerns

There are many important OOP principles, but I'm mainly going to address the Separation of Concerns (or Concern related to Computer Science, as it often is what you need to consider first: Why do you have the classes/objects, and what is their intended purpose?

Somewhat simplified one could say that: An object/class shouldn't need to concern itself with stuff outside of itself. This could allow for the internal of any class to be replaced, as long as the public API (the public methods to call it) aren't changed. I'm going to try to exemplify this related to the various classes you've provided.

Card

In other words, a Card shouldn't need to concern itself who might use it, and how they might use it. And the basic method of handling a card should remain somewhat constant.

More specific, it seems kind of strange that a Card is able to change its value or suit. What kind of a gaming card is able to do that? If it is the King of Diamonds, then it usually stays that way for ever.

To me, it would be more natural for the cards to have a method defining how the output could look like. For example to choose alternative textual variations: "value: 13, suit: Spade", "King of Spade", "K♠" or even "". The last two examples from: Wikipedia's Playing Cards in Unicode.

Possibly the parent Card class should be rather empty, and allow for subclasses to specify the criteria of that card. Like ordinary playing cards, or a Uno deck, or Pokemon deck, and so on.

Deck

The Deck consists of Cards, but other than basic handling of cards, it shouldn't know too much about the cards. And it shouldn't really know anything about a Player or a Game using the Deck.

And this answers your question on dealCard(). It shouldn't know anything about the player, and basically it should only remove a Card from the deck, and return it to whomever who might use it as they please.

Other interesting functions for the Deck could be re-insert a card into the deck, possibly verifying that the card is legal in this kind of deck. Imaging solitaire games like Spider (using only the suite of Spade), or games using double decks.

Player, or maybe Hand?

I'm not sure what I would put in a Player class, but in the context of a card game, I think I would rather have a Hand class to describe my current set of cards.

In this context, it would be natural to add/remove cards to the hand. And to display it in various alternatives. It could possibly have some generic methods for describing the order of a hand compared to another hand.

For subclassing one could also imagine that the hand could calculate the overall value of the hand, for example the Poker value, or whether it contained sets or series, I could imagine have methods for calculating the value of my hand, for example the Poker Hand value, or whether I had any series or sets. And the subclasses could specify which hands were the most valuable related to each other.

Code review

In general your code looks nice, with proper indentation and brace usage. I would prefer a little more consistency in commenting the methods/classes at a given place related to the definition. You could/should consider using Javadoc, or a given documentation standard for describing your classes.
A shuffle() method which only shuffles 20 cards, by swapping 2 each time, seems like a really lousy way to shuffle a deck. I'm sure you can do better than this. Maybe loop through the deck once, and switch the card placement to somewhere else in the deck?
Better presentation alternatives would be nice, I think. See comment on Card class above.
A minor detail on the SUIT enum. I would order it as SPADE, HEART, DIAMOND and CLUB, as that is the common ordering of value of cards in a lot of card games. Not entirely thrilled about the Uppercasing, but not sure what's the common method in Java to denote globals like these.

PS! I've used Wikipedia for reference, there does exist better description, but for consistency I chose to use these here.

PPS! Another interesting principle are the SOLID principle, but it might be difficult to wrap your head around if you're very new to programming.


Function to return the sum of multiples within a range

Simpler implementation

You don't need naturals at all, and offset either.
You could make the outer loop iterate over the range(start, end),
and for each value check if it can be divided by any one of nums,
and add to the sum.

msum = 0
for i in range(start, end):
    for num in nums:
        if i % num == 0:
            msum += i
            break
return msum

API

The interface of your function is not intuitive:

The range start parameter goes after the range end parameter. That's not intuitive. Consider how Python's range works:

With one arg, the first arg is the end of the range
With two args, the first arg is the start, the second is the end of the range. It's natural that way

I suggest to follow that example
The first arg is called "multiple", singular. It's not a multiple. It's a collection of numbers. So nums would be a better name, and it would make it easier for readers to understand how to use this function

Input validation

In this part:

if start == 0:
  raise ZeroDivisionError('Cannot start with the number 0')

The zero division error is inappropriate. You did not divide by zero,
and it won't make sense for callers to catch this exception and handle it.
In other languages this should be an IllegalArgumentException, in Python ValueError would be more appropriate.
The real problem is not division by zero, but inappropriate use of the function.

But then, why is start=0 inappropriate? I see nothing wrong with that.
What would be wrong is having 0 in nums.
That's what you should validate instead.

Coding style

The recommended practice is to use snake_case for function names, not CamelCase. See more coding style recommendations in PEP8.


Take a number and sum its digits raised to the consecutive powers

Recommendations:

For starters I would recommend passing an Int to your function and then converting it to a String before splitting it up and mapping it to its digit components.
Next, Scala has a useful built in function called zipWithIndex that you could use over (myDigits.indices zip myDigits). Granted it will reverse the ordering from what you have, but that can be handled as you can see in the code below.
I would also recommend splitting any map / filter / etc over multiple lines to increase readability.
When you are using reduce to sum the elements of a container you can instead apply the built in sum method.
Finally, I would hold off on converting the (1 to 100) from a Range to a List until after your filter operation is complete.

Code:

def f(i: Int): Int ={
  val myDigits = i.toString.map(_.asDigit)

  myDigits.zipWithIndex.map { case (y, x) =>
    pow(y, x+1).toInt
  }.sum
}

val x = (1 to 100).filter(i => i == f(i)).toList


Expressing current time with natural language

Python supports double-ended inequalities:

End_str = ['at night', 'in the morning','in the afternoon','in the evening']

if 0 <= hour < 6:
    Ending = End_str[0]
elif 6 <= hour < 13:
    Ending = End_str[1]
elif 13 <= hour < 19:
    Ending = End_str[2]
elif 19 <= hour < 24:
    Ending = End_str[3]

I've changed 23 to 24 for consistency and rearranged the members of End_str.  I don't see how hour should be anything other than an integer, so I've removed the casts.

if minute == 0 or minute == 00 is redundant, since 00 is exactly the same as 0.

I would expect noon and midnight to be handled as special cases.


Using a compiler specified on the command line or automatically detected

Pattern match instead of using isJust and fromJust. (You could use maybe instead of pattern matching, but I think pattern matching is clearer in this case.)

This eliminates the possibility of forgetting to ensure a value is a Just before calling fromJust on it.

guessMetapost :: Options -> IO ()
guessMetapost opts
   = case optMetaPost opts of
         Just mcc -> putStrLn $ printf "using enforced Metapost compiler: %s" mcc
         Nothing -> do
           cc' <- compiler Metapost.interface
           case cc' of
               Just cc -> putStrLn $ printf "found Metapost compiler: %s" cc
               Nothing -> putStrLn "found Metapost compiler: none"

(Your code wasn't consistently returning any options, so I've stripped that bit out.)


Few notes :

// Return the default value for the type.
if (property.PropertyType.IsValueType)
{
    return Activator.CreateInstance(property.PropertyType);
}
return null;

You can use ternary operator here

// Return the default value for the type.
return property.PropertyType.IsValueType
    ? Activator.CreateInstance(property.PropertyType)
    : null;

Those })() at the end of your functors are a little bit confusing in my opinion it will be a clearer if you call .Invoke() explicitly }).Invoke()

var validations = property.GetCustomAttributes(
typeof(ValidationAttribute))?.Cast<ValidationAttribute>()
?? Enumerable.Empty<ValidationAttribute>();

You should be able to specify the type argument explicitly to avoid the .Cast<T>

var customValidationAttributes = property.GetCustomAttributes<ValidationAttribute>();
var validations = customValidationAttributes ?? Enumerable.Empty<ValidationAttribute>();


jQuery templating with ES6/ES2015 template strings

I was reading through your code and I got to

  if(value) {
    if(value instanceof Node || value instanceof jQuery || allNodes) {
      nodeIndexes.push(i);
      html += tempFiller(i);
    } else if(value) {
      html += value;// || '';
    }
  }

and I had to read over it a few times, but I think that you can do away with the outside if statement or at least not check value a second time.

either one of these look like they are going to do about the same thing

if (value instanceof Node || value instanceof jQuery || allNodes) {
    nodeIndexes.push(i);
    html += tempFiller(i);
} else if (value) {
    html += value;
}

this would go through both checks, much the same way that the original code did, except you don't check the existence of value first, this might cause some errors, so I would probably do this instead

if (value) {
    if (value instanceof Node || value instanceof jQuery || allNodes) {
      nodeIndexes.push(i);
      html += tempFiller(i);
    } else {
      html += value;
    }
}

turned the else if into an else, because we already know that value is going to pass a truthy test, no need to check it a second time.


Boiler.js Deep Object Comparison Code/Performance Optimizations?

After going through the code and the library itself, here are some thoughts:

Functions are still objects. You can even attach properties to it. You might want to look into this unless you only want to compare the function, excluding the things attached to it.

function foo(){};
foo.bar = 'baz';
console.log(foo.bar); //baz

Early on, you can weed out values that are equal or actually the same to avoid going through everything. Equal strings, numbers, booleans and even objects in general (Since they are compared by identity) return true.

obj1 === obj2

If this returns false, it could be that the values are non-equal primitives, or non-identical objects. You can return false for the primitives. For objects in general, only then will you do the "structure equality check".
Comparisons return a boolean value. So if you return a boolean after a comparison without doing anything else after, you can shorten the statement.

/*from*/ if(a !== b) return false;
/* to */ return a === b;

While for(var o in obj1) is perfectly valid JS, it's something you'd look out for. You actually did this twice in the code. If you pass your code through a linter, you'd get a o already defined error. Do this instead

var o;

for(o in obj1){...}
...
for(o in obj2){...}

Or better, just use another variable name instead of o on the second loop.
You seem to already have a lot of abstractions in your library, which is good. However, your code seems to use a mix of abstracted and vanilla code. I suggest using your abstracted code so that in case the approach for a certain operation is wrong, you only need to modify the abstracted version.

jQuery actually does this. It keeps a "Core API" which is used by the other parts of the source. If you look at their source, each and extend are used quite a lot.
null and undefined are already falsy values. Assuming you already weeded out other values for obj1, you could already simplify.

if(typeof obj1 === "undefined") return false;
if(obj1 === null || obj1 === undefined) return false;

//to

if(!obj1) return false;
//or
if(_.isFalsy(obj1)) return false;


Though I've got a lot to say, it's mostly just me pulling out stuff from my Python toybox, which let you write what you want, rather than how to get it. In general, this is a really clean module and there's nothing utterly heinous going on in there.

def __init__(self, capacity):
    self.chambers = {}

    print 'Locker Initialized.'
    for n, chamber in enumerate(range(0, capacity)):
        self.chambers[n] = Chamber(n)
    print 'Locker Created: ', self

For starters, you don't need to use a dict for this, a list will do just fine. You're giving yourself a constant number of chambers, nothing new ever enters, and nothing ever gets deleted. You may have done this because you've got a C or Java background, know about linked lists, and are a bit worried about access times. In Python, a "list" is actually an array under the hood, so you actually gain by using one.

The range function by default goes from 0 to n-1, so adding a 0 parameter is needless here.

Enumerate will zip together an enumerable with incrementing integers. Range returns a list of incrementing integers, so calling enumerate(range(0,n)) gives you back [(0,0), (1,1), (2,2), ..., (n-1,n-1)] (effectively, it's a little subtler than that). I can't really think of a use case for this, and you don't actually use the second part of each tuple anyway, so you can strip that out.

Finally, comprehensions are a really useful way of generating lists more cleanly. Rather than having a loop that keeps appending things, describing how a result is achieved, you instead write an expression that states what the result is, which makes your intention a little clearer. I'd replace your __init__ with

def __init__(self, capacity):
    print 'Locker Initialized.'
    self.chambers = [Chamber(n) for n in range(capacity)]
    print 'Locker Created: ', self

def find_chamber_by_pin(self, pin):
    for chamber in self.chambers.values():
        if pin == getattr(chamber.user, 'pin', None):
            return chamber
    return None

getattr is awesome, but when you use it with a constant string you don't gain a great deal. You know that chamber.user will always be either an instance of User or None, and in Python None is falsey, so you can replace your condition with if chamber.user and pin == chamber.user.pin:

I'd go a little further than this, though. Your loop is over the list of occupied chambers, so let's call it that...

def occupied_chambers(self):
    return (chamber for chamber in self.chambers if self.chamber.occupied)

def find_chamber_by_pin(self, pin):
    for chamber in self.occupied_chambers():
        if chamber.user.pin == pin:
            return chamber
    return None

If you wanted to crush your number of lines down, you could also exploit next, but the resulting function starts to look a little chaotic. It's there if you like it:

def find_chamber_by_pin(self, pin):
    return next((chamber for chamber in self.occupied_chambers()
                     if chamber.user.pin == pin), None)

def find_available_chamber(self):
    for chamber in self.chambers.values():
        if chamber.occupied is False:
            return chamber
    return None

def count_available(self):
    counter = 0
    for chamber in self.chambers.values():
        if chamber.occupied is False:
            counter += 1
    return counter

There aren't all that many situations where you gain from comparing stuff to True and False. Rather than chamber.occupied is False, not chamber.occupied is preferred (but see later on).

These functions both iterate over the same thing, so abstract it out:

def available_chambers(self):
    return [chamber for chamber in self.chambers if not chamber.occupied]

def find_available_chamber(self):
    try:
        return self.available_chambers()[0]
    except IndexError:
        return None

def count_available(self):
    return len(self.available_chambers())

class Chamber(object):
    def __init__(self, uid):
        self.uid = uid
        self.occupied = False
        self.user = None
        print 'Chamber Initialized: ', self

    def reserve(self, user):
        self.occupied = True
        self.user = user
        print 'Chamber Reserved: ', self

    def release(self):
        self.occupied = False
        user = self.user
        del user
        self.user = None
        print 'Chamber Released: ', self

First off, your release method deletes its user. This doesn't actually achieve anything. You can just set the user to None and the garbage collector will sort it out for you when it notices your object no longer references it.

Second, it seems like you want to keep an invariant that occupied is True if user is set and occupied is false if user is unset. For something like this, I'd use the property decorator which, among other things, lets you create properties that only exist based on other properties of your object. Half the time though we're not interested in whether or not the chamber is occupied, we want to know that it's available, so let's add that in, too

@property
def occupied(self):
    return bool(self.user)

@property
def available(self):
    return not self.occupied

Now we don't need to keep updating that occupied property any more! You can also go back and change your Locker.available_chambers() method to use this new property.

Putting it all together, I refactored your code into:

class Locker(object):

    def __init__(self, capacity):
        print 'Locker Initialized.'
        self.chambers = [Chamber(n) for n in range(capacity)]
        print 'Locker Created: ', self

    @property
    def occupied_chambers(self):
        return [chamber for chamber in self.chambers if chamber.occupied]

    @property
    def available_chambers(self):
        return [chamber for chamber in self.chambers if chamber.available]

    def find_chamber_by_pin(self, pin):
        return next((chamber for chamber in self.occupied_chambers
                     if chamber.user.pin == pin), None)

    def find_available_chamber(self):
        try:
            return self.available_chambers[0]
        except IndexError:
            return None

    def count_available(self):
        return len(self.available_chambers)

    def __len__(self):
        return len(self.chambers)

    def __repr__(self):
        return '<LOCKER: {} of {} Available>:'.format(self.count_available(), len(self))

class Chamber(object):
    def __init__(self, uid):
        self.uid = uid
        self.user = None
        print 'Chamber Initialized: ', self

    @property
    def occupied(self):
        return bool(self.user)

    @property
    def available(self):
        return not self.occupied

    def reserve(self, user):
        self.user = user
        print 'Chamber Reserved: ', self

    def release(self):
        self.user = None
        print 'Chamber Released: ', self

    def __repr__(self):
        return '<CHAMBER {}:{}>:{}'.format(self.uid, self.occupied,
                                             self.user)

class User(object):
    def __init__(self, pin):
        self.pin = pin
        print 'User Created: ', self
    def __repr__(self):
        return '<USER PIN: {}>'.format(self.pin)

locker = Locker(4)

while True:

    pin = raw_input('Locker Idle. Enter Unique PIN:')

    chamber = locker.find_chamber_by_pin(pin)

    if chamber:
        chamber.release()

    else:
        chamber = locker.find_available_chamber()
        if chamber:
            user = User(pin)
            chamber.reserve(user)
        else:
            print 'Chambers Full. Wait for relase.'

    print 'New Status: ', locker

You asked about the advantages of using @property, and when it's appropriate to use it. I've not been able to dig out any "official" style guides on it, so what you're about to read is basically just my opinion. I should also point out that I'm a Ruby developer, too, so a lot of its idioms tend to bleed into my Python. Most notably, in Ruby you don't generally care whether you're fetching a property or calling a 0-parameter method.

Functionally, there's not really much difference between a @property-decorated function and a regular one that just takes no arguments. The difference is in the "feel" of your interface to anyone using it. If you're asking an object about its state, then you probably want a @property decorator. If you're asking it to do something, then you want a method. Getting a property should be fairly quick, and should (almost) never change the state of the object.

Also notable is that Python is not Java, so methods like def get_foo(self): return self._foo are never appropriate. If a caller might want to do something with foo, then instead consider writing a method that does it for them. Don't expect client code to repeatedly call getters and setters to mutate your object.


First you can change those non-required letters to a specific character like '.'.

Turning the 2D array into a string or array of byte. For example:

1234
5678
90ab
cdef
=>
string1: 1234
string2: 5678
string3: 90ab
string4: cdef

Remove '.' in these string so that later u can check faster.

Also doing this with other rows, column, and oblique.

Scan result in -> or <- direction only.

Related algorithm you may find here.

Moreover, you can omit some impossible cases such as:

input:

8 aaaa
aaaaoooo
oooooooo
oooooooo
oooooooo
oooooooo
oooooooo
oooooooo
oooooooo

Find those which never touch required characters like the last three rows in this case and  do not trag() with it.

I suggest using this algorithm to scan it:

For rows:

var
    ignore: array[1..1000, 1..1000] of boolean;
    counter: integer;
counter:=0;
for i:=1 to n do
    while j<=n do
    begin
        ignore[i, j]:=false;
        if kar[i, j] = '.' then
        begin
             count:=count+1;
             ignore[i, j]:=counter> length(s);
             break;
        end
        else
            counter:=0;
    end;


Initialize an object with a key at runtime

ECMAScript 2015 adds a new feature called computed property names.
It allows you to create a property in object literal without specifying the name for the key -- it lets you use a value of a variable.

const keyName = 'foo'
const object = { [keyName]: 21 } // { foo: 21 }

You can read about a bunch of similar things on 2ality.

In your example, that would be:

function make_obj (key, func, val) {
  return { [key]: func(val) };
}


isset() accepts multiple parameters, you can simplify:

if (isset($parameters["inserted_id"]) && isset($parameters["inserted_password"])) {

To

if (isset($parameters["inserted_id"], $parameters["inserted_password"])) {

When ever I read anyone's code or database schema and I see any mention of id, I immediately assume that I am dealing with a positive integer.  If the value is anything other than a positive integer, I never use id in the field/column/variable name.
I never use mysqli's init() call because it is optional.  I'll recommend objected-oriented mysqli syntax because it is less verbose.
I don't think I'd json encode/decode your form data -- it seems like unnecessary extra data handling.  See here: jQuery Ajax POST example with PHP
echo doesn't need those parentheses.
I am confident that @YourCommonSense will post a comprehensive answer containing the 3 pieces of commented advice and more, so I'll leave those recommendations to him.
You don't need to write out all those close() calls, just echo your message and let the script end naturally.  If you're going to kill the script at if (isset($_SESSION['user_id'])) { be sure to sure to echo something for consistency.
I find javascript alert() boxes to be terribly annoying and a bit trashy to be honest.  Give your site some "class" and fashion an attractive presentation for any response messages that you plan to offer.
Your .html has form fields, but no form -- that doesn't feel valid to me.  I'll recommend adding the form tags and names attributes.  Some discussions: https://stackoverflow.com/q/33370025/2943403


Comparing version numbers with JavaScript

A small review;

Once you know that one version digit is larger than the other, you can exit immediately
You did not declare i with const or let
I would advise the use of a beautifier for your code, it's a bit compact in some places
The code does not handle well versions with different counts of digits
You should always pass the base, when you call parseInt

I wrote an alternative version with 2 extra tests;

function checkVersion(a, b) {
    const x = a.split('.').map(e => parseInt(e, 10));
    const y = b.split('.').map(e => parseInt(e, 10));

    for (const i in x) {
        y[i] = y[i] || 0;
        if (x[i] === y[i]) {
            continue;
        } else if (x[i] > y[i]) {
            return 1;
        } else {
            return -1;
        }
    }
    return y.length > x.length ? -1 : 0;
}

console.log(checkVersion("1.2.2", "1.2.0"), 1); // returns 1 as expected
console.log(checkVersion("1.0.5", "1.1.0"), -1); // returns -1 as expected
console.log(checkVersion("1.0.5", "1.00.05"), 0); // returns 0 as expected
console.log(checkVersion("0.9.9.9.9.9.9", "1.0.0.0.0.0.0"), -1) // returns -1 as expected;
console.log(checkVersion("1.0.5", "1.0"), 1); // returns 1 as expected
console.log(checkVersion("1.0", "1.0.5"), -1); // returns -1 as expected
console.log(checkVersion('2019.09', '2019.9'), 0) // returns 0


Searching a Join List for an index Attempt #2

Your code is completely fine, although the suffix Ht for the sublist sizes is a little bit strange.

For the tests you can use

genJoinList :: Arbitrary a => Int -> Gen (JoinList Size a)
genJoinList 0 = pure Empty
genJoinList 1 = Single (Size 1) <$> arbitrary
genJoinList n = do
  left <- choose (0, n)
  Append (Size n) <$> (genJoinList left) <*> (genJoinList (n - left))

toList :: JoinList b a -> [a]
toList Empty          = []
toList (Single _ x)   = [x]
toList (Append _ l r) = toList l ++ toList r

You can now check whether indexJ n js returns the same value as toList js !! n:

prop_index :: (Eq a, Sized m, Monoid m) => Int -> JoinList m a -> Bool
prop_index n js = indexJ n js == indexI n (toList js)
  where
    indexI n xs = lookup n $ zip [0..] xs

main = quickCheck $ \n -> forAll (sized genJoinList) $ \js -> prop_index n js

An Arbitrary instance would need FlexibleInstances by the way.


Do you use the '-Wall' options of GHC ? It is quite handy, especially when there are non-exhaustive pattern matches in your (non-exhaustive pattern matches are bad ;-) )

TicTacToe.hs:84:41: Warning:
    Defaulting the following constraint(s) to type ‘Integer’
      (Num b0) arising from the literal ‘2’ at TicTacToe.hs:84:41
      (Integral b0) arising from a use of ‘^’ at TicTacToe.hs:84:39
    In the second argument of ‘(^)’, namely ‘2’
    In the second argument of ‘(>)’, namely ‘length xss ^ 2’
    In the second argument of ‘(||)’, namely ‘n > length xss ^ 2’

TicTacToe.hs:96:58: Warning:
    Defaulting the following constraint(s) to type ‘Integer’
      (Num b0) arising from the literal ‘2’ at TicTacToe.hs:96:58
      (Integral b0) arising from a use of ‘^’ at TicTacToe.hs:96:56
    In the second argument of ‘(^)’, namely ‘2’
    In the first argument of ‘show’, namely ‘(length board ^ 2)’
    In the first argument of ‘(++)’, namely ‘show (length board ^ 2)’

TicTacToe.hs:37:11: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for ‘winner’: Patterns not matched: []

TicTacToe.hs:62:1: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for ‘toPlayer’: Patterns not matched: Empty
Linking dist/build/TicTacToe/TicTacToe ...

Note: you can also feed your source code into hlint. It will sometimes be able to find some smarter ways to write code (though it won’t give you anything special in your case).

Util module

Concerning the Util module, unless you want to distribute it apart from your project, it should not be placed in Data.Utils.

The nth function can be written using splitAt:

nth :: Int -> (a -> a) -> [a] -> [a]
nth i f l = case splitAt i l of
                (start, elm:end) -> start ++ [f elm] ++ end
                _                -> []

That way, just reading the code makes it clear the nth function applies a function to the nth element of a list.

TicTacToe

You still have problems with putStr and the buffering of ouput. You should put a hFlush stdout right after your putStr call (imported from System.IO). Here’s my terminal:

Turn: Player 1
1
Tile number (1-9): +-+-+-+
|X| | |
+-+-+-+
| | | |
+-+-+-+
| | | |
+-+-+-+

Turn: Player 2
2
Tile number (1-9): +-+-+-+
|X|O| |
+-+-+-+
| | | |
+-+-+-+
| | | |
+-+-+-+

You have placed validateInput and askInput in the "Game logic functions" block though they obviously are UI related.

In validateInput:

"Only integers allowed" is a message that must be generated by the user interface since it converts a String to an Int (this has no direct link to the game and could be reused in other programs)
"Out of range" and "Already filled" are messages that must be generated by the game itself

Note: as the error messages themselves are related to the user interface, the functions should not return them in plain english. One way to do this is to create a type : data ValidateError = OutOfRange | AlreadyFilled | OnlyInteger deriving (Eq) (or a class of types for more advanced error handling). With this, your functions do not deal with translation problems or with representation (an error could also be represented by a sound, an animation or a graphic).

You have a mutual recursion between askInput and gameStep. askInput should not call gameStep. askInput should just do one thing: ask the player a value and return it, nothing else. askInput also decides which player will play. Again, it is not its role. Try to apply the Single responsibility principle.


Server side:

There's no point in importing os and glob inside the function. Local import is used for very specific cases and this is not one of them.
You're defining newset and then returning newest, did you test your code?
There's no point in defining newest (after fixing the typo), and then returning it in a separate line. Just return it in one line.
Add a space before key=..., as per Python conventions.

Client side:

What you've implemented here isn't very smart. You're constantly asking the server for updates, instead of having the server push updates to you when ever it detects them. You've essentially implemented a REST API, but for the wrong reasons. Take a look at websockets (flask-socketio is pretty good).


With the Java functional extensions you can "easily" encode these tests as a BinaryPredicate short-circuitung and set. See the documentation for The and method on BiPredicate.

Consider the following code which you can add-to as your conditions change:

private static final BiPredicate<QueueMsgPushConditionEntity, QueueUpdatedDto> MATCH = ((c, q) -> c != null && q != null)
    .and((c, q) -> matchQueueState(c.getQueueState(), q.getState()))
    .and((c, q) -> matchFirstPush(c.getFirstPush(), q.getSerialId())
    .and((c, q) -> matchPushType(c.getPushType(), PushType.QUEUE_CALL))
    .......

Now, with that static lambda/functional expression, you can change your match function to look like:

private Integer match(List<QueueMsgPushConditionEntity> conditions,
                      QueueUpdatedDto queueUpdatedDto) {

    Optional<QueueMsgPushConditionEntity> first = conditions.stream()
        .dropWhile(c -> !MATCH.test(c, queueUpdatedDto))
        .findFirst();

    return first.map(c -> c.getQueueMsgPushConfigId()).or(null);

}

What the above stream does, is go through all the conditions, and it throws them all away until it finds one that matches all the MATCH tests, and then it stops looking. If/when it finds one, it returns it as the Optional, which is mapped to the Integer, or null if nothing was found.


Something I ran into while making my own implementation:

After 34 rows, the highest number in the row will be two 1166803110s. Adding these for row 35 exceeds the maximum value for ints, resulting in integer-overflow.

You might consider putting the line that does the addition into a checked block, so that an OverflowException is properly thrown:

for (int j = 0; j < prevRow.Count - 1; j++)
{
     checked
     {
         row.Add(prevRow[j] + prevRow[j + 1]);
     }
}

As mentioned in the comments, the values in the rows grow almost exponentially. This means that switching from int to long as datatype in the lists will only roughly double the amount of rows that can be supported before these too overflow.


Making a ul list element animation on hover

First of all i mention again, that i would use a GIF animation to solve this and not a JS. Its a very suboptimal solution to a simple problem.

Your code in the code block is missing two var declarations you have in you jsFiddle example.

Here are the things i would change:

In the most cases, when you have to type the same value twice you do something wrong. Use variables to store your stuff. Makes code more maintainable, easy to read, faster in some cases etc... And give your variables names that speak for them selves. Since you don't write any comments, its even more important.

Cache your jQuery objects in variables. By selecting them again and again, your code gets slow and is hard to mainain. Here an example:

$animate = $("li.animate");
$animate.hover(/* blabalbal */);

Put all your code in a function and pass variable stuff (things that could change) as parameters. Always ask your self what could change if you want to reuse the same code for a different CSS / HTML configuration. (Like different size of the element)

var yourFunction = function( $elem ){
  $elem.each(function(){
   //do something
  });
};

$(function(){ //document ready
  yourFunction( $("whatever element you want to handle") );
});

Then you can call your function in the document ready and you don't have to write all your stuff into your document ready function.

In general split your code in as small generic functions as possible. (Morden browser compile functions that are used often, can make a huge performance differences)

Inside your hover functions you reselect $('.animate'). What are you doing if you have more then one element that has this class? You can refer to the element you are hovering with this inside your hover function:

   $(something).hover(function(){ $(this) //give you back a jQuery selection of the hovered element
   },function(){});

The biggest problem i see in your code is that you have declared your variables very globally, what are you doing if you need to apply this code twice on the same page?

Hope this helps.


You can limit the number of threads you're using via a thread pool. For example:

public class EventManager {
    private static ExecutorService pool = Executors.newFixedThreadPool(8);
    [....]

and then use it like so:

pool.execute(new MyRunnable(this, event));

You should also take care of shutting down the pool when/if you dispose the EventManager.
For further information check the API docs (Android in your case).


Deduplicate << operator implementation on inheritance

Yes use a virtual print() function.
PS. I would also make the toString use the virtual print function to make it more effecient.
class Person
{
    // OTHER STUFF

    virtual void print(std::ostream& target = std::cout) const
    {
        target << firstName << " ";
        if (middleName != "") {
            target << middleName << " ";
        }
        target << lastName;
    }
    std::string toString() const
    {
        std::stringstream  stream;
        this->print(str);
        return stream.str();
    }

    friend std::ostream& operator<<(std::ostream& target, Person const& person)
    {
        person.print(target);
        return target;
    }
};

class Tweeter: public Person
{
    // OTHER STUFF

    // Don't need this any more: => std::string toString() const;
    // Don't need this any more: => friend std::ostream& operator<< (std::ostream& target, Tweeter const & source);

    virtual void print(std::ostream& target = std::cout) const override
    {
         target << "[" << to_string(id) << "] ";
         Person::print(target);
         target <<  " (" << twitterHandle << ")";
    }
};


Using enum descriptions to string/text binding

This looks perfectly reasonable.  In fact, the only thing I would really change is this:

string parameterString = parameter as string;
if ( parameterString == null )
    return DependencyProperty.UnsetValue;

if ( Enum.IsDefined (value.GetType (), value) == false )
    return DependencyProperty.UnsetValue;

You have this in both Convert methods, and it would be just as clear like this:

string parameterString = parameter as string;
if ( parameterString == null || !Enum.IsDefined (value.GetType (), value) )
    return DependencyProperty.UnsetValue;

Additionally, you could concatenate this:

object parameterValue = Enum.Parse (value.GetType (), parameterString);
return parameterValue.Equals (value);

Like this:

return Enum.Parse (value.GetType(), parameterString).Equals (value);

For your XAML, you do not need to put each property on its own individual line.  I typically only break them up when they do not fit on my screen all at once, more like this

<TextBlock Text="How do you measure distance?" Margin="6,0,0,0" Grid.ColumnSpan="2" Grid.Row="0" />
<RadioButton Grid.Row="1" Grid.Column="0"
             Content="{Binding PreferredUnit, ConverterParameter=Metric, Converter={StaticResource EnumToStringConverter}}"
             IsChecked="{Binding PreferredUnit, ConverterParameter=Metric, Converter={StaticResource EnumToBooleanConverter}, Mode=TwoWay}" />

Finally, for your UI, you most likely want to label your radio buttons as what they are, and perhaps change your UI a little to accommodate the labels and still look good.  I would recommend a ComboBox if you have trouble adjusting the UI to look good.  You could then bind the SelectedItem or SelectedIndex to a value in your VM and use a converter to change the value as needed.

<ComboBox Text="Label">
    <ComboBoxItem>Metric (meters)</ComboBoxItem>
    <ComboBoxItem>Imperial (feet)</ComboBoxItem>
</ComboBox>


Pretty-print dollar amounts using custom precision for large amounts

To me your code looks very WET. Everything is using the same core but with minor tweeks here and there. And so we can convert your code to a for loop.
TRANSFORMS = [
    (           12, "$", 10**12,    3, ".3f", " trillion",    ".000",        ""),
    (            9, "$", 10** 9,    2, ".2f",  " billion",     ".00",        ""),
    (            6, "$", 10** 6,    1, ".1f",  " million",      ".0",        ""),
    (            0, "$", 10** 0,    2, ".2f",          "",     ".00",        ""),
    (float("-inf"),  "", 10**-2, None,    "",    " cents", "1 cents",  "1 cent"),
]

def convert_float_to_value(number):
    if number == 0.0:
        return "0 cents"
    digits = 1 + math.floor(math.log10(number))
    for d, *t in TRANSFORMS:
        if digits > d:
            return f"{t[0]}{round(number / t[1], t[2]):,{t[3]}}{t[4]}".replace(t[5], t[6])

From here we can start to see patterns and other improvements.

Excluding cents; t[2], t[3] and t[5] all have the same size.
This means we can build them all from one value.
v = ...
t[2] = v
t[3] = f".{v}f"
t[4] = "." + "0"*v

It makes little sense to use .2f for billions. I've never, until this day, seen "$1.10 billion". It's almost like you've used the wrong word and meant to say "dollars".
To fix this I'd stop using .2f. However this will break how .replace works, and can add some hard to fix bugs.
(Converting 10.01 to 101)
To fix this I'd convert integers to ints and keeps floats as floats.

We haven't built t[3] and t[5] from t[2] for plain dollars as it still requires .2f to make sense.
To deal with this we can make a function pretty_round that takes a number, a number of digets to round to, an option for the output to be a fixed amount of decimal places and any additional formatting. The only thing is that the output has return a string and a float.
def pretty_round(number, ndigits=None, fixed=False, format_spec=""):
    number = round(number, ndigits)
    if number % 1 == 0:
        return number, format(int(number), format_spec)
    return number, format(number, format_spec + (f".{ndigits}f" if fixed else ""))

With the above changes we can see t[5] and t[6] are only there to convert cents from plural to singular.
And so why not just check if the output is singular or plural and append the correct term?

By changing the method of finding digits to use len we can replace float('-inf') with -2 and build t[1] from d.

I am going to reorder the table so that they're grouped better. t[0] should be near t[5] and t[6].
And we can now give them easy to understand names.

TRANSFORMS = [
    (12,    3, False, " trillion", "$",       "",       ""),
    ( 9,    2, False,  " billion", "$",       "",       ""),
    ( 6,    1, False,  " million", "$",       "",       ""),
    ( 0,    2,  True,          "", "$",       "",       ""),
    (-2, None, False,          "",  "", " cents",  " cent"),
]

def pretty_round(number, ndigits=None, fixed=False, format_spec=""):
    number = round(number, ndigits)
    if number % 1 == 0:
        return number, format(int(number), format_spec)
    return number, format(number, format_spec + (f".{ndigits}f" if fixed else ""))

def convert_float_to_value(number):
    digits = len(str(int(number)).lstrip('0-'))
    for exp, dp, fixed, magnitude, prefix, plural, singular in TRANSFORMS:
        if digits > exp:
            number_f, number_s = pretty_round(number / 10**exp, dp, fixed, ",")
            name = singular if number_f == 1 and exp <= 0 else plural
            return f"{prefix}{number_s}{magnitude}{name}"

We can see that TRANSFORMS is not normalized.

All of prefix, plural and singular are refering to dollers and cents.
This can be extracted out into it's own table.
Not only does it reduce how WET your code is it allows us to replace dollars with other monetary notations.
Additionally it allows making changes easier if you want to change from using "$" to "dollars"

The magnitude can change even in English. This is as 1 trillion can equal 1 billion, depending on which scale you use.
Having this baked into the TRANSFORMS table can be problematic in the future.

With your values fixed is the same as not exp.

SHORT_SCALE = [
    "",
    " thousand",
    " million",
    " billion",
    " trillion",
]
USD = [
    ("$", "", ""),
    ("", " cents", " cent"),
]
TRANSFORMS = [
    (12, 3),
    ( 9, 2),
    ( 6, 1),
    ( 0, 2),
    (-2, 0),
]

def pretty_round(number, ndigits=None, fixed=False, format_spec=""):
    number = round(number, ndigits)
    if number % 1 == 0:
        return number, format(int(number), format_spec)
    return number, format(number, format_spec + (f".{ndigits}f" if fixed else ""))

def convert_float_to_value(number, *, scale=SHORT_SCALE, currency=USD):
    digits = len(str(int(number)).lstrip('0-'))
    for exp, dp in TRANSFORMS:
        if digits > exp:
            number_f, number_s = pretty_round(number / 10**exp, dp, not exp, ",")
            prefix, plural, singular = currency[exp < 0]
            name = singular if number_f == 1 and exp <= 0 else plural
            return f"{prefix}{number_s}{scale[int(exp / 3)]}{name}"


How can I make this SQL Bit scalar function more efficient?

I am rewriting my answer to be more clear...

the way you have it written the exists clause will be executed many times...

You should move the exists clauses inside the if block so that in the cases that the other parts don't match it will be forced to short circuit.  You can't depend on SQL server tsql statements to short circuit in the manner you expect.

So this will not execute the inner "IF exists" if the @context isn't 'batch' etc...

The way you have it written it may or may not execute the exists query.

IF (@context = 'batch' AND @sampleTypeId = 247)
begin

        if EXISTS(
            SELECT *
            FROM batch
            WHERE batchid = @contextId
            AND (batch.sampletypeid = @sampleTypeId OR batch.sampletypeid IS NULL)
        ) RETURN 1  ELSE RETURN 0

end

for more reading on this subject check out this articles.

http://beingmarkcohen.com/?p=62

http://www.sqlmag.com/article/tsql3/short-circuit

http://blogs.msdn.com/b/bartd/archive/2011/03/03/don-t-depend-on-expression-short-circuiting-in-t-sql-not-even-with-case.aspx


<?php

// first up i have removed the numbers, those numbers can be automatically added using an ordered list,
// then if you add a menu option later you don't have to renumber everything and look through every file to check the $Nav_ID matches
$nav_normal = array("Home","Read Me","License Agreement","General Information","Database Installer","Create an Account","Create Config","Successfully installed");

// removed as documented below
// $last_normal = array_pop(array_keys($nav_normal));

// we need to start the list somewhere?, using an ordered list will automatically number the menu options
echo "
";

foreach($nav_normal as $name){

    if($Nav_ID == $name){
        // $Nav_Type is not very descriptive
        // $Nav_Type = "Selected";
        $Nav_Selected = "Selected";
    } else {
        $Nav_Selected = '';
        // it is not necessary to have a state for unselected
//        $Nav_Type = "Unselected";
    }

    // the last if/else block could be replaced by this single line
    $Nav_Selected = ($Nav_ID == $name) ? "Selected" : '';

    // it is not worth escaping php for a single, line, it is easier just to embed the html and echo it
    // make sure we call htmlspecialchars or characters like >< & " etc will stuff up your html
    echo "
".htmlspecialchars($name)."
";

    // this makes no visible difference, multiple spaces are rendered as one in html
//    if($name != $last_normal){
//        echo("\n                                        ");
//    }else{
        echo "\n";
//    }

}

// if we want extra spaces after the last item in the loop, just echo them after the loop has finished
echo "                                        ";

// don't forget to close the ordered list too
echo "
";


The first thing you need to do is define what you mean with "best". Fastest to execute? Most readable? Best Java-ness?

In any case neither solution is very "nice". The first one unecessarily removes the "current" item und re-adds it, the second one uses indexOf, thus indirectly has two loops, and finally the third one makes a copy of the list, which is even slower.

When using "low level" removing/adding and modification of the original list, I guess I'd do it like this (untested):

public void reOrder(List<String> list, String current) {
   int i = list.length;
   while (i-- > 0 && list.get(0) != current)
      list.add(list.remove(0));
}

(BTW, consider making use of the generics: public <T> void reOrder(List<T> list, T current) {...)

There is also a Java API function that does this (Collections.rotate), but it requires the index of the "current" element. If you have a "better" or more optimized why to get the index, other than the "left to right" search of indexOf (such as a binary search, or a map), then that would be a better solution.

In any case, using the current item's index instead of the item itself is something you should consider (depending on the the architecture of your project), because it generally not a good idea to have to search for the index of an item every time you do something with the list.

If speed is really a practical problem for you, then another thing you should check, is if you really need to reorder the actual list. There are ways just to create a "view" of the list in the desired order which would basically take virtually no additional time (especially it would be independently from the length of the list) to create and use.


In response to not triggering the message repeatedly, I would store the previous check for a collision so you know if a collision has started or ended.

If there is a collision but your previous check didn't show a collision, then you have a new collision and you can trigger the event. However, if the previous check did show a collision, don't fire the callback since it has already been fired.

I would also recommend using custom jQuery events. This allows you to separate out the callback from the animation code.

Below I've adapted your code to trigger a custom event when you detect a collision has started or ended. Here's the updated javascript (also available as a modification of your fiddle):

$(document).ready(function () {

    $(".menu").data("collision", false);
    $(".menu").on("collision_start", function () {
        $(".container").append("Welcome Earthling");
    });

    $(".container").click(function () {

        $(".menu").stop().animate({
            left: "+=100px"
        }, {
            duration: 300,
            complete: function () {
                $(".menu").animate({
                    left: "0"
                }, 800);
            },
            step: function () {
                //Test for collision
                var hit_list = $(this).collision(".test");
                var current_collision = hit_list.length != 0;

                // compare this to what we last observed
                var changed_collision = current_collision != $(this).data("collision");

                if (changed_collision) {
                    // save this new observation for future comparisons
                    $(this).data("collision", current_collision);

                    // trigger an event
                    $(this).trigger("collision_" + (current_collision ? "start" : "stop"));
                }
            }
        });
    });
});


While there are circumstances where you need to decouple the Principal from the Identity, in many applications this is not the case, and the distinction will only complicate the code.  The way security is best handled in an application depends very much on the individual needs of the particular app.

Martin Fowler's article Dealing with Roles provides an in depth analysis on to the different patterns that can be used to implement role-based security, and the indications of necessity for each pattern.

In general, you can't make an assumption that a solution that separates the principal from the identity is the optimal solution for all applications.  I have encountered many scenarios where it was unnecessary and added nothing but additional classes.  In that case, it is better to merge the two interfaces.

Furthermore, these are interfaces not classes.  An interface denotes a "has a" relationship between the instance and the definition, where as a class denotes an "is a" relationship.  An instance of a User in the OP's example is an object that has both an Identity and a Principal (Security Context).  You can always break things down to further levels of complexity, but if the application functionality doesn't indicate a reasonable need to separate the class, then Why would you do it?


Is this a good and simple example for Singleton Pattern

For explaining the Singleton pattern the ABC naming is confusing. Just come up with some real name, e.g. Database, Logger etc. Something that might need access to a common config. Instead of System.out the config, you might want to add some mock code to init the database connection or get the logging directory.

Please keep in mind that Java classes usually are starting with a capital letter.

The static instance variable is usually called only instance.

In which context do you want to explain the pattern. Maybe we find a more suitable example?

Check http://www.oodesign.com/singleton-pattern.html for a nice explanation and some examples and drawbacks.

Please be aware that a Singleton might seem to help you sometimes in production code, but it definitely makes your life harder in testing your code. See "Dependency Injection" for an alternate approach.


Print all nodes that are at distance k from a leaf node

Your algorithm seems fine; it is indeed \$O(n)\$ time and \$O(n)\$ space. If you adjusted your code somewhat, you could reduce it to \$O(h)\$ space (ignoring input), where \$h\$ is the height of the tree; I'll come back to this later. One nit: it doesn't handle k == 0.

The major issue with this code is that it doesn't help the reader understand it. Your names describe the mechanics of the named item, not its purpose (recurse, list, items -- what purpose do these have in your algorithm?). The classes are divided oddly -- encapsulation is broken (e.g. almost all of your code has to know the precise representation of the tree).

Encapsulation of the tree representation

KDistanceFromLeaves<T>'s constructor takes a List<T>. Here you're making assumptions about the representation of the tree that have nothing to do with its type. The easiest solution is probably to take a TreeNode<T> instead (and make TreeNode<T> a public class instead of a nested class of KDistanceFromLeaves<T>. Alternatively, you could implement something like

interface IterableTree<T> {
    interface Iterator {
        T getValue();
        boolean hasLeft();
        /** The behavior of getLeft() is undefined when !hasLeft() */
        Iterator getLeft();
        /** The behavior of getRight() is undefined when !hasRight() */
        boolean hasRight();
        Iterator hasRight();
    }
    boolean isEmpty();
    /** The behavior of getRoot() is undefined when isEmpty(). */
    Iterator getRoot();
}

Two implementations arise immediately to mind:

class TreeNode<T> implements IterableTree<T>, IterableTree<T>.Iterator {
    private final T value;
    private TreeNode<T> left = null;
    private TreeNode<T> right = null;

    public TreeNode(T value) { this.value = value; }
    public void setLeft(TreeNode<T> left) { this.left = left; }
    public void setRight(TreeNode<T> right) { this.right = right; }

    /** A non-null TreeNode<T> is never an empty tree */
    @Override
    public boolean isEmpty() { return false; }

    @Override
    public TreeNode<T> getRoot() { return this; }

    @Override
    public T getValue() { return value; }

    @Override
    public TreeNode<T> getLeft() { return left; }

    @Override
    public boolean hasRight() { return right != null; }

    @Override
    public TreeNode<T> getRight() { return right; }
}

public ListBackedTree<T> implements IterableTree<T> {
    private final List<T> nodes;

    public ListBackedTree(List<T> nodes) { this.nodes = nodes }

    private class Iterator implements IterableTree<T>.Iterator {
        private int index;

        public Iterator(int index) { this.index = index; }

        @Override
        public T getValue() { return nodes.get(index); }

        @Override
        public boolean hasLeft() { return 2 * index + 1 < nodes.size(); }

        @Override
        public Iterator getLeft() {
            return new Iterator(2 * index + 1);
        }

        @Override
        public boolean hasRight() { return 2 * index + 2 < nodes.size(); }

        @Override
        public Iterator getRight() {
            return new Iterator(2 * index + 2);
        }
    }

    @Override
    public boolean isEmpty() { return nodes.isEmpty(); }

    @Override
    public Iterator getRoot() { return new Iterator(0); }
}

If you use IterableTree<T> instead of List<T>, your users don't have to convert between tree representations just to use your algorithm -- they can use whatever tree they've already got lying around.

As a side note, from an encapsulation point of view, with the code you had, create should be a static method on TreeNode<T> (or even be renamed to TreeNode<T>.TreeNode(List<T>)), not a private method on KDistanceFromTreeLeaves<T>. Classes should be responsible for understanding their own representation.

Rewriting the algorithm

As I mentioned above, your algorithm is fine. The problem comes in the way it is presented.

I'd start by making kDistanceFromLeaf a static method that takes a tree as an argument rather than a method on a class whose only member is a tree. It sort of made sense with your code, since you transformed the tree passed to the constructor and so wanted to save the effort of transformation each time you called your algorithm. However, your transformation was simply a change in representation -- you don't do any additional computation. Thus, it makes more sense to abstract the algorithm away from the representation than to transform the data and make your algorithm depend on a single representation.

How about the return value? A List is ordered and may contain multiple copies of a given value. That doesn't really model our return value. What we really want to return is a Set -- this is an unordered collection that contains at most one copy of each value.

Next up is naming. What is items? Well, it's a list of the current node's ancestors. So let's call it ancestors. What about list? This is a list of the nodes that satisfy our condition. We could call it found or targets. visited is obviated by using a Set instead of a List.

Finally, comments. First, it is sensible to document the purpose of classes and methods using doc comments. Second, it is sometimes very useful to add comments that explain why code is written a certain way.

With all that in mind, here's another whack at implementing the algorithm:

/** Collects implementations of interview questions */
class InterviewProblems {
    /**
     * Given a tree, determines which nodes are exactly k distance from
     * a leaf node (that is, nodes that are k levels above a leaf node).
     */
    public static <T> Set<T> kDistanceFromLeaf(
            IterableTree<T> tree, int k) {
        Set<T> found = new HashSet<>();
        if (tree == null || tree.isEmpty()) return found;
        computeKDistanceFromLeaf(tree.getRoot(), k, new ArrayList<T>(), found);
        return found;
    }

    private static <T> boolean isLeafNode(IterableTree<T>.Iterator node) {
        return !node.hasLeft() && !node.hasRight();
    }

    /** Recursive helper function for {@link #kDistanceFromLeaf}. */
    private static <T> void computeKDistanceFromLeaf(
            IterableTree<T>.Iterator node, int k,
            List<T> ancestors, Set<T> found) {
        ancestors.add(node.getValue());
        // If this is a leaf node, its kth ancestor should be added to found.
        if (isLeafNode(node) && ancestors.size() > k) {
            found.add(ancestors.get(ancestors.size() - 1 - k));
        }
        if (node.hasLeft())
            computeKDistanceFromLeaf(node.getLeft(), k, ancestors, found);
        if (node.hasRight())
            computeKDistanceFromLeaf(node.getRight(), k, ancestors, found);
        ancestors.remove(ancestors.size() - 1);
    }
}

Minor comments

You use final a lot for local variables. That's fine (and as someone who uses C++ a lot, I certainly understand the instinct). However, a more common Java style is only to mark local variables final when they are to be used by inner classes. final is not nearly as useful as C++'s const and the cost-benefit tradeoff (cost: final is sprinkled liberally through the code; benefit: you know that the reference won't be reassigned, but not that the objects won't be modified) is less in favor of adding final in Java than const in C++.

Yay unit tests! One question: You've given an example in the problem description -- why not write a unit test that confirms that the code correctly works the example?

A final comment: I haven't compiled, much less tested, the code in this example, so use it with care and let me know if you have any questions!


To expand on Hubert Grzeskowiak's answer the custom data attribute is a good option for you as you can continue specifying content in the markup as it should.

But there is a way with CSS to display it with the content property. Used on a pseudo element, you can choose to show it or not depending on viewport width with media queries.

This will allow you to :

minimize markup
change the content according to the viewport width
no use of JS
keep the content in the markup

DEMO

th {
    border: 1px solid #000;
    position:relative;
}
td {
    border: 1px solid #000;
}
.full:after{
    content: attr(data-state);
    display:none;
}
@media screen and (max-width:320px) {
    .full:after{
        position:absolute;
        top:0;left:0;
        width:100%; height:100%;
        background:#fff;
        display:block;
}

        California
        Florida
        Texas
        Georgia

        Sacramento
        Tallahassee
        Austin
        Atlanta


Use a custom IComparer<T> to sort the the items.

class TeamSheetStaffPocoComparer : IComparer<TeamSheetStaffPoco> {

    public int Compare(TeamSheetStaffPoco a, TeamSheetStaffPoco b) {

        if (a.StaffID == null && b.StaffId == null)
        {
            return a.FreeTextName.CompareTo(b.FreeTextName);
        }

        if (a.StaffID > 0 && b.StaffID > 0)
        {
            return a.Name.CompareTo(b.Name);
        }

        return a.StaffID > 0 ? 1 : -1;
    }

 }

Then you can simplify the last two lines to

var result = resList.OrderBy(x => x, new TeamSheetStaffPocoComparer()).ToList();

Also, you can now reuse the comparison class elsewhere too if you wish.


'StrictInt' Python object class that prohibits casting numbers with non-integer components to `int`

Converting everything via a float means that you get the wrong result whenever the input cannot be represented exactly as a double-precision floating-point number. For example, this is surely not acceptable:

>>> StrictInt(10**23)
99999999999999991611392

There's an OverflowError when the input is too large to be represented as a float:

>>> StrictInt(10**400)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr195375.py", line 13, in __new__
    f = float(value)
OverflowError: int too large to convert to float

The strategy of enumerating the allowable types (int, StrictInt, float, str) means that many plausible use cases are disallowed, for example with fractions.Fraction:

>>> from fractions import Fraction
>>> StrictInt(Fraction(10, 1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr195375.py", line 10, in __new__
    raise TypeError("Cannot convert type '{type}' to strict integer".format(type=t))
TypeError: Cannot convert type 'fractions.Fraction' to strict integer

and similarly with decimal.Decimal.
The Pythonic approach is to use duck typing — that is, instead of testing whether input belongs to a fixed collection of types, you call the appropriate methods on the input. Here we want to determine whether the input has a non-zero fractional part, and otherwise to use the integer part. Hence we need Python's built-in divmod function:

quotient, remainder = divmod(value, 1)
if remainder:
    raise ValueError("could not convert value due to non-zero "
                     f"fractional part: {val!r}")

There is no point taking *args and **kwargs if you are not going to use them.

Putting this together:

class StrictInt(int):
    "Subclass of int that refuses to coerce non-integer values."
    def __new__(cls, value):
        if isinstance(value, str):
            for converter in (int, float, complex):
                try:
                    value = converter(value)
                    break
                except ValueError:
                    pass
            else:
                raise ValueError(f"invalid literal for {cls.__name__}(): "
                                 f"{value!r}")
        if value.imag:
            raise ValueError("could not convert value due to non-zero "
                             f"imaginary part: {value!r}")
        quotient, remainder = divmod(value.real, 1)
        if remainder:
            raise ValueError("could not convert value due to non-zero "
                             f"fractional part: {value!r}")
        return super(StrictInt, cls).__new__(cls, int(quotient))

This handles a wider ranges of input types:

>>> StrictInt(Fraction(10, 2))
5
>>> StrictInt(Decimal('11.00000'))
11
>>> StrictInt(5+0j)
5

and it copes with integers that are too large to be represented as floats:

>>> StrictInt(10**400) == 10**400
True


Effective ways to find partial sha1 collision

Choosing two strings, hashing them, and comparing the first 8 hex characters of the hash should produce a match once every 2^32 iterations.  The question implies that the values for x for the match aren't required to be the same, so your approach is much too restrictive.  You need to compare the hash you just generated with all of the previous hashes.  If you use a Dictionary<String, String> or similar to store previous results, you can expect a collision after 2^16 elements.

Coding-wise, your byte-to-string conversion can be made more efficient (you do work that is discarded).  You might consider just returning 8 bytes and writing a comparitor for that.


Presenting user with options and executing a function based on user choice in Javascript

I think a good way to approach this would be to integrate all the data (descriptions, options, and additional room choices) into an object indexed by room number or step name (since multiple things can be done in a single room). Starting at the first room, parse the data for that room to display the description and choices appropriately, and continue recursively whenever a new choice is made. Doing it this way means that, to set up the rooms, you only need to change around the object room numbers and strings instead of writing convoluted JavaScript logic.
For example, for the hallway and 2 rooms, you could have:
const steps = {
  hallway: {
    desc: 'You see two rooms',
    choices: ['Room 1', 'Room 2']
  },
  'Room 2': {
    desc: 'Nothing of interest here',
    // when the choice description and JS step name are not the same,
    // separate them
    choices: [{ desc: 'Exit', target: 'hallway' }]
  },
  'Room 1': {
    desc: 'You find a letter on the table',
    choices: [
      { desc: 'Read it', target: 'readLetter' },
      { desc: 'Exit', target: 'hallway', onChoiceDesc: 'You exit the room and return to the hallway' }
    ]
  },
  readLetter: {
    // ...
  },
};

Whenever a new step runs, if the choice that was just chosen had a onChoiceDesc property, display that. Otherwise, display the desc of the new step onto the page. Iterate through each choice to add a button, a button description, and a click handler.
To conditionally display a choice depending on program state, add a function to the choice object. Eg, if, after reading the letter, something becomes available in the hallway, you could add the following:
choices: ['Room 1', 'Room 2', { desc: 'Room 3', target: 'Room 3', showIf: () => hasReadLetter }]

readLetter: {
  desc: 'You start reading the letter. The letter informs you that Room 3 exists',
  choices: [
    { desc: 'Exit', target: 'hallway', onChoiceFn: () => hasReadLetter = true }
  ]
}

where onChoice gets invoked when the button is clicked (in addition to the default behavior of re-rendering the hallway step). (Make sure to have declared a hasReadLetter variable outside.)
That's the general idea - leave the manipulation of the DOM to the other code that parses through the steps object, while writing the meat of the game inside the steps object.

Although you'll probably be ditching most of it, some suggestions regarding your current code:
Classes are good for tying together data with methods related to the data. If all you have is plain data, a class doesn't help you. In your case, unless you were planning on adding methods later, using a plain object would make more sense for the Rooms.
Use consistent indentation so that you (and other readers of the code) can pick up on the { } blocks at a glance. Ideally, use an IDE that indents code properly and automatically. For example, this:
}
 var f1hallway = new Room("You see two rooms", ["Room 1", "Room 2"]);
    whichArea = function(areaSelected) {
                selectedArea = areaSelected;

should be
}
var f1hallway = new Room("You see two rooms", ["Room 1", "Room 2"]);
whichArea = function(areaSelected) {
    selectedArea = areaSelected;

Declare variables before using them - if you don't, you'll either be implicitly assigning to the global object (which is inelegant), or an error will be thrown if running in strict mode (and strict mode is recommended). Not declaring a variable before using it is a not-uncommon source of bugs when one finds that the variable isn't scoped as one expected it to be. The whichArea = should be let whichArea =.
Use modern syntax If you're going to write in ES6+ (which you are with the class, and as you should), never use var, it has too many gotchas to be worth using nowadays - use const instead when declaring variables, or use let when you have to reassign the variable.
Prefer IDL properties over setAttribute when feasible - IDL properties are usually more concise and easier to read and write. These two:
choiceButton.setAttribute("class", "choice-button");
choiceButton.setAttribute("id", x);

can be
choiceButton.className = "choice-button";
choiceButton.id = x;

(though, neither of those should be necessary at all: to target the button with CSS, you should be able to do .choices > button, by giving the parent a class name instead. Dynamic IDs are quite a code smell too - to get the index inside a click handler, either check the child's index in an array of all siblings, or use a data attribute, or a Map - but not an ID. Or, even better, in this case, just use the closure in the click handler over the index being iterated over.)
Prefer .textContent over .innerHTML unless you're deliberately setting text content; .textContent is faster, safer, and more semantically appropriate.
Prefer strict equality - loose equality with == and != has a whole bunch of weird coercion rules that neither you nor others who happen to read the code should have to have memorized to understand what's going on. Use === and !== instead.


There could be a number of factors here. First, most of the computation happens in a tiny kernel - asm.js isn't necessary to make that fast, usually the normal JIT can do just as well. asm.js really shines on large applications with lots of hot code.

And asm.js might win or lose on such tiny kernels just because the register allocator might emit something a little different. Small kernels are very noisy that way.

But, the issue here looks like something else. Check out this, which modifies that code to add a little "counter" which adjusts the value sent into sin(). Actually, most of the time spent in this benchmark is in sin(), as shown by the profiler. And in Firefox, sin() is actually a little different in asm.js mode and not - when not, there is a cache which helps speed up simple code like you see in the SunSpider benchmark. All browsers implemented such caches because they sometimes really help. But so far Firefox doesn't have such a cache on asm.js. Anyhow, the counter I added makes it so the cache is less effective - a much wider range of values is sent into sin(), and with that change, asm.js is significantly faster. Or, to put it another way: asm.js is about as fast as before, but non-asm.js is much slower, due to the cache no longer helping.

What are the implications? If you need this code to be very fast, you might just implement your own sin() cache in asm.js. You can make it as low-precision as you want, so it could be even more efficient than the browser's general and precise cache.

Even better, you can implement sin() in asm.js as well, once more making it as low-precision as you can tolerate. Right now browsers call out to libc for sin(), which tends to be very precise, and a lower-precision asm.js one could beat that. It would also be more consistent between users, since no libc differences. (We are considering shipping sin() with emscripten's libc, for these reasons, but haven't so far.)


Genetic algorithm in Python that plots its evolution

random.seed is a bug: add parentheses to actually call the function.
Use collections.namedtuple so you can write member.fitness instead of the less readable member[0]
copy.deepcopy should not be necessary in a functional approach
Keeping the genes in a tuple instead of a list would make the member tuple fully immutable, in line with the functional approach. This eliminates the need to deep-copy objects as you can safely copy just references.

After these changes create_member becomes like this:

import collections
Member = collections.namedtuple("Member", "fitness genes")

def create_member(genes):
    genes = tuple(genes)
    return Member(sum(genes), genes)

In some places you create members without calling create_member. Be sure to change them, for example:

def mutate_member(member, rate=1):
    return create_member(mutate_genes(member.genes, rate))

With immutable members there is no need to recalculate fitnesses. You can delete such functions.


Just a few thoughts...

You are using x and y coordinates. Why not take advantage of the Point class? The MouseEvent class has methods that return Point objects, and it would probably make your code more readable. x1 and y1 don't mean anything to me, but you could probably give meaningful names to the points represented by (x1, y1) and (x2, y2).

The use of magic numbers (you storing 2 and 3 into SWITCH, for example) is a poor practice. Use constant ints or (as Landei suggested in the comments) an enum. It will allow you to improve the readable and understandability of the code - at a first read-through, I didn't get what you were doing.

As per Java standards, a class name should begin with a capital letter. Your class is currently called r. You should give it a meaningful name. You might also want to look into other Java standards for code formatting in terms of brace placement, indentation, and so forth. To me, your code is just plain hard to read because of formatting.

Rather than if and switch/case statements, consider leveraging polymorphism in order to draw different shapes. Move the logic to draw different shapes into concrete subclasses, while perhaps maintaining common logic in a superclass.


Critique my first C++ "Hello World" program

It has been commented that when working in C++ you should use std::string.  Assuming you want to stay with C style strings (or at least understand how you ought to work with them, in case you ever have to), I have the following suggestions:

strcpy(title,tit);

tit can be larger than the buffer title allows.[1]  In that case, your program will crash or worse, continue running while corrupting some other part of memory.  To avoid that you should always use functions which let you track the size of the destination buffer and detect overflow.  For example:

strncpy(title, sizeof(title)-1, tit);
title[sizeof(title) - 1] = 0;

This has some undesirable traits in that it will silently truncate the string if the input is larger than the destination.  If you are working on a system that has the non-standard strlcpy, that has some cleaner error conditions:

if (strlcpy(title, sizeof(title), tit) >= sizeof(title)))
{
    // TODO: decide how to handle the error (in your case maybe throw
    // an exception)
}

Moving along the spectrum (from code that crashes given large input, to code that truncates the input, to code that errors out when the buffer in insufficient...), you might also want to dynamically allocate memory for this.

char *title;

Book(const char *tit)
{
   title = strdup(tit);
   if (!title) { throw std::bad_alloc(); }
}

This creates complications if a Book object is ever copied, so you need to handle that:

Book(const Book &b)
{
   title = strdup(b.title);
   if (!title) { throw std::bad_alloc(); }
}

And it needs to be freed when your object is destroyed:

~Book()
{
   free(title);
}

If this seems too complicated it's because for higher-level C++ code it probably is.  std::string will take care of all of this for you.  Note though that the memory layout of your object will be substantially different with these dynamic-memory approaches.[2]

Next up...

Book miolibro((char *)"aaa");

As a general rule, having to do casts like this is often an indicator that you're doing something wrong.  :-)  When writing code and reviewing the work of others' I tend to try to avoid as many unnecessary casts as possible.  A lot of times these mask bugs, for example casting a function to an incorrect function pointer type can produce crashes, or casting away const may crash when someone tries to modify a read-only buffer.  For reasons like this it's a good habit to watch for inappropriate casts when reading code, and be sure not to introduce them yourself; code like this should offend your sensibilities.  :-)  [3]

In your case, the issue is that string literals have the type const char*, so the compiler complains that you are passing this to something that doesn't have const.  So what you need to do here is:

Book(const char *tit)
{
    // ...
}

Footnotes and tangential comments:
[1] If there are any English speaking people who might read your code, I suggest you come up with a better name than tit for that variable.
[2] In the earlier example, characters of title exists alongside any other members of the class.  When using dynamic memory, there's now an extra pointer dereference going on to get to the characters.  In most cases this won't make a difference but you can think of theoretical cases where the former is desired over the latter.
[3] Side note: In my experience one way to tell that someone doesn't know what they're doing in C/C++ is the use of casts.  A sloppy programmer will write code that the compiler rejects, and then to get it "working" quickly they'll introduce casts to silence compiler warnings instead of fixing the actual problem.  If you are working on a team where people do this, I find it's sometimes a good indication to be skeptical of that person's work for other reasons.


Unordered list in HTML with animated list points

Your HTML is far too overloaded.

The .point elements are unnecessary and can be replaced by using the pseudo-element ::before. This requires adding the property content: "".
Generally as a rule, it's wrong to use the same class on all child elements, especially when it's generic like item. Better mark the list itself and use a child selector to select the items, for example .animated-list > li.
The <div class="text"> also seem unnecessary for this example. Setting display: inline-block and width have nothing to do with animated bullets and the color and font-family should be assigned on a higher level element such as the body.

In the CSS, as mentioned above

replace ul with ul.animated-list
replace .item with ul.animated-list > li
replace .point with ul.animated-list > li::before

The sudden use of :first-child instead of .point seems strange. Use ul.animated-list > li::before here too, thus ul.animated-list > li:nth-of-type(1)::before.

Finally, I'd expect the the bullets to animate when hovering over the list item not just the bullet itself, so I'd replace .point:hover with ul.animated-list > li:hover::before.

And for some "flair" consider adding transition: transform 0.1s; to get a smooth animation.

EDIT: Here's my code: http://codepen.io/anon/pen/adoWxp