For what it's worth I think you've over complicated this. It seems to me that you care if you succeed or not and then want to pass as much information on to someone who can figure out what went wrong. The only 2 lines that are in the try block are parsing to doubles so just catch Exception and beef up the information included.

public void UpdateJobGeoCoordinates(Job job)
{
    var address = _kernel.GetKernel();

    var gpsCoordinate = _locator.GetGpsCoordinates(address);

    try
    {
        job.Lat = Double.Parse(gpsCoordinate.Item1, CultureInfo.InvariantCulture);
        job.Lng = Double.Parse(gpsCoordinate.Item2, CultureInfo.InvariantCulture);
    }
    catch (Exception ex)
    {
        ResetCoordinates(job);
        Logger.Warn("Geo location issue for Job [{0}] , Exception details: {1}", job.ERPServiceOrderId, ex);
    }
}

Note that Exception.ToString() is so much more useful than just the message.

You'll get the type of the exception, the message and the stack trace.


Excel VBA optimizing for large data base

Finding (and removing) duplicates is already a built-in functionality; this code is kind of reinventing the wheel. Making VBA code faster than native functionality, from what I've seen, requires thinking outside the box and manipulating memory locations.

But let's review the code we're looking at.

Sub DupValidation()

Kudos for using a meaningful name! This one reads like a noun though; since Sub procedures typically do something, it's common practice to make their names start with a verb, so ValidateDuplicates would be a better name. The procedure is also implicitly Public; consider always using explicit modifiers.

Next we have a handful of declarations, for each of the variables used in the procedure. Again, kudos for explicitly declaring all variables (is Option Explicit specified?) - but consider declaring them when they're needed, as they're needed. That way it's much harder to accidentally leave unused variables behind, like what happened to lastrow2.

Rule of thumb, if there's a digit at the end of a name, it's usually a bad name. ws1 could be sheet, or ticketsSheet.

But you're not here to hear about variable naming are you.

I'm curious why Range("g2:g" & lastrow) is good enough to get a range encompassing all cells in column G, but once inside the loop we switch to a very long-winded Range(Cells, Cells) call instead of just doing Range("B2:B" & lastrow) like we just did.

Do we really need to COUNTIF to identify a 2nd or 3rd (or 250th) duplicate for one value?

If we had a data structure we could quickly lookup a value from, we could put the known-dupe value in it, and then only perform the expensive COUNTIF when we already know we're not looking at a known duplicate value. Dictionary and its O(1) keyed retrieval sounds like a good tool for this.

So instead of just writing True into column G, we can store the value of column B into our dictionary, and then the loop can now conditionally evaluate the countif when the dictionary doesn't already contain the value in column B.

Actually, with a dictionary you could make the whole loop much more efficient than that.

Start at row 2, end at lastrow: the number of iterations is known before we even start looping - the loop should be a For loop, not Do While. So we loop i from 2 to N, and at each row we try to add the value of column B into the dictionary. If the value already exists in there (that's O(1); CountIf is O(n)), then we know we have a dupe at that row so we write True to column G. After the loop, column G identifies all dupes, and the dictionary contains all the unique values. Iterating a variant array of values in-memory instead of worksheet cells would be even faster. You'll find the Dictionary class in the Scripting library if you want it early-bound.

But then again, I doubt it would be faster than the native highlight duplicates functionality.


It's hard to make small tweaks to this code to make it do what you want, so I'm going to give some pointers on how to do a wholesale rewrite.
Before you can write a card game, you need to write a data model for a deck of cards.  Picking the right data model makes everything else easy (part of why your program was hard to write and is hard to fix that the cards were modeled in a way that didn't make the rest of the program easy).  Here's how I'd do it:
from enum import auto, Enum
from random import shuffle
from typing import List, NamedTuple

class Rank(Enum):
    ACE = 1
    TWO = 2
    THREE = 3
    FOUR = 4
    FIVE = 5
    SIX = 6
    SEVEN = 7
    EIGHT = 8
    NINE = 9
    TEN = 10
    JACK = 10
    QUEEN = 10
    KING = 10

class Suit(Enum):
    SPADES = auto()
    CLUBS = auto()
    DIAMONDS = auto()
    HEARTS = auto()

class Card(NamedTuple):
    rank: Rank
    suit: Suit
    def __repr__(self) -> str:
        """Pretty-print the name of the card, e.g. 'Queen of Hearts'"""
        return f"{self.rank.name.title()} of {self.suit.name.title()}"

There's my Card class -- every card has a rank and suit.  Enums have the convenient built-in functions name and value that I can use for pretty-printing and also for scoring (I set the value of my Rank enum to correspond to standard scoring numbers).
A NamedTuple is an easy way to build a class that contains multiple other values that never change; it automatically implements a constructor to set its member variables and in many cases you don't need to do anything other than declare what those variables are, but you can also add other methods to it.  My Card implements a magic __repr__ function so that anywhere we print one (including inside a list) it will get formatted as something like Queen of Hearts rather than the default NamedTuple formatting of Card(rank=Rank.QUEEN, suit=Suit.HEARTS).
And here's a really quick example of how you could use this class to implement a game like blackjack.  This isn't an actual blackjack game, I've just implemented the dealer part to demonstrate how building a deck, shuffling, and dealing would work, but hopefully you can play with this code and see how simple everything is when you have a nice data model.  In particular something like the best_value function is going to be really important to a blackjack game (and it's a lot easier to define it as its own function and then be able to call it in a bunch of places).
deck = [Card(rank, suit) for suit in Suit for rank in Rank]
print("Here's our deck fresh from the factory: ", deck)
shuffle(deck)
print("Here it is all shuffled: ", deck)

def best_value(hand: List[Card]) -> int:
    """Get the best blackjack value for a hand of cards (highest without busting)"""
    value = sum([card.rank.value for card in hand])
    if value < 12 and any([card.rank == Rank.ACE for card in hand]):
        # Count one of our aces as 11, adding 10 to the total.
        value += 10
    return value

print()
print("Deal me two!")
hand = [deck.pop(), deck.pop()]
print(f"My hand is {hand}, which is worth {best_value(hand)}")

while best_value(hand) < 17:
    print("Hit me!")
    card = deck.pop()
    hand.append(card)
    print("I got ", card)

if best_value(hand) > 21:
    print("Bust!")
print(f"{hand} = {best_value(hand)}")

Run this code, read through it, understand how it works, then take another crack at writing a blackjack program and hopefully it'll be easier this time around.  :)


Okay

All of them

Don't have multiple statements on the same line like that.
Use either spaces or tabs, don't use both.
<?php something; ?> <?php somethingElse; ?> is pointless. Don't do that.
Be consistent. Sometimes you're doing funcName( $param ) and sometimes funcName($param). Pick one and stick with it.

1)

Looks good security wise. See above All of them for improving.

2)

Looks good, but too little information to know. If you haven't already, set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION and PDO::ATTR_EMULATE_PREPARES to false. See `PDO::setAttribute().

3)

Sometimes you are redirecting to localhost, sometimes to mywebsite. Use a variable. See $_SERVER.
}} is horrible.

4)

Very good. Queries that don't use parameters don't need to be prepared. Note however that there's a very fine line! Every time you need a variable inside of a query, you want a prepared statement.

5)

You are vulnerable to XSS attacks on your tags. This can be prevented by escaping your tags for HTML output.

6)

Look at the all of them list for details on how to improve.

All in all, you must improve your code-style. Your code is extremely unreadable and will be hard to maintain in the future.

Aside from that one XSS vulnerability, it looks good to me, but again, it's hard to tell just with the code you've given.


Code Style
Remember to follow PEP 8 where you can. In particular, you should use snake_case rather than camelCase.
Making your Intentions Clear
Be sure to use comments to explain why your steps are needed rather than just what your code does:
lenText -= 1 # reduce lenText by 1

It is reasonably clear what your code is doing, but you could comment to explain why you're doing this. I'd be tempted to rewrite your substring finding loop as:
# Iterate over all possible substrings of text
for start_index in range(0, len(text)):
    for end_index in range(start_index + 1, len(text) + 1):
        L = text[start_index:end_index]
        # Your logic here

Storing Results
If you preferred, you could save some memory by only storing the patterns that have the highest score we've seen so far.
# Stores the highest seen pattern score so far.
highest_score = 0
# Stores the substrings of text that give highest_score.
highest_substrings = []

You then just need to check if your current score is strictly greater than the highest score seen so far and empty highest_substrings, then if you see a score greater than or equal to highest_score you add that substring to highest_substrings.


Don't be discouraged by how much I have written. I'm a professional software developer and my colleagues make fun of me because of how pedantic my code reviews are. I think what you've done is actually pretty neat for a first program, and I like that you've obviously made a conscious effort to break things into useful functions (a lot of beginners don't do this well).

I always think people shouldn't pull punches early on in code reviews because it saves agro later on. Some of my points (particularly the formatting/style/naming points) will feel like pedantry, but the issue is that tiny projects become small projects become moderately sized projects and before you know it you have got a beast on your hands. So its worth getting the little stuff right early.

Formatting

Typically the class should be indented inside the namespace. having two braces at the same indentation level as you have done at the end of the snippet looks strange.
the second line of bool BonusCompliment() is not indented correctly

Naming

Choose a naming convention and stick to it religiously. This will make your code easier to read.

compliment is a sequence of compliments so should be plural
Don't abbreviate names unless its really obvious (int rng) as it makes your code harder to read. I had to guess that this stands for "random number generator", but even unabbreviated its not named correctly - it is the value returned by the generator, not the generator itself. Personally I'd probably have called it index
Why the underscore in string _result? its a common convention in some codebases to prefix class variables with an underscore as a way of distinguishing them, but this is a local variable.
C# code doesn't typically use underscores to separate words in identifier names, so your namespace looked a little out of place to me

Style

Style points are usually controversial so others might not agree with the observations I've made. Look into the point, research the opinions that are out there and form your own opinion. Once you have done this make sure you are always consistent.

You don't brace single-line if statements. Many programmers (including me) consider this to be poor practice - have a look at this
Number literals within code blocks are known as magic numbers which is a practise which is generally discouraged because they make the code harder to read. For example with (bonus <= 3) it is not really clear to the casual reader what the significance of the number '3' is. Is it the age of mum's recently purchased second hand car? The temperature that day? Give a magic number meaning by defining it as a class constant outside the method. This also means that if this number changes at a later date, the change only needs to be made in one place, reducing the possibility of errors.

public class Program {
    private const int MumsBirthday = 3;

    public bool IsItMumsBirthday(int dayOfMonth) {
        return dayOfMonth == MumsBirthday;
    }
}

Simplifications

public static string RandomCompliment() can just return compliment[rng]; rather than saving it into a variable and returning that
BonusCompliment() doesn't need the if/else. Just use return bonus <= 3

Misc

Using labels and the goto keyword is generally frowned upon in most programming languages that implement it - you can google for a fair bit of discussion on this point. As with all these kind of 'rules of thumb', if you think you have found a genuine use case that can't be better represented with other language constructs, by all means use goto. Typically though, the behaviour you are trying to implement is done with do/while like this

bool wantsMoreCompliments = true;
while(wantsMoreCompliments) {
    string answer = null;
    do {
        if(answer != null) {
            // Write error message to console
        }
        answer = Console.ReadLine()
    } while(answer != "yes" && answer != "no")
    // Do something with answer
    // Decide if wantsMoreCompliments
}

Its also worth noting that the use of goto here effectively turns your while loop into an if block - there is never going to be an instance where it loops more than once, since it gets to the end and simply jumps out of the loop.
in public static string RandomCompliment() you create an array of compliment strings. In most situations you will handle as a beginner, sequences of objects should be represented by a List<T> data structure rather than an array. For some more detailed discussion on this topic see here.
Consider using a collection initialiser for the compliments list as this is much less verbose than the way you have done it:

List<string> compliments = new List<string> {
    "Your hair smells nice",
    "Your face is ok I guess"
    // More compliments
};

Edit

In answer to your question about how to use the list with the random number generator, you would do it like this:

assuming compliments is the list we defined above:

int index = number.Next(compliments.Count);
return compliments[index];


Asynchronously wait for a task to complete and do some async action while waiting

public delegate Task AsyncAction();

Instead of creating a custom delegate type, you could just reuse Func<Task> (even though logically, it is an action and not a function).

return Task.FromResult(true);

Consider adding an overload that takes a non-async onTimeout delegate, so that this confusing code wasn't required.

Or, if you do something like this often, have some TaskEx.Completed, or something like that.

Otherwise, good job. I especially like that you remembered to use ConfigureAwait(false) everywhere.


In dequeue, you do this:

pop everything from main and push to helper
pop one from helper
pop everything from helper and push to main

Basically moving all elements, twice.

You can do better:

if helper is empty: pop everything from main and push to helper
pop one from helper

This will significantly reduce the number of times elements are moved.

Don't forget to adjust isEmpty accordingly.


Print 10 × 10 square of X and O characters, split diagonally

Lots of answers already, but most of them seem to be about alternative solutions. I'll review your code on the details and show you how to refactor your code step by step. (This is a long answer, link to bottom of answer)

String s = new String();

Creating a new String could be simplified to "". The only time you'll actually use the String constructor is for creating strings from arrays like char[] or byte[].

The first line of output

for(int i = 0; i < 10; i++)
{
    s  += "X";
    for(int j = 0; j < 9; j++)
    {
        if(i == 0)
        {

            s += "O";
        }

Seems simple enough. Add an X, then add 9 O's.

The second line of output

for(int i = 0; i < 10; i++)
{
    s  += "X";
    for(int j = 0; j < 9; j++)
    {

        if(i == 1)
        {

            if(ft == true)
            {
                s+="X";
                ft = false;
            }
            if(j == 8)
            {
                continue;
            }
            s += "O";
        }

ft starts off true. Like that, you'll print 1 X, then enter the j loop, add one more X, then an O, and you loop from there to add the remaining characters. This leads to the problem that you have one character extra... so you have to add the j == 8 check to stop the algorithm from printing a line with 10 characters.

You can check boolean conditions without an equality operator, like so:

if(ft)
{
    s+="X";
    ft = false;
}

This will work just as well as the ft == true check.

The third line of output

for(int i = 0; i < 10; i++)
{
    s  += "X";
    for(int j = 0; j < 9; j++)
    {

        if(i == 2)
        {

            if(ft == true)
            {
                s+= "XX";
                ft = false;

            }

            if(j == 7)
            {

                break;
            }
            s += "O";

        }

Same as the second line, except here you add two X on the first iteration, and to compensate, you break one iteration earlier. This is kind of problematic, since you now have to duplicate your code for each iteration. You're missing out on the power of the for-loop.

Did you know Strings come with a length() method? You can retrieve the current length with it.

We can use that method to change the for loop so that each iteration adds just one character.

        if(i == 2)
        {

            if(ft == true)
            {
                s+= "XX";
                ft = false;

            }

            if(j == 7)
            {

                break;
            }
            s += "O";

        }

If we use the length() method here to determine ft...

        if(i == 2)
        {
            if(ft == true)
            {
                s+= "XX";
                ft = s.length() < 3;
            }

            if(j == 7)
            {

                break;
            }
            s += "O";

        }

Then we can change the code so that it only adds one character at a time, removing the condition that was added to prevent going over 10 characters.

        if(i == 2)
        {
            if(ft == true)
            {
                s+= "X";
                ft = s.length() < 3;
            }
            else
            {
                s += "O";
            }
        }

We could copy this change for all cases...

        if(i == 3)
        {
            if(ft == true)
            {
                s+= "X";
                ft = s.length() < 4;
            }
            else
            {
                s += "O";
            }
        }

but that seems like we're still duplicating code.

Fortunately, it seems we can make use of the fact that... if i == n, then the check needs to be s.length() < n + 1.

So let's apply that change.

        if(i == 3)
        {
            if(ft == true)
            {
                s+= "X";
                ft = s.length() < (i + 1);
            }
            else
            {
                s += "O";
            }
        }

Now all the cases look like this:

        if(i == 2)
        {
            if(ft == true)
            {
                s+= "X";
                ft = s.length() < (i + 1);
            }
            else
            {
                s += "O";
            }
        }

        if(i == 3)
        {
            if(ft == true)
            {
                s+= "X";
                ft = s.length() < (i + 1);
            }
            else
            {
                s += "O";
            }
        }

Seems like we can merge the cases i == 1 through i == 9 because they're all the same. And since i only goes to 9 because of the i < 10 condition, all we're interested in is checking that it's not the first iteration:

        if(i != 0)
        {
            if(ft == true)
            {
                s+= "X";
                ft = s.length() < (i + 1);
            }
            else
            {
                s += "O";
            }
        }

Here's where we're at now.

boolean ft = true;

String s = "";
for(int i = 0; i < 10; i++)
{
    s  += "X";
    for(int j = 0; j < 9; j++)
    {
        if(i == 0)
        {

            s += "O";
        }

        if(i != 0)
        {
            if(ft)
            {
                s+= "X";
                ft = s.length() < (i + 1);
            }
            else
            {
                s += "O";
            }
        }

    }
    System.out.println(s);
    s = "";
    ft = true;

}

Now... if we modified the setting of ft to do the s.length() < (i + 1) check before we tried to add a new character to the line, we could even merge the i == 0 case.

for(int i = 0; i < 10; i++)
{
    s  += "X";
    for(int j = 0; j < 9; j++)
    {
        ft = s.length() < i;
        if(i == 0)
        {

            s += "O";
        }

        if(i != 0)
        {
            if(ft)
            {
                s += "X";
            }
            else
            {
                s += "O";
            }
        }

    }
    System.out.println(s);
    s = "";
    ft = true;

}

Now, in the case i == 0, ... you enter the j-for loop with one "X" in your string already. So ft would be set to false, always. And in the i != 0 case, if ft is not true... we do the same thing as the i == 0 case. So we can remove the checks whether i is or is not 0, as it will work just fine:

for(int i = 0; i < 10; i++)
{
    s  += "X";
    for(int j = 0; j < 9; j++)
    {
        ft = s.length() < i;
        if(ft)
        {
            s += "X";
        }
        else
        {
            s += "O";
        }
    }
    System.out.println(s);
    s = "";
    ft = true;

}

Now that we've made that change, the code is short. But it's not that clear yet. ft is a pretty meaningless variable. If we renamed it to notEnoughXYet, the code becomes a bit more clearer:

boolean notEnoughXYet = true;

String s = "";
for(int i = 0; i < 10; i++)
{
    s  += "X";
    for(int j = 0; j < 9; j++)
    {
        notEnoughXYet = s.length() < i;
        if(notEnoughXYet)
        {
            s += "X";
        }
        else
        {
            s += "O";
        }
    }
    System.out.println(s);
    s = "";
    notEnoughXYet = true;

}

... We can still go further, though.

There are two places we set notEnoughXYet to true and s to "". Maybe we can merge them?

What about putting it at the start of each iteration of the i for loop?

for(int i = 0; i < 10; i++)
{
    boolean notEnoughXYet = true;

    String s = "";
    s  += "X";
    for(int j = 0; j < 9; j++)
    {
        notEnoughXYet = s.length() < i;
        if(notEnoughXYet)
        {
            s += "X";
        }
        else
        {
            s += "O";
        }
    }
    System.out.println(s);
    s = "";
    notEnoughXYet = true;

}

Like this, we see that we can eliminate some more duplication: the setting of s and notEnoughXYet at the bottom can disappear. And s could be initialized to X.

for(int i = 0; i < 10; i++)
{
    boolean notEnoughXYet = true;
    String s = "X";
    for(int j = 0; j < 9; j++)
    {
        notEnoughXYet = s.length() < i;
        if(notEnoughXYet)
        {
            s += "X";
        }
        else
        {
            s += "O";
        }
    }
    System.out.println(s);
}

You could even move notEnoughXYet to the inner for loop...

for(int i = 0; i < 10; i++)
{
    String s = "X";
    for(int j = 0; j < 9; j++)
    {
        boolean notEnoughXYet = s.length() < i;
        if(notEnoughXYet)
        {
            s += "X";
        }
        else
        {
            s += "O";
        }
    }
    System.out.println(s);
}

Or get rid of it entirely.

for(int i = 0; i < 10; i++)
{
    String s = "X";
    for(int j = 0; j < 9; j++)
    {
        if(s.length() < i)
        {
            s += "X";
        }
        else
        {
            s += "O";
        }
    }
    System.out.println(s);
}

There's still a double setting of X to s, though. If you wanted to change the characters you'd have to change it in two places. Maybe you should just make the inner loop also do 10 iterations?

for(int i = 0; i < 10; i++)
{
    String s = "";
    for(int j = 0; j < 10; j++)
    {
        if(s.length() <= i)
        {
            s += "X";
        }
        else
        {
            s += "O";
        }
    }
    System.out.println(s);
}

Note that I have changed the s.length() < i to s.length() <= i because now the first iteration also needs to put an X.

The result

What we've just done, is step for step, identifying duplication or similarities, and then looking for the differences in that duplication to merge the duplication. The end result is code which, whilst containing more complexity because it doesn't spell out each case individually, is considerably shorter and should be more understandable.


It's generally a good idea to remove duplication wherever possible. If you have two functions that are logically similar, but don't share code, you run the risk of code rot - updating one function and forgetting to apply similar changes to the other.

There are a few ways I would suggesting working around this without sacrificing too much readability.

Find common parts of each function and refactor them out into their
own sub-functions
Use higher-order functions to inject the unique
logic into a more generic base function

I hardly know Javascript at all, so I can't be too specific on how to handle this case, but it looks like you only have a very small amount of code that isn't shared.

if (statics.timeout_id) {
    clearTimeout(statics.timeout_id); // fade
    clearInterval(statics.timeout_id); // fadeL
}

// .. snip ..

// Added in fadeL
if (!statics.timeout_id) {
    statics.timeout_id = setInterval(next, statics.granularity);
}

// .. snip ..

if (statics.elapsed < max_time) { // fade
if (statics.elapsed > max_time) { // fadeL
    statics.timeout_id = setTimeout(next, statics.granularity); // fade
    clearInterval(statics.timeout_id); // fadeL
}

A really simple approach would be to make a base function that accepts a boolean value to differentiate between the slight changes in behavior:

NS.prototype.base_fade = function (direction, max_time, is_fade_l) {
    var statics = {},
        elements = this;
    statics.elapsed = 0;
    statics.granularity = 10;
    if (statics.timeout_id) {
        if (is_fade_l) {
            clearInterval(statics.timeout_id);
        } else {
            clearTimeout(statics.timeout_id);
        }
    }
    (function next() {
        var kindex,
            opacity;
        statics.elapsed += statics.granularity;
        if (is_fade_l && !statics.timeout_id) {
            statics.timeout_id = setInterval(next, statics.granularity);
        }
        if (direction === 'up') {
            for (kindex in elements) {
                if (elements.hasOwnProperty(kindex)) {
                    opacity = statics.elapsed / max_time;
                    elements[kindex].style.opacity = opacity;
                }
            }
        } else if (direction === 'down') {
            for (kindex in elements) {
                if (elements.hasOwnProperty(kindex)) {
                    elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
                }
            }
        }
        if (is_fade_l) {
            if (statics.elapsed > max_time) {
                clearInterval(statics.timeout_id);
            }
        } else {
            if (statics.elapsed < max_time) {
                statics.timeout_id = setTimeout(next, statics.granularity);
            }
        }
    }());
};

Then call that function from fade and fadeL providing the correct boolean. This way, at least, you have a guarantee that the code that is logically the same will stay the same. It also takes up less space in your codebase, and doesn't require all that much more parsing to understand it mentally.

You might be able to get more modular with this, and refactor some elements out into their own functions, but my own lack of knowledge of the language and the codebase means I'm not quite up to suggesting those changes. In general though, try to consolidate logically equivalent code wherever you can. It will make your life easier in the long run.


Python program that obfuscates an email address

The code is straightforward and reads well, but:

string concatenation is not very efficient, especially in a loop. You'd be better off using str.join on an iterable;
encoding the mailto: part yourself impairs readability and maintenance, if only you had a function to do it for you. Oh wait...
The comment at the beginning would be better as a module docstrings, you would then be able to use it as the argparse description using __doc__;
You should avoid interleaving code and function definition, and protect top level code using an if __name__ == '__main__': guard.

Proposed improvements:

#!/usr/bin/python

"""Convert a string into its HTML entities"""

import argparse

def command_line_parser():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('string_to_mung', help='String to convert')
    parser.add_argument('-l', '--link', action='store_true',
                        help='Embed the munged string into a mailto: link')
    return parser

def mung(plain):
    return ''.join('&#{};'.format(ord(c)) for c in plain)

if __name__ == '__main__':
    args = command_line_parser().parse_args()
    string_munged = mung(args.string_to_mung)
    if (args.link):
        string_munged = '{1}'.format(mung('mailto:'), string_munged)
    print(string_munged)


Project Euler 62: cubic permutations, logic

Return Value

The question is asking for the smallest cube (127035954683), your code returns the list of values whose cubes permute to that ([5027, 7061, 7202, 8288, 8384]), so it's technically wrong.

Signature

The problem as described suggests a function that takes a single argument as input: the number. You additionally require a limit. What's the limit for? How do you know that the limit you picked isn't too small? You happen to pick a good limit, but what if we needed to go up in digits? What if we wanted to find the smallest cube with 7 permutations?

try/catch

You have this code:

try:
    return choosen
except:
    return 0

It took me a lot of squinting to actually realize what it is you were catching. Ohhh... NameError on choosen. And then you have the same thing in the interior - you're catching not an exception but an undefined name. That is awkward code to understand.

First, you can just up-front declare choosen = 0, that lets you drop the last try/except block completely.

Next, you can up-front declare minimal to be None and change that block to be:

if minimal is None or temp_minimal < minimal:
    minimal = temp_minimal

Or you could declare minimal to be sys.maxint. Also there, you're assigning to a variable named min_cand but never reading it, so not sure what that is for.

Algorithm

I think you're overthinking the problem somewhat. You have the right approach with keeping track of a dictionary with the sorted permutation. But then you kind of lose me with the digit counting. I chuckled at the_one = chosen(...), but I have no idea what that function is doing.

Here's my thoguht process. When our count for a particular permutation reaches the goal count, we have to verify that there aren't any future cubes that would end up here. That remark is correct. However, we know exactly which things we need to test - so we should just explicitly test those:

To start with:

def my_cube_perm(num_perms):
    def as_str(x):
        return ''.join(sorted(str(x)))

    counts = collections.defaultdict(int)
    smallest = {}

    for i in itertools.count(start=1): # no limit!
        cube = i**3
        cube_str = as_str(i**3)
        counts[cube_str] += 1
        smallest.setdefault(cube_str, cube)

        if counts[cube_str] == num_perms:
           # ok what, now?

The next smallest possible cube that could produce cube_str is i+1. The largest possible cube that produce it comes from reverse-sorting cube_str and taking its cube root. So just walk that range:

max_possible = int(int(''.join(reversed(cube_str)))**(1/3.))
if not any(as_str(p**3) == cube_str
           for p in xrange(i+1, max_possible+1)):
    return smallest[cube_str]

This is ~2.3x faster (38ms vs 87ms), but more importantly I think is easier to follow the logic and is much shorter.

Algorithm Update

N3buchadnezzar makes a good point in that the first solution I found isn't necessarily the smallest. We could have 5 permutations of one cube all fall in between the first and next 4 permutations of another. So we have to keep track of some more state. If we find a value that we think is the answer - we save it and the length of its cube. Once we get to a cube with more digits, if we have anything saved, return at that point.

Full solution looks like this:

def my_cube_perm(num_perms):
    def as_str(x):
        return ''.join(sorted(str(x)))

    counts = collections.defaultdict(int)
    smallest = {}

    best = None
    best_len = 0

    for i in itertools.count(start=1):
        cube = i**3
        cube_str = as_str(cube)

        # got an answer that is definitely shorter?
        if best is not None and len(cube_str) > best_len:
            return best

        counts[cube_str] += 1
        smallest.setdefault(cube_str, cube)

        if counts[cube_str] == num_perms:
            # check all the possibilities!
            max_possible = int(int(''.join(reversed(cube_str)))**(1/3.))
            if not any(as_str(p**3) == cube_str
                       for p in xrange(i+1, max_possible)):
                # update our best solution - if appropriate
                if best is None or smallest[cube_str] < best:
                    best = smallest[cube_str]
                    best_len = len(cube_str)

This increases runtime to 46ms. But then again, runtime of an incorrect algorithm doesn't really matter. And still ~1.9x faster.


Forming error messages from a multidimensional associative array

In my opinion, this code is all right.  As any explicit code, these loops are quite straightforward to follow. And making it more concise will likely make it more cryptic as well. I would only make a minor brush-up, removing the unnecessary default clause and make the proper indentation. Variable interpolation is also more natural to read, in my opinion.

Also, variables must be explicitly initialized, just a mention is not enough. If you need an empty array then you must initialize an empty array. Although in the present code the $errors variable doesn't exist before the loop, the code could evolve over time, and there could be the possibility that a variable with the same name will be used above. If you just mention it, as $errors; it will keep the previous value. If you initialize it as $errors = []; you will always know it's an empty array.

function generateErrorMessages($e)
{
    $errors = [];
    foreach ($e as $type => $array)
    {
        foreach ($array as $key => $values)
        {
            foreach ($values as $v)
            {
                switch($type)
                {
                    case 'invalid':
                        $errors[$type][$key][] = "$v is not a valid $key";
                        break;
                    case 'missing':
                        $errors[$type][$key][] = "$v is a required $key - other functions have dependencies on it";
                        break;
                }
            }
        }
    }
    return $errors;
}


Making a package for a one-class program seems like overkill.  You would be better off naming the class AreaCalculator, which would be more meaningful than Main.

Instead of writing the menu as a very long string, it would be more manageable to split it:

System.out.println("Welcome to the Area Calculator! " +
    "Enter 1 to find the area of a Rectangle, " +
    "Enter 2 to find the area of a Square, " +
    "Enter 3 to find the area of a Triangle or " +
    "Enter 4 to find the area of a Circle");

(This has no effect on performance.  The compiler will embed just one long string constant in the bytecode.)

A chain of if-elses would be better written using a switch block.  Not only is it easier to see the patten at a glance, it is also more efficient, in that it compiles to a single tableswitch opcode.

Since there are so many places where you write System.out.println() followed by scanner.nextInt(), it makes sense to write a function for that.  Should you later decide to add validation and error handling, you can implement it in one central place.  I suggest changing System.out.println() to System.out.print().

I don't see any reason why the inputs should be restricted to ints.  You could just as easily accept doubles.

I recommend splitting each calculation into a separate function, to ensure that they do not interfere with each other.  For example, if you were to add support for parallelograms and trapezoids, you might have a conflict for a variable named height, if you lumped everything into main().  The resulting main() would be just a menu.

import java.util.Scanner;

public class AreaCalculator {
    private static double ask(Scanner scanner, String prompt) {
        System.out.print(prompt);
        return scanner.nextDouble();
    }

    private static void rectangle(Scanner scanner) {
        double length = ask(scanner, "Please enter the length of the rectangle: ");
        double width = ask(scanner, "Please enter the width of the rectangle: ");
        System.out.println(length * width);
    }

    private static void square(Scanner scanner) {
        double lengthOfASide = ask(scanner, "Please enter the length of a side: ");
        System.out.println(lengthOfASide * lengthOfASide);
    }

    private static void triangle(Scanner scanner) {
        double triangleBase = ask(scanner, "Please enter the base of the triangle: ");
        double triangleHeight = ask(scanner, "Please enter the height of the triangle: ");
        System.out.println(0.5 * triangleBase * triangleHeight);
    }

    private static void circle(Scanner scanner) {
        double radius = ask(scanner, "Please enter the radius of the circle: ");
        System.out.println(Math.PI * (radius * radius));
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to the Area Calculator! " +
            "Enter 1 to find the area of a Rectangle, " +
            "Enter 2 to find the area of a Square, " +
            "Enter 3 to find the area of a Triangle or " +
            "Enter 4 to find the area of a Circle");

        switch (scanner.nextInt()) {
          case 1:
            rectangle(scanner);
            break;
          case 2:
            square(scanner);
            break;
          case 3:
            triangle(scanner);
            break;
          case 4:
            circle(scanner);
            break;
        }
    }
}


Two comments:

The existing code only checks for free ports under 8081.  The full range is 0-65535.
You're only checking the IPv4 definition of 'localhost'.  We live in the future! IPv6 calls localhost ::1.  At first blush, this would seem to not matter - something's either listening or not, right? - but it turns out that firewalls sometimes have different rulesets for IPv4 vs IPv6, so one may get through but the other not.  You didn't specify what this code was for, so it's just a caveat to keep in mind.


Group by consecutive values in first column and second column value

In your code, you are checking for changes in a vector or for the differences between consecutive elements of a vector by using lag and then cleaning up the introduced NA value. When looking for changes, I would find it cleaner to handle the first element separately, which enables you to do the operation in a single line of code. For differences in timestamp, diff would make everything a lot cleaner:

metrics <- metrics %>%
  mutate(typing_episode = cumsum(c(1, head(package_name, -1) != tail(package_name, -1)))) %>%
  group_by(typing_episode) %>%
  mutate(second_group = cumsum(c(1, diff(timestamp) > 1000 * 60 * 3)),
         typing_episode2 = typing_episode * 1000 + second_group)
print(metrics)

As you note, typing_episode2 might have repeats if second_group can exceed 1000. A reasonable alternative might be to do something like typing_episode2 = paste0(typing_episode, "_", second_group). Then you won't need to worry about non-unique typing_episode2 values.


Code with many "early returns (exits)" into the functional style

After reading the code, I assume these are the signatures of the building blocks of your code

class IdInfo
class PasswordInfo
class ConnectionInfo

def calcIdInfo:IdInfo=???
def calcPwdInfo(idInfo:IdInfo):PasswordInfo=???
def calcConnInfo(idInfo:IdInfo,pwdInfo:PasswordInfo):PasswordInfo=???

I left out the implementations for the calc as they don't really matter.

There are several possible variations to improve on the current code. Let's have a look at the last call to  map in connect  :

 connInfoOpt map (connInfo => {
    try {
      verify(idInfo, pwdInfo, connInfo)
      Some(idInfo, pwdInfo, connInfo)
    } catch {
      case ex: IOException => None
      case ex: AuthorizationException => None
    }
  }) getOrElse None

The try expression has type Option[(IdInfo, PasswordInfo, ConnectionInfo)] which is the type you want as the output of the function connect. As the name connInfoOpt suggests, it is also an option. Map on option has a signature roughly equivalent to :

map(f:A=>B):Option[B]

Where A is the type which is wrapped in the original option, and B is the type wrapped in the resulting option.

Thus let's say connInfoOpt has type Option[ConnectionInfo] we get

A = ConnectionInfo
B = Option[(IdInfo, PasswordInfo, ConnectionInfo)]

Therefore the return type of the map expression is Option[B] which can be expanded to

Option[Option[(IdInfo, PasswordInfo, ConnectionInfo)]]

Here lies the first problem : to get the Option[(IdInfo, PasswordInfo, ConnectionInfo)] out, you use getOrElse None. A slightly shorter way to express that is to call flatten.

The original expression can thus be rewritten as:

 connInfoOpt map (connInfo => {
    try {
      verify(idInfo, pwdInfo, connInfo)
      Some(idInfo, pwdInfo, connInfo)
    } catch {
      case ex: IOException => None
      case ex: AuthorizationException => None
    }
  }) flatten

which has type Option[(IdInfo, PasswordInfo, ConnectionInfo)]. The next step is to study the option type and see that it has a flatMap method which has the following signature :

flatMap(f:A=>Option[B]):Option[B]
// for comparison with map which was
map(f:A=>B):Option[B]

Then notice that each intermediary is step is of the form  :

option map { A=> Option[B] } flatten

for instance:

connInfoOpt map (connInfo => {
  try {
    verify(idInfo, pwdInfo, connInfo)
    Some(idInfo, pwdInfo, connInfo)
  } catch {
    case ex: IOException => None
    case ex: AuthorizationException => None
  }
}) flatten

can be rewritten as :

connInfoOpt flatMap (connInfo => {
  try {
    verify(idInfo, pwdInfo, connInfo)
    Some(idInfo, pwdInfo, connInfo)
  } catch {
    case ex: IOException => None
    case ex: AuthorizationException => None
  }
})

Which means the whole function can now be simplified to :

 def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {
    val idInfoOpt = try {
      Some(calcIdInfo())
    } catch {
      case ex: IOException => None
    }

    idInfoOpt flatMap (idInfo => {
      val pwdInfoOpt = try {
        Some(calcPwdInfo(idInfo))
      } catch {
        case ex: AuthorizationException => None
      }

      pwdInfoOpt flatMap (pwdInfo => {
        val connInfoOpt = try {
          Some(calcConnInfo(idInfo, pwdInfo))
        } catch {
          case ex: IOException => None
        }

        connInfoOpt flatMap (connInfo => {
          try {
            verify(idInfo, pwdInfo, connInfo)
            Some(idInfo, pwdInfo, connInfo)
          } catch {
            case ex: IOException => None
            case ex: AuthorizationException => None
          }
        })
      })
    })
  }

We got rid of the 3 getOrElse but this still isn't so nice. Let's extract a few methods next to make the code easier to read :

def safeIdInfo():Option[IdInfo]={
  try {
    Some(calcIdInfo())
  } catch {
    case ex: IOException => None
  }
}

def verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {
  try {
    verify(idInfo, pwdInfo, connInfo)
    Some(idInfo, pwdInfo, connInfo)
  } catch {
    case ex: IOException => None
    case ex: AuthorizationException => None
  }
}

def safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Option[ConnectionInfo] = {
  try {
    Some(calcConnInfo(idInfo, pwdInfo))
  } catch {
    case ex: IOException => None
  }
}

def safePwdInfo(idInfo: IdInfo): Option[PasswordInfo] = {
  try {
    Some(calcPwdInfo(idInfo))
  } catch {
    case ex: AuthorizationException => None
  }
}

then the connect method looks like :

def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {
  safeIdInfo() flatMap (idInfo =>
    safePwdInfo(idInfo) flatMap (pwdInfo=>
      safeConnInfo(idInfo, pwdInfo) flatMap (connInfo =>
        verifyConnInfo(idInfo, pwdInfo, connInfo)
      )
    )
  )
}

Which is better but not perfect. Let's apply some scala syntactic sugar :

def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {
  for{
    idInfo   <- safeIdInfo()
    pwdInfo  <- safePwdInfo(idInfo)
    connInfo <- safeConnInfo(idInfo, pwdInfo)
    verified <- verifyConnInfo(idInfo, pwdInfo, connInfo)
  } yield verified
}

The connect method is much better (I think) but we end up with repetition in the "safe" methods. Actually, Scala offers a type to reduce this duplication, the Try type which we will use to replace the Option type in the "safe" methods :

def verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Try[(IdInfo, PasswordInfo, ConnectionInfo)] = Try {
  verify(idInfo, pwdInfo, connInfo)
  (idInfo, pwdInfo, connInfo)
}
def safeIdInfo():Try[IdInfo]=Try(calcIdInfo())
def safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Try[ConnectionInfo] = Try(calcConnInfo(idInfo, pwdInfo))
def safePwdInfo(idInfo: IdInfo): Try[PasswordInfo] = Try(calcPwdInfo(idInfo))

Of course doing this, the connect method is no longer valid at the type level it needs to be adapted. To match the exact behavior of the original code the adaptation will look like :

  def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {
    val tryVerified = for{
      idInfo <- safeIdInfo()
      pwdInfo <-  safePwdInfo(idInfo)
      connInfo <- safeConnInfo(idInfo, pwdInfo)
      verified <- verifyConnInfo(idInfo, pwdInfo, connInfo)
    } yield verified

    tryVerified match {
      case Success(value) => Some(value)
      case Failure(authException:AuthorizationException)=> None
      case Failure(ioException:IOException)=> None
      case Failure(failed)=> throw failed
    }
  }

However I will suppose that you don't really want to rethrow unknown runtime exceptions and instead want to return None for any error, in which case the following form of connect should work :

  def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {
    val tryVerified = for{
      idInfo <- safeIdInfo()
      pwdInfo <-  safePwdInfo(idInfo)
      connInfo <- safeConnInfo(idInfo, pwdInfo)
      verified <- verifyConnInfo(idInfo, pwdInfo, connInfo)
    } yield verified

    tryVerified.toOption
  }

The complete code is now :

 def verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Try[(IdInfo, PasswordInfo, ConnectionInfo)] = Try {
    verify(idInfo, pwdInfo, connInfo)
    (idInfo, pwdInfo, connInfo)
  }
  def safeIdInfo():Try[IdInfo]=Try(calcIdInfo())
  def safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Try[ConnectionInfo] = Try(calcConnInfo(idInfo, pwdInfo))
  def safePwdInfo(idInfo: IdInfo): Try[PasswordInfo] = Try(calcPwdInfo(idInfo))

  def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {
    val tryVerified = for{
      idInfo <- safeIdInfo()
      pwdInfo <-  safePwdInfo(idInfo)
      connInfo <- safeConnInfo(idInfo, pwdInfo)
      verified <- verifyConnInfo(idInfo, pwdInfo, connInfo)
    } yield verified

    tryVerified.toOption
  }

Using the right types, a functional style and some syntactic sugar can go a long way to simplify your code :)

For further reference, check the scala doc for Option and Try, also check out the FAQ on yield for more explanations on the for-expression syntactic sugar.


Searching all diagonals of a 2D M x M array

This reminds me of what I wrote a while ago for my Tic Tac Toe Ultimate game.

In case I get anything wrong, here is a relevant part of my original code:

// Scan diagonals for a winner: Bottom-right
for (int yy = 0; yy < board.getSizeY(); yy++) {
    newWin(conds, consecutive, loopAdd(board, 0, yy, 1, 1));
}

private static List<Winnable> loopAdd(HasSub<? extends Winnable> board,
        int xx, int yy, int dx, int dy) {
    List<Winnable> winnables = new ArrayList<>();

    Winnable tile;
    do {
        tile = board.getSub(xx, yy);
        xx += dx;
        yy += dy;
        if (tile != null)
            winnables.add(tile);
    }
    while (tile != null);

    return winnables;
}

When making this in C#, you can return IEnumerable<char>. The idea of the method is to start at a specific point and to iterate until you're outside the valid area.

I think it's a bad idea that you're currently using String concatenation first, and then checking if the string contains the char. Instead you can indeed as Carsten points out in the comments use a state machine for that. It only needs to be about an int really that keeps track of how many consecutive matches you've had so far, and when it reaches a non-match it starts over at zero. When it reaches the string length, it returns true.

Anyways, back to the main part, here's what I would try to do:

private IEnumerable<char> loopOver(string[] board,
        Point position, Point delta) {

    char value;
    while (true) {
        if (!charIsInsideBoard(board, position))
            break;

        value = getCharInBoard(board, position);
        position.x += delta.x;
        position.y += delta.y;
        yield return value;
    }
}

Whenever I'm using C#, I love using the wonderful yield keyword.

private boolean contains(IEnumerable<char> loop, string searchFor) {
    int matches = 0;
    foreach (char ch in loop) {
        if (ch == searchFor[matches]) {
             matches++;
        }
        else {
             matches = 0;
             if (ch == searchFor[matches]) {
                 matches++;
             }
        }
        if (matches == searchFor.Length) {
             return true;
        }
    }
    return false;
}

Then in your allDiagonals method (which really could be renamed to searchAllDiagonals) all you need to do is to call the contains and loopOver methods a couple of times.

boolean searchAllDiagonals(string[] board, string searchFor)
{
    boolean result = false;
    for (int i = 0; i < board[0].Length; i++) {
        result = result || contains(loopOver(board, new Point(i, 0), new Point(1, 1), searchFor);
    }
    for (int i = 0; i < board.Length; i++) {
        result = result || contains(loopOver(board, new Point(0, i), new Point(1, 0), searchFor);
    }
    ...
}

Please note that I have not tested this code, and as I haven't done any C# development since last time I might have mixed something up. I also might have mixed up X and Y, but that happens for me in Java too every now and then.

Other Suggestions:

Don't use i and j when you're using nested loops. row and col are so much better, or x and y. I myself use xx and yy sometimes for loops when I already have another x / y variable.
As your variable is named board, what do I know, perhaps your whole point is to check for a winner in a Tic Tac Toe game. If a game is your context, then I'd recommend not using string[]. Use a BoardField[][] variable instead, or preferably wrap such a 2D array in a Board class (which can contain the charIsInsideBoard and getCharInBoard methods).


When all you have is a hammer, every problem looks like a nail.

You're trying to do something with code, that's not the code's job. Delete all this code and tackle the problem at the root: make sure your code runs with the appropriate permissions.
It's that simple.
-- My humble opinion

Deleting folders is a risky business

Indeed! If your running code doesn't have permission to wipe out your hard drive, you have some exceptions to deal with, i.e. you should wrap I/O calls in a try...catch block.


Refactor module for calls to internal image service

// Store everything in a scope. It's to preven you from polluting the global
// scope as well as protect your code from collisions.
;(function(ns) {

  // Pulling out constants into this scope. They only need to be declared once.
  var imgSvcPath = './imageSizer.svc';
  var defaults = {
    type: null,
    src: '',
    width: 120,
    height: null
  };

  function configureImg(options) {
    var options = options || {};
    var presets = options.type ? Images.getPresets(options.type) : {};

    // It's best if you extend to a blank object. Don't override the defaults.
    return $.extend({}, defaults, options, presets);
  }

  function buildResourcePath(svcName, options) {

    var conf = configureImg(options);

    // I assume you use jQuery because of $.extend so I introduce $.param
    // which takes a map and converts it into a serialized parameter list

    var params = {};

    // And ternaries can be very messy and unreadable. Now using if-else instead.
    if (conf.skuId !== undefined) params.sku = conf.skuId;
    else params.path = conf.src;

    if (conf.height) params.size = 'h|' + conf.height;
    else params.size = 'w|' + conf.width;

    if (conf.quality) params.quality = conf.quality;

    return imgSvcPath + '?' + $.param(params);
  }

  // Let's append our API to the namespace

  ns.getSizedUrl = function(options) {
    if ('undefined' === typeof options.src) {
      console.error('upi.Services.Image::getSizedUrl configuration options must provide an image src string')
    }
    return buildResourcePath('GetResizedImage', options)
  };

  ns.getSizedUrlForSku = function(skuId, options) {
    if ('undefined' === typeof skuId) {
      console.error('upi.Services.Image::getSizedSkuUrl configuration options must provide sku ID')
    }
    options = options || {};
    options['skuId'] = skuId;
    return buildResourcePath('GetResizedSkuImage', options)
  };

  // Change your namespace to something else. Image is already taken.
  // Image is the constructor for making image elements with JS.
}(this.MyImage = this.MyImage || {}))


Goto

Honestly, I didn't even know that PHP supported labels and goto. But this is how the manual for PHPs goto starts:

If you don't have a very good reason to use goto, just don't use it. It generally leads to bad code.

What you have is basically this:

if(strpos(URL,'error/'))
    goto start;

// init database

start:
    // init app

Or in other words:

if error:
    do not start database connection

start program

So you can rephrase your confusing goto statement like this:

if(!strpos(URL,'error/')) {
    initDatabase();
}

initApp();

function initDatabase() {
    // Connection::set(...)
}

function initApp() {
    // start session, call dispatcher, etc
}

Formatting

You should always use curly brackets, even for one-line statements. If you absolutely think that you need to omit them (you don't), be consistent. This for example isn't easy to read:

if(!PROD){ //if the app is online PROD=TRUE
    throw $e;

}else
    header('location: '.WEBROOT.'error/503/',503);

exit;

But something like this also isn't clear at first glance:

if(strpos(URL,'error/'))
    goto start;
try{

At the very least add a new paragraph. But really, curly brackets are the right thing here.

header redirect

In your case it isn't strictly necessary, but it's good practice to always die after a header redirect as a client doesn't has to follow it, so code that comes after it will be executed as well.

This may cause you problems in case you add further code later on, and expect the redirect to stop execution.

Extract

Extract is not a very good function. It's not secure to let a user have complete control over your variables, and it leads to bad code, as it's unclear what variables are defined.

Just assign the variables you need directly.

Misc

I wouldn't hard-code URLs such as your error URL. Ideally, URLs are customizable in some config file.


Accessing multiple data members in Blackjack classes

This code:

void Game::hit(unsigned playerNum)
{
    Card newCard = deck.deal();
    players[playerNum].getPlayerHand()[0].getHandCards().push_back(newCard);
}

should read:

void Game::hit(unsigned playerNum)
{
    Card newCard = deck.deal();
    players[playerNum].hit(newCard);
}

The thing is, your classes shouldn't access each other like that. You shouldn't have getter methods that return the internal vectors. You should have methods that perform operations. If you do that, I think your question won't even come up.


Dynamic programming solution to "Climbing Stairs"

The code in the post has to compute the \$i\$th Fibonacci number, \$F_i\$, for every \$i \le n\$, in order to compute \$F_n\$. It's possible to do much better than that, by using the recurrence $$ \eqalign{F_{2n−1} &= F_{n}^2 + F_{n−1}^2 \\ F_{2n} &= (2F_{n−1} + F_{n}) F_{n}} $$ combined with memoization. For example, you could use the @functools.lru_cache decorator, like this:

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    """Return the nth Fibonacci number."""
    if n <= 1:
        return n
    elif n % 2:
        a = fibonacci(n // 2)
        b = fibonacci(n // 2 + 1)
        return a * a + b * b
    else:
        a = fibonacci(n // 2 - 1)
        b = fibonacci(n // 2)
        return (2 * a + b) * b

this computes the \$10^6\$th Fibonacci number, which has more than 200,000 decimal digits, in a fraction of a second:

>>> from timeit import timeit
>>> timeit(lambda:fibonacci(10**6), number=1)
0.06556476117111742
>>> len(str(fibonacci(10**6)))
208988

By contrast, the code in the post cannot compute Solution().climbStairs(10 ** 6) without running out of memory.


First, you need to bind this to the notice function as well

this:

if(this.state.number <= 0) {
  return true;
} else {
  return false;
}

Can be written as:

this.state.number <= 0

as It will return those booleans anyway

in which case you could write:

notice() {
  const { number } = this.state

  if(number >= 10) {
    return 'You\'ve reached N° 10.';
  }

  if(number <= 0) {
    return 'You can\'t decrement. You\'re at N° 0';
  }

  return 'You can do both.';
}

Note the destructuring pattern:

const { number } = this.state
// is the same as
const number = this.state.number


An appropriate term for this code is spaghetti code – it's tightly intertwined with other parts of the app, so one cannot easily take out a part of it and reason about it without thinking about the rest of the app. Just like it's hard to pull out one single spaghetti from a bowl.

It's not inherently bad, as long as the program is really small (< 10 lines). But as your program grows, you're bound to experience that it's getting harder and harder to reason about your program and make changes in it without breaking things. You might even reach a point where you're afraid to make any changes, as things are so likely to break.

I guess one needs to go through this to really start to look for better ways of organizing the code. So don't feel bad about yourself. Everybody starts out like this. If you want to improve, look out for books like "Pragmatic programmer" or "Clean code". Or search the web for "JavaScript style guide" and "Software engineering principles".

To answer in more detail...

I find it really hard to understand what this code does:

Seems that it's been extracted out of a larger file, that could give us some context.
It calls into various functions like drawTable(), addEditValue() which aren't defined in here.
It assigns to some global variables like names and idEdit, which are also not defined in here.

Several style issues make the code hard to read:

It's sloppily indented – sometimes 4, sometimes 2 spaces, sometimes no indentation at all.
Some lines end with semicolon, others don't.
The comments are sometimes misleading, like:

// to get the current URL witout hash
const getLink = window.location.hash.slice(1)

It actually does the opposite – it returns the hash-part of the URL.
At other times the comments state what's already obvious from the code:

// listen a click on the page
top.addEventListener('click', function(e){

The name getLink looks like a function name, but it's not a function. A good style is to only name functions with verbs (as they do things).
The name data is meaningless. All variables contain data. Naming a variable data is just as helpful as naming it variable.
The name character is very confusing. Previously you pushed e.target.id to the history state (naming it data). And then in popstate you get back the history state and call it character. If it's a character, then call it so consistently in both places. But it looks like it's not just a single character, because you assign it to idEdit – so it seems to be some sort of ID instead.

Regarding your question:

  But in the part of the code with browser history I can't find a way to use jQuery, only pure JS.

That's absolutely fine. jQuery is a library for doing DOM manipulations (for interacting with the HTML on the page). You shouldn't use it for other things besides that.


I see one possible mistake in your code: you do not check if a key already exists before writting a new {Key,Value} pair. This may be intentional, but in this case I think that the read(Key,Db) should return a list of value rather than a single value.

Looking at pattern matching I think that you can simplify the code like this:

read(_Key,{db,[]})-> {error,no_instance};
read(Key,{db,[{Key,CurValue}|_Data]}) -> {ok,CurValue};
% the pattern maching can be done directly, no need to use when.
% I propose to return a tuple {ok,Value} to be consistent with the previous case
% so it will be possible to use pattern matching when using the result of read/2,
% even if the value returned is {error,no_instance}!
read(Key,{db,[_Pair|Data]}) -> read(Key,{db,Data}).
% don't need to create 2 variables

match(Element,Db) -> match(Element,Db,[]).
% transform the function to be tail recursive

match(_Element,{db,[]},R)->R;
match(Element,{db,[{CurKey,Element}|Data],R}) -> match(Element,{db,Data},[CurKey|R]);
% the pattern maching can be done directly, no need to use when.
match(Element,{db,[_Pair|Data]},R) -> match(Element,{db,Data},R).
% don't need to create 2 variables


Find a list of objects in an array with JavaScript

You could first get the index of the first element of the search array.

Then loop while index !== -1 and check all elements in the search array with the elements in the base array. For checking outside of the range of the array use the reminder operator %.

Return index if all elements are equal.

If not get a new index with indexOf and an incremented start value.

Array#every breaks the iteration if the callback returns false.

function find(search, array) {
    var index = array.indexOf(search[0]);

    while (index !== -1) {
        if (search.every(function (a, i) { return a === array[(index + i) % array.length]; })) {
            return index;
        }
        index = array.indexOf(search[0], index + 1);
    }
    return -1;
}

console.log(find([3, 4, 5], [1, 2, 3, 4, 5, 6, 7]));          //  2
console.log(find([6, 7, 1, 2], [1, 2, 3, 4, 5, 6, 7]));       //  5
console.log(find([60], [1, 2, 3, 4, 5, 6, 7]));               // -1
console.log(find([3, 4, 5], [1, 2, 3, 4, 6, 7, 3, 4, 5, 9])); //  6
.as-console-wrapper { max-height: 100% !important; top: 0; }


Spectrum Analysis with Discrete Fourier Transform

A few things:

When you have the start, endpoint and the number of steps you want in a vector then linspace is better than colon:

t = linspace(tBeg, tEnd, measurement_rate);

It's cleaner, since you don't have to calculate the length of each step.

exp( -2 .* pi .* j  .*(point_index - 1) .* (freq_index - 1) / total_freqs );

j looks like a variable, especially since you use i as a variable later on. The recommended way to denote the imaginary unit is 1i or 1j. That way it can't be confused with a variable, and you don't risk overwriting it.

You don't need .* when multiplying by scalars. It's only needed between matrices or vectors. If you only use it between matrices then it's easy to see which variables are vectors/matrices, and which are just scalars. It's now hard to tell if point_index, freq_index and/or total_freqs are scalars or matrices.

There's only one vector in that statement (point_index), so no dots are needed.

The for loop can be vectorized, which is the MATLAB way to do something like that. I don't have MATLAB at hand, so I can't do it for you, unfortunately. If you have a version newer than R2015B, then you can do implicit matrix expansion by adding two vectors of different orientation:

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

You can do this with point_index and freq_index, then do matrix multiplication to get the final ft.

Don't use error as a variable name. It's a useful function that you can use to, well, throw errors.

You don't need a space after \n in a string, unless you actually want a space in front of the first letter in the next line:

f = %.2f [Hz] \nA = %.2f [V]'

Your variable names are very good
Your coding style is good
I don't like clear and close all in the beginning of the script, but that's up to you.


You use for index, letter in enumerate(string_list): but don't use the index.
Instead of using string_list.index(vowel) in the second loop you can instead build an index list in the first loop.
And reverse either the index list or the vowels list.
This should have a better time complexity as string_list.index(vowel) seems to be making your code time complexity \$O(n^2)\$.

I'd also change your code to follow PEP8, and remove all the redundant _list parts in your variable names.
As this makes your code easier to read.

Finally I'd return, rather than print, the final list as it makes the code  more reusable. And, as Mathias commented, you could also change your return type to a string, as giving a string as input and getting a list of strings as output is a little odd.

VOWELS = set('aeiou')

def reverse_vowels(string):
    string = list(string)
    vowels = []
    indexes = []

    for index, letter in enumerate(string):
        if letter in VOWELS:
            vowels.append(letter)
            indexes.append(index)

    for i, char in zip(indexes, reversed(vowels)):
        string[i] = char

    return ''.join(string)


Calculating Luhn-algorithm checksum digit

This is a good start! I'll do two passes over your code, one to address issues of style, and another to leverage functions from the Haskell Prelude to decrease code length and bring it more in line with typical Haskell usage and idioms.

Style

Your sumOfChars function is a good example of tail-recursion, but in Haskell we would take that String apart through pattern matching. A Haskell String is really a list of characters, or [Char], so we'll decompose it as a list.

sumOfChars :: [Char] -> Int -- String is a synonym for [Char]
sumOfChars [] = 0 -- The empty list is the same value as the empty string, i.e. [] == ""
sumOfChars (c:cs) = digitToInt c + sumOfChars cs

The : is the list cons operator, c is the head of the list and cs is the tail. So, c == str !! 0 and cs == tail str. (And head is the function we usually use for getting the element at index 0 in a list.)

twoMult isn't wrong, but function application in Haskell doesn't require any parentheses. Parentheses are for grouping since function application has the highest precedence of any operation.

twoMult :: Char -> String
twoMult c = show (digitToInt c * 2)

Using an if statement at the top level of a function is usually an indication that you can use a guard. Guards are a bit like a multi-way if.

identificationSum :: [Char] -> Int
identificationSum [] = 0
identificationSum s@(c:cs) -- The 's@' part is an as-pattern, explained below
    | length s `mod` 2 == 1 = sumOfChars (twoMult c) + identificationSum cs
    | otherwise             = digitToInt c + identificationSum cs

Each guard begins with a pipe (|) and evaluates to a Bool value. First pattern matching takes place, then guards are evaluated in order. otherwise is just a synonym for True, i.e., a guard that always succeeds when evaluation reaches it.

I used an as-pattern there to bind the value of c:cs to an identifier. This is a handy shortcut and much preferable to writing c:cs all over the place if you need both the original value and its decomposition.

remainingToTens is a little odd, and I'd guess that you got to that answer when the compiler complained about there not being an instance for Fractional Int, yeah? Integer division uses a function called div, / is for Fractional values (like Float or Double) (yeah it's a little strange the first time you come across this).

remainingToTens :: Int -> Int
remainingToTens x = (x `div` 10 + 1) * 10 - x -- Edit: This is incorrect, use version below

And determineLastDigit just has a few extra parentheses.

determineLastDigit :: String -> Int
determineLastDigit s = remainingToTens (identificationSum s)

Idiomatic Haskell

Many of the operations you implemented can be expressed using some of the higher-order functions we have in the Prelude and coding in a functional style.

Instead of using primitive recursion on the elements of a list in sumOfChars, typical Haskell usage would see us using functions like sum and map to manipulate the entire list without getting into the weeds.

sumOfChars :: [Char] -> Int
sumOfChars cs = sum (map digitToInt cs)

maps type is (a -> b) -> [a] -> [b], that is, it takes a function - that itself takes an element of type a and returns something of type b - and a list and returns a list where that function has been applied to every element of the first list. sum adds all the values in a list of numbers.

One further thing we could do to that function is to write it in pointfree style. Writing functions pointfree is definitely an aspect of Haskell style, but don't concentrate on it overmuch until you have a solid grasp on the basics of the language. I've included an Appendix A at the bottom of this post where functions have been written pointfree for your reference.

identificationSum could be written many, many ways (some as in the appendices below) but given the context of sumOfChars, twoMult, and the specification of the algorithm I would favor separating out the functionality into two phases. First, constructing a new string based on doubling every other digit, and secondly summing all of the digits. To do this I'll introduce a new function.

doubleAlternating :: [Char] -> [Char]
doubleAlternating []       = []
doubleAlternating (c:[])   = twoMult c
doubleAlternating (c:d:cs) = twoMult c ++ [d] ++ doubleAlternating cs

And then identificationSum is a composition of doubleAlternating and sumOfChars.

identificationSum :: String -> Int
identificationSum s = sumOfChars (doubleAlternating s)

remainingToTens could really just benefit from some modular arithmetic. Use the rem function.

remainingToTens :: Int -> Int
remainingToTens x = negate x `mod` 10

I'll take it a little further with inlining in the appendices, but as it stands this is a very readable translation of the problem as it was stated. Having a close correspondence to the problem domain can be much more valuable than terse code for the sake of terseness.

Appendix A: Pointfree

One of the things I like about pointfree style is that it forces you to think in terms of functions, higher order abstractions, and data pipelines. Presented without further comment.

sumOfChars :: [Char] -> Int
sumOfChars = sum . map digitToInt

twoMult :: Char -> String
twoMult = show . (* 2) . digitToInt

identificationSum :: String -> Int
identificationSum = sumOfChars . doubleAlternating

determineLastDigit :: String -> Int
determineLastDigit = remainingToTens . identificationSum

Appendix B: Code golf

Understanding this will help you explore the Prelude and hopefully have a stronger grasp of function composition. I'll admit it's a little showy though. ;-)

checksum :: String -> Int
checksum s = negate (sum . map digitToInt . concatMap show . zipWith ($) (cycle [(* 2), id]) . map digitToInt $ s) `mod` 10


First, the do { ... } blocks inside the cases are not needed:
func beats(otherSign: Sign) -> GameState {
    switch self {
    case .rock:
        if otherSign == .paper {
            return .lose
        } else if otherSign == .scissors {
            return .win
        }
        return .draw
    case .scissors:

    // ...
}

But why use a switch-statement for self and an if-statement for otherSign? The    if-statement is error-prone (we might e.g. forget a case), whereas the switch-statement perfectly matches the enum declaration and the compiler checks the exhaustiveness, i.e. that all cases are treated exactly once:
func beats(otherSign: Sign) -> GameState {
    switch self {
    case .rock:
        switch otherSign {
        case .paper:    return .lose
        case .scissors: return .win
        case .rock:     return .draw
        }
    case .scissors:

    // ...
}

This is already more compact than the original code, but still clear and easy to read.
Now we go one step further: A single switch-statement is sufficient because you can switch on a tuple in Swift:
func beats(otherSign: Sign) -> GameState {
    switch (self, otherSign) {
    case (.rock, .rock):     return .draw
    case (.rock, .paper):    return .lose
    case (.rock, .scissors): return .win

    case (.paper, .rock):     return .win
    case (.paper, .paper):    return .draw
    case (.paper, .scissors): return .lose

    case (.scissors, .rock):     return .lose
    case (.scissors, .paper):    return .win
    case (.scissors, .scissors): return .draw
    }
}

It is clear to the reader that (and how) all possible combinations are handled. Repeated or missing cases are detected by the compiler.
There is also another, completely different option. We can assign the integer values 0, 1, 2 to rock, paper, scissors, respectively, e.g. by making it an integer based enumeration:
enum Sign: Int {
    case rock, paper, scissors

    // ...
}

then the outcome of the comparison can efficiently be computed from the difference of the integer values:
func beats(otherSign: Sign) -> GameState {
    let diff = self.rawValue - otherSign.rawValue

    // ...
}

I'll leave it to you to work out the details (hint: modulo arithmetic), and to decide which variant your prefer: A (verbose) switch-statement with 9 cases, or a compact mathematical calculation.


Is this escape unescape function pair correct?

Performing string substitutions using multiple passes is almost always a bad idea, not only for performance, but for correctness.  In this case, there is indeed a bug: unescape('//PLUS/PLUS') should produce '/PLUS+', but instead produces '/++'.

Therefore, you have to parse the input string in one pass:

import re

def unescape(s):
    def replacement(match):
        return {
            '/': '/',
            'PLUS': '+',
            'MINUS': '-',
        }[match.group(1)]
    return re.sub('/(/|PLUS|MINUS)', replacement, s)

In your original code and in the implementation above, there is a lot of repetition.  If there are more symbols being escaped than just + and -, then it makes sense to specify the mapping just once.

ESCAPE_CHAR = '/'
ESCAPE = {
    ESCAPE_CHAR: ESCAPE_CHAR,
    '+': 'PLUS',
    '-': 'MINUS',
}
ESCAPE_RE = re.compile('|'.join(map(re.escape, ESCAPE.keys())))

UNESCAPE = dict((v, k) for (k, v) in ESCAPE.items())
UNESCAPE_RE = re.compile(
    re.escape(ESCAPE_CHAR) + '(' +
        '|'.join(map(re.escape, UNESCAPE.keys())) +
    ')')

def escape(s):
    return ESCAPE_RE.sub(lambda match: ESCAPE_CHAR + ESCAPE[match.group(0)], s)

def unescape(s):
    return UNESCAPE_RE.sub(lambda match: UNESCAPE[match.group(1)], s)


A couple of real issues (rather than the imaginary ones previously pointed out):
Your code does not fully implement the requirements of iterator.

You have not implemented the operator-> as required by the iterator concept.
operator* should return by reference.
This is because *x = t is a requirement of iterator and without the reference this will not work as expected (or at all depending).

Without the container code its hard to tell if you can use the same iterator for both const and non-const iterator types. So sometimes its useful to provide const overloads of the above (but that will depend on usage).
see: http://www.sgi.com/tech/stl/trivial.html
You classify your iterator as
std::bidirectional_iterator_tag

This is an indication that you can go backwards and forwards with the iterator. In fact the concept means that your iterator must also support operator-- are well as operator++.
See: http://www.sgi.com/tech/stl/BidirectionalIterator.html
The link you provide indicates that a square list is circular. So moving forward all the time you may never reach the end. But without understanding (or seeing your implementation) it is hard to tell if the current implementation will work.
    iterator & operator ++()
    {
        _node = _node->next;   // Will this ever reach a NULL
                               // Or do you have a special version of
                               // iterator that marks the end.
                               //
                               // Note: end is one past the last element
                               //       Which makes this doubly hard to
                               //       implement with a circular list.
                               //       But can be done if you use a sentinel.
                               //
                               // The default constructor suggests that the
                               // end is marked by a NULL but hard to be sure.
        return *this;
    }

No point in defining destructor the default version will work perfectly. (As a side note: since it is not virtual there can be no derived types with alternative behaviors so making things symmetric is doubly useless).
    ~iterator(){}

This is perfectly fine.
        iterator  retVal = *this;

But just as a personal preference I prefer:
        iterator  retVal(*this);

As mentioned above (but without the container code it is hard to tell). Well this test work for the end iterator.
    bool operator != (iterator const& rhs) const
    {
        return _node != rhs._node;
    }
    bool operator == (iterator const& rhs) const
    {
        return _node == rhs._node;
    }

There is no requirement for bidirectional iterators to have a less than comparison. Unless you really want to store iterators in a sorted container I would leave this out.
Note: A random access iterator does have a requirement for a less than operator. But it has a precondition that it can only compare iterators that are reachable from each other.
see: http://www.sgi.com/tech/stl/RandomAccessIterator.html
    bool operator < (iterator const& rhs) const
    {
        return _node < rhs._node;
    }

The second thing to consider is the sort ordering correct?

You are defining the less than operator in term of pointer arithmetic. Unless the object are allocated by the same allocators from a known block this is actually undefined behavior. For pointer comparison to be valid they need to be in the same allocated block.
Is this a good ordering? Youre ordering is based on their address (not the position in the container). So things may be in a jumbled up state in relation to everything else. This may be perfectly fine but something you should keep in mind.

WHY The following answers is a complete waste of time and WRONG
So please stop voting for it.

I learnt about its importance following discussions on one of the C++ working groups. It's a good practice to follow smarter people.

Yes but you have to also understand when to apply these principles. Some ideas contradict other ideas if you just use them bluntly. You need to understand each idea but also when to apply it.
The concept of operator symmetry is an important concept when used in the correct situation (no argument there). The problem is that iterators are not the correct situation and it plays no part.
But we have two competing concepts at play here. One: is symmetry is good. Two: auto conversion of types by the compiler is bad.
You have to balance the two concepts. In terms of iterators auto converting iterators is a very bad idea. You want to make the user of the iterator be explicit about any conversions (as the STL designers did (see below)). As a result the symmetry concept can not be used (as it requires auto conversion).
Why it makes no sense for auto conversion
 Container    x;
 AltCont      y;

 // You can not compare iterators
 // From different containers.
 if (x.begin() < y.end()) {
     // At best this is undefined
     // At worst this is undefined behavior.
 }

 // There is no logic to that situation.
 // SO because you should not compare iterators from different
 // containers the type of the iterator when being tested will
 // ***ALWAYS*** be the same type.

 // The type of the iterator is always `Container::iterator`
 // Its a required property of a container.
 Container::iterator  begin = x.begin();
 Container::iterator  end   = x.end();

Q: A but you can create other types of iterator from your iterator.
A: Yes. But this new type is not comparable to the old type.
typedef std::reverse_iterator<Container::iterator> reverse_iterator;
reverse_iterator rbegin(end);
reverse_iterator rend(begin);

The types are still not comparable.
 if (begin < rbegin) {  // Compile time error
 }                      // For a good reason
                        // there is no logical reason for the ranges
                        // to be equivalent.

You will also note it does not work the other way around.
 if (rbegin < begin) {
 }

Why you ask is this second case a big deal. Well there is no constructor on Cont::iterator to create an object of type std::reverse_iterator<Cont::iterator>. So in the first test above there was no way to convert rbegin into the correct type.
BUT there is a constructor on std::reverse_iterator<Cont::iterator> that takes an object of Cont::iterator so in the second condition we could be in a situation where begin is auto converted into std::reverse_iterator<Cont::iterator> and the expression would compile. But luckily for us the designers of the STL decided that was a bad idea and made the constructor explicit to prevent auto conversion and thus prevent the code from compiling.
OK so why is in Dangerous
Its also hides errors.
The above code will generally generate a compiler error (so you spot it and correct it quickly). But lets dig in and build the code as suggested by @vinipsmaker.
For this to work there either has to be a conversion from one iterator to the other or as he suggests a base class and a derived type.
 class IterBase
 {  /* Define iterator */ }

 class IterDerivedForCont1: public IterBase
 {  /* Define iterator */ }

 class IterDerivedForCont2: public IterBase
 {  /* Define iterator */ }

 class Cont1 {
     typedef IterDerivedForCont1 iterator;
     /* Other Stuff */
 }

 class Cont2 {
     typedef IterDerivedForCont2 iterator;
     /* Other Stuff */
 }

 bool operator<(IterBase const& l, IterBase const& r)
 { return TEST(l,r);}

 Cont1   a;
 Cont2   b;

 if (a.begin() < b.end()) {
     // You want this to compile?
     // Not really. But it will
 }

 // So in this case you are hiding errors from the user.
 // That could have been easily spotted by the compiler.


Great work so far! And good on you for seeking review. In general, your code is pretty good, and works correctly. As you've asked, though, here are some suggestions for improvement.

The assignment:

inch = 2.54 #centimeters

is potentially confusing; instead, you could make it clear that it is a ratio:

CM_PER_INCH = 2.54

Note the UPPERCASE_WITH_UNDERSCORES name for a constant, per the style guide.

centimeters = int(input("Enter a number of centimeters"))

There is no reason to limit the user to int input - why not allow float? Then they can enter and convert e.g. 4.2cm.

Also, this will fail with input that can't be converted to an integer (what if the user types seven?) - have a look at this SO community wiki if you want to add validation.

print "Entered number of %s centimeters is equal to %s inches" % (centimeters , centimeters / inch)

This line is too long (see the style guide again). Also, % formatting is a little old-fashioned, compared to str.format. I would split this into two lines:

template = '{.2f}cm is equal to {.2f}"'
print template.format(centimeters, centimeters / CM_PER_INCH)

Or use line continuation:

print '{.2f}cm is equal to {.2f}"'.format(
    centimeters,
    centimeters / CM_PER_INCH
)

In use:

>>> print template.format(float(centimeters), centimeters / CM_PER_INCH)
5.00cm is equal to 1.97"

If you want another challenge, have a go at implementing the reverse calculation, and allowing the user to choose which way to convert.


This will return false for attr in such an object {'attr': undefined}:

$.fn.hasAttr = function(name) {
   return this.attr(name) !== undefined;
};

If this is not exactly what you want, have a look at related posts (one, two) and search for much more.

This (and similars) will always evaluate to true, if schemaElements object has the postalAddress key:

if (schemaElements.postalAddress){
    defaults.utilities.missAtrr(schemaElements.postalAddress, "itemscope");
}

here's an example session from Chrome developer console:

var rules = {'a': $('html').find('#idontexist')};
rules.a;
// []
if (rules.a) {console.log(true)} else {console.log(false)};
// true

Be consistent with ; at the end of the lines.


Deleting a node from a binary search tree

Here is how I would do this. I've sprinkled comments throughout the code, so hopefully this will be helpful.

//generalize the node to work for types other than just int
public class Node<T extends Comparable<? super T> >
{
    private T value; //get; set;
    private Node<T> left; //get; set;
    private Node<T> right; //get; set;

    /**
     * construct a Node with value
     *
     * @param val value for this node
     */
    public Node(T val)
    {
        value = val;
        left = null;
        right = null;
    }

    /**
     * copy constructor
     *
     * @param n node to copy from
     */
    public Node(Node<T> n)
    {
        value = n.value;
        left = n.left;
        right = n.right;
    }

    /**
     * @return true if this node has no children
     */
    public boolean isLeaf()
    {
        return (left == null && right == null);
    }

    public Node<T> getLeft() { return left; }
    public Node<T> getRight() { return right; }
    public T getValue() { return value; }
    public void setLeft(Node<T> n) { left = n; }
    public void setRight(Node<T> n) { right = n; }
    public void setValue(T v) { value = v; }
}

And the BST. Since it doesn't really make sense to delete without being able to add nodes to the tree first, I've put in adding as well.

public class DeleteNodeBST<T extends Comparable<? super T> >
{
    private Node<T> root = null;
    private int nodes = 0; //get;

    /**
    * add a node to the tree
    *
    * @param n node to add
    * @return true if add is successful
    */
    public boolean add(final Node<T> n)
    {
        //null guard
        if (n == null || n.getValue() == null)
        {
            return false;
        }

        boolean isSuccessful;
        if (root == null)
        {
            root = n;
            ++nodes;
            isSuccessful = true;
        }
        else
        {
            isSuccessful = findHome(root, n);
        }

        return isSuccessful;
    }

    /**
     * create a node containing input value and add it to the tree
     *
     * @param val value for new node
     * @return true if add is successful
     */
    public boolean add(final T val)
    {
        return add( new Node<T>(val) );
    }

    /**
     * attempt to place a node under another
     *
     * @param adoptor node to look under
     * @param adoptee child node looking for a home
     * @return true if child node finds a place, otherwise false
     */
    private boolean findHome(Node<T> adoptor, final Node<T> adoptee)
    {
        int comp = adoptor.getValue().compareTo( adoptee.getValue() );

        if (comp > 0)   //adoptor comps greater than adoptee, so go left
        {
            if (adoptor.getLeft() == null)
            {
                adoptor.setLeft(adoptee);
                ++nodes;
                return true;
            }
            //recurse until we find somewhere to place the adoptee node
            return findHome(adoptor.getLeft(), adoptee);
        }
        else if (comp < 0)  //adoptor comps less than adoptee, so go right
        {
            if (adoptor.getRight() == null)
            {
                adoptor.setRight(adoptee);
                ++nodes;
                return true;
            }
            //recurse until we find somewhere to place the adoptee node
            return findHome(adoptor.getRight(), adoptee);
        }

        return false;
    }

    /**
     * attempts to delete a node from the tree
     *
     * @param n node to delete
     * @return true if node is deleted, otherwise false
     */
    public boolean delete(Node<T> n)
    {
        //null guard
        if (n == null || n.getValue() == null)
        {
            return false;
        }

        return delete( n.getValue() );
    }

    /**
     * attempts to delete a node from the tree containing the value
     *
     * @param val value of node to delete
     * @return true if node is deleted, otherwise false
     */
    public boolean delete(final T val)
    {
        //the node to be deleted
        Node<T> target = null;
        //to keep track of parent node
        Node<T> parent = null;
        //variable node reference
        Node<T> node = root;

        while (node != null)
        {
            if (val.compareTo( node.getValue() ) == 0)  //eureka!
            {
                target = node;
                break;
            }
            else if (val.compareTo( node.getValue() ) > 0)  //target greater, so go right
            {
                parent = node;
                node = node.getRight();
            }
            else    //target less, so go left
            {
                parent = node;
                node = node.getLeft();
            }
        }

        if (target == null)
        {
            //target not found
            return false;
        }

        boolean isLeft = (target == parent.getLeft() );

        if (target == root) //the node that's baleeting is in fact the root node
        {
            //get last house on the left on the right!
            //it becomes the new root
            node = getLastHouseOnTheLeft( parent.getRight() );
            if (node != null)
            {
                node.setLeft( parent.getLeft() );
                node.setRight( parent.getRight() );
                root = node;
            }
        }
        else if ( target.isLeaf() )
        {
            if (isLeft)
            {
                parent.setLeft(null);
            }
            else
            {
                parent.setRight(null);
            }
        }
        else if (target.getLeft() != null && target.getRight() != null) //two children, some shuffling
        {
            if (isLeft)
            {
                parent.setLeft( target.getRight() );
                parent.getLeft().setLeft( target.getLeft() );
            }
            else
            {
                parent.setRight( target.getRight() );
                parent.getRight().setLeft( target.getLeft() );
            }
        }
        else    //one child is simpler
        {
            if (target.getLeft() == null)
            {
                if (isLeft)
                {
                    parent.setLeft( target.getLeft() );
                }
                else
                {
                    parent.setRight( target.getLeft() );
                }
            }
            else
            {
                if (isLeft)
                {
                    parent.setLeft( target.getRight() );
                }
                else
                {
                    parent.setRight( target.getRight() );
                }
            }
        }

        return true;    //baleeted
    }

    /**
     * extract the last house on the left
     *
     * @param start the node to start on
     * @return the last house on the left
     */
    private Node<T> getLastHouseOnTheLeft(final Node<T> start)
    {
        Node<T> candidate = null;
        Node<T> parent = null;
        Node<T> node = start;

        while (node != null)
        {
            if ( node.getLeft() != null )
            {
                parent = node;
                candidate = node.getLeft();
            }

            node = node.getLeft();
        }

        if (parent != null)
        {
            parent.setLeft(null);
        }

        return candidate;
    }

    /**
     * get a node from the value it's associated with
     *
     * @param v value as a key to finding the node containing it
     * @return node associated with the value
     */
    public Node<T> getNode(T v)
    {
        //null guard
        if (v == null)
        {
            return null;
        }

        Node<T> node = root;
        int comp;
        while (root != null)
        {
            comp = node.getValue().compareTo(v);
            if (comp == 0)
            {
                return node;
            }
            if (comp > 0)
            {
                node = node.getLeft();
            }
            else
            {
                node = node.getRight();
            }
        }

        return node;
    }

Finally, some simple test cases, plus an example graph:

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public class TestDeleteNodeBST
{
    DeleteNodeBST<Integer> delBst;
    Node<Integer> node;

    @Before
    public void init()
    {
        delBst = new DeleteNodeBST<Integer>();

        assertTrue(delBst.getNumberOfNodes() == 0);
    }

    @Test
    public void testAddNode()
    {
        node = new Node<Integer>(1);
        assertTrue(node.getValue() == 1);
        assertTrue(node.getLeft() == null);
        assertTrue(node.getRight() == null);

        delBst.add(node);
        assertTrue(delBst.getNumberOfNodes() == 1);

        Integer two = 2;
        assertTrue( two > node.getValue() );
        assertTrue( two.compareTo(node.getValue() ) > 0 );

        delBst.add(two);
        assertTrue(delBst.getNumberOfNodes() == 2);
        assertTrue( delBst.getNode(2).getValue().equals(2) );
    }

    @Test
    public void testCorrectness()
    {
        delBst.add(5);
        delBst.add(4);
        delBst.add(3);
        delBst.add(2);
        delBst.add(1);
        delBst.add(0);
        assertTrue(delBst.getNumberOfNodes() == 6);

        node = delBst.getNode(3);
        assertTrue(node.getValue() == 3);
    }

    @Test
    public void testDeleteNode()
    {
        delBst.add(5);
        delBst.add(4);
        delBst.add(6);
        delBst.add(7);
        delBst.add(2);
        delBst.add(3);
        delBst.add(1);
        /*
         * tree should look like this now
         *           5
         *        4     6
         *      2         7
         *     1 3
         */
        assertTrue( delBst.delete(2) ); //3 should take 2's place
        assertFalse( delBst.delete(2) );//nothing to delete now
        node = delBst.getNode(3);
        assertTrue(node.getValue() == 3);
        assertTrue(node.getRight() == null);
        assertTrue(node.getLeft().getValue() == 1);
    }
}


I have no complaints about this.

Esthetically it seems that squishOn 'a' "aaabcbcbc" should create the groups:

[ "aaa", "bcbcbc" ]

instead of:

[ "aaa", "b", "c", "b", "c", "b", "c" ]

Due to laziness it may not make any difference. This is something that perhaps should be benchmarked. To form the groups the first way use the groupBy function from Data.List like this:

groupBy (\x y -> x == y || (x /= 'a' && y /= 'a')) input

So, two characters are in the same group if they are equal or if they are not both the character to be squished. Of course, if you do this you'll have to switch the groups back together differently with something like:

concatMap f (groupBy (\x y -> ...) ...)
  where f ('a':xs) = "a"
        f xs       = xs

(Substitute the literal 'a' with the squishing character.)

This alternate approach probably makes more sense if you were to define squishing on ByteString or Text.


Shell script to parse variable definitions from Scala build file

I'd use awk to generate shell syntax, and source it in the shell:

$ source <(
    awk '
        $1 == "name"         {print "PROJECT_NAME=" $NF}
        $1 == "scalaVersion" {print "SCALA_VERSION=" $NF}
    ' build.sbt
)

$ echo $PROJECT_NAME,$SCALA_VERSION
happy,2.11.8

If the name or version strings might contain spaces, then we need to be more specific about awk's field separator:

$ cat build.sbt
name := "hello world"
scalaVersion := "2.11.8"
sparkVersion := "2.2.0"

$ awk '
    $1 == "name"         {print "PROJECT_NAME=" $NF}
    $1 == "scalaVersion" {print "SCALA_VERSION=" $NF}
' build.sbt

PROJECT_NAME=world"              # << oops
SCALA_VERSION="2.11.8"

$ awk -F '"' '
    $1 ~ /^name/         {printf "PROJECT_NAME=\"%s\"\n",  $2}
    $1 ~ /^scalaVersion/ {printf "SCALA_VERSION=\"%s\"\n", $2}
' build.sbt

PROJECT_NAME="hello world"
SCALA_VERSION="2.11.8"