Little issues

Your indentations seems wrong : too many spaces in a few places, not enough in a few other places. Whitespaces matter in Python so this is definitly something you should fix before going any further.

Style

Python has a style guide called PEP 8 which is definitly worth reading and and worth following if you do not have good reasons not to. In you case, your usage of whitespaces around parenthesis and the trailing whitespaces for instance are not compliant to PEP8. You'll find tools online to check your code compliancy to PEP8 in a automated way if you want to. This could also help you to detect and fix your indentation issues.

Don't Repeat Yourself

You've already realised that your code was repeating itself and that is was a bad thing. Let's see how this can be improved.

The only difference between SPCa and SPC is that SPC has an additional line printed at the beginning. It might be easier to replace all the calls to SPC() by a call to print and then a call to SPCa. Once this is done, we can get rid of SPC and maybe rename SPCa in play_game.

At this stage, the code looks like:

from random import choice

def play_again():
    print "Do you want to play again:- Choose 'yay' or 'nay'"
    user_again = raw_input('->')
    if user_again == 'yay':
        play_game()
    elif user_again == 'nay':
        print "Ok bye! hope you enjoyed the game. See you soon! :)"
    else:
        print "Please choose correct option."
        play_again()

def play_game():
    computer_choice = choice(['stone', 'paper', 'scissor'])
    computer_choosed = "Computer choosed %s" % computer_choice
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = raw_input('->')

    if user_choice == computer_choice:
        print computer_choosed
        print "So it's a tie"
        play_again()

    elif user_choice == 'stone':
        if computer_choice == 'paper':
            print computer_choosed
            print "So, You loose"
            play_again()
        elif computer_choice == 'scissor':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()

    elif user_choice == 'paper':
        if computer_choice == 'scissor':
            print computer_choosed
            print "So, you loose."
            play_again()
        elif computer_choice == 'stone':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()

    elif user_choice == 'scissor':
        if computer_choice == 'stone':
            print computer_choosed
            print "So, you loose."
            play_again()
        elif computer_choice == 'paper':
            print computer_choosed
            print "So, Cheers! You won!"
            play_again()
    else:
        print "please choose correct option"
        play_game()

print "You are playing Stone, Paper, Scissor."
play_game()

if main guard

In Python, it is a good habit to move your code actually doing things (by opposition to merely defining things) behind an if __name__ == "__main__": guard. This is useful if you want to reuse the code : you can import the file and get all the benefits from it (the definition of values/functions/classes) without having it performing unwanted actions.

In your code, the end of the script becomes :

if __name__ == "__main__":
    # execute only if run as a script
    print "You are playing Stone, Paper, Scissor."
    play_game()

Now we can get into the actual changes in your code. One of the issue it that you have multiple functions calling each other which make things difficult to understand.

All branches in play_game end up calling play_again (except when the option is not correct). It may be easier to call it once, at the end of the function like this.

else:
    print "please choose correct option"
    play_game()
    return
play_again()

However, an even more simple option would be to check at the beginnign that the value is correct. You could define a list with the correct options and use it like this :

from random import choice

game_options = ['stone', 'paper', 'scissor']

def play_again():
    print "Do you want to play again:- Choose 'yay' or 'nay'"
    user_again = raw_input('->')
    if user_again == 'yay':
        play_game()
    elif user_again == 'nay':
        print "Ok bye! hope you enjoyed the game. See you soon! :)"
    else:
        print "Please choose correct option."
        play_again()

def play_game():
    computer_choice = choice(game_options)
    computer_choosed = "Computer choosed %s" % computer_choice
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = raw_input('->')

    if user_choice not in game_options:
        print "please choose correct option"
        play_game()
        return

    if user_choice == computer_choice:
        print computer_choosed
        print "So it's a tie"

    elif user_choice == 'stone':
        if computer_choice == 'paper':
            print computer_choosed
            print "So, You loose"
        elif computer_choice == 'scissor':
            print computer_choosed
            print "So, Cheers! You won!"

    elif user_choice == 'paper':
        if computer_choice == 'scissor':
            print computer_choosed
            print "So, you loose."
        elif computer_choice == 'stone':
            print computer_choosed
            print "So, Cheers! You won!"

    elif user_choice == 'scissor':
        if computer_choice == 'stone':
            print computer_choosed
            print "So, you loose."
        elif computer_choice == 'paper':
            print computer_choosed
            print "So, Cheers! You won!"

    play_again()

if __name__ == "__main__":
    # execute only if run as a script
    print "You are playing Stone, Paper, Scissor."
    play_game()

Also, this may call for a better option. You could define a function asking a user for a value in a list. This function could be used in 2 places and make your code easier to follow and less repetitive.

from random import choice

game_options = ['stone', 'paper', 'scissor']

def get_user_input_in_list(lst):
    user_input = raw_input('->')
    while True:
        if user_input in lst:
            return user_input
        else:
            print "Please choose correct option."

def play_again():
    print "Do you want to play again:- Choose 'yay' or 'nay'"
    user_again = get_user_input_in_list(['yay', 'nay'])
    if user_again == 'yay':
        play_game()
    elif user_again == 'nay':
        print "Ok bye! hope you enjoyed the game. See you soon! :)"

def play_game():
    computer_choice = choice(game_options)
    computer_choosed = "Computer choosed %s" % computer_choice
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = get_user_input_in_list(game_options)

    if user_choice == computer_choice:
        print computer_choosed
        print "So it's a tie"

    elif user_choice == 'stone':
        if computer_choice == 'paper':
            print computer_choosed
            print "So, You loose"
        elif computer_choice == 'scissor':
            print computer_choosed
            print "So, Cheers! You won!"

    elif user_choice == 'paper':
        if computer_choice == 'scissor':
            print computer_choosed
            print "So, you loose."
        elif computer_choice == 'stone':
            print computer_choosed
            print "So, Cheers! You won!"

    elif user_choice == 'scissor':
        if computer_choice == 'stone':
            print computer_choosed
            print "So, you loose."
        elif computer_choice == 'paper':
            print computer_choosed
            print "So, Cheers! You won!"

    play_again()

if __name__ == "__main__":
    # execute only if run as a script
    print "You are playing Stone, Paper, Scissor."
    play_game()

This is better but we still have play_game calling play_again and play_again calling play_game.

Maybe play_game should be used to play a single game and shouldn't call play_again at all. This can be done by removing the call to play_again in play_game and moving it after the call to play_game in play_again. That way, we'd just have play_game calling itself.

You'd have something like :

from random import choice

game_options = ['stone', 'paper', 'scissor']

def get_user_input_in_list(lst):
    user_input = raw_input('->')
    while True:
        if user_input in lst:
            return user_input
        else:
            print "Please choose correct option."

def play_again():
    print "Do you want to play again:- Choose 'yay' or 'nay'"
    user_again = get_user_input_in_list(['yay', 'nay'])
    if user_again == 'yay':
        play_game()
        play_again()
    elif user_again == 'nay':
        print "Ok bye! hope you enjoyed the game. See you soon! :)"

def play_game():
    computer_choice = choice(game_options)
    computer_choosed = "Computer choosed %s" % computer_choice
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = get_user_input_in_list(game_options)

    if user_choice == computer_choice:
        print computer_choosed
        print "So it's a tie"

    elif user_choice == 'stone':
        if computer_choice == 'paper':
            print computer_choosed
            print "So, You loose"
        elif computer_choice == 'scissor':
            print computer_choosed
            print "So, Cheers! You won!"

    elif user_choice == 'paper':
        if computer_choice == 'scissor':
            print computer_choosed
            print "So, you loose."
        elif computer_choice == 'stone':
            print computer_choosed
            print "So, Cheers! You won!"

    elif user_choice == 'scissor':
        if computer_choice == 'stone':
            print computer_choosed
            print "So, you loose."
        elif computer_choice == 'paper':
            print computer_choosed
            print "So, Cheers! You won!"

if __name__ == "__main__":
    # execute only if run as a script
    print "You are playing Stone, Paper, Scissor."
    play_game()
    play_again()

This is a bit better but you can go further in the separation of concerns. It is probably a better option to have play_again to return a boolean and have a while loop ensuring we call play_game as long as required.

This would look like:

from random import choice

game_options = ['stone', 'paper', 'scissor']

def get_user_input_in_list(lst):
    user_input = raw_input('->')
    while True:
        if user_input in lst:
            return user_input
        else:
            print "Please choose correct option."

def play_again():
    print "Do you want to play again:- Choose 'yay' or 'nay'"
    user_again = get_user_input_in_list(['yay', 'nay'])
    return user_again == 'yay'

def play_game():
    computer_choice = choice(game_options)
    computer_choosed = "Computer choosed %s" % computer_choice
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = get_user_input_in_list(game_options)

    if user_choice == computer_choice:
        print computer_choosed
        print "So it's a tie"

    elif user_choice == 'stone':
        if computer_choice == 'paper':
            print computer_choosed
            print "So, You loose"
        elif computer_choice == 'scissor':
            print computer_choosed
            print "So, Cheers! You won!"

    elif user_choice == 'paper':
        if computer_choice == 'scissor':
            print computer_choosed
            print "So, you loose."
        elif computer_choice == 'stone':
            print computer_choosed
            print "So, Cheers! You won!"

    elif user_choice == 'scissor':
        if computer_choice == 'stone':
            print computer_choosed
            print "So, you loose."
        elif computer_choice == 'paper':
            print computer_choosed
            print "So, Cheers! You won!"

if __name__ == "__main__":
    # execute only if run as a script
    print "You are playing Stone, Paper, Scissor."
    while True:
        play_game()
        if not play_again():
            print "Ok bye! hope you enjoyed the game. See you soon! :)"
            break

Now we can get into the internals of play_game.
First, you could get rid of the various way where printing is repeated.

def play_game():
    computer_choice = choice(game_options)
    computer_choosed = "Computer choosed %s" % computer_choice
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = get_user_input_in_list(game_options)

    print computer_choosed
    if user_choice == computer_choice:
        assert result == 0
        print "So it's a tie"
    else:
        win = False  # unused value

        if user_choice == 'stone':
            win = (computer_choice == 'scissor')
        elif user_choice == 'paper':
            win = (computer_choice == 'stone')
        elif user_choice == 'scissor':
            win = (computer_choice == 'paper')

        if win:
            print "So, Cheers! You won!"
        else:
            print "So, you loose."

There are various way to define who wins in a game of player/scissors/rock. You could define a dictionnary mapping the different combinations possible to the winner. I quite like using modulo arithmetic to find the result.

Final code looks like:

from random import choice

game_options = ['stone', 'paper', 'scissor']

def get_user_input_in_list(lst):
    user_input = raw_input('->')
    while True:
        if user_input in lst:
            return user_input
        else:
            print "Please choose correct option."

def play_again():
    print "Do you want to play again:- Choose 'yay' or 'nay'"
    user_again = get_user_input_in_list(['yay', 'nay'])
    return user_again == 'yay'

def play_game():
    computer_choice = choice(game_options)
    computer_choosed = "Computer choosed %s" % computer_choice
    print "Make an choice"
    print "Choose stone, paper, scissor"
    user_choice = 'stone' # get_user_input_in_list(game_options)
    computer_idx = game_options.index(computer_choice)
    user_idx = game_options.index(user_choice)
    result = (computer_idx - user_idx) % 3

    print computer_choosed
    if result == 0:
        print "So it's a tie"
    elif result == 1:
        print "So, you loose."
    else:
       assert result == 2
       print "So, Cheers! You won!"

if __name__ == "__main__":
    # execute only if run as a script
    print "You are playing Stone, Paper, Scissor."
    while True:
        play_game()
        if not play_again():
            print "Ok bye! hope you enjoyed the game. See you soon! :)"
            break


C++11 version of Windows EventWaitHandle

Despite the good odds of a tail-call optimisation, your use of recursion seems unidiomatic and sets off alarm bells in my head. Though they are largely unfounded in a practical sense, I'd say that's enough of a warning to just perform loop-waiting with an actual loop, instead.

You could do with some documenting comments, as it's not clear to a non-WinAPI person what this class actually does.

Some of your code lines are too long to read comfortably.

I can't spot any actual bugs though.


Your NewPomodoro function should simply be called New (the fact that you're creating a Pomodoro thing is inherent in "you're calling pomodoro.New" and "there's only one New", if there were more, it would make sense to have, say, NewTimer and NewManager).
I don't see what the PomodoroService is actually useful for, it seems to be abstraction for the sake of abstraction. I would simply put the StartBreak, StartLongBreak, and StartWorking methods directly on the timer/manager, as long as this is essentially all there is.
I would probably have called PomodoroManager something else. Probably Pomodoro, PomodoroTimer or (most probably) just Timer (the fact that it's a Pomodoro timer is inherent from being in the pomodoro package).
I am ambivalent about having the various timers and channels in sub-structs. There's few enough that I am not 100% sure not doing so makes the code mode readable. However, since the members are not exported, their types do not need to be exported, since they can't be accessed from outside the package anyway. I would also name the structs in plural, since they clearly contain "channelS", "durationS" and "intervalS".
Since you're never seemingly using the values passed across your channels, you might as well make then chan struct{} instead of chan bool.
I would consider making your intervals to be of type time.Duration instead of int.
I would consider wrapping all the exec.Command("say", ...).Output()" calls in a non-exported utility function (called, say, say).


Depending on how many types of items you will have and how many items will be live at any one time it may pay to use the flyweight pattern. Where each item stack has a pointer to an item type which holds all the behavior, and hold the data that makes the stack unique and/or is used very often (how many items in the stack, id for the sprite to draw, ...).

Making the ItemStack objects fixed size (with a pointer when the you need that extra storage space) will let you make an inventory hold a std::vector<ItemStack> instead of a std::vector<std::unique_ptr<ItemStack>>. The first will have much better performance when iterating over all items in an inventory. Hold by value what you can and use as few pointers as possible for the rest.

I'm not a fan of complex inheritance trees, either you need a virtual function in the base class anyway or you need dynamic_casts all over the place.

Stackable as a tag type is a pretty bad way of making something stackable. You will need to dynamic_cast to find out whether it can stack and the stackable items may each have a different max stacksize that you then need to query. So just create a single virtual size_t get_max_stack() in the base class of the item type.


Script to convert Shift + Spacebar into four spaces on SE

You can use charAt to grab the preceding character and check it against a space, newline, or empty string (the case when the cursor is at the start). But let's not stop there.

white and pad are okay enough (white is probably unnecessary, but space would be a better name since newlines are typically included in the generic term "whitespace"), but those other names are truly horrible!
You should probably maintain their full text selection--beginning and end.

Updated code:

$("textarea").keydown(function (e) {
    if (e.shiftKey && e.keyCode === 32) {
        var pad = "    ",
            text = this.value,
            start = this.selectionStart,
            end = this.selectionEnd,
            scroll = this.scrollTop,
            before = text.slice(0, start),
            after = text.slice(start),
            prevChar = before.charAt(before.length - 1);
        if (prevChar === "" || prevChar === " " || prevChar === "\n") {
            this.value = before + pad + after;
            this.selectionStart = start + pad.length;
            this.selectionEnd = end + pad.length;
            this.scrollTop = scroll;
            e.preventDefault();
        }
    }
});

Here are some future enhancement ideas:

Search for the preceding newline to ensure there is only whitespace before the cursor. This would fully stop expansion inside a sentence. Right now you can still insert four spaces in the middle right after a space.
Consider using ctrl + space so you can add ctrl + shift  + space for outdenting.
Shift/unshift every selected line instead of just the cursor position. Right now the { } button can be wrangled to do shifting, but it's cumbersome since you have to put some non-space character on the first line to get indentation.


Remove duplicate elements from char array

One possibility is to use a Set. Just add the elements from the array and then get the unique elements from the Set. This algorithm will be O(n) instead of O(n^2) because each element is accessed only once.

Note that you can use Arrays.asList() to simplify the coding, too.


Prim's algorithm via Priority Queues to print the minimum spanning tree of an undirected graph

For who is not familiar with Prim's algorithm: it finds a minimum spanning tree for a weighted undirected graph.

My suggestions:

Generics: the class Edge should be declared as Edge<T> or it won't compile as is. Or is it an inner class? Also the generic is missing in Comparable and the method compareTo.
compareTo: typically, for primitive types is better to use <,>, and return -1,0 or 1. In your case, compareTo could overflow the integer with a negative weight. You can change it from:
public int compareTo(Edge other) {
  return this.weight - other.weight;
}

To:
public int compareTo(Edge other) {
  return Integer.compare(this.weight,other.weight);
}

addAll instead of for-loop: adding all edges to the queue can be done with addAll. From:
for (Edge edge: adjacencyList.get(currentNode)) {
    edges.add(edge);
}

To:
edges.addAll(adjacencyList.get(currentNode));

Testing: the method printMSTPrims is hard to test. Would be better to have a method mstPrims that returns a result and then print it with another method. In that case, would be easier to test mstPrims.
Naming: the name edges is a bit generic, an alternative can be edgeQueue or just queue.

Your final assumption:

PS. I assume the graph does not have loops and self-edges.

So a tree? A (connected) acyclic undirected graph is a tree. Anyway, looking at your method I don't think there should be problems even if there are cycles.


Your code represents a well-known pattern. In Java, files like this are called resource files and they are delivered together with the code in a .jar file (which is essentially a .zip file).

As pointed out in a comment, you cannot use your code with absolute paths. This is good since the entire purpose of the code is to find a resource relative to the source code that needs this resource.

The call to abspath looks redundant to me. I'm assuming that __file__ is already an absolute path. You may want to check the documentation about it.

A downside of your function is that you have to define it in each file that wants to open relative files since it uses __file__. You cannot import that function, as it is now.


First thing's first, instead of calling out to the gzip program with os.system, use the gzip module in Python.  This will almost always be more portable: http://docs.python.org/2/library/gzip.html

Second of all, instead of using os.path.getsize and os.path.getmtime just use a single os.stat call: http://docs.python.org/2/library/os.html#os.stat  You can call this once and cache the results for a single file.

Don't require calling self.date() in order to set the unix_time and file_date attributes.  Instead make those into properties.  For example you could write that like:

class CheckFile(object):
    'Operation on file like get size,file time etc..'

    def __init__(self, fname):
        self.fname = fname
        self._stat = None

    @property
    def stat(self):
        if self._stat is None:
            # Note: This will not update automatically if your file's stats change
            self._stat = os.stat(self.fname)
        return self._stat

    @property
    def unix_time(self):
        return self.stat.st_mtime

    @property
    def datetime(self):
        return datetime.fromtimestamp(self.unix_time)

    @property
    def age_in_days(self):
        return (datetime.today() - self.datetime).days

All that said, although I wouldn't discourage anyone from wanting to learn object-oriented programming, for this particular application writing a class is overkill :)


C++ Stack implementation with linked-list

This is the archaic form of template declaration:

template <class T>

The more modern form is:

template<typename T>

Technically not difference but class implies user defined type while typename implies any type. Most modern libraries will use the newer version. There is also one obscure corner case template templates were it makes a difference.

You don't need to define a constructor for node.

  struct node {
    T data;
    node* next = nullptr;
    node(T data, node* next) : data(data), next(next) {};
  };

The initializer list contruct will have the same affect.

  struct node {
    T data;
    node* next;
  };
  ...
  new node {data, top};

Also I would use standard naming convention. User defined types start with an upper case letter while variables and methods start with a lower case letter. This helps you distinguish between object creation and function calls very easily.

You have missed the destructor. This means a non empty stack will leak all its members when it goes out of scope. So you should define a destructor to cleanup when the object is destoryed.

Now that you have a destructor:

You don't obey the rule of 3 or 5 (somebody else mentioned the rule of 7 but I don't know what that is, if somebody would like to clarify in the comments?).

Rule of 3: If you define a destructor, copy constructor or copy assignment then you probably need all three.

Rule of 5: Rule of 3 + the 2 move operators. Allows you define move operators for your object so that it is move compatible.

The alternative to using the Rule of 3/5 is to use the Rule of 0. This basically means the node object cleans itself up. This would require using std::unique_ptr. The top in your list and the next in the node would need to use this type.

Personally I don't think this is appropriate for building lists (but it is definitely an option and other people would recommend it).

You are passing by value here:

  void Push(T value)

This is fine for simple types of T. But if T is expensive to copy then you copy it to the Push method. Then you copy it again when you construct the object.

Try pushing by reference and moveable reference.

 void Push(T const& value);  // Pass value by reference.
 void Push(T&& value);       // Pass by r-value ref allowing a move.

This function does not change the state of the object.

  bool IsEmpty() {
    return top_ == nullptr;
  }

You should probably mark it as const. This allows you to pass the stack by const reference and still check the state of the object.

DRY you code.
The following code is repeated in two places

    if (IsEmpty())
      throw std::runtime_error("Stack is empty");

That means it is a candidate to be put into its own function.

You can not implement Pop() that returns a value in an exception safe manner. As such the standard stack uses two separate methods top() which returns a reference to the top value and pop() that returns void but removes the top item from the stack.

You should probably follow this convention.

These two functions return by value.

  T Peek()
  T Pop()

This means you make a copy of the value. This is fine for simple types like integer but for complex classes this is potentially expensive. Another reason to use top() and void pop(). But here at least Peek() should return a reference to avoid the copy.


Right off the bat, your code needs some serious indentation. It's barely readable given its current state. If you happen to use Sublime Text, there's HTML-CSS-JS Prettify plugin.

Another thing I noticed is you're loading jQuery twice.

Next, your code is highly coupled. Your condition to check the buttons are highly coupled to the behavior it does. What would happen if I want to change the behavior to another key? Or what if you want to operate in another platform which uses different keyboard norms (Mac vs PC)? You can read Game Programming Patterns to get an idea of configurable keys.

Another thing to consider is what if the user wants to bail out of a level? What if the user accidentally pressed a button that progressed him a level, but wants to go back and use another combination instead? Usually Esc was reserved for this. For multi-press button combinations, releasing all buttons is an option.

jQuery also has event.which which is a normalized version of charCode and keyCode.

Your code lives in the global space, which means level is highly modifiable and pollutes the global namespace. You could put your code inside a closure, an IIFE to be exact, to prevent that.


Website with images that pan to different sides

Well I can only guess without seeing the code where the DOM is actually accessed but one thing that looks big to me is that you appear to be manipulating each individual element in seperate frames. If you did the calcs in one function for all elements that would be (I believe) one set of reflow calcs set off in the browser rather than per elements-moved.

Basically any time there is a change to the DOM a series of reflow calculations is set off in the browser. I think when say three DOM changes are made in one function call, the browser is aware of all three before it starts doing anything. Whereas with seperate funcs it does that same work multiple times.

How much reflow calculation gets set off for an action on the DOM in any given browser isn't something I'm a real wizard on but IIRC tends to be a fairly crude operation that doesn't necessarily take "out of flow" elements like absolutely positioned containers into consideration. That said, I still tend to find the DOM seems to have an easier time of it when you try to optimize by taking movable elements out of flow first.

If you don't need to support older browsers, look into CSS3 animation approaches. These can drastically improve animation performance since browsers can optimize for actions before they happen.

Barring that, avoid touching the DOM as much as possible in loops. If you must access properties on a DOM element multiple times, don't keep reacquiring it. Assign it to a var, effectively caching that operation (note: might not matter in newer browsers). But actually making changes to the DOM is where you need to optimize the most. Sidestep with pre-set CSS3 animations or follow some of the older-school stuff I've outlined here and we can examine in more depth if needed.


Your ProjectLinqDataContext is disposable so make sure to wrap the usage in a using statement. Efficiency will be based on how your database is indexed. The query itself looks fine. You can also use method syntax for a more fluent and object oriented look. This doesn't affect anything, but I think it's much more readable.

using(var context = new ProjectLinqDataContext())
{
    var user = context.Customers.FirstOrDefault(y => y.CustomerUsername == model.Email && y.CustomerPassword == model.Password);
    //do something with user if it's not null
}

Make sure your password has been hashed and salted of course.


calculateCombinations

Your method does a lot of not required iterating. You only have to iterate up to x-1 in the outer loop as afterwards the if statement evaluates always to false (-> you can remove the number variable and thus the #combination call). The value of y and counter is the same on each iteration -> you can drop the counter variable.
The if statement can be removed by starting the inner loop at y+1.
The resulting code would look something like:

public static void calculateCombinations(int x) {
    int y = 0;
    while (y < x - 1) {
        y++;
        for (int i = y + 1; i <= x; i++) {
            System.out.println(y + " -- " + i);
        }
    }
}

This can be written with two for loops to keep the code shorter:

public static void calculateCombinations(int x) {
    for (int i = 1; i < x; i++)
        for (int j = i; ++j <= x;)
            System.out.println(i + " -- " + j);
}

Besides that I would rename the method as it prints the combinations, with the current name I would assume that the method returns the combinations.

permutation

This method is effectively a recursively written loop that returns the product of the range [1,i] (=factorial, thus method should be renamed to factorial) and thus can be replaced with:

public static int permutation(int i) {
    // should add check for negative values
    int p = 1;
    for (; i > 1; i--)
        p *= i;
    return p;
}

For O(1) performance you could precompute the factorials for values up to 12 (all factorials in int range).


Finding if there is a subset that sums to a target value from an array of integers

This will be a solely style-focused review, because your code (don't take it personal) looks horrible...
SPACE to breathe:
Your code is cramped, and your poor operators and statments a sqeezed together like sardines in a tin.
Spaces are free! Use them!
Tabs to clarify:
You seem to have an aversion to indenting your code, or rather really indenting it. You indent by 2 spaces. That's a little thrifty. Use one tab or four spaces instead. This makes it easier to distinguish between levels, especially when you have large blocks of indented code in one method.
Braces to see:
Additionally you seem to dislike Braces to separate blocks. So here goes:
Wherever optional, still use braces!
Why? Because it's clear, consistent and less prone to bugs when you do.
Ctrl+Shift+F to format:
Use your IDE!!! Eclipse and Netbeans are both free, and both can do much of the formatting for you.
Your Code, after Applying just these three things:
public boolean groupSum6(int start, int[] nums, int target) {
    if (nums.length == 0) {
        return target == 0;
    }

    if (start == nums.length - 1) {
        return target == nums[nums.length - 1] ||
                (target == 0 && !(nums[nums.length - 1] == 6));
    }

    if (target == 0 && nums[start] == 6) {
        return false;
    }
    if (target == 0 && !(nums[start] == 6)) {
        return groupSum6(start + 1, nums, 0);
    }

    if (groupSum6(start + 1, nums, target - nums[start]) || nums[start] == 6) {
        return groupSum6(start + 1, nums, target - nums[start]);
    }

    return groupSum6(start + 1, nums, target);
}

I think this is much more readable


Find the smallest positive number missing from an unsorted array

There are a few things you can do to simplify your code:

There's no need to keep track of the maximum positive integer if you remove the condition from the second for loop: for (int i = 1; ; i++).
That means you don't need to check whether the hash already contains the given number: just add it right away.
If you don't mind a small performance hit you can use Linq's ToHashSet instead: var set = array.ToHashSet(); (Edit: or new HashSet<int>(array); if you're not using .NET Framework 4.7.2).
Edit: Alternately, if you expect a lot of negative values in your inputs, not adding those to the set can result in a fair speed improvement - I'm seeing a 30% improvement for inputs with 50% negative values.

The first three changes don't really speed things up, and the last one is fairly input-specific. For a significant and more reliable performance improvement, replace the hash with an array of booleans:

var presence = new bool[array.Length + 1];
foreach (var value in array)
{
    if (value > 0 && value < presence.Length)
    {
        presence[value] = true;
    }
}

for (int i = 1; i < presence.Length; i++)
{
    if (!presence[i])
    {
        return i;
    }
}
return presence.Length;

The maximum possible return value is array.Length + 1, so values larger than that can safely be ignored (just like negative values) because they won't affect the result. The input [1, 2, 3] produces 4. Replacing any of these numbers with a larger one will create a gap: [1, 99, 3] produces 2. Whether or not 99 is present is irrelevant: what matters is that 2 is not present.

For large inputs this is about twice as fast, for small inputs it can be more than 10x faster. Hash set lookups are fast, but there is some overhead involved, so they won't beat array lookups.

Edit: The proposed solution on their website is (re)using the input array as a lookup table. It's moving all positive numbers to the front and then marking the presence of numbers by making the value at that index negative - somewhat similar to the above approach. I guess the first step allows them to simplify the rest of the algorithm, but it does make things slower. That first step can be removed with careful swapping and negating, making it run faster, but it's still a bit slower as the array of boolean approach - and more difficult to understand.


I think it is usually better to take advantage of the built-in functions. Python lists already have a sort function, so you would expect a list of pool balls to be sortable by the start arrangement (a list of tuples/lists is already sortable, Python compares them element wise).

One way to achieve that is with a custom key function:

order = [1, 13, 11, 7, 8, 6, 9, 5, 14, 15, 2, 12, 3, 10, 4]
# Simplified balls list, as the fill style is not really needed for this
balls = [[n] for n in range(1, 16)]
balls.sort(key=lambda ball: order.index(ball[0]))

This is very succinct, but you could also promote the lambda key function to a proper function:

def pool_start_order(ball):
    order = [1, 13, 11, 7, 8, 6, 9, 5, 14, 15, 2, 12, 3, 10, 4]
    return order.index(ball[0])

balls = [[n] for n in range(1, 16)]
balls.sort(key=pool_start_order)

Another alternative is to make a PoolBall class, that is sortable, something like this:

class PoolBall(object):
    order = [1, 13, 11, 7, 8, 6, 9, 5, 14, 15, 2, 12, 3, 10, 4]

    def __init__(self, number):
        assert 1 <= number <= 15
        self.number = number
        self.fill = 'Solid' if number <= 8 else 'Striped'
        self.order = PoolBall.order.index(number)

    def __lt__(self, other):
        return self.order < other.order

    def __eq__(self, other):
        return self.number == other.number

    def __str__(self):
        return "{self.number} {self.fill}".format(self=self)

    def __repr__(self):
        return "{self.__class__.__name__}({self.number})".format(self=self)

    balls = [PoolBall(i) for i in range(1, 16)]
    balls.sort()

Here, the __str__ and __repr__ are just there for pretty printing.

Whichever way you go, once you have a correctly sorted list of balls, you can use a function that successively takes one more ball, something like:

def pyramid_arrangement(balls):
    """
    Given a list of balls, arranges them in a pyramid shape.
    Yields each row.

    Leaves the balls list empty.
    """
    take = 1
    while balls:
        yield [balls.pop() for _ in range(take)]
        take += 1

Which you can use like this:

if __name__ == "__main__":
    balls = [PoolBall(i) for i in range(1, 16)]
    balls.sort(reverse=True)
    for row in pyramid_arrangement(balls):
        print row


Checking if a number is divisible by 2-11

You do this quite alot

if s % 3 == 0:
    return True
else:
    return False

Instead you could return directly

return s % 3 == 0


Return the condition
When we test for equality, a == b is either 1 if they're equal or 0 if they're not (see C11 §6.5.8 Relational operators). Therefore we can simply return the expression instead of an if-else construct:
bool fifo_is_full(struct fifo * fifo)
{
    return fifo->elements == fifo->size;
}

bool fifo_is_empty(struct fifo * fifo)
{
    return fifo->elements == 0;
}

Feel free to add parentheses around the expression to make it more readable. Alternatively we can use a ternary expression, but that just adds noise and has no additional benefit.
Interrupt safety
fifo_add_byte and fifo_get_byte are not interrupt safe.
Let's say we're using fifo_add_byte somewhere in our usual code but also in an interrupt handler, for example to queue jobs. In main we check current GPIO pin states, and the interrupt comes from some kind of bus.
For the sake of simplicity, let's assume fifo->write_index == 0 and fifo->elements == 0.
We enter fifo_add_byte in main:
// in main:
fifo_add_byte(job_fifo, GPIO_PIN4_STATE);

and follow its definition:
bool fifo_add_byte(struct fifo * fifo, uint8_t newbyte)
{
    if (fifo_is_full(fifo))
    {
        return 0;
    }
    else
    {
        if (fifo->data_ptr == NULL)
        {
            return 0;
        }
        const uint16_t MASK = fifo->size - 1;
        fifo->data_ptr[fifo->write_index] = newbyte;
...

And then an interrupt occurs. We already wrote fifo->data_ptr[0] = GPIO_PIN4_STATE so our data is safe, right?
Well, inside the interrupt handler, we have the following line:
// in interrupt_handler_i2c:
fifo_add_byte(job_fifo, i2c_read_data);

fifo->write_index didn't get updated in our main yet, so our fifo->data_ptr[0] will now be set to i2c_read_data. Afterwards, fifo->write_index gets incremented before we exit the interrupt handler and then again after we enter main again:
// ... back in main:
        fifo->write_index = (++fifo->write_index) & MASK;
        fifo->elements++;
        return 1;
    }
}

Our fifo->data_ptr now contains { i2c_read_data, 0, ... }, fifo->write_index = fifo->elements = 2. However, GPIO_PIN4_STATE's value is lost.
Depending on the plattform, fifo->elements++ or another increment operation might get interrupted and even that operation won't work. And no, volatile isn't a proper solution for interrupts.
We have some ways to remedy this:

we could use critical sections in our index-logic to prevent interrupts
we could use atomic indices/sizes, if our platform supports those
we could mark the fifo "in use" and just return false during an interrupt, but that hinders functionality (it's also very error prone and subject to similar issues)
we could do nothing and simply state that the FIFO isn't safe to be written to from both the usual program and interrupt handlers (same for reading from both locations)

And that's the least we can do to fix this issue: add documentation.
Documentation
None of our code is documented. At least fifo_init needs a documentation, and it needs a very large warning about using a power-of-two size. Otherwise, our MASK logic will yield most interesting behaviours.
The documentation is also the perfect place to state interrupt safety. The FIFO is safe to use within interrupts*, as long as its only written to from within those and only read from outside of an interrupt context.
Usual C-style comments (or Doxygen comments for fancy exports) can be used within our code:
/**
 * \file fifo.c
 *
 * \warning When you use a FIFO in the context of ISRs, make sure that the information
 *          flows only in one direction, e.g. use fifo_add_byte only in ISRs and
 *          fifo_get_byte only in the rest of your program or vice versa.
 *
 *          Using fifo_add_byte in both ISRs and the rest of your program might
 *          yield unexpected results.
*/

...

/**
 * Adds the given byte to the fifo.
 *
 * \returns false if the fifo is full or the data pointer is invalid
 *
 * \warning This function MUST be either used exclusively from ISRs OR the rest
 *          of your program and MUST NOT be used in a recursive ISR context.
*/
bool fifo_add_byte(struct fifo * fifo, uint8_t newbyte)
...

Now, you might think that this is a little bit too much, and you're completely right. The following documentation might prove enough:
/** WARNING WARNING WARNING
 * Only push bytes in interrupt routines and only pull bytes in your `main`
 * (or the other way round)!
*/

However, there should be at least something, even if it will be only read by a future version of you. But that future version will be glad to have some hint why data might get lost or duplicated.
*: Truth be told: that depends whether elements++ and elements-- are atomic operations on our platform.
Parting words
Interrupt safety, code brevity and missing documetation aside: well done. Your code is well-formatted, the overall ring-buffer FIFO design is sound, and it's something I'd write in a similar way. I'm not a fan of the & MASK logic, to be honest, but that's personal preference. Also keep in mind that volatile does not mean thread- or interrupt-safe, so better have a look at the keyword and atomics.
Other than that: Well done.


Determining whether (x,y) points in the input constitute a function

Let's condense this down. What you're trying to check is that for any given x, the y values you're told are all the same.

Now let's try to express this as succinctly as possible:

Let's start with a few simplifying assumptions. All your x and y values are going to be integers. Furthermore, let's assume we handle them as Tuples and not as Lists. This enables a somewhat cleaner signature for our types

We start with a list of points and in the end we want a boolean to drop out. Our type signature accordingly looks like this:

isFunction :: [(Int, Int)] -> Bool

This function can be decomposed into a few steps. First we need to group by the x values.

isFunction points = -- we'll fill this in later
   where
   grouped = groupWith fst points -- fst accesses the first item in a tuple

now that we have all points grouped, we need to examine their y values

   ys = map (map snd) grouped -- snd gets the second item in a tuple

And now we want to make sure that every group of y values is always the same value.
For this I'll use a bit of a hack

   areEqual = map (\l -> all (== (head l)) (tail l)) ys

What this does is a bit hard to grasp at first glance, but types will help us understand.

Let's fill back the types for all the stuff we had until now:

grouped :: [[(Int, Int)]]  -- List of List of Points
ys :: [[Int]]  -- List of List of Integers

Now let's examine what this does in areUnique. We know that none of the lists in ys are empty. That's very useful for accessing the first element in the list and setting it as baseline for the rest of the list we're examining. All items in a single list (and accordingly belonging to a single x) must be pairwise equal. This explicitly means they must be equal to the first item.

That's how we can use all (== (head l)). That line could also be written as the following:

   areEqual = map (\yGroup -> all (== yGroup!!0) yGroup)

Now we have in areUnique a [Bool], each of them indicating, whether the group is consistent.

That allows us to formulate the final result of isFunction we omitted above:

isFunction points = all id areEqual

So now we have a pretty function that will do the work of your is_func, including all the work of no_other_y. We need to import GHC.Exts for it to work, because it provides groupWith. If you don't have GHC on your system, you will need to write a replacement, but that's probably a good exercise in itself. Only that much: sorting before grouping helps a lot.

A nice sideeffect of this is that we're reducing the time-complexity from \$\mathcal{O}(n^2)\$ to \$\mathcal{O}(n \log n)\$

Now aside from this move away from list comprehension into a more explicit model that should additionally be quite a bit faster, there's not that many things to say about your code.

Granted, you largely ignore types (which is something that I personally do exactly the opposite of) and you're using python naming conventions, which only clashes with readLn, getLine and replicateM_.

This is what we got for now:

import GHC.Exts  (groupWith)

isFunction :: [(Int, Int)] -> Bool
isFunction points = all id areEqual
   where
   grouped = groupWith fst points
   ys = map (map snd) grouped
   areEqual = map (\l -> all (== l!!0) l) ys

Now let's get a bit fancier. We can inline a few of these definitions:

areEqual = map (\l -> all (== l!!0) l) (map (map snd) grouped)

notice the repeated use of map. We can get around that by using function composition (.):

areEqual = map ((\l -> all (== l!!0) l) . (map snd)) grouped

interestingly it's not necessary to map to the y value alone. While semantically appropriate, the x values already should be the same. This allows us to drop the mapping:

areEqual = map (\l -> all (== l!!0) l) grouped

Now we can inline grouped to obtain (which uses $, the self closing parenthesis):

areEqual = map (\l -> all (== l!!0) l) $ groupWith (fst) points

And to top it off, this can be inlined into our all, which gets us to:

isFunction points = all id $ (map (\l -> all (== l!!0) l)) $ groupWith fst points

At this point we replace our fancy self-closing braces with function composition to obtain

isFunction points = (all id) . (map (\l -> all (== l!!0) l)) . (groupWith fst) points

which can then be reduced to:

isFunction = (all id) . (map (\l -> all (== l!!0) l)) . (groupWith fst)

That in turn can be simplified to (hat tip to @Gurkenglas):

isFunction = all (\l -> all (== l!!0) l) . groupWith fst


Closest distance between points in a list

1. Review

There are no docstrings. What do these functions do? What arguments do they take and what do they return?
You write:

  I just tried to delay the sqrt computation as long as possible

This suggests that your cost model for Python is not quite right. In CPython, it's more expensive to call square than it to call sqrt:

>>> from timeit import timeit
>>> timeit('square(999)', 'from __main__ import square')
0.11685514450073242
>>> timeit('sqrt(999)', 'from math import sqrt')
0.057652950286865234

That's because most of the time executing a program in CPython is spent in the execution of bytecode. The actual cost of computing the square root is small by comparison.

Because bytecode is expensive, it sometimes pays (in CPython) to do more computation, if you can arrange for it to be done in the fast C implementation rather than in slow Python code. In this case I would consider using math.hypot, like this:

from math import hypot

def distance(p, q):
    "Return the Euclidean distance between points p and q."
    return hypot(p[0] - q[0], p[1] - q[1])

This is faster than calling square_distance:

>>> timeit('square_distance((1, 2), (3, 4))', 'from __main__ import square_distance')
0.4481959342956543
>>> timeit('distance((1, 2), (3, 4))', 'from __main__ import distance')
0.32285499572753906

In closest, the argument n must be the length of the list of points P. So it would be simpler to assign it yourself and avoid the requirement for the caller to pass it in (which is risky, because the caller might get it wrong).
The function closest has a side-effect: as well as computing the shortest distance, it sorts the list P. Unexpected side effects should be avoided — it is easier to understand code if it only has "local" effects on data structures. In this case, there are two alternatives: you could require the caller to sort the points before passing them in, or you could take a copy and sort the copy, like this:

def closest(P):
    "Return the closest Euclidean distance between two points in the list P."
    return _closest_distance(sorted(P), len(P))

When recursing:

dl = _closest_square_distance(P[:mid], mid)
dr = _closest_square_distance(P[mid:], n - mid)

the list slice P[:mid] has to copy out the contents of the slice. It would be cheaper to remember the endpoints of the slice you are working on and avoid the copying:

def _closest(P, start, stop):
    # closest Euclidean distance between two points in the slice P[start:stop]
    # handle base cases here

    mid = (start + stop) // 2
    dl = _closest(P, start, mid)
    dr = _closest(P, mid, stop)

In the base cases, you could save some duplication by using itertools.combinations and writing:

if n <= 3:
    return min(distance(p, q) for p, q in combinations(P, 2))

The base case logic could be extended to larger values of n. I find that for large random point sets, n <= 8 performs well.
The function:

lambda x: x[1]

is the same every time, so consider storing it in a global variable (or using operator.itemgetter(1)).
The code finds the points in the strip by iterating over all the points in P. But since you have the points sorted by their \$x\$ coordinate, you can find the endpoints of the strip using the bisect module.
The code does not take advantage of the fact that the two points being compared can only be closer than closest_distance if they were in different halves (if they were in the same half, then they have already been compared by the recursive calls and closest_distance already takes them into account).

2. Revised code

from bisect import bisect_left, bisect_right
from itertools import combinations, islice
from math import hypot
from operator import itemgetter

def distance(p, q):
    "Return the Euclidean distance between points p and q."
    return hypot(p[0] - q[0], p[1] - q[1])

_Y_COORD = itemgetter(1)

def closest_distance(P):
    "Return the closest Euclidean distance between two points in the list P."
    P = sorted(P)
    PX = [x for x, _ in P]

    def _closest(start, stop):
        if stop - start <= 8:
            return min(distance(p, q)
                       for p, q in combinations(P[start:stop], 2))

        mid = (start + stop) // 2
        dist = min(_closest(start, mid), _closest(mid, stop))

        mid_x = PX[mid]
        left = bisect_left(PX, mid_x - dist, lo=start, hi=mid)
        right = bisect_right(PX, mid_x + dist, lo=mid, hi=stop)
        strip = sorted(P[mid:right], key=_Y_COORD)
        strip_y = list(map(_Y_COORD, strip))

        for p in P[left:mid]:
            y = p[1]
            i = bisect_left(strip_y, y - dist)
            j = bisect_right(strip_y, y + dist)
            assert j - i <= 6
            for q in strip[i:j]:
                dist = min(dist, distance(p, q))

        return dist

    return _closest(0, len(P))


You could start by actually trying to combine them yourself. :/ we appreciate code reviews but honestly this was a copy and paste job.

function accountDeactivate(msg) {
  if (!$('.accountautologoff').length) {
    $('.content').append('
' + msg +'
');
    $('body').addClass('disabled');
    $('html').removeClass('loading');
    $('.accountautologoff').hide().fadeTo(600, 1, 'swing');
    $(document).bind('mousewheel', function (e) { e.preventDefault(); });
    $('.content-home, .content-search').fadeTo(600, 0.5, 'swing');
  };
}


Generate the Norwegian equivalent to social security numbers

Comment on C++ interface:

You are doing work outside of ID that belongs as part of the class:

ID generator;

for(int i = 0; i < DATE_LENGTH; i++){
    *(generator.getDate() + i) = int(dateString[i]-'0');
}

generator.setYear(1900 + (*(generator.getDate() + 4) * 10) + *(generator.getDate() + 5));

while(i < 500){
    generator.individSiffer();
    generator.generate();
    i++;
}

Because this work is not part of a method you are exposing implementation details of your ID class via getter methods. All of which is bad:

A better interface would have been:

std::string date = getDate(); // Get a valid date or throw.
ID          generator(date);

std::cout << generator;

Comments on Code

Don't use this interface.
What happens if the user types an extra long line of stuff.

cin.getline(dateString, BUFFER);

Its not going to crash but you are left with lots of crap on the input stream. User input is line based so read a line from the user and then try and parse the line. Because a line can be any length don't use that version of get line.

std::string line;
while(std::getline(std::cin, line))
{
    // Valid line has been read.
    if (validDate(line))
    {    return line;
    }
    std::cerr << "Invalid date please try again\n";
}
throw std::runtime_error("The user give up trying to enter a date correctly");

Comments on C functions

C based functions for printing printf() are dangerous, because they are not type safe. Prefer to use the C++ type safe streams.

Comments on Data values

generator.setYear(1900 + (*(generator.getDate() + 4) * 10) + *(generator.getDate() + 5));

What about people born after 31st Dec 1999?

Comments on Loop structures

while(i < 500){
    // STUFF
    i++;
}

// This kind of loop is better written as a for:

for(int loop=0; loop < 500; ++loop) {
    // STUFF
}

Also notice that I am declaring my loop variable as close to the point of usage as possible. Do not use the C style of putting all the variables at the top of the function. Put your variables where you can see there declaration and type easily.


Helper method to shuffle cards list for online gaming

4 bytes is only 4,294,967,296
Consider there are 52! possible shuffles = 8 * 10^67

Use a proper shuffle like Fisher Yates. You get a proper shuffle with only 0-51 random.  Also shuffle from the prior shuffle (not a sorted deck). If you look closely Fisher Yates it produces exactly 52! deals.  It is perfect.

I am not sure about your algorithm but I think the problem is that it will produce too many shuffles and they will not have uniform distribution.  I think it will produce 52^52 deals.

A perfect random with a less than perfect algorithm is a bigger vulnerability than a perfect algorithm and a less than perfect random.

You can use the regular Random and a proper algorithm and not be exploited unless they know the seed.  But it does not hurt to use RNGCryptoServiceProvider.

Poker security


Find sum of 3 that total a target from a List

In general it looks OK to me, but you could maybe consider the following:

1) Return a IEnumerable<int[]> instead of List<List<int>> and then yield the positive results when found:

            ...
            else if (sumSoFar == sum)
            {
              yield return new int[] { iValue, jValue, kValue };
            }...

2) The names sumI, sumJ, sumK are somewhat misleading because they aren't sums. Better names would be valueI, -J, -K

  int valueI;
  int valueJ;
  int valueK;

3) For the fun of it, you could consider: Because you basically do the same same loop nested three times, it could be a candidate for a recursive function iterating over each addend and yielding all the positive sums. In that way you could generalize the algorithm to handle any number of addends...


1. Introduction

You asked:

  what should I do at first when I face this kind of problem?

This is a good question! When I studied computing at university I was taught the following general technique:

Analyze the program and work out its complexity — that is, how does its runtime depend on its input?
Measure its runtime on some small examples.
Combine the complexity from step (1) with the measurements from step (2) to estimate the runtime for the worst case.
If the worst case is unacceptable, try to find a better algorithm.

As you get better at carrying out these steps, some of them will become second nature to you and so you won't have to go through them all in such detail as I do below. But when you're starting out, or unsure about the approach to take it's good practice to be thorough.

2. Analysis

The way to analyze a program is to annotate each line with the time it takes and the number of times it is executed. Then all you have to do is multiply and add!

But that's easier said than done, because how on earth do we know how long each line takes to execute? If we really wanted an accurate answer we could estimate it by running lots of tests. But we don't actually need to compute an exact answer: we just want an idea of how the runtime varies as a function of the input size. So as a first approximation, we'll say that simple operations (assignment, calling xrange, etc) take constant time 1, and that arithmetic operations like addition and subtraction take time proportional to the number of digits in the numbers. (We'll see later that this is an over-simplification, but it will have to do for now.)

CODE                          TIME TAKEN  NUMBER OF EXECUTIONS
============================  ==========  ====================
sum = 0                       1           1
z = k                         1           1
for i in xrange(1, n+1, 2):   1           n / 2
    d = z * 2                 log z       n / 2
    sum += d                  log sum     n / 2
    z = z * k                 log z       n / 2
if (n + 1) % 2 == 0:          log n       1
    sum = sum - d // 2        log sum     0 or 1
r = sum % 1000000007          log sum     1

(Note that I've rewritten the code to use n and k instead of a and b, so that the code more closely matches the statement of the problem.)

Now, in order to turn this into a total runtime, we need to know how big sum and z become. Well, \$z\$ gets multiplied by \$k\$ on each iteration of the loop, so after the \$i\$th iteration, \$z = k^{i+1}\$, and so \$z\$ is no more than about \$k^{n\over 2}\$ and so \$\log z\$ is no more than about \$n \log k \over 2\$.

At each iteration we add \$2z\$ to sum, where \$z\$ is no more than \$k^{n\over 2}\$. And there are about \$n \over 2\$ loop iterations, so sum is no more than \$nk^{n\over 2}\$ and so \$\log{sum}\$ is no more than \${n\log k\over2} + \log n\$. So adding everything up, we get a total runtime bounded by $$1 + 1 + {n\over 2} + {n^2 \log k \over 4} + {n^2 \log k + n\log n \over 2} + {n^2 \log k \over 4} + \log n + 2{n \log k + \log n \over 2}$$ which we can reorganize in terms of \$n\$ to get $$ n^2 \log k + {n\log n\over 2} + (\log k + {1\over 2})n + 2\log n + 2.$$  Now, as \$n\$ gets large, the terms containing \$n^2\$ will dominate (all the other terms become small by comparison). So we expect that as \$n\$ becomes large the runtime will become roughly proportional to \$n^2\log k\$.

(If this looks kind of complicated, it's because I've written out all the steps in detail. When you get experienced with the method, then you can skip all the steps that you know aren't going to appear in the result and just concentrate on the "big guns". For example, I would say to myself, "hmmm, that's \$Θ(n)\$ loops, each of which is handling numbers of typical size \$Θ(n\log k)\$ so the total runtime is \$Θ(n^2\log k)\$.")
Measurement is easier if we organize the code into functions, like this:

def palindromes(n, k):
    """Return the number of palindromes up to n letters long, using an
    alphabet of k letters, modulo 1000000007.

    """
    sum = 0
    z = k
    for i in xrange(1, n + 1, 2):
        d = z * 2
        sum += d
        z = z * k
    if (n + 1) % 2 == 0:
        sum = sum - d // 2
    return sum % 1000000007

Now we can measure the time taken (using Python's built-in timeit module) for some small values of \$n\$:

from timeit import timeit

def t(n, k):
    """Return the time taken to compute palindromes(n, k)."""
    return timeit(lambda:palindromes(n, k), number=1)

>>> t(10**3, 26)
0.0003402099828235805
>>> t(10**4, 26)
0.01810335897607729
>>> t(10**5, 26)
1.3598145439755172
>>> t(10**6, 26)
137.12631450797198

Let's plot the measurements from step (2) and draw a line of best fit to the equation \$t=an^2\$ that we worked out in step (1):

The fit looks pretty good and the coefficient of proportionality is \$a = 1.37 × 10^{-10}\$.

The worst case from the problem description is \$n=10^9\$, so this would result in a runtime of \$1.37 × 10^8\$ seconds, which is more than 4 years.
Four years is likely to exceed the time limit, so we need a better algorithm. How do you come up with one? Well, there are basically two sensible approaches here.

The first is to look for existing algorithms that solve the problem (or similar enough problems). It helps here to be familiar with lots of different types of algorithm so that you have some idea of where to look. And the way to become familiar with lots of algorithms is to read algorithms textbooks and then do some of the exercises.

The second approach is to use mathematical analysis to find alternative ways of computing the same results. For example, if you had a function like this:

def nsum(n):
    """Return a sum that depends on n."""
    result = 0
    for i in xrange(n):
        result += 1
    return result

Then I'm sure you could find a mathematical expression for the result in terms of the input \$n\$, and that would allow you to simplify the body of this function to:

    return max(n, 0)

or even:

    return n

if you didn't care about negative values of \$n\$.

3. Improving the algorithm

In this problem the mathematical approach looks like the way to go. Take a look at the analysis in §2.1 above. You can see that I was able to get quick estimates for the size of z and sum. But with a bit more care, could we work out the exact values for these variables?

Let's try that. We know that at the start of the \$i\$th iteration, \$z = k^i\$, and so \$d = 2k^i\$. So after \$m\$ loop iterations, the sum is $$ \sum_{1 \le i \le m} 2k^i = 2\sum_{1 \le i \le m} k^i. $$ If \$k=1\$ then this is \$2m\$, otherwise using the formula for summation of a geometric series it's $$ 2\left({k^{m + 1} - 1 \over k - 1} - 1\right). $$ There are exactly \$m = \left\lfloor{n + 1 \over 2}\right\rfloor\$ loop iterations, and if \$n\$ is odd we have a final subtraction of \$- k^m \$. So this suggests the following code:

def palindromes2(n, k, p=1000000007):
    """Return the number of palindromes up to n letters long, using an
    alphabet of k letters, modulo p.

    """
    if k == 1:
        return n % p
    m = (n + 1) // 2
    r = 2 * ((k**(m + 1) - 1) // (k - 1) - 1)
    if n % 2:
        r -= k**m
    return r % p

But we're not done! The first thing to do is to check that this is right, as it would have been easy to make a mistake in the mathematics. So let's check this function against the original:

>>> all(palindromes(n, k) == palindromes2(n, k)
...     for n in range(1, 1000) for k in range(1, 27))
True

But is it fast enough? Measurements suggest that it is faster that the first version of the code, but not fast enough to get the answer for \$n=10^9\$ in reasonable time:

>>> t(10**4, 26)
0.00031872402178123593
>>> t(10**5, 26)
0.011414641980081797
>>> t(10**6, 26)
0.2926187649718486
>>> t(10**7, 26)
11.10361772798933

We had better go through the analysis again for the new program and estimate the runtime. This time I'll omit the detailed analysis and cut straight to the point: we have some arithmetic operations here, on numbers that get as big as \$k^{{n + 1 \over 2}+1}\$, that is, with roughly \$n \log k\$ digits. We expect additions and subtractions on numbers of this size to take time roughly proportional to \$n \log k\$, and similarly for multiplication and division by small numbers. But there are also two exponentations: how long do these take? Well, I don't know about you, but I'm not sure of the runtime complexity of Python's ** operator. So there are two ways to go here: we could dive into the details of Python's exponentiation algorithm (yuck), or we could just assume that computing \$k^m\$ takes time proportional to some power of \$n \log k\$, say \$1 + b\$, and work out the value of \$b\$ by fitting the measurements to the equation \$t = an^{1+b}\$. Here's the best fit:

with parameters \$a = 4 × 10^{-11}\$ and \$b=0.63\$. (The value for \$1+b\$ is close to the exponent in the Karatsuba multiplication algorithm, which is the algorithm that CPython uses for multiplication of big numbers — see the function k_mul in longobject.c.)

So in the worst case (\$n = 10^9\$) the new algorithm is going to take about 5 hours. This is better than the 4 years of the original algorithm but is still likely to be unacceptable!

4. Further improving the algorithm

So we have to find another improvement. This is looking tricky: where can that come from? Well, the key observation is that the final result has to be returned modulo \$10^9+7\$, and so it can never have more than ten digits. And yet the intermediate values that we are computing are huge: in the worst case, \$k^m\$ has hundreds of millions of digits. This is a terrible waste of computation if we are going to compute a number with at most ten digits. So is there a way that we can do all the arithmetic modulo \$10^9+7\$ and so keep the intermediate values small?

How is that going to work? Modular addition, subtraction and multiplication are easy — we just add, subtract or multiply normally and then take the modulus later. For efficient modular exponentiation we can use the built-in function pow.

But we need a modular division operation in order to divide by \$k - 1\$, and Python doesn't have one built-in. In fact, modular division doesn't always exist — we can only divide by \$x\$ modulo \$p\$ if there is a unique number \$y\$ such that \$xy ≡ 1 \pmod p\$. (In this case \$y\$ is called the "multiplicative inverse of \$x\$ modulo \$p\$".) Luckily the modulus \$p\$ is prime, and this means that the multiplicative inverse \$y\$ exists for every \$x ≠ 0\$, and we can use the extended Euclidean algorithm to compute it.

That leads to this implementation:

def modular_inverse(x, p):
    """Return the multiplicative inverse of x modulo the prime p."""
    y, z, a, b = 0, 1, p, x
    while b:
        a, (q, b) = b, divmod(a, b)
        y, z = z, y - q * z
    return y

def palindromes3(n, k, p=1000000007):
    """Return the number of palindromes up to n letters long, using an
    alphabet of k letters, modulo the prime p.

    """
    if k == 1:
        return n % p
    m = (n + 1) // 2
    r = 2 * ((pow(k, m + 1, p) - 1) * modular_inverse(k - 1, p) - 1)
    if n % 2:
        r -= pow(k, m, p)
    return r % p

Again, we must check that this is correct:

>>> all(palindromes(n, k) == palindromes3(n, k)
        for n in range(1, 1000) for k in range(1, 27))
True

and see how bad the worst case is:

>>> timeit(lambda:palindromes3(10**9, 26), number=1)
3.3604970667511225e-05

That's probably acceptable now.


Some notes:

(months -1) if today.day < birth_date.day. Note that this is doing nothing, months - 1 is evaluated and dropped.
There is a age = in every branch of the conditional, and finally age is returned. That's unnecessary and not idiomatic, in Ruby conditionals are expressions, so we don't need to create a variable.
About this:

age = "#{months} months" if years == 0
age = "1 year, #{months} months" if years == 1

It's preferable not to use in-line conditionals when you are dealing with assignments or expressions (it's ok if you are performing side-effects, i.e. fail("error") if x < 0). In general follow functional programming guidelines, specially when dealing with logic (if you do some programming that does not deal with logic, please let me know ;-)). It should look (you could also use a case) something like this:

age = if years == 0
  "#{months} months"
elsif years == 1
  #{months} months" if years == 1
...
end

I'd write:

def age(birth_date)
  today = Time.zone.today
  total_months = (today.year*12 + today.month) - (birth_date.year*12 + birth_date.month)
  years, months = total_months.divmod(12)
  strings = [[years, "year"], [months, "month"]].map do |value, unit|
    value > 0 ? [value, unit.pluralize(value)].join(" ") : nil
  end
  strings.compact.join(", ")
end

Note that, to keep it simple, this code (as yours) ignores the day of the month, which gives a slightly wrong answer.


Considering that you simply return null if the itemproperties are null, do that immediately:

if (itemproperties == null)
{
    return null;
}

if (propName.Contains("."))
{
}

That way you don't need to have 80+ lines inside an if.

The same is probably true for your next check -- if (propName.Contains(".")) -- but since you don't provide us with enough information I cannot help you there: where does propName come from? Where does record come from?

I see duplicate code:

actualproperty.Substring(0, actualproperty.IndexOf('['));
propertyNameList[i].Substring(0, propertyNameList[i].IndexOf('['));

Shouldn't that be converted to a method call?


In order to simplify the user interface I switched to using a drop down list. It has minimized the amount of visual interference the original script had on the webpage as well as streamlined the code.

var zNode       = document.createElement ('div');
zNode.innerHTML = `
Selection Report
<select name='selection' id='numbers'">
    <option value="Choose" selected="selected">Choose Option</option>
    <option value="#ctl00_CPH_lsD_pnlListSelector input:checked">Departments Selected</option>
    <option value="#ctl00_CPH_lsD_pnlListSelector input:not(:checked)">Departments Not Selected</option>
    <option value="#ctl00_CPH_lstSelectorPosition3_pnlListSelector input:checked">Hospitals Selected</option>
    <option value="#ctl00_CPH_lstSelectorPosition3_pnlListSelector input:not(:checked)">Hospitals Not Selected</option>
    <option value="#ctl00_CPH_lsJT_pnlListSelector input:checked">Job Titles Selected</option>
    <option value="#ctl00_CPH_lsJT_pnlListSelector input:not(:checked)">Job Titles Not Selected</option>
    <option value="#ctl00_CPH_lsJF_pnlListSelector input:checked">Job Functions Selected</option>
    <option value="#ctl00_CPH_lsJF_pnlListSelector input:not(:checked)">Job Functions Not Selected</option>
</select>`;

zNode.setAttribute ('id', 'myContainer');
document.body.appendChild (zNode);

GM_addStyle ( `
    #myContainer {
        position:               absolute;
        top:                    0;
        right:                  0;
        font-size:              20px;
        color:                  white;
        background:             green;
        border:                 3px outset black;
        margin:                 2px;
        padding:                2px 2px;
        text-align:             center;
    }
    #myContainer span {
        margin:                 0 10px;
    }
    #hospNotSelectBtn {
        cursor:                 pointer;
    }
    #hospSelectBtn {
        cursor:                 pointer;
    }
    #deptNotSelectBtn {
        cursor:                 pointer;
    }
    #deptSelectBtn {
        cursor:                 pointer;
    }
    #jobSelectBtn {
        cursor:                 pointer;
    }
    #jobNotSelectBtn {
        cursor:                 pointer;
    }
    #jobFunctionSelectBtn {
        cursor:                 pointer;
    }
    #jobFunctionNotSelectBtn {
        cursor:                 pointer;
    }
    #myAlertBox {
        font-size: small;
        background: white;
        border: 5px solid green;
        padding: 4px;
        position: absolute;
        top: 280px; right: 80px;
        max-width: 300px;
        white-space:pre-wrap;
    }`);


Because of the lexicographically smallest tie breaker restriction, you're basically funelled down this approach. In particular, you can't do without the sort.

"""Returns array in wave pattern by first sorting
the array and then swapping the adjacent digits"""

Docstrings are interface level documentation. They should describe what a function does, not how it does it. For a description of how a given implementation works, use comments.

array.sort()  ##sort the given array

Consider whether it's appropriate to do this in place (and so mangle the input array) or whether it would be better to use sorted

for i in range(0,(len(array)-1),2):  ##skip every second number
    array[i], array[i+1] = array[i+1], array[i]  ##swap adjacent numbers

You could rewrite this generators or using various tools from itertools if you wanted to avoid the explicit for loop.

However, what you have is clearer about what's going on and, given that you are working from a list already, reasonable in terms of performance.

print wave([6,7,8,1,2,3,4])
print wave([5,1,3,4,2])
print wave([11,3,5,2,7,1,6,8,10,9,4])

I note that you're only checking odd length lists with no negatives and no duplicates. Consider more comprehensive testing.


I don't think much of it, to be honest.  It's not as reliable as you might think, because once you start passing objects between contexts (e.g. different windows) it will fail miserably.  Add to that the fact that

Object.prototype.toString.call(<any value>);

could do most of your work for you and your extension starts to look a little redundant and unnecessary.

Here's a detailed article on this problem: Cross-context isArray and Internet Explorer


First of all, it's probably best to realize that a heap isn't particularly useful for this problem as it's specified. It can be used, but it doesn't really contribute much (if anything at all).

If you do use a heap, you want to take the specific properties of a max heap into account. In particular, a heap is arranged so each node is at least as large as any of its descendant nodes. As such, the first node is always the largest. The second largest is one of the second and third. In a typical case, the other of the second and third will be the third largest (and depending on how we insert items into the heap, we can enforce that being the case, which we probably want to do here). This allows us to find the three largest items in the heap without actually removing them from the heap at all.

As to why we don't need to use a heap, and why it doesn't really contribute much: we really only care about the three largest items seen at any given point. That being the case, we can start with the first three. They're clearly the largest seen to that point, so their product is the first (meaningful) output. Then we want to find the smallest of those three. Compare that to the fourth item, and if it's larger, copy it over the smallest of the first three, then print the product of the first three. Repeat that (find smallest, check against next item, get new value if larger, print out product) until we reach the end of the input.

This requires something like four comparisons (and possibly one assignment) per iteration, regardless of the number of inputs. A quick test shows it running in ~400 ms on my machine

At least in theory, this can be further optimized by observing that the smallest of the first three can only change when we add a new (larger) item to the first three. When we read a number and it's smaller than the smallest of the first three, we can print the previous product, throw away the new number, and repeat.

At least in a quick test on my machine, the latter doesn't seem to make a noticeable difference though. This is probably because the actual computation is already fast enough to keep up with the I/O, so speeding the computation up even more makes little (or no) difference. It's also possible, however that with only three numbers to look at, it's just as fast to scan them as it is to decide whether to scan them or not.


Count the occurrence of each unique word in the file

Efficiency

I won't say much about efficiency - because without a clear use-case it will be hard to know whether possible changes would be worth the effort - but my main concern would be fact that you force a whole file into a string, of which you immediately produce a second copy. It would be nice to see a version which takes a stream of some description rather than a whole file, as this could (in theory) cope with very large files (ones which can't fit in memory), could have much better memory characteristics, and with a bit of effort could start processing the file before it has read the whole thing, so that you are not stalled waiting for the whole file before you can begin (though an asynchronous implementation would be necessary to fully exploit such possibilities).

API

Don't hard-code the input file-name. Put this code in a nicely packaged method, and take the input as a parameter. This parameter could be a file-name, but it could also be a Stream or String (if you intend to always read the whole thing at the start) or whatever; you can always provide a convenience method to cover important use-cases.

And don't print the output to the console: if the calling code wants to print the counts to the console, let it do that, but give it the information it needs to do what it wants, rather than deciding what to do with the information for it. Returning the dictionary (perhaps as an IDictionary, so that you aren't coupled to the particular class) produces a much more useful interface.

IDictionary<string, int> CountWordOccurances(string text);

If your specification says that you must be printing these counds to the console, then you can write a method to print out the dictionary (perhaps to an arbitrary TextWriter, rather than only Console.WriteLine, which is no fun to test against), and write another method which composes the two.

Comments

Comments should be useful, explaining why code is doing what it is doing or providing some important context. // Converts the string to lower case string says nothing which text.Tolower() doesn't already, and is liable to rot as the method is modified. The code uses the Regex object’s Replace method to replace the characters that match the pattern with a space character. is far too wordy, and just states what the code is doing, without any indication as to why it might be doing that. We can see that it uses a Regex object, and we can see that that is uses the replace method, and we can see that it replaces matches with a " ": none of this needs clarifying.

Variables

I'm not terribly fond of your variable naming. They don't escape the method, so it doesn't really matter what style you use (though everyone uses lowerCamelCase, see the Microsoft Naming Guidelines), but you must be consistent. Value -> value (or values, since it is a collection). CountTheOccurances is not a great name; counts or wordCounts would scan much better. reg_exp encodes no information beyond that which is clear from the type. Something like letterFilter might be better.

I'd be inclined to ditch textToLower, and just replace text: it's so easy to use the old variable accidentally when they have such similar names. If you wanted the separation to be clear, you could put the reading of the text and to-lowering in a different scope (or even method), so that only textToLower appears for the rest of the method; however, you've already confused matters by re-using textToLower as textToLowerAfterRegex.

Splitting

Your regex bit doesn't really make sense; you are replacing every character that doesn't map to a lower-case latin letter or arabic numeral with a space: where is the specification which tells you what counts as a word or not? I'll leave someone who knows more about unicode to comment on how you should do this sort of thing properly, but your code is deficient, not least because it will cut "naïve" into "na" and "ve".

You can use Regex.Split instead of performing a replacement and then splitting, and use something like \p{L} to cover a wider variety of letters (just for example). A LINQ where can then be used to filter out empty entries.

Regex nonLetters = new Regex(@"[^\p{L}]");
return nonLetters.Split(text).Where(s => s.Length > 0);

A more efficient alternative might be to use a regex which matches words, and return captures instead of splitting; however, again, if performance is a concern, then you need to benchmark under realistic conditions.

Regex wordMatcher = new Regex(@"\p{L}+");
return wordMatcher.Matches(text).Select(c => c.Value);

I'd be strongly inclined to separate this 'extracting words' bit from the 'counting words' bit, and to avoid ToLowering at this point. Indeed, rather than using ToLower() to group words, consider supplying the dictionary a case-insensitive string comparer such as StringComparer.CurrentCultureIgnoreCase.

Counting

Though there is merit in using a separate ContainsKey call and [key] lookup, it's more efficient and a bit tidier to use TryGetValue. Here are 2 obvious ways of using it.

if (CountTheOccurrences.TryGetValue(value[i], out int count))
{
    CountTheOccurrences[value[i]] = count + 1;
}
else
{
    CountTheOccurrences.Add(value[i], 1);
}

// or

int count;
if (!CountTheOccurrences.TryGetValue(value[i], out count))
{
    Count = 0;
}
CountTheOccurrences[value[i]] = count + 1;

Personally I prefer the second one (count doesn't leak if not-found), but the first is closer to what you already have.

Another option is to ditch the loop completely, and use a LINQ GroupBy call, reducing the code complexity alot. In the code below, I write a custom general-purpose CountOccurances method, which could be reused for other purposes, and makes the intention of the code plain without compromising on performance (GroupBy would introduce significant overheads).

Example Rewrite

The below incorporates most of the ideas above, with a couple of other adjustments. The separation of concerns is maybe a little excessive, but while the number of lines of code seems to have increased, essentially all the complexity is hidden away in the completely generic (and potentially widely reusable (I wish LINQ had it already)) CountOccurrences method; the other methods are trivial, but none-the-less encapsulate domain information behind a nice API.

/// <summary>
/// Convenience method which prints the number of occurrences of each word in the given file
/// </summary>
public static void PrintWordCountsInFile(string fileName)
{
    var text = System.IO.File.ReadAllText(fileName);
    var words = SplitWords(text);
    var counts = CountWordOccurrences(words);
    WriteWordCounts(counts, System.Console.Out);
}

/// <summary>
/// Splits the given text into individual words, stripping punctuation
/// A word is defined by the regex @"\p{L}+"
/// </summary>
public static IEnumerable<string> SplitWords(string text)
{
    Regex wordMatcher = new Regex(@"\p{L}+");
    return wordMatcher.Matches(text).Select(c => c.Value);
}

/// <summary>
/// Counts the number of occurrences of each word in the given enumerable
/// </summary>
public static IDictionary<string, int> CountWordOccurrences(IEnumerable<string> words)
{
    return CountOccurrences(words, StringComparer.CurrentCultureIgnoreCase);
}

/// <summary>
/// Prints word-counts to the given TextWriter
/// </summary>
public static void WriteWordCounts(IDictionary<string, int> counts, TextWriter writer)
{
    writer.WriteLine("The number of counts for each words are:");
    foreach (KeyValuePair<string, int> kvp in counts)
    {
        writer.WriteLine("Counts: " + kvp.Value + " for " + kvp.Key.ToLower()); // print word in lower-case for consistency
    }
}

/// <summary>
/// Counts the number of occurrences of each distinct item
/// </summary>
public static IDictionary<T, int> CountOccurrences<T>(IEnumerable<T> items, IEqualityComparer<T> comparer)
{
    var counts = new Dictionary<T, int>(comparer);

    foreach (T t in items)
    {
        int count;
        if (!counts.TryGetValue(t, out count))
        {
            count = 0;
        }
        counts[t] = count + 1;
    }

    return counts;
}

Note that every method has inline-documentation, which describes its job (though I'll grant the summaries are not very good; with a proper spec be able to writer better APIs with better documentation).


Neatly Transforming Anorm ResultSet Into Map[Parent , (Set[Child1], Set[Child2]))]

I was hoping someone would review your scala but I don't think it's going to happen. So I thought I would at least say something about sql.

Alias names

Table aliases are handy especially for very long table names, however I feel that your naming is too minimal. Single-letter aliases tell Mr. Maintainer nothing about what the table means, and it can get confusing if you have multiple tables starting with the same letter. b, a, m are not very useful. Instead I would use Bill, Act, Mat or something similar.

Formatting

Your formatting is not bad, I see you've kept columns from the same table on the same line and that's good; but inline SQL can be a bit difficult to read especially when you introduce column aliases. My recommendation is to use a line break after each column you SELECT. I also noticed a bit of inconsistency in capitalization of key words.

This:

 SQL(
          """
            |SELECT
            | b.id, b.dateDue
            | ,a.id as activityId, a.notes, a.startTime, a.endTime
            | ,m.id as materialId, m.cost, m.description, m.storageLocation
            |FROM Bill b
            |LEFT JOIN Activity a ON a.bill_id = b.id
            |LEFT JOIN Material m ON m.bill_id = b.id
            |WHERE b.id = {id}
          """.stripMargin)

I would instead write like this:

 SQL(
          """
            |SELECT Bill.id
            | ,Bill.dateDue
            | ,Act.id AS activityId
            | ,Act.notes
            | ,Act.startTime
            | ,Act.endTime
            | ,Mat.id AS materialId
            | ,Mat.cost
            | ,Mat.description
            | ,Mat.storageLocation
            |FROM Bill
            |LEFT JOIN Activity AS Act ON Act.bill_id = Bill.id
            |LEFT JOIN Material AS Mat ON Mat.bill_id = Bill.id
            |WHERE Bill.id = {id}
          """.stripMargin)


Don't use wildcard imports

You had this same advice on your prior post. You apparently decided to ignore it. It doesn't make you look smarter.

Use import tkinter as tk if you must. But put some kind of prefix on Tk functions so that later readers of your code - including yourself months from now - will know when a function call or class reference is to an outside library:

class AppUI(Frame):   # ?

class AppUI(tk.Frame): # Aha!

Use super in __init__

Instead of calling Frame.__init__ you should call super like so:

super().__init__(...)

See this article by Raymond Hettinger for more details.

Don't hold open files you don't use

You open files in __init__ that you don't use and don't close. Avoid this. Instead, open/read/close or open/write/close them when you actually need to. The open operations are cheap compared to writing or reading from a file, and file handles are a scarce resource.

Also, doing your open/read or open/write at the same time allows you to use the preferred Python idiom, with, for your file I/O:

with open('savegame.txt', 'r') as save:
    savetext = save.read()
    ...

The with model handles errors well and automatically closes the resource when you're done, so you don't have to worry about it.

Move your GUI code out of __init__

Do what you need to do to set up member data, then delegate your GUI setup to another method. This makes init easier to understand, and you will likely find some code reuse once you have the "create a method" approach in mind.

Use bound methods rather than global variables

You have a callback like so:

def cashin(cash):
    ...
    app.money += int(cash)

But app is a global variable that points to your AppUI. How do you call it? With this line, set up in __init__:

    self.moneyGet = Button(root, text="Get Money!", command=lambda:cashin(self.cashGet))

So you're inside self.__init__, passing a function as a command to a button. But inside the function, you have to look up a global variable to figure out the value of self?

Try passing a bound method, or using a closure, for this kind of thing.

command=self.cashin  # no parens, it's a reference not a call

Wrap your top-level code in a function

There's a standard idiom for top-level code in Python. Use it!

def main():
    root = Tk()
    app = AppUI(root)
    app.pack()
    root.mainloop()

if __name__ == '__main__':
    main()

Encapsulate!

You pass root into AppUI() as a parameter. So why are you calling root.mainloop()? Why don't you encapsulate this in your AppUI?

app = AppUI()  # Let __init__ figure out to call tk.Tk()
app.run()      # app.run can call self.master.mainloop()


Is this a better way to validate a text box for mobile number only?

Again, properly indent the code. The code was unreadable to the point that we broke our own rules and edited the code in question just to be able to review it.

Other than that, the biggest issue with this is all of the magic numbers. They mean absolutely nothing to Mr. Maintainer. Normally at this point, I tell people to create an Enum, but in this case, there's one built in. Use the Keys Enumeration to replace all of those hardcoded numbers.


Guess the presents someone will get by comparing wishlist attributes

It's nice that you were able to implement guess_gifts as a single expression.

I don't recommend writing it that way, though.  For every item in the wishlist, you will scan the entire presents list for a match.  Wouldn't it be nice to just do a lookup instead?  You could do such a lookup if the wishlist were in a more convenient format.

def guess_gifts(wishlist, presents)
  # Transform the wishlist, mapping attributes to a list of names
  wishmap = Hash.new { |hash, attributes| hash[attributes] = [] }
  wishlist.each { |w| wishmap[w.reject { |k| k == :name }].push(w[:name]) }

  # Then just do the lookups
  presents.flat_map { |attributes| wishmap[attributes] }
end

Another benefit is that we're doing a map on presents rather than on wishlist, so I think we might not need to call uniq on the results.


Make pinging faster while looking for a Windows PC

You will have to reduce the timeout interval with the -w option (milliseconds), but I don't know what is the minimum timeout that still gives reliable results.

You could try

ping -w 500 -n 1 192.168.250.%%N


The Closer class and its setCloser method does not close anything so I'd rather call it CloseOperationProvider. I guess you could get rid of it and annotate the setCloser() parameter instead:

@Inject(optional = true)
private void setCloseOperation(@Named("closeOperation") int closeOperation) {
    frame.setDefaultCloseOperation(closeOperation);
}


If I read the wikipedia article correctly then the algorithm should have amortized constant cost - and you have implemented it pretty much 1:1. Given that with your implementation you always start with disjoint nodes and any call to any of the public methods ends up calling Find which will automatically flatten the tree I doubt you can get much better.
UnionFindNode is not a particularly good name for the data structure: intermingles operations with the data structure in the name. Just Node or maybe DisjointSetNode would be better.
You could use == or != instead of ReferenceEquals which would make the code a bit easier to read.
Consider making your node class generic and add a T value property - right now your nodes are not all that useful as they don't hold any data.


How to use the value of a method result based on a test?

I believe fooclass is a reference of Foo class. I can only think about introducing a variable and check it to prevent the double-invokation of same method.

String fooInfo = fooclass.getInfoText();
if (!"".equals(fooInfo))
{
    this.setInfoText(fooInfo);
}

NOTE

I'm using "".equals(fooInfo) to avoid NPE.


Remove the everyOtherMove flag variable

You use it only once to control the logic of your program:

if ( ! everyOtherMove ) {

and this usage may be substitued with a evenness check of the moveCount variable that you would have anyway.

Do not declare vars so much before using them

At line 36 temp is declared as an int, at line 113 temp is used for the first time. How can the reader remember the type of temp 77 lines later? Declare it just before using it.

Loop variables should be declared inside the loop statement as C99 allows it.

Use ternary when it clearly simplifies

if ( (numberOfDisks & 1) == 0 )
    smallestDir = 1;
else
    smallestDir = -1;

Becomes

int smallestDir = (numberOfDisks & 1) == 0 ? 1 : -1

Much shorter and without the smallestDir = repetition.

Using % instead of bitwise operations to check evenness would be a further improvement.

Reduce main (both code and vertical whitespace)

I introduce this helper function:

int wrap_around(int min, int max, int value)
{
    return value < min ? max : (value > max ? min : value);
}

(Please note that it could also be written with if conditionals, I wrote it like this just because of my familiarity with ternary).

The first if branch now is:

    if (moveCount % 2 == 0) {
        // move smallest disk
        rodFrom = rod[1];
        rodTo = wrap_around(1, 3, rodFrom + smallestDir);
        disk = 1;
    }

while before it was:

    if ( ! everyOtherMove ) {

        // move smallest disk

        rodFrom = rod[1];

        rodTo = rodFrom + smallestDir;
        if ( rodTo > 3 )
            rodTo = 1;
        if ( rodTo < 1 )
            rodTo = 3;

        disk = 1;

    }

The same concept is expressed in much less space, and this is a good attribute in my view because:

Some logic is modularized in other functions, the reader gets a more abstract overview.
If all code is compacted this way an overall view of the program becomes possible helping understanding.

Compacting the else clause

    else {

        // make only valid move not involving the smallest disk

        // find disk at the top of each rod

        for ( i = 1; i <= 3; ++i )
            topDisk[i] = numberOfDisks + 1;

        for ( i = numberOfDisks; i >= 1; --i )
            topDisk[rod[i]] = i;

        // find which disk to move

        switch ( rod[1] )
        {
            case 1:
                rodFrom = 2;
                rodTo = 3;
                break;
            case 2:
                rodFrom = 1;
                rodTo = 3;
                break;
            case 3:
                rodFrom = 1;
                rodTo = 2;
               break;
            default:
                printf ("error");
                break;
        }

        if ( topDisk[rodFrom] > topDisk[rodTo] ) {
            // swap values
            temp = rodFrom;
            rodFrom = rodTo;
            rodTo = temp;
        }

        disk = topDisk[rodFrom];

    }

I do not fully understand the uppermost two for loops but both the switch and the body of the if ( topDisk[rodFrom] > topDisk[rodTo] ) statement are performing very clear, specific tasks, so:

    else {
        // make only valid move not involving the smallest disk
        // find disk at the top of each rod
        for ( i = 1; i <= 3; ++i )
            topDisk[i] = numberOfDisks + 1;
        for ( i = numberOfDisks; i >= 1; --i )
            topDisk[rod[i]] = i;

        // find which disk to move
        find_start_and_destination(rod[1], *rodFrom, *rodTo);
        if ( topDisk[rodFrom] > topDisk[rodTo] ) {
            SWAP(rodFrom, rodTo);
        }
        disk = topDisk[rodFrom];

    }

I just removed the unnecessary blanklines (blanklines should separate logically separated blocks of code, not each line / statement), and used a function to incorporate the switch and a macro to swap variables. The function must use pointers because two values may not be returned from a function in C, but I think the modularization is still an advantage.


Avoiding code duplication in multiple except blocks in Logger class

Method decomposition looks like the way to go here:

def _try_post(self, json):
    """Try posting the message (unless this timed out previously).
    Return True if successful, False otherwise.

    """
    if not self._timedOut:
        try:
            self._post(json)
            return True
        except urllib.error.HTTPError:
            pass
        except socket.timeout:
            self._timedOut = True
    return False