Fixing navbar when scrolling beyond a certain number of pixels

Cache your jQuery objects as @Abbas mentioned. Also, you could use toggleClass with a state switch:

var $catNavBar = $('#catNavBar'),
    $headerGbCont = $('#headerGbCont'),
    followScroll = $(window).scrollTop() > 130;

$catNavBar.toggleClass('navbar-static-top', !followScroll);
$catNavBar.toggleClass('navbar-fixed-top', followScroll);
// etc..
$headerGbCont.width(followScroll ? 50 : 109);

Regarding magic numbers like 130, I would suggest that you calculate distances between elements and define rules based on the result rather than approximating when you should switch classes.


Cleanup code to add div structure to element

You should let CSS handle most of the job for you. Example

JS:

var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var count = 1;
var html = '';
for (var i = 0; i < a.length; i++) {
    var div = $("<div>" + a[i] + "</div>");
    $('#container').append(div);
}

CSS (where the magic is):

#container div:nth-child(3n+1) { /* Every third! */
    clear: both;
}

#container div {
    float: left;
    width: 100px;
}


Monitoring the recursive growth of a zombie rabbit population

Comments on your code:

I’m surprised by the requirement that the input to answer() has to be a string, not an int.

Since an int seems to be the natural input, I’d put most of the processing code in a separate function that only deals in ints, and do the string mangling at the very far edges of the program. Something like:

def answer(str_S):
    result = answer_from_int(int(str_S))
    if result is None:
        return None
    else:
        return str(result)

That allows you to separate the processing logic from the (somewhat unusual) interface.
There are no comments or docstrings in your code, which means that

I don’t know what it’s supposed to do, and
I don’t know why you wrote it this way.

Knowing either of those would make the code substantially easier to read, review and maintain. Get into the habit of writing comments and docstrings – when you’re debugging your old code, you’ll thank yourself for it.
Choose more descriptive variable names. You can usually find more appropriate names than single characters, and the result is significantly more readable code. It’s much easier to follow the control flow if I’m following names instead of letters.

Comments on your approach:

You’re right, this won’t scale. You’re caching a huge number of results, most of which aren’t used. I did some quick experiments, and found that \$R(n) \approx 2n\$, which means that a 10^25 lookup is going to require a dict with 10^25 entries. Ouch.

You’re building up to find \$S\$, even if \$S\$ is huge. We can approach it much faster.

Here are a few suggestions:

Computing a single value \$R(n)\$ only needs a small subset of the values \$R(1)\$ to \$R(n-1)\$. By using the recurrence relations, you can get to it in very few operations (I think O(log n).)

So rather than computing and caching every value you might need, only do that for the results you actually need. This will result in significant occupancy and processing savings.

But how do we know which values of \$R(n)\$ we should look at?
Let's split the sequence into odd and even results, which I’ll define with the notation
$$R_O(n) = R(2n) \qquad R_E(n) = R(2n+1)$$
Since all \$R(n)\$ are positive, both of these sequences are monotonically increasing. Further note that \$R(n) \geq n\$ for all \$n\$.

As such, I know that if there is some \$n\$ such that \$R(n)=S\$, it must have \$0 \leq n \leq S\$. So we can do a binary search in the odd/even subsequences for \$S\$, and quickly find out whether it’s in either of the sequences (and then which has the larger value of \$n\$).

Here’s a skeleton class I wrote that allows me to efficiently compute zombit counts. The code isn’t complicated, so you can try filling it out:

class Zombit(dict):

    def __init__(self):
        # set up the initial values

    def lookup(self, N):
        # Get the value R(N), either from the cache or by computing from
        # the recurrence relations.  Remember to cache the result!

I can use this to look up \$R(6\cdot10^{300})\$ in a fraction of a second and with minimal occupancy. You’ll easily be within the bounds of the question, and then some. (Trying to go higher, I ran into Python’s max recursion depth.)

Setting up the binary search is a bit harder, but still not too complicated.


if (!fileExists(args[1])) {
        puts("Could not access file / file not found.");
        return 1;
    }

    FILE *file = fopen(args[1], "r");

This seems more complicated than necessary.

    FILE *file = fopen(args[1], "r");
    if (NULL == file) {
        puts("Could not access file / file not found.");
        return 1;
    }

This has the exact same effect as fileExists but it leaves you with an open file handle.  The other method tested that it could open a file and then assumed that the second open worked.  So it's actually slightly less safe, as well as more code.

You might argue that it would be extremely rare for the first open to succeed and the second one to fail.  I agree with you.  But rare is not never.  Thus, "slightly" less safe.

    int temp = 0;
    int position = 0;
    int swapped = 0;

    for (int i = 0; i < LINE_BUFFER; i++) {
        if (isdigit(line[i])) {
            if (!swapped) {
                position = i;
                temp = line[i];
                swapped = 1;
            } else {
                line[position] = line[i];
                line[i] = temp;
                swapped = 0;
            }
        }
    }

I don't like using negative test conditions.  I'd normally fix this by switching the if and else blocks.  In this case though, the current order makes more sense.

My second thought was that the name was wrong.  So I was going to change the name to needs_swapped or similar.  But then I realized that if I changed the name, the current form would be correct.  The name swapped is actually backwards.  When swapped is true, then you haven't swapped but need to do so.  So my third thought was to simply swap the meaning.

    int temp = 0;
    int position = 0;
    int swapped = 1;

    for (int i = 0; i < LINE_BUFFER; i++) {
        if (isdigit(line[i])) {
            if (swapped) {
                position = i;
                temp = line[i];
                swapped = 0;
            } else {
                line[position] = line[i];
                line[i] = temp;
                swapped = 1;
            }
        }
    }

Now I have the else as the negative of the condition, which I like.  And we've also made it so that when swapped is 1 (true in C parlance), we've just swapped.  When swapped is 0 (false in C), we're ready to swap.

But I actually think that there is a more idiomatic way to do this in C.  You are saving an index (position), a value (temp), and a Boolean (swapped).  But you actually only need to save the location.  Consider

    char *location = NULL;
    for (int i = 0; i < LINE_BUFFER; i++) {
        if (isdigit(line[i])) {
            if (NULL == location) {
                location = &line[i];
            } else {
                int temp = *location;
                *location = line[i];
                line[i] = temp;
                location = NULL;
            }
        }
    }

or less explicitly (and slightly out of order)

    char *location = NULL;
    for (int i = 0; i < LINE_BUFFER; i++) {
        if (isdigit(line[i])) {
            if (location) {
                int temp = *location;
                *location = line[i];
                line[i] = temp;
                location = NULL;
            } else {
                location = line + i;
            }
        }
    }

Either version reduces three variables at function scope down to one at function scope and one at the most local block scope.

It's up to you which version you find more readable.  I also switched between line + i and &line[i].  They do the same thing, so it's pretty much a readability difference.

And I like this better, as rather than using a Boolean to track whether or not we need to swap, we track based on whether we know where to swap.  Less parallel logic increases robustness.

Twice now I've used the notation NULL == variable (where variable is any declared variable like location or file).  The reason for this is that in C, if (variable = NULL) { is valid and will compile and run.  It creates unreachable code, as NULL will always be false.  So modern compilers often warn on this.  But it's valid grammatically.  If you instead always write if (VALUE == variable) { (where VALUE is any constant like NULL or 3), then a typo leads to if (VALUE = variable) { which is not valid and won't compile.

Like I said, most modern compilers will warn on this.  So it's not as important as it once was.  But if you start editing C code, you are likely to see this idiom used.  This is why.


An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++

Instead of simply printing output, it would be better to have self-checking unit tests, so you can fail your build as soon as you break something, rather than having to notice a change in the output.
You probably want to include some tests with very large (positive and negative) values to make sure you get accurate results with these, and don't fall foul of integer overflow (which will cause gross inaccuracy with unsigned types, and is Undefined Behaviour with signed integer types).
It's disappointing that there are no tests using primitive types other than int.


Demonstrating the speed advantage of parallel computation

Currently each future processes SIZE elements (increasing the NUM_OF_THREADS increases the total workload (NUM_OF_THREADS * SIZE)). Instead you want to divide the workload between each of the futures:

int start = SIZE / NUM_OF_THREADS * iThreadLocal;
int end = SIZE / NUM_OF_THREADS * (iThreadLocal + 1);

Besides that iThread could (and should) be a local variable. The spacing between operators is inconsistent, you should add whitespace around the operators (except for unary operators) to improve readability.


"The Trip" challenge from Programming Challenges

Your algorithm seems to be correct though a bit overcomplicated.
But the code is not correct. consider:

9999.1
9999.1
9999.0
9999.1

$0.05

And the correct answer is $0.07

This is due to lack of precision in float implementation. It does not mean you should use double, it mean you should check your casts and try to avoid using float at money computations at all.

Also, i suggest to check your inputs.


Easier way to find matching array from a lot of arrays

For readability, use an Object instead of a 2d array.

E.G:

public class BluetoothMacAddress {
    private String macAddress;
    private float positionInBuilding;
}

Use java.util.List, then you can have a list of lists:

private sttaic final List<MacAddress> MAC_ADDRESSES_A_BLUETOOTH = Arrays.asList(
    new BluetoothMacAddress("B09122F5D126", "210.105"),
    new BluetoothMacAddress("B09122F5F26B", "136.121"),
    new BluetoothMacAddress("B09122F5F619", "181.172"));

private static final List<List<MAC_ADDRESSES>> MAC_ADDRESSES = Arrays.asList(
    MAC_ADDRESSES_A_BLUETOOTH,
    MAC_ADDRESSES_B_BLUETOOTH
    ...
);

Your new method would then look something like this:

private MacAddress compareArrays(String[] beacon) {
    for (List<MacAddress> macAddresses : MAC_ADDRESSES ) {
        if (Arrays.equals(beacon, getFirstArray(macAddresses))) {
            return macAddresses;
        }
    }
    // not found
    return null;
}

You'd have to change the beacon parameter to be a MacAddress too, or convert the MacAddress to a String[] (or visa-versa).


You're creating a new List<int> for every node in the tree, which is a lot of garbage for the garbage collector. Each value will also end up getting appended to many temporary lists.

Let's kick the can down the road and assume that the work of creating the list has been taken care of for us. We take the result list as a parameter and append to that

private static void ConvertTreeToList(TreeNode root, List<int> result)
{
    if (root == null)
    {
        return;
    }

    result.Add(root.Index);
    ConvertTreeToList(root.Left, result);
    ConvertTreeToList(root.Right, result);
}

Now we just add a helper function

private static List<int> ConvertTreeToList(TreeNode root)
{
    var result = new List<int>();
    ConvertTreeToList(root, result);
    return result;
}


Project Euler #3 in C# - largest prime factor

Here's my solution to this problem

    static void Main(string[] args)
    {
        long num = 600851475143;
        int count = 3;
        Stopwatch sw = Stopwatch.StartNew();
        while (num > 1)
        {
            if (num%count == 0)
            {
                num /= count;
            }
            else
            {
                count += 2;
            }
        }
        sw.Stop();
        Console.WriteLine("The largest prime factor of the number {0} is {1} ", 600851475143, count);
        Console.WriteLine("Time to calculate in milliseconds : {0}", sw.ElapsedMilliseconds);
        Console.ReadKey();
    }

First of all most of the exercises you will find on Project Euler will require some math formula or concept in order to achieve the highest possible performance. It's not pure programming and thus not the best place to practice it in my opinion (ofc assuming you don't know all the formulas) you will probably learn more math than programming in the process which is a good thing if that's what you are looking for. Long story short look for formula before you go into the programming.

Back to your actual code :

Why is your code working slow ?
 There are few points here that I want to make first method calls are slower than just a bunch of code in a single method again some problems you will find later in Project Euler will be pretty easy to solve but hard to optimize so the usual C# code has everything separated in methods and classes because the performance loss is not that big in a normal project however here this might be your only bottleneck in some cases. You should always think in perspective what if you had even bigger number ? Would your method still work fast enough ? A working program doesn't mean that it's a good program.

Next you start thinking what can you improve and why exactly you are doing certain things. Do you really need to know every single number that is prime ?

In my solution there is simple prime factorization starting from the smallest prime we keep increasing the current number we have until we get a number that we can divide only by itself i.e the  largest prime factor. 100,000 iterations run for about 3000-3200 ms on my machine.


In Python, it is part of the mentality to check for behavior rather than for exact type.

Your method doesn't even need recipients to be a list—it can be any iterable (e.g. a set) so it can be used in the for loop. Strings, however, are also iterable, so you need to tell them apart.

One way to check if something is a string is to look for a string-specific method, such as strip.

def __Emailer(text, subject, recipients, auto=True):
    import win32com.client as win32

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)

    if hasattr(recipients, 'strip'):
        recipients = [recipients]

    for recipient in recipients:
        mail.Recipients.Add(recipient)

    mail.Subject = subject
    mail.HtmlBody = text

    if auto:
        mail.send
    else:
        mail.Display(True)


Equality comparison for a surname value object class

I don't see any advantage that this class provides over a simple string. I expect a Surname to be at least case-insensitive but this class' equality is exactly the same as if it was a string.

I also don't understand why you change the hashcode of the string? You could just return the one that _value returns... but agian, this would be the same as an the one of an ordinary string.

Take a look a the StringComparer.OrdinalIgnoreCase because this is what you actually need... I guess. It would make sense.

As far as a Surname is concerned I also expect it to yield true when comparing "John" with " John    ". So you might want to Trim the value.

This kind of case-insensitive trimmed string is such a common use case that I have special class for that. It saves a lots of headaches when working this kind of data.


Change type of property in derived class

Judging from the code you provided, the program is behaving as if you are using the new keyword.  This causes your property to behave differently based upon whether your form is used in the context of type DataObjectEditForm versus type DataObjectExEditForm.

To clarify:

var form = new DataObjectExEditForm ();
form.EditDataObject = new DataObjectEx ();

DataObjectEditForm  baseForm = form;
var  data = baseForm.EditDataObject;  // data = null!?!

From the looks of it, you should instead be using virtual/override on your property.

public class DataOjectEditForm : Form
{
    protected DataObject _editDataObject;

    protected virtual DataObject EditDataObject
    {
        get { return _editDataObject; }
        set { _editDataObject = value; }
    }

    //Do stuff only dependent on DataObject
}

public class DataOjectExEditForm : DataObjectEditForm
{
    protected override DataObject EditDataObject
    {
        get { return _editDataObject; }
        set
        {
            if (value == null)
               _editDataObject = null;
            else _editDataObject = value as DataObjectEx ?? new DataObjectEx(value);
        }
    }

    //Add stuff dependent on the additions in DataObjectEx
}

Of course, that is only going to guarantee that the backing field used by the form is consistent.  If the bug is the result of _editDataObject being used in some contexts while _editDataObjectEx was used in other contexts, then this will solve your issue.


Putting all desktop items into a new folder

You hard-coded "C:\Users\Shadow\Desktop" three times.  Once would have been too many, as it turns a general-purpose script into a throwaway script.  Your script could take a command-line parameter or infer the desktop directory for the current user.

If you must hard-code a path as a string literal, use raw strings to prevent Python from interpreting special backslash escape sequences such as \n for Newline.

Let's focus on this function:

#Function that does the moving
def moveFilesToFolder(files, directory, folder):
    for files in directory:
        shutil.move(files, folder)

What is files?  It's a parameter that you accept but never use.  Rather, you reuse the same variable name as a dummy variable for iteration.
Using an iteration variable with a plural name is awkward.
What do the parameters directory and folder mean?  How about renaming directory → files and folder → dest_dir for clarity?

I was curious how you actually call that function, given the weird parameter design.

moveFilesToFolder(file, desktop, newFolder)

At first glance, it appears that the script should fail, since file is never defined as a variable in your script.  However, it turns out that file is the name of a built-in constructor function.  So, you're passing some arbitrary function as a parameter to a function that ends up doing nothing with it.  I find that rather funny.


You can turn this into "here doc" solution by using wrapping it in a process substitution <(...), like this:

awk -f <(cat << "EOF"
{
    ... // awk script, as if in a file
}
EOF
)

This way, you can write ' directly, as if in a .awk script file,
because there ' is no longer an enclosing character.

Note that cat << "EOF" is necessary instead of simply cat << EOF to avoid variable expansion of $1, $3 and $4.

Also, to avoid multiple print statements,
you will have to embed newlines with \n, and end lines with \ to continue the same print statement on the next line.

Finally, you don't need the sed -e 1d, because awk can do this alone, using a NR > 1 filter. However, to account for the extra line in the input, whenever you use NR in the awk script, you would have to change that to NR - 1.

Putting the above together, this script is equivalent to yours (produces same output):

awk -F';' -f <(cat << "EOF"
NR > 1 {
print "\
DECLARE @v_trmPfiID_fk varchar(16) = '"$1"'\n\
DECLARE @v_trmNom varchar(6) = '"$3"'\n\
DECLARE @v_trmNbrTrav smallint = "$4"\n\
IF EXISTS (SELECT 1 FROM trimestre WHERE trmPfiID_fk = @v_trmPfiID_fk AND trmNom = @v_trmNom)\n\
    BEGIN\n\
        UPDATE trimestre\n\
        SET trmNbrTrav = @v_trmNbrTrav\n\
        WHERE trmPfiID_fk = @v_trmPfiID_fk AND trmNom = @v_trmNom\n\
    END\n\
ELSE\n\
    BEGIN\n\
        PRINT 'The script execution FAILED for record " (NR - 1) " (pfiID ' + @v_trmPfiID_fk + ', trimestre ' + @v_trmNom + ').'\n\
    END\n\
go\n\
"
}
EOF
) < in.csv


performance test the code for finding time taken to fill the disk space

You may be able to speed up the body of the loop using the sum function & list comprehension:

mem = sum( timeTaken // v for v in proc_r )

But the real speed up won’t come until you realize you can compute a lower limit for timeTaken, and begin looping starting from that value, instead of from zero.


Project Euler LCM of 1..20, with some guesswork

The below formula can be used to get the LCM of two numbers. See Reduction by the greatest common divisor section in Wikipedia

               a * b
lcm(a, b) = ―――――――――――
             gcd(a, b)

GCD can be calculated by using the Euclidean AlgorithmSee Using Euclid's algorithm section in Wikipedia.

gcd(a, b) = gcd(b, a % b)

Using these two formulas, the LCM can be calculated as follow

console.time('new');

function gcd(a, b) {
    while (b !== 0) {
        var temp = a;
        a = b;
        b = temp % b;

        // Can be written in ES6 as
        // [a, b] = [b, a % b];
    }

    return a;
}

function lcm(a, b) {
    return a * b / gcd(a, b);
}
var range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
console.log(range.reduce(lcm, 1));
console.timeEnd('new');

This is very efficient than using while and for, see this JsFiddle demo.

Note: This answer is inspired by this and this posts.


NumPy provides numpy.interp for 1-dimensional linear interpolation. In this case, where you want to map the minimum element of the array to −1 and the maximum to +1, and other elements linearly in-between, you can write:

np.interp(a, (a.min(), a.max()), (-1, +1))

For more advanced kinds of interpolation, there's scipy.interpolate.


It looks good overall.

I see two possible problems.

Race condition in deleteTodo

Running the program twice at the same time you might lose one change because reading the old file, writing the new file and renaming is not atomic.

You can avoid that problem when using a "tododir" with one single file per item. It will also scale better with the number of todo items. Note, that that's very similar to why maildir is superior to mbox. See the rationale at djb's site.

Error handling is missing

You don't catch exceptions when doing file operations and use the partial read. For that simple interactive program I would not catch file operation errors but would surely use readMaybe.


That works, but obviously, the code is repetitive, and a lot of work to maintain.  To prepare each Mad Lib, you have to count the number of each type of blank, to make the required number of prompts.  Then, you fill in the blanks using str.format(…) with some rather cryptic placeholders in the format string.

A smarter approach would be to have the computer do most of that work for you, so that you only need to supply a template in some human-friendly format, and the code figures out the necessary prompts.  That would necessitate a complete rewrite of the code.

Furthermore, you should avoid making separate lists for each part of speech, because that forces you to write separate code to handle each part of speech.  Rather, you should store the words in a dictionary, with the parts of speech as
keys, and list of words as values.  (More specifically, you can use a defaultdict to ensure that each key is initially associated to an empty list.)  Storing the data in a dictionary would also help you avoid the nasty use of global variables.

Suggested solution

This solution uses regular expressions to analyze the template and perform the word substitutions.

from collections import defaultdict
import random
import re

def mad_lib(template):
    blanks = re.findall(r'\{(.*?)\}', template)
    random.shuffle(blanks)
    words = defaultdict(list)
    for part_of_speech in blanks:
        words[part_of_speech].append(input(part_of_speech + ":\n> "))
    for answers in words.values():
        random.shuffle(answers)
    return re.sub(
        r'\{(.*?)\}',
        lambda match: words[match.group(1)].pop(),
        template
    )

print("<<<<<<<<<<<<<<<<<<<<<<<<< Mad Libs >>>>>>>>>>>>>>>>>>>>>>>>>")

print(mad_lib(
    "{Verb(-ing)} these {Noun(plural)}, {Noun} like a {Noun}, I'm {Verb(-ing)} {Noun(plural)} now, someone {Verb(-ed)} me do I {Verb} {Noun(plural)}, it's gonna be {Adjective}, {Verb(-ing)} {Noun(plural)} that's what I'm {Verb(-ing)} about yeah"
))

print(mad_lib(
    """You have been {Verb(-ed)} into Hogwarts {Noun(singular)} of {Adjective} and {Adjective}. You will be {Verb(-ing)} throughout the {Noun(singular)} and will {Verb} in the {Noun(plural)}. You will be {Verb(-ed)} in one of the four houses.
{Noun(singular)}, {Noun(singular)}, {Noun(singular)} or {Noun(singular)} and will learn much about the {Adjective} {Noun(plural)}. Once you arrive you will {Verb} The Great {Noun(singular)} for a feast with the headmaster, Proffessor
{Noun(singular)}. You will need to get all the {Adjective} {Noun(plural)} in {Noun(singular)} Alley and get a {Noun(singular)} from Ollivanders {Noun(singular)} shop. We hope to {Verb} you there."""
))


There's a reason the algorithms in the standard library use iterators instead of dealing with containers directly. One is that it makes code like this quite a bit simpler. For example, using iterators, we could write Flatmap something like this:

template <typename InIter, typename OutIter, typename FN>
void Flatmap(InIter begin, InIter end, OutIter out, FN fn) {
    for (; begin != end; ++begin) {
        auto y = fn(*begin);
        std::copy(std::begin(y), std::end(y), out);
    }
}

This is somewhat more versatile, since it can take input from/write output to essentially any iterator, rather than necessarily reading from one vector and producing another vector. Likewise, what's produced by fn doesn't have to be a vector either--it can be essentially any container (anything for which we can use std::begin() and std::end(), to be more exact). While vector is certainly common, there are reasons for using other containers--and sometimes even a reason to write to something that isn't exactly a container either. For example:

std::vector<int> inputs { 1, 2, 3 };

Flatmap(inputs.begin(), inputs.end(),
        std::ostream_iterator<int>(std::cout, "\t"),
        [](auto x) { return std::vector<decltype(x)> { x, x * 2, x * 3 }; });

Note that I've used auto as the parameter type in the lambda, so this test code requires C++14, but Flatmap itself is fine with C++11.

If you wanted to be a bit more forward thinking, you could write this to work with ranges instead of iterators. Eric Neibler's range library is fairly nice, and seems well on its way toward being included in an upcoming C++ standard.

Along with the code being simpler and more versatile, the other obvious advantage would be that this follows the same style as standard library code--for example, its signature and usage is essentially identical to std::transform.


Real time graph simulation of dice tossing

You are doing a lot of unneeded stuff. I completely deleted the for loop in the main part as well as the second plt.show. I also removed the plot_points function. None of this changed the functionality of the program, as far as I can tell.

matplotlib.animation.FuncAnimation takes an optional fargs argument which contains arguments to be passed on to the animate function. So this gets rid of needing global variables.

I made update_results modify x. This makes the update_results function obsolete, because now we only need to increment the element at the index chosen by the dice, which we can inline in the animate function.

I made the starting array start with all zeros, which is more realistic. Because of this I had to include a min(x) or 1 in animate to ensure that if the minimum is 0, 1 is used. I used the fact that [0] * 3 == [0, 0, 0] to simplify the initialization.

I also made the y limit fix you suggested by updating it in the animate function and made it obvious that the first parameter of the animate function is unused by using _ for it.

import random

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

SIDES = 6

def animate(_, x, patches):
    die_toss = random.randrange(SIDES)
    x[die_toss] += 1
    for rect, h in zip(patches, x):
        rect.set_height(h)
    print(x, max(x) / float(min(x) or 1))
    axes = plt.gca()
    axes.set_ylim([0, max(x) + 1])
    return patches

def main():
    x = [0] * SIDES

    fig = plt.figure()
    n, bins, patches = plt.hist(
        x, SIDES, facecolor='green', alpha=0.75)

    frames = 500
    ani = animation.FuncAnimation(fig, animate, fargs=(x, patches))
    plt.show()

if __name__ == "__main__":
    main()


Check whether a list of list of string fits a regex efficiently

Bonus points if someone can calculate the asymptotic time my algorithm takes.

Too much. It's exponential, as you're generating the whole candidate set. Even the improvement by rolfl doesn't change it.
You could do much better by analyzing the regex. For example "\\d{3}" will never match anything starting with a letter and you could cut off many possibilities. However, doing this in general is pretty complicated.
There's a method which might do this for you: hitEnd. I'm not sure if it does the right thing, but I guess so:

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.
When this method returns true, then it is possible that more input would have changed the result of the last search.

So you could test you incomplete candidates against the regex and possibly save yourself the work with expanding them.


Byte Array to Hexadecimal String Conversion

Ask yourself "how can I make the meaning and intention of the code more clear?"

Consider making small helper methods rather than duplicating code:

static byte HighNibble(byte b) => (byte)(b >> 4);
static byte LowNibble(byte b) => (byte)(b & 0xF);
static char NibbleToHex => ... etc.

And now instead of

    b = ((byte)(bytes [i] >> 4));
    c [i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30)
    b = ((byte)(bytes [i] & 0xF));
    c [i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);

Which is overwhelming in the sheer amount of punctuation, we have:

 c [i * 2] = NibbleToHex(HighNibble(bytes[i]));
 c [i * 2 + 1] = NibbleToHex(LowNibble(bytes[i]));

So much easier to read and understand.


I question the value of this template class.  We hide many important members of std::unordered_map (including crbegin(), empty(), reserve(), at(), try_emplace()) for no good reason.  The additional functions that are provided have no business being members: they are perfectly implementable as free functions without privileged access.

Considering the members in turn:

insert(): only instantiable if T is convertible to the map's value_type.  Unnecessarily copies the argument.
operator(): unnecessary, given that we have operator[].
operator[]: unnecessarily copies its argument.
find(), size() begin(), end(): required only because the map is private.
exists(): should be a free function.  If this is generic, why is the parameter called userId?
remove() - why not just use the erase() that accepts a key?  Or do we have to build with pre-C++11 library?

When I've wanted to provide something like the exists() here, I've made it a standalone template function that can work with many kinds of container:

/*
 * contains()
 * A convenience overload that searches from beginning to end of a container.
 *
 * If an iterator is supplied, it will be written with the found position or
 * container.end() as appropriate.
 */
template<typename T, typename U>
inline bool contains(const T& container, const U& value)
{
    using std::begin;
    using std::end;
    return find(begin(container), end(container), value) != end;
}

template<typename T, typename U, typename Iter>
    /* Iter should be a T::iterator or T::const_iterator */
inline bool contains(T& container, const U& value, Iter& it)
{
    using std::begin;
    using std::end;
    return (it = find(begin(container), end(container), value)) != end;
}

/*
 * Overloads for pointer-to-const values within containers of pointer-to-mutable.
 */
template<typename T, typename U>
inline bool contains(const T& container, const U* value)
{
    using std::begin;
    using std::end;
    return find(begin(container), end(container), value) != end;
}

template<typename T, typename U, typename Iter>
inline bool contains(const T& container, const U* value, Iter& it)
{
    using std::begin;
    using std::end;
    return (it = find(begin(container), end(container), value)) != end;
}

/*
 * Overloads for maps (by key)
 */
template<typename T>
inline bool contains(const T& container, const typename T::key_type& key)
{
    return container.find(key) != container.end();
}

template<typename T, typename Iter>
inline bool contains(T& container, const typename T::key_type& key, Iter& it)
{
    return (it = container.find(key)) != container.end();
}

template<typename T>
inline bool contains(const T& container, const typename T::key_type& key,
                     typename T::mapped_type& result)
{
    typename T::const_iterator it;
    return contains(container, key, it) && (result = it->second, true);
}


General Code Review

First, your function and my proposed changes (entropy') side-by-side.

import Data.List (foldl1', foldl')

entropy :: [Int] -> Int -> Int -> Double
entropy itemFrequencies totalElements logarithmicBase =
  -(foldl1' (+) $ map (\p -> p * (logBase b p)) probabilities)
    where
      is = map fromIntegral itemFrequencies
      l  = fromIntegral totalElements
      b  = fromIntegral logarithmicBase
      probabilities = map (\i -> i / l) $ is

entropy' :: (Foldable f, Integral a, Floating b) => a -> a -> f a -> b
entropy' totalElems base =
  negate . foldl' (\ent f2 -> ent + freqEntropy f2) 0
  where
    freqEntropy f = let p = (fromIntegral f) / l
                    in  p * logBase b p
    l             = fromIntegral totalElems
    b             = fromIntegral base

My comments, in an arbitrary order:

Why are you using foldl1'? It makes sense to use foldl' from a performance perspective, but it isn't clear to me why you require a nonempty list. Perhaps use a Maybe to encapsulate this possibility of failure, or outline why you expect a nonempty list in a comment. It's a good idea to keep tabs on where your partial functions are to avoid surprises at runtime. My function just returns 0 for a null Foldable.
Your types can be generalized more than Int and Double, if you want this to be more flexible/reusable. What I did to find these types was track down what functions you were using and figure out what their types were (which were more general than Int or Double or []). Then I resolved the overall function to its most general type. Whether this is necessary or useful depends on your application. I think the most useful generalization here is to Foldable in case you wanted to calculate entropy of things that were not lists.
When I changed to generalize to Foldable, I rolled all of the maps into the foldl'. This may be more performant if the compiler doesn't combine maps, but it's also a tad bit more complicated to understand.
I moved the itemFrequencies to be the last argument so I could write the function pointfree. Pointfree is kind of cute, but if you think it's more readable you can change the order and/or put the explicit itemFrequencies back in.
I added an explicit call to negate (I didn't get what was going on at first with the -(foldl1' ...)).
I shortened the names so that things are not overwhelmingly long or verbose. This is just my personal taste. I think if you're going to have descriptively long variable names, you shouldn't skimp on the description for your temporary variables. I think b is OK since it's a common variable for base, but I would recommend using something like len instead of l and itemFreqs' instead of is.

Performance and Profiling

I can't really help you on this front. GHC does have a profiler, which might be useful if you want to do some serious profiling.


Retrieve data from two different rows in a single SQL query?

You can use Sql Server's window functions LEAD and LAG to get access to two rows in one SELECT statement.
Here's just one way to get the results you're after:
DECLARE @jobs TABLE
(
    Job char(1) primary key,
    Start_time datetime,
    End_time datetime
);

INSERT @jobs VALUES
('A', '2020/01/10 8:00', '2020/01/10 8:15'),
('B', '2020/01/10 8:15', '2020/01/10 8:17'),
('C', '2020/01/10 8:17', '2020/01/10 8:19'),
('D', '2020/01/10 8:19', '2020/01/10 8:53');

SELECT Job,
    Start_time,
    [Other job],
    [Other job's end time],
    DATEDIFF(mi, Start_time, [Other job's end time]) [Diff (min)]
FROM
(
    SELECT
        Job,
        Start_time,
        LEAD(Job, 2) OVER (ORDER BY Start_time) [Other job],
        LEAD(End_time, 2) OVER (ORDER BY Start_time) [Other job's end time]
    FROM @jobs
) AS data
WHERE [Other job] IS NOT NULL

Which shows:
Job  Start_time              Other job Other job's end time    Diff (min)
---- ----------------------- --------- ----------------------- -----------
A    2020-01-10 08:00:00.000 C         2020-01-10 08:19:00.000 19
B    2020-01-10 08:15:00.000 D         2020-01-10 08:53:00.000 38

You can output the difference between two specific jobs by filtering appropriately:
SELECT Job,
    Start_time,
    [Other job],
    [Other job's end time],
    DATEDIFF(mi, Start_time, [Other job's end time]) [Diff (min)]
FROM
(
    SELECT
        Job,
        Start_time,
        LEAD(Job) OVER (ORDER BY Start_time) [Other job],
        LEAD(End_time) OVER (ORDER BY Start_time) [Other job's end time]
    FROM @jobs
    WHERE Job IN ('A', 'C')
) AS data
WHERE Job = 'A'

Which shows:
Job  Start_time              Other job Other job's end time    Diff (min)
---- ----------------------- --------- ----------------------- -----------
A    2020-01-10 08:00:00.000 C         2020-01-10 08:19:00.000 19


General static value required by multiple classes

If the seed parameter is required for the Noise class to work properly, it must go to the constructor as a required parameter. If an invalid seed passed to the constructor, it should throw an ArgumentException explaining what's wrong with the seed and (ideally) what the expected value could look like (e.g. if there are some range rules take place in your domain).

Consumers of the Noise class will have to inject the proper value (likely taking it from the settings).


Your function is slow for large values of n because the intermediate
values of num and den quickly grow to huge integers, making the multiplication slow.

You can improve that
by reducing each intermediate result "modulo m", so that all numbers will
always be in the range 0 ... m-1.

The final division num/den must then be computed as a "modular division":

def mod_div(a, b, m):
    """modular division

    Returns a solution c of a = b * c mod m, or None if no such number c exists.
    """
    g, x, y = egcd(b, m)
    if a % g == 0:
        return (a * (x // g)) % m
    else:
        return None

using the "Extended Euclidean Algorithm, for example with the code from
http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm#Recursive_algorithm

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

The if/else can be avoided, either as @Janos suggested, or by replacing
r by n-r if the latter is smaller. Your function would then look like this:

def f(n, r, m):

    if n - r < r:
        r = n - r

    num = 1
    den = 1

    for j in xrange(n - r + 1, n + 1):
        num = (num * (j ** j % m)) % m
    for k in xrange(2, r + 1):
        den = (den * (k ** k % m)) % m

    return mod_div(num, den, m)

At least for large values of n this should be faster. I made a test
with f(10000, 100, 747164718467):

Your code: 25 seconds
Above code: 0.2 seconds

A possible further improvement would be to compute the powers j ** j % m also
with a "modular power" method, such as power_mod() from http://userpages.umbc.edu/~rcampbel/Computers/Python/lib/numbthy.py.
The reduced the time for calculating f(10000, 100, 747164718467)
to 0.05 seconds on my computer.


Simplify

Since $# cannot be both 0 and 1 at the same time, it would be better to join the two if conditions here:

local a="$1"
if [ $# -eq 0 ]
then
    a="default"
fi
if [ $# -eq 1 ]
then
    git config --global user.name "$a"
    git config --global user.email "$a@$a.com"
fi

But, actually, what if there are 2 or more parameters instead of 0 and 1? It can happen by a programming mistake. It would be more robust to rewrite this by checking the values of the parameters, rather than their total count:

if [ "$1" ]
then
    git config --global user.name "$1"
    git config --global user.email "$1@$1.com"
fi

Notice that I eliminated the a local variable, as it was pointless (a="default" set but never actually used).

Avoid changing directories in scripts

This is a bit fragile:

cd ~/root_install/grunt
npm install
cd ~/root

A cd command may fail, for example if the directory was not yet created. In general it's not a good idea to change directories inside a script, as the script might perform actions in unexpected directories when things go wrong.

A good solution in such situations is to wrap commands within (...), like this:

(cd ~/root_install/grunt; npm install)

Directory changes executed inside (...) will not affect the environment outside.

You can learn more about this syntax in the Compound Commands section in man bash:

   (list) list  is  executed in a subshell environment (see COMMAND EXECU-
          TION ENVIRONMENT below).  Variable assignments and builtin  com-
          mands  that  affect  the  shell's  environment  do not remain in
          effect after the command completes.  The return  status  is  the
          exit status of list.

Robustness

Note that if you re-run the script a 2nd time, some commands will fail, for example these:

mkdir ~/root_install/grunt
ln -s ~/root/config/grunt/package.json ~/root_install/grunt/package.json
ln -s ~/root/config/grunt/Gruntfile.js ~/root_install/grunt/Gruntfile.js

If the directory and the symlinks already exist, the script will print error messages for these lines. You can avoid that by adding some flags:

mkdir -p ~/root_install/grunt
ln -sf ~/root/config/grunt/package.json ~/root_install/grunt/package.json
ln -sf ~/root/config/grunt/Gruntfile.js ~/root_install/grunt/Gruntfile.js

Naming

These variable names are not very helpful:

local a=$(which bash) b=$(which git) c=$(which grunt) d=$(which subl)
local g=$(which node)  i=$(which heroku)

Better name these after the commands they represent:

local bash=$(which bash) git=$(which git)  # and so on ...


Checking balance of a travel card with Selenium

Your code is actually quite clean and readable, good job. Here are some of the things I would consider changing:

you can simplify get_credentials() a bit, using the tuple packing/unpacking:

def get_credentials():
    """Get user credentials from a JSON file."""
    with open('auth.json', 'r') as f:
        auth = json.load(f)
        return auth['username'], auth['password']

end your docstrings with a dot as per PEP8
if the page manipulation selenium code is going to continue grow, you should definitely consider switching to using Page Object pattern building abstractions around the webpages you are working with. But, for this kind of problem, it is perfectly fine to not use page objects
div.pull-left does not look like a good quality locator. It may work now, but this locator is fragile because it is design-specific (pull-left is a bootstrap class used for page layout). See if this element has an id or a data-oriented class or a data-oriented attribute.


Client side authorization when retrieving from server

Bearing in mind that it is a ecmascript-8 feature, instead of waiting for the promise to be fulfilled with a callback:

axios.get(this.route('authorize', params))
   .then(res => {
     Vue.set(this.userAuthorizations, key, res.data.allowed)
   })
   .catch(err => this.showError(err.message))

the code could wait until the response is retrieved using await:
async can (ability, model = null, id = null) {
  const key = `${ability}_${model}_${id}`
  const params = {
    ability, model, id
  }

  const response = await axios.get(this.route('authorize', params))
    .catch(err => this.showError(err.message))

  Vue.set(this.userAuthorizations, key, res.data.allowed)
  return res.data.allowed
}

Note that can() needs to be declared as async in order for await to be permitted inside of it.


VBA code to read Excel file and conditionally complete formulas based on the contents

Some tips I suggest trying...

VarM and a shouldn’t be variants. I would change those to integers.

Overly abundant on counting loops, in this scenario you should loop a range through a named range.

Also use the .offset(1,0) instead of  adding 1 for rw. Use .offset(0,1) instead of reading the cells(lastrow,”b”). Set application.calculation back to automatic at the end (I wouldn’t turn it off but depends on your data rows). Use with end with statements, it’ll help make the code more readable as well.

You have a lot of if else end if blocks. I would break that into a select case statement when a criteria is met for your formulas. I’m on my phone but I hope this makes enough sense for you to try. This is what the structure would look similar to:

with ws
for each cell in MyRNG

‘Select case for cell criteria
‘if statement here for formula criteria
‘End if
‘Next case statement here...

Next cell
End with


This strikes me as looking a little like code I'd expect to see from a compiler--code that works, but completely ignores both traditional x86 register usage, and the special instructions the x86 provides for the job.

Traditionally, you'd use edi to point to your destination string, and esi to point to your source string. You'd use a repnz scasb to find the end of the first string, and lodsb/stosb to copy bytes from the source to the destination (there is actually a movsb to copy bytes as well, but it doesn't allow you to check for the end of the string as you copy).

Note that this depends on the direction flag being 0, but every compiler of which I'm aware leaves it that way (and depend on your leaving it that way as well).

    xor eax, eax     ; set al to value we're looking for, 0 in this case.
    lea ecx, [eax-1] ; set ecx to 0ffffffffh

    mov edi, [esp+4] ; find end of dest string
    repnz scasb

    mov esi, [esp+8] ; we've found the end of the destination, now do the copy
    dec edi

copy_loop:
    lodsb
    stosb
    test al, al
    jnz  copy_loop
    ret

This is somewhat shorter. Under normal circumstances, we can expect either one to be memory bound, so speed probably isn't particularly relevant (but if we did care, it would depend on the exact processor in use--this would tend to work better on older processors, but would be about the same to possibly even a little slower on newer processors).

As far are readability goes, either one is fairly easy to read, but I think my code fits more closely with how somebody with experience writing code for an x86 would expect to see the registers used. As far as indentation goes, there doesn't seem to be much agreement about whether to indent assembly language. Your indentation certainly doesn't hurt anything, but it isn't like higher level languages where it's expected to the point that unindented code is clearly a problem. The way I've written the code above (instructions indented one stop, label(s) at the left margin) is almost certainly more common.

I should probably add that I'm a bit hesitant to post on this subject--while I think I wrote assembly language quite well at one time, it's been years since I wrote enough to notice. I do look forward to @Edward posting a review on this (though I'm not sure whether he writes much assembly code any more either).


Opportunities missed

You have essentially the same algorithm in both examples. When I first looked at the solutions the sort at the start was a worry. The logic is sound, to work from the smallest word as there will be no more characters to test then is contained in that word.

However you have the sort AoT and the result is you set first to be the longest word in the array.

Changing the sort to be the other direction works great improving the performance near 3-4 times if there is a much shorter word in the array. However there is no real benefit with the sort if all the words are of similar length.

Another missed optimization is breaking out of the inner loop when you set isDuplicates to false. Adding a break saves having to do any further iteration and gives another 10% performance. BTW the name  duplicates would have just as much meaning.

String.search(arg) and String.indexOf(arg)

The real bottle neck is in the inner loop where you locate the current character e in the current word. letters.search(e)

It may look innocent but this is where knowing the language well come into play. String.search(arg) takes as the first argument a regExp but also works with just a string. The catch is that the string is first converted to a regExp before the search starts. This is a huge overhead.

If you use String.indexOf instead your code is almost twice as fast. I tried to write something that could beat it using Maps to reduce time complexity, and as such only starts to outperform when the word lengths get much longer 50+ characters.

Rewrite

So for small words your solution with slight modification is very fast.

Sort now from smallest to largest,
Breaks from inner loop when no duplicates found.
Uses faster String.indexOf to do inner character search.

And some name changes..

function commonCharsNo(words) {
    const [first, ...rest] = words.sort((a, b) => (a.length - b.length));
    const duplicates = [];
    [...first].forEach(e => {
        let duplicate = true;
        for (let x = 0, len = rest.length; x < len; x++) {
            let word = rest[x];
            const i = word.indexOf(e);
            if (i !== -1) {
                rest[x] = word.slice(0, i) + word.slice(i + 1);
            } else {
                duplicate = false;
                break;
            }
        }
        if (duplicate) {
            duplicates.push(e);
        }
    });
    return duplicates;
}

Reduce complexity

The search (now indexOf) is where the code gets poor complexity \$O(m)\$. Its \$O(n.m)\$ where \$n\$ is the number of characters in the smallest word and \$m\$ is the mean number of characters per word.

You can reduce this to approx \$O(w.m)\$ where \$w\$ is the number of words and \$m\$ is the mean number of characters per word.

The improvement is small and only pays out for longer words.

function findCommonChars(words) {
    var chars;
    const result = [];
    words = [...words.sort((a,b)=>b.length - a.length)];
    const countChars = (word, res = new Map()) => {
        for (const char of word) {
            res.has(char) && (!chars || chars.has(char)) ?
                res.get(char)[0]++ : res.set(char, [1]);
        }
        return res;
    }
    chars = countChars(words.pop());
    const charCounts = words.map(word => countChars(word));
    for (let [char, count] of chars.entries()) {
        for (const word of charCounts) {
            if (word.has(char)) { count = Math.min(count, word.get(char)[0]) }
            else {
                count = 0;
                break;
            }
        }
        while (count--) { result.push(char) }
    }
    return result;
}


Can I ask why you're trying to do this? If this is homework or a way to "practice Java/Object-Oriented programming", please say so. If it's a real question, the best way to represent XPath input is actually a string. XPath is way more complicated than what you've (XPath 2.0 even more so), and you would need a lot of more work to model this properly. If it's a subset of XPAth, then what subset?

Edit: A few examples.

Valid XPath expressions:

ancestor-or-self::*
../employee[@secretary and @assistant]
substring("12345", 1.5, 2.6)
child::para[position()=5][attribute::type="warning"]

Valid XPath 2.0 expressions:

($x div $y) + xs:decimal($z)
fn:error(xs:QName("app:err057"), "Unexpected value", fn:string($v))

Also note that you can evaluate XPath expressions using the standard javax.xml.xpath, thus not needing rolling your own. If you need something else, maybe reuse the source code of javax.xml.xpath to suit your needs?


Structuring a HTML5 game without a framework

In order to prevent objects from depending on global variables (and in JavaScript almost every identifier is actually a variable), you can use the principle of dependency injection.

When an object needs to interact with another object, it should receive that object, either when it is initialized, through a setter or as a method parameter.

When your player requires the world, you could pass it when you create it and store it in a variable in local scope:

var player = new Player(world);

However, when your game has multiple worlds and the player moves from one to the other, it would be good to be able to change the world. In that case you could have a setter:

var player = new Player();
player.setWorld(world);

When the world is only required for a single method, you can also decide to pass the object to that method as a parameter:

player.checkCollisions(world);


c++ is it worth preprocessor optimization for for loops while i < 1

Notational suggestion: if insisting on a bracketed controlled statement, favour
#if 0 < repetitions
# if 1 < repetitions
    for (int i = 0; i < repetitions; i++)
# endif
    {
        CallFunc(functionPtr, otherParamaters …); // inline call to timed function
    }
#endif


Speedup for Project Euler 44 - pentagon numbers

You're right that the problem condition that \$\left|P_k - P_j\right|\$ be minimized means that to properly solve it, it's not sufficient to find a pair of pentagonal numbers whose sum and difference are both pentagonal: you have to also establish that there is no pair of pentagonal numbers with the required property and a smaller difference.

Once you've found one pair of pentagonal numbers with the required property, this gives you a bound on \$j\$ and \$k\$; unfortunately the bound is in the millions, so that any \$\Omega(n^2)\$ algorithm (in particular, any algorithm that compares pairs of pentagonal numbers below the bound) will take far too long. It's no good just speeding up what you've got: you have to take a completely new approach.

So here's a rough sketch of an alternative algorithm.

The \$n\$th pentagonal number is $$P_n = {n(3n-1)\over 2}.$$ By completing the square, $$P_n = {(6n - 1)^2 - 1 \over 24}.$$ If \$P_k - P_j = P_x\$ and \$P_k + P_j = P_y\$ are both pentagonal numbers, then $$ \eqalign{ (6k - 1)^2 - (6j - 1)^2 &= (6x - 1)^2 - 1 \\ (6k - 1)^2 + (6j - 1)^2 &= (6y - 1)^2 + 1 } $$ Write \$K = 6k - 1\$, \$X = 6x - 1\$, and \$Y = 6y - 1\$. Add the two equations above, getting $$ 2K^2 = X^2 + Y^2. $$

So the plan is:

Iterate over all values for \$k\$ below the bound that you already established.
For each \$k\$, let \$K = 6k - 1\$, and enumerate all the ways to write \$2K^2\$ as the sum of two squares \$X^2 + Y^2\$.
For each such decomposition, if \$X ≡ -1 \pmod 6\$ and \$Y ≡ -1 \pmod 6\$ and \$J = \sqrt{K^2 - X^2 + 1} ≡ -1 \pmod 6\$, then this is a solution.

In step 2, the enumeration of \$2K^2\$ as sums of two squares can be computed efficiently by factorizing \$K\$ and then using the Brahmagupta–Fibonacci identity. Since you are going to be needing a lot of these factorizations, it will be most efficient to sieve for them.

This ought to be doable within your 10 second goal.

(Credit: I adapted this strategy from Daniel Fischer's post in the Project Euler forum.)


Making user login system secure with $_SESSION

One long line that is hard to read.

The technique looks legitimate, but I caution against reusing 'username' as the key for storing the login state.  Who knows, someday you might want to be able to persist a username even when logged out.  Or maybe a multi-page user registration form would set $_SESSION['username'] between pages.  I recommend choosing something more explicit, such as 'login_time' — and you could also use it later to help with automatic logouts after a certain time.

Note that calling header(…) does not halt the regular program flow.  Whoever calls check_session_valid() will still need to terminate further processing if the session is invalid, so your check_session_valid() should return a TRUE/FALSE value as well.  You could also throw an exception to ensure that regular program flow is impossible.


Recursive Binary Tree Inorder Traversal in Python

Naming

Solution is a bit generic for a class name. It could basically mean anything, because almost every algorithm has some kind of solution. A better fitting name would be TreeTraversal. It tells the reader (you, but also others) what it means.

inorderTraversal has two problems. Firstly, it doesn't sound like a method name, because methods are usually verbs. Secondly, the convention for methods and functions in Python is lower_case_with_underscores, also called snake case. My suggestion is to name it traverse_inorder, or even just inorder considering you rename the class to TreeTraversal.

inorderHelper has the same two problems as the previous one, but additionally it does not really tell you what it does. If it is a helper, maybe it should be a class, but it does not do enough for that. If it is a method or function, what does it help you with, i. e. what does it do? A better name might be traverse, and you could consider making it an inner method of the other method, since it will not be used outside of it. That way the user of the class does not need to think about which one of the two methods to use.

OOP

You might consider making all that code (after the suggested changes above, only one short method) part of the tree class. After all, it depends on the tree anyways. Of course this does not apply if you did not write the Tree class yourself, or if you want to make a more generic traversal class for different types of trees.

In def inorderHelper(self, node, inorder) you do not need to specify a parameter for inorder. Since it is a member variable, you can just access it via self.inorder.

def inorderHelper(self, node, inorder):
    if (node is None):
        return
    else:
        self.inorderHelper(node.left, inorder)
        inorder.append(node.val)
        self.inorderHelper(node.right, inorder)

You can invert the if-condition and thus make the code shorter. The else is implicit. The parantheses around the condition are not needed and usually not used, since without them it reads more naturally.

def inorderHelper(self, node, inorder):
    if node is not None:
        self.inorderHelper(node.left, inorder)
        inorder.append(node.val)
        self.inorderHelper(node.right, inorder)


char *str = "ABCADEFGHIJKL";

This should be const char* str because string literals are usually stored in read-only memory.

for (int i = 0; i < 255; i++)
    arr[i] = 0;

You can get rid of this loop by using aggregrate initialization:

array<char,255> arr{};  // zero-initialize all elements

int i = 0;

while (str[i])

You can get rid of the index variable i by using the string pointer for iteration. Also use a for loop which is more concise:

for(; *str; ++str)
{
    if (arr[*str] == 1)
    {
        cout << "Not unique";
        return 0;
    }

    arr[*str] = 1;
}

I would also change array<char,255> to array<bool,255> which expresses intend better as you only use values of 0 and 1 anyway.

Edit:

As pointed out in this answer the OPs code (and mine aswell) is vulnerable to buffer overruns. Although OP stated that input will be ASCII only (which is in the range of 0..127), if the string is user input then it shouldn't be trusted.

One way the vulnerability could be mitigated would be a range check of the input characters. If they are out of the ASCII range, discard them, replace them by a "dummy" value or do whatever fits your situation.


GeeksforGeeks: Rotate matrix by 90 degrees

A simple improvement for readability could be to eliminate the - 1 in the indices by replacing size with max = mat.GetLength(0) - 1;:

void rotateMatrix(int[,] mat)
{
  int max = mat.GetLength(0) - 1;
  for (int x = 0; x < (max + 1) / 2; x++)
  {
    for (int y = x; y < max - x; y++)
    {
      int temp = mat[x, y];             // save 1
      mat[x, y] = mat[y, max - x]; // move 3 into 1
      mat[y, max - x] = mat[max - x, max - y]; // move 9 into 3
      mat[max - x, max - y] = mat[max - y, x]; // move 7 into 9
      mat[max - y, x] = temp;
    }
  }
}

You could also make a pair of vars for max - x and max - y as :

void rotateMatrixReview(int[,] mat)
{
  int max = mat.GetLength(0) - 1;
  for (int x = 0; x < (max + 1) / 2; x++)
  {
    for (int y = x; y < max - x; y++)
    {
      int xmax = max - x;
      int ymax = max - y;
      int temp = mat[x, y];             // save 1
      mat[x, y] = mat[y, xmax]; // move 3 into 1
      mat[y, max - x] = mat[xmax, ymax]; // move 9 into 3
      mat[xmax, ymax] = mat[ymax, x]; // move 7 into 9
      mat[max - y, x] = temp;
    }
  }
}

Just for the fun: another approach could be:

void Swap(int[,] mx, int r1, int c1, int r2, int c2)
{
  int tmp = mx[r1, c1];
  mx[r1, c1] = mx[r2, c2];
  mx[r2, c2] = tmp;
}

void rotateMatrix(int[,] mat)
{
  int m = mat.GetLength(0) - 1;

  // l = level in the matrix from outer = 0 to inner
  for (int l = 0; l < (m + 1) / 2; l++)
  {
    // o = offset along rows and cols
    for (int o = 0; o < m - 2 * l; o++)
    {
      Swap(mat, l, l + o, l + o, m - l);
      Swap(mat, m - l - o, l, m - l, m - l - o);
      Swap(mat, l + o, m - l, m - l - o, l);
    }
  }
}


Changing a user status flag, with validation

Maybe just change the before_update to execute when #changed? is true?

http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-changed-3F

EDIT: After looking at the question again, I'd change my answer. I think it's reasonable to return true. There's not really anyway around it, considering the way callbacks handle the return value. I suppose you could invert the values of the is_kyc_verified to be something like is_kyc_unverified?. But, that already seems confusing.

I do however think you should move the unless: :is_kyc_verified_changed? into the change_kyc_status method. I find the current flow a little hard to follow, as you must check in two places if is_kyc_verified will be set.

I might change it to something like:

before_update :confirm_is_kyc_verified
...
def confirm_is_kyc_verified
  if !is_kyc_verified.changed? && is_kyc_verified && valid?
    is_kyc_verified = false
  end

  true
end


How to find the common factors of 2 numbers

Indentation & style
One of the most distinctive features of Python is its use of indentation to mark blocks of code. Your code is not properly indented (each level of indentation should be equivalent to 4 spaces not like this:
def print_factors(x,y):
 l = []

like this:
def print_factors(x,y):
    l = []

Check pep8 https://www.python.org/dev/peps/pep-0008/ the official Python style guide, you'll find it helpful when learning the basics of Python code style and naming conventions.
Return
a function should not print anything, it should return
print (list(set(l).intersection(m)))
#len(print (list(set(l).intersection(m))))

and print is a function in Python 3.x, so it's very obvious it has no length
len(the commented line).
len
len() is used to get the length of sequences:
my_list = [1, 2, 3, 4]
print(len(my_list))

output: 4
Docstrings
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docsting is defined by including a string constant as the first statement in the object's definition.
it is generally a good practice to use docstrings in your functions explaining what the function does that are usually enclosed within triple quotes:
def print_factors(number1, number2):
    """Return factors of number1 and number2."""
    # do things
    # return something

Descriptive variable names
l = []
for i in range(1, x + 1):
    if x % i == 0:
        l.append(i)
m = []
for i in range(1, y + 1):
    if y % i == 0:
        m.append(i)
print (list(set(l).intersection(m)))

what is l, what is i what is x ... names should be descriptive to improve the readability of your code (whether people that are reading your code and trying to understand or you reading your own code in the future) and here's an example:
factors_1 = []
factors_2 = []
for divisor in range(1, number1):
    if number1 % divisor == 0:
        factors1.append(divisor)
for divisor in range(1, number2):
if number2 % divisor == 0:
    factors2.append(divisor)

The code

Your function is not even doing what it should be doing (returning
the number of common factors not the factors themselves.
You don't have to iterate over the whole range of the number, you iterate up to the square root of the number is sufficient to find all factors.

This is how the code might look like:
def get_factors(number):
    """Generate factors of number."""
    yield 1
    for divisor in range(2, int(number ** 0.5) + 1):
        if number % divisor == 0:
            if number // divisor != divisor:
                yield divisor
                yield number // divisor
            if number // divisor == divisor:
                yield divisor

if __name__ == '__main__':
    number1 = int(input('Enter first number: '))
    number2 = int(input('Enter second number: '))
    number_1_factors = set(get_factors(number1))
    print(f'Factors of {number1}: {number_1_factors}')
    number_2_factors = set(get_factors(number2))
    print(f'Factors of {number2}: {number_2_factors}')
    common_factors = number_1_factors & number_2_factors
    print(f'Number of common factors of {number1} and {number2}: {len(common_factors)} factors.')


Removing this odd while(true) for checking the queue

It sounds like you are sleeping only to avoiding busy waiting on the queue too frequently.

How about following the suggestion in this SO answer:

https://stackoverflow.com/a/5014271/2268996

so that you use the blocking Take method in your worker with code like this:

while (true)
{
    UserMessage m = blockingQueue.Take();
    dataItems.add(m);
    RaisePropertyChanged(() => FilteredDataItems);
    ... (no need to sleep here)...
}

You will still have the while (true) but not the Thread.sleep(...) call. Will that work for your situation?


Do  you  really  need  a  comment  above  every  line? There are a few good comments like # Function to retrieve current timestamp, hopefully using window.performance object, but comments like # Indicates if module is running are really not useful. They add no value to the code itself, and can be removed. Preferably, you should only be using comments when parts of the code are unclear.

Secondly, your function alias raf is fairly unclear. I'd recommend renaming it to something like requestFrame. Also, if you're creating aliases for functions like this, I'd also recommend creating one for window.cancelAnimationFrame, and other functions like this.

Finally, I'd recommend renaming tick to something like tickLoop, like how it's described in the comment above it.


A couple of notes on your code before going into alternative solutions.

In your findTriplet method, you are doing:

if (squareA == sum) {
    return true;
}
return false;

which is more concisely expressed as

return squareA == sum;

Your main getTriplets method checks whether (i != k) || (j != k), but this isn't possible by construction: k starts at i+j so it cannot be equal to i or j; thus this check can be removed. Also j starts at 1 when you could make it start at j + 1, which would also get rid of the i != j check.

You can do this in O(n²) by utilizing a TreeSet.

The idea is the following:

Transform the array into a TreeSet<Integer>, where each element will be the squared value of the element in the array. Using a TreeSet has the advantage that it sorts the elements ascendingly and allows for fast look-up.
For each element in the set, get all the elements greater than it and see if the set contains a third value equal to the sum of those two. This is because, if we look for 3 numbers a, b and c where a + b = c, then having both a and b only leaves the question: does the set contains a + b?

A possible implementation is the following:

private void getTriplets(int[] arr) {
    NavigableSet<Integer> set = new TreeSet<>();
    for (int element : arr) {
        set.add(element * element);
    }
    for (Integer a : set) {
        for (Integer b : set.tailSet(a, false)) {
            if (set.tailSet(b, false).contains(a + b)) {
                tripList.add(new Triplet(a, b, a + b));
            }
        }
    }
}

The method tailSet(element, false) will return a view of the set with all the elements strictly greater than the passed element. This method runs in constant-time. In the code above, a will loop through all the values of the set, b will loop over the values greater than a and we see if the set contains a + b. If it does then we have found a Pythagorian triplet.

This solution does have the overhead of creating a Set (so O(n) memory) but it is simple to write.

Another approach with O(1) memory is to keep an array but the approach is very similar:

  Sort the array in ascending order. This takes O(n log n).
  Now consider each element a[i]. If a[i]=a[j]+a[k], then, since numbers are positive and array is now sorted, k<i and j<i.

  To find such indexes, run a loop that increases j from 1 to i, and decreases k from i to 0 at the same time, until they meet. Increase j if a[j]+a[k] < a[i], and decrease k if the sum is greater than a[i]. If the sum is equal, that's one of the answers, print it, and shift both indexes.

  This takes O(i) operations.
  Repeat step 2 for each index i. This way you'll need totally O(n²) operations, which will be the final estimate.

Step 2 is similar to finding a given number by summing up integers from 2 sorted arrays.

In terms of code, you could have the following:

private void getTriplets(int[] arr) {
    int[] squaredArray = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        squaredArray[i] = arr[i] * arr[i];
    }
    Arrays.sort(squaredArray);
    for (int i = arr.length - 1; i >= 0; i--) {
        int j = 1, k = i;
        while (j < k) {
            int sum = squaredArray[j] + squaredArray[k];
            if (sum < squaredArray[i]) {
                j++;
            } else if (sum > squaredArray[i]) {
                k--;
            } else {
                tripList.add(new Triplet(squaredArray[j], squaredArray[k], squaredArray[i]));
                j++;
                k--;
            }
        }
    }
}

The main loop on i is performed descendingly since we're looking for two elements whose sum is squaredArray[i] (and the array is sorted ascendingly).


Strategy

The code would be more elegant if you made the apply_patch function more like a language interpreter.  Though it may be unavoidable that you have to treat the text as an array, you can treat the patch as a stream of instructions.  That would relieve you of the annoyance of having to increment i.

If your patch is already in string form, then you can turn it back into a stream using StringIO.  Chances are, you would be acquiring the patch from an input stream (such as STDIN), so you would use that stream directly instead.

To make that work, you would have to get rid of the if patch_array[i+2] == "s/.//" special case, which involves looking ahead by two lines.  In any case, you would be better off implementing support for s/.// as the string substitution command that it is meant to represent.

Command parsing

This feels like a lot of lines of code to parse the command line, especially to handle the fallback line numbers:

#grab the command
patch_array[i].match(/(\d*),?(\d*)(\w)/)
first_line = $1.to_i
last_line = $2.to_i
command = $3
if first_line == 0
  first_line = current_line
end
if last_line == 0
  last_line = first_line
end

You could simplify first_line and last_line by assigning the values correctly the first time.  To do that, you would need a regexp that produces a nil capture group when the number is missing.

For stricter validation, the regexp should be anchored by \A and \Z.  I suggest using a using the regexp to specify exactly what commands are supported, for validation.

If the command is unsupported, you should raise some kind of exception rather than raising a String object.  The exception message should include the bad command, to aid debugging.

Text manipulation

The name new_text_array is a bit cumbersome.  How about just text?  You don't need to assign the result to a new_text variable at the end of the function.

Instead of deleting a line at a time using delete_at, you can knock out an entire slice at once, using a Range for array indexing.

There is code duplication between the a command and the c command.  The key insight is that a c (change) is just a combination of d (deletion) and a (append).

Suggested solution

This is about half the original line count.

require 'stringio'

def self.apply_patch(old_text, patch)
  text = old_text.split("\n")
  patch = StringIO.new(patch)
  current_line = 1

  while patch_line = patch.gets
    # Grab the command
    m = %r{\A(?:(\d+))?(?:,(\d+))?([acd]|s/\.//)\Z}.match(patch_line)
    raise ArgumentError.new("Invalid ed command: #{patch_line.chomp}") if m.nil?
    first_line = (m[1] || current_line).to_i
    last_line = (m[2] || first_line).to_i
    command = m[3]

    case command
    when "s/.//"
      (first_line..last_line).each { |i| text[i - 1].sub!(/./, '') }
    else
      if ['d', 'c'].include?(command)
        text[first_line - 1 .. last_line - 1] = []
      end
      if ['a', 'c'].include?(command)
        current_line = first_line - 1
        while (patch_line = patch.gets) && patch_line.chomp! != '.'
          text.insert(current_line, patch_line)
          current_line += 1
        end
      end
    end
  end
  text.join("\n")
end


Extended Euclidean Algorithm in modern and readable C++

The code is rather tiny so there isn't much to say, but I still have a couple of remarks:

Since you're using C++17, you can take advantage of variable templates to simplify your static assertions a bit:

static_assert(std::is_integral_v<A>, "arguments to egcd are integers");
static_assert(std::is_integral_v<B>, "arguments to egcd are integers");

The LWG issues 2733 and 2759 highlight the fact that any possibly cv-qualified bool satisfies the std::is_integral trait, but the GCD and LCM operations don't make much sense for boolean types. Consequently, the extended operations don't make much sense for boolean types eithers. You could add the following static assertions to make it clear:

static_assert(not std::is_same_v<std::decay_t<A>, bool>, "arguments to egcd are not booleans");
static_assert(not std::is_same_v<std::decay_t<B>, bool>, "arguments to egcd are not booleans");

Since you're always computing both a / b and a % b, you can compute std::div instead which computes both at once and returns a structure with quot and rem members. Actually, the algorithm used to compute the remainder of a and b also computes the quotient of a and b, so functions like std::div exist in several programming languages so that users can take advantage of it instead of discarding a computed value and computing it again.
They're not widely available at the moment, but if you intend to keep returning an std::tuple, a C++17 decomposition declaration would probably make your code more readable by providing explicit names instead of the opaque std::get<position>:

if (b == 0) {
    return std::make_tuple(a, 1, 0);
} else {
    auto divmod = std::div(a, b);
    auto [gcd, bezout_x, bezout_y] = egcd(b, divmod.rem);
    return std::make_tuple(gcd, bezout_y, bezout_x - divmod.quot * bezout_y)
}


Readability

The vector initialization in main would be more readable if the {{ and }} were broken out onto separate lines.

    vector<vector<int>> nums = {
        {1, 1, 1, 0, 0, 0}, // 0
        {0, 1, 0, 0, 0, 0}, // 1
        {1, 1, 1, 0, 0, 0}, // 2
        {0, 0, 2, 4, 4, 0}, // 3
        {0, 0, 0, 2, 0, 0}, // 4
        {0, 0, 1, 2, 4, 0}
    }; // 5
    vector<vector<int>> nums2 =
    {
         {0, -4, -6, 0, -7, -6},
         {-1, -2, -6, -8, -3, -1},
         {-8, -4, -2, -8, -8, -6},
         {-3, -1, -2, -5, -7, -4},
         {-3, -5, -3, -6, -6, -6},
         {-3, -6, 0, -8, -6, -7}
    };

Complexity

The function int hourglassSum(vector<vector<int>> &arr) is too complex (does too much) it would be better if it was 2 functions:

int singleHourglassSum(vector<vector<int>> &arr, size_t i, size_t j)
{
    int hourglassSum =
            arr.at(i - 1).at(j - 1) +
            arr.at(i - 1).at(j) +
            arr.at(i - 1).at(j + 1) +
            arr.at(i).at(j) +
            arr.at(i + 1).at(j - 1) +
            arr.at(i + 1).at(j) +
            arr.at(i + 1).at(j + 1);

    return  hourglassSum;
}

int maxHourglassSum(vector<vector<int>> &arr) {
    int highestSum = INT_MIN;
    for (size_t i = 1; i < arr.size() - 1; ++i) {
        int sum = 0;
        for (size_t j = 1; j < arr.at(i).size() - 1; ++j) {
            sum = singleHourglassSum(arr, i, j);
            if (sum > highestSum) {
                highestSum = sum;
            }
        }
    }
    return highestSum;
}

Keep in mind the Single Responsibility Principle:

The Single Responsibility Principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.


For the table definitions, just use an INT for the keys.  You probably aren't saving anything by using SMALLINTs.  Schema changes tend to be a pain in larger projects, so you might as well try to avoid any possibility of trouble.

CREATE UNIQUE INDEX index_PK ON owner_property(property_id, owner_id); is redundant, since the table already has PRIMARY KEY properties_PK(owner_id, property_id).

The foreign key constraints look well done.

Having separate tables just for email and phone_number is probably overkill.  The e-mail addresses and phone numbers could just be attributes on the owner_email and owner_number tables, respectively.  I would put NOT NULL constraints on both of those attributes.  The phone_number field should probably be longer than VARCHAR(10).  (Note that MySQL tends to silently discard the part of the string beyond the length limit.)

Similarly, VARCHAR(50) for the property address is probably too stingy.

For your first query…

select af.property_id
from property af
inner join owner_property op
on af.property_id = op.property_id
where op.owner_id = 1; //find all properties of owner_id = 1

… you don't need to join anything at all.

select property_id
    from owner_property op
    where owner_id = 1;

For your second query…

select a.*
from home_owner a
inner join owner_property op
on a.owner_id = op.owner_id
where op.property_id = 3; //find all owners of property_id = 3

Use better indentation.  SELECT has a FROM clause and a WHERE clause.  FROM has an INNER JOIN.  INNER JOIN has an ON.
Use a table alias that makes better sense (or don't use an alias at all).

select o.*
    from home_owner o
        inner join owner_property op
            on o.owner_id = op.owner_id
    where op.property_id = 3; //find all owners of property_id = 3


The reason why the video states that you should not create SOEs on top of MXD based map services is because in 10.1 you will not be able to start a service from an mxd. You will need to convert your map document into a service definition.

One of the issues you will find with MXD-based SOEs in 10 when you upgrade to 10.1, is that your code most likely will be accessing layers or layouts in the map service. This is pretty common in MXD-based SOEs because it is through layers that you get to the datasets you want to use in your code etc.  At 10.1, your SOE code will break, because layers, layouts etc are only available in MXD-based SOE map services. If you create an MSD-based map service and build an SOE on top of it, you will notice the same. With MSD-based SOEs you need to use IMapServerDataAccess to get to the data sources in your map.  And that code will just work in 10.1. So writting SOE's on top of MSD is a good way to understand what will be possible in 10.1

I suggest you look at this and this.

As for using IMapDocument... go for it. It will work fine in 10.1


Static quiz module with predefined answers

Overall this is already pretty well organized and compact.  There isn't a lot of duplication or obvious abstractions that can be made.  It would be helpful to see the HTML to see if there are any changes that would make the Javascript easier to write.
A couple of suggestions:

Wrap the entire code block in an IIFE to avoid cluttering global namespace
 (function ($, undefined) {
     // Your code here ...
 } (jQuery));

Use .width() instead of .css('width', ...)

Some of your variables are only being referenced once and can be inlined:
 $('.flag').on('click', ...); // etc.


Retrieve generic contract names for Managed Extensibility Framework

The code in the question was an attempt to generate type contract names, from the way I saw how MEF created them. Especially the difference from Type.FullName, which was previously used, when getting a contract name. For this reason, the code is a probably inferior re-implementation of MEF's own name generation, and should not be used for this purpose.

This is the contract name resolution used by MEF in .NET framework (maybe different namespace in Core, Apps etc.):

Namespace:

System.ComponentModel.Composition

Static method:

AttributedModelServices.GetContractName(Type)

Unfortunately, it's often easier to re-invent the wheel, than to find out about existing implementations...


dispatch event listener problem after click

e.preventDefault();
e.stopPropagation();

if (e.target.nextElementSibling == null) {

    if (e.target.getAttribute('target') != null) {
        window.open(e.target.getAttribute('href'), e.target.getAttribute('target'));
    } else {
        window.location.href = e.target.getAttribute('href');
    }
}

Change that part to:
if (e.target.nextElementSibling == null) {
    return;
}

e.preventDefault();
e.stopPropagation();


By building two implementaions of a much simpler function you can see that the function in the question is in a form that is tail recursive.

let rec recList n =
    match n with
    | 1 -> [1]
    | _ -> n :: recList (n - 1)

let accList n =
    let rec loop (l,acc) =
        match l with
        |1 -> acc
        |_ -> let l' = l - 1 in loop(l',l::acc)
    loop (n,[]) |> List.rev

[<EntryPoint>]
let main argv =

    // Fails with a stack overflow!
    // printfn "%A" (recList 100000)
    printfn "%A" (accList 10000000)

The recList implementaion again demonstrates that a simple recursive function will cause the stack to explode, on my machine this happened between 10000 and 100000.

The accList version which mirrors the function in the question works with values much larger than the one that caused the recList function to fail.


Is there any way to condense my code so it does not take up so many lines?

When refactoring code that is not DRY then try to identify the parts that actually do change and put those parts into some kind of data structure like a list or dictionary. Then wrap everything into a function.
apps = {'app1': r"C:\Users\red\Desktop\app1",
        'app2': r"C:\Program Files (x86)\app2",
        ...
       }

selected_app = clicked1.get()

def click():
    os.startfile(apps.get(selected_app))
    i = 0
    while i < 20:
        try:
            app.connect(title_re=".*" + selected_app)
            break
        except pywinauto.findwindows.ElementNotFoundError:
            time.sleep(1)
            i += 1
    app1 = app.top_window()
    app1.move_window(x1, y1)
    time.sleep(.5)
    app1.maximize()


Could this connection and query class be improved?

convention for PHP class names is PascalCase, so your class should be ConnectionToDb.
you are inconsistent with your indentation (2 vs 4 spaces).
select * is discouraged. Don't just select everything if you only need one column, select only that column.
limit is actually a vector for SQL injection. You should also clean table before using it in a query. Even if the data isn't user supplied right now, as this is a class, which is meant for reuse, you can never be sure how it will be used in the future.
Don't just echo unsanitized data from the database (because it might be user supplied), this can result in an XSS vulnerability.

 isn't valid HTML, use
 or

I don't see the benefit of having this as a class. I would just remove make_connection and add the connection as a parameter to run_test_query.
run_test_query isn't a very good name.


Indentation and formatting are fine, as is the algorithm itself.

Your naming is inconsistent, compare n and Value; _value and _FnMinus1.  There are a variety of conventions to follow, but consistency is the most important thing.

_FnMinus1 and _FnMinus2 are only used in one method, so they can be made local to that method.

The API is a little odd:

fib.n = i;
fib.Calculate();
int result = fib.Value;

It would be more convenient if I could do this with one line, like int result = fib.Calculate(i), which would return the value.  Then it seems that n and Value are unnecessary.

Furthermore, right now there is nothing that keeps n and Value synchronized.  The class should maintain the invariant that Value is always the nth Fibanacci number.  You could do the work in the n assignment or mark Value as dirty when n changes.  Either way you essentially get rid of Calculate, so that's another approach.  I prefer getting rid of n and Value, I just mention this in case you think it makes sense to keep them.

Between Implementation 1 and Implementation 2, it's pretty much a wash.  1 has the benefit of only making one allocation.  Since the class is (going to be) stateless, it's perfectly reusable.  On the other hand 2 declares fib inside the loop, which minimizes its scope (which is good).


Python Automate the Boring Stuff Collatz exercise

Some quick thoughts:

Linting the code will make it more easily readable to Python developers (including yourself when you get used to it).
elif (number % 2 == 1) : could just be else: because a number which is not even must be odd.
return (newNumber) should be just return newNumber.
The code below #Input validation loop should be in a main function, called if __name__ == '__main__'. That way it's possible to import your function for reuse in other code.
Rather than returning just the next number in the sequence you probably want to return an infinite iterator so that the caller can get more numbers trivially:

class Collatz():
    def __init__(self, start):
        self.number = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.number in [0, 1]:
            raise StopIteration()
        if self.number % 2 == 0:
            self.number = int(self.number / 2)
        else:
            self.number *= 3
            self.number += 1
        return self.number

Use:

>>> print(list(Collatz(15)))
[46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]


Finding the item with the minimal value in a sequence

Redundant use of indexing
Since you only need value, not index, you could store current minimal value instead of its index. This would allow for for loop, like
for item in sequence:
    if item < current_minimum:
        current_minimum = item

You both ditch overhead for array access, for tracking the index and - most important - code looks cleaner. (although that's subjective)
No support for generators
Generators provide items one at a time, instead of wasting memory on all of them at once. Your code would force generation of all items before first of them is processed. This is not really good.
Well, if you don't use indexing then you don't need len and generators would work just fine, your if len(args) == 1: clause is good in this regard.
Confusing behaviour with single argument
However, special treatment for a lone argument is not obvious from signature, that's not really good. If one does not know about this behaviour, one can easily use stuff like min_element = minimal(*some_list) which would generally work but will do an unexpected thing if some_list had only one element.
Yes, it seems extremely useful, but also confusing. Maybe limiting to one argument only and expecting users to do stuff like minimal((1,2))? I'm really not sure. It seems useful enough that built-in min works like that, but generally speaking decisions like this should not be taken lightly.
Also, take a closer look at what min does - there's also an option of using a key function and providing default value.


You might have some bug in the algorithm.

"testdata"

struct A {};
struct B {};
struct C {};
struct D {};

using Types = typelist<A, B, C, D>;
using Permutations = typelist<
    typelist<A,B,C,D>,
    typelist<A,B,D,C>,
    typelist<A,C,B,D>,
    typelist<A,C,D,B>,
    typelist<A,D,B,C>,
    typelist<A,D,C,B>,
    typelist<B,A,D,C>,
    typelist<B,A,C,D>,
    typelist<B,C,D,A>,
    typelist<B,C,A,D>,
    typelist<B,D,C,A>,
    typelist<B,D,A,C>,
    typelist<C,A,B,D>,
    typelist<C,A,D,B>,
    typelist<C,B,A,D>,
    typelist<C,B,D,A>,
    typelist<C,D,A,B>,
    typelist<C,D,B,A>,
    typelist<D,A,C,B>,
    typelist<D,A,B,C>,
    typelist<D,B,C,A>,
    typelist<D,B,A,C>,
    typelist<D,C,B,A>,
    typelist<D,C,A,B>
>;
static_assert(std::is_same<permute_t<Types>, Permutations>{}, "!");

results in:

prog.cpp:90:1: error: static assertion failed: !
 static_assert(std::is_same<permute_t<Types>, Permutations>{}, "!");
 ^


First of all, there is no need to use iter_mut() on conferences, as you never change the original rankings. As we clone the teams later, we can simply use

let mut raw_teams: Vec<Vec<Vec<Team>>> = rankings
    .conferences
    .iter()
    .map(|c| c.divisions.iter().map(|d| d.teams.clone()).collect())
    .collect();

Now that we have a Vec<Vec<Vec<Team>>, we can call flatten:

let flattened_teams: Vec<Team> = raw_teams.into_iter().flatten().flatten().collect();

I used into_iter() as your original code left raw_teams empty.

However, we can skip raw_teams entirely if we use flat_map instead of map(…).flatten():

let flattened_teams: Vec<Team> = rankings
    .conferences
    .iter()
    .flat_map(|c| &c.divisions) // need to borrow due to iter()
    .flat_map(|d| &d.teams)     // need to borrow due to iter()
    .cloned()                   // clone the elements
    .collect();

If we don't want to borrow, we can of course just move everything into flattened_teams by simply removing cloned() and &:

let flattened_teams : Vec<Team> = rankings
    .conferences
    .into_iter()
    .flat_map(|c| c.divisions)
    .flat_map(|d| d.teams)
    .collect()

None of these functions use mut.


Jest / Enzyme test for a React component to calculate average data speed

There are two distinct parts in your test:

Testing the rendering of AvgSpeed component.
Testing the logic of getAverage() and extractSpeeds().

This separation between components and logic is good. I would suggest separating them even more by moving the getAverage() and extractSpeeds() functions to separate file, which you can then test completely independently from the component.

The component rendering test however is dependent on the logic. That's not good:

You're re-testing the logic through the component test, which is duplication.
When there's a change in logic, the component test will also break, resulting in more work maintaining the tests.

So your component test really is more of an integration test, not a pure unit test. There are basically two ways to improve on that:

Change the component. Instead of the component importing these functions and calling them, perhaps you could perform the calculation outside of the component and just pass in download and upload props.
Change the test. Instead of letting the component call actual getAverage() and extractSpeeds() you could replace them with mock implementations. Though, the less mocking you need, the better. So, you could consider combining the two functions into one, which will be easier to mock out.

Usually the first approach is better and requires no extra tooling. If you decide to go the mocking route, my personal choice is the rewire library, of which there exist various versions for various environments (e.g. for Babel).

Regarding specific tests

Avoid temporary variables when you can write the values inline. Instead of:

expect(extractSpeeds(inputObj, downloadIn)).toEqual(downloadOut);

prefer:

expect(extractSpeeds(inputObj, "download")).toEqual([22, 24]);

Avoid logic in tests. Logic is error-prone. While hard-coded values are a big no-no in normal code, in test code they're usually OK. Instead of:

input = [1, 2, 3];
input = input.map(n => (n += 1));

just hard-code it:

input = [2, 3, 4];

Try to write one assertion (expect) per it() block. This way you can give a more descriptive name for each scenario you want to test.

Don't simply repeat the same test multiple times. For example, you're testing the getAverage with [1,2,3], [2,3,4], [3,4,5] - it's essentially the same test: three sequential numbers. Try to come up with more fundamentally different scenarios:

different lengths of array.
positive/negative numbers, fractional numbers, zero.
array of similar numbers.

Think of the edge cases:

What if there is no data? (e.g. empty object or array)
What kind of input data would be problematic? (e.g. negative numbers)


Work with indices instead of elseif statements

You should write a function that identifies the index of this.textContent in the currencyData array. Why not try something like this:

function myIndexOf(o) {
    for (var i = 0; i < currencyData.length; i++) {
        if (currencyData[i].currency == o) {
            return i;
        }
    }
    return -1;
}

Taken from this Stackoverflow answer.

Then you can run:

currentIndex = myIndexOf(this.textContent)
getCurrency(currencyData[currentIndex].currency, currencyData[currentIndex].symbol);

And it's entirely extensible.

Avoid unnecessary HTML updates

Seems like you can reduce $span to only update the innerHTML of a span element rather than reinitializing your span element each time you append it to $('.js-input-amount-prepend'). This would slightly shorten getCurrency