Python/Pandas code creating 12 month product balance forecast

The most confusing part in your code is that new_df in create_timeseries_df is actually a pd.Series full of generators! It took me a while to understand what is actually going on there. What was the point of using them in the first place? I don't think you win anything from it.

I also don't understand what was the point in using OrderedDict. Usual dict should be enough.

p=1
while p <= num_periods:
    ...
    p += 1

This is not a Pythonic way. Instead you should do it like this:

for p in range(num_periods):
   ...  # Don't forget that p will start from 0, not 1

if period == 'monthly':
    e_bal = round(b_bal - (balance*1/12*run_off_rate), 4)
    e_bal += round((balance*1/12*new_funds_rate), 4)
if period == 'annual':
    e_bal = round(b_bal - (balance*run_off_rate), 4)
    e_bal += round((balance*new_funds_rate), 4)

No need to repeat twice. No need to repeat twice. For example, if you decide to change precision from 4 to 5 then you have to change it in 4 places!
See "Why is DRY important?" for explanations why such code is bad.
I suggest to rewrite it to something like this (not sure about the dict with coefficients though):

term_coefficients = {'monthly': 1 / 12,
                     'annual': 1.}
precision = 4
...
coefficient = term_coefficients[period]
e_bal = round(b_bal + balance * coefficient * (new_funds_rate - run_off_rate),
              ndigits=precision)

Actually you don't need dateutil.relativedelta to get desired timeseries. Pandas already has this kind of functionality. Check this out:

pd.DataFrame({'Month': pd.date_range(start=start_date,
                                     periods=periods_count,
                                     freq='M')})

Your column Period is actually just an index column + 1:

some_df['Period'] = some_df.index + 1

I don't know if you really need this column at all because you already have column 'Month' that you can use for grouping data.

So, I decided to refactor your code. I split the logic in several functions in a different way than you did. I added type hints and changed format of a docstring to reST (see list of different formats). Unfortunately, I have no idea how to name the functions and some variables. It's up to you to name them properly.
If you have any questions, I will add explanations to my answer.

import datetime as dt
from typing import List

import pandas as pd

pd.options.display.float_format = '{:.2f}'.format

TERM_COEFFICIENTS = dict(monthly=1 / 12,
                         annual=1.)

def get_final_result(*,
                     balances: List[float],
                     start_date: dt.date,
                     periods_count: int,
                     new_funds_rate: float,
                     run_off_rate: float,
                     precision: int = 4.,
                     term: str = 'monthly'):
    """
    Implements the cash flow modeling for demand products
    :param balances: initial balances of product at t0
    :param start_date: calendar date of t0
    :param periods_count: number of period to model
    :param run_off_rate: annualized rate
    at which deposit runs off - straight line
    :param new_funds_rate: annualized rate
    at which funds increase (net)
    :param term: the period used for modeling
    i.e. monthly, annual
    :param precision: number of digits in final balance
    :return: a schedule of liquidity
    based on the inputs ordered by time
    """
    output_df = pd.DataFrame()

    for balance in balances:
        df = get_df(balance=balance,
                    start_date=start_date,
                    periods_count=periods_count,
                    new_funds_rate=new_funds_rate,
                    run_off_rate=run_off_rate,
                    precision=precision,
                    term=term)
        output_df = output_df.append(df)

    return output_df.groupby(
            ['month', 'period'])[['start_balance', 'end_balance']].sum()

def get_df(*,
           balance: float,
           start_date: dt.date,
           periods_count: int,
           run_off_rate: float,
           new_funds_rate: float,
           precision: int,
           term: str) -> pd.DataFrame:
    df = pd.DataFrame(dict(month=pd.date_range(start=start_date,
                                               periods=periods_count,
                                               freq='M')))
    df['period'] = df.index + 1

    terms_balances = get_balances(balance,
                                  periods_count=periods_count,
                                  term_coefficient=TERM_COEFFICIENTS[term],
                                  run_off_rate=run_off_rate,
                                  new_funds_rate=new_funds_rate,
                                  precision=precision)

    df['start_balance'] = terms_balances[:-1]
    df['end_balance'] = terms_balances[1:]

    return df

def get_balances(balance: float,
                 *,
                 periods_count: int,
                 term_coefficient: float,
                 run_off_rate: float,
                 new_funds_rate: float,
                 precision: int) -> List[float]:
    balances = [balance]
    for _ in range(periods_count):
        balances.append(round(get_end_balance(
                balance,
                start_balance=balances[-1],
                term_coefficient=term_coefficient,
                run_off_rate=run_off_rate,
                new_funds_rate=new_funds_rate),
                ndigits=precision))
    return balances

def get_end_balance(balance: float,
                    *,
                    start_balance: float,
                    term_coefficient: float,
                    run_off_rate: float,
                    new_funds_rate: float) -> float:
    return (balance * term_coefficient * (new_funds_rate - run_off_rate)
            + start_balance)

if __name__ == '__main__':
    data = pd.DataFrame({
        'balance': {
            1: 1500,
            2: 700},
        'freq': {
            1: 999,
            2: 999},
        'maturity': {
            1: '2018-01-31',
            2: '2018-01-31'},
        'period': {
            1: 'months',
            2: 'months'},
        })

    print(get_final_result(balances=data['balance'].tolist(),
                           start_date=dt.date(2018, 1, 31),
                           periods_count=12,
                           run_off_rate=0.,
                           new_funds_rate=0.1,
                           precision=4))


I'm a little bit short on time at the moment, but I'ld like to share a few minor observations with you. Maybe I will also find time to look at performance related optimizations and expand it later.

You said you would like your code to be Pythonic. With that in mind you could replace print(list(reversed(values))) by print(values[::-1]) which uses slicing (nice explanation on Stack Overflow) to revert the list. Since you need the complete list nevertheless, there is no real advantage in using a reverse iterator instead of a list directly.

Also since "Explicit is better than implicit." (from Zen of Python) I would prefer to see

distance = hamming if input_mode == 1 else levenshtein

or something similar instead of

distance = [hamming, levenshtein][input_mode - 1]

The proposed version would also allow you to drop the string to int conversion. It would even work if the user entered something else than the two values presented by the prompt. levenshtein would be assumed to be the default then. Change the if to your liking if you prefer hamming as default. Although this might not be something to think about, since you have an input validation in place (good). However, the way it is written could be improved since you have a really small range (read: two) values that are valid. That makes it possible to list them explicitly:

# Validate user input
if input_mode not in (1, 2):
    raise ValueError("Invalid mode: " + input_mode)

This almost reads like normal language.


Generic implementation of SiftUp/Down operations on binary heap

Don't specify the array size in int arr[5] = {2, 1, 5, 4, 3};. int arr[] = {2, 1, 5, 4, 3}; will cause less maintenance issues.
Don't use magic numbers. All other occurrences of 5 should be replaced with either sizeof arr / sizeof *arr or much better turn arr into an std::array and use arr.size().
I don't like the combination of while (true) with a conditional break. Not sure how to get around it though.
I don't understand what the static_cast<unsigned> are for. Casts are not very appealing.
You use auto for basically everything including unsigned ints, but then you explicitly name the type typename std::iterator_traits<RandIt>::value_type when auto would suffice.
I would appreciate some comments. I don't actually know what SiftUp and SiftDown do and why they are not hidden in some heap implementation. I suppose returning when n < 2 is because you are heapifying the array and an array of less than 2 elements it automatically a heap, but I'm not sure.
The code in main is essentially a demo how to use the code. That is good. You could flesh that out a bit though. I made a move only type to check if you screwed up move semantics somewhere. You probably did too. Leave the check in. Also add an assert to make sure the resulting array is 5 4 3 2 1. (that is the correct result, right?). Therefore, when people mess with optimize the code they will be notified when they screw up. Add a case with an empty array, 1 element array and an array with a bunch of equal elements to show you thought about edge cases.
SiftUp and SiftDown could probably use some asserts to check if invariants hold. This also documents that there are invariants and what they are and you are told when you break them.
I would add some line breaks and even parenthesis to if statements. That is a style/habit thing through. If you can get your hands on code written by the interviewer's company try to mimic their style.
last in SiftDown should be a const & to avoid an unnecessary copy. Same goes or first in SiftDown, but then you need to pass std::begin(arr) instead of just arr.

After having criticized a lot let me say this: I would probably hire you. You show a good understanding of C++ and should be easy to shape into a good software developer. Good luck!


Ok, I think I've found an answer that I can appreciate. From Marcus Zarra's blog:

  A view controller typically shouldn’t retrieve the context from a
  global object such as the application delegate. This tends to make the
  application architecture rigid. Neither should a view controller
  typically create a context for its own use. This may mean that
  operations performed using the controller’s context aren’t registered
  with other contexts, so different view controllers will have different
  perspectives on the data.

source: http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/

Look's like I'll go back to passing the managed object context via Segue.


Backbone.js App approach not very scalable - nested views

The success function for the user.fetch statement is annoying. Just messing around, I am not sure this is any better as a whole (or if it even works):

var Util = {
    error: function (msg) {
        return function () { new Error({ message: msg }); };
    }
};

var controllers = {};

_.extend(controllers, Backbone.Events);

var events = {
    fullStory: 'fullStory',
    user: 'user'
};

controllers.on(events.fullStory, function (id) {
    var query = new Parse.Query(Steps),
        steps;
    query.equalTo("story", id);
    steps = query.collection();

    steps.fetch({
        success: function () {
            new App.Views.Steps({ collection: steps });
        },
        error: Util.error("Error loading story.")
        }
    });
});

controllers.on(events.fullStory, function (id) {
    var title = new Story({ objectId: id });
    title.fetch({
        success: function(model, resp) {
            var idUser;
            new App.Views.Title({ model: title });
            idUser = title.toJSON().idUser;
            controllers.trigger(events.user, idUser);
        },
        error: Util.error('Could not find that story.')
    });
});

controllers.on(events.user, function (idUser) {
    var user = new Parse.User({ objectId: idUser });
    user.fetch({
        success: function () {
            // I just need the username key here...
            new App.Views.Username({model:user, el:$("#user")});
        },
        error: Util.error('Could not find the user you requested.')
    });
});

App.Controllers.Documents = Backbone.Router.extend({
    routes: {
        "story/:id" : "fullStory",
        "" : "index"
    },

    fullStory: function (id) {
        controllers.trigger(events.fullStory, id);
    }
});


First, Where are you writing in ofile?

Second, ;) you can use with statement to opening and closing files like below:

pattern=r'species,subl,cmp=\s{4}(.*)\s{4}(.*)\s{4}(.*)\s{3}s1,torque=(.{12})(.{12})'
infile=sys.argv[1]; outfile=sys.argv[2]
with open(infile, "r") as ifile, open(outfile, "w") as ofile:
    for line in ifile:
        match = re.match(pattern, line)
        if match:
            ofile.write('%g %12.5e %12.5e' % (int(match.group(1)), float(match.group(4)), float(match.group(5))))


Don't use:
using namespace std;

In the header file it is really bad and can break code. But even in the source file is considered bad practice.
see: Why is “using namespace std;” considered bad practice?

This does not read a line:
string Console::ReadLine() {
    string result;
    cin >> result;   // This reads a single space separated word:
    return result;
}

Use std::getline()
std::string Console::ReadLine() {
    std::string result;
    std::getline(std::cin, result);
    return result;
}

How does organization not become quickly overwhelming based on how VS Community creates the initial project structure?

I don't understand what this means.

Why is static not accepted in the cpp file when the declaration states static void in the h file?

Why waste the developers time adding in words the compiler already knows.

When transferring from one language to another a direct translation is usually not advisable. You have to use the other language in the way it is designed to be used, otherwise you are not going to get the improvements you desire.


if a == N+1:
     counters = [maximum]*N #array initializer

Looks \$O(N)\$ to me, making your total time complexity \$O(Nm)\$ worst case. The other guy has 2 separate loops, one \$O(m)\$ the next \$O(n)\$, for a total time complexity of \$O(m+n)\$ or \$O(max(n,m))\$.

Take home message:

Ditch the \$O(N)\$ array initializer, it's not worth it. Use 2 separate passes, like the other guy did.


Well I agree with the exception sentiment.  Errors are communicated by
exceptions (unless it is an exceptional case, but really, what you have
seems very standard, I don't see a reason to deviate here).

The typecheck for the input should probably be revised.  It's not
(immediately) clear to me what input arrays you actually want to accept.
In any case the isinstance check should probably be done the other way
round, i.e. check what type you want to accept (just np.ndarray?)
instead of the ones you don't want (because the reader has to infer what
other types there are).  It might also be easier to defer the check
until after np.asarray has returned a result, because afaik things
like nested lists can actually be converted meaningfully as well (unless
you don't want that obviously).

The shape check needs to be tighter as well, e.g. (4, 1, 1) < (4, 2)
is still true.

The method __array_wrap__ is just passing through the values, so is it
even needed?

The first argument of __array_finalize__ is self, so in the interest
of clarity I'd use that as well, although I can see the point in
expressing that it's the new array as well.

The use of hasattr in __repr__ strikes me as a bit odd, since in the
construction of the object you do assign them, so is there a case when
neither name, info, nor applied are available?  I'd also add test
cases if you rely on the output of repr.

As far as I can see from the
subclassing doc
the code seems fine otherwise.

Style-wise the indentation in Python code is four spaces, not two, there
are spaces missing in some method argument lists and I'm sure a tool
like pep8 will pick up more issues if you were to run it on the code.


Transforming a dict of lists into a list of dicts

You can at least turn the inner for loop into a list/generator comprehension and use list.extend ("Flat is better than nested"):

def return_dict_as_list(raw_input):
    mylist = []
    for key, values in raw_input.items():
        my_list.extend({'mykey': key, 'myvalue': value} for value in values)
    return mylist

But you can even turn it into one list comprehension with two for loops in it (and no nested lists):

def return_dict_as_list(raw_input):
    return [{'mykey': key, 'myvalue': value}
            for key in raw_input
            for value in raw_input[key]]

This will be a bit faster, too, since list comprehensions loop at C speed.

Another approach is to make it a generator:

def to_list_generator(d):
    for key, values in d.items():
        for value in values:
            yield {'mykey': key, 'myvalue': value}

This makes it a lot easier to see what is happening (depending on your taste). It also means that you don't need to hold the new list in memory but can process one item at a time in some other function.


You can use Array#filter to get elements from array which are not present in other array.

var a = [2, 4, 8, 16, 32],
    b = [2, 4, 32, 64, 128, 256];

// Define custom method on Array prototype
// Pass the array as parameter
Array.prototype.diff = function (arr) {

    // Merge the arrays
    var mergedArr = this.concat(arr);

    // Get the elements which are unique in the array
    // Return the diff array
    return mergedArr.filter(function (e) {
        // Check if the element is appearing only once
        return mergedArr.indexOf(e) === mergedArr.lastIndexOf(e);
    });
};

// How to call?
var diff = a.diff(b);

console.log(diff);
document.write('<pre>' + JSON.stringify(diff, 0, 4) + '</pre>');

Shorter version:

var diff = array1.concat(array2).filter(function (e, i, array) {
    // Check if the element is appearing only once
    return array.indexOf(e) === array.lastIndexOf(e);
});


Using BigInt in JavaScript, write a factorial function that takes either a Number or BigInt and returns a BigInt

My answer is pretty heavily based on this resource on BigInt, so feel free to explore that a bit first.

With that said, here are some of the key points I saw:

BigInt can use all the same types of simple arithmetic as Number, along with 0 being considered falsy as usual

1n + 3n === 4n // true!

BigInt is also usable as a JS primitive. Neat!

typeof 1n === "bigint" // true!

BigInt and Number should not be mixed and matched. The coercion between the two is ambiguous, and as such JavaScript would throw an exception in that circumstance, so you should only either use one or the other.

1 + 1n // whoops

If the article still holds true, BigInt doesn't have the luxury of using operations in the built-in Math object. So you would either need to stick to simple arithmetic, or build (or otherwise find) those implementations yourself.
Since the supported operations on BigInt are not constant time (according to the article), it is recommended to use BigInt strictly when a use case will frequently involve numbers higher than the largest representable int in Number (253). Your question is one such case, since factorials grow extremely fast, so I think it's fine as is.


Performance of your implementation is \$\Theta(N^2)\$ in all cases. You can improve it by holding a boolean variable indicating whether the current pass over the array swapped at least once the neighbouring array components. If the boolean is false, the array is sorted and we can exit the sort:

void bubbleSort(int a[], int s) {
    for (int i = 1; i < s; i++) {
        bool swapped = false;

        for (int j = 0; j < s - i; j++) {
            if (a[j] > a[j + 1]) {
                std::swap(a[j], a[j + 1]);
                swapped = true;
            }
        }

        if (!swapped) {
            return;
        }
    }
}

The above alternative implementation runs in linear time on almost sorted arrays.

Also, as you can see above, #include <utility> offers you a swapping routine (std::swap); why not use it?

Hope that helps.


Instead of appending the id's one by one, I would use:

ids = list(people.keys())

Note that I changed names to ids, as numbers don't seem like names to me. This is something that @jano's answer included but didn't explicitly state.

Then you can change your the rest of your code to:

first_names = set()
last_names = set()

for details in people.values():
     first_names.add(details['first'])
     last_names.add(details['last'])


General comments
I don't see much wrong with the code. The biggest concern I might have is that PHP code is mixed in with the HTML - an alternative to this would be using a template system. CodeIgniter has the template parser class which should allow you to do this.

Please be critical, very severe with me.

Okay - I am not typically this critical but you asked for it! The next section has a couple other review points
Minor nitpicks
In the PHP code, $data is not declared before values are assigned to specific keys:

$data['solicitud']  = $this->helpdesk_model->getRequest($session_data['usuario'], $index, $order);

I don't see a problem with this practice but the PHP documentation advises against it:

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment.

I tried running the jQuery callback through the demo page on eslint.org. It showed this warning:

'event' is defined but never used.

For this line:

$(".sub-menu .menu-item, .module-item").click(function(event) {

While event could be used if necessary, it isn't needed.


Create a Promise that resolves when jQuery loads

This is... hacky. It's extra code that could have just gone away if you just loaded your scripts through proper methods.

If jQuery is ubiquitous, it might be more beneficial to just load it up front.
If you have a build step, then compile it as a dependency of your app.
If you're doing asynchronous modules, consider using RequireJS.

In addition, browser cache will do its part to reduce loading times. Only the initial load will be slow. Also, async does not help in any way with load speed. It only reduces the time your script will block the HTML.


Python monkeypatch an API and search through iterable object tree

I think it is more futureproof to use multi-inheritance to resetname and use GatherFailedTests together rather than copy and pasting the code and only having it have single inheritance with copy pasted source.

class RenameThenGatherFailedTests(resetname, gatherfailed.GatherFailedTests):
    pass

gatherfailed.GatherFailedTests = RenameThenGatherFailedTests

I think this is simply better than the copy some code and don't copy other hybrid in the original question. However, I'm still uncertain if simply copying and altering the entire source would be a better practice.


Mostly minor stuff

Good use of fflush(stdout); to insure output.  Something often missed.
Minor: int main() { is not explicitly allowed per the standard.  Better to use int main(void) {
Minor: Naked physical quantity.  Values like height, weight, time, should have units made clear  feet vs meter $327.6 million mistake

// usleep(8000000);
#define SOME_us_TIME_CONSUMPTION (8000000 /* us */)
usleep(SOME_us_TIME_CONSUMPTION);

Minor: Avoid printf() when fputs() will do.  Avoid % issue.. BTW did you mean "safely" vs "savely"?

// printf("This is printed after 'LoadingDots' savely quit.\n");
fputs("This is printed after 'LoadingDots' savely quit.\n", stdout);
// or
puts("This is printed after 'LoadingDots' savely quit.");

Long lines: Respect the width for the target audience - in this case code review.

// pthread_create(&loadingThread, &attr, loadingDots, (void *)"Loading (main, does something long)");

vs.

pthread_create(&loadingThread, &attr, loadingDots,
    (void *)"Loading (main, does something long)");

Consider auto format.  The space between bool            loadingStop will likely shrink with auto formatting.  Insure code is presentable even after auto formatting.

// looks OK
static bool loadingStop;
static pthread_mutex_t loadingMutex;

Minor: Not a fan of {} one liners

// if (loadingStop) { break; };
if (loadingStop) {
  break;
};


Finding two numbers that add to a given total

Here is an alternative approach using set logic, which is O(n) in the average case:

n = 181
n2 = n//2
numbers = [80, 98, 83, 92, 1, 38, 37, 54, 58, 89]
goodnums = {n-x for x in numbers if x<=n2} & {x for x in numbers if x>n2}
pairs = {(n-x, x) for x in goodnums}

What this does is first filter out values that are greater than 1/2 the target value, since one number in each pair must be that way.  Then it subtracts the remaining numbers from the target (in this case 181).  This gets the other value from the pair.  Then it uses set logic to extract only those values where the other value is present in the original list of numbers.

So to put it more briefly, it finds all values x such that 181-x is also present in the list.

Edit: If you don't want to include cases where both members of the pair are equal and it only exists once, such as n=2 and numbers = [1], as Gareth pointed out, add this to the end:

if not n%2 and (n2, n2) in pairs and numbers.count(n2) == 1:
   pairs.remove((n2, n2))

This will check if n is even and, if so, if there is exactly one value where x==n//2, if so remove (n//2, n//2) from the results.


Pseudo-random number generator port from C

I cannot see any functional issues when comparing the C code against the Java code. it would seem they should produce the same results given the same input. Of course, a logical course of action would be to write a test system for the code which wraps the C code in to a program which accepts a single seed value as an argument, and produces a stream of int values in 'network byte' order. You then pipe that stream in to a Java program which produces the same stream, and compares the results. I would actually set up a test where the Java program starts a sub-process for the C version, and runs it with many input seeds, including the logical edge-cases (0, 1, -1, Long.MAX_VALUE, Long.MinValue, and all seeds from -100 to +1000). For each run, compare the first 10,000 generated values.

That would give me some measure of confidence that the code is a faithful reproduction.

Like you, I believe the Java code is a fair reproduction, but, like you, I would want to check it again.

Now,about the code, you are doing unnecessary work. There is no need to store the oldState:

public int nextInt() {
  long oldState = state;
  state = oldState * MULTIPLIER + inc;
  int xorShifted = (int) (((oldState >>> 18) ^ oldState) >>> 27);
  int rot = (int) (oldState >>> 59);
  return Integer.rotateRight(xorShifted, rot);
}

That code can be reduced to:

public int nextInt() {
  int xorShifted = (int) (((state >>> 18) ^ state) >>> 27);
  int rot = (int) (state >>> 59);
  state = state * MULTIPLIER + inc;
  return Integer.rotateRight(xorShifted, rot);
}

Also, while your comments about the >>> vs >> are accurate, and I prefer the use of >>> here, you should also know that the only shift which has a significant impact (where using >>> makes a difference vs. >>) is the part:

(state >>> 18)

In that shift, if it was a negative state, and you used >>, it would shift the sign bit to position 46 (and all higher bits). Then the subsequent >>> 27 would shift those effects in to the low-order 32-bits. Since the value is truncated to 32 bits, any sign-shift effects which happen above 32 bits are irrelevant, and as I say, the only sign-shift which can effect the low 32 bits is the first one.

Also, Java uses a mask on the int rotate value, and for Integer.rotateRight it only considers the low-5 bits in the value, so the following are identical because the rotate effectively applies the mask 0x1f to the value anyway:

Integer.rotateRight(xorShifted, (int)(oldState >>> 59))
Integer.rotateRight(xorShifted, (int)(oldState  >> 59))

You may want to test the performance of each, and exercise your profiler....


Nth Fibonacci number (Bottom-up with dict)

Before we come to the actual algorithm: python has an official style-guide, PEP8. It recommends using lower_case for variable and function names (and PascalCase for classes). It also recommends avoiding unnecessary blank lines, which means having exactly two blank lines before a function definition (one if it is a class method) and only a single blank line to separate logical code blocks if necessary. Lastly, you should put a blank after the comma in an argument list or a colon ({1: 1, 2: 1} and not {1:1,2:1})

You should learn about decorators!

In the most simple way you could use it like this:

def memoize(func):
    func.memo = {1: 1, 2: 1}
    return func

@memoize
def Fib(n):
    for i in range(3, n+1):
        Fib.memo[i] = Fib.memo[i-1] + Fib.memo[i-2]
    return Fib.memo[n]

print Fib(15)

This makes a memo object bound to the func.

What you really want, though, is a decorator that silently caches every result, whenever you call your function. As it stands, you are also wasting cycles. If you calculate Fib(15) and after that Fib(16) it would be nice if the code took the already computed values of Fib(14) and Fib(15). Your code calculates all intermediate values for every n, though.

Here are two memoization decorators that can do what you need:

import functools

def memoize(func):
    cache = func.cache = {}

    @functools.wraps(func)
    def wrapper(n):
        if n not in cache:
            cache[n] = func(n)
        return cache[n]
    return wrapper

def memodict(f):
    """ Memoization decorator for a function taking a single argument """
    class MemoDict(dict):
        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret
    return MemoDict().__getitem__

@memodict
def fib(n):
    if n == 0:
        return 0
    if n in (1, 2):
        return 1
    return fib(n-1) + fib(n-2)

The first decorator is a bit easier to understand, as it does a bit what you started out doing already. It defines a cache for the function and stores the result of the function in the cache if it is not already in there. It returns the value in the cache.

The second is a more optimized and is slightly faster. It only works with single-valued functions (as yours is).  It uses the fact that the magic method __missing__ is called for a dict if a requested key does not exist, before raising a KeyError. In this method the cache is populated.

Important limitation:
Both of these implementations will raise a RuntimeError with recursion limit exceeded if you want to get a too big Fibonacci number right away (where too big is already somewhere between 250 and 300). Here, you can, however, use what you already have and just calculate all Fibonacci numbers up to that number:

for n in xrange(large_number):  # Use range in python 3.x
    fib(n)
print fib(large_number)


Any performance difference would be too small to measure.

Code 2 pollutes the global namespace with three variables: $, fitvidsInit, and sliderInit.  Therefore, Code 1 is better.  I suggest eliminating $area and $slider as well:

jQuery( function( $ ) {

    // Responsive video
    $( "#sidebar" ).fitVids();

    // Image gallery
    $( ".owl-carousel" ).owlCarousel();

});


Customer ViewModel with optional JSON initialization parameter

The issue that I have with the viewmodel, and I suspect that it is the issue that you're having, is that you have two code paths to keep in sync when initializing the object.

By getting rid of the if {} else {} and having a default value going into the knockout observable as an alternative value then you reduce the lines of code and you only define the properties of the object once.

Something like this:
I have used undefined as the default in this case

function Customer(customer) {
    var self = this;
    self.CustomerId = ko.observable(customer.CustomerId || undefined);
    self.CustomerName = ko.observable(customer.CustomerName || undefined);
    self.DateOfBirth = ko.observable(customer.DateOfBirth || undefined);
    self.EmailAddress = ko.observable(customer.EmailAddress || undefined);
    self.CustomerContacts = customer ?  ko.mapping.fromJS(customer.CustomerContacts, customMapping): ko.observableArray();
}


bash script for constructing RNA pipeline

This script looks like a wall of text and barely readable.
Let's break it down from top to bottom.

Simplify the handling of -h

Since the if at the beginning to check if the first parameter is -h will exit if true,
it would be simpler to drop the else part entirely:

if [ "$1" == -h ]
then
    echo "Usage: sh $0 cuffcompare_output reference_genome blast_file"
    exit
fi

I also dropped the quotes around the -h, they are not necessary.

Validate the command line arguments

The script expects 3 parameters, but doesn't validate if it really received them.
I suggest to rewrite the top part like this:

help() {
    exitcode=$1
    echo "Usage: sh $0 cuffcompare_output reference_genome blast_file"
    exit $exitcode
}

[ "$1" == -h ] && help 0
[ $# -lt 3 ] && help 1

I added a help function to avoid duplication, because I wasn't too reuse the same help message when exiting the program in both cases:

When the first param is -h, print help and exit with 0, meaning success
When there are less than 3 params, print help and exit with 1, meaning failure

Instead of if statements I used && expressions to make it shorter and simpler. The result is equivalent.

Give the parameters meaningful names

The parameters $1, $2 and $3 are scattered here and there in the wall of text,
and they are not exactly easy to remember.
Give them proper names right after validation:

cuffcompare_output=$1
reference_genome=$2
blast_file=$3

And use these names throughout the script.

Taming the wall of text...

Add some line breaks.
Group together lines that are most tightly related.
For example,
for the lines that are the continuation of a pipeline, put
a line break before and after would make this easier to read.
And when a pipeline gets too long,
add some more line breaks (escaped with \) to make the important ending part more visible,
for example when redirecting output to a file.

For example, I think this is more readable:

wget https://github.com/TransDecoder/TransDecoder/archive/2.0.1.tar.gz && tar xvf 2.0.1 && rm -r 2.0.1

makeblastdb -in $3 -dbtype nucl -out $3.blast.out

grep '"u"' $1 | \
gffread -w transcripts_u.fa -g $2 - && \
python2.7 get_gene_length_filter.py transcripts_u.fa transcripts_u_filter.fa && \
TransDecoder-2.0.1/TransDecoder.LongOrfs -t transcripts_u_filter.fa

sed 's/ .*//' transcripts_u_filter.fa | grep ">" | sed 's/>//' \
> transcripts_u_filter.fa.genes

cd transcripts_u_filter.fa.transdecoder_dir

sed 's/|.*//' longest_orfs.cds | grep ">" | sed 's/>//' | uniq \
> longest_orfs.cds.genes

grep -v -f longest_orfs.cds.genes ../transcripts_u_filter.fa.genes \
> longest_orfs.cds.genes.not.genes

sed 's/^/>/' longest_orfs.cds.genes.not.genes \
> temp && mv temp longest_orfs.cds.genes.not.genes

python ../extract_sequences.py longest_orfs.cds.genes.not.genes ../transcripts_u_filter.fa longest_orfs.cds.genes.not.genes.fa

blastn -query longest_orfs.cds.genes.not.genes.fa -db ../$3.blast.out -out longest_orfs.cds.genes.not.genes.fa.blast.out -outfmt 6

python ../filter_sequences.py longest_orfs.cds.genes.not.genes.fa.blast.out longest_orfs.cds.genes.not.genes.fa.blast.out.filtered

grep -v -f longest_orfs.cds.genes.not.genes.fa.blast.out.filtered longest_orfs.cds.genes.not.genes.fa > lincRNA_final.fa

As a small tip, a shorter equivalent of grep ">" | sed 's/>//' is sed -ne 's/>//p'.


Get value from dictionary given a list of nested keys

Unless I'm missing something you'd like to implement, I would go for a simple loop instead of using recursion:

def nested_get(input_dict, nested_key):
    internal_dict_value = input_dict
    for k in nested_key:
        internal_dict_value = internal_dict_value.get(k, None)
        if internal_dict_value is None:
            return None
    return internal_dict_value

print(nested_get({"a":{"b":{"c":1}}},["a","b","c"])) #1
print(nested_get({"a":{"bar":{"c":1}}},["a","b","c"])) #None


I was thinking if I should add labels like write even if I wouldn't jmp to them, so code would be cleaner.

Writing labels that aren't jumped to is fine. Provided they have meaningful names, it can help to understand the program.

My comments (not in a particular order)

;esi=1
mov esi, 1

This is a redundant comment! I already can see what the instruction does. What I can't know is what the ESI register will be used for.

;if(argc==1)
;goto open
cmp dword [esp], 1
jnz open

Here the comment does not correspond to the code. The code actually does if(argc!=1).

cmp edx, 0
jnz read

The more usual way to test for zero would be test edx, edx. It has a smaller encoding and is generally a bit faster.

mov ebx, 0

Similarly, zeroing a register is best done using the xor instruction (xor ebx, ebx). This is both faster and shorter.

mov dword [fd], 0

Your program would not need this instruction at all, if you would move the fd variable from the .bss section to the .data section using fd dd 0.

This in turn opens up an opportunity to shorter the code from:

    cmp dword [esp], 1
    jnz open
    mov dword [fd], 0
    jmp read
open:

to:

    cmp dword [esp], 1
    je  read
open:

Also note that in conjunction with the cmp instruction, it's better to use je and jne.
In conjunction with the test instruction, it's preferable to use jz and jnz.

je and jz have an identical encoding but choosing the right instruction mnemonic better expresses what the intention of the code is.

;if(esi<argc)
cmp dword esi, [esp]
jl open

The argc is by its very nature an unsigned number. After all it's just a count. You should use the conditional jumps that are provided to deal with the unsigned conditions. So better use jb open (JumpIfBelow).
Also there's no point in writing the dword size-tag. The mention of the dword register ESI already dictates the size.

mov edx, eax
mov eax, 4
mov ebx, 1
mov ecx, buf
int 0x80

I always prefer to write the function number directly above the int 0x80 instruction. That way it's immediately clear what function is getting invoked. And for perfection I even assign the registers in a sorted manner:

mov edx, eax
mov ecx, buf
mov ebx, 1
mov eax, 4
int 0x80

Putting it all together

not being afraid to write redundant labels
putting the comments in a separate column for readability
shaving off one more byte by using the fact that ESI==1 when cmp dword [esp], 1 is executed.

section .text
    global _start

_start:
    mov  esi, 1
    cmp  [esp], esi        ;if(argc==1) goto read
    je   read
open:
    xor  ecx, ecx          ;fd=open(path,oflag)
    mov  ebx, [esp+esi*4+4]
    mov  eax, 5
    int  0x80
    mov  [fd], eax
read:
    mov  edx, BUFSIZE      ;bytes_read=read(fd,buf,BUFSIZE)
    mov  ecx, buf
    mov  ebx, [fd]
    mov  eax, 3
    int  0x80
write:
    mov  edx, eax          ;write(STDOUT_FILENO,buf,bytes_read)
    mov  ecx, buf
    mov  ebx, 1
    mov  eax, 4
    int  0x80
more:
    test edx, edx          ;if(bytes_read!=0) goto read
    jnz  read
close:
    mov  ebx, [fd]         ;close(fd)
    mov  eax, 6
    int  0x80
next:
    inc  esi
    cmp  esi, [esp]        ;if(esi<argc)
    jb   open
exit:
    xor  ebx, ebx
    mov  eax, 1
    int  0x80

section .data
    fd   dd 0              ;fd=STDIN_FILENO

section .bss
    BUFSIZE equ 1024
    buf  resb BUFSIZE

Concern

Nowhere in your code do you check for any errors from api calls like open or read. Imagine what might happen in these cases?


Can I use IDisposable by treating abstract concepts such as colors as resources?

Readability-wise, this is fine, though I prefer ConsoleForegroundBrush, because it keeps the theme of Drawing library, which is well known, and in the real world, you can definitely destroy/dispose brushes / put them down, but disposing an actual colour would be like... changing the color of the text back to black?

The main issue is there is a performance impact that comes with using, as this is really a try/finally block under the hood, and so you are adding try/finally around your code which may slow things down unnecessarily, particularly if there's other non-console logic in the using block.

The using block can also sometimes hide other errors, because it's a try/finally block. If you put a using block inside a try() block and your dispose method of the ConsoleForegroundColour class throws an exception (such as if the Console became null somehow), you will probably only see the Dispose() exception, and not the other exception. This situation is highly unlikely to happen in your class though.


Scan similar files in different directories and report differences

There is no reason here for this to be a class. You don't even use any class features and even have to work around it being a class by doing e.g. DirInfo.save(self._dirInfo, fname) instead of being able to do self.save(fname).

I would also add more functions, for example for hashing the file content.

import os
import stat
import hashlib
import json

STAT_FILE = "data.txt"

def get_stat_info(file_name):
    sbuf = os.fstat(os.open(file_name, os.O_RDONLY))
    return {'type': stat.S_IFMT(sbuf.st_mode),
            'mode': stat.S_IMODE(sbuf.st_mode),
            'mtime': sbuf.st_mtime,
            'size': sbuf.st_size}

def hash_file(file_name):
    hasher = hashlib.sha256()
    blocksize = 512000000
    with open(file_name, 'rb') as f:
        for chunk in iter(lambda: f.read(blocksize), b""):
            hasher.update(chunk)
    return hasher.hexdigest()

def probe(dir_name):
    dir_info = {}
    for file in os.listdir(dir_name):
        if file == STAT_FILE:
            continue
        file_with_path = os.path.join(dir_name, file)
        file_info = {'name': file}
        if os.path.isfile(file_with_path):
            file_info.update(get_stat_info(file_with_path))
            file_info['sha256'] = hash_file(file_with_path)
        if os.path.islink(file_with_path):
            file_info['symlink'] = os.readlink(file_with_path)
        dir_info[file] = file_info
    return dir_info

def save(dir_info, file_name):
    with open(file_name, 'w') as f:
        json.dump(dir_info, f)

def load(file_name):
    with open(file_name, 'r') as f:
        return json.load(f)

def compare(dir_info1, dir_info2):
    files1, files2 = dir_info1.keys(), dir_info2.keys()

    for f in files1 - files2:
        print (f, "is verwijderd")
    for f in files2 - files1:
        print (f, "is toegevoegd")
    for f in files1 & files2:
        file_info1, file_info2 = dir_info1[f], dir_info2[f]
        for key in file_info1:
            if file_info1[key] != file_info2[key]:
                print("In bestand:", f, "was", key, file_info1[key], "nu is", key, file_info2[key])

if __name__ == '__main__':
    dir_name1 = "D:\\Testmapje met random files"
    dir_info1 = probe(dir_name1)
    save(dir_info1, os.path.join(dir_name1, STAT_FILE))

    dir_name2 = "D:\\Testmapje met random files 2"
    dir_info2 = probe(dir_name2)
    save(dir_info2, os.path.join(dir_name2, STAT_FILE))

    compare(dir_info1, dir_info2)

Note that the save and load functions are not actually necessary, but I left them in because you might want to look at the results. In the compare function it makes a lot more sense to directly compare the two dictionaries, instead of saving them to a file and reading them back again.

I also changed all variables to conform to Python's official style-guide, PEP8, which recommends lower_case.


Ruby class to encapsulate Retrying (for instance, with email)

Other than the cosmetic suggestion we discussed about removing the unnecessary self prefixes, my central critique is that you're mixing concerns in this code.

Currently, you have specific logging strategies and even logging messages hardcoded in the retryer.  Which will make it hard to use the class in other contexts.

The retryer should do just one thing: retry X number of times and return a result.

Exactly what you want the return values to be is up to you (you could even make a RetryResult class), but one simple option would be an array of results from each attempt: true would be the final array value if it eventually succeeds; and the array would rescued errors from each failed attempt.

The calling code could then decide how to process that information: logging it, sending emails, ignoring it, etc.


Filtering of maximum value by ID and category sum

You could also do the following. Compute the first grouping by id and category, sum up the values:
y = df.groupby(["id","category"])["value"].sum()

Afterwards, grab the best category according to your definition:
y.groupby("category").sum().nlargest(1)

Combining these, so that we get the full job done:
y = df.groupby(["id","category"])["value"].sum()
cat = y.groupby("category").sum().nlargest(1).index
y.loc[:,cat]


Simple Bespoke WordPress Integration Plugin

It's a good idea with frameworks to follow the method calls to see what you're actually doing, Wordpress is one of the most exploited frameworks out there and thus has fairly good security improvements. Here is the Wordpress WP_Query class you're invoking (assuming you have the latest code pulled).

It looks like the __construct calls $this->query on your $params, which calls wp_parse_args(). (If you already have the code pulled, Grep can help finding where in the code the class lives).
https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php

As far as security is concerned, your primary concern would be with the user supplied data $_GET['q']. If you do not feel that the WP_Query class is doing enough to sanitize the user data you can sanitize it yourself.

In your case, it looks like you only want the user to supply a integer? If that is the case you can filter. Adjust as necessary:

if (filter_var($_GET['q'], FILTER_VALIDATE_INT)) {
   // is int
}

Additional tips:
There is no reason to set $_GET['q'] to $TagNumber in your example, since you're not sanitizing it. Doing so only increases memory usage and complicates code review.

Be consistent about whether or not to clear between an if and "{". Most of the reason for clearing has to do with refactoring and applies mostly to class definitions.

There is no need to ?> close the script, it can add unintended white space.

Don't indent functions unless they are inside classes (looks to be intended for no reason).

Pick a style for naming variables, e.g. snake_case; not $TagName and $params, but $tag_name and $params

I hope this is helpful :-)


The way you're using TaskScheduler.Current to try to synchronize access to Tasks won't work (unless this code runs under a very specific custom TaskScheduler).

With the default scheduler, a Task can be executed on any ThreadPool thread, which means that multiple threads could access Tasks at the same time. The simplest fix for that is to use lock instead of trying to use TaskScheduler (which will also simplify your code a bit).

Since you seem to be using Tasks just for counting, another option would be to replace it with int field and then use Interlocked.Increment()/Decrement() to modify it.
I think you should save the exception that's caught in ExecuteJob() somewhere, so that when you encounter an issue, you can actually diagnose it.

Also, it looks like you're not saving the results of jobs anywhere. I think that's a bad idea, you should have some sort of logging, to see where the problem was when something doesn't work right. (Was the job even scheduled? Did it complete successfully? Etc.)

And I'm not sure you want to differentiate between "failed" and "failed on exception". When something fails, you usually want to know why it failed, which is what exceptions are for.
Why are most of the properties of JobConsumer public? If you want to allow adding a new job to Jobs, but nothing else, then create a method for that.

And why is Tasks protected, when you don't have any virtual methods? The default accessibility should be private (which means you don't need a property anymore and you can use just a field) and you should change that only when you have good reason.
The way you use ReadNewJobs() seems to indicate that items are actually consumed only when the enumerable is iterated. That's not a bad idea (BlockingCollection.GetConsumingEnumerable() does the same thing), but it should be documented very clearly that that's what is expected from the method.
Since you're on .Net 4.5, you can use await Task.Delay() instead of Thread.Sleep(). This means you would need to make the lambda async and you should probably also use Task.Run() instead of Task.Factory.StartNew() (which is a good idea anyway, because it's shorter).
There is no need to spell the name System.Threading.Tasks.Task in full, use just Task.
I don't think that the name AbstractJob needs to emphasize that the class is abstract, calling it just Job would work just as well. Another possible name is JobBase.


Do you see what I see? Because I see copy-pasta: Yummy :)

            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            int month = calendar.get(Calendar.MONTH);
            int date = calendar.get(Calendar.DATE);
            int year = calendar.get(Calendar.YEAR);
            today.setTime(new Date());
            today.set(Calendar.HOUR, hour);
            today.set(Calendar.MINUTE, minute);
            today.set(Calendar.SECOND, second);
            today.set(Calendar.YEAR, year);
            today.set(Calendar.MONTH, month);
            today.set(Calendar.DATE, date);

This (or subsections thereof) are copy-pasted for each block in your method.

This screams for extraction into a method:

private static void copyCalendarFields(Calendar source, Calendar destination,
  int... fields) {
    for (int field : fields) {
       destination.set(field, source.get(field));
    }
}

And suddenly things become significantly smaller:

        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        today.setTime(new Date());
        today.set(Calendar.HOUR, hour);
        today.set(Calendar.MINUTE, minute);
        today.set(Calendar.SECOND, second);

is just:

copyCalendarFields(calendar, today,
    Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND);

and suddenly these long blocks of code are gone and the whole method is a lot more digestable


Extending SeqLike - move an element to the front of the sequence

You might be overcomplicating a bit by reaching further than you need into builder mechanics.  If you rewrite the signature of SeqLikeOps to

import scala.language.higherKinds
implicit class SeqLikeOps[A, F[_]](seq: SeqLike[A, F[A]])
  (implicit cbf: CanBuildFrom[F[A], A, F[A]]) {

then bringToFront can basically look like this:

def bringToFront(a: A): F[A] = {
  val as = // Do some magic with seq
  as.to[F]
}

Using higher kinds makes the upper bound go away while leaving the messy details of building to .to[F]
Here's one way to do that using Iterators for efficient space usage and gc and for their laziness.

implicit class SeqLikeOps[A, F[_]](seq: SeqLike[A, F[A]])(implicit cbf: CanBuildFrom[F[A], A, F[A]]) {
  private sealed trait Step {
    def iter: Iterator[A]
    def run(x: A): Step
  }
  private case class Found(iter: Iterator[A]) extends Step {
    def run(x: A) = Found(iter ++ Iterator(x))
  }
  private case class NotFound(iter: Iterator[A], val a: A) extends Step {
    def run(x: A) =
      if (x == a)
        Found(Iterator(x) ++ iter)
      else
        NotFound(iter ++ Iterator(x), a)
  }
  def bringToFront(a: A): F[A] = {
    val result = seq.iterator.foldLeft(NotFound(Iterator[A](), a): Step) {
      (s, a) => s.run(a)
    }
    result.iter.to[F]
  }

}

Using Iterator this way does grow the heap in proportion to the size of seq, because of the lazy ++.  There are other ways to do this, still using the continuation-passing-style of Found/NotFound, which don't even do that.  If such a solution isn't clear to you, I can provide one on request.

That aside, using an Iterator to build the final collection is a win.

As to variance, I can see no use for it in SeqLikeOps.  Your aim here is to be returning the same collection type wherever possible and the same A always.  Any subtype of F[A] is going to be seqLike and you return F, so variance has no purpose.

Sticking with the direct use of the builder (which may give the best performance), you might want to consider indexOf rather than find.  Then if it returns -1 or 0, you just return the original. Otherwise you can build b using a, seq.take(index) and seq.drop(index + 1) with no recursion or other tricks needed.  Oh, and you forgot sizeHint...

def bTF(a: A)(implicit cbf: CanBuildFrom[F[A], A, F[A]]): F[A] = {
  seq.indexOf(a) match {
    case i if i > 1 => {
      val b = cbf()
      b.sizeHint(seq)
      b += a
      b ++= seq take i
      b ++= seq drop (i + 1)
      b.result
    }
    case _ => seq.repr
  }
}

Of course, what we both really want is a way to minimise traversal.  Scala just doesn't make that as easy as I'd like.   But indexOf does mean only 1 traversal, with no new build, both if the value isn't found or if it is already at the front.  It also means equality tests are only done on one traversal, not two.

After a little more thought, I came up with a variant of the above solution which really only iterates just once.  But it may not be future-proof.

def bTFi(a: A)(implicit cbf: CanBuildFrom[F[A], A, F[A]]): F[A] = {
  val iter = seq.iterator
  val pred = iter.takeWhile(_ != a)
  val b = cbf()
  b.sizeHint(seq)
  b += a
  b ++= pred
  if (iter.isEmpty)
    seq.repr
  else {
    b ++= iter
    b.result
  }
}

Using the iterator this way means only one traversal of the collection.  It works because, when forced by the assignment to the builder, takeWhile(_ != A) has to examine the first element which does equal a.  And any Iterator operation which fetches the next element discards it after use.  So this does work with the absolute minimum of traversal and good economy of space.

I just have a feeling this may rely on an implementation detail that might change.  I will ask around.

EDIT:

Using anything other than next and hasNext on an iterator is considered not safe as the state of the iterator after any other operation is considered an implementation detail.  But hey,  here's an even simpler version:

def bTFi2(a: A)(implicit cbf: CanBuildFrom[F[A], A, F[A]]): F[A] = {
  val iter = seq.iterator
  val pred = iter.takeWhile(_ != a)
  (Iterator(a) ++ pred ++ iter).to[F]
}

which does feel a bit dirty.


Adding and removing classes at different heights on page using jQuery

I know you tagged this jQuery, but I believe that loading in jQuery for this seems like a lot of processing for little benefit, so I decided to write it in a more universal approach, which I think is the main problem with your code.

What you want to accomplish is to have a little script that can be included and will work predictably in as many circumstances without being to specific, so first I went about actually creating a structure:

The element the class will be applied to will have an attribute named data-scroll-group - it will define the group name for these scrollable items.
The elements that your header will respond to will contain an attribute constructed of the above group name and prefixed by data. It's contents will be the classname(s) you want to apply.

This structure looks like this:

This means you could have many scroll groups on the page, allowing you to reuse the code with different aspect and different headers, different responders, etc... It makes your code less connected to the DOM and more based in a structure.

The rest is pretty simple. Use getBoundingClientRect to get the elements position compared to the viewport. I am currently applying the classes using the position of the viewport, but you could simply get the same getBoundingClientRect on the header and add the values together to get a result for your header specifically.

Check out the snippet and tell me if you have any questions about it. You could replace my header.className with jQuery if you wanted - you could replace most of it with jQuery, but I think coupling your code to jQuery has no benefit here, as you want this to work anywhere, and pure vanilla Javascript is about as long.

// This is a handy wrapper function that will return an array of matching element instead of a nodeList
function querySelectorArray(query, root){
  return Array.prototype.slice.call((root || document).querySelectorAll(query));
}

// Get all headers that are designated 'scroll-group'
var headers = querySelectorArray('[data-scroll-group]');

// Loop through the headers
headers.forEach(function(header){
  // Get the name of the group from the headers [data-scroll-group] attribute
  var group = header.getAttribute('data-scroll-group');
  // Get all the sections with a matching data-[data-scroll-group] attribute
  var sections = querySelectorArray('[data-' + group + ']');
  // Create an Event Listener for scrolling
  window.addEventListener('scroll', function(){
    // Declare a lastSection variable that can store the last class that scrolled by
    var lastSection = false;
    sections.forEach(function(section){
      // Get the elements position compared to the viewport
      var offset = section.getBoundingClientRect();
      // If the position is smaller than 0 it has scrolled further than that section
      // The same is true for the scroll being smaller than the negative height - if so, it is out of view.
      if(offset.top < 0 && offset.top > -offset.height) lastSection = section.getAttribute('data-' + group + '');
    });
    // Apply the class to your header
    header.className = lastSection || '';
  })
});
body {
  padding: 0;
  margin: 0;
  padding-top: 20px;
  height: 405vh;
  font-family: Arial, serif;
}
header {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  background: #dd0300;
  -webkit-transition: all 1s;
  transition: all 1s;
  color: #fff;
  padding: 5px 20px;
  box-sizing: border-box;
}
header.blue {
  background: #4e88ff;
}
header.shadow {
  box-shadow: 0 0 20px #000;
}
section {
  box-sizing: border-box;
  width: 100%;
  height: 100vh;
  background: #ccc;
  padding: 20px;
}

  Header

  Scroll Down (header will become blue)

  Scroll Down (header will have a shadow, no longer blue)

  Scroll Down (header will have a shadow and be blue)

  Scroll Down (header will reset)


Length of longest non-repeating substring challenge using sliding window

In this loop, while start < len(s):, the string s is not changing, so the length of the string is not going to change either.  Yet, for each iteration, you will evaluate len(s) in order to evaluate the loop condition.  len(s) is undoubtably a fast operation, but you should still cache the result to avoid the function call every iteration.

limit = len(s)
while start < limit:
    # ...

The loop for i in range(start, len(s)):, you are again calling len(s) for each iteration (of the outer loop).  You could replace this with for i in range(start, limit):, but we will still have a different issue...

You are (mostly) not using i inside the loop; you are using s[i].  And you look up the character s[i] in 3 different places inside the loop.  Instead of looping over the indices, and looking up the character at the index, you should directly loop over the characters of the string.

for ch in s[start:]:
    # ...

Except for that pesky seen[...] = i statement.  You still want the index.  The enumerate() function can be used to count as you are looping:

for i, ch in enumerate(s[start:], start):
    if ch in seen:
       start = seen[ch]+1
       seen = {}
       break
    else:
       seen[ch] = i
       size += 1

Hint

When scanning the string abcdefgdhijklmn, after encountering the second d, you reset to the character after the first d, and continue your scan.  But ...

Do you have to?  Aren’t all the characters between the first d and the second d unique?  Is there any way you could preserve that information, and continue on, without needing to restart with the e?  Maybe you don’t need nested loops!


Split your code into small units

If you split you split your code, (most of the time) you automatically make it easier to read and to test. Also, it allows you to use Python syntactic sugar like list comprehension much more easily.

Modulo operator

As suggested in the comments, the % operator allows you to write things in a smarter way.

Better than abcdef...z

You can use string.ascii_lowercase (after importing string) instead of defining it yourself.

Use join instead of string concatenations

As adviced by the Python Style Guide called PEP 8 :

  In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

This is very straightforward once you have a function to encode a single letter.

At this stage, the code looks like :

def caesar_letter(symbol, key):
    if symbol in LETTERS:
        return LETTERS[(LETTERS.find(symbol) - key) % len(LETTERS)]
    else:
        return symbol

def caesar(msg, key):
    return ''.join(caesar_letter(l, key) for l in msg.lower())

result = [Keycode(key, caesar(message, key)) for key in range(len(LETTERS))]

Another tips

Instead of generating all possible strings only to stop once you've found the one you want, you could generate them at you go. If the first string is the one you want, you'll avoid most of the work.

for key in range(len(LETTERS)):
    code = caesar(message, key)
    d = code.split()
    for word in d:
        if word in picks('wordlist.txt'):
            print('Code : {0:s}\nKey  : {1:}'.format(code, key))
            break

if __name__ == "__main__":

You should move your code actually doing stuff behind an if __name__ == "__main__": guard. I'll let you read more about this.


Sort a linkedlist with 3 elements 0, 1 and 2

The mash-up you continue to have with Objects and primitives is something that is easy to resolve, yet you don't. Is there some reason I am missing why it is important to convert your data to an Integer Object before converting it back to an int?

public void add(Integer item) {

Why can't that be:

public void add(int value) {

???? Your Node class stores it as an int, so there is no reason to do the multiple conversions.

The algorithm you have used for the 'sorting' is similar to what I would do. There are a few nitpicks though (one of them is not so small....):

Use Post-increment and Post-Decrement operators:

a[node.item] = a[node.item] + 1;

and

a[i] = a[i] - 1;

should be:

a[node.item]++;

and

a[i]--;

Why use a linked list at all? Seriously, what does the Node concept buy you? This problem could easily be solved with a primitive array (... or an ArrayList, or LinkedList if you were not using primitives .....). If your data was stored as an array, it would be as simple as:

public void sortZeroesOnesAndTwos() {
    int[] itemcount = new int[3];

    for (int item : data) {
        itemcount[item]++;
    }

    int pos = 0;
    for (int item = 0; item < a.length; item++) {
        while (itemcount[item]-- > 0) {
            data[pos++] = item;
        }
    }
}


Py3 ebay-scraper - Project I need cheap GPU

There are multiple things to improve, let's try to categorize them.

Code Style

there is a number of PEP8 code style violations, specifically:

documentations strings need to be enclosed into triple double quotes, start with a capital letter and end with a dot (reference)
group imports properly

handling a bare exception with except: is considered a bad practice
when you check for a substring to be present in a string, you can use not in, e.g. not 'shipping' in li.text.lower() can be replaced with a more readable:

'shipping' not in li.text.lower()

I would also improve the way you format the search URL, extracting the base url as a constant and using str.format() to insert keywords into the URL:

BASE_URL_TEMPLATE = 'https://www.ebay.com/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw={keywords}&_sacat=0'

def make_search_string(keywords):
    """Constructs a search products string."""
    return BASE_URL_TEMPLATE.format(keywords='+'.join(keywords))

Web-Scraping and HTML Parsing

if you would switch to requests instead of urllib, you then can seriously improve on the performance of making the requests by re-using a session:

  ..if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase.

lxml if used instead of html.parser can provide an HTML parsing performance boost as well
see if using a SoupStrainer to focus your HTML parser on the desired part of the HTML tree only is also applicable in your scenario. It can further speed up the HTML parsing step
using a LBYL approach inside the find_next_page would be a bit more readable and concise:

def find_next_page(soup):
    """
    Finds next page.

    Returns:
        Next page link if exists
        None if next page does not exists
    """
    next_page_link = soup.select_one('a.next')
    return next_page_link['href'] if next_page_link else None

scrape_page() function is overly complicated. For instance, there is a single element with id="ListViewInner" on the page and it does not require a loop to locate this element. And, you can do better in locating elements on the page:

def scrape_page(soup, index):
    """
    Scrapes page for products and save them as a dictionary.

    Returns:
        A dictionary of products
    """
    products = {}

    for produce_index, item in enumerate(soup.select('#ResultSetItems li'), index):
        title = item.select_one('a.vip')
        price = item.select_one(".prc")
        shipping_price = item.select_one('.ship')

        products[produce_index] = {
            'Title': title.find(text=True, recursive=False) if title else None,
            'Price': price.get_text(strip=True) if price else None,
            'Shipping': shipping_price.get_text(strip=True).split()[0] if shipping_price else None
        }

    return products, produce_index

(not tested)

Also note the use of enumerate() for better handling enumeration (thanks @graipher for the idea).


Overall, your naming conventions are pretty good.  I don't feel like I need to go look at mixins themselves to figure out what their purpose is.  The extensive use of extends does concern me, since it can lead to larger CSS rather than smaller like you might expect (see: Mixin, @extend or (silent) class?).

Your %textOnDarkBg and %textOnRedBg extend classes might be redundant.  If you're not already using Compass, you might want to take a look at it.  It offers a function as well as a mixin for setting a good contrasting color against your desired background color (see: http://compass-style.org/reference/compass/utilities/color/contrast/).  Highly useful if your project is intended to be themed.

Generally speaking, using colors for class names isn't very clear unless the content is about color (eg. a color wheel or a rainbow).  What is red for?  Is it for errors?  Or maybe a call to action?  The same thing goes for dark.  Using inverted or closed might be better choices.  If the site's design is already dark, a dark button probably doesn't make much sense.

Your code only allows the user to have exactly 2 colors (default and red), which seems more limited than it needs to be.  You could easily make it very flexible by making use of lists (or maps, which will be in the next version of Sass).  Here's an example from my own project:

//      name     dark    light
$dialog-help:    #2E3192 #B9C2E1 !default; // purple
$dialog-info:    #005FB4 #BDE5F8 !default; // blue
$dialog-success: #6F7D03 #DFE5B0 !default; // green
$dialog-warning: #A0410D #EFBBA0 !default; // orange
$dialog-error:   #C41616 #F8AAAA !default; // red

$dialog-attributes:
    ( help    nth($dialog-help, 1) nth($dialog-help, 2)
    , info    nth($dialog-info, 1) nth($dialog-info, 2)
    , success nth($dialog-success, 1) nth($dialog-success, 2)
    , warning nth($dialog-warning, 1) nth($dialog-warning, 2)
    , error   nth($dialog-error, 1) nth($dialog-error, 2)
    ) !default;

@each $a in $dialog-attributes {
    $name: nth($a, 1);
    $color: nth($a, 2);
    $bg: nth($a, 3);

    %dialog-colors.#{$name} {
        color: $color;
        background-color: $bg;
    }

    %dialog-colors-inverted.#{$name} {
        color: $bg;
        background-color: $color;
    }

    %badge-colors.#{$name} {
        background-color: $color;
        color: $background-color;
    }

    %button-colors.#{$name} {
        @include button($base: $bg) {
            @include button-text($color, inset);

            @include button-states;
        }
    }

    %button-colors-inverted.#{$name} {
        @include button($base: $color) {
            @include button-text($bg, inset);

            @include button-states;
        }
    }

    %button-colors-faded.#{$name} {
        @include button($base: fade($bg, 10%)) {
            color: #CCC;

            @include button-states;
        }
    }
}

In case you're wondering why I'm using multiple classes, I've setup a short demo:  http://sassmeister.com/gist/7792677


Although you are using the using statement with StringReader and StringWriter both the XmlReader and XmlWriter are implementing IDisposable as well, so the usage of it should be enclosed in a using statement too.
Catching an exception without doing anything with it is usually bad practice. You should at least log the exception.
Although you have named your variables and methods well, I am a little bit concerned about the info parameter because it isn't telling anything about what it is.


Convert dictionary of lists of tuples to list of lists/tuples in python


SFTP Ruby script for downloading files from server

One of the core elements your code is missing is object-orientation. Take advantage of Ruby's powerful object model. That alone will vastly improve what you have.

What we're going to do is progressively breakdown everything into chunks of logic and encapsulate these chunks of logic in objects and methods.

Before that, let's go through each line and give feedback if anything seems a little off..

#The host address
HOST = "www.example.com"

It seems you've defined quite a few constants for things which, by nature, will change on a user-by-user basis. They are not constants, they are variables, and so it would be better to use variables.

However, if you do replace them with variables, you will not see any real benefit because the code is largely a procedural script. You have to define the constants/variables directly in the script and load that. You will see the benefit of using variables instead once the arguments and execution of the script are separated.

#Array to hold the file names for easier sorting
files = Array.new

You almost never need to initialize variables like this in Ruby. Look into inject for an alternative.

entries.each do |entry|
  files << entry.name
  files_details << entry.longname
end

This, along with the empty collections you defined above, give the impression that something is wrong. We are storing files and file details in separate arrays. There appears to be a focus on primitives, where we should instead be thinking about how we can encapsulate these in objects. There is nothing wrong with using arrays, but we should think about another approach when it becomes obvious that simple primitives are not providing the functionality we need in a clean way.

download_size = files_details[-1].split(' ')[4].to_i

The drawback of a simple array is made immediately obvious on the above line.

puts "Total #{(files.size.to_i) - 2} backups found on server."

We have littered about puts statements as a way to log the execution of the script. Perhaps we later want to log this to a file instead? That would be a good enough reason to extract it into its own object, and, if we want, later change the method of how we log.

puts "The latest file is : #{files[-1]}, Size : #{(download_size)/1048576} MB"

Another common mistake, though easily fixed, is the magic number 1048576. Give it some kind of meaning by hiding it behind a descriptive variable/constant or method.

# args[0] : file metadata

Along with magic numbers, we have magic indexes being used everywhere. You yourself can see this is difficult to follow and so have created a comment to remind you what you are dealing with. Again, this should be hidden behind a descriptive variable or method.

STDOUT.write "..."

We have now changed from puts to STDOUT.write. I haven't played around with this so unsure as to why, but lets assume this something we can also include in our logging object.

On a side-note - we have lots of comments in this code. As you begin to hide details behind descriptive names, you will see that the value in comments begins to diminish. If you have to litter comments everywhere then perhaps your code isn't readable enough?

Now let's start refactoring. With all that in mind, where do we begin? I can show you the end result, but that isn't useful in learning how to approach this in the future. The focus on creating small, composable objects and methods should be an ever-present design decision when programming Ruby. We are learning to think in objects.

The first thing I would do is throw the entire thing into a single object. Something like:

class RubySFTP
  HOST = "www.example.com"
  # etc

  def start
    files = Array.new
    files_details = Array.new

    Net::SFTP.start #etc
  end
end

This has immediately brought up the concept of RubySFTP. We would use as so: RubySFTP.new.start. It should be noted I could have created a class-method self.start and simply called RubySFTP.start, but that would take away the need to instantiate the object, which we will quickly make use of as we begin to breakdown our logic.

Again, focusing on small, descriptive methods, we can see start does not satisfy this at all. Because the logic is wrapped in a block, it is difficult to modify this to our tastes. For that reason, we will get rid of the block and simply use Net::SFTP.start(HOST, USER, :keys => [SERVER_KEY_LOC]).

That means we would then have:

  def start
    files = Array.new
    files_details = Array.new

    sftp = Net::SFTP.start # etc

    sftp.dir.entries # etc
  end

We are now initializing 3 variables in a single method. This can indicate a kind of code-smell when working with objects. We could clean this up greatly by extracting them into methods of the same name. When we do this it is important we don't reinitialize them every time they are called, so we use memoization.

For example, instead of sftp = [..], we have:

def sftp
  @sftp ||= Net::SFTP.start(HOST, USER, :keys => [SERVER_KEY_LOC])
end

If we do that with those other two variables (files and files_details), our start method now looks like:

def start
  sftp.dir.entries #etc
end

Now it is simply a case of running through things and seeing what we can extract into other methods..

entries = sftp.dir.entries([SERVER_BACKUP]).sort_by(&:name)

..becomes..

def sorted_entries
  @sorted_entries ||= sftp.dir.entries([SERVER_BACKUP]).sort_by(&:name)
end

..

download_size = files_details[-1].split(' ')[4].to_i

..becomes..

def download_size
  @download_size ||= files_details[-1].split(' ')[4].to_i
end

..and so on.. One other note here - though I am using memoization for each of these methods, this is only really a good idea if you are calling that method more than once. We might remove that later on, but noticing where you could benefit from memoization is a good habit to develop.

If we remove all the puts for now, let's see how this has affected the start method..

def start
  sorted_entries.each do |entry|
    files << entry.name
    files_details << entry.longname
  end

  sftp.download!(SERVER_BACKUP+files[-1], LOCAL_BACKUP+files[-1]) do |event, downloader, *args|
    # etc
  end
end

As you can see, this has clearly cleaned things up. We are hiding implementation details behind descriptive methods which is allowing us to think about the program from a better perspective.

Next, the way we are building files and files_details and the way we are accessing them is not that great - files_details[-1].split(' ')[4].to_i. We would much prefer if we could do something like file.download_size instead.

Ideally, what we want to do is wrap the files in our own object so we can build a more useful interface. We could also wrap the collection of files, but for simplicity we still use an array.

That means this:

entries.each do |entry|
  files << entry.name
  files_details << entry.longname
end

Should be, for one, in its own method, and, two, wrap the files (entry). That would look like:

def entries
  sorted_entries.map { |entry| Entry.new(entry) }
end

We would then build an Entry class and define a simple interface to extract what we're looking for. For example:

class Entry
  def initialize(entry)
    @entry = entry
  end

  def name
    @entry.name
  end

  def download_size
    @entry.longname.split(' ')[4].to_i
  end
end

Now our start method simply has:

def start
  sftp.download!(SERVER_BACKUP+entries[-1].name, LOCAL_BACKUP+entries[-1].name) do |event, downloader, *args|
    # etc
  end
end

The next thing we want to remove is those magic indexes (entries[-1]). We could do that by defining a new method on our RubySFTP object called last_entry..

def last_entry
  entries[-1]
end

Simple, but more descriptive. This might not matter so much for -1 as anybody working on this code should know that -1 is the last index, but it is something to keep an eye on.

While we're at it, we'll also extract SERVER_BACKUP+files[-1] and LOCAL_BACKUP+files[-1] into descriptive methods..

def last_entry_remote_path
  SERVER_BACKUP + last_entry
end

def last_entry_local_path
  LOCAL_BACKUP + last_entry
end

Now let's tackle the sftp.download! block.

I will not rewrite the whole thing, but you should consider using a custom handle as detailed in the docs here.

That means you would have a custom handler such as:

class CustomHandler
  def on_open(downloader, file)
    puts "starting download: #{file.remote} -> #{file.local} (#{file.size} bytes)"
  end

  def on_get(downloader, file, offset, data)
    puts "writing #{data.length} bytes to #{file.local} starting at #{offset}"
  end
end

..and your sftp call would look like:

sftp.download!(last_entry_remote_path, last_entry_local_path, progress: CustomHandler.new)

That about ends the core of our refactoring. Let's address the log for a second. Effectively what we want is Logger.log('etc'). We can then change the implementation without affecting the code which uses the logger. Here's a simple logger:

class Log
  def self.log(string)
    puts string
  end
end

You can see now how you can change puts to write to a file instead without actual editing the code which uses the logger.

Now let's fix the constants.

I said before that those constants weren't actually constants. Truth is, they ARE constants in the context of your script because they will not change throughout the execution of it. However, if you extract your script into objects which will be defined in different files, you introduce an element of reusability. You can instantiate your RubySFTP class many times, and pass through different variables as you see fit.

For that reason, we should convert those constants to variables and use as such so we can do:

RubySFTP.start(host, user, server_key, remote_path, local_path)

Though this isn't technically a requirement of your program, using objects has still allowed us to clean things up, and will serve you as it grows.

Before we update our class, we should think about reducing the amount of arguments being passed into it in our newly defined interface above. Generally, 3 arguments is enough. 5 is surely too much. One way to combat this might be to pass in an options hash. Having said that, for simplicity, I am going to keep the 5 arguments.

The long initialize method is a code smell. It doesn't look right for a reason - we are passing in too many arguments.

class RubySFTP
  def initialize(host, user, server_key, remote_path, local_path)
    @host = host
    @user = user
    @server_key = server_key
    @remote_path = remote_path
    @local_path = local_path
  end

  def self.start(host, user, server_key, remote_path, local_path)
    new(host, user, server_key, remote_path, local_path).start
  end

  def start
    # etc
  end
end

With all of those changes, here is the finished code, broken down into a few objects - RubySFTP, Entry, and CustomHandler. Keep in mind that this can be broken down further.

class RubySFTP
  def initialize(host, user, server_key, remote_path, local_path)
    @host = host
    @user = user
    @server_key = server_key
    @remote_path = remote_path
    @local_path = local_path
  end

  def self.start(host, user, server_key, remote_path, local_path)
    new(host, user, server_key, remote_path, local_path).start
  end

  def start
    # prime for extraction!
    Logger.log("Connection to Server successful")
    Logger.log("Total #{entries.size.to_i} backupds found on server.")
    Logger.log("etc")
    Logger.log("etc")

    sftp.download!(
      last_entry_remote_path,
      last_entry_local_path,
      progress: CustomHandler.new
    )
  end

  private

  def sftp
    @sftp ||= Net::SFTP.start(@host, @user, keys: [server_key])
  end

  def sorted_entries
    @sorted_entries ||= sftp.dir.entries([@remote_path]).sort_by(&:name)
  end

  def entries
    sorted_entries.map { |entry| Entry.new(entry) }
  end

  def last_entry
    entries[-1]
  end

  def last_entry_remote_path
    @remote_path + last_entry.name
  end

  def last_entry_local_path
    @local_path + last_entry.name
  end
end

Entry

class Entry
  def initialize(entry)
    @entry = entry
  end

  def name
    @entry.name
  end

  def download_size
    @entry.longname.split(' ')[4].to_i
  end
end

CustomHandler -- from here

class CustomHandler
  def on_open(downloader, file)
    puts "starting download: #{file.remote} -> #{file.local} (#{file.size} bytes)"
  end

  def on_get(downloader, file, offset, data)
    puts "writing #{data.length} bytes to #{file.local} starting at #{offset}"
  end

  def on_close(downloader, file)
    puts "finished with #{file.remote}"
  end

  def on_mkdir(downloader, path)
    puts "creating directory #{path}"
  end

  def on_finish(downloader)
    puts "all done!"
  end
end

Couple of final notes - I might have missed a couple of things during this review and refactoring, but I hope it gives you a good foundation to work from. Secondly, I have left some things for you to clean up yourself so you can apply the advice given -- for e.g. files.size.to_i - 2 should be extracted into a total_files method.

Let me know if you have any questions or have noticed something that doesn't add up and I'll try to help.


Overall, your code seems okay if you have UI elements setting each of these attributes. If you are solely setting these requests in one go with code, having separate mutations is overkill and probably unnecessary.

I think there are some things you can improve though.

Reactivity

The new key-value pairs you add to headers and body are not reactive, because it is not possible to detect addition of new keys in Objects via native methods. I strongly recommend to use Vue.set(..) and Vue.delete(..) when dealing with objects.

Default

You have a reset function that has the same payload as found under the default state. Consider factoring out this part and copying it everytime you need a new state. You need to keep in mind that you require a deep copy to get this to work.

LoC

You can potentially decrease the number of lines of code by creating a generator function that generates your mutations. The thing with a generator function is that it adds an extra layer of abstraction, and will likely make your code less readable than it is now. I don't think factoring out the mutations you have here into a generator function is very helpful either.


Is it correct to use delegates as properties?

Yes, I think this is reasonable code. If you want to set more delegates at the same time or unsubscribe a delegate, events would be more appropriate. But if you don't want to do that, delegate properties are fine.

There are some things to think about though:

The code you use to invoke the delegates is not thread-safe. If one thread called WriteLogMessage() and another thread set logOutput to null at the same time, you might get a NullReferenceException. The thread-safe version would be:

var logOutputTmp = this.logOutput;
if (logOutputTmp != null)
    logOutputTmp(string.Format(format, args));

Consider using automatic properties. They do the same thing as your code, only with less writing. Also, get accessor is usually written before the set accessor, but that's only a minor style issue.

public Action<string> LogOutput { get; set; }

Do you need the public setters and the parameterless constructor? If you expect that both delegates will be always set at construction, then it's better to make that clear and have only one constructor and no public setters.


Select a list from a 2D list, take the last item from its nearest non empty left neighbour and put it at its head

First of all, there is no need for pull's first parameter to be Maybe [[Int]]. More on that later. Also, it will get easier if we switch the parameters. Also more on that later.

So let's start with that modification:

pull  :: Int -> [[Int]] -> Maybe [[Int]]
pull 1 _      = Nothing
pull 2 ([]:_) = Nothing
pull _ [_]    = Nothing

As you can see, I don't use names for things I'm not interested in. This makes it possible to focus on the interesting parts, e.g. the 1 and 2 matches, and the single-element match in the last line.

Now, your other definitions get a lot easier if you don't use guards, but pattern matching instead. If we rewrote the next pattern with your style, we end up with:

pull n ([]:xs:xss) =
  | p' == Nothing = Nothing
  | otherwise     = Just ([] : p'')
  where
    p' = pull (n-1) (xs:xss)
    p''= fromJust p'

Which is slightly easier due to the missing Justs in pull (n-1) …. However, with a case … of …, it's a lot more succinct:

pull n ([]:xss) = case pull (n-1) xss of
  Nothing -> Nothing
  Just p  -> Just ([] : p)

This "if there is Nothing return nothing, otherwise change the Just value" slightly pattern is so common, that there is even a function for that, fmap, which you can think of as

fmap :: (a -> b) -> Maybe a -> Maybe b
fmap _ Nothing  = Nothing
fmap f (Just v) = Just (f v)

So we can shorten that whole case to

pull n ([]:xss) = fmap ([]:) (pull (n-1) xss) -- *

We continue for the following cases:

pull 2 (xs:ys:xss) = Just ((init xs) : ((last xs):ys) : xss)
pull n (xs:[]:xss) = case pull (n-1) (xs:xss) of
  Nothing -> Nothing
  Just p  -> Just ((head p) : [] : (tail p))

pull n (xs:xss) = fmap (xs:) (pull (n-1) xss) -- *

Note that in both cases marked with -- *, you pattern matched on xs2:xss and used xs2:xss. That's not necessary.

So all patterns are:

pull  :: Int -> [[Int]] -> Maybe [[Int]]
pull 1 _           = Nothing
pull 2 ([]:_)      = Nothing
pull _ [_]         = Nothing
pull n ([]:xss)    = fmap ([]:) (pull (n-1) xss)
pull 2 (xs:ys:xss) = Just ((init xs) : ((last xs):ys) : xss)
pull n (xs:[]:xss) = case pull (n-1) (xs:xss) of
  Nothing -> Nothing
  Just p  -> Just ((head p) : [] : (tail p))
pull n (xs:xss) = fmap (xs:) (pull (n-1) xss)

Now that you can see all cases, it should be obvious that your missing at least one, namely the one for the empty list pull 0 []. Also note that using last and init isn't very efficient, since you need to traverse the list twice. You could write a function like

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

which returns both the init and the last element. But that's left as an exercise.

TL;DR

use case … of … (or pattern matching) instead of guards if you want to use the matched value either way (or use pattern guards).
make sure that you handle all cases
use Maybe on outputs; if your function cannot do something sensible with Maybe inputs, don't use it, that's what >>= is for.


Get exactly `n` unique randomly sampled rows per category in a Dataframe

Have you tried using DataFrameGroupBy.filter()  (I don't have recent pandas on this machine so I can't test it).
n = 4
df = pd.DataFrame({'category': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 1],
                   'value' : range(12)})

# sample exactly x rows per category
df = df.groupby('category').filter(lambda x:x.size >= n).sample(n)


A sleep primitive for CUDA device-side code

If, as Robert Crovella suggests, the clock64() calls don't get optimized away, then this should be enough:

using clock_value_t = long long;

__device__ void sleep(clock_value_t sleep_cycles)
{
    clock_value_t start = clock64();
    clock_value_t cycles_elapsed;
    do { cycles_elapsed = clock64() - start; }
    while (cycles_elapsed < sleep_cycles);
}


You're jQuery can be written in one simple function as a catch all for the entire navigation. As you stated you think it could be condensed, you'd be right. As a rule of thumb if you see yourself writing the same thing over and over you should be able to cut it all down into one function.

Starting with one of your methods I'll step through it to show how you can condense this and make it more efficient.

$("ul#topnav li.home").hover(function() { //Hover over event on list item
    $(this).css({ 'background' : 'url(images/tab_hobt.png) no-repeat top left'}); //Add      background color + image on hovered list item
    $(this).find("span").show(); //Show the subnav
}, function() { //on hover out...
    $(this).css({ 'background' : 'none'}); //Ditch the background
    $(this).find("span").hide(); //Hide the subnav
});

First things first, you're creating no less than 5 jQuery objects for each time someone hovers and moves out of a menu item.

Two things on this :

Don't use jQuery where you don't need it
Cache jQuery objects for re-use
Make your code scalable

Don't use jQuery to...

Modify CSS unless it is absolutely required (ie CSS alone can't achieve what you want). In this case CSS can handle you're requirements easily.

If you find you need to change a lot of CSS and would like this CSS to change due to a jQuery or javascript event. use .addClass() and .removeClass(). Applying the styles in CSS rather than in jQuery. This is far more efficient in terms of code and your eyes. :)

Cache your jQuery objects

$(this).css(...);
$(this).find("span");

would be better served with one cached object

var self = $(this);

self.css(...);
self.find("span");

Make your code scalable

By this I mean using techniques that allow you to do some relatively advanced things without the need for re-writes / re-factors in the future. One of these is to bind events to a lower level element with .on rather than .hover or .click. If in the future you modify the menu for some reason with jQuery/JS and DOM elements are removed / re-added, event bindings will be lost. Using .on avoids this problem.

Refactoring your code

I've deliberately not included any CSS changes in this code as you can and should include these in your CSS rather than dynamically with jQuery / JS. I have however added and removed a class, this should contain all the style changes required for the mouseenter and mouseleave events.

$("#topnav").on({
    mouseenter : function(event)
    {
        var self = $(this),
            menu = self.find("span");

        // Check if a menu is present and show it
        if (menu.length > 0)
        {
            menu.show();

            // Add an is-active class to the menu link
            menu.siblings("a").addClass('is-active');
        }
    },
    mouseleave : function(event)
    {
        var self = $(this),
            menu = self.find("span");

        // Check if a menu is present and hide it
        if (menu.length > 0)
        {
            menu.hide();

            // Remove is-active class on the menu link
            menu.siblings("a").removeClass('is-active');
        }
    }
}, "li");

I hope this helps you!


Personally I don't like multiples if statements inside a for, here is my suggestion:

def handler_option_c(t, b):
    t.pencolor("brown")
    t.forward(100) # Change this to modify the size of the tree

handlers = { "c" : handler_option_c, ....

And you do the same for the other options, and then on your main

for c in code:
    handlers[c](t, branch)

Or you can put that on a lambda also