See at @Caridorc first.

Use the full power of the stream.

The standard stream operators will read a word at a time for you.

std::string word;
while(std::cin >> word)
{
     // DO STUFF.
}

The above will read a file. If you just want to read a line. Read a line then use string stream.

// Read a line
std::string line;
std::getline(std::cin, line);

// convert line to stream
std::stringstream linestream(line);

// Loop over it one word at a time.
std::string word;
while(linestream >> word)
{
     // Operate on word.
}

DRY your code

Both sides of your if statement are doing the same thing. The difference is handling the last word (one not terminated by a space). You should move common code outside the if statement just leave the non common code in the if statement.

    if (<test>)
    {
    }
    else
    {
    }

    // This all seems common across the two if statements.
    pigLatWord = word.substr(index);
    length = pigLatWord.length();
    pigLatWord.insert(length, "ay");
    pigLatWord.insert(length, 1, word[index]);
    pigLatWord.erase(0, 1);
    index = word.length();

Declaration when needed.

Put your variable declarations as close to the point of use as you can. This way you don't need to look for their type very far (it is where the code is). They only get constructed when you need them (and destroyed as soon as possible) so preventing excessive use of space and not costing anything if you don't need them.

// These could be moved to the other side of the if.
// As pigWord is only used after the loop (in my new version)
string pigLatWord;

Declare one variable per line.

string pigLatWord, pigLatSentence = "";
int length = 0, index = 0;

Humans need help in reading code. Don't make it hard for them. Declare one variable per line. This also helps when refactoring code later. You will only move the variables you need and source control tools will find it easier to do a diff on the change.

Pass by const reference.

If you do not plan on modifying the input pass by const reference to prevent a copy.

string pigLatin(string const& word){
             //        ^^^^^^

Design.

If I was actually going to write this I would encapsulate the concept of a Pig Latin word in a class. Then you can localize the change in a single well named class. You can then make use of standard routines to help read/print.

class PigLatinWord
{
    // STUFF
};

int main()
{
    // Copies std::cin to std::cout converting to PigLatin
    // on the copy to the output stream.
    std::copy(std::istream_iterator<std::string>(std::cin),
              std::istream_iterator<std::string>(),
              std::ostream_iterator<PigLatinWord>(std::cout, " ")
             );
}


It feels like you have muddled the model, view, and controller. With a name like Person, I would expect this object to act as a model.  Constructing a person shouldn't also make its UI.  At the least, make the UI rendering a separate explicit step.

A second potential problem is that concatenating strings into HTML without escaping can lead to JavaScript injection vulnerabilities (also known as cross-site scripting).  I recommend using $.text() to fill in the text.

function Person(data) {
    this.name = data.name;
    this.age = data.age;
}

Person.prototype.speakName = function() {
    alert(this.name);
};

Person.prototype.speakAge = function() {
    alert(this.age);
};

Person.prototype.render = function($container) {
    var $element = $(
        '

'
    );

    // Fill text and bind events
    var self = this;
    $element.find('.name')
            .text(self.name)
            .click(function () {
                self.speakName();
             });

    $element.find('.age')
            .text(self.age)
            .click(function () {
                self.speakAge();
             });

    // render element
    $container.append($element);
};

//////////////////////////////////////////////////////////////////////

var persons = [
    new Person({
        name: 'Tom',
        age: 30
    }),
    new Person({
        name: 'Dick',
        age: 25
    }),
    new Person({
        name: 'Harry',
        age: 45
    })
];

for (var i = 0; i < persons.length; i++) {
    persons[i].render($('#person-container'));
}
.person {
    border: 1px solid black;
    margin-bottom: 5px;
}


My main objection to your code is:

Principle of Least Surprise

I was pretty surprised that:

make_index_range<15u, 0u, 3u>

is the sequence

std::index_sequence<15, 12, 9, 6, 3>

given that it sure looks like we're going from 15 to 0 by 3s... which intuitively should produce std::index_sequence<>. You already do correctly provide two type aliases, where make_index_range is an alias for make_integer_range... so if somebody wants a negative range, they should have to do:

make_integer_range<int, 15, 0, -3>.

That change will also simplify your implementation, which leads into...

Simplify, Simplify, Simplify

Once you drop the increasing/decreasing check, the code becomes simpler. We are always going from Begin to End by Step.

First, let's determine the size of our sequence. For signed integers, we can just divide by Step and floor at 0. For unsigned integers, we have to ensure that End is at least as big as Begin:

template <class T, T Begin, T End, T Step>
struct sequence_size
: std::conditional_t<
        std::is_signed<T>::value,
        std::integral_constant<T, std::max<T>(0, (End - Begin)/Step)>,
        std::integral_constant<T, (End >= Begin) ? (End - Begin)/Step : 0>
        >
{ };

And then, with a default template parameter, our detail::make_integer_range can just be a simple pack expansion. No need for separate cases for increasing/decreasing sequences, since that would be handled by simply having a negative Step for signed integral types:

namespace detail {
    template <class T, T Begin, T End, T Step,
        typename = std::make_integer_sequence<T, sequence_size<T, Begin, End, Step>::value>
        >
    struct make_integer_range;

    template <class T, T Begin, T End, T Step, T... Idx>
    struct make_integer_range<T, Begin, End, Step, std::integer_sequence<T, Idx...>>
    {
        using type = std::integer_sequence<T, Idx * Step + Begin...>;
    };
}

template <class T, T Begin, T End, T Step>
using make_integer_range = typename detail::make_integer_range<T, Begin, End, Step>::type;

template <std::size_t Begin, std::size_t End, std::size_t Step>
using make_index_range = make_integer_range<std::size_t, Begin, End, Step>;

Add Default Step

Using 1 as a default is pretty standard, so let's just do that:

template <class T, T Begin, T End, T Step=1>
using make_integer_range = typename detail::make_integer_range<T, Begin, End, Step>::type;

template <std::size_t Begin, std::size_t End, std::size_t Step=1>
using make_index_range = make_integer_range<std::size_t, Begin, End, Step>;

Add Default Start

You could also provide a default beginning by having your aliases take a pack of ints. Something like:

template <class T, T... Vals>
using make_integer_range = typename detail::make_integer_range_variadic<T, Vals...>::type;

template <std::size_t... Vals>
using make_index_range = make_integer_range<std::size_t, Vals...>;

With:

template <class T, T... Vals>
struct make_integer_range_variadic
: make_integer_range<T, Vals...>
{ };

template <class T, T End>
struct make_integer_range_variadic<T, End>
: make_integer_range<T, 0, End, 1>
{ };

template <class T, T Begin, T End>
struct make_integer_range_variadic<T, Begin, End>
: make_integer_range<T, Begin, End, 1>
{ };

This would allow:

make_index_range<5>       ==> <0, 1, 2, 3, 4>
make_index_range<2, 5>    ==> <2, 3, 4>
make_index_range<2, 5, 2> ==> <2, 4>

YMMV on whether or not you want to allow this, but just throwing this out as an option in case you do.


This docstring is very long and confusing. The official Python style guide recommends that you have a short one line summary of what the function does before launching into longer, detailed paragraphs.

def collect_request(transaction_id):
    '''Waits while collecting a mobile bank ID request.

    You can make a delay for 9 seconds before you start to call the Collect
    method. After 9s you begin to make CollectRequest with a 3 seconds delay
    between each collect. First answer will probably be
    OUTSTANDING_TRANSACTION, then USER_SIGN and at last COMPLETE. (After six
    OUTSTANDING_TRANSACTION you get NO_CLIENT, just to indicate that the user
    not yet has started her BankID client.

    After 180 seconds, you will at last get faultStatus EXPIRED_TRANSACTION'''

I'm not sure I got it quite right, so I'm sure you can come up with a better one. Also there's not much need for using url as a variable directly before it's used 'when you can pass it directly to Client. Though it should either be a constant defined elsewhere or a user provided parameter. There's a lot of values like that in here. Making something a constant makes it clearer what the value means, where it comes from and what it's for.

WSDL_URL = "some url"
PROVIDER = "bankid"

etc.

Your third if should actually be an elif, since the second and third conditions are mutually exclusive. You should then remove the continue and instead manually call break from inside your if response.progressStatus == 'COMPLETE' block. It makes more sense that way, that your loop breaks when this condition is fulfilled, rather than the continue being called in certain other cases. Unless you want to break even if any unhandled progressStatus value is received. ie. As it stands, if progressStatus is anything but 'OUTSTANDING_TRANSACTION', 'USER_SIGN' or 'NO_CLIENT' then the loop breaks. If that is intentional, then you should comment as such.

Also don't use the old syntax for exceptions, it's ambiguous and explicitly doesn't work in Python 3. You should use except WebFault as f. The reason it's ambiguous is that it doesn't allow you to do multiple exceptions properly, imagine you had to try do except WebFault, ValueError, f. It wouldn't make any sense, however you could do except (WebFault, ValueError) as f perfectly fine.


Another way to run reports on a SpiceWorks SQLite database using a linked server in SSMS?

Ouch.... you are not filtering the data you are selecting from the OPENQUERY source....

But, let's get some things straight first.... you say:

  either way I don't think it would have been clean and straightforward anyway

Using OPENQUERY automatically excludes any pretext of 'clean and straightforward'. They are incompatible.

So, as soon as you use OPENQUERY you can assume that you have already got ugly code (with a fat ass).

The trick is to use makeup - to cover up the blemishes.

In this case, you can filter the records, but you need to be creative.... you have:

SELECT * FROM OPENQUERY(SPICEWORKS, '
    SELECT users.email
        , tickets.id
    FROM tickets
        INNER JOIN users ON tickets.created_by = users.id')
WHERE id = @TicketID

I would suggest the following:

declare @ticketsql as nvarchar(1024)
;

set @ticketsql = '
    SELECT users.email
        , tickets.id
    FROM tickets
        INNER JOIN users ON tickets.created_by = users.id
    WHERE tickets.id = ' + @TicketID
;

select * FROM OPENQUERY(SPICEWORKS, @ticketsql)


The meaning of lock-free
Although your program is free of locks in the traditional sense, "lock free programming" typically describes a style of programming with certain guarantees.  One of these guarantees is that even if one or more threads are suspended indefinitely, other threads can continue to make progress.  This wikipedia article on Non-blocking algorithms describes "lock-free" and "wait-free" programming in more detail.
In your code, if one thread is permanently suspended between these two lines:

    prev = atomic_xchg64(&head->tail, node);
    prev->next = node;

then some other thread will spin forever in this loop:

                            while (ACCESS_ONCE(head->next) == next)
                                    head->next = ACCESS_ONCE(node->next);

and furthermore, no nodes past the node that the suspended thread "half-pushed" will be able to be popped.
ABA problem
Additionally, your code falls victim to the ABA problem.  Consider an initial situation with two nodes in your FIFO:
A -> B    (head->next = A, head->tail = B)

Suppose thread #1 calls __fifo_list_pop(), and gets to this line:

            if (cmpxchg_eq(&head->next, node, next) == node) {

Here, node will be A, and next will be  B, and the code is about to atomically change head->next from A to B.
Now suppose thread #1 is descheduled, and in the meantime, other threads pop both A and B off the FIFO, and then push A and C back on the FIFO.  Now, your FIFO looks like this:
A -> C    (head->next = A, head->tail = C)

If thread #1 now wakes up, it will perform the atomic exchange, causing head->next to point at B which isn't even alive any more:
A -> B    (but B was already popped and is now dead)


Run query and insert the result to another table

psycopg2 already implements your extract_table

Since you're using cursor.copy_from to load data into the new table, why not use something along the lines of cursor.copy_to to write them to a file?

However, cursor.copy_to will translate to COPY table_name TO 'filename' [ [ WITH ] ( option [, ...] ) ] in its current implementation. You thus need to use cursor.copy_expert and provide the whole SQL query to be executed.

The copy_expert call will write to STDOUT or read from STDIN and redirect to/from the file-like object passed as the second argument (file). I believe the query to execute should look like

copy_query = "COPY (" + query + ")"\
    "TO STDOUT"\
    "WITH CSV HEADER DELIMITER '\t' NULL '' ENCODING 'utf-8'"

with or without the HEADER option; not sure how copy_from would handle it.

You can thus rewrite copy_table something along the lines of:

# Using format string because we trust the query, are we?
copy_query = "COPY ({}) TO STDOUT WITH CSV HEADER DELIMITER '{}' NULL '' ENCODING '{}'".format(src_query, DELIMITER, ENCODING)
with NamedTemporaryFile('w+t', encoding=ENCODING, newline='') as fp:
    logging.info("Writing result to a temporary file.")
    with src_conn.cursor() as cursor:
        cursor.copy_expert(copy_query, fp)
    fp.flush()
    fp.seek(0)
    logging.info("Copying result to {}".format(dst_table_name))
    with dst_conn.cursor() as cursor:
        if truncate_table:
            logging.info("Truncating {}.".format(dst_table_name))
            # It seems like we do trust the new name too
            cursor.execute('TRUNCATE {};'.format(dst_table_name))
        cursor.copy_from(file=fp, table=dst_table_name, sep=DELIMITER, null="")
    dst_conn.commit()

Handling database state

The dst_conn.commit() at the end of copy_table is bad practice. You most likely want to use the context manager available on connection objects to handle that for you, especially if things goes wrong.

Using the connection's context manager is to handle commits and rollbacks only and does not close the connection when leaving the context block. So you can write, say

conn = psycopg2.connect(...)

with conn:
    # Use cursor(s)

with conn:
    # Use (other) cursor(s)

with conn:
    # You get the deal

conn.close()

You're also handling the creation of named cursors using lot of duplicated code. I understand that their use differ a bit from client cursors, but the creation can be simplified to:

cursor = conn.cursor(name=get_random_cursor_name() if use_named_cursor else None)

since the name argument is already None by default.

You can even go further by letting the user provide its own name using constructs such as:

def copy_table(..., cursor_name=None, ...):
    ...
    with src_conn:
        with src_conn.cursor(name=cursor_name) as cursor:
            ...

This way, you can have calls such as:

copy_table(src_conn, dst_conn, query, dst_table_name='foobar')
copy_table(src_conn, dst_conn, query, cursor_name='foobar', dst_table_name='foobar')
copy_table(src_conn, dst_conn, query, cursor_name=get_random_cursor_name(17), dst_table_name='foobar')

Protect from user input

As usual in SQL, you should not trust user input. As such, you might want to not directly use the provided query string. However you do want to build the copy query yourself. For these usages, psycopg2 provides the cursor.mogrify method.

The copy query can thus be built using:

copy_query = "COPY (%s) TO STDOUT WITH CSV HEADER DELIMITER '%s' NULL '' ENCODING '%s'"

and then passed to copy_expert with:

cursor.copy_expert(cursor.mogrify(copy_query, (src_query, DELIMITER, ENCODING)), fp)

You may also be interested in providing a way to build the source query by binding parameters. In such cases, variable length arguments can be used to simplify handling of bound arguments:

def copy_table(query, *args, src_conn, dest_conn, dest_table_name,
               cursor_name=None, truncate_table=False):
    copy_query = "COPY (%s) TO STDOUT WITH CSV HEADER DELIMITER '%s' NULL '' ENCODING '%s'"
    with NamedTemporaryFile('w+t', encoding=ENCODING, newline='') as fp:
        logging.info("Writing result to a temporary file.")
        with src_conn:
            with src_conn.cursor(name=cursor_name) as cursor:
                query = cursor.mogrify(query, args)
                copy_query = cursor.mogrify(copy_query, (query, DELIMITER, ENCODING))
                cursor.copy_expert(copy_query, fp)
        fp.flush()
        fp.seek(0)
        logging.info("Copying result to {}".format(dst_table_name))
        with dest_conn:
            with dest_conn.cursor() as cursor:
                if truncate_table:
                    logging.info("Truncating {}.".format(dst_table_name))
                    cursor.execute('TRUNCATE %s;', (dst_table_name,))
                cursor.copy_from(file=fp, table=dst_table_name, sep=DELIMITER, null="")

You will need to use named arguments for anything other than the query and its parameters:

copy_table('SELECT * FROM public.my_table WHERE product_count > %s', 200,
           src_conn=database_remote,
           dest_conn=database_local,
           dest_table_name='public.my_table_subset',
           cursor_name='foobar')


Finding consecutive occurrences of a value in an array

First off your code doesn't work as you want it too.
>>> has22([2, 1, 2, 2, 1, 2, 1])
False
>>> has22([2, 1, 2, 1, 2, 1, 2])
True

Your code also doesn't follow PEP8, and the name of your variables are, long, really long.
This code, as you've written it, intends to look forwards and backwards, consequently, this causes the code to use more memory than needed. It also adds to the complexity of the code, thus making it harder to read.
Instead if you make the code travel only one way, and change forward_start to prev_index and next_forward_occurrence to index, you can obtain:
def has22(nums):
    total_occurrences = nums.count(2)
    if total_occurrences >= 2:
        prev_index = 0
        for _ in xrange(total_occurrences - 1):
            index = nums.index(2, prev_index)
            if nums[index] == nums[index + 1]:
                return True
            prev_index = index + 1
    return False

I don't like the use of nums.count(2) as it causes the algorithm to become \$O(2n)\$.
Instead I'd break upon index becoming -1.
def has22(nums):
    prev_index = 0
    while True:
        index = nums.index(2, prev_index)
        if index == -1:
            break
        if nums[index] == nums[index + 1]:
            return True
        prev_index = index + 1
    return False

But both of these are still, harder to read compared to the algorithm that you stated in the question.

I do aware of a quick solution by iterating the list in a for loop and comparing current and next items for equality until it reaches the end

Here is the algorithm you're talking about:
def has22(nums):
    nums = iter(nums)
    prev = next(nums, StopIteration)
    if prev is not StopIteration:
        for num in nums:
            if num == prev and num == 2:
                return True
            prev = num
    return False

Where a simpler approach would use any and zip, and a smarter approach would also use itertools.
def has22(nums):
    return any(num1 == num2 and num1 == 2 for num1, num2 in zip(nums, nums[1:]))

from itertools import tee, izip

def has22(nums):
    a, b = tee(nums)
    next(b, None)
    return any(num1 == num2 and num1 == 2 for num1, num2 in izip(a, b))


Recursion can make for elegant code, but it can also make for very slow code. Calculating Fibonacci numbers and Factorials are both classic examples where the recursive algorithm is simple to implement, but slow beyond the first few (and very small) input values.

I don't know Delphi, so I quickly implemented this in VB6, but you should be able to consider it psuedo-code.

Function Factorial(x As Integer) As Long
    Dim result As Long
    Dim startIndex As Integer

    result = 1
    For startIndex = x To 1 Step -1
        result = result * startIndex
    Next

    Factorial = result
End Function


The function throws NumberFormatException and IllegalArgumentException.
Your implementation caters to your edge cases, take these for example:

1Kb (Do you wish to handle bits). This gets converted to 1KB (unwantedly).
1M iB (Incorrect position of space)
1 (No units).

Not sure if the input is manual or system feeded.
Why not have a function that validates the input and if it can be tailored (1MiB), it returns a operable string.
A Map can be used instead of the units' char array, for loop and Math.pow for each input.
getBytesFromFormattedSize() calls getBytesFromSize() which again calls getBytesFromFormattedSize(). Instead a flow as this would look clean.

 getBytesFromFormattedSize(){
     //Get a valid string (if possible) (in two forms value and unit)
     // Proceed thereof.
 }

fixedSize.contains()  has an O(n) time complexity. Instead a boolean would easily suffice the otherwise redundant call once we insert a space.
Names such as arr, size, bytes are ignorant to their puprose.
Too much of hard coded values to actually understand the flow.
Should I return 1000? http://en.wikipedia.org/wiki/Mebibyte
return Integer.parseInt(arr[0]); assumes that the value would not be greater than INT_MAX? Does the input guarantee that?
If size is an empty string, charAt(0) could give exception IndexOutOfBoundsException().


Computation of inter-grid distance array for 2D lattice

1. Introduction

Veedrac is totally correct: you can't expect to compute a \$ 1000^2 \$ by \$ 1000^2 \$ array of distances: this would have \$ 10^{12} \$ elements, and if each element is a double-precision floating-point number then that would require 8 terabytes of memory.

So you need to reconsider your approach to whatever it is you are trying to do. You're going to have to compute these distances when you use them, instead of precomputing an array. Unfortunately, you haven't explained what you are trying to do, so we can't help. The only thing we can do, given what you've presented, is show you how to compute your result a bit faster and a bit tidier.

2. Review

There are no docstrings or comments. What do your functions compute? What is the meaning of variables like U? It's very hard to provide advice about code like this when the purpose is unclear.
The use of the print statement means that the code is not portable to Python 3. Better to use the print function.
Python has a built-in module timeit for timing execution of code. It's better to use this instead of writing your own.
Code at the top level of a module makes it hard to test a program or time its execution. It would be better to put this code into a function, for example:

def dist_array(U=60):
    Ulist = range(U**2)
    a = []
    ...
    return np.vstack(a)

Then in the interactive interpreter you could run:

>>> from timeit import timeit
>>> timeit(dist_array, number=1)
554.5194303740282

3. Performance

As always when speeding up NumPy code, you should scrutinize every Python loop—that is, every for, while, generator and comprehension—to see if the computation can be vectorized, that is, transformed into a sequence of NumPy whole-array operations. The usual approach is to start by removing the innermost loops and work outwards.

So let's start with the group of lines:

di = np.array([np.abs(FromListToGrid(l)[0]-FromListToGrid(i)[0])
               for i, x in enumerate(Ulist)])
di = np.minimum(di, U-di)
dj = np.array([np.abs(FromListToGrid(l)[1]-FromListToGrid(i)[1])
               for i, x in enumerate(Ulist)])
dj = np.minimum(dj, U-dj)
d = np.sqrt(di**2+dj**2)

I'm going to give speedups in terms of percentages of the runtime for the original version of the code.

Note that x is unused, so we don't need the enumerate, we can just write for i in range(len(Ulist)) which is the same as for i in Ulist. This saves about 2%, bringing the runtime down to 98%.
Expand the function FromListToGrid inline:

di = np.array([np.abs(np.floor(l / U) - np.floor(i / U))
               for i in Ulist])
di = np.minimum(di, U - di)
dj = np.array([np.abs(l - np.floor(l / U) * U - i + np.floor(i / U) * U)
               for i in Ulist])
dj = np.minimum(dj, U - dj)
d = np.sqrt(di ** 2 + dj ** 2)

This brings the runtime down to 32%.
Note that l does not depend on i so some of the computation can be moved out of the loops:

zi = np.floor(l / U)
di = np.array([np.abs(zi - np.floor(i / U)) for i in Ulist])
di = np.minimum(di, U - di)
zj = l - zi * U
dj = np.array([np.abs(zj - i + np.floor(i / U) * U) for i in Ulist])
dj = np.minimum(dj, U - dj)
d = np.sqrt(di**2+dj**2)

This brings the runtime down to 22%.
Avoid the list comprehensions altogether using NumPy whole-array operations:

Uarray = np.arange(U ** 2)
zi = np.floor(l / U)
di = np.abs(zi - np.floor(Uarray / U))
di = np.minimum(di, U - di)
zj = l - zi * U
dj = np.abs(zj - Uarray + np.floor(Uarray / U) * U)
dj = np.minimum(dj, U - dj)
d = np.sqrt(di ** 2 + dj ** 2)

This brings the runtime down to 0.4%.
Move the computation of anything that does not depend on l out of the loop over l. Also, use numpy.hypot instead of np.sqrt(di ** 2 + dj ** 2):

a = []
Uarray = np.arange(U ** 2)
Ui = np.floor(Uarray / U)
Uj = Ui * U - Uarray
for l in Uarray:
    zi = np.floor(l / U)
    di = np.abs(zi - Ui)
    di = np.minimum(di, U - di)
    zj = l - zi * U
    dj = np.abs(zj + Uj)
    dj = np.minimum(dj, U - dj)
    d = np.hypot(di, dj)
    a.append(d)

This brings the runtime down to 0.2%.
Now we can start to remove the loop over l. This can be done in stages, lifting one line at a time out of the loop (and checking that the results are correct as we go). To show how this works, let's lift the computation of di out of the loop. We have:

for l in Uarray:
    zi = np.floor(l / U)
    di = np.abs(zi - Ui)
    di = np.minimum(di, U - di)
    # etc.

We can easily compute all the values of zi at once, like this:

Zi = np.floor(Uarray / U)
for l in Uarray:
    di = np.abs(Zi[l] - Ui)
    di = np.minimum(di, U - di)
    # etc.

Now we observe that Zi is just the same as Ui, so that becomes:

for l in Uarray:
    di = np.abs(Ui[l] - Ui)
    di = np.minimum(di, U - di)
    # etc.

Next we lift Ui[l] - Ui out of the loop. This expression computes the pairwise differences between Ui[l] and all elements in Ui. NumPy's "broadcasting" mechanism means that we can do this in one step, for all values of l, just by indexing Ui in two different ways, like this:

Ui.reshape(-1, 1) - Ui.reshape(1, -1)

In fact, broadcasting means that we don't even need the second reshape; this is the same as:

Ui.reshape(-1, 1) - Ui

Putting that together, we now have:

di = np.abs(Ui.reshape(-1, 1) - Ui)
di = np.minimum(di, U - di)
for l in Uarray:
    # etc.

We can keep applying this process to lift all the computation out of the loop (I won't go into the details), resulting in this:

def dist_array(U=60):
    Uarray = np.arange(U ** 2)
    Ui = np.floor(Uarray / U)
    di = np.abs(Ui.reshape(-1, 1) - Ui)
    di = np.minimum(di, U - di)
    Uj = Ui * U - Uarray
    dj = np.abs(Uarray.reshape(-1, 1) - Ui.reshape(-1, 1) * U + Uj)
    dj = np.minimum(dj, U - dj)
    return np.hypot(di, dj)

There's probably a little bit more time to be squeezed out by using NumPy's out= parameter to reduce the memory usage, but I'll stop here.

This is more than 500 times as fast as the original code, and computes the U=60 case in about a second on my laptop.

4. Simplifying

The computation of dj now looks like this:

    Uj = Ui * U - Uarray
    dj = np.abs(Uarray.reshape(-1, 1) - Ui.reshape(-1, 1) * U + Uj)

If we do the multiplication before the reshape, this becomes:

    dj = np.abs((Uarray - Ui * U).reshape(-1, 1) + Uj)

which is:

    dj = np.abs(-Uj.reshape(-1, 1) + Uj)

and since we're taking the absolute value, that's:

    dj = np.abs(Uj.reshape(-1, 1) - Uj)

which is symmetric with the computation of di.
We have:

    Uarray = np.arange(U ** 2)
    Ui = np.floor(Uarray / U)
    Uj = Ui * U - Uarray

but this is the same as:

    Uarray = np.arange(U ** 2)
    Ui, Uj = divmod(Uarray, U)

and this is the same as:

    Ui, Uj = np.mgrid[:U, :U]
    Ui = Ui.reshape(-1)
    Uj = Uj.reshape(-1)

(see numpy.mgrid).
Now that the computation of di and dj is so similar, it makes sense to extract the common code into a function, like this:

def dist_array(U=60):
    def d(i):
        i = np.abs(i.reshape(-1, 1) - i.reshape(-1))
        return np.minimum(i, U - i)
    i, j = np.mgrid[:U, :U]
    return np.hypot(d(i), d(j))


It's a little hard to review code like this in Python because we're pretending there's no built-in list class, but a Python without a list doesn't feel like Python at all, so the code ends up looking like some other language.

I mention this because there are named tuples in Python 2.7 and Python 3, and they pretty much do exactly what your Node class does:

import collections
Node = collections.namedtuple('Node', ['item', 'link'])

n = Node(item=22, link=self.head)  # Make a new node.

Then again, if we're pretending lists don't exist, maybe we should pretend tuples don't exist either.

There's a lot of duplication in your code. These two classes are very similar. The push and append methods appear to be exactly the same method, for example. The two pop methods are almost exactly the same. The constructors are the same. So this seems like a good place to use inheritance. Make a base class, maybe with a name like LinkedList, which has the constructor and any methods which are exactly the same. Make the List and Stack both inherit from the LinkedList.

In your current code, you have separate implementations for pop that seem to do exactly the same thing, except that the stack version also removes the item. I would add separate pop and top methods. pop always removes and returns the top item, while top just returns the item without removing it. Then, if you want to make it impossible to remove the top item of a list, override the pop method to just call top. This is more or less how C++'s STL works, although C++'s pop doesn't return the item it removed.

So the final code would look something like this:

class LinkedList:
    def __init__(self):
        self.top_index = 0
        self.head = Node()

    def push(self, item):
        # Code from push / append here

    def pop(self):
        # Code that removes and returns the top here.

    def top(self):
        # Code that just returns the head here.

    def is_empty(self):
        return self.top_index == 0

class List(LinkedList):
    def insert(self, item, pos=0):
        # Code for insert here.

class Stack(LinkedList):
    # Whatever functionality is unique to the stack.
    # If there isn't any, you can consider not having a stack
    # class and just using a LinkedList.

I'll leave the details up to you, but that's basically how I would do it.

Am I right in thinking the following function is incomplete?

def pop(self, *args):
    if not args:
        item = self.head.item
        head = self.head.link
        return item

Were you going to add an else clause the retrieves the item at a specified index, like what you have in get? If that was what you had in mind, I think default arguments would be a better solution than using *args. Using get as a model, something like this:

def get(self, pos=0):
    if pos == 0:
        return self.head.item
    elif pos > 0:
        current = self.head
        count = 0
        while count < pos - 1 and current.link != None:
            current = current.link
            count += 1
       return current.item
    else:
       raise IndexError()

I find this clearer than the version with *args. Also, in case you wanted to use *args in the future, you can now do so without having to parse it.

Your use of style conventions and code formatting looks good. It can be confusing to get this right in Python since the standard library sets such a horrible example :)


Auto change page title while bookmarking a page

That seems like a very fragile thing to do.  If it works at all, you would still only succeed on browsers where the keyboard shortcut is ControlD.  It probably won't work on a Mac or on a mobile device.  It will probably break if the user interface is in a non-English locale with different keyboard shortcuts.  It would also have no effect if the user initiates the bookmark creation using the menu rather than a keyboard shortcut.

You should probably step back and consider why such a hack is necessary in the first place.  Ideally, you should design the page titles such that they already make reasonable bookmark titles.


Shell script to download and extract a tarball from GitHub

You're looking for set -e. From POSIX:

  -e
  When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.

In other words, plain commands cause the shell to exit if they fail. (You can use something like command || true to allow command to return nonzero.) If you need to perform some cleanup, you can set a trap for the EXIT pseudo-signal.

And better double-quote all your variable expansions. That way your script won't fail horribly if you ever point it at a directory or an URL containing ? or * or a space.

dry -r
wget --no-check-certificate "$location" --output-document="$renamed"
mkdir -p "$dir"
gunzip "$renamed"
echo "extracting to $dir"
tar xf "$file.tar" --directory "$dir" --strip-components 1
echo "Cleaning up..."
rm -r "$file.tar"
echo "Done"

Another useful shell idiom to pass optional arguments to a shell script without hassle is to set variables only if they're unset. That way you can pass arguments through the environment, e.g. file=v0.9.1 myscript.

: "${file=v0.9}"
: "${renamed=$file.tar.gz}"
: "${dir=utils/external/firepython/}"
: "${location=https://github.com/darwin/firepython/tarball/$file}"


Prove that the graph is a valid tree in Python

Before going in depth of your algorithm, a few stylistics notes:

I assume that the class Solution(object) thing is required by leetcode, so it might not apply. But as a general note, your validTree method does not need to store/interact with any state. Thus there is no need for it to be a method and would benefit to be defined as a function. Also the naming should be snake_case as per PEP8: def valid_tree(n, edges):. is_valid_tree might also be a better name.
In Python 2, the keys method of dictionaries build and return a new list. It is generally recommended that your use iterkeys instead which return a proxy object to the actual keys of the dictionary. However, such object does not support the len protocol. But the dictionary support it without having to build anything new: len(visited_nodes).

Tidy up your special case

Your algorithm performs two checks:

Every node is reached through an edge;
Every node can reach each other through at most one path.

The only special case to that is, for only one node, to have no edges. The other cases will be handled by the for loops (which will do nothing if edges is empty) and the last check. Thus I would write:

def is_valid_tree(n, edges):
    if n == 1:
        # 1 node must not have edges
        return not edges
    ...

You can also remove all special cases by using default values in visited_nodes. More on that later.

Don't use stuff that you don't use

Sounds weird, doesn't it? But the same goes for your use of defaultdict: you use it without using the extra functionalities over dict. In fact, using visited_nodes = {} will not change anything in your program. So use that instead, it will remove a bit of overhead.

defaultdicts usage is to make use of default values instead of having to explicitly assign them, such as in:

d = defaultdict(list)
d['test'].append('something')
d['test'].append('something else')
d['other test'].append('a third thing')
print(d) # defaultdict(<class 'list'>, {'test': ['something', 'something else'], 'other test': ['a third thing']})

But instead, here you explicitly assign empty lists before assigning to them. This is because you explicitly want to define the key of the dictionary; and, in fact, you do not care about the value. Since you do not use values, why using a dictionary to start with? Use a set they are like dictionaries, but only for keys:

def is_valid_tree(n, edges):
    if n == 1:
        return not edges

    visited_nodes = set()
    count = True
    unvisited = []

    for key, value in edges:
        if key in visited_nodes and value in visited_nodes:
            return False

        if count:
            visited_nodes.add(key)
            visited_nodes.add(value)
            count = False
            continue
        if key in visited_nodes:
            visited_nodes.add(value)
        elif value in visited_nodes:
            visited_nodes.add(key)
        else:
            unvisited.append([key, value])

    for key, value in unvisited:
        if key in visited_nodes and value in visited_nodes:
            return False

        if key in visited_nodes:
            visited_nodes.add(value)
        elif value in visited_nodes:
            visited_nodes.add(key)
        else:
            return False

    return n == len(visited_nodes)

Remove "duplicated" checks

First of, the count variable is useless: it only store whether the dictionary (or the set) is empty. You can get the exact same information using not visited_nodes which is True when visited_node is empty and False otherwise.

Second, you want to add both key and value as key (so maybe they need to be renamed) of visited_nodes if either of them is already one. You can thus simplify the writing using a boolean or and retain the same functionality:

if key in visited_nodes or value in visited_nodes:
    visited_nodes.add(key)
    visited_nodes.add(value)

Using the set approach also help you write less verbose code: use the intersection & operator of sets:

for edge in edges:
    edge = set(edge)
    commons = visited_nodes & edge

    # If a path exist between the nodes in edge
    if commons == edge:
        # A cycle exist and thus it is not a tree
        return False

    # If a node has been visited or if it is the first edge
    if commons or not visited_nodes:
        # Add the path
        visited_nodes.update(edge)
    else:
        # Process later
        unvisited.append(edge)

Third, as stated earlier, you can get rid of all your special cases by initializing visited_nodes = {0}. This will allow you to remove the first check (if n == 1) since it is now handled by return n == len(visited_nodes). And it will also handle adding branches from the node 0 instead of any two first nodes.

Last, the body of both for loops is pretty similar. You may want to factorize it out. Unfortunately, I'm not able to come up with something elegant. It is possible to retry edges by appending them again at the end of edges instead of using unvisited, like so:

def is_valid_tree(n, edges):
    visited_nodes = {0}

    for edge in edges:
        branch = set(edge)
        commons = visited_nodes & branch

        # If a path exist between the nodes in edge
        if commons == branch:
            # A cycle exist and thus it is not a tree
            return False

        # If a node has been visited already
        if commons:
            # Add the branch
            visited_nodes.update(branch)
        else:
            # Process later
            edges.append(edge)

    return n == len(visited_nodes)

Unfortunately this can lead to infinite loops in cases where your code would have reached that return False in the second for loop. However, we can come up with some checks to prevent that. And it's still better than your solution because…

It appears that you have a bug

Calling Solution().validTree(5, [[0, 1], [3, 4], [2, 3], [1, 2]]) returns False. This is because you delay checking for [[3, 4], [2, 3]] but, when running the second checks, instead of delaying [3, 4] which would be integrated in a third pass, you return False. Same would be true for inputs such as Solution().validTree(n, [[0, 1], [n-2, n-1], [n-3, n-2], ..., [1, 2]]) which would need n-3 delayed passes to come to the answer True.

All in all, this doesn't sound like \$O(n)\$ worst case, and you need to fix that bug. Either you try something different, or you patch the previous simplification. I’d go with this one and use a Counter to track the number of time we delayed the treatment for a given edge. Special care has to be taken to provide hashable objects to the counter:

from collections import Counter

def is_valid_tree(n, edges):
    visited_nodes = {0}
    delays = Counter()

    for edge in edges:
        branch = set(edge)
        commons = visited_nodes & branch

        # If a path exist between the nodes in edge
        if commons == branch:
            # A cycle exist and thus it is not a tree
            return False

        # If a node has been visited already
        if commons:
            # Add the branch
            visited_nodes.update(branch)
        else:
            edge = tuple(edge)
            delays[edge] += 1
            if delays[edge] < n:
                # Process later
                edges.append(edge)
            else:
                # Too much delay, can't be processed
                return False

    return n == len(visited_nodes)


Iterate dictionary object efficiently in c# with pre defined keys?

I believe you can do this if you put the header keys inside an array, and then you can loop over the array itself, and use TryGetValue for the dictionary.

This is the simplest form for it :

public readonly string[] HeaderKeys = {
    "header-abc",
    "header-pqr",
    "header-def",
    "header-hip"
}

for(var x = 0; x < HeaderKeys.Length; x++)
{
    var isKeyExist = values.TryGetValue(HeaderKeys[x], var KeyValue);

    // if there is no key defined, just go to the next iteration.
    if(!isKeyExist) { continue; }

    switch (HeaderKeys[x])
    {
      case "header-abc":
          // inline assigning
          HeadOne = HeadOneId = KeyValue;
          break;
      case "header-pqr":
          HeadTwo = HeadTwoId = KeyValue;
          break;
      case "header-def":
          HeadThree = HeadThreeId = KeyValue;
          break;
      case "header-hip":
          HeadFour = HeadFourId = KeyValue;
          break;
      //.. bunch of other case block here with similar stuff
    }
}

You need a readonly string[] this way, it can't be changed once initialized. System.Array is the lightest, and yet the simplest array, so using for loop with it would give you the fastest iteration over any other collection type.

Next, you only want to pass each header key to the TryGetValue and get the value. The TryGetValue would return true if the value has been out, and false if there is none.

Then, you have one line if condition :

    // if there is no key defined, just go to the next iteration.
    if(!isKeyExist) { continue; }

This would skip any iteration if the result of TryGetValue is false.
And I believe that string.IsNullOrWhiteSpace(KeyValue) is an extra unneeded work. So, I got rid of it. because even if the KeyValue is null or empty, the variables would be also null. So, at this stage you're just assigning variables, the other validation would be on other part of the current system where it needs to be critical to have a value.

Now, assigning the variables like this :

HeadOne = KeyValue;
HeadOneId = HeadOne;

can be simplified to this :

HeadOne = HeadOneId = KeyValue;

the difference is that the first one would let the compiler read the value twice. While the second would read it once, and assign it twice.


Parsers are for parsing

This is probably the strangest primality test I've ever seen. So for those that want to write their own primality test, please don't use this approach.

Almost all your functions can be written without a Parser. toXTerminatedAs is probably the best example:

toXTerminatedAs :: Int -> String
toXTerminatedAs n = replicate n 'a' ++ "x"

That's easy to read, and more likely to be correct. Either way, I assume you know that, so let's get started with the actual review.

Try not to shadow existing names

We return to toXTerminatedAs:

toXTerminatedAs :: Int -> String
toXTerminatedAs = end . parse (manyAccum acc digit) "" . show
  where acc digit cur = concat (replicate 10 cur) ++ toAs digit
        toAs digit    = replicate (fromEnum digit - 48) 'a'
        end (Left _)  = error "I can't deal with negative numbers, sorry"
        end (Right x) = x ++ "x"

We have three digits here. Two of them are function arguments, but the first one is Parsec's digit function. That's misleading. Use d or another name that's not already in use. Alternatively, import Parsec qualified or as P to show the difference more clearly.

Use the standard library

We stay at toXTerminatedAs. fromEnum digit - 48 isn't that clear to someone who doesn't know Enum instances or 48 well. But digitToInt shows its intend very well. It's provided by Data.Char:

import Data.Char

-- ....

toXTerminatedAs :: Int -> String
toXTerminatedAs = end . parse (manyAccum acc digit) "" . show
  where acc d cur     = concat (replicate 10 cur) ++ toAs d
        toAs d        = replicate (digitToInt d) 'a'
        end (Left _)  = error "I can't deal with negative numbers, sorry"
        end (Right x) = x ++ "x"

isLeft is provided by Data.Either, so no reason to implement it yourself.

Also, try to avoid ++ in recursive functions or accumulators, as it turns \$\mathcal O(n)\$ algorithms into \$\mathcal O(n^2)\$ ones.

Encapsulate often used functionality in a function

You often use parse parser "". That's somewhat error prone as you can accidentally forget the file name.

Instead write a small function that takes care of the SourceName for you:

parse' :: Stream s Identity t => Parsec s () a -> s -> Either ParseError a
parse' p = parse p ""

While we're at it, we add a

parseViaX p = isLeft . parse' p . toXTerminatedAs

Add type signatures

parseViaX is missing its type signatures because I don't know the ones of fibParser and primeParser. Always add type signatures to top-level bindings. Not only will it serve as minimal documentation, but it will also make sure that the compiler does not infer too general types or types you didn't expect.

Document complicated expressions

fibParser and primeParser should get some documentation.

Bottom line

Don't mix parsing and arithmetic, at least for arithmetic tests. It's messy and hard to read. Both fib and prime are easy to write without any parsing at all.

If you were going for code obfuscation: kudos to you, that was brilliant.


Cast an object to Decimal? or Int? etc but leave it as null if it is null

If you know that the object is always either double or null, then that's exactly what the double? type can represent and you can convert to that using a cast:

object obj = ...;
double? doubleValue = (double?)obj;

And once you have double?, you can cast it to decimal? and it will work both for the case when the value is null and when isn't:

decimal? decimalValue = (decimal?)doubleValue;

Or, on a single line:

decimal? decimalValue = (decimal?)(double?)obj;

Apart from being clear, this approach is also likely going to be pretty efficient.


jQuery form builder for parsing email array into single input

Extract the code that creates a row to a function, make it return the row created with all the elements inside of it, so that you can use it like this:

var $newAuthorityContainer = $(".new-authority-container");
var $row = createRow().appendTo($newAuthorityContainer);

And then again later:

var $newMemberContainer = $(".new-member-container");
var $row = createRow().appendTo($newMemberContainer);

Alternatively, pass in the container that you want to add the row to, for example:

var $newMemberContainer = $(".new-member-container");
createRow($newMemberContainer);

The function for this latter example:

function createRow($container) {
    var $row = $('<div />', {
        class: 'row'
    }).appendTo($container);

    var $large11 = $('<div />', {
        class: 'large-11 columns'
    }).appendTo($row);

    var $input = $('<input>', {
        type: 'text',
        placeholder: 'email@domain.com',
        class: 'authority-email'
    }).appendTo($large11);

    var $large1 = $('<div />', {
        class: 'large-1 columns'
    }).appendTo($row);

    var $removeContainer = $('<div />', {
        class: 'remove-container'
    }).appendTo($large1);

    var $remove = $('<a>', {
        href: '#',
        class: 'remove'
    }).html('<i class="fa fa-fa fa-remove"></i>').appendTo(
        $removeContainer);
}

I don't see other troubling duplication.

However, I see a bit troubling typo in the variable name authortyEmails. This could lead to errors, so I suggest to fix that.


Parsing data from big json field and geocode services then store to PostgreSQL using psycopg2 instead django-orm

Avoid globals

There is no need in using the global keyword here since you’re not modifying your conn. But there is also no need to access this variable at global scope, you can easily pass it as parameter.

One of the advantages of using parameters instead of a global variable being that you can more easily test each function with a custom connection when you need to.

Avoid top-level code

conn = psycopg2.connect("dbname=gym user=gyms")
data = get_data(conn) # Adding parameter from previous advice
for d in data:
    fill_data(conn, d) # Adding parameter from previous advice
conn.close()

Is better within its own function: you get the workflow at first glance. You can also use the function parameters to pass the connection credentials.

Using a function here lets you easily write:

if __name__ == '__main__':
    time_start = time.time()
    check_data("dbname=gym user=gyms")
    print 'Timeit %s' % (time.time() - time_start)

You clearly see there what is computation and what is timming. This is also best practice to wrap the executable part of your code under if __name__ == '__main__'.

But you are usually better off using timeit for performances measurement.

Avoid managing database state yourself

psycopg2 provide context managers to wrap connection or cursor objects. For the former it handles auto-commit/rollback based on how things went within the context; and for the latter it auto-closes it.

You can thus write

def get_data(conn):
    with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:
        cursor.execute("""
                       SELECT *
                       FROM dblgis_grabber_firm;
                       """)
        return cursor.fetchall()

and for update_data, you’ll need to auto-commit/rollback the connection:

def update_data(conn, id_row, row, data):
    with conn:
        with conn.cursor() as cursor:
            cursor.execute(
                "UPDATE dblgis_grabber_firm SET %s=%s WHERE id=%s;",
                (AsIs(row), data, id_row)
            )

I removed the return statement since you never make use of it.

Improve get_from_contacts

First of, the name is misleading. It doesn't get anything, it set data in the database. It probably should be named update_from_contacts. Alternatively, you could keep the name get_from_contacts and have that function actually do what it claims to do; and nothing more:

def get_from_contacts(contact_group, representation):
    result = []
    for contacts in contact_group:
        for contact in contacts.get('contacts'):
            if contact.get('type') == representation:
                result.append(unicode(contact.get('text')))
    return '; '.join(result)

You will need to have update_data calls near your get_from_contacts; but it separate concerns. And you can save on number of parameters.

You could also improve the overall execution: initialyzing a list to the empty list and appending inside a for loop is often an anti-pattern in python and better served with a list comprehension. Here the join call calls to using a generator expression:

def get_from_contacts(contact_group, representation):
    return '; '.join(
        unicode(contact.get('text'))
        for contacts in contact_group
        for contact in contacts.get('contacts')
        if contact.get('type') == representation
    )

Avoid redundancy

In fill_data, there are several constructions that look alike. You should be able to extract the structure from the data and use iterations to achieve the desired result without copy/pasting similar blocks of code:

GEO_FETCH = {
    'street': get_street,
    'street_number': get_house,
    'postcode': get_postcode,
}

CONTACT_FIELDS = {
    'phone_number': 'phone',
    'site': 'website',
    'email': 'email',
}

def fill_data(conn, instance):
    longitude = instance.get('longitude')
    latitude = instance.get('latitude')

    id_row = instance.get('id')

    contact_group = json.loads(
        instance.get('all_data', {})
    ).get('contact_groups', {})

    for field, fetcher in GEO_FETCH.iteritems():
        if not instance.get(field):
            geo_data = fetcher(longitude, latitude)
            if geo_data:
                update_data(conn, id_row, field, geo_data)

    for row_name, field_name in CONTACT_FIELDS.iteritems():
        row_data = get_from_contacts(contact_group, field_name)
        update_data(conn, id_row, row_name, row_data)

Bringing it all together

# -*- coding: utf-8 -*-

import json
import psycopg2.extras
from psycopg2.extensions import AsIs
from methods_grabber import (get_district, get_city,
                             get_street, get_house, get_postcode)

GEO_FETCH = {
    'street': get_street,
    'street_number': get_house,
    'postcode': get_postcode,
}

CONTACT_FIELDS = {
    'phone_number': 'phone',
    'site': 'website',
    'email': 'email',
}

def fill_data(conn, instance):
    longitude = instance.get('longitude')
    latitude = instance.get('latitude')

    id_row = instance.get('id')

    contact_group = json.loads(
        instance.get('all_data', {})
    ).get('contact_groups', {})

    for field, fetcher in GEO_FETCH.iteritems():
        if not instance.get(field):
            geo_data = fetcher(longitude, latitude)
            if geo_data:
                update_data(conn, id_row, field, geo_data)

    for row_name, field_name in CONTACT_FIELDS.iteritems():
        row_data = get_from_contacts(contact_group, field_name)
        update_data(conn, id_row, row_name, row_data)

def get_from_contacts(contact_group, representation):
    return '; '.join(
        unicode(contact.get('text'))
        for contacts in contact_group
        for contact in contacts.get('contacts')
        if contact.get('type') == representation
    )

def update_data(conn, id_row, row, data):
    with conn:
        with conn.cursor() as cursor:
            cursor.execute(
                "UPDATE dblgis_grabber_firm SET %s=%s WHERE id=%s;",
                (AsIs(row), data, id_row)
            )

def get_data(conn):
    with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:
        cursor.execute("""
                       SELECT *
                       FROM dblgis_grabber_firm;
                       """)
        return cursor.fetchall()

def check_data(db_credentials):
    conn = psycopg2.connect(db_credentials)
    for data in get_data(conn):
        fill_data(conn, data)
    conn.close()

if __name__ == '__main__':
    import timeit
    timeit.timeit('check_data("dbname=gym user=gyms")',
                  number=1, globals={'check_data': check_data})

Beyond readable code

Good production code is not only clear but also correctly documented to be maintainable. You should spend some time writing some docstrings to help any future reader understand what your code does. Comments in the code can also help understand how the code accomplishes its goals.


BF interpreter in Python that uses recursion to handle loops

As you didn't mention what are you looking for in a review, I will make some general comments regarding your code.

Formatting and variables

Try to read PEP8

indent your code using 4-spaces TAB
try removing redundant parentheses from your while loop loops
function names should be lower case (so try renaming your def readNoLoop(). Perhaps something like read_no_loop().
variable in functions should also be lowercase

Name conventions

Try renaming you variables based on their usage. For example: it - what is it ? What is its purpose ? Think about this when you are naming your methods / variables.

For example, instead of making comments right beside the variables, rename them and remove the comments:

array = [0]  # byte array
ptr = 0  # data pointer

Will become:

byte_array = [0]
data_pointer = 0

So far, we would have something like this:

import sys

byte_array = [0]
data_pointer = 0

def read_no_loop(char):
    global data_pointer
    # Increment/Decrement the byte at the data pointer
    if char == '+':
        byte_array[data_pointer] += 1
    elif char == '-':
        byte_array[data_pointer] -= 1
        if byte_array[data_pointer] < 0:
            raise ValueError("Negative value in byte_array")
    # Increment/Decrement the data pointer
    elif char == '>':
        data_pointer += 1
        while data_pointer >= len(byte_array) - 1:
            byte_array.append(0)
    elif char == '<':
        data_pointer -= 1
        if data_pointer < 0:
            raise ValueError("Negative value of pointer")
    # Output the byte at the data pointer
    elif char == '.':
        sys.stdout.write(chr(byte_array[data_pointer]))
    # Store one byte of input in the byte at the data pointer
    elif char == ',':
        byte_array[data_pointer] = ord(sys.stdin.read(1))

def interpret(char_chain):
    it = 0
    loop_begin = []
    while it < len(char_chain):
        if char_chain[it] == '[':
            loop_begin.append(it)
        elif char_chain[it] == ']':
            sub_chain = char_chain[loop_begin[-1] + 1:it]
            while byte_array[data_pointer] > 0:
                interpret(sub_chain)
            loop_begin.pop()
        else:
            read_no_loop(char_chain[it])
        it += 1

if __name__ == "__main__":
    # Brainfuck program to print "Hello World!"
    code = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'
    try:
        interpret(code)
    except:
        raise

Those elifs are bothering me, so you can try doing something like this:

instructions = {
  '+': increment,
  '-': decrement,
  # and so on
}

As per your code, I can't see much of improvement at the functionality level. Perhaps I will let others to do this.

More, I like how you used recursion in this code. In general, you have a nice structure.


Add Strings in-between index of ArrayList if not already exists

A few things come to mind:

First of all, as you access the list at index + 1 without any bounds check, the code will fail if a user attempts to use the method to add elements to the end of the string. You should probably handle that gracefully.
Changing the input parameter's value index is not expressedly forbidden, but it makes my skin crawl. Furthermore, you have to coordinate two values in a loop (s and index) which makes the code error prone. In this case, I'd go for an index based loop instead for(int i = 0; i < strings.length; i++) and use strings[i] and list.get(index + i). This way, you have only a single variable changing in the loop.
If there's nulls in the list, the code will throw an NPE. Preferably use Objects.equals(x, y) instead of x.equals(y) to stay null-safe.


I can't see any obvious memory leaks. If you're worried, then you might start out by seeing what sys.getrefcount tells you.
You will need to package up your array-of-doubles as a new type of Python object. See section 2 of the Extending/Embedding manual.
Since you know that you are creating float objects, you could speed things up slightly by using PyFloat_FromDouble instead of the generic Py_BuildValue (which has to parse its first argument and then dispatch). But this is not going to beat NumPy, because packaging up an array-of-numbers as a new type of Python object is exactly what NumPy does, and that's why it runs so fast: it doesn't have to allocate a new Python object for every position in the list.


As we know, the numbers that could be placed in sudoku cells are limited (1..9). So we can easily make an index to existence of 1 through 9 in each row, column and square.
Consider we use rowIndex[9][10], colIndex[9][10] and sqrIndex[9][10] for this purpose. Now checking that putting value v in row x and column y would be like below:

if ( rowIndex[x][v] ) return FAILURE;
if ( colIndex[y][v] ) return FAILURE;
var sqrID = (x/3)*3 + (y/3);
if ( sqrIndex[sqrID][v] ) return FAILURE;
return SUCCESS;

and if SUCCESS is returned we can put that value in the specified cell and update our maps:

rowIndex[x][v] = colIndex[y][v] = sqrIndex[(x/3)*3+(y/3)][v] = 1;

P.S: sqrIndex address all squares in row major.


Testing whether a matrix contains a submatrix

A few suggestions regarding the style:

There's no need for parentheses in the pattern matching blocks. Those are evaluated as tuples by the very fact that they are comma separated:

match smallValue = largeValue, widthIndex < searchWidth with
| true, true  -> WidthLoopRec heightIndex (widthIndex + 1)
| true, false -> true
| false, _    -> false

and:

 match isMatch , heightIndex < searchHeight with
 | true, true  -> HeightLoopRec (heightIndex + 1)
 | true, false -> true
 | false, _    -> false

In HeightLoopRec, there's no need for isMatch. You can use the result of calling WidthLoop directly inside the pattern matching (maybe with parentheses to make it more legible):

match (WidthLoop heightIndex), heightIndex < searchHeight with

The function HeightLoop is not needed and can be removed and replaced by its contents, making HeightLoopRec the top level function. This is obvious by its signature (unit -> bool). It doesn't take anything as input, unlike its internal tail-recursive function whose signature is int -> bool.
WidthLoop can be inlined (let inline WidthLoop heightIndex =).
I think it would be better to handle the exceptions before getting into the actual computation. In fact, if the code base is done in F#, there should be no null values (as those would be replaced by option types). Within your code domain, illegal values should be made unrepresentable, as the famous motto goes.

This should also account for out-of-range indexing. If a mathematical operation makes no sense, the typing itself should not allow it to be made.

You could use FsCheck to test your code with random values to see that your code never raises exceptions. Logically, "no answer" should not be represented as false. If a function may return no value at all or a bool, then its return type should be bool option, where None would represent the lack of a valid result.
Your function name should probably reflect more clearly their intention. I'm not a mathematician, but I guess you would mean something like isRowContained (instead of WidthLoop), or whatever makes sense.


Shortening System.out - which is better?

With the second approach you hide that out refers to System.out, so if anytime later you want to redirect the output, you need to change only static final PrintStream out = System.out; since the rest of the code is only aware of the fact that it is writing to a PrintStream.

The first approach is just using the shortcut offered by static imports.

Which one to use depends on the purpose of the code. If it is a one time, throwaway code trying out something, then I'd go with the first, otherwise the second, if there are many print statements. Otherwise I would not care replacing System.out.

On the other hand I would consider using a logger instead of System.out and that could be redirected to System.out to a File and to many other targets.


Stateful function pointer for passing C++ capturing lambdas / std::functions to C style callbacks

When you have a C callback you usually pass two things

A pointer to a C function
A void* pointer that is passed to your C function.

The C function must know the type of the original object so it can cast the pointer back to its original type. only after it has been cast back can it be used. And you must cast it back to the exact type it was before you converted to void* or you are in undefined behavior.
So this means the C function must understand the original type.
Since your original type is a templated type (i.e. you don't know the type in general) you can't cast it back (unless you templitize the function so that the function you pass to C has a understanding of the templitized types).
The easy way to do this is to implement a virtual interface. Then you can get a pointer to the base class convert this to a void* then in the C function you can convert back to the base class pointer and call the appropriate virtual interface on this base pointer. Virtual dispatch will then take care of calling the correct implementation.

OK found the reference you were eluding to:
Next time just add it to the question.
From: https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5P.html#Property-SetELinkCb
herr_t elink_callback(const char* parent_file_name,
                      const char* parent_group_name,
                      const char* child_file_name,
                      const char* child_object_name,
                      unsigned*   acc_flags,
                      hid_t       fapl_id,
                      void*       op_data)
{
    puts(child_file_name);
    return 0;
}

int main(void) {
    hid_t lapl_id = H5Pcreate(H5P_LINK_ACCESS);
    H5Pset_elink_cb(lapl_id, elink_callback, NULL);
    ...
}

Notice at the top of the document it talks about C functions: https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5P.html
This library is robably built by a C compiler so the whole ABI is a C ABI. Thus you can not pass any functions of C++ linkage as a parameter to a callback (The C code does not know how to correctly set up the stack frame to make a correct C++ call). You can only pass functions with C linkage.
Now some compilers use a very similar ABI for C and C++ and you may get lucky passing a function that uses C++ linkage, but that just means you are getting lucky.
Things like exceptions (that's just the first thing I can think of) will not be properly tracked across the stack frame boundries when going into C built stack frame.
As you are getting lucky it is likely that sometime in the future it will just suddenly stop working with no way to diagnose the problem.


You can use the lens library to remove the need for the setList function. The ix lens does this, giving read+write access to an element at an index. The type of this is:

ix :: Index m -> Traversal' m (IxValue m)

Or, for lists in particular:

ix :: Int-> Traversal' [a] a

Using the .~ operator, the value of a lens can be set. So to remove need for the setList funtion, just use this:

applyToEveryPair2 :: ((a,a) -> [(a,a)]) -> [a] -> [[a]]
applyToEveryPair2 f (xs) = do i<-[0..length xs - 1]
                              j<-[0..length xs - 1]
                              guard (i /= j)
                              (x',y') <- f (xs !! i, xs !! j)
                              return . (ix i .~ x') . (ix j .~ y') $ xs

The other thing to notice about your code is it will call every pair of elements twice: eg it will call the supplied function with the item at index 2 and 5, then with the items at indexes 5 and 2. I'm not sure if this is intended.


Let's go through mechanical errors:

use size_t instead of int

int length = vec.size();

what if there is no zero element?

result[0] = vec[0];

the same as first:

int last = 0;

the same as 1, 3:

for(int i=0; i<length; i++)

Optimization errors:

Is there any reason why do you need to return a COPY of vector? If you need return copy, so why do you pass it by reference?
Extra resize of vector is extremely heavy and slow operation.

result.resize(last+1);

Prefer pre-increment to post-increment
use reserve and push_back, instead of resize and []. In you case result.size() <= v.size(). So, make following:

std::vector<T> result;
result.reserve(v.size);
result.push_back( vec[0] );

In the loop:

result.push_back( vec[i] );

So, including all comments above:

template<class T>
std::vector<T> remove_duplicate(const std::vector<T>& vec)
{
    std::vector<T> result;

    if(!vec.empty())
    {
        result.reserve(vec.size());
        result.push_back(vec.front());

        for(size_t i = 0; i< vec.size(); ++i)
            if(vec[i] != result.back())
                result.push_back( vec[i] );
    }

    return result;
}


Fixed-size array-based implementation of a queue

API

The method names you chose are unusual for queues. It's good to get inspiration from the JDK. Following the example of Queue,
I suggest these renames:

push -> add
pop -> poll
top -> peek
empty -> isEmpty

Protecting internal implementation details

The getQueueDebug should ideally not be there at all,
and definitely not with public visibility.
It's best to test classes through their public interfaces.
Avoid exposing internal details.

Readability

The currIndex != 0 condition is used at multiple places.
This meaning of this condition is "not empty",
and the code would be more readable if you replaced it with a !isEmpty() method call.

Copying arrays

Instead of manually copying contents of an array like this:

for (int i = 1; i <= internalQueue.length - 1; i++) {
    internalQueue[i - 1] = internalQueue[i];
    internalQueue[i] = null;
}

It's more efficient to use System.arraycopy:

System.arraycopy(internalQueue, 1, internalQueue, 0, internalQueue.length - 1);

Performance

Moving the elements of internalQueue on every poll is inefficient.
You could instead use two indexes to point to the first and last element in the queue, and only move elements when really necessary.

In fact, @TedHopp put it beautifully in a comment:

  [...] By thinking of the array as circular (and using two indexes as suggested) it's never necessary to move elements. All it takes is some close attention to indexing to distinguish between an empty and a full queue.

Java conventions

Note that it's not a convention in Java to prefix interface names with a capital I, as you could see already in the Queue interface of the JDK.

You could use Queue as your interface name,
and since the implementation is effectively an array-backed bounded queue,
you could name the implementation class ArrayBackedBoundedQueue, for example.


Your regex is overly complicated, I must admit. The negative lookahead is going to do a lot of work to identify all the negative cases before even looking for (nearly) positive matches.

I think the trick you are missing is the word-boundary anchor. Consider the following regex:

\*\w+\b

This looks for an asterisk, followed by characters, and then a (zero length) word-boundary. Now, both *SOME* and *SOME match that, since the \b happens before the asterisk. The negative lookahead would be useful after the word-boundary. Consider the following:

\*\w+\b(?!\*)

Look for *SOME where the SOME is a complete word not followed by an asterisk.

Here's a little demonstration ....

Edit: Note, there is no reason to add the case-insensitive switch ((?i)) because your regular expression has no specific case-based characters.


Prim algorithm implementation for adjacency list represented graph

I try some review, although I don't know the Prim algorithm until now, so there are mostly general things here. Hope it is helpful nevertheless. The following points are in random order:

Regarding the language:

In your Vertex() {} class, you can omit the bVisited = false; as it is already initialized in the declaration. Otherwise, it's better to use an initializer list, Vertex() : bVisited(false) {}.
In C++11 (which you tagged) I would rather use the standard-library smart pointers and not the boost stuff. So, I would add an #include<memory> and replace all boost:: namespaces by std::.
Your function getMinEdge can be replaced by an single-line STL algorithm:

auto getMinEdge(const EdgeList& edgeList) -> boost::shared_ptr<Edge>
{
    return *std::min_element(edgeList.begin(),edgeList.end()
                           , [](boost::shared_ptr<Edge> const& a
                              , boost::shared_ptr<Edge> const& b)
                               { return a->cost < b->cost; });
}

When using range-based for loops

 for(boost::shared_ptr<Edge> edge : dstVertexEdgeList)

I would rather use auto instead of explicitly stating the type. Moreover, as copying a shared_ptr is not an unexpensive operation (as the memory manager must increase its reference count), here I would use auto& or better auto const& and pass the shared_ptr by reference.

The same holds for statements like boost::shared_ptr<Edge> minEdge = getMinEdge(potentialEdgeList); or EdgeList& dstVertexEdgeList = (minEdge->dstVertex).lock()->edgeList;. Better use auto or auto&, resp.

Regarding the design:

Regarding the storage scheme: The std::list<std::shared_ptr<Vertex> > you chose is probably the safest option, but probably also not the most performant. As an alternative you could for instance use std::shared_ptr<std::list<Vertex> >. It's rather fast and advantageous imo if vertices are more or less constant, such that you do not make changes in copies of the class -- because these would affect the original list. Further I would also consider whether a simple std::list<Vertex> is sufficient for you, as that is surely the easiest choice (--then you could then forget about all the smart-pointer stuff). Much here depends on the size of the pointed-to objects. The smaller they are, probably the less appropriate is the overhead of a shared_ptr.

The same holds for EdgeList. Here, you seem to make some copies and change these, such that std::shared_ptr<std::list<Edge> > doesn't make much sence (as you would change the original list). However, as edge is a rather small object, again a simple std::list could be more efficient.

But these are fundamental design questions which affect "only" the performance. I leave them up to you and will go on with the implementation as it is.
Rather than a std::list, you can also consider using a std::set or a sorted std::vector (as you already using boost, the latter corresponds to a flat_set). This gives you better performance for the search (logarithmic vs. linear for a list) but an increased effort for insertion and deletion (logarithmic vs. constant for a list).
The weak_ptr in the Edge class is ok, though it might not exactly be what you want. At the moment it works like this: an Edge connects two vertices. If now one vertex is removed from the graph, the Edge remains, but when you want to go along it the shared_ptr from weak_ptr initialization will fail and implicitly tell you that it is a dead end. I don't know whether this is desired.

Instead, the graph object should know that it has to automatically remove this Edge once the Vertex is destroyed. This obviously would require some corresponding logic in the Graph class. As an alternative, you could also create a closer coupling between the two classes (e.g. maybe hold an EdgeList for each vertex).

Further, when you go for a weak_ptr and .lock() it, you must keep track that it still points to something which is alive. Otherwise, access to variables of the pointed-to class fails. If you not check for existence and simply rely on it due to your code, a raw pointer would be sufficient.

So, that's it for now, hope it helps. When I get to know the Prim algorithm itself, I'll maybe make an update.


Find how much reputation a user had on a given date

The main improvements I would suggest are:

Minimize the number of accesses made to the large, minimally indexed, SEDE tables.
Break the query into multiple steps.
Reduce or eliminate code repetition.

Temporary tables are allowed on SEDE. Use these to fetch the minimal data needed from the large base tables to perform the calculations. Referring to these smaller data sets will be much more efficient than interrogating the base tables multiple times.

Properly used, temporary tables enable more accurate cardinality estimation, automatic statistics on intermediate results, and provide indexing opportunities - all of which can improve final plan quality and performance.

Breaking the query up also makes the logic easier to comprehend and debug (initially, and when maintaining it in future). Errors and redundancies are much easier to spot with smaller queries.

I have not attempted to improve the reputation calculation logic itself, except in a few minor ways, but the following illustrates a possible re-implementation of the provided code using temporary tables:

Initialization

DECLARE
    @UserId integer = 22656, -- Jon Skeet, why not
    @UntilDate datetime = CURRENT_TIMESTAMP;

DROP TABLE IF EXISTS
  #Posts, #Data, #Edits;

Posts data

Just the columns we are going to need from the Posts table:

CREATE TABLE #Posts
(
    Id integer NOT NULL,
    AcceptedAnswerId integer NULL,
    CommunityOwnedDate datetime NULL,
    PostTypeId tinyint NOT NULL
);

Load the minimal number of rows needed:

INSERT #Posts
(
    Id,
    AcceptedAnswerId,
    CommunityOwnedDate,
    PostTypeId
)
SELECT
    P.Id,
    P.AcceptedAnswerId,
    P.CommunityOwnedDate,
    P.PostTypeId
FROM dbo.Posts AS P
WHERE
    P.OwnerUserId = @UserId
    AND P.CreationDate <= @UntilDate
    AND
    (
        P.CommunityOwnedDate IS NULL
        OR P.CommunityOwnedDate <= @UntilDate
    );

This applies the common predicates in the original query as early as possible, including setting a boundary of the values of CommunityOwnedDate that might impact the reputation calculation up to the desired date. Other filtering could be added here, for example to restrict the PostTypeId values to just those of interest.

The execution plan (for Jon Skeet) is:

This plan is relatively efficient, being primarily based on a seek to the OwnerUserId specified. The Merge Interval subtree is concerned with finding the range of CommunityOwnedDate values used as a secondary seek predicate.

The Key Lookup is sadly unavoidable, given the SEDE view dbo.Posts wrapping the underlying table dbo.PostsWithDeleted (filtering on DeletionDate IS NULL without a supporting index). Nevertheless, it does mean we can filter CreationDate in the same lookup without adding significant cost.

Adding votes data

The next step adds the columns we need from the voting data associated with the qualifying posts. This is performed as a second step rather than joining all in one step because the #Posts table provides useful accurate cardinality and statistical information. A join query is quite likely to mis-estimate, resulting in an inappropriate plan selection or hash spill, for example.

CREATE TABLE #Data
(
    AcceptedAnswerId integer NULL,
    CommunityOwnedDate datetime NULL,
    PostTypeId tinyint NOT NULL,
    BountyAmount integer NULL,
    VoteTypeId tinyint NOT NULL,
    CreationDate datetime NOT NULL
)
WITH (DATA_COMPRESSION = ROW);

Row compression is not necessarily super-useful here, but it does illustrate the extra flexibility of using discrete result sets.

INSERT #Data WITH (TABLOCK)
(
    AcceptedAnswerId,
    CommunityOwnedDate,
    PostTypeId,
    BountyAmount,
    VoteTypeId,
    CreationDate
)
SELECT
    P.AcceptedAnswerId,
    P.CommunityOwnedDate,
    P.PostTypeId,
    V.BountyAmount,
    V.VoteTypeId,
    V.CreationDate
FROM #Posts AS P
JOIN dbo.Votes AS V
    ON V.PostId = P.Id
WHERE
    V.CreationDate <= @UntilDate
    AND
    (
        P.CommunityOwnedDate IS NULL
        OR P.CommunityOwnedDate > V.CreationDate
    );

The query above again applies predicates as early as possible, and gives us a combined view of the posts and votes that we can interrogate in multiple ways later on at low cost (certainly much cheaper than accessing the base tables again).

The execution plan features accurate cardinality estimates, appropriate use of parallelism, and a hashtable build-side bitmap filter used to perform semi-join reduction on the Votes table scan. This removes rows that cannot possibly join even before they are surfaced from the storage engine to the query processor (as indicated by the INROW attribute).

Suggested Edit Data

We only need the date (no time component) and total reputation earned for suggested edits:

CREATE TABLE #Edits
(
    ApprovalDate datetime PRIMARY KEY,
    Reputation integer NOT NULL
);

INSERT #Edits
(
    ApprovalDate,
    Reputation
)
SELECT
    G.ApprovalDate,
    EditRep = 2 * COUNT(*) -- 2 rep per approved suggested edit
FROM dbo.SuggestedEdits AS SE
CROSS APPLY
(
    VALUES (CONVERT(datetime, CONVERT(date, SE.ApprovalDate)))
) AS G (ApprovalDate)
WHERE
    SE.OwnerUserId = @UserId
    AND SE.ApprovalDate <= @UntilDate
    AND SE.RejectionDate IS NULL
GROUP BY
    G.ApprovalDate;

Using CROSS APPLY with VALUES allows us to avoid repeating the datetime to date conversion in the SELECT list and GROUP BY clause. The converted value is put back in a datetime type for consistency with the other SEDE-derived tables.

It is generally best practice to pay careful attention to data types, avoiding implicit conversions. This has myriad benefits, not least for cardinality estimation and join performance & optimizations.

A possible improvement to the code here would be to use the date type everywhere only the date portion is needed.

The parallel scan of the SuggestedEdits table is the best we can do here, without better indexing in SEDE.

Reputation Per Day

This table largely replaces the original r2d subquery, computing reputation totals per day:

CREATE TABLE #DayTotals
(
    CreationDate datetime PRIMARY KEY,
    ReputationFromVotes integer NOT NULL,
    ReputationFromBounties integer NOT NULL,
    ReputationFromAccepts integer NOT NULL,
    ReputationFromSuggestedEdits integer NOT NULL
);

INSERT #DayTotals WITH (TABLOCK)
(
    CreationDate,
    ReputationFromVotes,
    ReputationFromBounties,
    ReputationFromAccepts,
    ReputationFromSuggestedEdits
)
SELECT
    D.CreationDate,
    ReputationFromVotes =
        ISNULL
        (
            SUM
            (
                CASE
                    WHEN D.PostTypeId = 1 AND D.VoteTypeId = 2 THEN 5
                    WHEN D.PostTypeId = 2 AND D.VoteTypeId = 2 THEN 10
                    WHEN D.VoteTypeId = 3 THEN -2
                    ELSE 0
                END
            ), 0
        ),
    ReputationFromBounties =
        ISNULL(SUM(CASE WHEN D.VoteTypeId = 9 THEN D.BountyAmount ELSE 0 END), 0),
    ReputationFromAccepts =
        ISNULL(SUM(CASE WHEN D.VoteTypeId = 1 THEN 15 ELSE 0 END), 0),
    ReputationFromSuggestedEdits = ISNULL(SUM(E.Reputation), 0)
FROM #Data AS D
LEFT JOIN #Edits AS E
    ON E.ApprovalDate = D.CreationDate
GROUP BY
    D.CreationDate;

The execution plan shows efficient parallel processing using only the relatively small temporary tables:

Other reputation totals

These are single values, stored in variables for convenience:

DECLARE
    @RepBountiesGiven integer =
    (
        SELECT
            ISNULL(SUM(-D.BountyAmount), 0)
        FROM #Data AS D
        WHERE
            D.VoteTypeId = 8 -- BountyStart
    ),
    @RepFromAcceptingAnswers integer =
    (
        SELECT
            2 * COUNT(*) -- 2 rep per answer accepted
        FROM #Posts AS P
        WHERE
            P.PostTypeId = 1
            AND P.AcceptedAnswerId IS NOT NULL
    ),
    @ReputationFromRepCap integer =
    (
        SELECT
            SUM
            (
                CASE
                    WHEN ReputationFromVotes + ReputationFromSuggestedEdits <= 200
                    THEN ReputationFromVotes + ReputationFromSuggestedEdits
                    ELSE 200
                END
            )
        FROM #DayTotals
    );

Final query

Now we have all the elements we need to produce the final output:

SELECT
    TotalReputation =
        @ReputationFromRepCap +
        SUM(DT.ReputationFromBounties) +
        @RepBountiesGiven +
        @RepFromAcceptingAnswers +
        SUM(DT.ReputationFromAccepts),
    ReputationFromRepCap = @ReputationFromRepCap,
    ReputationFromBounties = SUM(DT.ReputationFromBounties),
    ReputationGivenAsBounties = @RepBountiesGiven,
    ReputationFromAcceptingAnswers = @RepFromAcceptingAnswers,
    ReputationFromAcceptedAnswers = SUM(DT.ReputationFromAccepts)
FROM #DayTotals AS DT;

Try the complete script at: SEDE Demo


Checking items in dictionnary
There is no need to call keys when checking for dictionnary membership. Much like there is no need of True in if my_bool == True.
on
Checking if a key exist and set it to a default value otherwise is so common that you have 2 standard ways of doing it: dict.setdefault(...) or using a collections.defaultdict.
trigger
Since KeyError should normaly not happen, you can use EAFP approach by using try...except instead of if. It's a tiny bit faster if exceptions are quite rare. Moreover, by using defaultdict you are guaranteed that every access to an item will be valid, thus eliminating the need to check membership of any key.
class
Since the only state you need is the one of the class, and in order to avoid instanciating to call methods, you can use @staticmethods and call them with Event.on(...) and Event.trigger(..).
Proposed alternative
from collections import defaultdict

class Event():
    __events = defaultdict(list)

    @staticmethod
    def on(event, func):
        Event.__events[event].append(func)

    @staticmethod
    def trigger(event, *args, **namedArgs):
        for func in Event.__events[event]:
            func(*args, **namedArgs)


Represent pairs of nonnegative integers using 2^a * 3^b

Your definition of cons is perfect.

Your definitions of car and cdr contain the log operation, which is a floating-point operation.  Not only are its results imprecise, it is not needed to solve this problem.  Furthermore, notice that the two definitions look very similar to each other.  Whenever one sees a repeated pattern, one ought to consider factoring it out.

To address the above two concerns, one may write a helper function, log-x, which is a specialized log function that takes integer parameters x and n and returns integer p such that x ^ p * y = n, where x does not divide y.  Then, car and cdr may call log-x, with x being 2 and 3 respectively.

In the following implementation, I have renamed the definitions so they do not conflict with primitives.

(define (cons-np a b)
  (* (expt 2 a) (expt 3 b)))

(define (log-x x n)
  (if (= (remainder n x) 0)
      (+ 1 (log-x x (/ n x)))
      0))

(define (car-np np)
  (log-x 2 np))

(define (cdr-np np)
  (log-x 3 np))


Do you really have a performance issue?

Optimizing a recursive function is usually done by performing tail call optimization, but this is not possible here since you have multiple branchs to explore at each function call.

I would thus not try to make the code faster, but the algorithm faster. If searching in a tree actually slows your code, that means you need to change the way it works so that you know which branch to explore at each function call and having O(log n) complexity instead of O(n). There are tons of trees which have nice properties likes this: B-trees, red-black trees, splay trees and so on. You can also consider using a hash table.


Quickly passing and parsing variable length float arrays

You can get some improvements by using JSON and moving the length increment to the back-end like so:

Nengo.SpaSimilarity.prototype.on_message = function(event) {
    var data = JSON.parse(event.data);
    var size = data.shift();
    while (data.length >= size) {
        this.data_store.push(data.slice(0, size));
        data = data.slice(size);
        size = data.shift();
    }
    this.schedule_update();
}


HackerRank - Array Manipulation - Follow-up

Whitespace, let your code breathe

Your code has a few logical sections, you should use empty lines to break them appart visually. It makes your code easier to read.

Personal opinion: front-load your type aliases

General wisdom in C++ is to define things as close as possible to their first use, but that's generally meant for objects with lifetimes. I personally prefer to put any type alias at the start of its scope.

algorithm is unused, so it should not be included

Simple enough: do not #include stuff you don't need.

That's kind of it, really, good job!

Edit: to answer your question, you could finagle something with std::accumulate, or just create a scope for partial_sum, but it's not worth the trouble. What you have it fine.


Concise way of creating a IntRange out of an Int

Since it.duration is quite long, you could use the alternative expression:

(it.duration / 10 * 10) .. (it.duration / 10 * 10 + 9)

You still have common subexpressions, though. To avoid these, you can define a cluster:

fun cluster(x: Double, size: Double) = (x - x % size) .. (x - x % size + size - 1)

or, to avoid the common subexpression:

fun cluster(x: Double, size: Double) = (x - x % size).let { it .. (it + size - 1) }

(I wrote the above without a compiler, so it may or may not work, but you get the idea.)

Then, you can group the trips by their cluster:

trips.groupBy { cluster(it.duration, 10.0) }

By the way, the group "30-39" also contains 39.999, so you might get contacted by a nitpicker that your range should better be called "[30,40)". ;)


Project Euler #14 - Longest Collatz sequence

While many of the Project Euler problems can be solved by brute force, this often isn't the fastest way to do them. Usually there is some kind of algorithmic insight that you can apply that will make your solution faster. This kind of insight is independent of programming language - simply running your code through a hypothetical "go-fast compiler" still won't match the speed of the correct algorithm.

In your case, here's a hint. Many of the sequences you calculate look the same as ones you've previously done. How could you use that information to speed up your algorithm?


Since

  EnteredCost and EnteredPaymentReceived are input parameters from MaskedTextBox

and a MaskedTextBox

  Uses a mask to distinguish between proper and improper user input.

then the validation is not necessary because all it does is to check whether the strings contain numeric data and a dot . as a separator. The MaskedTextBoxs alredy do that so why are you validating their input again?


By breaking the code into separate methods, you've made it easier to read, which is good. You've not made it easier to test though (unless you expose those methods to the test framework, which then creates a leaky abstraction and brittle tests). Therefore all you should be testing with your revised code is ParseResponse itself. ParseResponse has lots of side-effects though, so is hard to test.

The solution is to decouple those side-effect causing parts of the code and to inject them:

public FeedSummary ParseResponse(string rssFeed,
                                 IXMLLoader loader,
                                 IXMLSanitizer sanitizer,
                                 IFeedCreator feedCreator)
{
    var doc = loader.LoadXml(rssFeed);
    var cleanData = sanitizer.SanitizeXml(doc);
    var feed = feedCreator.CreateFeed(cleanData);
    return ParseFeed(feed);
}

The you can create implementations of IXMLLoader etc that can be individually tested with integration tests and provide mocks for testing ParseResponse itself.


Translating LaTeX documents into different languages using DeepL API

While using sys.argv is fine for a first version of a program, you should give it a proper CLI. It would be nice if multiple latex files could be passed (since it is common to split a large project into multiple files) and also to specify the source and target languages. For this you can use argparse:

import argparse

def parse_args(args=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("--from", default="DE", help="Language of the source document(s)")
    parser.add_argument("--to", default="EN", help="Language of the target document")
    parser.add_argument("file", nargs="+", help="Path(s) to the latex file(s)")
    return parser.parse_args(args)

if __name__ == "__main__":
    args = parse_args()
    print(args.to, args.from, args.file)
    ...

This even gives you a nice usage message when calling the script with the option -h or --help:

usage: script_name.py [-h] [--from FROM] [--to TO] file [file ...]

positional arguments:
  file         Path(s) to the latex file(s)

optional arguments:
  -h, --help   show this help message and exit
  --from FROM  Language of the source document(s)
  --to TO      Language of the target document

Now, let's get to your "hashing". When randomly selecting from \$H = 9999 - 1111 = 8888\$ values, it takes on average \$Q(H) = \sqrt{\tfrac{\pi}{2}H}\approx 118.16\$ draws until you get a number twice. In other words, if you have more than about 120 elements, you will overwrite some. And that number is actually less than half of that because you separately hash \begin and \end.

One way to avoid collisions is to just keep on counting up. For this you could use itertools.count, which produces an infinite stream of increasing numbers, starting with the argument (or 0 if not given), when being iterated:

from itertools import count

counter = count(1111)
assert len(searchObj1) + len(searchObj2) <= 8888, "Too many objects to hash"
list1 = ['X#X{}'.format(i) for _, i in zip(searchObj1, counter)]
list2 = ['X#X{}'.format(i) for _, i in zip(searchObj2, counter)]

Another way to make it less likely is to extend the range. And at that point you might as well use the built-in hash function:

list1 = ['X#X{}'.format(hash(x)) for x in searchObj1]

In this case you would need to relax the and len(line) == 7 requirement later.
When opening files, you should use the with keyword to ensure they are properly closed, even if an exception occurs somewhere in the block:

with open(fileInputName) as fileIn, open(fileOutName, "w") as fileOut:
    ...

You should also think about better names. Python has an official style-guide, PEP8, which recommend using lower_case instead of camelCase. In addition, list1, searchObj1, d2 are all not very good names.
Doing string addition can be very costly, because in Python strings are immutable. This means that when you do str_a + str_b, Python has to allocate a new string object of length len(str_a) + len(str_b) and then copy the content of both strings into that new array. This takes more time the longer the strings are and the more often you do it. Since you are adding strings of the length of a full document and are doing so in a loop, this can be very slow.

Instead, build a list and str.join it at the end:

translated = []
for line in fileIn:
    #print(line)
    if line.startswith("X#X") and len(line) == 7:
        translated.append(line)
    elif not line.strip():
        translated.append('')
    else:
        translated.append(pydeepl.translate(line, args.from, args.to))
translated = '\n'.join(translated)

Note that I directly iterate over the file (since files are iterable), meaning that this program is less limited by the amount of memory available. However this means that the progress bar does not work anymore (and I therefore removed it here), because it needs to know how many lines there are. You can use something like this to add it back: https://blog.nelsonliu.me/2016/07/29/progress-bars-for-python-file-reading-with-tqdm/