The strength of a password has nothing to do with the presence of special characters! Obligatory xkcd reference:

correct horse battery staple is a very strong password, but you would classify it as weak, simply because it doesn't contain capital letters, symbols, or numbers. Rethink the idea.

Testing

You will never indicate that a password is very strong because of this ordering:

elif len(password) >= 8:
    print('Your password is strong ! ')
elif len(password) >= 16:
    print('Your password is very strong ! ')

If len(password) is, say, 20, both branches are true. So you want to makes ure that the most restrictive one goes first:

elif len(password) >= 16:
    print('Your password is very strong ! ')
else:
    print('Your password is strong ! ')

Regex

The point of compile is if you reuse the same regex many times, you can make it more efficient. You use each one exactly once, so it's a waste of processing time. What you want to instead use is re.search(), since you don't care about all the instances you just want to know if there is such a thing:

lower_match = re.search(r'[a-z]', password)
upper_match = re.search(r'[A-Z]', password)
...

Then check against None instead of checking len(). Also your symbol check is inefficient. You have a bunch of |s, when you could simply list them all:

symbol_match = re.search(r'[\"\'~!@#$%^&\\*\(\)_=\+\|,./\?:;\[\]\{\}<>]', password)

Importing

from X import *

is highly frowned upon. Just do import re and use re.X everywhere.


Approach for one class to safely refer to another, with both having unknown lifetimes

I think using a bit of dynamic allocation std::shared_ptr and std::weak_ptr makes sense as they provide a solid implementation of the tracking behaviour you need.

Your original though has a nice property of not using any dynamic allocation.
If the tracking logic could be refine and made more general if might be a handy bit of library code to have around.

This is my attempt so far:

template <typename T>
class SafeRefTo;

template <typename T>
class Tracked : public T
{
public:
    using T::T;
    ~Tracked();
    void addReferee(SafeRefTo<T> *manager) {safeRefToThis = manager;}
    void markSafeRefInvalid() {safeRefToThis = nullptr;}
private:
    SafeRefTo<T> *safeRefToThis;
};

template <typename T>
class SafeRefTo
{
public:
    template <typename... Args>
    Tracked<T> makeTracked(Args... args)
    {
        Tracked<T> tracked{args...};
        attach(tracked);
        return tracked;
    }

    void attach(Tracked<T> &tracked)
    {
        tracked_ = &tracked;
        tracked_->addReferee(this);
    }
    void detach()
    {
        if(tracked_ != nullptr)
        {
            tracked_->markSafeRefInvalid();
            tracked_ = nullptr;
        }
    }
    template <typename TrackedMemFun, typename... Args>
    void invoke(TrackedMemFun fun, Args... args)
    {
        if(tracked_ != nullptr)
            (tracked_->*fun)(args...);
    }
private:
    Tracked<T> *tracked_;
};

template <typename T>
Tracked<T>::~Tracked()
{
    if(safeRefToThis != nullptr)
        safeRefToThis->detach();
}

Then the client code is simply:

#include <iostream>

class Actor
{
public:
    Actor() = default;
    Actor(std::string extraText)
    :
    extraText(extraText)
    {}

    void act(unsigned int times) {
        for(; times; --times)
        {
            std::cout << "hello world!" << extraText << "\n";
        }
    }

private:
    std::string extraText;
};

int main()
{
    SafeRefTo<Actor> manager;
    {
        auto tracked(manager.makeTracked());
        manager.invoke(&Actor::act, 1); //output: hello world!
    }//"tracked" goes out of scope: the pointer in "manager" is now invalidated.
    manager.invoke(&Actor::act, 1);
}


Ajax plugin that binds to click and page load

Edit: The part below was, I think, me not seeing the forest for all the trees. The issue is quite simply that you're passing the string 'window' to jQuery, rather than the object window. So jQuery tries to bind an event listener to a <window> HTML element - which, obviously, does not exist.

What you want, is

$(window).bind("load", function () { .... });

or, better:

$(window).on("load", function () { .... });

or

$(window).load(function () { .... });

or, simply

$(function () { .... });

basically, anything other than trying to pass the string 'window'

Actually, the least flexible part of your code are the ajax requests themselves. If the ajax options are hard-coded in the plugin, you still don't have much flexibility; it's the same ajax requests each time. For instance, if you want to load ajax on a scroll event, you still have to edit the plugin to add the ajax request options and/or add an if(options.eventType === "scroll"). So you're splitting your code up, but not gaining any real flexibility.

I'd suggest making a simple function that takes an element, an event type, and some ajax options, so you can bind any event to any ajax request. Something like

function bindAjax(element, event, ajaxOptions) {
  ajaxOptions = $.extend({
    // default ajax options, if any
  }, ajaxOptions);

  $(element).on(event, function (event) {
    $.ajax(ajaxOptions);
    event.preventDefault();
  });
}

bindAjax(window, "load", { ... });

You don't gain that much by doing this, though, compared to "raw" jQuery code.


First, a number X is even if X mod 2 is 0.

I think is more understandable something like this:

function isEven(n){
  return (n % 2 == 0);
}

The function will return true if the number n is even and false if it's odd.


Speed up sorting algorithm in R: make one column "smaller" than the other

You solution does the job, but it is often better to vectorise your code. See the following example. First get the ordering of all elements in column a and b and then use this to rearrange the elements in the data.frame.

library(tictoc) #to get the run time

df <- data.frame(a = runif(10000),
                 b = runif(10000))

# your solution
tic()
df.loop <- df
for (i in 1:nrow(df.loop)){
df.loop[i, ] <- sort(df.loop[i, ])
}
toc()

#sort (order) only once
tic()
index.a <- 1:nrow(df)
index.b <- (nrow(df) + 1) : (2*nrow(df))
a.b.ordered <- order(c(df[, 1], df[, 2]))
b.greater.a <- match(index.b, a.b.ordered) < match(index.a, a.b.ordered)
df.index <- df
df.index[b.greater.a, 1] <- df[b.greater.a, 2]
df.index[b.greater.a, 2] <- df[b.greater.a, 1]
toc()

identical(df.loop, df.index)


There's an obvious flaw if the candidate port is closed on 127.0.0.1 but open on a different interface that you want your service to bind to.  That's particularly relevant if you want it to listen on all interfaces (0.0.0.0).

If your service binds to the localhost address, then that's obviously not a concern.


I think both your solution and your testing are fine.

A couple of test cases I would add (but your solution also passes them):

a string starting with BOM, e.g. {"\xef\xbb\xbfhi", "\xef\xbb\xbfHi"}
a string which is not a valid UTF-8 string, e.g. {"h\xffi", "H\xef\xbf\xbdi"}
a string with multiple invalid UTF-8 bytes, e.g. {"h\xff\xffi", "H\xef\xbf\xbd\xef\xbf\xbdi"}

Explaining the invalid UTF-8 strings: Since you are converting your input string to runes, invalid UTF-8 bytes are reported as a value of 0xfffd (the Unicode replacement character), which when encoded as UTF-8 (happens when you convert []rune back to string) results in a sequence of []byte{0xef, 0xbf, 0xbd}; this is what the invalid 0xff byte is compared to in the test case.

Performance wise I would use a string => []rune conversion as you not only need the runes, but you also want to convert them back to a string. Using append() is slower, and it has to assign a slice value (a descriptor) at each rune.

Also note that if we convert the string to []rune, we only need to assign (overwrite) new runes which are converted to their upper case:

This is how I would do it:

func AlternateCase(s string) string {
    rs, upper := []rune(s), false
    for i, r := range rs {
        if unicode.IsLetter(r) {
            if upper = !upper; upper {
                rs[i] = unicode.ToUpper(r)
            }
        }
    }
    return string(rs)
}


Overall you've done a good job with your code, there are a couple things I'd look out for :

You aren't paying for whitespace! What I mean is that it's important to let your
code breathe. Use some empty lines, it'll do wonder for your eyes when dealing with big chunks of code.
Why is tries an array? In my opinion, tries should represent the number of tries, so it should be a number!
Notice that you have for conditions, ==, <, > and... ? Say I ask you to give me a number that is neither equal, smaller or greater than 3, is there a possible option? What you should do instead is make sure the player input a number! Right now, if I was to answer "I don't know my numbers I'm just a baby" to "We are going to play high and low, the avabile numbers are from 1 to 100 included.", your program will crash! You should look into try/catch blocks to solve this problem, that could be a next thing to learn for you!
Say I need three tries on my first playthrough, then I start a new game (using "yes" when prompted) and I'm able to succeed on the first try, your code will tell me I've needed four tries to succeed. Can you find out why and how you can fix that?
You could simplify your loop using the break keyword, that's also something you should search for (while we're at it, try to understand the usage of break, return and continue. Those three keywords are pretty useful, although you probably already know about return).
What if I'm an english major and I can't stand making grammar mistakes (It's obviously not my case) and I write "Yes", instead of "yes" or "YES", when asked if I want to play again? What you could do is compare the lowered (or uppered) version of the input with what you want to check (ex. still.lower() == "yes").


Bug?

It looks like there is a bug here:

else
{
    (11 - 11) - (13 - 13) - inputEncrypted;
}

After simplification, the expression becomes:

else
{
    -inputEncrypted;
}

... which does nothing, as the result is not assigned, the value of inputEncrypted is unchanged. If you wanted to negate the value of the variable, you would have to write like this:

else
{
    inputEncrypted = -inputEncrypted;
}

I don't know if this is your real intention (didn't look at your code close enough). But the original code does absolutely nothing, it's reduced to a statement whose result is not stored anywhere.

Use boolean expressions directly

This can be simplified:

if (success == true && (redo == 'y' || redo == 'Y'))
    keepGoing == true;
else
    keepGoing = false;

To this:

keepGoing = success && (redo == 'y' || redo == 'Y');

Notice how you don't need to write x == true, you can use boolean expressions directly.

Naming

A name like whatToDoFunc is obviously bad. Good function names are extremely important to understand how a program works.


for h1 in range (0, 4):
  for h2 in range (h1+1, 5):
   for b1 in range (0, 3):
    for b2 in range (b1+1, 4):
     for b3 in range (b2+1, 5):
      hand_check = []
      hand_check.append(hand[m1])
      hand_check.append(hand[m2])
      hand_check.append(board[b1])
      hand_check.append(board[b2])
      hand_check.append(board[b3])

Use itertools for this kind of thing:

for h in itertools.combinations(hand, 2):
  for b in itertools.combinations(board, 3):
    hand_check = list(h) + list(b)

Also, I don't find hand_check to be a helpful name. In general I expect variable names to be nouns (unless they're Booleans, when predicates make sense), and when I parse hand_check as a noun I find that it's a check modified by hand. The smallest change would be to rename it hand_to_check; I prefer candidate_hand.

      if (hand_check[0].suit == hand_check[1].suit and hand_check[1].suit == hand_check[2].suit and hand_check[2].suit == hand_check[3].suit and hand_check[3].suit == hand_check[4].suit):

Ugh. Use set.

if len(set(card.suit for card in hand_check)) == 1:

      hand_check = sort(hand_check) #Custom sort for my array of objects
      hand_ranks = "".join([str(hand_check[0].rank),str(hand_check[1].rank),str(hand_check[2].rank),str(hand_check[3].rank),str(hand_check[4].rank)])

       control = [dictionary_A[hand_ranks][0],dictionary_A[hand_ranks][1]]
      else:
       control = [dictionary_B[hand_ranks][0],dictionary_B[hand_ranks][1]]

Firstly, why the quadruple-lookup? Why not

lookup_table = dictionary_A if only_one_suit else dictionaryB
control = lookup_table[hand_ranks]

?

Secondly, although Python's string manipulation is quite fast, since you're aiming to microoptimise you should think in terms of integers rather than strings. I'd delve into the fascinating world of perfect hashes to try to get a lookup table which fits into L2 cache, or maybe even L1 with luck (there are only 6188 multisets of 5 ranks, so less than 25 kB of lookup table suffices).

      if first_int:
       best_hand = hand_check
       rank = control
       first_int = False
      elif (int(control[0]) > int(rank[0])):
       rank = control
       best_hand = hand_check
      elif (int(control[0]) == int(rank[0])):
       if (int(control[1]) > int(rank[1])):
        rank = control
        best_hand = hand_check

If you initialise rank to [-1] then you should be able to eliminate first_int and simplify this to

      if (control > rank):
        rank = control
        best_hand = hand_check

Now, I've addressed micro-optimisation above, but the first rule of optimisation is to start by looking at the algorithm.

  What I need to do is check all arrays formed by 2 items from hand and
  3 items from board, like combination = [Hn,Hm,Bi,Bj,Bk] (100
  combinations in total)

  Then I need to compare each one of the combinations against a
  dictionary

is wrong. What you need to do is find the set of five cards formed by 2 cards from the hand and 3 cards from the board which has the highest score.

I'd suggest that you micro-optimise and then benchmark against a major restructuring with the following outline:

for suit in the_four_suits:
  hand_mask = build_mask((card for card in hand if card.suit == suit))
  board_mask = build_mask((card for card in board is card.suit == suit))
  check_royal_flush(hand_mask, board_mask)
  check_straight_flush(hand_mask, board_mask)
  check_flush(hand_mask)

hand_counts = count_by_ranks(hand)
board_counts = count_by_ranks(board)
check_four_of_a_kind(hand_counts)
check_full_house(hand_counts)
...

The key ideas are to do everything with bit manipulation and to return as soon as you know that no further checks will produce a hand better than the best you've already found. For count_by_ranks, if you allocate three bits per rank then overflow into the next rank is impossible since there are only four suits. So e.g. to check for a four of a kind:

total_counts = hand_counts + board_counts
possible_fours = total_counts & 0x4924924924
# possible_fours indicates ranks where we have all four cards between hand and board
# We take three cards from board, so rule out ranks where all four are in the board
possible_fours &= ~board_counts
# Similarly, rule out ranks where all four are in hand
possible_fours &= ~hand_counts
# And rule out ranks where three are in hand
possible_fours &= ~((hand_counts << 1) & (hand_counts << 2))
if possible_fours != 0:
  # We have a four-of-a-kind: just need to extract it


You can simplify several things:

if custom_data_folder == '': can become if not custom_data_folder:
if os.path.exists(default_path) is True can be just if os.path.exists(default_path)

Other notes:

it is questionable that you return "The file or path does not exist." string in case a path does not exist. Throwing an error would probably make more sense
make your default directory name a constant
you can avoid calculating the full default path if custom is provided
you can reduce code duplication and construct a path first, then check if it exist, raise an error if it does not and return if does exist

All the above things taken into account, here is the modified code:

import os

DEFAULT_DIRECTORY = 'data'

def get_file():
    """TODO: docstring"""
    custom_data_directory = input("Name of custom data directory - Hit ENTER to default: ")
    file_name = input("File name: ")

    directory = custom_data_directory or DEFAULT_DIRECTORY
    path = os.path.abspath(os.path.join(directory, file_name))

    if not os.path.exists(path):
        raise ValueError("Path '{path}' does not exist".format(path=path))

    return path

Some thoughts for further improvements:

you should probably create a better separation of concerns and have this function parameterized with file and directory names - moving user input related things from out of the function
create a docstring explaining what your function does
.format() formatting can be replaced with an f-string if on Python 3.6+
get_file is probably not the most descriptive name for this function, consider renaming it - get_full_file_path?..


DetailsView

You should pass jquery selector to the el — Backbone will handle it. Also, note that you should pass DOM element to the el property.

Injecting one view into another is often a bad practice (if relation is not like parent and subview): is.options.dataEditorView.$el.show(); this.options.finalView.render();

Consider triggering event like validation-success from DetailsView. Subscriber to this event should be in the route or other main object.

DataEditorView

var point = {
    x: $("#input-point-x").val(),
        y: $("#input-point-y").val()
};

Series.create(point);
// Probably you want to add new point to existing collection this.options.seriesCollection?

Another view injection: this.options.summaryView.addPoint(points);

Just add new point into collection and subscribe to event in the summaryView (see next block).

// Micro optimization
var pointX = $(".point-x");
pointX.val("");
pointX.focus();

SummaryView

Add view.listenTo(seriesCollection, 'add', addPoint) into initialize step. addPoint should accept parameters: model, collection, options, where model is a new point which was added to the collection.

In this function you should run collection.toJSON() to prepare points for D3.data().


Relationship design for auto parts store database

You have all the tables you need and you have the many-to-many relationships correct, I think.

I'd suggest that you add a Parent field to Category and then create a hierarchy of categories instead of having a Category table with a single Subcategory table.

create table Category(
    CategoryId int not null identity(1,1),
    ParentCategoryId int null,
    CategoryName nvarchar(100) not null,
    primary key (CategoryId))

As a point of style, I'd name the many-to-many tables with underscores instead of numbers, i.e. Model_Year_Part.

Note that I used nvarchar instead of varchar.

If you ask a question on StackExchange for a school project, don't forget the citation if you use the answers! It's okay to ask but never to plagiarise.


Generating a C++ header containing OpenGL function definitions

In python it is not necessary to end a line with a ;.

Your function generate_header_file is probably better named write_to_header_file.

I would read the file only once and do everything in one pass in generate_header_string:

from itertools import chain

def generate_header_string(function_names_file_name):
    header_string1 = [INITIAL_HEADER_STRING_ONE]
    header_string2 = []

    def_string1 = "PFN{}PROC {};"
    def_string2 = "\t{1} = (PFN{0}PROC)GetGLProcPointer(\"{1}\");"

    with open(function_names_file_name, "r") as function_names:
        for line in function_names.readlines():
            line = line.rstrip("\n")
            line_upper = line.upper()
            header_string1.append(def_string1.format(line_upper, line))
            header_string2.append(def_string2.format(line_upper, line))
        header_string1.append(INITIAL_HEADER_STRING_TWO)
        header_string2.append("}")
        header_string2.append("\n#endif")

    return "\n".join(chain(header_string1, header_string2))

Here I changed the accumulation variable to lists which I join in the end. This gives some memory boost, because string addition is very costly, especially if the strings become bigger (and your INITIAL_HEADER_STRING_X is already quite big). The lists also get rid of having to manually write \n in the strings, because we can just use it as joining variable at the end.

You will want to give the two variables better names (like header_declaration and header_initialization or whatever fits their use case; I don't know any OpenGL syntax, so I'm not exactly sure).

I also declared the strings you format once before the loop to avoid having to redeclare them every iteration. They could also do with better names, probably something similar to the header lists.


query = friend_ids.map {|id| "SELECT id FROM test WHERE user_id=#{id}"}.join " INTERSECT "

Bam.

Edit: Ok, well, not just bam. First of all, if you're using Rails, go with something like NewAlexandria's answer, because it doesn't involve raw string interpolation (which quickly leads to SQL injection vulnerabilities). To make the above a little more safe (and assuming the IDs are integers), you should probably do

query = friend_ids.map { |id|
  "SELECT id FROM test WHERE user_id = #{id.to_i}"
}.join " INTERSECT "


Best way to access lists and nest them with if statements

Here are just a few comments to help improve your code:

When you have a collection, think about how you are going to access the collection. Most of the time, you are going to treat it as a group of items (example: "weapons") and so you should use a plural name. Rarely, you will treat a collection as a single item (example: "database"), and so you should use a singular name.

Always use functions. Yes, python supports having statements directly "up against the wall." But it is much, much easier to write test cases, to debug your code, and to change your mind about what order to do things if you have a single name (function) for a group of statements. Moving things around as blobs of text is miserable and prone to errors.

When you find yourself doing something twice, write a function! In your case, asking the user for some input is a good place to put a function:
 show_message("There's a wizard conjuring a spell.")
 choice = get_choice("What do you do?",
       "Talk to the wizard",
       "Attack the wizard",
       "Run away")

As far as your collection of weapons is concerned, think about what kind of game you are writing. If you are writing a "dungeon" style game, where there is going to be a lot of fighting monsters, then having real weapon-objects with stats will be important. In that case, you'll probably want either a set or a list, but you'll want a separate variable to track which of the possibly many weapons is currently being wielded.
On the other hand, if you are writing more of a "text adventure" game, where just having "the sword" is enough to beat a monster, then you might not want a collection at all. Instead, you might want one or more boolean variables, or perhaps a dictionary full of booleans.

      if user_has['the sword']:
          show_message("The troll runs away!")
      else:
          show_message("The troll eats you. You have died.")

To specifically answer your question about how to access members of lists: note that you are using the list.append() function. This takes an object and adds it to the end of the list. So if you have 11 items in the list, and you .append another item, it will be the 12th item (index 11, because list indexes are 0-based).
You can access that item in two ways. The "hard way" is to compute the length of the list and subtract one:
 item = "sword"
 weapons.append(item)
 sword_index = len(weapons) - 1
 print("You have a", weapons[sword_index])

An easier way is to reply on the fact that python supports negative indexes as being from the end of the list. That is, list[-1] is the last item, list[-2] is the next-to-last item, etc. This works with indexes and with slices, so you can also say list[1:-3] or list[-5:] for example. See note 3 in the sequence docs for details.


Checking whether a list is sorted, ascending or descending

I'm a little sure if this is well suited for Code Review, but here goes a little analysis:

Using anonymous functions

This doesn't look right as it is repeating too much code, which is a clear code smell. When quickly looking at it, it is unclear what the actual difference is between the two. So this is not a good option.

Using eval

An old saying says "using eval is evil", and you should avoid using eval if possible. Not only does it have an performance hit, but it is also a major source of security flaws, and not readable code.

Defining your own operator

This is by far the nicest solution, as it doesn't repeat code, and it reads the best. However you could simplify it using direct assignment of the operator instead of using a lambda expression, thusly making it to be:

import operator

my_operator = operator.ge if reverse else operator.le
all(my_operator(unsorted[indices[i]], unsorted[indices[i + 1]]) \
    for i in xrange(len(indices) - 1)))

In a function using a pairwise recipe

Or introducing a function, and the pairwise iterator from itertools recipes v2.7:

import operator
import itertools

def is_sorted(iterable, reverse= False):
    """Check if the iterable is sorted, possibly reverse sorted."""

    def pairwise(iterable):
        """s -> (s0,s1), (s1,s2), (s2, s3), ..."""
        a, b = itertools.tee(iterable)
        next(b, None)
        return itertools.izip(a, b)

    my_operator = operator.ge if reverse else operator.le

    return all(my_operator(current_element, next_element)
                   for current_element, next_element in pairwise(iterable))

# Test the function
print is_sorted([1, 2, 3, 4])            # Should be True
print is_sorted([4, 3, 2, 1], True)      # Should be True
print is_sorted([4, 1, 2, 3])            # Will not be True, ever...


That's a brute force search of hashes for a particular prefix, meaning it's complexity is \$O(2^n)\$, where \$n\$ is the number of bits in the prefix. In your case that's \$2^{28}\$.

You can't make it faster in terms of complexity or the hash would be broken, but you can increase the constant factor.

Using cProfile I see that out of 30 seconds of runtime the worst offenders are:

8042221   10.763    0.000   24.243    0.000 tmp.py:10(getHash)
      5    5.138    1.028   30.701    6.140 tmp.py:13(populate)
8042222    3.805    0.000    3.805    0.000 {_hashlib.openssl_sha1}
8042221    5.143    0.000    5.143    0.000 {method 'encode' of 'str' objects}
8042221    3.876    0.000    3.876    0.000 {method 'hexdigest' of '_hashlib.HASH' objects}
8042221    1.320    0.000    1.320    0.000 {method 'join' of 'str' objects}

The actual hashing is done in hexdigest and OpenSSL. Those pretty much cannot be reduced, so at best it could be made ~3 times as fast.

In python 2 you can remove the encode invocation. That alone saves a few seconds. A set is faster for in testing, so that's also an easy fix. Take advantage of hashlib.sha1's copy and update by noticing the length stays constant and you are at 2x the speed:

def getHash(data, h):
    h = h.copy() # "fork" the hash
    h.update(data)
    return h.hexdigest()

def populate(n):
    h = hashlib.sha1("blob " + str(n) + "\0") # shared part of the hash
    for data in product(possible_letters, repeat=n):
        s = getHash(''.join(data), h)[0:7]
        if s in messages:
            print(s,data)

On Python 3 you can encode the letters into bytes and avoid encode inside the loop, for similar performance.

You might still make it about 1.5x as fast if you replaced the product -> join algorithm with something faster (bytearray(n) and depth first search?), but that's about it.


Pick a random big word from a list of words using Python

Comments

Python functions are written in snake_case.
You could use function parameters for word length and filename.
You could use iterators and generators to avoid loading the whole file into memory.
If you read the file line by line, you need to take care with the trailing newline character: len("test\n") is 5.

Refactoring

Here's a way to rewrite your function. Thanks to a generator, the script only loops once over every line:

import random

def goal_word(min_length=7, filename="words.txt"):
    with open(filename) as wordbook:
        words = (line.rstrip('\n') for line in wordbook)
        large_words = [word for word in words if len(word) >= min_length]
    return random.choice(large_words)

print(goal_word(7))
# evening
print(goal_word(15))
# circumnavigations

Optimization

@etchesketch commented that rstrip is called on every line even though it's only needed for one word. Here's a variation:

import random

def goal_word(min_length=7, filename="words.txt"):
    min_line_length = min_length + 1
    with open(filename) as wordbook:
        large_words = [line for line in wordbook if len(line) >= min_line_length]
    return random.choice(large_words).rstrip('\n')

print(goal_word(7))
# jauntily
print(goal_word(15))
# fundamentalists

On a dictionary of English words (/usr/share/dict/american-english), this function is 3 times faster than the previous one.

Exception handling

In the above examples, goal_word(30) fails with IndexError: Cannot choose from an empty sequence. There's no indication that the desired length is too long.

Before calling random.choice, the script could simply check that large_words isn't empty:

import random

def goal_word(min_length=7, filename="words.txt"):
    min_line_length = min_length + 1
    with open(filename) as wordbook:
        large_words = [line for line in wordbook if len(line) >= min_line_length]
    if large_words:
        return random.choice(large_words).rstrip('\n')
    else:
        raise ValueError("No word found with at least %s characters." % min_length)

print(goal_word(7))
# jauntily
print(goal_word(15))
# insurrectionist's
print(goal_word(30))
# ValueError: No word found with at least 30 characters.


Presenting modal dialogs from XIB in Cocoa: best/shortest pattern?

Based on Ken Thomases answer given on SO here, here is my revised modal window module. Note that the window should have the system close button disabled, or otherwise you will have to handle windowWillClose, which will lead to having _dialogCode like in my original code above. If, however, OK and Cancel are the only buttons that end the modal dialog, then:

#import "MyPasswordWindowController.h"

@interface MyPasswordWindowController ()
@property (weak) IBOutlet NSSecureTextField *passwordField;
@end

@implementation MyPasswordWindowController

- (IBAction)okCancelAction:(NSButton *)sender
{
    [NSApp stopModalWithCode:sender.tag]; // the OK button's tag should be 1
    [self.window close];
}

+ (NSString*)run
{
    MyPasswordWindowController* windowController =
        [[MyPasswordWindowController alloc] initWithWindowNibName:@"MyPassword"];
    if ([NSApp runModalForWindow:windowController.window])
        return windowController.passwordField.stringValue;
    return nil;
}

@end


Look at the code below. I haven't tried it yet, but the idea is avoid iterating query that will take a long time. So, I just use one query.

CASE "TestGrid":
        $SnapArrayResult = array();
        $PlayArrayResult = array('A','B','C','D');
        echo "
\n";
        echo "
Data on Alliance
\n";
        echo "

	\n";
        $SnapResult = $db-> query("SELECT snap,COALESCE(count(*),0) as pCnt,hex(alliance) as alliance FROM scSVR WHERE hex(alliance) IN (hex('A'),hex('B'),hex('C'),hex('D')) GROUP BY snap,alliance ORDER BY snap ASC");
        $changeSnap = null;
        $PlayerRow = array();
        while ($SnapRow = $db-> fetch_assoc($SnapResult))
        {
            if($changeSnap!=$SnapRow['snap'])
            {
                $SnapArrayResult[] = $SnapRow['snap'];
                $changeSnap=$SnapRow['snap'];
                $PlayerRow[$changeSnap] = array();
                echo "".DTConvS($SAR)."	\n";
            }
            $PlayerRow[$changeSnap][$SnapRow['alliance']] = $SnapRow['pCnt'];
        }

        echo "

\n";
        echo "
";
        foreach($PlayArrayResult as $PAR){
            echo "
".$PAR."	";
            foreach($SnapArrayResult as $SAR){
                echo "".$PlayerRow[$SAR][$PAR]."	\n";
            }
            echo "
";
        }
        echo "

";
        break;


Count number of unique adjacent cells in a matrix

bug

in count_adjacent_islands, number_of_islands = 0 should be number_of_countries = 0

mutate original argument

Most of the time, it's a bad idea to change any of the arguments to a function unless explicitly expected. So you better take a copy of the matrix first:

matrix_copy = [row[:] for row in matrix]

tuple unpacking

instead of for shift in ((-1,0), (1,0), (0,-1), (0,1)):, you can do for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):, then row, col = [x+y for x,y in zip((this_row, this_col), shift)] can be expressed a lot clearer: row, col = x + dx, y + dy

continue

instead of keep nesting if conditions, you can break out of that iteration earlier if the conditions are not fulfilled

for row_index, row in enumerate(matrix):
    for column_index, _ in enumerate(row):
        if matrix[row_index][column_index] != 0:
            number_of_islands += 1
            clean_neighbours(matrix, row_index, column_index)

can become:

for row_index, row in enumerate(matrix_copy):
    for column_index, _ in enumerate(row):
        if matrix_copy[row_index][column_index] == 0:
            continue
        number_of_islands += 1
        clean_neighbours2(matrix_copy, row_index, column_index)

saving 1 level of indentation on the code that actually does the lifting. This is not much in this particular case, but with larger nested conditions, this can make things a lot clearer, and save a lot of horizontal screen estate

recursion

If there are some larger islands, you will run into the recursion limit. Better would be to transform this to a queue and a loop

from collections import deque
def clean_neighbours2(matrix, x, y):
    cell_value = matrix[x][y]
    if cell_value == 0:
        return

    matrix[x][y] = 0

    queue = deque([(x,y)])

    while queue:
        x, y = queue.pop()
        for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            row, col = x + dx, y + dy
            if (
                0 <= row < len(matrix)
                and 0 <= col < len(matrix[0])
                and not matrix[row][col] == 0
            ):
                continue
            if matrix[row][col] == cell_value:
                queue.append((row, col))
                matrix[row][col] = 0

def count_adjacent_islands2(matrix):
    matrix_copy = [row[:] for row in matrix]
    number_of_islands = 0
    for row_index, row in enumerate(matrix_copy):
        for column_index, _ in enumerate(row):
            if matrix_copy[row_index][column_index] == 0:
                continue
            number_of_islands += 1
            clean_neighbours2(matrix_copy, row_index, column_index)
    return number_of_islands

For the sample data you provided, this code took 3s compared to 4s for the original on my machine

alternative approach

Using numba and numpy, and a slight rewrite to accomodate for numba compatibilities:

from numba import jit
import numpy as np

@jit()
def clean_neighbours_jit(matrix, x, y):
    cell_value = matrix[x, y]
    if cell_value == 0:
        return

    matrix[x, y] = 0

    queue = [(x, y)]
    row_length, column_length = matrix.shape

    while queue:
        x, y = queue.pop()
        for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            row, col = x + dx, y + dy
            if (
                not 0 <= row < row_length
                or not 0 <= col < column_length
                or matrix[row, col] != cell_value
            ):
                continue
            queue.append((row, col))
            matrix[row, col] = 0

@jit()
def count_adjacent_islands_jit(matrix):
    matrix_copy = matrix.copy()
    number_of_islands = 0
    row_length, column_length = matrix_copy.shape
    for row_index in range(row_length):
        for column_index in range(column_length):
            if matrix_copy[row_index, column_index] == 0:
                continue
            number_of_islands += 1
            clean_neighbours_jit(matrix_copy, row_index, column_index)
    return number_of_islands

This expects a numpy array as matrix, (for example: count_adjacent_islands_jit(np.array(A))) but does the job in about 200 to 300ms, (about 80ms spent on converting A to an np.array), so more than 10x speedup.


A Maximum Function For Various Type Arbitrary Nested Iterable Implementation in C++

Using the right concept
Indeed, Summable is the wrong concept to use if you want to check if the value type is such that you can calculate the maximum of two values. Have a look at the documentation of std::max(). In particular, it requires that the type is LessThanComparable. So you could create a concept to test that. There is already a concept std::totally_ordered, which is a bit more strict than necessary.
Simplify Max()
You do an elaborate dance to get the right type for maxValue, but why not just use auto? Also, use std::max() to calculate the maximum for you:
template<class T>  requires Iterable<T>
static inline auto Max(const T& numbers)
{
    auto maxValue = Max(numbers.at(0));

    for (auto& element : numbers)
    {
        maxValue = std::max(maxValue, Max(element));
    }

    return maxValue;
}


This piece:

if (fullUrl.EndsWith("/"))
{
    fullUrl += "Routes";
}
else
{
    fullUrl += "/Routes";
}

can be rewritten to:

fullUrl += fullUrl.EndsWith("/") ? "Routes" : "/Routes";

or:

if (!fullUrl.EndsWith("/"))
    fullUrl += "/";
fullUrl += "Routes";

Since you're using the TryCreate method, there's no need to throw an exception. You just have to notify the caller whether the conversion succeeded or not. Plus, throwing an exception in a get statement is bad practice. This results in following:

if (Uri.TryCreate(fullUrl, UriKind.Absolute, out uri))
    return uri.ToString();
//if no succesful creation:
return String.Empty;

If you do want to throw an exception, use a try/catch block and a regular Uri constructor. This should be placed in a method and not in the get statement then:

try
{
    uri = new Uri(fullUrl, UriKind.Absolute);
    return uri.ToString();
}
catch (UriFormatException ex)
{
    throw;
}

My favor would still be with the TryCreate resulting in following final code:

public string ServiceLocation
{
    get
    {
        var fullUrl = ConnectionStringData.Location.Trim();
        fullUrl += fullUrl.EndsWith("/") ? "Routes" : "/Routes";

        Uri uri = null;

        if (Uri.TryCreate(fullUrl, UriKind.Absolute, out uri))
            return uri.ToString();
        return String.Empty;
    }
}


Assuming that there is no other code in the class that you deleted here, I'm not sure why you store all the connection details in the object. I recommend to inline createDBObject into the constructor and drop the now unused fields.

After this inline there is also no usage of your setData method and you can drop it, too. In general I would not work with string identifiers, if you are not forced to. If you rename you field user to username you have to keep in mind the string and fix it to. Not all IDEs will support you here.

The following code will do the same as yours:

<?php

class GrumpyPdo
{
    private $databaseObject;

    private $killOnError = true;
    private $echoOnError = false;

    private $opt = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];

    function __construct($host, $user, $pass, $db, $charset = "utf8")
    {
        $dsn = "mysql:host={$host};dbname={$db};charset={$charset}";
        $this->databaseObject = new PDO($dsn, $user, $pass, $this->opt);
    }

    function query($query, $values = [])
    {
        if (empty($values)) {
            $stmt = $this->databaseObject->prepare($query);
            $stmt->execute($values);
        } else {
            $stmt = $this->databaseObject->query($query);
        }
        return $stmt;
    }

    function handleError($error)
    {
        error_log($error);
        if ($this->echoOnError) echo $error;
        if ($this->killOnError) die($error);
    }
}

Except the fact that your handleError is not used any longer. It is up to you, if you also want to drop it or rebuild your query method to catch PDOException and handle them with your method somehow.

From an OOP-point of view, as an slightly different approach, you might want to extend PDO instead of a delegation (with PHP 7.1 strict typing):

<?php

class GrumpyPdo extends \PDO
{
    /**
     * @var bool
     */
    private $killOnError = true;
    /**
     * @var bool
     */
    private $echoOnError = false;

    public function __construct(string $host, string $user, string $pass, string $db, string $charset = "utf8")
    {
        parent::__construct("mysql:host={$host};dbname={$db};charset={$charset}", $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
    }

    public function run(string $query, array $values = []): PDOStatement
    {
        try {
            if (empty($values)) {
                $stmt = $this->prepare($query);
                $stmt->execute($values);
            } else {
                $stmt = $this->query($query);
            }
        } catch (PDOException $e) {
            $this->handleError($e->getMessage()); // if you die, you will lose the stack trace?
            throw  $e;
        }
        return $stmt;
    }

    private function handleError(string $error): void
    {
        error_log($error);
        if ($this->echoOnError) echo $error;
        if ($this->killOnError) die($error);
    }
}

As stated in the comment, you need to think about your "error handling", if you want to stay with these debug flags. And as a drawback of PHP inheritance in this case, it is required to rename query to something else like run, because you can't override the original PDO method.

I nearly missed one last thing. In OOP you always need to be aware of the visibility of your methods and field. Please check my usage of private and public.


Don't use std::endl
Use "\n" instead of std::endl. The latter is equivalent to "\n", but also forces a flush of the output stream, which can be bad for performance.
Don't confuse getting a value with printing a value
You have functions like int GetPrice(), that look like they return the price as an int. However, in your implementation, you actually print the price to the screen, and return nothing. Either don't print and return the price, or rename the function void PrintPrice() and return nothing.
It's usually better to just return the value instead of printing them. The caller can then decide if they want to print the value, and if so how.
Consider adding operator<< overloads for printing
It's always best to make classes behave like standard types. When printing something, wouldn't it be nice if you could write the following?
FrozenPizza fp(1, 2, 3);
std::cout << fp;

You can if you create a friend operator<<(), like so:
class FrozenPizza: public FrozenFood {
    ...
    public:
    friend std::ostream &operator<<(std::ostream &os, const FrozenPizza &fp);
};

std::ostream &operator<<(std::ostream &os, const FrozenPizza &fp) {
    os << "\tFrozen Pizza Info:\n"
          "\t\tWeight: " << fp.GetWeight() << " ounces\n"
          "\t\tDiameter: " << fp.GetDiameter() << " inches\n";
}

The advantage is that you can now also "print" to different streams beside std::cout, like to a std::stringstream or a std::ofstream, making it much more generic.
Mark constants with const
In your classes, you initialize the member variables with some value, after which they can never be changed. In that case, make those member variables const, so that this is also clear to the compiler, which can then better optimize your code, and give an error if you accidentily do write to those variables:
class Frozenfood {
    const int Price;

protected:
    const int Weight;

public:
    ...
};

To be able to set these const variables in the constructor, use member intialization lists:
FrozenFood::FrozenFood(int APrice, int AWeight):
        Price{APrice},
        Weight{AWeight} {
}

I see you already use member initializer lists when initializing the base class, which is good.
Mark member functions that do not modify any member variables as const
Apart from making member variables const, you can also make member functions const. This tells the compiler that these functions do not change any member variables, which allows it to generate better code, produce errors if you do accidentily make changes, and allows those functions to be called on const objects.
So for example:
class FrozenFood {
    ...
    int GetPrice() const;
    int GetWeight() const;
};

int GetPrice() const {
    return Price;
}

int GetWeight() const {
    return Weight;
}

Consider using #pragma once
You are using header guards correctly. However, it can be a chore to add #ifndef..#define..#endif, and it is easy to accidentily copy&paste the header guard and forget to change the name. All major compilers support #pragma once. If you add that to the header files, the compiler will ensure it's only ever included once.
However, as pointed out by others, it is not standard C++ (yet). Also, C++20 introduces modules, which avoids the need for header guards.


Query to get distinct items at the top of results and duplicates following

That's a simple task for Windowed Aggregates :-)

Assign a sequential number (1,2,3,...) to each row with the same Item and order by that number:

WITH cte AS
 (
   SELECT Id, Item,
      ROW_NUMBER()
      Over (PARTITION BY Item
            ORDER BY Item) AS rn
   FROM Items
 )
SELECT Id, Item
FROM cte
ORDER BY rn, Item

Another way replaces ROW_NUMBER with

      COUNT(*)
      Over (PARTITION BY Item
            ROWS UNBOUNDED PRECEDING) AS rn

This should be more efficient as it doesn't need to actually sort.
I can't test it right now, but it should be similar to a trick used in older versions of SQL Server (before Cumulative aggregates have been implemented):

      ROW_NUMBER()
      Over (PARTITION BY Item
            ORDER BY (SELECT 1)) AS rn


In memory data access for CSV files that may have changed

It's always a good idea to try to design LINQ compatible classes. Your  DataContext can be designed this way.

first you need to un-static-fy the field, it shouldn't be static (rarely anything has to be)
implement the ILookup interface as it behaves exactly as your data-context, this is, return an empty collection if the key hasn't been found. Internally you can use a dictionary
there is no need to scan the types and fill the dictionary with empty collections

Example:

public class DataContext : ILookup<Type, BaseEntity>
{
    private readonly IDictionary<Type, BaseEntityGroup> _items = new Dictionary<Type, BaseEntityGroup>();

    public bool Contains(Type type) => _items.ContainsKey(type);
    public int Count => _items.Count;
    public IEnumerable<BaseEntity> this[Type type]
    {
        get => _items.TryGetValue(type, out BaseEntityGroup result) ? result : Enumerable.Empty<BaseEntity>();
        set => _items.Add(type, new BaseEntityGroup(type, value));
    }
    public IEnumerator<IGrouping<Type, BaseEntity>> GetEnumerator() => null;
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

This requries another helper class for storing the items, so let's create one. It needs to implement the IGrouping interface:

public class BaseEntityGroup : List<BaseEntity>, IGrouping<Type, BaseEntity>
{
    public BaseEntityGroup(Type type, IEnumerable<BaseEntity> items) : base(items) => Key = type;
    public Type Key { get; }
}

Now you can work with it like this:

var dc = new DataContext();
dc[typeof(string)] = new BaseEntity[]
{
    new BaseEntity2(),
    new BaseEntity2()
};

but you want to use some generics? So why not create a two extensions for it:

public static DataContext Add<T>(this DataContext context, IEnumerable<BaseEntity> items) where T : BaseEntity
{
    context[typeof(T)] = items;
    return context;
}

public static IEnumerable<T> Get<T>(this DataContext context) where T : BaseEntity
{
    return context[typeof(T)].Cast<T>();
}

Should you now need to query your data-context you can easily do it with LINQ.


You've already placed a constraint on the first parameter that it should be IConvertible, so the methods of that interface is available to you.

decimal decimalValueIfNull = valueIfNull.ToDecimal(CultureInfo.InvariantCulture);

Converting back to the generic type won't be as straight forward.  When casting between an object and a value type, no conversions will be made and you are just boxing/unboxing the value.  Since you have a constraint that the type be a value type, the casts won't really work here.  In fact, I don't think it's even possible to do so generically.  If a conversion exists from decimal to the type you wouldn't be able to express that here.  And you won't be able to use the Convert class to do the conversion, there's no way to "add" conversions to existing convertible types.

Your best (and probably only) option would be to convert it to a dynamic variable and let the runtime figure out whether or not that conversion exists.  That way if you have a custom ValueType here that has an implicit or explicit conversion from a decimal, it will be used.

return (T)(dynamic)sum;

If you know for sure that the types that are used here can be converted from a decimal, then you could convert back using IConvertible.ToType().

return ((IConvertible)sum).ToType(typeof(T), CultureInfo.InvariantCulture);


String Name; – Variable names begin with lowercase by convention: String name;.
unit_price; unit_type; – Variable names are camel case by convention: unitPrice; unitType;
boolean groupOffer – It's convention to start boolean variables with is..., has..., can..., must...: boolean isEligibleForGroupOffer. Such you also don't need the comment.
int unit_price;  int buy,get;

Your amounts are integers only? Really? Not float or BigDecimal:

  Currency

  It is recommended to use BigDecimal class while dealing with Currency or monetary values as it provides better handling of floating point numbers and their operations.

buy and get are verbs that fit better to a method name. Do you mean buyingPrice and sellingPrice?
More than one variable declaration per line is discouraged.

I'd rename UnitType to SellingUnitand NUMERIC to PIECES.
I'd implement the body of your first constructor with just:

this(name, unitPrice, sellingUnit, isEligibleForGroupOffer, 0, 0);

And the one of the second with:

this.name = name;
this.unitPrice = unitPrice;
this.sellingUnit = sellingUnit;
this.isEligibleForGroupOffer= isEligibleForGroupOffer;
this.buyingPrice = buyingPrice;
this.sellingPrice = sellingPrice;

I'd add a space after the commas in parameter and argument lists for easier reading.
I'd change static ... getPrice(...) to a non-static member of Product with then a header of public BigDecimal getPriceFor(float quantity).
It's convention to separate name and parenthesis in statements like if (...) with a space to easily distinguish them from method invocations.
I'd simplify:

float price = product.unit_price * quantity;
//To decrease the price of free items.
if(product.groupOffer) {
  price = (quantity/(product.buy+product.get)) * product.buy * product.unit_price;
}
return price;

to:

return isEligibleForGroupOffer  //To decrease the price of free items.
         ? quantity / (buyingPrice + sellingPrice) * buyingPrice * unitPrice
         : unitPrice * quantity;


Recursive os.scandir() for copying/moving files preserving subdirectories

You use pathlib.Path, which is great, but it can do a lot more:

Operations like os.path.splitext should be modernized using the suffix attribute of Path objects; for a full list of those designated replacements, see the documentation.
os.scandir can in this case be replaced by Path.rglob. This is where the recursion you mentioned comes into play. But that's it: Recursive globbing is an irrelevant implementation detail here. The point is that we do not have to do it "manually". rglob takes a pattern as its string argument, which can be the suffix you mentioned.
Further, os.makedirs can be Path.mkdir with parents=True for the latter. This is not as big a win as the others, but nice.

Eventually, it turns out the os import can be done without altogether, and recursion is neatly tucked away:

from pathlib import Path
from shutil import copy2  # "identical to copy() but attempts to preserve to file metadata"

COPY_FROM = Path("source")
COPY_TO = Path("dest")

SUFFIX = "*.py"

for source in COPY_FROM.rglob(SUFFIX):
    subpath = source.relative_to(COPY_FROM)
    destination = COPY_TO.joinpath(subpath)
    destination.parent.mkdir(parents=True, exist_ok=True)
    copy2(source, destination)

Note the use of copy2, which is identical to copy but attempts to preserve metadata.
This can be convenient for e.g. music files.

The parent attribute is the logical parent path to the found file, so essentially all path elements except for the found file itself.
Like in your solution, those path elements (directories) have to be created first.
In mkdir, exist_ok=False is the default and would prohibit us from most desired operations, like copying files in subdirectories.

The above gives the following result, which is hopefully what you are aiming for:

~$ tree
.
├── dest
│   ├── file1.py
│   ├── test1
│   │   ├── file2.py
│   │   └── file3.py
│   └── test2
│       ├── file4.py
│       └── test3
│           └── file5.py
└── source
    ├── file1.py
    ├── test1
    │   ├── file2.py
    │   └── file3.py
    └── test2
        ├── file4.py
        └── test3
            └── file5.py


You don't need two passes.

    boolean status = false;
    int i;
    int count = 0;
    for (i = 0; i < a.length; i++) {
        if (a[i] % 2 == 0) {
            count++;
        }
    }
    if (count == 2) {
        int j;
        for (j = 0; j < a.length; j++) {
            if (a[j] % 2 == 0) {
                System.out.println(a[j]);
                break;
            }
        }
        int nextValue = a[j + 1];
        System.out.println(nextValue);
        if (nextValue % 2 == 0) {
            status = true;
        }
    } else {
        status = false;
    }
    return status;

You can replace this with just

    int i;
    for (i = 0; i < a.length - 1; i++) {
        if (a[i] % 2 == 0) {
            i++;
            if (a[i] % 2 == 0) {
                i++;
                break;
            } else {
                return false;
            }
        }
    }

    if (i == a.length && a[i-1] % 2 != 0) {
        return false;
    }

    for (; i < a.length; i++) {
        if (a[i] % 2 == 0) {
            return false;
        }
    }

    return true;

or even shorter

    for (int i = 0; i < a.length - 1; i++) {
        if (a[i] % 2 == 0) {
            i++;
            if (a[i] % 2 == 0) {
                i++;
                for (; i < a.length; i++) {
                    if (a[i] % 2 == 0) {
                        return false;
                    }
                }

                return true;
            } else {
                return false;
            }
        }
    }

    return false;

Either of these only requires a single scan.

If they find no even numbers in the first a.length - 1 elements, they fall through and return false.

If they find an even number but the next number is odd, they return false.

If they find two even numbers and then find a third, they return false.

If they find two even numbers and every remaining number is odd, they return true.

This saves both status and count as variables.

But the shortest version that I could write was

    int evensCount = 0;
    for (int number : numbers) {
        if (number % 2 == 0) {
            evensCount++;
        } else if (evensCount > 0 && evensCount != 2) {
            return false;
        }
    }

    return evensCount == 2;

Note that I renamed a to numbers in this case.  I prefer that kind of name for collections and arrays, and since I only use it once, there was less advantage to terseness.

This version only checks if numbers are even in one place.  All the other versions had to do this in multiple places.  I believe that makes this code DRYer as well as shorter.

This iterates through the array, counting the even numbers.  For each odd number, it checks if it has seen any even numbers.  If it has, it checks if it has seen exactly two.  If not, it can return false.  If it has seen exactly two consecutive even numbers, it keeps going.  If it goes all the way through and finds exactly two even numbers, it can return true.  Otherwise, it returns false.

So if it sees one even number followed by an odd number, it will abort and return false.  The evensCount will be equal to 1.

If it sees three or more consecutive even numbers, it will return false once it sees the next odd number.  Or when it is done iterating if the even numbers last until the end.

If it sees two consecutive even numbers and then an odd number, it will search for more even numbers.  If it finds one, it will eventually return false.  If it doesn't, it will return true after scanning the entire array.

You could sometimes speed it up by adding another if that checks if evensCount is greater than two.  However, that will also slow it down in some situations.  And of course it is more code.  If time is critical, it might help.  Or not.  It really depends on the inputs.  I omitted it because it is only sometimes better at all and I'm not sure we need to optimize to that level.

My test cases:

    System.out.println("The result is: " + isTwinoid(new int[]{3, 3, 2, 6, 5, 6, 7}));
    System.out.println("The result is: " + isTwinoid(new int[]{3, 3, 2, 6, 6, 7}));
    System.out.println("The result is: " + isTwinoid(new int[]{3, 3, 2, 7, 6, 7}));
    System.out.println("The result is: " + isTwinoid(new int[]{3, 8, 5, 7, 3}));
    System.out.println("The result is: " + isTwinoid(new int[]{3, 3, 2, 6, 7}));
    System.out.println("The result is: " + isTwinoid(new int[]{3, 3, 2, 6}));

Results:

  The result is: false
  The result is: false
  The result is: false
  The result is: false
  The result is: true
  The result is: true


calculate tree height (arbitrary tree) - python

Standard indentation is four spaces.
Missing spaces here and there.
Unnecessary parentheses after while.
Can't handle empty trees.
Name di is really unclear, i and p could also be better.
Using .keys() like that is pointless.
Using negative values is pointless and confusing. Using abs on the result is particularly confusing, as it suggests that the value you give it could be negative or positive. Since you know it's negative, that should've been just -max_distance.
No need to reinvent max.

Rewritten accordingly:
def height(array):
    depth = {-1: 0}
    while len(depth) <= len(array):
        for child, parent in enumerate(array):
            if parent in depth:
                depth[child] = depth[parent] + 1
    return max(depth.values())

For performance, instead of repeatedly searching for children with finished parents, first do one pass to collect each parent's children. Then when you finish a parent, simply go through its previously collected children to finish them, too. This is then linear instead of quadratic time.
Or if the limits are small enough (so far you still haven't answered the comment asking about that), you could use a simple recursive depth(node) function decorated with functools.cache, apply it to all nodes, and take the max. Also linear time.


The technique you're looking for is called memoization (or in other contexts it might have names like caching). Lazy evaluation is something else entirely.

Memoization is the canonical example for how decorators work in Python, but you don't need to learn the additional language construct if you don't like. Consider the following snippet. It could be more general, but that's beside the point.

def memoize(f):
    cache = {}
    def _f(n):
        if n not in cache:
            cache[n] = f(n)
        return cache[n]
    return _f

What we've created is a function that takes another function as an argument. How do we use it? Well, we pass a function into it.

def pi(n):
    # do stuff
pi = memoize(pi)

Take a close look at this.

First we make our normal function that deals with primes.
Next, we pass it into this memoize() monster that we just made.
When memoize() sees this function (now just called f), it makes a cache and defines a new function _f(). It's this new function _f() that's finally returned (i.e., at the end of all this, pi is the same as whatever _f happened to be), so let's look closely at what _f() does.

First, _f() takes a look in the cache to see if we've already seen the value n. If not, it stores the output f(n), i.e. the original pi(n) we wanted, in the cache.
Next, it returns the pre-computed value straight from the cache. That's it.

Now we've eliminated the use of globals (behind the scenes the cache thing we described is stored in what's called the closure of _f), we've taken the problem of caching away from pi() to give pi() a small, single purpose, and we've created a reusable memoization mechanism that we can apply to any other function that takes exactly one hashable input.

Back to the decorator thing I mentioned earlier, you could just as well write

@memoize
def pi(n):
    # do stuff

to memoize the pi function instead of applying the memoizer after the fact. It doesn't make much of a difference either way, but the latter is considered more pythonic.

To be able to take multiple arguments, you can start to do things with *args and **kwargs in your memoizer, but that's additional complexity without a lot of added benefits for the sake of this problem.


Style

The while loop definitly looks like a for loop to me.

Clearer function

Your function numberSieve does not many things. It would be simpler if it was to simply return a value and this value was used afterward to fill arrays.

If we are doing so, we could take this chance to make clear what it returns : it could return whether x is prime or not. By renaming it isPrime, things would be more straightforward.

Also, if you do so, you realise that you can start your loop from 2 if you want to get the same output as you had before.

Here is the corresponding code :

// Create isPrime function
function isPrime(x) {

    // 0 and 1 are not prime
    if (x < 2) {
        return false;
    }
    // Sieve for positive numbers above 1
    else {
        // Some more variables for later use
        possibleFactors = [];
        zFactors = [];
        matchingFactors = [];

        // Takes all numbers that are half of x and below because they are possible factors
        for (i=2; i < x/2+1; i++) {
            possibleFactors.push(i);
        }

        // Takes all possible factors and divides x by them
        for (i=0; i < possibleFactors.length; i++) {
            z = x/possibleFactors[i];
            zFactors.push(z);
        }

        // Checks if the x divided by the possible factors is equal to any of the other possible factors
        for (i in possibleFactors) {
            if (zFactors.indexOf(possibleFactors[i]) !== -1) {
                matchingFactors.push(possibleFactors[i]);
            }
        }

        // Checks if there are any matching factors
        return (matchingFactors.length == 0);
    }
}

var primeNums = [];
var compNums = [];

// For each number 0-100 runs the sieve
for (a = 2; a<= 100; a++) {
    if (isPrime(a))
        primeNums.push(a);
    else
        compNums.push(a);
}

// Prints out the prime number and composite number arrays
print("Prime Numbers: " + primeNums);
print("Composite Numbers: " + compNums);

Clearer algorithm

You don't need to handle arrays to know whether a number divides or not anyther number. You can just use the modulo operator.

function isPrime(x) {

    // 0 and 1 are not prime
    if (x < 2) {
        return false;
    }
    // Sieve for positive numbers above 1
    else {
        // Takes all numbers that are half of x and below because they are possible factors
        for (i=2; i < x/2+1; i++) {
            if (x % i == 0)
                return false;
        }
        return true;
    }
}

A smarter algorithm

At the moment, you look for divisors going up to x/2 + 1. Actually, if there are any divisors, there will be a least one divisor d such that $$ d \le sqrt(x) $$

Therefore, instead of having a algorithm with completity O(N), we have O(sqrt(N)) which is much faster for big values of N.

   // Takes all numbers that are half of x and below because they are possible factors
    for (i=2; i <= Math.sqrt(x); i++) {
        if (x % i == 0)
            return false;
    }
    return true;

A more appropriate algorithm

If you want to generate a list of primes (and non-primes) in an efficient way, you should have a look at the Sieve of Eratosthenes.


I see a very big advantage of your current approach rather than moving the implementation of onGetPriceType to the GetBuildType class (May I suggest changing the name to GetBuildTypeTask?)

Decoupling code. Your GetBuildType class is 100% independent of your activity. That is a good sign. If needed, you could at any time re-use the GetBuildType class and provide it with another GetBuildTypeInterface.

A side suggestion: I assume that result.parse() doesn't need to be run on the UI-thread, so you can change your class to extend AsyncTask<Void, Void, Map<String, String>> and make the conversion to map in doInBackground (or return null if u.getBt() returns null). Also, you don't need to create a new empty HashMap before parsing the JsonArray, simply Map<String, String> map = jsonArray.parse(); will do.

The only disadvantage I see with your current implementation is that you get an extra interface. But I really don't think that's so bad compared to having decoupled code.


A simple dict comprehension and use of str.format() will do the job here:

>>> {"{}V{}".format(name, version): description
     for name, version, description in movies}
{'HarryPotterV1': 'Movie about magic',
 'HarryPotterV4': 'Movie about more magic',
 'JawsV1': 'Movie about sharks',
 'JawsV2': 'Movie about more sharks'}

Or, in very old versions of Python where dict comprehensions don't exist, simple replace with dict() and a generator expression - e.g: dict(... for ... in moves).

Note that if this is just because you want to have the data as keys, you don't need to turn them into a string, a tuple can be a key too:

>>> {(name, version): description
     for name, version, description in movies}
{('Jaws', 1): 'Movie about sharks',
 ('HarryPotter', 4): 'Movie about more magic',
 ('Jaws', 2): 'Movie about more sharks',
 ('HarryPotter', 1): 'Movie about magic'}

This would be more appropriate where you don't need the strings, as it means you don't have to parse stuff out or create strings for keys, and makes the data easier to manipulate.


Using pytest fixtures for the expected answers to a test?

I don't do much python, but I do find your use of a fixture to return the answer a little bizarre.  For me, having the actual string in the test would be the way to go.  As I understand it, what you don't like about doing this is that you end up with multiple tests, all of which are calling different implementations and then verifying that the implementation returns the same thing.  This sounds like something you might want to use a parameterized test for.  Rather than passing in the changing data though (since it's the same), you'd parameterize the method under test:
@pytest.mark.parametrize("fizzbuzzer",
    [fizz_buzz_if_calc, fizz_buzz_using_boolean])
def test_fizz_buzz_has_correct_items(fizzbuzzer):

    actual = fizzbuzzer()

    assert actual == [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']

If the test fails, then you get an indication as to which failed as part of the test name and the follow up information:
________________________________ test_fizz_buzz_has_correct_items[fizz_buzz_if_calc] _________________________________

fizzbuzzer = <function fizz_buzz_if_calc at 0x7f2ff2bbab80>


I'm not entirely sure what this code does, but it certainly seems too long for the problem. First some general review:

      let numString = n.toString();

This is a matter where opinions will certainly differ, but I would prefer to instead assign n = n.toString(); as n is never used again, and the real purpose of this line is to coerce the input to the type which you want to receive.

      let permutations = []

This is a bit surprising: you only need to generate one permutation, so why do you need an array with many? A comment explaining the purpose would be nice.

      let smallest = numString[0];

This is also surprising. "Smallest" in what sense? It's unlikely that the smallest digit will coincidentally be the first one.

      if(descending || same){
        return -1;
      }

Is there any reason for using two variables here? I think it could be simplified by having one variable which tracks whether there's any increase over the previous digit (although the complete rewrite will eliminate this anyway).

      const permute = (prefix, str) => {

What does this function do? Comment!

        let index = String(str).length;

Earlier the code used toString(); here it uses String(...) to do the same thing. Be consistent.

        if(index == 1){

Although index will always be a number, consistently using === reduces the cognitive load in working out whether == should really have been ===.

      let nextBiggest = Infinity;

WTF? This method was working with strings: where does Infinity come into it?

      return -1

This should be unreachable, so why not throw an exception to alert you to the fact that if it's reached you have a bug?

Now, the part you're really interested in. The algorithm.

The question of finding the next permutation in lexicographic order is a classical one (going back 7 centuries) and well documented in the literature. E.g. Wikipedia gives the following algorithm:

  Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
  Find the largest index l greater than k such that a[k] < a[l].
  Swap the value of a[k] with that of a[l].
  Reverse the sequence from a[k + 1] up to and including the final element a[n].


A few quick stylistic things:

Don't use <>, its considered an older style use != instead
When comparing against None, use "x is None" not "x <> None" or "x != None" This is because there is only one None object so its more correct to compare object identity
Don't use == True or == False. There are some corner cases that won't do what you expect. They clutter your code and make it look like you don't know what you are doing.
Your variables do not provide much hints about what they are doing. For example you have variables named truth. Given that we already knew there were holding booleans thats not very useful.

To actually rework your code:

You set values in a truth list, then use those values to decide whether or not to take an action. Flags clutter code. Rather then setting those flags, why don't we maintain a list. By adding a remaining_Comp1 and remaining_comp2 list I push elements in there instead of setting Truth values in my list. This completely eliminates the neccesity of keeping the truth lists and eliminates a lot of the code.
You have two for loops which iterate over all possible combinations of elements from your two lists. By using itertools.product, we can make this simpler
You check that comp1 is not empty, but not comp2. This looks like an oversight.
You are keeping track of depth to make sure you don't go into too much detail. But you've basically reimplemented a for loop. I'd move depth into a for loop and simply bail out with a break statement if comp1 or comp2 is empty.
Rather then checking whether trace is None, I recommend using a NullTracer which simply does nothing when it is called.

Your code reworked:

def bcw_do_collide_i(obj_A,obj_B,tracer=None, accuracy = 30):
    """ Check whether Box-Circle World objects obj_A
    and obj_B collode. If so, return True,
    otherwise return False.
    """
    if tracer is None:
        tracer = NullTracer()

    # items to be checked
    comp1 = [obj_A]
    comp2 = [obj_B]

    for depth in range(accuracy):
        if not comp1 or not comp2:
            return False

        remaining_comp1 = []
        remaining_comp2 = []
        # Find any non colliding components
        for c1, c2 in itertools.product(comp1, comp2):
            circum_1 = bcw_circumcircle(c1)
            circum_2 = bcw_circumcircle(c2)
            tracer([c1,c2,circum_1,circum_2], ["k--","b--","r--","r--"])
            if bcw_do_circles_overlap(circum_1,circum_2):
                remaining_comp1.append(c1)
                remaining_comp2.append(c2)
                # Check for colliding components
                in_1 = bcw_incircle(c1)
                in_2 = bcw_incircle(c2)
                tracer([c1,c2,in_1,in_2],
                   ["g--","b--","r--","r--"])
                if bcw_do_circles_overlap(in_1,in_2): return True

        # Subdivide all components whose outers collide
        def expand_components(components):
            result = []
            for c1 in remaining_comp1:
                result += bcw_components(components)
            return result

        comp1 = expand_components(remaining_comp1)
        comp2 = expand_components(remaining_comp2)

    return False


Find the number of all specific substrings in a string

First off, I believe you are confusing the terms "specific" and "special" in the description.

Method isSpecial

You could move the if (occurrences.size() > 2) statement into the for loop, because once you know that there are more than 2 different characters, there is no need to continue adding more characters to the Set. Then you can also initialize the HashSet to an initial size of 3, because it never can grow larger than that.
You don't need the part input.charAt(0) == input.charAt(input.length() - 1) in the final expression, because when the length is more than two and if there are exactly two different characters, it can never be
false when input.charAt(input.length() / 2) != input.charAt(0) is true.
Finally I'd put input.length into a local variable. That will speed up the for loop by a tiny amount by avoiding the method call and it will make the final expression a bit shorter and thus better to read

private static boolean isSpecial(String input) {
    int len = input.length();
    Set<Character> occurrences = new HashSet<>(3);
    for (int i = 0; i < len; i++) {
        occurrences.add(input.charAt(i));
        if (occurrences.size() > 2) {
            return false;
        }
    }
    if (occurrences.size() == 1) {
        return true;
    }
    return len % 2 == 1 && input.charAt(len / 2) != input.charAt(0);
}

Method substrCount

This method can be shorten significantly by using Java 8's Stream API:

static long substrCount(String s) {
   return allCombinations(s).stream().filter(ClassName::isSpecial).count();
}

(ClassName is the name of the class isSpecialis in.)


Find the sum of the digits in factorial of 100 in Erlang

Don't need rewrite functions which already exist in standard library. Almost always it's will give worse result and just take away your time for writing and testing.

For converting from integer to list (string) - integer_to_list/1
For getting some single result from set data in a list - use lists:foldl/3
For extracting the numerical value from digit symbol - just subtract zero-value($0, number representation in Erlang).

So, if accumulate all of this points, get:

task_(N)->
lists:foldl(fun(X,Sum)->Sum+X-$0 end,0,integer_to_list(fact(N))).

If saying generally, I don't see any problem in rule - "one function for one task". It will make your code more readable, flexible and good for testing.


Updating list of string while other threads are reading from it

Yes if you only read the whitelist.

You can guarantee this at runtime by wrapping it in Collections.unmodifiableList while setting.

whitelist.set(Collections.unmodifiableList(tempList));

However because you don't use any other feature of the AtomicReference other than get and set, you don't need AtomicReference at all (or if you do it should be final); just volatile is enough:

private volatile List<String> whitelist = Collections.emptyList();//empty dummy list

whitelist = Collections.unmodifiableList(tempList);

And check with if (whitelist.contains(hash)) return null;

That leads me to the list itself; if you only check whether a values is contained within the list then you should consider changing the list to a HashSet.

private volatile Set<String> whitelist = Collections.emptySet();

Set<String> tempList = new HashSet<String>();
for (File f : scriptWhitelistDirectory.listFiles()){
    tempList.add(f.getName());
}
whitelist = Collections.unmodifiableSet(tempSet);


You are completely over-doing it. Your algorithm will be O(n3) (I think) on the length of the input when you can do it more simply in O(n2).

Consider the following instead:

Start at the middle of the input.
While the substring starting from this index is not equal the substring beginning the start of the input with the same length, we increment the index.
Finally, we return the length of the final substring that matched.

Basically, the logic can be summed up by this drawing:

-------------
^^^^^^ ^^^^^^ matches or not?

// if no continue

-------------
^^^^^   ^^^^^ matches or not?

// if no continue

-------------
^^^^     ^^^^ matches or not?

You can see the logic.

Implemented in code, it would be the following:

private static int identifyGarlandDegree(String candidate) {
    int length = candidate.length();
    int index = length / 2;
    while (!candidate.substring(0, length - index).equals(candidate.substring(index))) {
        index++;
    }
    return length - index;
}

Note that we don't need to add a check on index: it won't go out of bounds since when index == length, it will exit normally (empty string being equal to another empty string).


Persisting objects in a ListBox ObjectCollection

If you don't mind using a little bit of LINQ, it can be simplified (and optimized) as such:

static class BukkitServerDataWriter
{
    private static readonly XmlSerializer xml = new XmlSerializer(
        typeof(List<BukkitServer>),
        new[] { typeof(BukkitServer) });

    public static void SaveServers(ICollection objects)
    {
        using (var writer = new XmlTextWriter("servers.xml", Encoding.UTF8))
        {
            xml.Serialize(writer, objects.Cast<BukkitServer>().ToList());
        }
    }
}


Prime number checker in Python 3 - follow-up

0. Overview

Your code is well written and what it does is clear. However I will argue that if you want a drastic increase in performance, you need to switch your algorithm. Testing primality can be done in polynomial time, but is generally a problem which requires sophisticated math. The problem can be solved in polynomal time as shown by the AKS_primality_test. However there are far faster algorithms than this one. As you can see, it is not the easiest thing to understand without a background in higher mathematics.

A review of your algorithm
Show a probabilistic approach
Compare your algorithm, the probabilistic, and the isprime function from the primefac package.

1. Review

As your code is fairly short, there is not much to comment on. I really like that you use a docstring in the beginning of your code to document it. The code looks good.

Use the if __name__ == "__main__": module. It makes it easier to test and easier to import.
Some of the comments are unnecessary and there is too much space in the last return.
The num <= 1 is a bit strange. It catches everything from inputing \$0\$ and \$1\$ to negative and decimal numbers. In my opinion it is better to treat negative numbers and non-integers with an error instead. Then we can explicitly remove \$0\$ and \$1\$ as special cases.

One way to handle this could be

try:
    int(num)
except ValueError:
    raise ValueError("Ops. Input must be a positive integer")
if int(num) != num or num < 0:
    raise ValueError("Ops. Input must be a positive integer")

if num in [0, 1]: return False

The last line could also have been written as

if num <= 1: return False

Since we have already tested that num => 0. However I prefer the first version as it is much clearer what it actually checks. You should always try to make it as clear as possible what you want to catch.

1.1 Some improvements on the algorithm

Say you check some number with your algorithm. If the number is not divisible by \$3\$ you do not need to ever check any multiples of \$3\$ again. Yet your code checks \$6\$, \$9\$ and so forth. A better approach would be to iterate over the numbers not divisible by \$2\$ or \$3\$. This removes the checking of \$2/3\$ of all numbers in comparison to only removing \$1/2\$. So, what numbers are not divisible by \$3\$ or \$2\$? Well all numbers are on the form \$6k+1\$, \$6k+2\$, \$6k+3\$, \$6k+4\$ or \$6k+5\$. Since they are either \$0\$, \$1\$, \$2\$, \$3\$, \$4\$ or \$5\$ numbers away from being a multiple of \$6\$. This means that only numbers on the form \$6k+1\$ or \$6k+5\$ are not divisible by \$2\$ or \$3\$.

Implementation is simple increase counter by \$6\$, test \$+1\$ and \$+5\$.

primes_to_remove = [2, 3, 5]
for prime in primes_to_remove:
    if num == prime: return True
    elif num % prime == 0: return False

# Look for a factor
limit = int(num**(0.5))+1
for multiple in range(6, int(num**(0.5))+1, 6):
    for k in [1, 5]:
        # If there is a factor
        if num % (multiple+k) == 0:
            # Its not a prime number
            return False

This can further be generalized by removing [2, 3, 5] as shown below

primes_to_remove = [2, 3, 5, 7, 11, 13, 19, 23, 29]
for prime in primes_to_remove:
    if num == prime: return True
    elif num % prime == 0: return False

# Look for a factor
limit = int(num**(0.5))+1
for multiple in range(30, int(num**(0.5))+1, 30):
    for k in [1, 7, 11, 13, 19, 23, 29]:
        # If there is a factor
        if num % (multiple+k) == 0:
            # Its not a prime number
            return False
return True

This idea of removing the first primes can again be modified into removing [2,3,5,7] and then check the remaining numbers. However the advantages of this method quickly diminish for larger primes as we are removing fewer and fewer numbers. As a last example, it is possible to only iterate over the primes. From the primesieve library we can import a prime generator.

from primesieve import Iterator

def is_prime_primegenerator(num):
    it = Iterator()
    prime = it.next_prime()

    # Iterate over the primes below sqrt(n)
    limit = int(num**(0.5))+1
    while prime < limit:
        prime = it.next_prime()
        if num % prime == 0:
            print num, prime
            return False
    return True

This is the best we can do following down your path of checking primes from the smallest to the largest. It assumes however that the next_prime() is extremely fast. Which it luckily is.

Using the 235 version of the sieve above, it gave me a \$2.5\$ times speed increase of your code. Putting it all together gives

def is_prime(num):
    '''Calculates whether num is a prime number,
    if it is return True otherwise return Flase'''

    try:
        int(num)
    except ValueError:
        raise ValueError("Ops. Input must be a positive integer")
    if int(num) != num or num < 0:
        raise ValueError("Ops. Input must be a positive integer")

    # SPECIALCASE: These are special cases that are not primes
    if num in [0, 1]: return False

    primes_to_remove = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    for prime in primes_to_remove:
        if num == prime: return True
        elif num % prime == 0: return False

    # Look for a factor
    limit = int(num**(0.5))+1
    for multiple in range(30, int(num**(0.5))+1, 30):
        for k in [1, 7, 11, 13, 19, 23, 29]:
            # If there is a factor
            if num % (multiple+k) == 0:
                # Its not a prime number
                return False
    return True

if __name__ == '__main__':
    print is_prime(600851)

Using some quick comparisons it seems that the 235 version is the fastest for solving larger primes while 23 and the naive are pretty similar in running times.

               naive   23    235    primes
600851475151 | 117ms   71ms  40ms   19ms

2. Probabilistic primality test

A short explanation can be found on Wikipedia.

  Probabilistic tests

  Probabilistic tests are more rigorous than heuristics in that they
  provide provable bounds on the probability of being fooled by a
  composite number. Many popular primality tests are probabilistic
  tests. These tests use, apart from the tested number \$n\$, some other
  numbers a which are chosen at random from some sample space; the usual
  randomized primality tests never report a prime number as composite,
  but it is possible for a composite number to be reported as prime. The
  probability of error can be reduced by repeating the test with several
  independently chosen values of a; for two commonly used tests, for any
  composite \$n\$ at least half the a's detect n's compositeness, so \$k\$
  repetitions reduce the error probability to at most \$2^{−k}\$, which can be
  made arbitrarily small by increasing \$k\$.

  The basic structure of randomized primality tests is as follows:

  Randomly pick a number \$a\$.
  Check some equality (corresponding to the chosen test) involving \$a\$ and the given number \$n\$. If the equality fails to hold true, then \$n\$
  is a composite number, a is known as a witness for the
  compositeness, and the test stops.
  Repeat from step 1 until the required accuracy is achieved.

  After one or more iterations, if \$n\$ is not found to be a composite
  number, then it can be declared probably prime.

The important bit is the three steps at the bottom. We put our number through some test and if it passes there is a \$1/2\$ chance of it being composite. After passing \$k\$ tests, the chances of being composite is \$2^{-k}\$. When big banks check for primality they often use a probabilistic prime test where \$k\$ is around \$80\$. The chances of a composite passing \$80\$ tests is just

$$
P_{80}(\text{composite}) = 2^{-80} = \frac{1}{1208925819614629174706176}
$$

So if you test \$1208925819614629174706176\$ numbers, on average one of them will be a composite passing all the tests. Below I will show a simple implementation of the Miller-Rabin primality test. It is one of the fastest and simplest ways to implement a primetest. This algorithm can be divided into three steps:

Generate a small list of primes below some limit (I used 1 million)
Check if the prime number is even, and some other small tests. Then check if it is in the primeset.
If the prime is bigger than the limit apply the Miller-Rabin primality test \$25\$ times. The number \$25\$ is arbitrary, however it does not need to be particularly big as the chances of a composite slipping through is \$2^{-k}\$.

The reason for step 1 is both because it is faster, but also because the Miller-Rabin test have a harder time detecting small primes. I imported the fastest prime_generator I could find through google. However if you allow for external libaries primesieve is faster. However generating primes is just a small part of the excecution time, and not worth optimizing further.
\${}{}\$

import numpy as np

def primesbelow(n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)
    sieve[0] = False
    for i in xrange(int(n**0.5)/3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[      ((k*k)/3)      ::2*k] = False
            sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False
    return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]

smallprimeset = set(primesbelow(100000))
_smallprimeset = 100000

def isprime(n, precision=25):
    # http://en.wikipedia.org/wiki/Miller-Rabin_primality_test#Algorithm_and_running_time
    try:
        n = abs(int(n))
    except ValueError:
        print("Input must be a non-negative integer")
    if n in [0, 1]:
        return False
    elif n in [2, 3, 5]:
        return True
    elif n % 2 == 0:
        return False
    elif n < _smallprimeset:
        return n in smallprimeset

# Miller-Rabin primality test

d = n - 1
s = 0
while d % 2 == 0:
    d //= 2
    s += 1

for repeat in range(precision):
    a = random.randrange(2, n - 2)
    x = pow(a, d, n)

    if x == 1 or x == n - 1: continue

    for r in range(s - 1):
        x = pow(x, 2, n)
        if x == 1: return False
        if x == n - 1: break
    else: return False
return True

3. Comparison

I used

pip install primefac

To be able to use the isprime function from the primefac package. Then I did some simple primality testing on a few semi-large numbers.

All the tests where done a \$100\$ times and then i took the average. I did a \$1000\$ averages for Miller-Rabin and primefac for better accuracy. There is no need to test composite numbers, because all the implementations stop once a prime has been found. All the tests are therefore done on primes.

    number              naive             23       235    primegen     miller    primefac
    -----------------------------------------------------------------------------------------
             60085159     0.69 ms    1.09 ms   0.47 ms     1.02 ms    0.25 ms    0.24 ms
           6008514763       22 ms      61 ms      7 ms      3.8 ms   0.104 ms    0.070 ms
          60085147517       56 ms      30 ms     12 ms      6.5 ms   0.072 ms    0.090 ms
         600851475151      283 ms     281 ms    155 ms     56 ms     0.364 ms    0.331ms
    99194853094755497   117328 ms  113053 ms  58010 ms  19117 ms     0.638 ms    0.239180 ms
    -----------------------------------------------------------------------------------------

As you can see you do fairly well for small values. For \$60085159\$ your code is about \$2.75\$ times as slow as the Miller-Rabin. However as the values increase so does the difference. For \$600851475151\$ your code is about \$777\$ times slower. Finally for \$99194853094755497\$ the Miller-Rabin is \$183899\$ times faster.

There might be something wrong with my testing since the 23-version is about as fast as the naive implementation (yours). However the 235 is a simple speed increase. If you want a drastic improvement however you need to switch to another implementation. Either use a library which has a builtin isprime function, or use a probabilistic approach: Fermat primality test, Miller-Rabin, Solovay-Strassen primality test, Frobenius primality are just some of the many fast implementations.


Given a string S and a set of words D, find the longest word in D that is a subsequence of S

You know, if you want to improve performance, the first thing to do is get a high-level overview of what your code does to achieve its aim. Currently, you do this:

Iterate over all words in D.

Iterate over the whole string S trying to prove it a sub-sequence.

That's trivially proven to be an \$O(\#D * \#S)\$ algorithm.

You can do better, by using the proper data structure:

Build a prefix-tree from the words, noting the longest word which can be found from there.
Iterate over the string.

Continue if the current character doesn't fit.
Update the best found if it is a terminal node.
recurse with the sub-tree.

Regarding your code:

Your use of a class is completely unmotivated. There are no invariants to protect, as evidenced by you marking it all public, and you only create it to call one single function anyway. Just make it a free function. Ok, if you change the algorithm, you might want to break it up it into building the trie, using a pre-computed trie, and putting it all together.
auto would allow you to always have the proper type, without cluttering your code with long and obscure names. Read "Almost Always Auto".
I'm not sure why you use a std::tuple. Maybe for obfuscation? If so, I confirm you are on the right way.
Always define variables in the smallest scope possible, unless there are significant advantages (most likely in performance) for a slightly longer lifetime.
return 0; is implicit for main().


You could just implement the infinite generator, and use itertools.takewhile to limit it:

>>> list(itertools.takewhile(lambda x : x < 8, fibonacci_inf(0,1)))
[1, 1, 2, 3, 5]


Making a datatable, maybe also with column filters

Use some variables. You don't need to chain function calls; it's just a neat thing you can do when appropriate, but it's not required.

$('#dt_a').each(function() {
  var target = $(this), // store this
      table  = target.dataTable({  // and store this too
          "sDom": "<'row'<'span6'<'dt_actions'>l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
          "sPaginationType": "bootstrap_alt",
          "oLanguage": {
              "sLengthMenu": "_MENU_ records per page"
          }
      });

    if (target.hasClass('trans')) {
        table.columnFilter({
            sPlaceHolder: "head:before",
            aoColumns: [
                null,
                { type: "text" },
                { type: "text" },
                { type: "date-range" },
                { type: "text" },
                { type: "text" },
                null,
                null
            ]
        });
    }
});


Condensing code that generates Pascal's triangle

Bugs

The variables xArr and g shouldn't be static.
The consequence of them being static is that you cannot use this class twice,
because the static state is not reset per instance.
For example this will cause an ArrayIndexOutOfBoundsException:

new PascalTriangleYar().pTriangle(3);
new PascalTriangleYar().pTriangle(4);

You can fix that by making g non-static.
But you should also make xArr non-static too,
because quite simply, it doesn't need to be static,
and there's no reason whatsoever to make it static.

Condensing the code

Condense code doesn't sound great.
It makes me imagine code with no vertical spaces and no spacing around operators.
That's condense. And that's no good.
Maybe you're looking for a different term.
Maybe want to DRY this up, reducing duplication,
and increasing reusability and modularity.

There's one thing useful to do for "condensing",
is removing unnecessary elements:

The getTri method is unused
The n variable in pTriangle is unused
The z variable in p2T is unused

Another thing for condensing is removing some excessive vertical space.
That is, one blank line between methods is enough,
and there shouldn't be blank lines before the closing braces } of code blocks.

Code duplication

Look very suspiciously at code like this:

xArr[n][p] = 1;

for (int fd = 0; fd < xArr[0].length - 1; fd++) {
    if (fd == 0)
        xArr[n][fd] = xArr[n - 1][0] + xArr[n - 1][1];
    else
        xArr[n][fd] = xArr[n - 1][fd - 1] + xArr[n - 1][fd + 1];

    xArr[r - 1][2 * r - 2] = 1;
}

Notice the duplication in the if-else branches.
Something is fishy there.
What's so special about the fd == 0 case?
On closer look, the case of fd == 0 is already taken care of,
by the xArr[n][p] = 1; statement earlier.
You can change the initialization step of the for loop to int fd = 1,
and the if-else can go away:

for (int fd = 1; fd < xArr[0].length - 1; fd++) {
    xArr[n][fd] = xArr[n - 1][fd - 1] + xArr[n - 1][fd + 1];
    xArr[r - 1][2 * r - 2] = 1;
}

Coding style

As @Hosch already covered many coding style issues I shouldn't repeat that,
but they are actually so important that I want to reemphasize:
please do everything that he suggested,
it will make a huge difference in the readability of your code.
Note that you don't actually have to manually make those corrections by yourself,
any decent IDE (Eclipse, Netbeans, IntelliJ) has shortcuts to do at least most of it for you at the touch of a few keystrokes.

In addition, prefer to use for-each loops instead of counting loops whenever possible. For example printArray can be rewritten as:

public void printArray(int[][] xArray) {
    for (int[] row : xArray) {
        System.out.println();
        for (int item : row) {
            if (item != 0) {
                System.out.print(item);
            }
            System.out.print("\t");
        }
    }
}

Notice some other improvements there:

Flipped the item == 0 condition to avoid duplicating System.out.print("\t")
No need for the "" in System.out.println("")

Thread safety, robustness

The code as it is, is very fragile.
This is because of the member fields g and xArr.
These fields give instance of your class a state,
and if the pTriangle method gets called by multiple threads at the same time,
they can break each other.

It's ok to have state and have thread-unsafe code when necessary.
But in this program it's not necessary.
You can completely eliminate the g and xArr member fields,
and pass them around as parameters to the methods that need them.
In fact, you don't need g at all, because its value is always n + 1,
so you can always derive it from n.

With these tips, the code can be rewritten as:

public void pTriangle(int r) {
    int[][] xArr = new int[r][2 * r - 1];
    xArr[0][r - 1] = 1;
    p2T(xArr, r, 1);
    printArray(xArr);
}

private void p2T(int[][] xArr, int r, int n) {
    int p = r - n - 1;

    xArr[n][p] = 1;

    for (int fd = 1; fd < xArr[0].length - 1; fd++) {
        xArr[n][fd] = xArr[n - 1][fd - 1] + xArr[n - 1][fd + 1];
        xArr[r - 1][2 * r - 2] = 1;
    }

    if (n < r - 1) {
        p2T(xArr, r, n + 1);
    }
}