I believe there's race conditions in your code, Specifically, if you call wakeup() asymettrically (more times than you call sleep()) then you run the risk of a few things:

you could have multiple running threads (i.e. there's not just one thread using the resource)
you may possibly trigger a condition where calling wakeup() twice, very fast, will cause the same thread to be unparked (i.e. waiting.peek() in wakeup()) will return the same value twice....).
it is possible that the queue does not contain a value when the wakeup is called because the 'active' thread is in the process of looking for itself (and removing other content from the queue) as it goes.

I have tried to find a way to make it work to my satisfaction below, but, frankly, I don't think it is possible without changing the code so much it is no longer 'yours'.

I think the reality is that a secure mechanism for this will necessarily rely on having a lock that contains both the unpark and the queue management.... at which point, using the park/unpark is no longer the right tool, so it defeats this process...

Feel free to read through what I was about to write, but, I am essentially abandoning it....

DISREGARD BELOW HERE

Right, you'll have to work with me on this one.... (it takes multiple 'heads' to work around 'threads'....)...

First, let me restate the problem I think you are trying to solve:

you have a resource that only one thread can access at a time
you want the 'waiting' threads to be queued (essentially in FIFO order) until the resource is available.
you want the waiting threads to be (b)locked rather than spinning.

You want the 'outside' code to look something like (this code will be in the resource-using threads):

try {
    blockedqueue.sleep(); // wait for my turn to use the resource
    doSomethingWith(resource);
} finally {
    blockedqueue.wakeup(); // indicate that another thread can use the resource.
}

I see that you start the BlockedQueue off in an 'unblocked' state, so the first thread in will immediately return. Only 'subsequent' threads will wait.

There is a gap in your logic though.... (hate to be the bearer of bad news....)...

It is possible for the queue to be empty when wakeup() is called even though there are blocked threads. This is because you may be removing() items in your loop at the same time as when the wake-up is called.

Also, I think that you should be more precise about what threads can re-awaken the queue. I like the try-finally concept which will assure that the same thread that calls sleep() will also call wakeup().

Consider the following alteration. Instead of using an AtomicBoolean to lock the thread, use an AtomicReference  (and I have renamed it to 'active' instead of 'lock'....

public void wakeup() {
    // Unlock.
    if (active.compareAndSet(this, null)) {
        // Wake the first in the queue (and remove it too) ... unpark does nothing with a null parameter.
        LockSupport.unpark(waiting.poll());
    } else {
        throw new IllegalMonitorStateException("Cannot unlock a thread unless you are the owner of the lock");
    }
}

This will prevent spurious wake-ups, but if you have asymmetrical code (more wakeup() than sleep()) you will get exceptions (I think that's a good thing).

In your sleep() method you can also gain some efficiency by not using the queue at all if you're the only active thread...

public void sleep() {
    final Thread me = Thread.currentThread();
    if (blocked.compareAndSet(null, me) {
        // nothing is waiting, next threads will, but we can just keep going
        // there is a slight possibility that we can 'jump the queue'
        // if sleep() is called at **just** the right time...
        return;
    }

    // here we know that some other thread is active....
    // Put me in the queue.
    waiting.add(me);
    try {
        // Block while not first in queue or we're blocked
        // wait till we are at the front of the queue and we are also
        // not blocked by anything. If we are blocked, then park.
        // If not, we immediately block the next front-of-queue as well.
        while (waiting.peek() != me || !blocked.compareAndSet(false, true)) {
            LockSupport.park(this);
        }
    } finally {
       // Take me from the queue.
       Thread removed;
       while ((removed = waiting.remove()) != me) {
           // Put it back! It wasn't me!
           waiting.add(removed);
       }
    }
}

I think you may have a problem with initial state, and spurious wake-ups.... Consider the following

You have multiple instances of a Runnable (ta and tb for thread A and thread B), each of them does blockingqueue.sleep(). The expectation is that they will be woken up in turn when the queue's wakup() method is called (wake up both ta and tb by calling wakeup() twice).

So, both threads are asleep, the queue contains [ta, tb] and the atomic boolean blocked is false (the


This probably makes integration and debugging harder:

if ($_GET['api']!=$apiKey) {
   header('HTTP/1.0 404 Not Found');
   die();
}

The error message is misleading, if someone use an older or wrong API key they probably will spend some time searching the error in a wrong place since it indicates that the URL is wrong, not the key. 403 Forbidden would be more convenient here.
This should be in a configuration file, it might change more often than the code itself:

$apiKey='foobar123';

This generates a random number:

$k=rand(1,10);

Documentation of mt_rand says the following:

  mt_rand — Generate a better random value

So I guess using mt_rand would we better. Furthermore, the linked page contains another interesting thing:

  [...]

  Caution

  This function does not generate cryptographically secure values,
  and should not be used for cryptographic purposes. If you need a
  cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

It really depends on the application and the sensitivity of your data which is more appropriate.
This usually referred as one-time password:

  one-use passwords

This check could be at the beginning of the script:

if (!isset($_POST['ip'],$_POST['ip'])) {echo 'error'; die();}

It's unnecessary to create an one-time password if the ip is empty.

Additionally, I guess the following is the same:

if (!isset($_POST['ip'])) {echo 'error'; die();}

You could eliminate the comment here with better variable naming:

$ile=12; //char number

Just rename it to $passwordLength.

See also: Clean Code by Robert C. Martin, Bad Comments, p67: Don’t Use a Comment When You Can Use a Function or a Variable
Two typos:

$adres should be $address
$dane to $done

I'd rename $sessi to a descriptive name. What does this variable store, what's its purpose? Put that into the name.
I'd change log to something more descriptive here:

$_SESSION[$sessi]="log";

logged_in would be easier to understand since it describes a state not an action (like log).


First of all I'd make code in Application_BeginRequest little bit more self-explicative:

if (!IsAjaxRequest())
    ExecuteAllRunOnEachRequestHandlers();

You have to introduce two small utility functions but it will make the intent clear when reading Application_BeginRequest (which may grow over time) without going in the details.

private bool IsAjaxRequest()
    => new HttpRequestWrapper(Request).IsAjaxRequest();

private void ExecuteAllRunOnEachRequestHandlers()
{
    foreach (var task in GetAllHandlers<IRunOnEachRequest>())
        task.Execute();

    IEnumerable<T> GetAllHandlers<T>()
        => ApplicationObjectFactory.Container.GetAllInstances<T>();
}

It may happen that you need to ignore other types of requests, in this case simply change IsAjaxRequest() to IsPageVisit() (or whatever else expresses the concept you want to capture) and remove the negation.

In Add(string, string) you always throw ArgumentNullException but which parameter is wrong is an important information that is lost. Also to be String.Empty and to be null are different things:

if (locationId == null)
    throw new ArgumentNullException(nameof(locationId));

if (String.IsNullOrWhiteSpace(locationId))
    throw new ArgumentException("...", nameof(locationId));

if (browserName == null)
    throw new ArgumentNullException(nameof(browserName));

if (String.IsNullOrWhiteSpace(browserName))
    throw new ArgumentException("...", nameof(browserName));

Vertical space is free, do not pack your code in one line, it hurts readability.

return Add(new AddVisitLogViewModel
{
     BrowserName = browserName,
     LocationIP = locationId.ToLower()
});

In Add(AddVisitLogViewModel) you may apply same principles:

public bool Add(AddVisitLogViewModel visitorLogViewModel)
{
    if (visitorLogViewModel == null)
        throw new  ArgumentNullException(nameof(visitorLog));

    if (HasVisistedToday(visitorLogViewModel)
        return false;

    AddItem(Mapper.Map<VisitorLog>(visitorLogViewModel));

    return true;
}

Where HasVisitedToday() is your actual code with a given name to quickly understand what it does (and probably to match an entry in your specifications).

Note the use of nameof() to avoid string constants.

Side note: if Add(AddVisitLogViewModel) isn't invoked outside your assembly (its container class is internal) then you might want to replace parameters validation with assertions:

Debug.Assert(visitorLogViewModel != null);


Printing lines of "*" of various lengths

I don't consider myself an expert when it comes to the internals of .NET's garbage collector, but as far as I understand:

Write("*") benefits from string interning, so there should be little to no GC overhead (other than what Write does internally, of course). However, Write has to be called for every single character, and that call overhead makes it (significantly) slower.
The WriteLine variant does allocate strings (among other things), so the GC will have to run more often. Whether that has any significant impact on performance is something you'll have to measure, but it's normally not something you need to worry about.
new string('*', numberOfTimes) is more efficient (both in terms of speed and in terms of allocations) than string.Concat(Enumerable.Repeat("*", numberOfTimes)).
You may run into different kinds of issues if you allocate a lot of very large objects (larger than 85.000 bytes), due to how the Large Object Heap works. But that's probably not relevant in this case.

Note that new .NET releases occasionally contain GC improvements, so while the general principles are probably fairly static, implementation details will change over time.


Functional Implementation of Co-prime pairs in array

How is my choice of variable names?

In general you used snake case for the function names which is more a ruby-style.

Additionally the function co_prime_pairs let me acept that it return pairs of co-primes. However it returns a number of co-pairs inside an array.

The variable co_primes is declared globally.

co_prime_pairs

This function is not a pure function internally because .forEach(y => co_primes.push([x, y])) modifies co_primes.
I rewrite the function and spit the logic into:

build pairs
filter the co primes
return the length

The functions:

const filterCoPrimes = xss =>
    xss.filter(xs => isCoPrime(xs[0], xs[1]))

const buildPair = x => y =>
    [x, y]

const buildPairs = (xs, pairs) =>
    xs.length === 0 || xs.length === 1
        ? pairs
        : buildPairs(
            xs.slice(1),
            pairs.concat(xs.map(buildPair(xs[0])))
        )

The chain:

const co_prime_pairs = xs =>
    filterCoPrimes(buildPairs(xs, [])).length

If we use pipe as a kind of function composition it can be rewritten to:

const co_prime_pairs = pipe(
    buildPairs([]),
    filterCoPrimes,
    length
)

Full working Example

function calls:

const gcd = (a, b) =>
  (b != 0) ? gcd(b, a % b) : a

const isCoPrime = (a, b) =>
  gcd(a, b) === 1

const filterCoPrimes = xss =>
  xss.filter(xs => isCoPrime(xs[0], xs[1]))

const buildPair = x => y =>
  [x, y]

const buildPairs = (xs, pairs) =>
  xs.length === 0 || xs.length === 1
      ? pairs
      : buildPairs(
          xs.slice(1),
          pairs.concat(xs.map(buildPair(xs[0])))
      )

const co_prime_pairs = xs =>
  filterCoPrimes(buildPairs(xs, [])).length

console.log(co_prime_pairs([4, 8, 3, 9]))

with pipe:

const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)))

const filter = fn => xs =>
    xs.filter(fn)

const map = fn => xs =>
    xs.map(fn)

const length = xs =>
    xs.length

const gcd = (a, b) =>
    (b != 0) ? gcd(b, a % b) : a

const isCoPrime = (a, b) =>
    gcd(a, b) === 1

const filterCoPrimes = xss =>
    xss.filter(xs => isCoPrime(xs[0], xs[1]))

const buildPair = x => y =>
    [x, y]

const buildPairs = pairs => xs =>
    xs.length === 0 || xs.length === 1
        ? pairs
        : buildPairs
            ( pairs.concat(xs.map(buildPair(xs[0]))) )
            ( xs.slice(1) )

const co_prime_pairs = pipe(
    buildPairs([]),
    filterCoPrimes,
    length
)

console.log(co_prime_pairs ([4, 8, 3, 9]))


Is this routine for determining the epsilon of a Double 100% valid?

a != double.NegativeInfinity && a != double.PositiveInfinity

This could be simplified to just double.IsInfinity(a). Though as far as I know, it is correct. I was worried that there may be more values representing infinity, like there are for NaN, but that doesn't seem to be the case.

Otherwise, your method seems to work to me in all edge cases, including +/-0, double.MaxValue and double.Epsilon (though you should write unit tests for these just in case). In the case of +/-0 and TowardsZero, D will become NaN, so your method returns null, which I think is correct behavior.


First of all your variable IPAddress is misnamed. It sounds as if it contained a single IP address, but in fact it contains a list of multiple triples, where each one does not only contain an IP address, but also the corresponding broadcast address and netmask. You should probably call it something like IPTriples.

If you look at your code it's basically doing three things:

Filtering out localhost
Replacing each ip address with a string representation
Concatenating the thus created list of strings, separating them with spaces.

For each of these 3 steps there's already an erlang function, which can be used to do it:

lists:filter which takes a predicate and a list and returns a list only containing elements that match this predicate.
lists:map which takes a function and a list and returns a list containing the result of the function for each element.
string:join which takes a list of strings and a separator and returns a string with each item in the list separated by the separator.

Usually it it is good style to reuse existing functionality as much as possible instead of reimplementing it. So using these functions, your get_ip_address_string can be rewritten to something like this:

get_ip_address_string() ->
    {ok, IPTriples} = inet:getif(),
    FilteredIPTriples = lists:filter(fun is_not_localhost/1), IPTriples),
    IPAddresses = lists:map(fun ip_triple_to_string/1, FilteredIPTriples),
    string:join(IPAddresses, " ").

is_not_localhost({{127,0,0,1}, _Broadcast, _Mask}) -> false;
is_not_localhost({_IP, _Broadcast, _Mask})         -> true.

ip_triple_to_string({{Oct1, Oct2, Oct3, Oct4}, _Broadcast, _Mask}) ->
    io_lib:format("~b.~b.~b.~b", [Oct1, Oct2, Oct3, Oct4]).

Note that this has also the benefit that the logic for filtering out localhost, the logic for turning the IP addresses into strings and the logic for building the result string from that are now no longer intertwined, which should make the code more manageable.


There's a potential failure. If a thread invokes startManager() and then another thread immediately invokes stopManager(), stopManager() could see managerFuture as null and do nothing before startManager() gets a chance to populate it. The end result would be as if stopManager() was never called.

There's no reason for convert() to call startManager() if the manager gets started on application start.

Don't ignore InterruptedException. At the very least call Thread.currentThread().interrupt(). There are many resources out there on how to correctly handle InterruptedException, including on StackOverflow.

I also question the premise that the manager needs to start up on another thread. You should only bother if this is client-side code and this is a demonstrated bottleneck on startup.

Updated Answer

It will, but synchronized is a blunt instrument. It usually locks for longer than you need, and it's a lock on the object itself. If somebody else used your class as a lock, none of your synchronized methods could run until it was released. If you insist on going this route, you should use a private static final RentrantLock and minimize the scope to what you really need to be locked.
No, it shouldn't, but it doesn't do anything. If you call startManager() on startup, then the init thread is already running. If convert() also calls it, convert() will wait for the init thread to release its lock, then find out that it's already been initialized. OR you can do lazy-load of the manager in convert(), but then you have to wait for it to spin up the first time, which doesn't seem optimal if it takes 5 seconds.
Ok.
My point is that introducing this logic to save yourself 5 seconds on application start-up in dev is a bad tradeoff. Performance tuning is fragile and usually difficult to understand. Don't do it unless you need to. Junior programmers will get confused and muck it up by accident.
I don't think you need a reference to the thread. You have the Future .. that's what you care about. The only operation you want to perform on the thread after you start it is to interrupt it, which you can do from the future. If you need to hold onto the thread for some reason, by all means do so, but if you don't, there's no point in keeping a pointer to it.


I note that you're restricting your types T to those that are IComparable, that is, those that implement CompareTo. A more general solution would allow the caller to specify their own IComparer which may be that type's CompareTo or may be something else entirely.

Also see https://stackoverflow.com/questions/14336416/using-icomparer-for-sorting


The way you keep track of lists which you are currently exploring is a bit inefficient. You basically have a stack which contains the first argument of the function for each recursive call. This exact information is also stored on the execution stack of the Python interpreter, so it's duplicated.

A more efficient way would be to abandon recursion and use a cycle instead, since you are already using a stack. That way, you will also save some more space by not duplicating the constant (non-changing) arguments f and seen on the execution stack.

Another, even more significant way to improve efficiency is by observing that the check if lst[idx] not in seen takes linear time, although this can be done in constant time.

1. Removing recursion

We can start with the existing stack of lists and extend it as necessary. Since we are basically doing a dept-first search, upon descent to the deeper level we need to remember the list which we are currently iterating over, as well as the position within that list (so we can later return and continue where we left off). This can be done for example by having two lists, one containing the lists and the other one containing the positions. Or we can have just one list containing 2-tuples of the form (list, position).

2. Faster cyclic reference detection

Instead of searching through the stack, item by item, we can use a set as you suggested in a comment. This will allow us to detect cyclic references in constant time and the whole issue will be settled.

An even better approach would be to combine the position-tracking with fast membership checking: we could have a list of lists (the stack), and a dictionary mapping each list to our position within that list. Then a list will be used as a key in the dictionary if and only if it is in the stack. Note that adding, updating and deleting items in a hashed dictionary are all essentially constant time operations, and so is checking whether a key is present. So we achieve constant time cycle detection, much like we would with a set, but in a more elegant way.

One "problem" here may be that if we have the same list in the stack twice, with two different positions, which position do we put in the dictionary? Or can we somehow put both of them there? The answer is, we don't care, because this will never happen. Since we don't want to visit the same list twice on our path down the tree, the stack will never contain the same list twice. Now the only problem is that Python doesn't allow us to use list objects as keys in dict.

3. Using lists as keys in a dictionary

Since list is not a hashable type, it cannot be used as a key in dict (which is a hashed dictionary). However, the solution is quite simple: we use id(lst) instead of the lst itself as the key. We can do this, since we only care about identity, not equality. As a side note, this is another case in which your program behaves incorrectly. It compares lists with the items in seen based on equality, not identity: if lst[idx] not in seen: …. Consider following code:

>>> a = []
>>> a.append(a)
>>> b = [a]
>>> a == b
True
>>> id(a) == id(b)
False
>>> a in [b]
True

What should happen if you call rTraverse(b)? I suppose you would want to traverse both a and b.

Refactored code

The code contains a (very basic) implementation of a custom data structure which facilitates the above-proposed approach. This data structure is then employed in the modified traverse function.

class CustomStack(list):
  """
  Our custom data structure to facilitate position-tracking
  and provide constant time membership checking for cycle detection.

  This data structure serves as the stack, hence inherits from `list`.
  It has an `item_pos` attribute which serves as the dictionary.
  """

  def __init__(self, *args, **kwargs):
    super().__init__((item for item, pos in args), **kwargs)
    self.item_pos = {id(item): pos for item, pos in args}

  def append(self, item, pos):
    if item not in self:
      super().append(item)
      self.item_pos[id(item)] = pos

  def pop(self):
    del self.item_pos[id(self.top)]
    return super().pop()

  def __contains__(self, item):
    return id(item) in self.item_pos

  def __getitem__(self, idx):
    item = super().__getitem__(idx)
    pos = self.item_pos[id(item)]
    return item, pos

  @property
  def top(self):
    return super().__getitem__(-1)

  def setpos(self, pos):
    """
    This functions allows us to update the saved position within the list
    which is being currently explored (= is last in the stack).
    """
    self.item_pos[id(self.top)] = pos

def traverse(lst, f = lambda x: x):

  stk = CustomStack((lst, 0))  # initial position in the list is 0

  while stk:
    curr_list, curr_pos = stk[-1]  # don't pop the top of the stack yet

    for idx in range(curr_pos, len(curr_list)):  # continue from the saved position

      item = curr_list[idx]

      if isinstance(item, list) and item not in stk:
        stk.setpos(idx+1)    # update the current position to restore it later
        stk.append(item, 0)  # push the new list onto the stack
        break  # we are going depth-first into the new, deeper list
      else:
        curr_list[idx] = f(item)

    else:
      # we did not break out of the `for` loop. that means we're done
      # with this list and we are returning to the previous level.
      stk.pop()

Recursive version

Since the code got a bit too long for such a simple task, we can try going back to using recursion, and use a set as you proposed. Similarly to the case with a dictionary, we have to use id(lst) instead of lst, because items in a set are hashed. Considering AJNeufeld's remarks on thread and exception safety, we can use a dummy default value for the seen parameter, and if we see that seen has this dummy value (as opposed to a "real" value, eg. a set instance), then we create a set instance as a local variable on the function's stack frame. Upon recursively calling the function, we pass a reference to this local variable, therefore no thread safety or exception safety issues ensue.

def traverse_simple(lst, f=lambda x: x, seen=None):

  if seen is None:
    seen = set()

  seen.add(id(lst))

  for i, item in enumerate(lst):

    if isinstance(item, list) and id(item) not in seen:
      traverse_simple(item, f, seen)
    else:
      lst[i] = f(item)

  seen.remove(id(lst))

By using id(lst), we are able to not only use a set and therefore detect cyclic references in constant time; we are also able to compare lists by identity instead of equality. This means the function does not fail on inputs on which your original function does fail, such as this:

>>> a = []
>>> b = [a]
>>> a.append(b)


Your code is reasonable, but there some small tweaks you could do.

Check out itertools, which adds some nice extensions to iterators. Specifically, it allows joining an iterator, instead of needing to collect to an intermediate Vec.
I'm unclear why you would use the Debug formatter for an integer.
Tuples have a space after the comma, between elements (see in the closure).
Your example might just be overly minimized, but there's no reason to use a Vec here, an array would suffice.

extern crate itertools;

use itertools::Itertools;

fn main() {
    let v = [(0, 0), (1, 1), (2, 2)];

    let strings = v.iter()
        .enumerate()
        .map(|(i, &(a, b))| format!("{}: ({}, {})", i, a, b))
        .join("\n");

    println!("{}", strings);
}

If you are OK changing the semantics a little, you can move the newline into the format! and collect into a String:

fn main() {
    let v = [(0, 0), (1, 1), (2, 2)];

    let strings: String = v.iter()
        .enumerate()
        .map(|(i, &(a, b))| format!("{}: ({}, {})\n", i, a, b))
        .collect();

    println!("{}", strings);
}

Note that there is now a trailing newline on the string.

The "unfortunate" thing about these solutions is that they all require intermediate string allocations - the result of format!.

There's a less-common method in itertools to deal with this: format_with:

extern crate itertools;

use itertools::Itertools;

fn main() {
    let v = [(0, 0), (1, 1), (2, 2)];

    let formatter = v.iter()
        .enumerate()
        .format_with("\n", |(i, &(a, b)), fmt| {
            fmt(&format_args!("{}: ({}, {})", i, a, b))
        });

    let strings = format!("{}", formatter);

    println!("{}", strings);
}

I wouldn't worry about this until you know you need that extra bit of performance ^_^


I would expect a function that has a "predicate" name (is_x()) to return a boolean value rather than a string.  The boolean is much more useful to the caller.
We should add a main-guard to top-level code, so the file could be useful as a module.
Consider adding some unit tests.  A convenient way to do this is using the doctest module, which finds tests in the function's docstring; any line beginning with >>> is a test, and is immediately followed by the expected result.
Building on the version shown by C.Nivs, that would give this improved version:
def is_palindrome(x):
    '''
    True if the letters of x are the same when
    reversed, ignoring differences of case.
    >>> is_palindrome('')
    True
    >>> is_palindrome('a')
    True
    >>> is_palindrome('a0')
    False
    >>> is_palindrome('ab')
    False
    >>> is_palindrome('ab a')
    False
    >>> is_palindrome('Aba')
    True
    >>> is_palindrome('Àbà')
    True
    '''
    x = x.lower()
    # Alternative (letters only):
    #     x = ''.join(filter(str.isalpha, x.lower()))
    # Alternative (letters and digits only):
    #     x = ''.join(filter(str.isalnum x.lower()))
    return x[::-1] == x

if __name__ == '__main__':
    import sys
    for string in sys.argv[1:]:
        # check each command-line argument
        message = 'is a palindrome' if is_palindrome(string) else 'is not a palindrome'
        print(f'{string} {message}')
    else:
        # no arguments, so run self-test
        import doctest
        doctest.testmod()

It may well make sense to separate the pre-processing from the palindrome checking, so that is_palindrome() simply returns x[::-1] == x, and the caller is responsible for deciding which characters are significant.  We could call it with a specific canonicalisation:
is_palindrome(string.lower())

More advanced would be to pass a normalisation function and/or a character filter, as optional arguments:
def is_palindrome(s, normalise=None, char_filter=None):
    '''
    True if the letters of x are the same when
    reversed, ignoring differences of case.
    >>> is_palindrome('')
    True
    >>> is_palindrome('a')
    True
    >>> is_palindrome('a0')
    False
    >>> is_palindrome('a0', char_filter=str.isalpha)
    True
    >>> is_palindrome('ab')
    False
    >>> is_palindrome('ab a')
    False
    >>> is_palindrome('Aba')
    False
    >>> is_palindrome('Aba', normalise=str.lower)
    True
    >>> is_palindrome('Àbà', normalise=str.lower)
    True
    '''
    if normalise:
        s = normalise(s)
    if char_filter:
        s = ''.join(filter(char_filter, s))
    return s == ''.join(reversed(s))

Usage of these optional arguments should be apparent from the extra tests I've added.

Bug
Whether we use [::-1] or reversed() to reverse the input string, we have a bug when the input contains characters that are formed using combining accents, as demonstrated by these additional tests:
>>> is_palindrome("o̅o") # o+overline, o
False
>>> is_palindrome("o̅o̅") # o+overline, o+overline
True

Both of these fail, because we reverse the string by treating each Unicode character independently, rather than considering them as (possibly multi-character) letters.  To fix that, we'll need to find or create a combining-character-aware function to reverse a string - I'm not aware of such a thing in the Python standard library.


Yes, it is safe. No, it is not a good idea.

Don't mix application logic and configuration with the database, the database is used for permanent storage of data.

Use a file (json, ini, xml, whatever) which is named the same but has different contents in production/dev environments. Then, it's as simple as:

$config = json_decode(file_get_contents('config.json')); //I'm assuming JSON here

Also, please don't globalize configuration. Pass whichever config option you need (just that config option, not the whole configuration array) into whatever function/object that needs it.


Some style points first:

StringTokeniser is discouraged see here
variables are lowerCamelCase in java convention. Try to avoid _ and don't start with a capital letter.
Longer meaningful names are a lot better than short (especially 1 letter) variable names. What exactly is that W? A variable called weights is so much easier to understand. I'll make an exception for n for being part of the assignment and i and j as loop variables for beïng know as loop variables.
java coding conventions say to ALWAYS use braces after each if/for/...
(The only exception I make is if you put the next statement on the same line as the if, for an example take a look at an auto generated equals implementation).
the opening braces usually go on the same line, not the next line, but it's a good thing that you're consistent.

Here's a cleaned up version of your code. It should still work exactly the same:

Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.nextLine(); // needed to proces the end of the first input line.
long[] weights = new long[n];
long[] cumulativeSum = new long[n];
int[] pushedby = new int[n];
long sum = 0;

for (int i = 0; i < n; i++) {
    weights[i] = input.nextLong();
    sum += weights[i];
    cumulativeSum[i] = sum;
}

for (int i = 0; i < n; i++) {
    for(int j = n-1; j >= 0; j--){
        if (j > i) {
            if (weights[j] >= (cumulativeSum[j] - cumulativeSum[i] - weights[j])) {
                pushedby[i]++;
            }
        }
        if (j < i) {
            if (weights[j] >= (cumulativeSum[i] - cumulativeSum[j] - weights[i])) {
                pushedby[i]++;
            }
        }
    }
}

for (int i = 0; i < n; i++) {
    System.out.print(pushedby[i] + " ");
}

You had an interesting idea with storing the sumtill but does it really help you? After all, you're still checking each possible pair.

What you could do instead is for each person in the list, walk the list to the left and to the right adding up the total weight up till that point and check if you can still push that guy. If you can, increment the pushedBy counter for that other guy. As soon as you can't you stop going further down the list.

Putting that into code looks something like this:

Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.nextLine(); // needed to proces the end of the first input line.
long[] weights = new long[n];
int[] pushedby = new int[n];
long sum = 0;

for (int i = 0; i < n; i++) {
    weights[i] = input.nextLong();
    sum += weights[i];
}

for (int currentPerson = 0; currentPerson < n; currentPerson++) {
    //check left of the current person as long as the current person can push them all.
    long totalWeight = -weights[currentPerson];
    for (int i = currentPerson - 1; i >= 0; i--) {
        totalWeight += weights[i];
        if (totalWeight > 0) {
            break; // can no longer push them all
        }
        pushedby[i]++;
    }

    //same for right of the current person
    totalWeight = -weights[currentPerson];
    for (int i = currentPerson + 1; i < n; i++) {
        totalWeight += weights[i];
        if (totalWeight > 0) {
            break;
        }
        pushedby[i]++;
    }

}

for (int i = 0; i < n; i++) {
    System.out.print(pushedby[i] + " ");
}
System.out.println(); //actually finish the line

I did notice that this gives a different result than yours. You may want to check which result is the correct solution to the problem.


Simplifying Counter of Checked Checkboxes

The formula can be simplified:

for the first four checkboxes, if any of the items are checked, multiple the number checked by 0.5 and add 0.5
Then add 1 if the fifth checkbox is checked.

So it might be simpler to just have a reference to the first for checkboxes and then the 5th checkbox. For the first for, one can use document.getElementsByName('foo') to get a NodeList, and then put those nodes in an array using Array.from() and use Array.slice() to get the first four checkboxes.

var firstFourBars = Array.from(document.getElementsByName('foo')).slice(0, 4);

For the record - I did consider using a CSS selector identical to that of the answer by @200_success (i.e. input[name=foo]:not(#bar5):checked) but because the NodeList returned by document.querySelectorAll() is not live, that DOM query would need to be run each time. See point #3 for more details.
Event delegation can be used to avoid adding a click handler to each checkbox in the HTML. The code below utilizes document.addEventListener() to call the calculateTotalCost whenever a click occurs. Because of this change, that function receives a reference to the event as the first argument. This allows changes based on any click anywhere but conditional logic dependent on event.target could be added.
DOM references can be stored in variables at the start of the script, so as to avoid multiple lookups (e.g. var printCost)
One other simplification:

var totalCost = 0;
var printCost = document.getElementById('calculatedCost');
totalCost = 100 * checkboxCount();

There is little point in setting totalCost to 0 and then assigning it 100 * checkboxCount(). Just assign it the latter product:

var totalCost = 100 * checkboxCount();

document.addEventListener('DOMContentLoaded', function() { //Wait for DOM to be ready
  //cache DOM references
  var printCost = document.getElementById('calculatedCost');
  var firstFourBars = Array.from(document.getElementsByName('foo')).slice(0, 4);
  var bar5 = document.forms["calculator"].elements["bar5"];

  document.body.addEventListener('click', calculateTotalCost);
  // helper function for filter
  function isChecked(checkbox) {
    return checkbox.checked;
  }

  function checkboxCount() {
    var count = firstFourBars.filter(isChecked).length;
    if (count) {
      count = count * 0.5 + 0.5;
    }
    if (bar5.checked) {
      count += 1;
    }
    return count;
  }

  function calculateTotalCost(event) {
    //could conditionally execute based on event.target
    var totalCost = 100 * checkboxCount();
    printCost.innerHTML = "$" + totalCost;
  }

});
<form id="calculator">

  <fieldset>
    <input type="checkbox" name="foo" id="bar1">Bar 1
    <input type="checkbox" name="foo" id="bar2">Bar 2
    <input type="checkbox" name="foo" id="bar3">Bar 3
    <input type="checkbox" name="foo" id="bar4">Bar 4
    <input type="checkbox" name="foo" id="bar5">Bar 5
  </fieldset>

</form>

Edit

I forgot to mention that in the modified code above, it waits for the DOM to be ready before before querying it (notice the first line document.addEventListener('DOMContentLoaded', function() { //Wait for DOM to be ready). Not only does it prevent attempts to access DOM elements before they exist, but the variables are scoped to the callback function instead of the global namespace.


If you want to clean up a bit the method, then I think that you should try another, more object oriented way of writing the method (currently the method is written procedurally).

Implementation 1

First lets create few interfaces, which will represent the Limit and the Offset:

public interface Offset {

    public String getOffset();

}

public interface Limit {

    public String getLimit();

}

Next we will need an implementations of this interfaces (I supposed that you are using MySQL as database, since its shorter syntax for limitation and offset is the same):

public MySQLOffset implements Offset {

    private final int offset;

    public MySQLOffset(int offset) {
        this.offset = offset;
    }

    @Override
    public String getOffset() {
        if (offset < 0) {
            throw IllegalArgumentException("Offset couldn't be a negative number.")
        }

        return offset + ",";
    }
}

public MySQLLimit implements Limit {

    private final MySQLOffset offset;
    private final int limit;

    public MySQLLimit(MySQLOffset offset, int limit) {
        this.offset = offset;
        this.limit = limit;
    }

    @Override
    public String getLimit() {
        if (limit <= 0) {
            throw IllegalArgumentException("Limit should be a strictly positive number.");
        }

        return String.format("LIMIT %s %s", offset.getOffset(), limit);
    }
}

Finally we will need one more interface, which will serve us as a glue between this two interfaces (I called it Pagination, since most of the times, offset and limit is used in combination for pagination of some API):

public interface Pagination {

    public String getPagination();

}

public MySQLPagination {

    private final MySQLLimit limit;
    private final MySQLOffset offset;

    public MySQLPagination(MySQLLimit limit) {
        this.limit = limit;
        this.offset = offset;
    }

    public String getPagination() {
        return limit.getLimit();
    }
}

Now, suppose that we have some data access object called PersonDAO, which should retrieve all the persons in a given range (bounded by limit and offset), then the code would look like that (I`ve change the name of getPersons method to retrievePersons, since we actually retrieves the person entries from the database, rather than getting them from some POJO):

.. code ommited ..

    PersonDAO.retrievePersons(new MySQLPagination(new MySQLLimit(new MySQLOffset(offset), limit)));

.. code ommited ..

public List<Person> retrievePersons(Pagination pagination) {
    return jdbcTemplate.query("SELECT * FROM `Person` " + pagination.getPagination());
}

Implementation 2

Suppose that you want to you use the long syntax of limitation and offset. Then the code will look like this:

public interface Offset {

    public String getOffset();

}

public interface Limit {

    public String getLimit();

}

public MySQLOffset implements Offset {

    private final int offset;

    public MySQLOffset(int offset) {
        this.offset = offset;
    }

    @Override
    public String getOffset() {
        if (offset < 0) {
            throw IllegalArgumentException("Offset couldn't be a negative number.")
        }

        return " OFFSET " + offset;
    }
}

public MySQLLimit implements Limit {

    private final int limit;

    public MySQLLimit(int limit) {
        this.limit = limit;
    }

    @Override
    public String getLimit() {
        if (limit <= 0) {
            throw IllegalArgumentException("Limit should be a strictly positive number.");
        }

        return "LIMIT " + limit;
    }
}

public interface Pagination {

    public String getPagination();

}

public MySQLPagination {

    private final MySQLLimit limit;
    private final MySQLOffset offset;

    public MySQLPagination(MySQLLimit limit, MySQLOffset offset) {
        this.limit = limit;
        this.offset = offset;
    }

    public String getPagination() {
        return limit.getLimit() + offset.getOffset();
    }
}

.. code ommited ..

    PersonDAO.retrievePersons(new MySQLPagination(new MySQLLimit(limit), new MySQLOffset(offset)));

.. code ommited ..

public List<Person> retrievePersons(Pagination pagination) {
    return jdbcTemplate.query("SELECT * FROM `Person` " + pagination.getPagination());
}

If you want you could also move the creation of the Pagination object into some factory method like this one:

public Pagination createPagination(int limit, int offset) {
   return new MySQLPagination(new MySQLLimit(limit), new MySQLOffset(offset))
}

Which also comes with some benefits, like more testable code etc.

Benefits of this implementation:

Implemented in OOP way
The validation of the input parameters is moved into the relevant classes, so the single responsibility principle is respected.
Easier to change the implementation
Easier for testing (suppose that you use one database for production and one for testing and they have different syntaxis for the limitation and the offset, then you should only mock the createPagination method and everything will work)
There is no if/else (or ternary operator) clauses in the getPersons method
Also now the getPersons method doesn't know how the limit and the offset of the query is constructed, which is the right way, since it`s work is to retrieve the entries, not to know how to construct them (which means little responsibilities for getPersons method)


Displaying subcategories of subcategories

SQL Injection

Yes, your code is safe against SQL Injection. Make sure to use prepared statements when fetching things from the database as well, even in internal application services without user input.

Others

Well, I'm guessing this is a subset of the code in Displaying categories and subcategories in php having different tables, so my review there still stands.


public class CircularLinkedlistinsert {

Class names should have the first letter of each word capitalized.  I'd also change the name to remove the activity and just describe the object.  i.e., CircularLinkedList.  The method names will describe whatever action is taken.

private static class Node {
    int element;
    Node next;

While it doesn't matter too much since this is a private nested class, the element and next fields should in theory be private as well and accessed via getElement() / getNext() and setElement() / setNext() methods.  This promotes encapsulation and good object-oriented practices.  (This is a purist observation, and what you've done works fine for your model.)

public void insertNodeInCircularLL(int element)

Again, I'd rename this method for style points.  Since the entire class is a CircularLinkedList, we can just call this insertNode(), or even something as simple as add() or put().

The problem with the rest of the implementation, to me, is that you are using the element field both as the content of the Node and its position in the linked list.  That's a problem.  What if I pass in an int to the method that isn't the next logical number in the sequence?  What if I pass in something like -1?

It looks like, based on this if statement (((current.element <= element)  && (current.next.element >= element))), that you're trying to facilitate inserting a node in between two other nodes.  I think there might be a more sane way to do it, however even if you want to continue with this approach and allow the client code to pass in an index directly, you will need to do some sanity checking of the input before processing.

I think you need to have the element field be something managed internally, with only the content of the node passed in to the insert method.  This is more of a logic error in your implementation than an issue with your coding style or practices, though.

Two more advanced notes from this:

If you do end up generating the IDs yourself, you ought to look into synchronization to avoid problems with multithreading.
This CircularLinkedList can only accept nodes which hold int information.  You could change the element field to be a true id, and then use Generics to make your implementation truly powerful.


Avoid indexing the keys in a Javascript array

You don't need to label object fields 0 or 1. On each Tab, you could have a field columns which is an array, of arrays containing the feeds in the column as so:

const Tabs = [
  {
    groupName: "News"
    columns: [
      [
        {"url":"http://xkcd.com/rss.xml","type":"mixed","limit": 8},
        {"url":"http://xkcd.com/rss.xml","type":"photo","limit": 4}
      ],
      [
        {"url":"http://xkcd.com/rss.xml","type":"mixed","limit": 8},
        {"url":"http://xkcd.com/rss.xml","type":"mixed","limit": 8},
        {"url":"http://xkcd.com/rss.xml","type":"photo","limit": 4}
      ]
    ]
  },
  {
    groupName: "Comics",
    columns: [
      [
        {"url":"http://xkcd.com/rss.xml","type":"photo","limit": 8},
        {"url":"http://superphazed.tumblr.com/rss","type":"photo","limit": 8}
      ]
    ]
  }
];


Improving CSV filtering with Python using regex

The CSV file contains text in some text encoding, and should not be opened in binary mode.

You should construct one regular expression to find any of the forbidden words.  It appears that you intended to do a case-insensitive search, but didn't write the code that way.  When constructing the regex, you should escape the strings, in case they contain any regex metacharacters. You don't need .*, since re.search() will look for the pattern anywhere in the string, nor do you need capturing parentheses.

If your comment says 100, then your code should have 100 rather than 99.

I suggest doing a destructuring assignment title, view_count = row to make it clear what each column represents.

with open('video_2013-2016.csv') as f:
    forbidden = re.compile('|'.join(re.escape(w) for w in exclude_list), re.I)
    for row in csv.reader(f):
        # Only record videos with at least 100 views and none of the bad words
        title, view_count = row
        if int(view_count) >= 100 and not forbidden.search(title):
            data_set.append(row)


Instead of creating an empty list and appending the values to it, try using list comprehension.

so instead of

y_location = []
x_location = []
for each in range(-size, size+1):
    y_location.append(parabola(each, size))
    x_location.append(each)

try

y_location = [parabola(each,size) for each in range(-size,size+1)]
x_location = list(range(-size,size+1))

In general you can use a profiler to see which part of your code requires the largest amount of computing making it easier to improve the code.
https://docs.python.org/2/library/profile.html


Can I always use variable-length argument lists instead of arrays in argument types whenever is a choice?

so basically it is your choice :

with optional params you cannot enforce user to input the value, so user can leave giving any input and complier will not complain.

new Options().withColumns();

with list of string , you need to give at least one value , value can be null.

new Options().withColumns(null);

so it all depends upon your use case.In this case table will always have columns so passing a array of column will make sense.


You query HttpContext.Current.Request.Cookies.Get("lang") twice. Access it once and store it in a variable.
You will get a problem if in the future you have to support more than 9 languages. Instead of accessing the last char from langCookie you should Split() langCookie by = and take the second array element. You can then use [Enum].TryParse() to get the enum.
Some horizontal spacing (new lines) would help to easier read the code.

Your code could look like so

Public Function GetLangFromCookie() As Language

    Dim langCookie = HttpContext.Current.Request.Cookies.Get("lang")

    If langCookie Is Nothing Then
        Return Language.English
    Else
        Return GetLanguage(langCookie.Value)
    End If

End Function

Private Function GetLanguage(languageCookieValue As String) As Language

    Dim splittetCookieValue As String() = languageCookieValue.Split(New String() {"="}, StringSplitOptions.RemoveEmptyEntries)

    Dim languageIdentifier As String = splittetCookieValue.LastOrDefault()

    Dim foundLanguage As Language

    ' We don't care about the success of the TryParse() call
    [Enum].TryParse(Of Language)(languageIdentifier, foundLanguage)

    ' because foundLanguage will be 0 if it doesn't succeed and will be checked here
    Return If(foundLanguage = Language.Undefined, Language.English, foundLanguage)

End Function


I don't understand why :nth-child selector is even in play here.  It seems all you are wanting to do is add a class to an li with same index within its parent as what the content's index within it's parent is.

I might suggest something along these lines to achieve that:

// Cache jQuery collections somewhere in scope that `scroll()` inherits.
// This prevents you from having to continually re-query the DOM every time
// there is a scroll event.
var $mainContent = $('.section .main-content');
var $eventLi = $('.events-widget-menu li');

$(document).scroll(function () {
    $eventLi.removeClass('current');
    // find content elements in view
    var $currentElements = $mainContent.filter(function(index) {
        return isScrolledIntoView(this);
    });
    // apply class to LI with corresponding index
    $currentElements.each(function() {
        var index = $mainContent.index(this);
        $eventLi.eq(index).addClass('current');
    });
}

This solution is not hard-coded to X number of elements.


?? is well known operator in C#.  It doesn't confuse but reduce coding.

Both snippets have same meaning.

But if it is .NET 4.0 onwards, i would rather use Lazy<T>.

private Lazy<string> lazyStringField = new Lazy<string>(GetStringField);
protected string StringField
{
    get
    {
        return lazyStringField.Value;
    }
}


Counting first letter of title and printing letters from a to z

Fiddle is currently broken again, but you should do the count as early as possible  -> Inner instead of more expensive Outer join and less rows to join.

SELECT l.letter AS firstLetter
  -- return 0 for missing letters
  ,Coalesce(lc.cnt,0) AS itemCount
FROM letter AS l
LEFT OUTER JOIN
 ( -- count letters before join
   SELECT Left(i.Title,1) AS letter
     ,Count(*) AS cnt
   FROM item AS i -- no Outer Join needed
   JOIN item_tag AS it
     ON it.item_id = i.id
    AND it.tag_id = 1
   GROUP BY Left(i.Title,1)
 ) AS lc
ON lc.letter = l.letter


Change your column loop to use a reference.

for (const auto &c : column_vec)

Without the reference, a copy will be made of each vector.  This will involve a memory allocation.  Using the reference you avoid all that, which should save a good deal of time since each c will be a single element vector.

auto r can stay since r will be a double.

Combine this with using reserve on row_vector will eliminate all but one memory allocation.


I recommend splitting your model (the database operation) from your view (the localization of your message).

Depending if you prefer a return code or a exception flow your code could look like:

public function create()
{
    if($this->user_exists) return ""; //do you really want to show nothing?
    $error=UserModel::create($this->password,$salt,$this->username); // don't have to be static! It's up to you.
    if ($error==-1) return "User could not be created";  //could be a constant UserModel::ERROR_GENERAL
    if ($error==0) return "Username already exists"; //UserModel::ERROR_EXISTS
    return "User has been created";
}

Translating this to exception is up to the reader :)

Actually I even would prefer to give the $error code to my template and let it handle the localization:

public function create()
{
    if($this->user_exists) return "";
    $error=UserModel::create($this->password,$salt,$this->username);
    $view=new View("templatefile.php");
    $view->assign('error',$error);
    return $view->render();
}

//"templatefile.php"
<?if ($error==1):?>...
<?elseif ($error==0):?>...
<?else:?>...
<?endif?>


Finding integer lengths for a right triangle with a given perimeter

You can improve the performance with a bit of math. Rather than doing this in \$O(p^3)\$ you can do it in in \$O(p)\$.

First remove \$c\$ from the equation:

$$
a + b + c = p\\
c = p - a - b\\
a^2 + b^2 = c^2\\
a^2 + b^2 = (a + b - p)^2$$

After this you can expand the right hand side and simplify.

$$
a^2 + b^2 = (a + b - p)(a + b - p)\\
a^2 + b^2 = a^2 + b^2 + 2ab - 2ap - 2bp + p^2\\
2ab - 2ap - 2bp + p^2 = 0\\
a = \frac{2bp - p^2}{2b - 2p}\\
$$

Which in Python can be:

def _right_a(p):
    for b in range(1, p // 2):
        a = (2*b*p - p**2) / (2 * (b - p))
        if a % 1:
            continue
        a = int(a)
        yield a, b, p - a - b

def int_right_tri(p):
    return {tuple(sorted(i)) for i in _right_a(p)}


Function to trigger animation with mouse wheel events

This:

var delta;
if (event.wheelDelta) {
    delta = event.wheelDelta;
} else {
    delta = -1* event.deltaY;
}

could be simplified to:

var delta = event.wheelDelta ? event.wheelDelta : -event.deltaY;

or even more succinctly:

var delta = event.wheelDelta || - event.deltaY;

For the if/else:

if (slidenum > 0) {
    slide1.play()
} else if (slidenum < 1) {
    slide1.reverse()
}

I personally find your end points take me a while to understand because of the way they overlap. I would find it easier like this:

if (slidenum >= 1) {
    slide1.play()
} else if (slidenum < 1) {
    slide1.reverse()
}

Or without the else which is redundant in this case.

if (slidenum > 0) {
    slide1.play()
} else {
    slide1.reverse()
}


Better jQuery function argument with if-statement?

Without changing too much, here are some tips on improving your code.
Assumptions:

You're working in modern web browser.
left, up, down, right are defined else where.

1)
Define all the variables at the top. I'm not sure where the fucntions left, up, down, right are.
2)
Use a switch instead of multiple if else.
3)
Perform an operation to collection if multiple elements share the same functionality. Refer to resetValues()
4)
Try to make all the if conditions as small as possible. Refer to !key.length
Here's what I came up with.
Array.prototype.forEach = Array.prototype.forEach || function(fn, scope) {
    for(var i = 0, len = this.length; i < len; ++i) {
        fn.call(scope || this, this[i], i, this);
    }
};

var self = this,
    check_left, check_right, check_up, check_down,
    left_itv, right_itv, up_itv, down_itv;

var resetValues = function(){
    ["left_itv", "right_itv", "up_itv", "down_itv"].forEach(function(el){
        clearInterval( self[el] );
    });
    ["check_left", "check_right", "check_up", "check_down"].forEach(function(el){
        self[el] = true;
    });
};

resetValues();

function check_itv(key) {
    if (!key.length) {
        return;
    }
    resetValues();
    switch( key ){
        case "left":
            left_itv = setInterval(left, 100);
            check_left = false;
            break;
        case "right":
            right_itv = setInterval(right, 100);
            check_right = false;
            break;
        case "up":
            up_itv = setInterval(up, 100);
            check_up = false;
            break;
        case "down":
            down_itv = setInterval(down, 100);
            check_down = false;
    }
}

Alternatively, you could swap the global variables inside a singleton(namespace) that has a reset functions. But that add a bit of complexity.


Find GCD of two numbers without using multiplication, division or modulus operators

The code in general looks decent. There are some minor things in coding style that could be improved.

I would rename isAEven to aIsEven or aEven. A variable is a state, not a question.

The method in itself doesn't rely on any state of some object. It's a utility function. It would make more sense if it were static instead. If you plan to provide other similar utility functions you could write a specific class to group those. Similar to the Math class already available in java.

In this block:

    if(isAEven && isBEven){
        return gcd( a >> 1,  b >> 1) << 1;
    }
    if(isAEven && !isBEven){
        return gcd( a >> 1, b);
    }
    if(!isAEven && isBEven){
        return gcd(a, b >> 1);
    }

the checks for !isXEven are redundant. After the first if, you know that not both are even. Whether or not to remove this is your choice on which is more readable. Alternatively you could write it as:

    if(isAEven && isBEven){
        return gcd( a >> 1,  b >> 1) << 1;
    } else if(isAEven){
        return gcd( a >> 1, b);
    } else if(isBEven){
        return gcd(a, b >> 1);
    }

I added the else to make it explicit that these 3 actually belong together. Changing the order isn't allowed anymore after removing the !... check.

About the actual algorithm. it looks slightly different from what I've seen before. Doing a little searching on the internet I found out it's almost the same as this Binary GCD algorithm.

You're only missing 2 optimisations.

The first one is the obvious if(a == b) return a. When both are equal you don't need to calculate anything else. The biggest difference can be seen if a = b = 1<<30 (the biggest integer power of 2) where your algorithm takes about 32 recursive steps.

The other optimisation is a bit less obvious. The last 2 recursive calls in the code can also use a bitshift:

if(a <= b){
    return gcd(a, (b-a) >>1);
} else {
    return gcd(b, (a-b)>>1);
}

Because at  that point we know a (or b) is odd and b-a (or a-b) is even. We can skip a cycle to bitshift the new b immediatly.

Side note: you don't really need all the bitshifting if you're not interested in micro-optimisations for speed. The simplified version also works fast as is:

private static int gcd(int a, int b) {
    if (a == b) return a;
    if (a == 0) return b;
    if (b == 0) return a;

    if (a <= b) {
        return gcd(a, b - a);
    } else {
        return gcd(b, a - b);
    }
}


MeasureDistance. The way it is written, sometimes it measures the duration of the signal, sometimes the (desired) time for the echo to arrive (consider what happens if you enter the first while loop). Suggestion:

def MeasureDistance():
    StartTime = time.time()
    GPIO.output(GPIOTrigger, True)
    while GPIO.input(GPIOEcho) == 0:
        pass
    # Found the raising front
    StopTime = time.time()
    GPIO.output(GPIOTrigger, False)

Of course, if the echo arrives faster than the code executes (and Python is slow), you'd get the elapsed time 0. I suppose there's nothing you can do about that, other than resorting to interrupts. Also, you may want to put some safeguards (a timer maybe) in case the raising front never arrives.

main. I don't see the need to import subprocess in the middle of the code. Also, state variables tend to create an unmaintainable code. Suggestion:

    try:
        Distance = MeasureDistance()
        while True:
            while Distance > 10.0:
                Distance = MeasureDistance()
                wait(5)
            switch_on()
            while Distance < 10.0:
                Distance = MeasureDistance()
                wait(5)
            switch_off()
    except KeyboardInterrupt:

PS: a magic 34300 constant must go. Give it a nice symbolic name (yes we all know it has something to do with the speed of sound).

Update.
Usually in the situations like yours you may have a funny behaviour at the breaking distance. Due to random factors (like the code execution time, and many more others) the distance is measured with a certain error, and the switch will go on and off unpredictably. To deal with it, allow for a hysteresis:

            while Distance > breaking_distance - tolerance:
                Distance = MeasureDistance()
                wait(5)
            switch_on()
            while Distance < breaking_distance + tolerance:
                Distance = MeasureDistance()
                wait(5)
            switch_off()


What is the most memory efficient way to load big arrays into PHP script?

I thought about this again. My comments are still valid, so including it in a php file is the cheapest way to get the array into your system and without a shared memory you will not reduce the total memory usage.

But maybe you can optimize it at an higher level of abstraction. Assuming that you always only need some countries/settings/localization in your loaded page and never all, you could split this array into multiple files.

<?php
...
function countryCodeToName($key)
{
    if (isset($this->countries[$key])) return $this->countries[$key];
    $firstCharacter=$key[0]
    include "country_".$firstCharacter.".php"; //similar to your file above
    $this->countries=$this->countries + $cty_arr;
    //some handling if still missing
    //and return ...
}


If you want to work with graphs in Python, you should have a look at the excellent module networkx. It has (usually fast) implementations of the most common (and many not so common) operations on directed and undirected graphs.
Your case in particular, finding all simple paths (i.e. paths without repeating nodes) between two nodes, is already implemented:
import networkx as nx

g = nx.Graph()  # bi-directional edges. Use nx.DiGraph() if you want to explicitly specify directions
g.add_edges_from([("A", "B"), ("B", "C"), ("C", "D"), ("C", "E"), ("E", "A")])
g.add_edge("E", "D")  # can also add individual edges

for path in nx.all_simple_paths(g, source="A", target="B"):
    print(path)

# ['A', 'B']
# ['A', 'E', 'C', 'B']
# ['A', 'E', 'D', 'C', 'B']

If you want to associate data with each edge and get back only this data, this is also possible:
g = nx.Graph()  # bi-directional edges. Use nx.DiGraph() if you want to explicitly specify directions
g.add_edges_from([("A", "B", {"sku": "SEGMENT1"}),
                  ("B", "C", {"sku": "SEGMENT2"}),
                  ("C", "D", {"sku": "SEGMENT3"}),
                  ("C", "E", {"sku": "SEGMENT4"}),
                  ("E", "A", {"sku": "SEGMENT5"})])
g.add_edge("E", "D", sku="SEGMENT6")  # can also add individual edges

paths = nx.all_simple_paths(g, source="A", target="B")
for path in map(nx.utils.pairwise, paths):
    for edge in path:
        print(edge, g.edges[edge]["sku"])
    print()

# ('A', 'B') SEGMENT1
#
# ('A', 'E') SEGMENT5
# ('E', 'C') SEGMENT4
# ('C', 'B') SEGMENT2
#
# ('A', 'E') SEGMENT5
# ('E', 'D') SEGMENT6
# ('D', 'C') SEGMENT3
# ('C', 'B') SEGMENT2

It even allows you to easily visualize the graph:
import matplotlib.pyplot as plt

nx.draw(g, with_labels=True, node_color="white")
plt.show()

Or, more fancy:
pos = nx.spring_layout(g)
labels = dict(zip(g.edges, [g.edges[e]["sku"] for e in g.edges]))
nx.draw(g, with_labels=True, node_color="white", pos=pos)
nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=labels)
plt.show()


You can ask SQL Server to recommend the indexes that might improve performance of your query by selecting the query and clicking on this Display Estimated Execution Plan button on the taskbar (or simply Ctrl+L):

This will analyze the query and it will show you the query cost of the operations required to retrieve the data, and eventually propose which indexes might be useful.

Btw, using the joins (as on your 2nd example) should be more efficient indeed.


It's better to base recursion at the length 1 or 0. It's usually trivial and reduces the chance of making an error. In your case, the code doesn't work for lists of length 1, and this can be easily fixed by setting the base case to perms' _ [x] = [[x]].

The costly operations in your code are repeated traversals of the input list. In particular, length xs is called every time, and as lists in Haskell are lazy linked lists, it costs you O(n). You could pass the length of the list as another argument instead.

Similarly last and init are O(n). You could use splitAt to traverse the list just once, or even better, rotate the other way around, something like shift (y:ys) = ys ++ [y] where you need to traverse the list just once (for ++) and pattern matching is also somewhat safer than using partial functions such as init/head/last/..., especially if you cover all cases and use -fwarn-incomplete-patterns.  You might also consider using Seq which has O(1) costs for manipulating its ends and O(log n) splitting/merging sequences in the middle, but has higher constant factor.

Another source of inefficiencies could be the ++ in the otherwise branch, as ++ needs to traverse the whole left argument. You might again try out Seq, or constructing the result using difference lists, which eliminates this problem.

You could solve several of these problems by introducing a helper function that'd return all possible splits of an input list, something like

splits :: [a] -> [(a, [a])]

for example splits [1,2,3] = [(1, [2, 3]), (2, [1, 3]), (3, [1, 2])]. And then recursively process the second part, prepending the picked element to all sub-results.

It's good that you provided the type of the top-level function.

Also (\a -> x : a) can be abbreviated to (x :) using η-reduction.

Below is code based on the above ideas, with some more optimizations (to improve sub-list sharing), left as an exercise to analyze:

 perms :: [a] -> [[a]]
 perms = go []
   where
     go rs [] = [rs]
     go rs xs = concatMap (\(y, ys) -> go (y : rs) ys) (splits xs)

 splits :: [a] -> [(a, [a])]
 splits = go []
   where
     go ys [] = []
     go ys (x : xs) = (x, ys ++ xs) : go (x : ys) xs


Draw polygons with increasing/decreasing vertices

closePath is not complement of beginPath
You are using ctx.closePath() incorrectly. ctx.closePath() is a path function, similar to ctx.moveTo(x, y). It creates a line from the current position to previous ctx.moveTo(x, y). It is not the complement of ctx.beginPath(). There is no need to use it in this case.
Keep it Simple.
Circle & Vector
You have defined Circle, and Vector objects.
When you create the circle you pass a x, y coordinate that you use to create a Vector  and assign to circle.center.
Rather pass a Vector to the Circle. eg
constructor(center, radius) {
    this.center = center;
    ...

circle = new Circle(new Vector(x, y), 10);

Just data stores
Both the Circle and Vector objects are just data stores, they do nothing else but hold some numbers. You can simplify both to much simpler forms
const Vector = (x = 0, y = 0) = ({x, y});
const Circle = (center = Vector(), radius = 20) = ({center, radius});

This saves you 11 lines of code, without changing the behavior.
Irrelevant data.
The function draw does some odd things. You create circles yet only ever use centers. As code in Code Review questions is considered to be complete. Using circle is superfluous, just use the vectors.
Cache data
Your code recalculates all the points each time you redraw, this is a waste of time. You can either

Store all the points for each shape and use existing path points or create them if they have not yet been created.
Store the 2D path calls as a Path2D.

2D rendering
When rendering to 2D canvas context always group path calls that use the same state (color, line width, etc) should be inside the same beginPath. beginPath and stroke require GPU state changes, which is where the rendering bottle neck is, on low end devices this bottle neck is very small making even simple renders slow due to poor state change calls.
The draw call has too many roles. Setting number of sides, displaying the number of sides, generating the points, all should be part of other functions. draw should only draw nothing more. Create the shape in another function and pass that data to the draw call. Displaying side count, and changing side shape can be done at a higher level.
Avoid setInterval
You should always avoid setInterval as it often makes managing timers more complex. Use setTimeout as there is no need to hold handles as it can be stopped via semaphore.
Avoid repetition
A lot of the code has very similar parts. Good code has very little repetition. This is done by using functions to do repetitive tasks.
More often than not the repetitive code will be such over many project. Writing functions for repeated code also creates a resource that can be moved from project to project saving you hours of time typing out the same thing over and over.
JavaScript supports modules that makes code reuse easy. The rewrite shows some examples,  DOM and Maths utils that would normally be in modules and imported. See rewrite comments
UI
Make the UI smart, buttons that can not or should not be used should be disabled. The disabled status of buttons also give the user feedback as to  the state of the app.
The rewrite maps the buttons to an object called actions which is in effect the interface to the app. Not only can  The user call actions, the code also uses actions to reset, and stop (when sides < 1)
Rewrite
At the top & bottom there is some commented code that shows how the utilities would be imported. The DOM utils are medium level code, if you have questions use the CR comments.

"use strict"; // not required when using modules
setTimeout(() => { // timeout only for CR snippet so that code is parse before execution
                   // Note I did not indent timeout as there is not much room for snipper

/* To use modules the imports would be. See bottom of snippet */
// import {query, listener, elements} from "./DOM/utils.jsm";
// import {constants} from "./Maths/constants.jsm";
// import {Vec2} from "./Maths/constants.jsm";

const ctx = query("#canvas").getContext("2d");
const center = Vector(ctx.canvas.width / 2, ctx.canvas.height / 2);

const rotate = - Math.PI / 2;
const shapes = [];
var sidesStep = 1;
var sides = 1;
var radius = center.y * 0.8;
var started = false;

const actions = {
    updateBtnStates() {
        btns.start.disabled = started;
        btns.stop.disabled = !started;
        btns.forward.disabled = sidesStep > 0;
        btns.backward.disabled = sidesStep < 0 && sides > 1;
    },
    start() {
        if (!started) {
            started = true;
            update();
        }
        actions.updateBtnStates();
    },
    stop() {
        started = false;
        actions.updateBtnStates();
    },
    reverse() {
        sides -= sidesStep;
        sidesStep = -sidesStep;
        actions.updateBtnStates();
    },
    forward() { actions.reverse() },
    backward() { actions.reverse() },
    reset() {
        sidesStep = 1;
        sides = 1;
        actions.stop();
        update(true);
    },
}
const btns = elements({
    start: "#startBtn",
    stop: "#stopBtn",
    forward: "#forwardBtn",
    backward: "#backwardBtn",
    reset: "#resetBtn",
});
Object.entries(btns).forEach(([name, el]) => listener(el, "click", actions[name]));

actions.reset();

function createShape(sides, r = radius) {
    const shape = [];
    var i = sides;
    while (i-- > 0) {
        const ang = (i / sides) * TAU;
        shape.push(Vector(Math.cos(ang) * r, Math.sin(ang) * r));
    }
    return shape;
}

function pathShape(points) {
    const path = new Path2D();
    var i = sides, j, p1, p2;
    while (i-- > 0) {
        j = i;
        p1 = points[i];
        while (j-- > 0) {
            p2 = points[j];
            path.moveTo(p1.x, p1.y);
            path.lineTo(p2.x, p2.y);
        }
    }
    return path;
}
function drawShape(ctx, path, pos, rotate, lineWidth = 0.5, col = "#000") {
    ctx.setTransform(1, 0, 0, 1, pos.x, pos.y);
    ctx.rotate(rotate);
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = col;
    ctx.stroke(path);
    ctx.setTransform(1, 0, 0, 1, 0, 0); // default
}
function clearCanvas(color = "lightgrey") {
    ctx.fillStyle = "lightgrey";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function update(once = false) {
    if (started || once) {
        !once && setTimeout(update, 1000);
        if (!shapes[sides]) { shapes[sides] = pathShape(createShape(sides)) }
        clearCanvas();
        drawShape(ctx, shapes[sides], center, rotate);
        numSidesEl.textContent = sides;
        sides += sidesStep;
        if (sides < 1) {
            sides = 1;
            sidesStep = 1;
            actions.stop();
        }
    }
}
},0); // End of timeout

/* The following would be a  Module file /DOM/utils.jsm */
const qryEl = qryEl => typeof qryEl === "string" ? query(qryEl) : qryEl;
const query = (qStr, el = document) => el.querySelector(qStr);
const listener = (eq, name, call, opt = {}) => ((eq = qryEl(eq)).addEventListener(name, call, opt), eq);
const elements = obj => (Object.entries(obj).forEach(([n, q]) => obj[n] = query(q)), obj);
// export {query, listener, elements};

/* The following would be a Module file /Maths/constants.jsm  */
// const constants.TAU = Math.PI * 2;
// export {constants};

/* The following would be a Module file  /Maths/Vec2.jsm */
// const Vec2 = (x = 0, y = 0) => ({x, y});
// export {Vec2};

/* To use modules the imports would be */
// import {query, listener, elements} from "./DOM/utils.jsm";
// import {constants} from "./Maths/constants.jsm";
// import {Vec2} from "./Maths/constants.jsm";

/* Replacements for imports constants, Vec2 */
const TAU = Math.PI * 2;
const Vector = (x = 0, y = 0) => ({x, y});

Sides:

    <button class='dir' id='backwardBtn'>BACKWARD</button>
    <button class='dir' id='forwardBtn'>FOWARD</button>
    <button id='startBtn'>Start</button>
    <button id='stopBtn'>Stop</button>
    <button id='resetBtn'>Reset</button>

    <canvas id='canvas' width='500' height='500'></canvas>

Warning Let
let in global scope is very bad.
General rule for let is. Only use it inside { blocks }, never use it in global scope.
Sorry OP the following is a little overly detailed and is in lue of the inevitable comments defending let.
A

...in 200ms expect "Hi" in console.
Another (diligent) script will crash

Another (sloppy) script can reuse b

Not crashing this script, but when the timeout (first script) callback calls b.log which is no longer a function it will throw an error.


Same PyObject for a shared_ptr C++ object

I'm not sure I understand all the premises of this question. My kneejerk reaction was, "Would it help if you could assume that C_CLASS derived from std::enable_shared_from_this<C_CLASS>? Is it in your power to make that an invariant in your codebase?" If so, I would even go a step further and ask whether you should just write an enable_PyObject_from_this<C_CLASS> along the same lines.

Anyway, I see a bit of reducible complexity in your code, I think.

template<typename C_CLASS>
using py_ptr = typename boost::python::pointee<boost::shared_ptr<C_CLASS>>::type;

Isn't this just a really complicated way of saying

template<typename T> using py_ptr = T;

(since pointee<ptr<T>>::type is ptr<T>::element_type is T by definition)?  And then you use it in contexts like

template<typename C_CLASS>
PyObject * createObject(const c_sptr<C_CLASS>& obj) {
    return boost::python::objects::make_ptr_instance<py_ptr<C_CLASS>,
            boost::python::objects::pointer_holder<c_sptr<C_CLASS>,
                    py_ptr<C_CLASS>>>::execute(obj);
}

which ought to be more like

template<typename T>
PyObject *createObject(const std::shared_ptr<T>& obj) {
    using namespace boost::python::objects;
    return make_ptr_instance<T, pointer_holder<shared_ptr<T>, T>>::execute(obj);
}

Even that looks more complicated than it feels like it ought to be, but I'm not finding much documentation about what make_ptr_instance is supposed to do (or for that matter why the second template type parameter to pointer_holder isn't defaulted).

I see you use Py_INCREF (all caps) but Py_DecRef (camel case). This suggests to the reader that something really subtle (and thus dangerous) is happening here — or else of course you'd be consistently using Py_IncRef/DecRef or Py_INCREF/DECREF (both of which are provided by the underlying library). But is the reader's inference correct? Are you really doing something subtle and dangerous? Or are you just mixing styles because you felt like it?

Are you at all worried that getCachedObjects<Base>() returns a completely different map from getCachedObjects<Derived>(), even though I might have a std::shared_ptr<Base> b and a std::shared_ptr<Derived> d such that b == d?


Date/Time picker for browsers that don't support the datetimelocal input

Yes there is a fair amount of repeated code - e.g. the options:

        dateFormat: "yy-mm-dd",
        timeFormat: "hh:mm TT",
        minuteGrid: 10,
        addSliderAccess: true,
        sliderAccessArgs: {
            touchonly: false
        },

These could be abstracted to a common object that gets extended with each call to datetimepicker() using Object.assign()
const commonOptions = {
    dateFormat: "yy-mm-dd",
    timeFormat: "hh:mm TT",
    minuteGrid: 10,
    addSliderAccess: true,
    sliderAccessArgs: {
        touchonly: false
    }
};

startDateTextBox.datetimepicker(Object.assign({
    onClose: function (dateText, inst) {
        if (endDateTextBox.val() != '') {
            const testStartDate = startDateTextBox.datetimepicker('getDate');
            const testEndDate = endDateTextBox.datetimepicker('getDate');
            if (testStartDate > testEndDate) endDateTextBox.datetimepicker('setDate', testStartDate);
        } else {
            endDateTextBox.val(dateText);
        }
    },
    onSelect: function (selectedDateTime) {
        endDateTextBox.datetimepicker('option', 'minDate', startDateTextBox.datetimepicker('getDate'));
    }
}, commonOptions));
endDateTextBox.datetimepicker(Object.assign({
    onClose: function (dateText, inst) {
        if (startDateTextBox.val() != '') {
            const testStartDate = startDateTextBox.datetimepicker('getDate');
            const testEndDate = endDateTextBox.datetimepicker('getDate');
            if (testStartDate > testEndDate) startDateTextBox.datetimepicker('setDate', testEndDate);
        } else {
            startDateTextBox.val(dateText);
        }
    },
    onSelect: function (selectedDateTime) {
        startDateTextBox.datetimepicker('option', 'maxDate', endDateTextBox.datetimepicker('getDate'));
    }
}, commonOptions));

The onClose function could be abstracted to a function that accepts the picker to modify as a parameter.
It appears there is an option in the datetimepicker documentation for a Range between date selection - it uses just the onShow option to set the min and max dates:

jQuery(function(){
 jQuery('#date_timepicker_start').datetimepicker({
  format:'Y/m/d',
  onShow:function( ct ){
   this.setOptions({
    maxDate:jQuery('#date_timepicker_end').val()?jQuery('#date_timepicker_end').val():false
   })
  },
  timepicker:false
 });
 jQuery('#date_timepicker_end').datetimepicker({
  format:'Y/m/d',
  onShow:function( ct ){
   this.setOptions({
    minDate:jQuery('#date_timepicker_start').val()?jQuery('#date_timepicker_start').val():false
   })
  },
  timepicker:false
 });
});


startTimer()

The time package provides timers natively. So rather than using a call to time.Sleep(), you can use time.NewTimer().

Use fmt.Printf() rather than fmt.Println() for printing formatted strings.

func startTimer(seconds int) {
    time.Sleep(time.Duration(seconds) * time.Second)
    fmt.Println("Time is up! You got ", points, " points")
    os.Exit(0)
}

Becomes:

func startTimer(sec int) {
    timer := time.NewTimer(time.Duration(sec) * time.Second)
    <-timer.C
    fmt.Printf("Time is up! You got %d points\n", points)
    os.Exit(0)
}

readCSV()

In readCSV(), you have multiple error variables. You can instead use a single error variable as you go along.

I advise against adding file retry logic. It complicates the code, and most users can simply re-run the command upon error. Instead, you should return an error value.

Using a named return (questions) means you should actually use the questions variable. Because I switch to multiple return values, I removed the named parameter.

Also be sure to close the file after you're done reading from it.

func readCSV(s string) (questions [][]string) {
    f, err1 := os.Open(s)
    records, err2 := csv.NewReader(f).ReadAll()
    for err1 != nil || err2 != nil {
        fmt.Println("Error: ", err1, err2)
        fmt.Println("Please re-enter the name of the CSV file: ")
        fmt.Scan(&s)
        f, err1 = os.Open(s)
        records, err2 = csv.NewReader(f).ReadAll()
    }
    return records
}

Becomes:

func readCSV(name string) ([][]string, error) {
    f, err := os.Open(name)

    if err != nil {
        return nil, err
    }

    qs, err := csv.NewReader(f).ReadAll()

    if err != nil {
        return nil, err
    }

    return qs, f.Close()
}

askQuestions()

Again, here you should use fmt.Printf() to print formatted strings.  You also use the value i as an index, but with the range keyword you can access the currently indexed value, see here.

You should check the return of fmt.Scan().

Rather than starting the timer within askQuestions(), I opted to move it to main(). This means we can remove the time argument.

main()

Naming variables like fPtr and sPtr is just extra typing. Documenting the type in the name itself is not very useful.

fPtr becomes name
tPtr becomes time
sPtr becomes shuffle

From your updated code with shuffling:

Rather than keeping a second copy of the shuffled questions, just modify the array in-place. You also don't need to seed rand (see this example from the Go docs).

Conclusion

Here is the code I ended up with:

package main

import (
    "encoding/csv"
    "flag"
    "fmt"
    "log"
    "math/rand"
    "os"
    "time"
)

var points int

func main() {
    name := flag.String("csv", "problems.csv",
        "filename in csv (question, answer)")
    time := flag.Int("time", 10, "time in seconds")
    shuffle := flag.Bool("shuffle", true, "shuffle your question order")

    flag.Parse()

    questions, err := readCSV(*name)

    if err != nil {
        log.Fatal(err)
    }

    if *shuffle {
        rand.Shuffle(len(questions), func(i, j int) {
            questions[i], questions[j] = questions[j], questions[i]
        })
    }

    go startTimer(*time)

    if err := askQuestions(&questions); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("You got %d points\n", points)
}

func readCSV(name string) ([][]string, error) {
    f, err := os.Open(name)

    if err != nil {
        return nil, err
    }

    qs, err := csv.NewReader(f).ReadAll()

    if err != nil {
        return nil, err
    }

    return qs, f.Close()
}

func askQuestions(questions *[][]string) error {
    for i, q := range *questions {
        fmt.Printf("Question %d: %s\n", i+1, q[0])

        var a string
        _, err := fmt.Scan(&a)

        if err != nil {
            return err
        }

        if a == q[1] {
            points++
        }
    }

    return nil
}

func startTimer(sec int) {
    timer := time.NewTimer(time.Duration(sec) * time.Second)
    <-timer.C
    fmt.Printf("\nTime is up! You got %d points\n", points)
    os.Exit(0)
}

Hope this helps!


Review my prime factorization function. Is it complete?

Your result is incorrect:

>>> allPrimeFactors(360)
[2, 2, 3, 3, 5]
>>> import operator
>>> reduce(operator.mul, allPrimeFactors(360), 1)
180

It is also unnecessarily complicated.  The usual approach is, whenever you encounter a prime factor, extract as many powers of it as possible from the number.  Here's another function that works:

def reallyAllPrimeFactors(n):
    factors = []
    for i in range(2, n + 1):
        while n % i == 0:
            factors.append(i)
            n = n // i
    return factors
>>> reallyAllPrimeFactors(360)
[2, 2, 2, 3, 3, 5]
>>> reduce(operator.mul, reallyAllPrimeFactors(360), 1)
360

Further optimizations to that are possible, but it is already much more efficient than your original.  For one thing, it doesn't need to check any of its results for primality.  (Why?)


A way to do this without a lot of variables and casting?

So you're looking for

int result = (int)Math.round((float)n/(float)d) * d;

(assuming you are only interested in the intermediate values for this particular calculation)

Here's a test case with an alternative:

import junit.framework.TestCase;

public class TestModulo extends TestCase {

    private final static int d = 7;

    public void testModulo() throws Exception {
        for (int n = 0; n < 30; n++) {
            assertEquals("fails for " + n, f2(n), f1(n));
        }
    }

    private int f1(int n) {
        return (int) Math.round((float) n / (float) d) * d;
    }

    private int f2(int n) {
        return ((n + d / 2) / d) * d;
    }

}

You can solve your problem using only integer math.


I do not have much experience with Laravel, so I will comment on your code as it is presented, but keep in mind that I may miss something which is already handled by the framework.

The first thing which strikes my mind is the getRoles() method. To me it seems you are doing the work of the native function array_column(). This means the method can be reduced to:

public function getRoles() {

    return array_column($this->roles, 'role');

}

I even think you could extract only the role names into a property. I am not familiar with how Laravel deals with databases, but I am sure you can extract only the role names associated with the user directly from the database. If you then extract the roles during instantiation of the class, you can remove the getRoles() method altogether.

I would also remove the methods player, coach and referee and replace them with a generic method. This is to make it easier in the future if you add/remove new roles. Consider the following method.

public function hasRole($role) {

    return in_array($roles, $this->getRoles());

}

You would then check if a user by simply writing the role name.

if(Auth::user()->hasRole('referee')) {
    // Do awesome stuff here
}

This would reduce the number of methods inside your class and make it so you wouldn't have to edit your exiting code just to add a new role. This follows the open-closed principle which states that a class should be open for extension, but closed for modification.

Now you can also pass the role name as variable (if you ever need to) without the fear of an undefined method error as the method would simply return false.

Happy coding!


I don't know what workFlow and urlglob are. So there might be wways to improve it that I don't know about.

_sync, _async and _merg are so similar that you should probably combine them in some way, instead of maintaining 3 near-identical copies of the same code. The callback part at the end is different in _merg because you're constructing an object at the end, but you can rewrite it so that the object-construction bit is handled where _merg is called.

In _urlMatch, the callback function doesn't follow the convention - the first argument should be an error argument. Even though you never need to call it with an error.

In fact, there's no reason why _urlMatch needs to be asynchronous at all. I.e. it shouldn't have the callback argument, and should finish with return match; instead of return callback(match);. Then, instead of _urlMatch(req.url, workFlow[meth], function(match) { ... });, do var match = _urlMatch(req.url, workFlow[meth]); ....

Similarly, _assembleTask can be made synchronous. (It makes a list of things to do; the things are asynchronous, but it doesn't actually do them, so it's OK.) The synchronous equivalent of callbacks with errors is the try-catch mechanism.

You've got a variable called module. nodejs has a built-in global variable called module. Since you've re-declared it, you're not interacting with the original module, so it's OK. Indeed, the global module usually isn't used inside function calls. But still, overriding variable declarations is generally frowned upon.

In _assembleTask, err is an unnecessary variable.

In _sync and _async, you can replace function(err, results) { return callback(err, results); } with callback.

You don't need any of these global variables (req, meth, url). You're only using them to pass information to _sync, _async, _merg and _assembleTask, so you should use arguments instead. It might look a bit messier, but global variables make code less modular and therefore harder to work with. Perhaps you did this because you didn't know what to write instead of a.sync = _sync, etc. You can use async.apply for this. I haven't documented the extra arguments to _sync/_async/_merg because I'm not sure exactly what they are.

More generally, you can use closures for this - so instead of async.apply(_sync, request, meth, match) in my version of the code, you could have written function(callback) { _sync(request, meth, match, callback); }. The anonymous function has access to the variables in its enclosing scope: request, meth, match. I only mention this because it's a more flexible way of doing things than async.apply. In this case it's not necessary, since you're writing _sync and can arrange for these three arguments to appear first.

You can replace typeof workFlow[meth][url].merg != 'undefined' with workFlow[meth][url].merg !== undefined. In fact, you can probably just replace it with workFlow[meth][url].merg. It depends on what values workFlow[meth][url].merg can have, so I can't be sure since you haven't told us what workFlow is. If workFlow[meth][url].merg is false, null, 0 or '', then workFlow[meth][url].merg is falsy but workFlow[meth][url].merg !== undefined is true; otherwise, it's OK to just use workFlow[meth][url].merg.

I would say you can do the same with typeof workFlow[meth][url].merg != 'undefined', but there's no reason why they should both be there anyway - just use if-else.

You seem to have an extra curly bracket at the end.

I've incorporated most but not all of these changes below. I haven't tested it, partly because I'm too lazy but mostly because I don't know what the setup is with these variables you haven't explained.

/**
 * Fork -> Synchronous process
 * @param  {Function} callback
 */
var _sync = function(req, meth, url, callback) {
    try {
        var tasks = _assembleTask(req, null, workFlow[meth][url].sync);
    } catch (mod) {
        return callback(true, 'Invalide Workflow : ' + mod);
    }
    async.series(tasks, callback);
};

/**
 * Fork -> Parallel process
 * @param  {Function} callback
 */
var _async = function(req, meth, url, callback) {
    try {
        var tasks = _assembleTask(req, null, workFlow[meth][url].async);
    } catch (mod) {
        return callback(true, 'Invalide Workflow : ' + mod);
    }
    async.parallel(tasks, callback);
};

/**
 * Merg - Parallel process
 * @param  {Object}   data - return values of sync and async
 * @param  {Function} callback
 */
var _merg = function(req, meth, url, data, callback) {
    try {
        var tasks = _assembleTask(req, data, workFlow[meth][url].merg);
    } catch (mod) {
        return callback(true, 'Invalide Workflow : ' + mod);
    }
    async.series(tasks, callback);
    });
};

/**
 * URL Matcher
 * @param {String}   needle - incoming url
 * @param {Object}   haystack - JSON object for
 */
var _urlMatch = function(needle, haystack) {
    for (var i in haystack) {
        if (urlglob(i, needle)) {
            return i;
        }
    }
    return null;
};

/**
 * Assemble tasks
 * @param {data}     data - data to be passed into instantiated object
 * @param {taskList} taskList - list of tasks to instantiate
 */
var _assembleTask = function(req, data, taskList) {
    var tasks = {};
    for (var key in taskList) {
        var mod = taskList[key].split('.');
        if (!procsObj[mod[0]]) throw mod;
        var procsInst = new procsObj[mod[0]](req, data);
        if (!procsInst[mod[1]]) throw mod;
        tasks[mod[0] + '_' + mod[1]] = procsInst[mod[1]];
    }
    return tasks;
};

/**
 * Main Method
 * @param  {Object}   request - request object passed from HTTP
 * @param  {Function} callback
 */
this.run = function(request, callback) {
    if (!(request.method in workFlow) && !('*' in workFlow)) {
        callback(405, 'Method Not Allowed');
    } else {
        var meth = (request.method in workFlow) ? request.method : '*';
        var match = _urlMatch(request.url, workFlow[meth]);
        if (match === null) {
            callback(404, 'Not Found');
        } else {
            var a = {};
            workFlow[meth][match].sync !== undefined && (a.sync = async.apply(_sync, request, meth, match));
            workFlow[meth][match].async !== undefined && (a.async = async.apply(_async, request, meth, match));
            async.parallel(a, function(err, results) {

                if (workFlow[meth][match].merg !== undefined) {
                    _merg(request, meth, match, results, function(err, merg) {
                        callback(err, {
                            sync: results.sync,
                            async: results.async,
                            merg: merg
                        });
                    });
                } else {
                    callback(err, results);
                }

            });
        }
    }
};