So this all looks pretty good, with not much to review. I didn't see the previous question, so I will throw my two cents in here.

You define the following at the top of your file:

SIGNS = ("rock", "paper", "scissors")
VERBS = ("crushes", "covers", "cut")
YES = ("yes", "y")

which is fine. However in all the classes where you use these variable you denote them with the global keyword. This isn't code breaking, but it is unnecessary. The global key word is used for global variables. What you are using is global constants that are defined at module scope, so you can get rid of those redundant lines.

It was suggested in the comments that you replace the print_results function by __str__, but I would actually suggest replacing it by __repr__. In cases where __str__ is not defined __repr__==__str__ anyways. So:

def __repr__(self):
    return "\n".join(
        ["Games played: %d"%self.rounds,
         "Games won: %d"%self.wins,
         "Games lost: %d"%self.losses,
         "Games drawn: %d"%self.draws,
         "Total played: %d"%self.rounds_total,
         "Total won: %d"%self.wins_total,
         "Total lost: %d"%self.losses_total,
         "Total drawn: %d"%self.draws_total])

This will allow you to print the object nicely with print counter.

These are all ultra minor things now:

The block

def __eq__(self, other):
    try:
        if self.sign == other.sign:
            return True
    except AttributeError:
        pass
    return False

has a redundant pass and redundant branch. This could be condensed to:

def __eq__(self, other):
    try:
        return (self.sign == other.sign)
    except AttributeError:
        return False

In a similar vain, there is no need to branch in __gt__ method:

def __gt__(self, other):
    return (self.sign == "rock" and other.sign == "scissors" or
            self.sign == "scissors" and other.sign == "paper" or
            self.sign == "paper" and other.sign == "rock")

and the __lt__ method:

def __lt__(self, other):
    return not self.__gt__(other)

is both redundant and incorrect (as pointed out in the comments, this is actually a less than or equal to that is written here, as any value that is not greater than will return true) and can be removed (the default version calls __gt__ and should handle your problem fine).

Finally for clarity I would define VERBS as a dictionary. It is more code, but it is also more readable:

VERBS = {"rock":"crushes", "paper":"covers", "scissors":"cut"}

this allows you to do the following in the main function:

verb = VERBS[player.sign]

and

verb = VERBS[computer.sign]


Bash script that searches for directories with files called package.json and install dependencies

Working with $@

If some command line arguments contain spaces this won't work:

DIRS=(lib tools $@)

In 99% of use cases you probably want to double quote $@.

Unnecessary work

It's unnecessary to execute $(pwd) in a loop if the directory doesn't change in between cycles:

  DIRS[i]="$(pwd)/${DIRS[i]}"

A simple fix is using $PWD instead, which will not incur command execution:

  DIRS[i]="$PWD/${DIRS[i]}"

Building arrays

This is not very idiomatic:

DIRS=(lib tools $@)
for i in "${!DIRS[@]}";
do
  DIRS[i]="$(pwd)/${DIRS[i]}"
done

It would be better like this:

DIRS=()
for i in lib tools "$@"
do
  DIRS+=("$PWD/$i")
done

cd in a sub-shell

This works because you made sure the paths are absolute paths:

while IFS='' read -r line; do
  echo "Installing dependencies for $line"
  cd "$line" && yarn
done < <(
  find "${DIRS[@]}" -iname 'package.json' -not -path '*/node_modules/*' -exec dirname {} \;
)

If the paths had been relative, this wouldn't work.
That's why you built DIRS, a considerable extra effort.
There's a way to make this safe even with relative paths,
by wrapping cd && yarn in a sub-shell:

while IFS='' read -r line; do
  echo "Installing dependencies for $line"
  (cd "$line" && yarn)
done < <(
  find lib tools "$@" -iname 'package.json' -not -path '*/node_modules/*' -exec dirname {} \;
)

Without DIRS, the script can be shorter and simpler.

find ... -execdir

If your version of find supports the -execdir option,
and if you don't mind not printing the "Installing dependencies for ...",
then you can further simplify the script:

#!/bin/bash

set -e

# Install dependencies in directories with a package.json file
find lib tools "$@" -iname 'package.json' -not -path '*/node_modules/*' \
  -execdir yarn \;

# Do current directory
echo "Installing dependencies for current directory"
yarn

If you really do want to print that informational line,
that's possible, though not very sexy:

find lib tools "$@" -iname 'package.json' -not -path '*/node_modules/*' \
  -exec printf Installing dependencies for \; -execdir pwd \; -execdir yarn \;


XOR instead of MOV
In your main subroutine, you move the value 0 into two registers.
A more efficient way to do that is to XOR the register with itself, like so:
xor r3, r3
Unnecessary branching
In your main subroutine, you branch over to the loop subroutine.
Since the loop subroutine is right beneath the main subroutine, you do not need a branch there since execution will just "fall through" to the loop subroutine.
Labels
I'm not sure how this works in ARM, but you seem to be using only global labels in your program, when there should be some local labels.
Local labels exist inside global labels, and they act kind of like a subroutine for a subroutine.
A change I might make is make the end_loop label a local label.
For more information on local labels, see here
For information on the syntax of a local label, see here
Disclaimer: I am not too familiar with ARM assembly, although I am familiar in other assemblies; some things I tell you might not work


Limiting function invocations using closures

This is called a debounce function, and you are doing it ok.

Here are some small improvements I can think of.  Nothing big:

Initialise lastInvokedTimestamp, so that it'll never be undefined.
Cache current time.
Track the threshold of next call instead, so that it becomes one addition per interval instead of one subtraction per entrance.
Pass arguments into the debounced function.
Simplify test cases's setTimeout.

function rateLimit ( func, interval ) {
  var nextInvokeTimestamp = 0;

  return function(){
    var now = Date.now();
    if ( now < nextInvokeTimestamp  ) {
      return console.log('too early!');
    }
    nextInvokeTimestamp = now + interval;
    console.log('go ahead!');
    return func.apply( this, arguments );
  };

}

// run test cases
function logHello( message ){
  console.log( message || 'Hello!' );
}
limitedDoSomething = rateLimit( logHello, 500 );
limitedDoSomething( "Welcome!" ); // should log “Welcome!”
setTimeout( limitedDoSomething, 400 );  // should not log “Hello!"
setTimeout( limitedDoSomething, 500 );  // should log “Hello!"

You may notice that David Walsh is doing it quite differently.

Using setTimeout defers the actual call to a later event loop, instead of current event, to let things settle down a bit.
Because of the delay (which can be as low as 0, i.e. 4ms), he can call with the latest arguments in the interval, for example the latest mouse move. A bigger interval lets you catch more calls, with a slower respond.

It is not better or worse; it's just a different speed bump for different needs.
If your requirement is simply "reduce multiple calls into one", you are doing fine.


Is this method really a problem? Why are you worried about it? There are some small changes you can make, but they do not have much of an impact on the performance of the routine (if it is slow...).

About the only things I can think of improving are:

you check whether the savedInstanceState is null twice, and those two checks can be merged in to one...
you create a new FilterFragment instance, and you either add it to (if it is not there), or replace it (if there already was one). Thus, you have the filterFragement, and you do not need to findFragmentById(...) since you should be finding the fragment you just put in there....

Here's your method with the lines commented out that I don't think you need, and also two new lines marked with //**ADDED**

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_3_filter);

    //if (savedInstanceState == null) {
    //    args = getIntent().getExtras();
    //} else {
    //    args = savedInstanceState.getBundle(Keys.args);
    //}

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    filterFragment = new FilterFragment();
    //filterFragment.setArguments(args);
    if (savedInstanceState == null) {
        filterFragment.setArguments(getIntent().getExtras());  //**ADDED**
        fragmentTransaction.add(R.id.containerOfFilterFragment, filterFragment);
    } else {
        filterFragment.setArguments(savedInstanceState.getBundle(Keys.args));  //**ADDED**
        fragmentTransaction.replace(R.id.containerOfFilterFragment, filterFragment);
    }
    fragmentTransaction.commit();

    //filterFragment = (FilterFragment)
    //        getSupportFragmentManager().findFragmentById(R.id.containerOfFilterFragment);
}


Tabbed navigation to hide and show pages

It's hard to give an exact answer without knowing your HTML structure, but if we assume that:

Your tab headers (apparently li-elements with classes like .search_locations and ids like #search_distributors) have some common class, such as .tabheader.
Each of your tabs is wrapped in an element with a common class, such as .tab.
You can add a HTML5 data- attribute on your tab headers to designate the tab whiches header it is.

Assumptions 1. and 2. are necessary so that you can use a common function for all the tabs without writing what is essentially the same code thrice.

Number 3. could be implemented like this:

Search locations

Then you can reduce your CoffeeScript to

$('.tabheader').on 'click', (e) =>
    e.preventDefault()
    tabId = $(e.currentTarget).data('tabId')
    $('.tab').hide()
    $('#' + tabId).show()
    $('.tabheader').removeClass('active')
    $(e.currentTarget).addClass('active')

See my jsFiddle.

If you, some strange reason, would not be able to alter your HTML in any way, your code would still be easier to maintain if you wrote a common function for displaying a tab, then called it for each of the click events:

showTab = (e, tab, header) ->
    e.preventDefault()
    allTabs = [
        '#distributor_location_search_filter_form',
        '#distributor_location_search_container',
        '#international_distributors_location_container',
        '#all_distributors_location_container'
    ]
    $(allTabs.join(',')).hide()
    if tab instanceof Array
        tab = tab.join(',')
    $(tab).show()
    allHeaders = [
        'li.search_locations',
        'li.international',
        'li.all_distributors'
    ]
    $(allHeaders.join(',')).removeClass('active')
    $(header).addClass('active')

$('#search_distributors').on 'click', (e) =>
    showTab(e, ['#distributor_location_search_filter_form', '#distributor_location_search_container'], 'li.search_locations')

$('#international_distributors').on 'click', (e) =>
    showTab(e, '#international_distributors_location_container', 'li.international')

$('#all_distributors').on 'click', (e) =>
    showTab(e, '#all_distributors_location_container', 'li.all_distributors')

See my other jsFiddle.

Note that there are also multiple jQuery plugins for tab behavior, such as one in Bootstrap and jQuery UI.


Project Euler #4 "Largest Palindrome product" in Python

You are recomputing the product upper * lower three times:

    while upper >= lower:
        if upper * lower <= largest_palindrome:
            break
        if is_palindrome(upper * lower):
            largest_palindrome = upper * lower

You should save it in a variable:

    while upper >= lower:
        product = upper*lower
        if product <= largest_palindrome:
            break
        if is_palindrome(product):
            largest_palindrome = product

Also, how about this version of is_palindrome:

def is_palindrome(n):
  s = str(n)
  return (s == s[::-1])

Update

Replace your loops with for and xrange:

largest = 0
for lower in xrange(999,99,-1):
    for upper in xrange(999,lower-1,-1):
        ...

It makes the intent of your code a lot clearer, and it is easier to correctly write the loop.

(The following is note quite right)

Finally, if upper*lower <= largest_palindrome, you actually return from the function:

        if upper * lower <= largest_palindrome:
            return largest_palindrome

The return will essentially break out of both while loops. Using just break will only break out of the inner loop. Of course, the remaining cases will execute very quickly since they will only last one iteration of the inner loop, but it is still a good optimization to know about.


Find the longest path in a matrix where each step has entries that differ by 1

So a couple of remarks:

If I understand the required solution, you seem to have a bug, e.g. longestWorm(new int[][]{{0, 1, 3}, {9, 8 ,7}, {4, 5, 6}}) returns 10, although there are only 9 numbers. The wormcount calculation is then wrong because you increment the counter twice instead of once. Recursively defining the problem, you can say that the length of a path is the length of the current cell (which is one), summed by the length of the remaining path. Which would make the length function something like:

private static int wormCount(int[][] mat, int i, int j){
    if (i < mat.length - 1 && mat[i][j] == mat[i + 1][j] + 1) {
        return 1 + wormCount(mat, i + 1, j);
    }
    ....
    return 1;
}

This also makes the base case very clear. You also do not necessarily need to pass the count variable. Only perhaps if you would want to make it a tail-recursive function, but AFAIK in Java it will not help you eliminate a stack overflow.

The problem is defined as finding a path of increasing order, but your code seems to calculate it the other way around. Not wrong, but slightly confusing.
In the longestWorm function, you calculate the same function twice. This is not necessary:

max = Math.max(max, wormCount(mat, i, j, 0));

You could save it in a local variable if it helps the readeability.

I do not know the optimal way to solve this problem. My guess would be you could at each index calculate the path length, and save it in a table. Because each value is unique, it could simply be a map between the value and the length of the path starting at that value (else, it could simply be a key generated using the indices i and j). Before calculating the length for a particular value (or starting at a particular index), you first look if you already calculated it, which you could then reuse.


Output string length and classical Fibonacci sequence in a web page

Getting the length of a string

You split the string into characters and then you count the array's length. While this works, there's an even simpler way of doing it, using the length property of a String:

const length = msgDiv.value.length;

Changing getStrLen

You can cache the DOM elements. Then you don't need to re-query them, each time the function is called:

const strlenInput = document.getElementById('textbox1');
const strlenDisplay = document.getElementById('msg');

const getStrLen = () => {
    strlenDisplay.textContent = strlenInput.value.length;
}

Now this alone won't work in the head-element of your document, as both elements are not available yet. You can either:

wait until the DOM is ready to run that script, like document.addEventListener('DOMContentLoaded', function(event) { […] }, or
place the Javascript at the end of your page instead

This is explained in detail here: $(document).ready(function(){}); vs script at the bottom of page.

Creating the Fibonacci sequence

genFibonacci() takes one parameter, so you pass an unused parameter, when calling the function recursively:

genFibonacci(times - 1, false);

There's a flaw in your logic: You don't reset the values each time the button is clicked. If the user's input is 1 and they hit the generate button 5 times, the result is not 0 but:

 0 1 1 2 3

With this in mind, let's try to change your algorithm, that it won't rely on external variables. We also don't necessarily need recursion here:

const getFibonacciValues = (n) => {
    const values = [];

    if (n >= 1) {
        values.push(0);
    }

    if (n >= 2) {
        values.push(1);
    }

    for (let i = 2; i < n; ++i) {
        values.push(values[i - 2] + values[i -1]);
    }

    return values;
}

Now we have a function, which purpose is solely to create the values. It doesn't have a clue, how you're going to output them. outFib() is doing this for us now:

const outFib = () => {
    const n = fibInput.value;
    const values = getFibonacciValues(n);
    fibDisplay.textContent = values.join(', ');
}

Now, this still has flaws, so we add a little bit of validation at least:

use parseInt to parse the value
check whether the input is at least 1
check whether the input is a number

The final result could look like this:

const fibButton = document.getElementById('fibClick');
const fibInput = document.getElementById('fibText');
const fibDisplay = document.getElementById('fibseq');

const getFibonacciValues = (n) => {
    const values = [];

    if (n >= 1) {
        values.push(0);
    }

    if (n >= 2) {
        values.push(1);
    }

    for (let i = 2; i < n; ++i) {
        values.push(values[i - 2] + values[i -1]);
    }

    return values;
};

const outFib = () => {
    const n = parseInt(fibInput.value);

    if (n < 1 || isNaN(n)) {
        fibDisplay.textContent = 'Please insert a number greater than 0';
        return;
    }

    const values = getFibonacciValues(n);
    fibDisplay.textContent = values.join(', ');
};

fibClick.addEventListener('click', outFib);
<input type="text" id="fibText">
<button id="fibClick">Generate Fibonacci Sequence</button>

Further improvements

This will fail for large inputs – try 2000 for example. You'll get a lot of Infinity.

You can take a look into bigNumber.js or you can set an upper limit, like if (n > 1000) { fibDisplay.textContent = 'Too large'; return; } or you could store all values for your maximum n.

Calculating all numbers over and over again is some overhead you could avoid. You could cache already calculated values, and only add new values if n > values.length. Alternatively you can store all numbers beforehand, which is an increase in memory usage, but your runtime becomes incredibly fast, as all you have left is:

const values = [0, 1, 1, 2, 3, …];
const output = values.splice(0, n);


LeetCode: Number of steps to reduce a number to zero C#

Not much to say for such a simple algorithm.  However there is an optimization that you could employ.  Check for odd instead of even, then convert to even.  Then divide by 2.  At most this cuts your iterations by half.

It would look like this:

public int NumberOfSteps(int num)
{
    int count = 0;
    while (num != 0)
    {
        if(num % 2 == 1)
        {
            num -= 1;
            ++count;
        }
        if(num > 0)
        {
            num /= 2;
            ++count;
        }
    }
    return count;
}


Density-based clustering of image keypoints

Just for correctness and not for performance reasons:
You nowhere mark any key as being clustered. As a result, keys may be clustered multiple times. In case all keys shall be clustered maximum one time, one may do the following modifications to the code above:

Add a following first line

clustered[i] = true;

behind

// add P to cluster c
clusters[c].push_back(keypoints->at(i));

and a following second line

clustered[neighborPts[j]] = true;

after

clusters[current_cluster].push_back(keypoints->at(neighborPts[j]));

Concerning the second line, make sure that it is inserted within the if-statement.


Group collections by their elements property

If they all implemented a common interface then you could simplify it.

 public interface ICustomerItem
    {
        Guid CustomerId {get;}
     }

Concat the the items together

var items = invoices.Concat(payments).Concat(orders);

Then project them into your class

 items
.GroupBy(x => x.CustomerId)
.Select(g =>
          new CustomerInfo(g.Key,
                 g.OfType<Order>(),
                 g.OfType<Payment>(),
                 g.OfType<Invoice>())


Java class: for getOrder, getData, updateData operation

(Please post working code next time.)

So first off, there are imports missing, so this doesn't compile as it
is, and the variable mark doesn't exist.

import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Comparator;

Either you import by name, or the whole package, just stick with one.

...
        if(counter == order) {
            return data;
        }
...

Then you should generally specify the visibility on all things,
otherwise you end up with package visibility, which is probably not what
you want.

public class App {
...
private Set<Integer> appData;

Use of generics is good, the constructor is okay except for the
unnecessary manual comparison.  This should be either using
TreeSet.descendingSet, or Comparator.reverseOrder, e.g.:

public App(List<Integer> data) {
    this.appData = new TreeSet<Integer>(Comparator.<Integer>reverseOrder());
    appData.addAll(data);
}

Some whitespace is also off and the spelling of methods should be
consistent, i.e. getdata should be get getData and updatedata
should be updateData as is mentioned in your spec.

That just to get you started here.


One file vs. many partials
My first comment is about the ProjectExtensions class itself. I would prefer keeping it together. If for any reason you want to make some consistent change in the extensions it's very hard to do that when they're scattered all over the place.
When to use extension methods
This is the main question: should I do this? My opinion: no. At least not to that extent.
When extension methods were unleashed in c# 3.0, the whole developer community (including me) went on a razzle with them and started creating extensions for just about anything. A bit like the days when text processors with more than one font entered the market. Suddenly we saw club bulletins appear that looked like (and violated) this:

The trouble is that with extension methods it's too easy to 'add' methods to a very general type while the scope of these methods is more restricted than the scope of the type itself, even within one namespace. For example, I had extension methods on string that I decided to ditch again later, when wisdom finally took over.
This phenomenon also applies to your extension methods. They are defined on IDbContext. Now I don't know how many IDbContext classes you intend to implement, but who says they're all going to have Project?
This means that you'd have to confine the extension methods to contexts knowing about Project. This, in turn, may imply that you may as well replace the extension methods by instance methods in one specific context class.
When create a method at all?
That's another question. No matter if it's an extension method or an instance method. Is the task even worth creating a generally accessible method? I specifically frown upon this GetProjectsFormatted method. To me, this looks like something that should probably be a service method. Remember the single responsibility principle? A context shouldn't have any knowledge about any format. That's a (domain) service's responsibility. It may make the context with all its paraphernalia less applicable (or targeted) to other parts of the application or other assemblies. Or, worse, you may get tempted to enter a range of FomatXyz methods to meet other specifications.
Alternatives
Finally, there are other ways to deal with this 'soft delete' problem, i.e. the problem that records are deactivated rather than physically deleted, while the deactivated records shouldn't be displayed. Of course (and that justifies your [extension] method efforts) you don't want to add where IsActive to each and every query.
But extension or instance methods supplying a pre-filtered set aren't enough either! Any old time you apply an Include you'll be in trouble.
var projects = db.GetProjects.Include(p => p.Members);

Of course this includes all members, active or not. And (grief), Includes can't be filtered.
Fortunately, there are better solutions for this. The most viable one, in my opinion, is EntityFramework.DynamicFilters, by which you can define filters that will be applied any time a type is queried, also in Includes.
A very technical, but more complete, solution is the one proposed by the EF team's product owner himself, the code and explanation of which is available here. More complete, because it also redirects deletes to setting a delete flag instead of physical deletes.
Another, pretty elegant, solution, also redirecting deletes, is here. But it uses inheritance, so it may not play nice with other inheritance schemes.


Community wiki because the root of the answer (use an MLT to copy the data) was already in the comments. Shoutout to dnoeth and Der Kommissar for already explaining most of this in the comments.

Kendra Little has a great article on this topic. In general, the ALTER TABLE statement can't be assumed to be minimally logged, in particular if it is a size-of-data operation, meaning that

each record in the table must be updated

When something is a size-of-data operation is a little outside the scope of this question, and you can find good resources for it online, but in general, if changing the column metadata also requires updating the table itself (which making a column NOT NULL is) then you're going to hit this bucket. As Kendra mentions, this can be really bad:

Once you get to the point where you can alter the data, you run into a different problem:

Altering the column uses a huge amount of transaction log space
It’s reaaaalllll slow

This is because changing from INT to BIGINT is a “size-of-data” operation.
SQL Server has to go through and update Every. Single. Row.
And log it.
And SQL Server has to reserve extra space in the log in case it needs to roll back (because that will require additional logging).
If you get this far without thinking about how much log file you’re going to need and you run out, then things get extra slow, because most of that rollback’s going to be done by just one thread.

The solution is, not surprisingly, also called out in that article. You're likely going to need to take a downtime, and you're likely going to need to create a new table, copy all the data, and then swizzle everything to be pointing in the right direction.
The most important feature that this relies on is Minimal Logging (required reading). If/when you achieve Minimal Logging, you're likely going to be able to eliminate your batching (or at least get rid of a lot of it). Additionally, you can likely do it without too much of a downtime if you use Snapshot Isolation (also required reading). In that scenario, you just start dumping data into a copy of the table to get most of it in, then take a downtime, clean up any discrepancies that happened during that time, swap the tables, fix any foreign keys, etc etc, then come away from downtime.
If you find yourself still in need of batching, you're going to be better off first getting a list of keys to process, and looping over that instead of using TOP or other techniques (likely gets you better table access and will avoid any sorts).
You'll also want to keep your recovery model in mind; if you have a FULL recovery model then you will need a manual full-backup, then switch to SIMPLE, do the work, switch back, and backup again. This is because minimal logging requires SIMPLE recovery mode.


Is this a conforming implementation of duration_cast?

I can't say for sure about the internal logic but I can point some problems or things that could be improved in your piece of code:

First of all, typename is missing before the names, making your code non-working with some compilers. I would also use using instead of typedef, but that's a mere matter of taste. Updated version:

using ratio = typename std::ratio_divide<Period, typename ToUnit::period>::type;
using common_type = std::common_type<typename std::common_type<typename ToUnit::rep, Rep>::type, intmax_t>::type;

std::common_type is variadic. You don't have to bother with nested std::common_types:

using common_type = typename std::common_type<typename ToUnit::rep, Rep, intmax_t>::type;

I know that MSVC has not a full support for constexpr, but duration_cast is supposed to be constexpr (it should work with the November 2013 CTP though):

template<typename ToUnit, typename Rep, typename Period>
constexpr ToUnit duration_cast_2(const std::chrono::duration<Rep, Period>& right)
{
    // ...
}


You don't have to distinguish if array.length if even or odd.
Just do:

    int[] right = new int[array.length/2];
    int[] left = new int[array.length - array.length/2];

It will make the two tables to have exactly array.length items together, divided by half as precisely as possible.


You can use a regular expression to match a range of repeated characters and replace it with the character and the count:

public static string Compress(string str) {
  return Regex.Replace(str, @"(.)\1*", m => m.Groups[1].Value + m.Value.Length);
}

If that is better or not is up for debate, but it is at least a lot shorter.

You can also make it simpler using a regular loop and access the characters by index instead of using a StringReader. That makes it easier to compare the characters next to each other:

public static string Compress(string str) {
  StringBuilder builder = new StringBuilder();
  for (int i = 1, cnt = 1; i <= str.Length; i++, cnt++) {
    if (i == str.Length || str[i] != str[i - 1]) {
      builder.Append(str[i - 1]).Append(cnt);
      cnt = 0;
    }
  }
  return builder.ToString();
}


Inverse Document Frequency (IDF) implementation

The layout and naming conventions look good.  Thank you for that.

_InverseDocFreq should be renamed _inverseDocFreq to keep with conventions and also stay consistent in your code.

I also think _terms should be an IList.  This just eliminates a bunch of the unneeded operations.

you are missing a ; after this statement in ProcessDocument

return doc.Split(' ')
            .GroupBy(word => word)
            .OrderByDescending(g => g.Count())
            .Select(g => g.Key)

I'm not sure why you are using MyInit, the constructor is the only place that is called.  I would move the code into the constructor, then you can make _numTerms, _terms, and _docFreq readonly.

I would rename _wordsIndex to _wordIndex because it is really only and index for each word.  I would also move the new into the constructor.

The for loop where you are filling the terms into the _wordIndex dictionary could be moved to its own method, I called it FillWordIndexWithTerms(), and it looks like

private void FillWordIndexWithTerms()
{
    for (var termIndex = 0; termIndex < _terms.Count; termIndex++)
    {
        _wordIndex.Add(_terms[termIndex], termIndex);
    }
}

I renamed i to termIndex to give it a bit better meaning in your code, and make it easier to read.

The constructor now looks like

public IDFMeasure(string[] documents)
{
    _docs = documents;
    _numDocs = documents.Length;

    _terms = GenerateTerms(_docs);
    _numTerms = _terms.Count;

    _docFreq = new int[_numTerms];
    _wordIndex = new Dictionary<string, int>();

    FillWordIndexWithTerms();
    GenerateDocumentFrequency();
    GenerateInverseDocfrequency();
}

In the GenerateTerms method, I would change the input parameter to an IEnumerable.  You could also use a method group in the linq statement, you don't need the lamba.  The function can also be made static.

private static IList<string> GenerateTerms(IEnumerable<string> docs)
{
    return docs.SelectMany(ProcessDocument).Distinct().ToList();
}

ProcessDocument looks good.

GetTermIndex looks good.

Log could be made static.  Other than that it looks good.

I would move the inner ForEach in GenerateDocumentFrequency to its own method.  This will reduce nesting.

private void GenerateDocumentFrequency()
{
    _inverseDocFreq = new float[_numDocs][];

    for (var i = 0; i < _numDocs; i++)
    {
        _inverseDocFreq[i] = new float[_numTerms];

        var curDoc = _docs[i];
        var freq = GetWordFrequency(curDoc);

        CalculateTermFrequency(freq);
    }
}

The ForEach can also be simplified using Linq.

private void CalculateTermFrequency(Dictionary<string, int> freq)
{
    foreach (var termIndex in freq.Select(entry => GetTermIndex(entry.Key)))
    {
        _docFreq[termIndex]++;
    }
}

In GenerateInverseDocfrequency I would rename i to currentDocument.  The nested ForEach should be moved to its own method, CalculateInverseDocumentFrequency.

private void GenerateInverseDocfrequency()
{
    for (var currentDocument = 0; currentDocument < _numDocs; currentDocument++)
    {
        var curDoc = _docs[currentDocument];
        var freq = GetWordFrequency(curDoc);

        CalculateInverseDocumentFrequency(currentDocument, freq);
    }
}

private void CalculateInverseDocumentFrequency(int currentDocument, Dictionary<string, int> freq)
{
    foreach (var termIndex in freq.Select(entry => entry.Key).Select(GetTermIndex))
    {
        _inverseDocFreq[currentDocument][termIndex] = Log((_numDocs)/
                                                            (float) _docFreq[termIndex]);
    }
}

GetWordFrequency could be made static.  Other than that it looks good.

Overall, nice code to read, the suggestions are just minor clean-up.  I really liked the way you used methods to separate different operations.


Conditionally write to a compressed stream

By default, GZipStream owns the underlying stream, so it disposes it when it's disposed itself. If you're okay with relying on that, then you could put the right Stream into a variable and then have just one using around it. Something like:

var writer = new FileStream(path, FileMode.Create);

if (CompressedStore)
    writer = new GZipStream(writer, CompressionLevel.Optimal);

using (writer)
{
   serializer.Serialize(writer, data);
}

This avoids the duplication and so it's shorter, but it's also less obviously correct (using combined with new is a good pattern, and it's not used here), so I think your original code is actually the better option. If there was more repetition than just one method call, it could make sense to extract that into a separate method, but that's not the case here.


Checking if an integer is a palindrome using either a string or a dict

Apart from performance, there are several other problems in your implementation which the other answers did not address.

This should not be a class. It should be a function, because it being a class offers no advantage whatsoever and it makes its usage more complex.
The variable palindrome is unnecessary and confuses the reader: this variable is always going to be True. So remove it.
Don’t cast the result of a division to int. Use integer division instead.
The if len(s) == 1 check is redundant: its logic is already subsumed in the subsequent code.
Use descriptive variable names: s for an arbitrary string is fine but i to denote the middle index of a sequence is cryptic.

An improved implementation (without changing the algorithm) would look as follows:
def is_palindrome(n: int) -> bool:
    s = str(n)
    mid = len(s) // 2
    for i in range(mid):
        if s[i] != s[-i - 1]:
             return False
    return True

Or, using a generator expression:
def is_palindrome(n: int) -> bool:
    s = str(n)
    mid = len(s) // 2
    return all(s[i] == s[-i - 1] for i in range(mid))

… and of course this whole loop could also be replaced with return s[:mid] == s[: -mid - 1 : -1] because Python gives us powerful subsetting.

I also want to address a misconception in your question:

looking up a value in a dictionary has lower time complexity than searching through a list,

That’s only true if the dictionary has the same size as the sequence (more or less …), and if looking up the key is constant. Neither is true in your case. But what’s more, you still need to construct the list/dictionary, and you completely omit the complexity of these operations.
In fact, the first thing your dictionary does is also construct the sequence — namely, by invoking str(x). It then goes on to traverse the whole list! Because that’s what i:j for i,j in enumerate(str(x)) does.
So before even starting your algorithm proper, it has already performed more work than your other implementation which, after all, only needs to traverse half the string. Even if you stopped at this point and returned, the second implementation would already be slower than the first, and you haven’t even finished constructing the dictionary yet (constructing the dictionary from key: value mappings also takes time).
As for the actual algorithm, you’re still traversing half the string, so once again you are doing the same work as your initial algorithm. This means you have the same asymptotic complexity. But even that part of the second algorithm is slower, because a dictionary is a much more complex data structure than a plain sequence, and each key access of the dictionary (s[p]) is substantially slower than the same access on a string or list would be.


Generic memoize utility function for pure functions

To address your first question:

Is the callable type hint here preferred as opposed to closure?

There is a very similar question on StackOverflow: PHP: Type hinting - Difference between Closure and Callable. It has three answers.
The first line of the answer by Xorifelse explains:

The main difference between them is that a closure is a class and callable a type.

And the last line of the accepted answer by Rizier123 has this suggestion:

So if you only want to type hint anonymous function use: Closure and if you want also to allow normal functions use callable as type hint.

And now, for something completely different general code review comments:
Variable naming
The name $k is a little too brief... $key isn't very long and describes what the variable is.
Simplifying ternary expressions
Correct me if I am mistaken but as long as PHP 5.3+ is used then this line:

$serialize = $serialize ? $serialize : 'serialize';

could be shortened using the fact that:

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE. Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.1

to the following:
$serialize = $serialize ?: 'serialize';

If PHP 7+ is used (which hopefully is the case, since at the time of writing, 7.2+ are actively maintained2) then the null coalescing operator i.e. ?? could also be used to simplify cases where a fallback should be used if a non-null value does not exist - e.g. :

 return isset($cache[$k]) ? $cache[$k] : ($cache[$k] = $fn(...$args));

Can become:
return $cache[$k] ?? ($cache[$k] = $fn(...$args));


Find combination of sets which sum up to a specified result

I usually don't like the Tuple but in this case it looks like a perfect example where I think you'd be much better off if you used one instead of the Set (that I'd name Pair).

The Tuple already can do all the equality stuff so you don't need to write it yourself or you can derive your class from the Tuple so that is supports the + operator.

class Pair : Tuple<int, int>
{
    public Pair(int item1, int item2) : base(item1, item2) {}

    public static Pair operator +(Pair left, Pair right)
    {
        return new Pair(left.Item1 + right.Item1, left.Item2 + right.Item2);
    }
}

Example:

var pair1 = new Pair(1, 2);
var pair2 = new Pair(1, 2);
var pair3 = new Pair(1, 3);

(pair1.Equals(pair2)).Dump(); // True
(pair1.Equals(pair3)).Dump(); // False


Function('return this')()

It took two minutes to me to understand what it does. Let's see what it does step by step

Function('return this')()

This is another way of creating function. An anonymous function which simply returns this object. () at the end of it will invoke this function immediately. This is equivalent to window. Why not just use window instead of writing this mysterious statement.

Do we need IIFE?

IIFE is used to avoid polluting global scope. In the code, there is no code other than window.jQuery(function($){ inside it. Thus, IIFE is not containing any variable or function that could be global. As variables/functions defined inside a function are not accessible from outside of it(provided variables are declared using var keyword), the callback function of window.jQuery(function($){ serves as the container scope.

In simple words, IIFE can be removed safely.

jQuery(function($) {

I, generally don't use the shorthand of ready. It looks confusing for readers who are not familiar with it.

jQuery(document).ready(function() {

is readable. jQuery, call the function when document is ready.

window.jQuery

window here is not required as jQuery is global object and only jQuery will work. No harm in using window but using only jQuery will save some keystrokes.

If you're not using any other library like prototype.js, MooTools, YUI, etc. that also uses $ namespace, you can use $ instead of typing jQuery.

See Avoiding Conflicts with Other Libraries

:file selector

You may use :file pseudo-selector to select <input type="file" /> elements. This again, saves some keystrokes and is readable too.

$('input:file').each(function() {

Caching $this.attr('id')

$this.attr('id') is used 6 times in the code. This can be cached just like you cached $(this) so that, jQuery don't have to read the attribute value again and again.

var id = $this.attr('id'); // Cached the ID of element

and use id in the code.

attr() vs data()

To read the value of data-* attribute, jQuery has provided data() method.
Instead of $this.attr('data-button-label'), $this.data('buttonLabel') can be used.

bind()

bind() is deprecated. To bind events us on(). bind internally calls on. By using on() directly, yo'll save one extra function call. See this answer on StackOverflow.

jQuery(document).ready(function($) {
  'use strict';

  $('input:file').each(function() {
    var $this = $(this);
    var $parent = $this.parent();
    var id = $this.attr('id');

    $this.detach();
    $parent.prepend(
      $('
' +
        '' +
        '' + ($this.data('label') || 'New image:') + '' +
        '' +
        '<input id="' + id + '_path" type="text" class="form-control" readonly="readonly">' +
        '' +
        '' +
        ($this.data('buttonLabel') || 'Browse') +
        '

' +
        '' +
        '' +
        '
')
    );

    $this.appendTo('#' + id + '_input-group label:last-child div:last-child');

    var $path = $('#' + id + '_path', $parent).click(function() {
      $this.click();
    });

    $this.on('change.input_file_styler', function() {
      $path.val(this.files[0] ? this.files[0].name : '');
    });
  });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

<input type="file" id="file" data-label="Select file to upload:" data-button-label="...">


Find max element in increasing-decreasing array

Your code will segfault for array size = 2. Rest looks correct to me.

Specifically, for size = 2,

left = 0
right = 1
mid = 0

And hence, this line:

if (arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1])

will try to access arr[mid-1] which is arr[-1] and can segfault/return incorrect answer.


Efficient way to extract the first row in a Group By group

I believe that DISTINCT is redundant, since the CTE should produce only one row for each date whose ROW_NUMBER() is 1.

Avoid selecting * in the CTE, and list the columns you want explicitly.

Your naming is poor: CTE, C, val, ad.  Please find more descriptive names.

If you are using any SQL Server ≥ 2012, then FIRST_VALUE() is the function you want.

SELECT CAST(archive_date AS DATE) AS C
     , FIRST_VALUE(archdata_value) OVER (
           PARTITION BY CAST(archive_date AS DATE)
               ORDER BY CAST(archive_date AS DATE)
       ) AS val
    FROM ArchiveData
    WHERE archdata_path_ID = @PathID
    ORDER BY C;


As for runtime duration, there is not really much you can do, as the algorithm is already optimum.

However, code can be simplified a bit. Here are some tips:

node_value_dict has same data as node_values -> not needed
Use input() instead of sys.stdin.readline().split() so you can avoid an import
Is there a need for connected_graph_component to be a dict? It should be fine as an array of arrays
As for the sorting, note that you can make the key a pair instead of only 1 value and it will sort first by first value, and if equal it sorts according to second value.
list(map(int, sys.stdin.readline().split())) is repeated multiple times, put it in a function
Sometimes batching print calls in 1 call instead of printing for each value is faster

This is my version of the code after applying these tips:

    def read_line_values():
        return list(map(int, input().strip().split(' ')))

    def connect_graph():
        n, m, k = read_line_values()
        node_values = read_line_values()

        connected_graph_component = [[] for _ in range(n + 1)]

        answer = []

        for m_i in range(m):
            n1, n2 = read_line_values()
            connected_graph_component[n1].append(n2)
            connected_graph_component[n2].append(n1)

        for i in range(1, n + 1):

            neighbours = connected_graph_component[i]
            if len(neighbours) < k:
                answer.append("-1")
            else:
                neighbours.sort(key = lambda node: (node_values[node - 1], node), reverse=True)
                answer.append(str(neighbours[k - 1]))

        print("\n".join(answer))
    connect_graph()

On a side note, if you run the same code as python 2.7.6 instead of 3.5.2, it´s about 2s faster.


This looks quite good, but as usual improvements can be made.

  private readonly PasswordHasher hasher;

instead of using the implementation, you should use the interface

private readonly IPasswordHasher hasher;

I don't see why you want to use both IPasswordHasher and IPasswordService. If your application is built upon IPasswordService you can just skip the implementation of the IPasswordHasher interface like

public class PasswordServiceAdaptor : IPasswordService
{
    private readonly IPasswordHasher hasher;

    public PasswordServiceAdaptor()
    {
        this.hasher = new PasswordHasher();
    }

    string IPasswordService.HashPassword(string password)
    {
        return this.hasher.HashPassword(password);
    }

    bool IPasswordService.VerifyPassword(string hashedPassword, string testPassword)
    {
        var result = this.hasher.VerifyHashedPassword(hashedPassword, providedPassword);

        return result == PasswordVerificationResult.Success;
    }
}

As it seems from the comments that you need to implement both interfaces, you should consider to just call the hasher directly without the call to AsPasswordHasher().

public class PasswordServiceAdaptor : IPasswordService, IPasswordHasher
{
    private readonly IPasswordHasher hasher;

    public PasswordServiceAdaptor()
    {
        this.hasher = new PasswordHasher();
    }

    string IPasswordHasher.HashPassword(string password)
    {
        return this.hasher.HashPassword(password);
    }

    PasswordVerificationResult IPasswordHasher.VerifyHashedPassword(
        string hashedPassword,
        string providedPassword)
    {
        return this.hasher.VerifyHashedPassword(hashedPassword, providedPassword);
    }

    string IPasswordService.HashPassword(string password)
    {
        return this.hasher.HashPassword(password);
    }

    bool IPasswordService.VerifyPassword(string hashedPassword, string testPassword)
    {
        var result = this.hasher.VerifyHashedPassword(
                         hashedPassword,
                         testPassword);

        return result == PasswordVerificationResult.Success;
    }
}


Throwing exception in the singleton pattern in C#

The initialize dance is not nice. Requires the caller to keep track of if it has been called etc. Pit of failure.
The IsInitialized() is not very useful as it is now as there no way to lock over check and initialize. There will always be a risk that another thread calls Initialize between the check IsInitialized and the call to Initialize.
I have not used HttpClient much but my gut feeling is that the locking is not needed.
A singleton will make it hard to mock in tests. What about writing it like this:

public class AssetSyncServiceClientSettings
{
    public string BaseUrl { get; set; }
    public bool JsonOnly { get; set; }
}

public interface IAssetSyncServiceClient : IDisposable
{
    // Picked a sample method randomly, you can expose an api that makes sense in your app/lib
    Task<string> GetStringAsync(string requestUri);
}

public sealed class AssetSyncServiceClient : IAssetSyncServiceClient
{
    private readonly HttpClient _client;
    private bool _disposed;

    public AssetSyncServiceClient(AssetSyncServiceClientSettings settings)
    {
        _client = new HttpClient();
        _client.BaseAddress = new Uri(settings.BaseUrl);

        if (settings.JsonOnly)
        {
            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
    }

    public Task<string> GetStringAsync(string requestUri)
    {
        VerifyNotDisposed();
        return _client.GetStringAsync(requestUri);
    }

    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        _disposed = true;
        _client.Dispose();
    }

    private void VerifyNotDisposed()
    {
        if (_disposed)
        {
            throw new ObjectDisposedException(this.GetType().FullName);
        }
    }
}

Doing it like this avoids initialization. If you need it lazy for some reason the service could handle it internally.
An interface probably makes sense for this so you can mock it in tests.
Use the Dependency Injection container to make the service a singleton instance.
Pass in the service interface in to constructors where it is needed. It makes the dependency explicit and makes it easy to mock in tests.
The settings object can perhaps contain urls so that the service can expose methods like public async Task<Stuff> GetStuffAsync()


Verify if the element is readonly or disabled

There are several major issues in the code:

violates the DRY principle
there is actually no element presence check - find_element_* method will fail with NoSuchElementException if the element is not found (well, you may be handling the exception outside of the method, but that scatters the logic too much resulting into more "spaghetti code")

Instead, I would follow the Page Object pattern and build a "Page Element" abstraction, where every element will have the read_only property:

class BasePageElement(object):
    # other methods here

    @property
    def read_only(self):
        elm = self.driver.find_element(*self.locator)
        return bool(elm.get_attribute("readonly"))

class AddressElement(BasePageElement):
    locator = (By.ID, "address")

Note that I'm using the By.ID locator here and the .get_attribute() method as opposed to less readable and more fragile XPath approach.

This, though, does not handle the "element is not present" case properly - you may wrap the .find_element() call with try/except or think of a more generic way to handle it.


secureRandomIntRange

Scheme

Basically what you generated with painstaking work is to create an implementation of the Complex Discard Method described in section A.5.2. That's a known secure scheme, so kudos for that.

I don't like the way bytes is calculated in the secureRandomIntRange function. It probably uses floating point and that may introduce rounding errors.  It took quite a search, but it is easy to calculate the bit length of the integer using Math.clz32(x) where x is the number:

sizeBytes = ((32 - Math.clz32(range)) + 7) / 8;

Note the name change from bytes to sizeBytes.

If you look closely you'll notice that this creates a problem with the value 0, as that is now represented by 0 bytes. Best not to allow ranges of zero elements. And for one element, you may just want to return that element. It also shows that going to 2^32 and over will represent problems, so that's a maximum for the range in this case (which is different from MAX_SAFE_INTEGER because that's 2^53).

Performance

If the range is somewhat higher than half of maxValueOfBytes then the scheme will loop with a 50% certainty. You can somewhat reduce that by deliberately generating a higher amount of bytes. That way you don't need as many bytes from the random number generator in the worst case scenario (at the obvious disadvantage of requiring more bytes for the good scenario). Note thought that you can get very unlucky tossing coins, and you might want to avoid such hickups where the while loop keeps on running.

One little trick that is sometimes performed is to check if range has just one bit set, i.e. is a power of two. In that case you can just randomly generate bits and return those. For instance, if the range is 256, then you can just return a single byte. If the range is 128 then you can generate a single byte, set the most significant bit to 0 and return the result. Basically, if you use precisely as many bits as required then your method degenerates to the Simple Discard Method.

secureRandomFloat

Random float is designed well, except that you might want to check how it handles precision for larger byte sizes. There is likely a maximum integer size as well, so rounding will probably get problematic for larger values of parameter bytes.

secureRandomChoice

It does seem to pick a random from a list of options. So sure, fine.

Code

Already mentioned in passing: there should be more guard checks on the input, especially on the secureRandomIntRange low end values.
Guard statements should result in an exception, not in a function returning null. You're not just propagating the billion dollar mistake, you're adding to it.
Try to avoid floating point operations. I know, I know, that's a stupid requirement for JavaScript, but really it is important because proving that your JavaScript doesn't have any rounding issues might be tricky. Hence the integer calculations performed for sizeBytes above: I'm sure that they work as long as everything is within the maximum size of a 32 bit integer.

That last note is probably going to be contested, especially since floats should not loose precision for calculations that stay within [0, 2^53). So you may want to keep an open mind to different arguments about it.


Save XML tags and information to another file

There are some good points raised in comments about the requirements, and you really need to think about them in order to write code that solves the problem.  I can get you started with some feedback though.

Organize your code into a function, so that it's clear what the inputs and outputs are.

StringReader reader = new StringReader(text);
while ((text = reader.ReadLine()

This is a really odd reuse of the variable text.  Declare another string, maybe called line.  But also reconsider if a line-centric approach is even appropriate.  XML is pretty free about where whitespace (including newlines) can appear - what if there is a break between the tag name and some attributes?  How will this affect your solution?

For the Regex @"(<.*>)(.*)(<\/.*>)", note that all of these quantifiers are greedy, which may result in you capturing more than you want.  Of course, it may turn out with some clarified specs that a regex isn't even the appropriate tool to use here.


First text game with Python - Higher or Lower

Here is an alternative implementation, with explanatory comments below. This introduces quite a few additional Python concepts:

from operator import ge, le, ne
import random

def get_valid_input(choices=set("hls")):
    while True:
        ui = input("Higher (H), Lower (L) or the Same (S)? ").lower()
        if ui in choices:
            return ui
        print("Not a valid choice, please try again.")

def game(rounds=8):

    cards = range(2, 15)
    faces = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}
    suits = ["Spades", "Hearts", "Clubs", "Diamonds"]

    comparisons = {'h': le, 'l': ge, 's': ne}

    pass_template = "Good job! The card is the {0} of {1}."
    fail_template = "Sorry, you fail. The card is the {0} of {1}."

    while True:
        card = random.choice(cards)
        suit = random.choice(suits)
        print("The first card is the {0} of {1}.".format(faces.get(card,
                                                                   card),
                                                         suit))
        for round_ in range(rounds):
            next_card = random.choice(cards)
            next_suit = random.choice(suits)
            if comparisons[get_valid_input()](next_card, card):
                print(fail_template.format(faces.get(next_card,
                                                     next_card),
                                           next_suit))
                break
            print(pass_template.format(faces.get(next_card,
                                                 next_card),
                                           next_suit))
            card, suit = next_card, next_suit
        else:
            print("Congratulations!")
        repeat = input("Play again? ").lower()
        if repeat not in "yes":
            print("Goodbye.")
            break

if __name__ == "__main__":
    game()

Comments:

Note adherence to the Python Style Guide, PEP-0008, e.g. using lowercase_with_underscores for variable names;
random.choice is used rather than hard-coding bounds for range (if you stick with choosing the index, at least assign the index first rather than picking a card based on a random number then using index to get that same number back);
The card is now just an integer, making comparison easy without needing to find the index. The "face" (e.g. 'Jack') is only looked up when displaying to the user (using dict.get to return either the face string if it's in the dictionary or the card value if not);
A dictionary, with the operator module, is also used to reduce duplication in the main loop. The trick is recognising the duplication - in all cases, you are comparing two cards with a particular rule. The following now only happen in one place, reducing chance of error:

Picking the next card;
Comparing the cards; and
Telling the user they've won or lost;

A function forces the user to provide valid input. This will loop until they pick one of 'h', 'l' or 's' (case-insensitive);
while True replaces the odd behaviour with x that never gets incremented; and
The whole thing is wrapped in a function, which makes it easier to import elsewhere later and has also allowed the "magic number" 8 to be variable when calling game.

One additional thing you might want to consider is actually simulating a deck of cards. As it stands, the same card could appear twice, i.e. the game is currently being played as if the card were being put back into the deck each time. This may or may not be what you're aiming for - I would expect to play as if the (up to) eight cards were being laid out on the table one after another.


Shorten my asynchronous DB queries, using async.js module

I think not.

Whereas you find the function(cb) { ... } wraps a bit messy, I think that this is the most elegant way to show readers that this is a separate functions, and that stuff is about to get asynchronous.. Again, compared to other approaches, this is quite clean.

Also, (I know this is just a small example), consider not using the lastInsertId variable. You could simply go for

async.waterfall([
    function(cb){
        db.query(insertQuery,values,cb);
    },
    function(results,_,cb){
       db.query(anotherInsertQuery,otherValues.concat(results.insertId),cb);
    }
],callback);


Harnessing hashCode as JAXB @XmlID in order to use it with @XmlIDREF

Thanks for including the hashCode() method. As I suspected, the purpose of the hashCode method is to fulfil the equals/hashCode contract, and is not suitable for being an ID. For example, by changing the number of wins, you change the hashCode, and by proxy you change the player's ID.

If you want the ID to be a temporary thing that is only constant for the short time that the player is constant, then your solution is OK. If you want the ID to last through a persist/restore cycle, or even from one moment to the next when they pee .... and their weight changes, then you need a different system.

In addition, while you claim your hashCode is unique, it is not technically true. The chances of their being a duplicate are remote, but it is possible that two players will have the same hashCode, and hence the same ID.

In reality, your system is not reliable, and the best solution would be to create an externally managed ID for each player - a record number from a database, a unique counter, or something.


You do not need IDisposable in your current implementation as you do not use any unmanaged resources or have any fields or properties which implement IDisposable which your class owns.

Setting the properties to null in the dispose method is unnecessary.

Method names should be Pascal cased and not contain underscores to adhere to standard naming conventions:

private void GetConnectionStringFromAppSettings()

Since the class cannot operate without a connection string or provider, you should throw an exception if they are not set:

private void GetConnectionStringFromAppSettings()
{
    this.Connection = ConfigurationManager.AppSettings.Get("Database");

    if (string.IsNullOrEmpty(this.Connection))
    {
        throw new InvalidOperationException("No connection string found in the configuration");
    }
}

You should use the Connection Strings section of the app.config instead of app settings.

You should resolve the factory once in your constructor instead of on every call to ConnectionReturnDataTable.

ConnectionReturnDataTable should be renamed to something like GetQueryResults.

DbCommand and DbDataAdapter are both IDisposable and should be used in a using statement (or a try/finally which is what a using compiles to).

private DataTable FillDataTable(DbConnection connection, string sql)
{
    using (DbDataAdapter adapter = this.Factory.CreateDataAdapter())
    {
        using (DbCommand command = connection.CreateCommand())
        {
            command.CommandText = sql;
            command.Connection = connection;
            adapter.SelectCommand = command;

            DataTable table = new DataTable();
            adapter.Fill(table);

            return table;
        }
    }
}

The connection property should be called ConnectionString

public string ConnectionString { get; set; }

In fact, the properties should probably become private fields as they shouldn't be modified from outside the class if you are using the app.config to specify their values.

You should be using parameterised queries instead of raw SQL


Missing level of technical depth (Recursive to Iterative)

as we felt they didn't demonstrate the level of technical depth we're seeking from candidates

This is a stock response. The engineers who interviewed you probably said something like “nah, not good enough”, so someone in HR sent you their stock response. Don't worry about the exact words; it wasn't written about you.

Some problems they might have objected to:

fold shouldn't throw an IllegalArgumentException when U is null; null is a reasonable input.
It traverses the Queue with both Queue.poll (which removes the first element) and an iterator (which doesn't modify the queue). Pick one or the other. Doing both may not even have well-defined behavior — what happens to the iterator when you remove the current element?
The initial isEmpty check is redundant. If the queue is empty, the iteration loop will do nothing.
There are lots of blank lines that take space without contributing to readability. That you include them in such a small program suggests you're not used to large programs.

There are also some design flaws in the specification.

Folder should not be an interface. It makes no sense to create an object in order to call its fold method; fold should simply be a static method.
If the original version used Queue.poll instead of an iterator, then it destroys the contents of the queue. It's usually not a good idea to modify arguments unnecessarily, because it tends to create bugs.
fold should probably accept any Iterable, not just a Queue.

If you didn't point out these problems, they might take that as a sign you wouldn't notice design flaws in real work either. Part of a programmer's job is noticing problems and (when feasible) fixing them!


Determine total number of seconds since the epoch

Edit: I very wrongly accused Jacobi of posting a flawed algorithm. So I removed my ranting and replaced by:

I had a try compiling your code and I worked on it to represent how I would have written it. See below. I hope this gives you hints about a different possible coding style. I hope to demonstrate some benefits. The main differences are:

Comment for readability. In six months you might be very much in doubt yourself of all the intricacies of an algorithm. I had a hard time deciphering your algorithm. I am also in favor of including references to the definitions of formulas etc, which allows reviewers to check them more quickly.
A good practice that I still don't manage to discipline myself to is to write commenting immediately for doxygen or another doc generator, so you can save yourself the hassle later. It usually forces you to document all parameters, return values, ... which is good practice anyway.
Code formatting to represent the structure of the code. I am a big fan of lots of spacing and horizontal alignment to spot the difference between similar lines easily.
I would refactor to avoid repeating the same code twice, even in the case of isLeapYear. I think the algorithm also becomes more readable when you change the condition by a clear function name. For reading how the algorithm works, I actually don't care about the implementation of the leapyear test.
Instead of testing for m < 2 to add or remove extra leapyears, I think it is beneficial to try and represent the reality in your code. I do this here by creating N_DAYS_IN_LEAP_MONTH. This benefits not only in simplifying the code, it also serves in multiple places, as now the input validation is more correct as well.
Returning -1 on error is misleading because it could also be a valid outcome. I would propose in any case to return 0 on error instead of -1, so it can be distinguished from valid output with a Boolean test as if( x = getUnixTimeStamp(...) ) -> valid. If you want to garantee no ambiguity, you should probably return a struct with an error status, an error message and a result.
Personally I prefer longer variable names for clarity, but I suppose that has to do with taste. I also changed nleapyears to nleapdays, which corresponds more to what is is.
I try to use const where I can. In this example it is a bit trivial, and compilers would probably compile it to the exact same assembler code without these consts, so you have to see if you find it worth the extra code. If your parameters aren't basic types, but objects however starting to take them as const refernces really starts making a difference.

Not implemented but advised:

Allow supporting inputs for the whole range of double. This makes your function more general, and thus more useful. If a program logic needs to restrict more, that should not be done in this function.

#include <algorithm>
#include <iostream>

double getUnixTimeStamp( int year, int month, int day, int hour, int minute, int second );

int main()
{
    std::cout << std::fixed << getUnixTimeStamp( 1979, 12, 31, 23, 59, 59 ) << std::endl;

    return 0;
}

// start of getUnixTimeStamp code
static const int N_DAYS_IN_MONTH     [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static const int N_DAYS_IN_LEAP_MONTH[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Is the passed in year a leap year?
// https://en.wikipedia.org/wiki/Leap_year#Algorithm
inline
bool
isLeapYear( const int year )
{
    return

             year % 400 == 0
        || ( year % 4   == 0  &&  year % 100 != 0 )

    ;
}

// returns the epoch timestamp for a given date in UTC
// reference: https://en.wikipedia.org/wiki/Unix_time

// current minimum supported date = 0000-01-01 00:00:00
// current maximum supported date = 2999-12-31 59:00:00
// returns 0 on faulty input, as well as for epoch input

// TODO: support full range of double rather than limiting arbitrarily

double
getUnixTimeStamp( const int year, const int month, const int day, const int hour, const int minute, const int second )
{
    // Do some bounds checking
    // Note that double will still not be indefinite, and you should check what the boundaries for double are.
    // (this also changes per implementation, so you need to check limits.h or something like that)
    // It would be more logical and correct to limit to the range permitted by double than to arbitrarily limit a 0y.
    // If your program needs this limit, you should enforce it outside this function, because it doesn't belong here.

    const int* const DAYS_PER_MONTH = isLeapYear( year ) ? N_DAYS_IN_LEAP_MONTH : N_DAYS_IN_MONTH;

    if
    (
            year   < 0  ||  year   > 3000
        ||  month  < 1  ||  month  > 12
        ||  day    < 1  ||  day    > DAYS_PER_MONTH[ month-1 ]
        ||  hour   < 0  ||  hour   > 24
        ||  minute < 0  ||  minute > 60
        ||  second < 0  ||  second > 60
    )

        return 0;
        // it is problematic to do error handling with the return value, as all possible return values could be valid epochs as well.
        // at least by taking 0 you can use a boolean check like if( x = getUnixTimeStamp(...) ) -> valid.
        // The check will fail for 1970-01-01-00-00-00

    // Calculate the seconds since or to epoch
    // Formula for dates before epoch will subtract the full years first, and then add the days passed in that year.

    int epoch       = 1970                  ; // UNIX epoch 01/01/1970
    int sign        = year > epoch ? 1 : -1 ; // So we know whether to add or subtract leap days

    int nleapdays   = 0                     ; // The number of leap days
    int monthsNDays = 0                     ; // The number of days passed in the current year

    // Count the leap days
    for( int i = std::min( year, epoch );  i < std::max( year, epoch );  i++ )

        if( isLeapYear( i )  )

            ++nleapdays;

    // Calculate the number of days passed in the current year
    for( int i = 1;  i < month;  i++ )

        monthsNDays += DAYS_PER_MONTH[ i - 1 ];

    return

        (
              ( year - epoch )  * 365       // add or subtract the full years
            +   sign            * nleapdays // add or subtract the leap days
            +   monthsNDays                 // The number of days since the beginning of the year for full months
            +   day - 1                     // The number of full days this month

        )         * 86400                   // number of seconds in 1 day

        + hour    * 3600
        + minute  * 60
        + second
    ;
}


Your code doesn't look too shabby! A few comments.

Declaring but then not using options made me stumble. If you don't have any options, don't make a parameter called options.
In my opinion there's not much point in separating _create and _event into two separate functions. If you do, you should rename _event so that it's more like a function name. Functions should be named such that they start with a verb; try something like _attachListener.
It's fine to use a closure-scope variable, but you're kind of half-using it. If you combine your two functions, you'll be able to get rid of it entirely.
_create isn't using its theElement parameter.
You should take advantage of method chaining when creating input. Also, consider naming jQuery variables with a leading $ to make it very explicit what type they are.
The .html() function does not take a jQuery object as a valid parameter; it takes either an htmlString or a function. Instead you should use inputWrapper.append(input);.
In fact, rather than creating an inputWrapper at all, use the .wrap() function.
Do you really want to use aSpan.html(tagText);, or do you want to use .text()? This depends on your use case but usually people will expect the behaviour of .text() (e.g. not having to escape their angle brackets).
For consistency, either name them both anInput and aSpan or drop the prefix.
Note that using function chaining, you can in fact completely eliminate the need for having any variables at all, if you prefer.

Here's my proposed rewrite:

(function($) {
  $.fn.taggify = function(options) {
    create(this);
    return this;
  };

  function create($theElement) {
    var $input = $('<input></input>')
      .attr('type', 'text')
      .attr('autocomplete', 'off')
      .css('border', 'none')
      .css('outline', 'none')
      .wrap('

');

    $input.on('keyup', function(e) {
      if (e.keyCode === 13) {
        var tagText = $input.val();
        var $span = $('');

        $span.text(tagText).wrap('

');
        $theElement.prepend($span.parent());
        $input.val('');
      }
    });

    $theElement.append($input.parent());
  }
})(jQuery);

$(function() {
  $('ul').taggify();
});
ul {
  background: #ccc;
  padding: 1em;
}


This code comes before the AJAX call. Is it right?

I would suggest adding the message to the DOM via the success callback - that way, if an error occurs then the message isn't displayed on the page.

Other feedback

Javascript

Cache DOM lookups

I would suggest you cache DOM references - e.g. store $('#messageBox'), $('#send'), $('.context') in variables (or better yet, constants if you are using ecmascript-6), preferably in a DOM-ready callback, because DOM-lookups aren't exactly cheap....

Accessing elements by class name can return multiple

Also: $('.context') is equivalent to document.getElementsByClassName()... which returns multiple elements. While methods like .scrollTop() and .innerHeight() operate for the first matched element, it would be more appropriate to select an element by id (i.e. with an id selector).

$(document).ready() with nested $(window).load()

I don't believe it is necessary to add the window load callback within the DOM ready callback. Also, bearing in mind that you posted this code a couple years ago, .load() is now deprecated as of jQuery version 1.8, because there is a new method .load() in the AJAX section.

Note that in the line below, displayMessage() is called and does not return a function, so the call to $(window).load() appears superfluous:

$(window).load(displayMessage(lastTimestamp));

To really make that function displayMessage an onload handler, one could make a partially applied function using Function.bind() :

$(window).load(displayMessage.bind(null, lastTimestamp));

PHP

Separate endpoints

It would be wise to separate the code in the display function into two different endpoints - one for fetching messages (which should perhaps use the GET HTTP verb), and one for creating a new post (which can stay as a POST or a PUT request). That way display isn't concerned with creating messages, so as to adhere to the Separation of Concerns principle.

Laravel code?

It looks like some of the Laravel DB facade and Eloquent methods (e.g. findAll()) are used, which makes me believe this is a Laravel controller method. If that is the case, it would be wise to access POST data via the Request object. Then lines like

$text = DB::Escape($_POST['text']);

Can be updated to use the Request::input() method:

$text = DB::Escape($request->input('text'));

Or using the dynamic input style:

$text = DB::Escape($request->text);


Find website URLs that begin with http:// or https://

Variable Names

Variables should be lower-cased and snake-case, meaning that multiple words should look like some_variable, not someVariable or SomeVariable. I think the name you've chosen for your regex is good and expresses exactly what it is:

protocol_regex = re.compile(...)

Checking length of a list/container data structure

It is not considered pythonic to check the emptiness of a container in python by using if len(container) == 0, most* containers have a __bool__ method built-in that allows you to do if not container for an empty one and if container for non-empty:

from collections import deque

if not {}:
    print("empty dict")
empty dict

if not []:
    print("empty list")
empty list

if not '':
    print("empty string")
empty string

if not deque():
    print("empty deque")
empty deque

if ['result1']:
    print('non-empty list')
non-empty list

One of the few that does not behave this way is queue.Queue, which I've included to give context to the most comment.

With this in mind, change your match check to:

if matches:
    # rest of code
else:
    # else code here


Naming and using functions

These are all very bad function names:

valid_year_finding()
valid_month_finding()
valid_day_finding()
birthday_checking()

Think of functions as actions. Typically their names should include a verb,
take an input, and either return an output, or modify state.
Consider this rephrasing and usage:

try:
    year = get_valid_year(year_input)
    month = get_valid_month(month_input)
    day = get_valid_day(year, month, day_input)
    validate_birthday(year, month, day)

    print('Your birthday is {} - {} - {}'.format(year, month, day))

except ValueError as e:
    print('Invalid birthday: ' + e.message)

The get_* methods should return valid values,
or else raise an exception if the input is invalid.
This way if a problem is found with year,
there's no need to process month.

Notice that above I pass year and month as parameters to get_valid_day.
This usage makes sense,
as you cannot validate a day without knowing the year and the month.

Example implementation:

def get_valid_year(year_input):
    year = int(year_input)
    if 1900 < year < 2020:
        return year
    raise ValueError('year is not within 1900 and 2020')

Formatting

There are serious formatting issues with this code.
Please read and follow the Python style guide.

A variable should have one type

For example after these statements,
year might end up as either integer or string:

if year_input > 1900 and year_input <2020:
    year = year_input
else:
    year = 'invalid'

Avoid the global keyword, and global variables

It's too hard to avoid using global. For example instead of this:

def valid_year_finding():
    global year
    if year_input > 1900 and year_input <2020:
        year = year_input
    else:
        year = 'invalid'

You could reorganize the code like this:

def valid_year_finding():
    if year_input > 1900 and year_input < 2020:
        return year_input
    else:
        return 'invalid'

year = valid_year_finding()

We got rid of the global keyword,
but the year_input global variable still remains.
Let's make that a parameter of the function instead:

def valid_year_finding(year_input):
    if year_input > 1900 and year_input < 2020:
        return year_input
    else:
        return 'invalid'

year = valid_year_finding(year_input)

Avoid free variables

If a variable is used in a code block but not defined there, it is a free variable.
In this function, year_input is a free variable:

def valid_year_finding():
    if year_input > 1900 and year_input < 2020:
        return year_input
    else:
        return 'invalid'

Free variables are acceptable when their scope is small and obvious.
In the posted code, year_input is defined in the global scope,
making it a global variable, which should be avoided.

Use the chained comparison operator

This condition can be simplified:

   if year_input > 1900 and year_input < 2020:

Using the chain comparison operator:

    if 1900 < year_input < 2020:

Use the right data structures

Instead of lists:

days_31 = ['jan', 'mar', 'may', 'jul', 'aug', 'oct', 'dec']
days_30 = ['apr', 'jun', 'sep', 'nov']
days_28 = ['feb']

These should be sets:

days_31 = {'jan', 'mar', 'may', 'jul', 'aug', 'oct', 'dec'}
days_30 = {'apr', 'jun', 'sep', 'nov'}
days_28 = {'feb'}  # granted, for this one, list or set doesn't matter

Use doc tests

Doc tests can greatly help you test your implementations,
here's an example:

def get_valid_year(year_input):
    """
    >>> get_valid_year('1901')
    1901
    >>> get_valid_year('1900')
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: year is not within 1900 and 2020
    >>> get_valid_year('2020')
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: year is not within 1900 and 2020
    >>> get_valid_year('x')
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: invalid literal for int() with base 10: 'x'
    """
    year = int(year_input)
    if 1900 < year < 2020:
        return year
    raise ValueError('year is not within 1900 and 2020')

If you have this code in a script called bday.py,
you could run the doc tests with:

python -m doctest bday.py

If the tests pass, it outputs nothing.
Otherwise it prints an informative report of what went wrong.


Crawl and gather all the urls recursively in a domain

There's no need to use cat here:
cat wget.txt | sed 's/:$//'  | url_matcher

Instead, simply have sed take its input from the file:
sed 's/:$//' wget.txt | url_matcher

Instead of using $RANDOM and mkdir, we can use the mktemp command (GNU coreutils) to create us a new directory (without risk of conflict with an existing one):
tempfolder=$(mktemp -d)

I think that now removes the only Bashism in the script.

Avoid pushd and popd in scripts (having to redirect the unwanted output should be a sign that these are intended for interactive shells).  Instead, we can use cd "$tempfolder" and something like cd .. to leave it (it doesn't matter where we end up, as we only use absolute paths after that).  Alternatively, don't change directory at all, but specify paths in full (I'll use a shorter name for the temporary directory):
dir=$(mktemp -d)

cleanup() {
    sed -e 's/:$//' "$dir/wget.txt" | url_matcher
    rm -rf -- "$dir"
}

trap cleanup EXIT

wget -nd --spider --recursive --no-verbose --output-file="$dir/wget.txt" "$1"

Other alternatives to pushd/popd include saving $PWD into a variable before changing directory, or using cd - (which internally does exactly that, as cd saves $PWD into $OLDPWD for that purpose).

We can avoid the temporary file altogether, to simplify the code and to allow us to start producing output without waiting for the crawl to finish.  We can do this in a couple of ways, by being creative with --output-file.  If we're on Linux, we can write to /dev/stdout instead of a file:
wget -nd --spider --recursive --no-verbose --output-file=/dev/stdout "$1" \
  | sed -e 's/:$//' | url_matcher

If we're happy to accept a Bash dependency again, we can use process substitution:
wget -nd --spider --recursive --no-verbose \
     --output-file=>(sed -e 's/:$//' | url_matcher) "$1"

However, neither of those dependencies are necessary, as wget follows the common convention of treating the filename - specially, to mean "standard output stream":
wget -nd --spider --recursive --no-verbose --output-file=- "$1" \
  | sed -e 's/:$//' | url_matcher

Modified code
#!/bin/bash

set -uo pipefail

exec wget -nd --spider --recursive --no-verbose --output-file=- "$1" \
    | sed -e 's/:$//' | url_matcher


Serialize the properties of an entity framework entity to data fields and back

If you are trying to convert the string to DateTime format that might be used in the EF object, you may try:

Convert.ToDateTime("2013-09-10 12:12:12",System.Globalization.CultureInfo.InvariantCulture)


Filling two angular $scope variables with data

The only thing that stands out a bit is the fact that you do 2 very similar angular.forEach() calls. You could extract these functions out and do only 1 call. I would also make -1 a named constant. I would also declare all variables on top.

What you could consider, but I don't advise it, since it reeks too much of CodeGolf, is to simplify the 2 if statements to 1 single push() call

(hidden.contains(item.id)? invisible : visible).push( item );

This piece of code extracts the filter functions and applies my other suggestions:

prepare: function (response) {

    var visible = [],
        invisible = [],
        HIDE = -1,
        hidden, filter;

    if (_hasParam('hidden')) {
        hidden = _getParam('hidden').split(',');
        /* Hide based on the hidden parameter */
        filter = function (item) {
            if (hidden.contains(item.id)) {
                invisible.push(item);
            } else {
                visible.push(item);
            }
        }
    } else {
        filter = function (item) {
        /* Hide based on the order of the item */
            if (item.order === HIDE) {
                invisible.push(item);
            } else {
                visible.push(item);
            }
        }
    }

    angular.forEach(response, filter);
    $rootScope.visible = visible;
    $rootScope.invisible = invisible;
}


LEFT JOINS are not inherently slow. It really depends on how you set it up. Are there any indexes on b.Assetnum? Having an index on that would probably speed up your joins tremendously. It probably is doing a full table scan on the join right now if you don't have any indexes.


Your regex could be improved:

$regex = "[^a-zA-Z0-9,-]";
$a = isset($_GET["a"]) ? preg_replace("/".$regex."/", "", $_GET["a"]) : "";

The character , shouldn't be in a URL, but _ can be.
You don't really need to add / to the beginning and end of your regex every time.
I see a lot of people do a-zA-Z when they could really just do a-z with a case insensitive search.

Becomes:

$regex = "/[^a-z0-9-_]/i"
          ^           ^^
$a = isset($_GET["a"]) ? preg_replace($regex, "", $_GET["a"]) : "";

Using if ($a == "in" && $aa != null) could probably be improved also as if $aa is not null, then it evaluates to true anyway:

if ($a == "in" && $aa)

With if ($a == "missinghtml") { $errorUrl = true; }, you should make it into an else if loop

like:

if ($a == "in" && $aa) { $searchLocation = $aa; }
else if ($a == "missinghtml") { $errorUrl = true; }


Evaluating result for mastermind comparison

The algorithm is short and concise. There might be a more clever way to do it, but it would likely be less readable.

This code will break if the guess is not the same length as the code. An empty string causes an out of out of bounds exception. A string longer than the code could cause other problems. You don't show what Answer is, but it looks like the last argument is the number of incorrect pins. This could lead to having more incorrect pins than there are in the code. You need to protect against each of these cases.

Since you are using strings, the value could contain characters other than digits. A guess with invalid characters should be treated differently than an incorrect guess.

You can add a check before the second loop to see if the all of the characters are correct. In that case you would skip over a N x M loop.


How to make this csv-reading PHP code more efficient?

Looping on feof is wrong. feof doesn't return return true until after you've hit the end of file. If the read pointer is sitting past the last character and you try to read, feof will return false, but the read will fail. At that point feof will return true.

Example:

1, a, b, c
2, a, b, c
3, a, b, c

Then reading it:

$rows = array();
while (!feof($fh)) {
    $rows[] = fgetcsv($fh);
}
print_r($rows);

A much more natural (and correct) loop structure is as follows:

while (($row = fgetcsv($fh)) !== false) {
    $rows[] = $row;
}

(You can of course use fgetcsv($fh, 1024) instead of fgetcsv($fh). Just an example.)

As far performance goes, you're doing what you're doing as fast as it can be done. In other words, to get a speed increase, the approach has to change, not the implementation.

There are three main approaches that you can take (that can all be combined as desired): use caching, put the HTML output straight into the first loop so you only do one loop instead of two, and try using a fixed field-size format rather than CSV so parsing overhead can be eliminated.

Putting the HTML output straight into the read loop is very gross from a separation of concerns perspective, and the gains would be minimal compared to the code quality hit.

Likewise, changing to a fixed size format would be a fairly minimal performance gain for quite a bit of headache.

Caching is what you need to do. A primitive approach is to just create an on-disk version of the array and read that rather than the CSV. A slightly more complex but much faster approach is to cache the CSV in memory using apc or even something like memcached (memcached is way overkill, as is arguably apc). Yet another approach is cache the output HTML rather than the array. This allows you to serve a static page rather than regenerate it each request. You can't get any faster than that.

Since the idea remains largely the same, I'll show an example of the simplest one to implement: caching the array.

$csvFilePath = "...";
$cacheFilePath = "...";

if (!file_exists($cacheFilePath) || filemtime($csvFilePath) > $cacheFilePath) {
    $fh = fopen($cacheFilePath, 'r');
    $rows = array();
    while (($row = fgetcsv($fh)) !== false) {
        $rows[] = $row;
    }
    file_put_contents($cacheFilePath, serialize($rows));
} else {
    $rows = unserialize(file_get_contents($cacheFilePath));
}

Though this one is very simple, it's also the least effective. I would cache the entire page output. I would probably use something like Zend_Cache or Symfony's caching component to avoid lots of nasty manual output buffer management. Alternatively, you could write your own simple page cache.


SQL query for monthly bills with amounts paid

Do you really need the subquery?

SELECT
bill.id as bill_id,
master.id as party_id,
master.name as party_name,
`amountExcVat`,
bill.vat,
amountExcVat + bill.vat as 'amtIncVat',
`purchasedDate`,
bill.status,
SUM(payment.cashPaid) + SUM(payment.chequePaid) as 'Amount Paid(cash+chq)',
FROM `partybill` as bill, `partymaster` as master, partypayment as payment
WHERE
party_id = partyId AND
bill_id = partyBillId AND
bill.partyId = master.id AND
bill.partyId = payment.id AND
UPPER(MONTHNAME(`purchasedDate`)) = 'OCTOBER' AND
YEAR(`purchasedDate`) = '2013'
GROUP BY partyId, partyBillId)

(I just wrote this without testing it so it might not work right out of the box)

Since you are already querying partypayment you should be able to do this


You could go for a more functional (rather than imperative) approach.

Such as:

fun String.masterCompare(otherString: String): Pair<Int, Int>? =
        when {
            length != otherString.length -> null
            else -> {
                // this part is really easy
                val commonAtSameIndex = zip(otherString).count {
                    (one, another) -> one == another
                }

                /* calculates the frequency map of characters in a given string.
                 * not the best solution in terms of performance - if you were to expect
                 * really large strings, you might be better off keeping the imperative approach.
                 * possibly with a bitmask instead of reassigning the mutable string. */
                fun String.toFrequency() = groupBy { it }
                        .mapValues { it.value.size }
                        .toMap()

                val thisFrequencyMap = toFrequency()
                val otherFrequencyMap = otherString.toFrequency()

                val commonOverall = thisFrequencyMap
                        .map { (letter, count) ->
                            min(count, otherFrequencyMap[letter] ?: 0)
                        }
                        .sum()
                commonOverall to commonAtSameIndex
            }
        }

I would also suggest avoiding nulls out of principle, and possibly returning (0, 0) if strings aren't of the same length.

If you do need to differentiate between this case and strings of the same length that don't share any characters, I'd consider coming up with dedicated types instead of a nullable Pair, which is too generic (and makes it easy to confuse which field stands for what).

Eg. the result type might be:

sealed class MasterComparisonResult {
    object DifferentLength : MasterComparisonResult()

    data class SameLength(val commonAtSameIndex: Int, val commonOverall: Int) : MasterComparisonResult()
}

And then the function returns a MasterComparisonResult instance.

Here's a version that combines the functional way - in my opinion much clearer - of calculating the number of identical characters in the same positions with the loop that calculates the other value.

A bit array is used for better performance.

fun String.masterCompare(otherString: String): Pair<Int, Int>? =
        when {
            length != otherString.length -> null
            else -> {
                // this part is really easy
                val commonAtSameIndex = zip(otherString).count {
                    (one, another) -> one == another
                }

                var commonOverall = 0
                val countedAlready = BooleanArray(length)

                /* this is yet another detail: there's no need for toList() allocation.
                 * you can iterate over this (String) straight away. */
                for (c in this) {
                    /* find the first occurrence of the c character in otherString
                     * that wasn't counted already */
                    val index = countedAlready
                            .asSequence()
                            .withIndex()
                            .filterNot { it.value }
                            .indexOfFirst { otherString[it.index] == c }
                    if (index >= 0) {
                        countedAlready[index] = true
                        commonOverall++
                    }
                }
                commonOverall to commonAtSameIndex
            }
        }


At this point your code is starting to become hard to follow. If you add any more complicated logic, you will not be able to easily understand it yourself if you return to it a few weeks later.

I would first of all separate out the parsing of an XML file so that you can change that independently of all the rest. You can make this a generator, so it doesn't need to know what happens with the data it provides (being written to a CSV file, printed to the terminal, shucked into /dev/null/, ...).

Using findall to find one element is not the right approach. Either there is exactly one e.g. './/Rational' element, in which case you can just use find, or there is not and you have to store all of them (or rethink your XML design).

You can use a dictionary comprehension and the relatively new f-strings to easily generate your row data (don't worry about missing keys here, we'll take care of them outside).

def parse_file(xml_file):
    tree = ET.parse(xml_file)
    for node in tree.getroot().findall('.//START'):
        repeated_values = dict(node.attrib)
        repeated_values['rational'] = node.find('.//Rational').text
        repeated_values['qualify'] = node.find('.//Qualify').text
        description = node.find('.//Description')
        repeated_values['description_txt'] = description.text
        repeated_values['description_num'] = description.get('num')

        for data in node.findall('.//SetData'):
            row = {f"set_data_{key}": value for key, value in data.attrib.items())}
            row.update(repeated_values)
            yield row

The csv module has a DictReader and, more importantly, a DictWriter class. These are a bit easier to use since you don't need to enforce the correct order in the parsing. It also has the writerows method (like all other csv writers) that can take an iterable of dictionaries to write. This is slightly faster than writing each row manually, and also more readable.

def join_xml_files(files, output_file, headers):
    with open(output_file, 'w') as f:
        writer = csv.DictWriter(f, headers)
        writer.writeheader()
        for xml_file in files:
            writer.writerows(parse_file(xml_file))

Note that restvals="" is already set by default and replaces missing keys with an empty string, so no need for collections.defaultdict(str) anymore.

You can then put the actual calling code under a if __name__ == "__main__": guard which allows you to import from this script without running it:

if __name__ == "__main__":
    directory = 'path to a folder with xml files'
    xml_files = map(str, Path(directory).glob('**/*.xml'))
    headers = ['id', 'service_code', 'rational', 'qualify', 'description_num',
               'description_txt', 'set_data_xin', 'set_data_xax', 'set_data_value',
               'set_data_x']

    # actually call the function
    join_xml_files(xml_files, "output.csv", headers)

As to reducing the file size: that's not possible without removing information. You could zip up the resulting file (it would still be just as large in memory when unzipping it, though), or you can leave out the redundant information (but then all programs reading this file need to fill in the information when necessary).


Your identifiers could be altered to make things clearer. What you're calling product_data is just a list of names, so perhaps product_names would be better. Then it follows that product should become product_name, as for product_name in product_names: makes perfect sense. And you should only call things x where that's the convention of the domain (e.g. mathematics).

One obvious code simplification is that you can iterate over a dictionary's keys and values simultaneously:

for product_no, product in json_data.items():
    for product_name in product_names:
        ...

This way your comparisons lower down are neater:

if product_name.lower() in product['name'].lower():

Rather than product_name.lower() every time you compare to it, lowercase everything once:

product_names = [name for name in product_strings.lower().split(',')]
                                               # ^ e.g. here

In this case you don't need it at all, as product_strings is already lowercase!

You can do multiple comparisons in one (logical) line, too, reducing duplication:

if (product_name in product['name'].lower()
        or product_name in product['des'].lower()):
    print (product, product_spec['name'])