Looks fine to me, you could potentially shave off some repetition, but it's not like it matters that much for a small script.
That said, I'd reuse the session, inline a few variables, fix the naming (constants should be uppercase) and use some standard library tools like os.path to make the script more error-proof.  The list return type could also be more concrete and mention that it's a list of strings for example.
Also, and that's a bit more important, I'd rather not have a script slurp in the whole HTTP response like that!  Who knows how big the files are, plus it's wasteful ... better to stream the response directly to disk!  Thankfully the APIs do exist, using .content.iter_any (or _chunked if you prefer to have a fixed chunk size) you can just iterate over each read data block and write them to the file like so:
import time
import os
import os.path
from bs4 import BeautifulSoup as bs
import aiohttp
import aiofiles
import asyncio
import urllib
import typing

STATISTICS_URL = 'https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics'
OUTPUT_FOLDER = 'C:/Users/<User>/OneDrive/Desktop/testing/'

async def fetch_download_links(session: aiohttp.ClientSession, url: str) -> typing.List[str]:
    r = await session.get(url, ssl=False)
    soup = bs(await r.text(), 'lxml')
    link = 'https://digital.nhs.uk' + soup.select_one('.cta__button')['href']

    r = await session.get(link, ssl=False)
    soup = bs(await r.text(), 'lxml')
    return [i['href'] for i in soup.select('.attachment a')]

async def place_file(session: aiohttp.ClientSession, source: str) -> None:
    r = await session.get(source, ssl=False)

    file_name = urllib.parse.unquote(source.split('/')[-1])
    async with aiofiles.open(os.path.join(OUTPUT_FOLDER, file_name), 'wb') as f:
        async for data in r.content.iter_any():
            await f.write(data)

async def main():
    async with aiohttp.ClientSession() as session:
        urls = await fetch_download_links(session, STATISTICS_URL)
        await asyncio.gather(*[place_file(session, url) for url in urls])

if __name__ == '__main__':
    t1 = time.perf_counter()
    print('process started...')
    asyncio.get_event_loop().run_until_complete(main())
    os.startfile(OUTPUT_FOLDER[:-1])
    t2 = time.perf_counter()
    print(f'Completed in {t2-t1} seconds.')


Formatting 3 integers (hours, mins, secs) to `00:00:00`?

The % formatting operator already supports 0-padding, just specify the width as 02. Also, you can pass a tuple to combine multiple numbers into the same string with a single format: "%02d:%02d:%02d" % (h, m, s).

In Python 3 the format string method is slightly preferred to the % operator, with Python 3.6 further allowing the format string to reference the variables directly. Using such formatted string literals or f-strings, the formatting would be expressed as: f"{h:02}:{m:02}:{s:02}".

As pointed out in the comments, if you're starting with datetime objects to begin with, you can use their own formatting functionality instead.


Class simulating a connection among two pins

I'm not sure how I feel about this.

public void OnCompleted()
{
    throw new NotImplementedException();
}

In my opinion, if you're going to implement a contract, you should fulfill the contract, even if that means doing nothing at all. There's little more frustrating than getting an object that you believe implements an interface only to find out that it doesn't really implement it. Oh no, this implementation throws an exception when I call that method. Now, my nice clean code that, previously, didn't care what concrete type it was passed has to type check it's args to make sure it's not an instance of this class you've created.

Ok. So I do know how I feel about it. I hate it. I really really hate it. I'd much rather that you fulfill the contract by truly not implementing it.

/// <summary>
/// Does nothing. Not implemented for reasons.
/// </summary>
public void OnCompleted() { }

Now my code doesn't have to type check for your class anymore. Even better, I know why you've not implemented this part of the contract and decided that this method should just do nothing at all when called.

Of course, if it's not going to do anything, then we can hide it from the public interface of the concrete type by explicitly implementing the interface.

/// <summary>
/// Does nothing. Not implemented for reasons.
/// </summary>
public void IObserver.OnCompleted() { }


For finding whether a puzzle state is solvable

You can use a fun fact from abstract algebra.  It's a group theory fact, to be more specific.  Read all about it here or here or, better yet, here.  I actually used this in my own sliding tile puzzle I created for the App Store in 2013.  But I used it to generate puzzles, not to verify solvability.

I see now where my original intended answer went wrong.  The math behind it requires the empty space be in the bottom right corner, and I missed that at first.  From the Wiki link:

  In particular if the empty square is in the lower right corner then the puzzle is solvable if and only if the permutation of the remaining pieces is even.

A permutation of numbers 1 through n is even if and only if it's obtained by performing an even number of swaps.  For example, the permutation 2 1 4 3 is an even permutation of 1 2 3 4 because it's obtained from two swaps: swapping 1 and 2, and swapping 3 and 4.  And the permutation 1 3 2 4 is not an even permutation (a so-called odd permutation) because it's obtained from one swap: swapping 2 and 3.  Note that the number of swaps is not unique for a given permutation, but the parity of the number of swaps is unique.

If you want to keep things as simple as possible then my recommendation to you is to use the following general process:

Start with a puzzle in the solved state.
Let m be a random positive even integer.
Swap m pairs of non-empty tiles (That is, leave the empty space where it is, in the bottom right corner).

Of course, you'll need some checks to make sure you don't swap the same pair several or even m times.  But this is by far the most efficient way to do this unless you consistently choose massively huge values of m.  This is what I did in my own app.

But anyway, if you want to stick with your original process of randomly generating a puzzle and seeing if it's solvable, then you can still use permutations to check solvability in O(n) time, where n = puzzle.length.

We already know the following:

  A puzzle is solvable if and only if the empty space is in the bottom right corner and the permutation is even.

Therefore for a randomly created puzzle we also need to figure out the Manhattan distance between the empty space and the bottom right corner.  This is equal to the number of rows the empty space is away from the last row plus the number of columns the empty space is away from the last column.  For simplicity I'll assume your board will always be square, and I think that's a reasonable assumption based on your original code.  Then with this Manhattan distance between where the empty square is and where it's supposed to be, a distance which I'll denote x, we have the following fact:

  A puzzle is solvable if and only the parity of the permutation equals the parity of x.

I won't rigorously prove this, but the basic idea is that every move you make will move the empty square and therefore can be thought of as a swap with the empty square.  And the empty square is an even Manhattan distance away (i.e., x is even) if and only if it takes an even number of swaps to get the empty square where it belongs.  Also, a composition of two permutations is even if and only if those two permutations have the same parity.

And, finally, here's the code:

public boolean isSolvable(int[] puzzle) {
    int [] myPuzzle;  // Copy puzzle because we'll be swapping elements.
    int [] indexArr;  // indexArr[0] is index of blank space in puzzle[].
                      // indexArr[1] is index of space #1 in puzzle[].
                      // indexArr[2] is index of space #2 in puzzle[], etc.
    int n = puzzle.length;
    int swapCount = 0;  // Number of swaps to get from shuffled state to solved state.
    int manDist = 0;  // Manhattan distance between shuffled empty space and bottom right corner.
    int gridWidth = (int) Math.sqrt(puzzle.length);
    int row, col;  // Row and column of the empty space in the shuffled puzzle.

    myPuzzle = new int[n];
    indexArr = new int[n];

    // Make a deep copy so we don't modify the original.
    // Also store indexes of the shuffled tiles.
    // This loop runs in O(n) time.
    for (int i = 0; i < n; i++) {
        myPuzzle[i] = puzzle[i];
        indexArr[puzzle[i]] = i;
    }

    // First get the Manhattan distance between where the empty space is and where it should be.
    row = indexArr[0] / gridWidth + 1;  // Row of empty space's shuffled position.  Add 1 to account for 0-based index.
    col = indexArr[0] % gridWidth + 1;  // Column of empty space's shuffled position.  Add 1 to account for 0-based index.
    manDist = 2*gridWidth - row - col;  // (gridWidth-row) + (gridWidth-col)

    // Count how many swaps we need to get to the solved state.
    // This loop runs in O(n) time.
    for (int i = 0; i < n; i++) {
        // Swap tile #i with whatever tile is in tile #i's correct position.
        // The current position for tile #i is indexArr[i].
        // The correct position for tile #i is (i+n-1) % n
        //   because the blank space #n is actually tile #0.
        // Thus we want to swap puzzle[indexArr[i]] with puzzle[(i+(n-1)) % n],
        //   but only if the swap is needed.
        // Note that we must also swap the corresponding stored indexes in
        //   indexArr so future loop iterations will work correctly.

        if (myPuzzle[indexArr[i]] != myPuzzle[(i+n-1) % n]) {  // If we need to swap
            // Swap the tiles, i.e., put tile #i in its proper place.
            swap(myPuzzle, indexArr[i], (i+n-1) % n);

            // Now swap their stored positions in indexArr.
            swap(indexArr, i, myPuzzle[indexArr[i]]);

            swapCount++;
        }
    }

    // Puzzle is solvable if and only if the permutation and manDist have the same parity.
    return (swapCount % 2 == manDist % 2);
}

private void swap(int[] arr, int a, int b) {
    arr[a] += arr[b];
    arr[b] = arr[a] - arr[b];
    arr[a] -= arr[b];
}

This runs in O(n) time overall.  I tested with a few samples and this agrees with your original implementation in all cases.


As an overarching rule, I never write scripts with the "stfu operator" (@). It looks like you plan to refine the session starting line, so I won't dwell.
You are calling time() 5 separate times in your function.  Because there is no benefit in recording their differences in terms of microseconds, I recommend that you call time() once, and cache the value in a variable/constant to be used in all processes in the custom function.
I tend to never use OR or AND in my php conditions (only in my SQL) as a matter of consistency.  This also prevents unintended hiccups regarding precedence.  Separately, I never use or die() in my scripts ...trying not to dwell.
Because you are generating a hash for non-cryptographic use, you may enjoy the advice/discussions about performance comparisons between different hash generators: Fastest hash for non-cryptographic uses?


Am I using Golang concurrency correctly to increase reliability?

It seems reasonable to start a goroutine for each input, but I'm not sure you need separate goroutines for parsing and sending.  After all, one is just waiting for the other to finish.  They might as well be the same goroutine.  Then you don't need either of the channels because they were just to let these two goroutines communicate.


Your code looks fine.

However, you are not showing us much to review, definitely come back when there is more to review.

Some minor comments:

Having your db connection config through ./config/db is good
You probably want to throw an exception if ( typeof cb !== "function" ) instead of silently ignoring that
The base/db code nests 4 levels of callback, you should look into queue management libraries for node.js


Leetcode #91 - Number of ways to decode a string

Memoization

Looking into memoization is a good idea - in this case it allows you to achieve \$O(n)\$ runtime performance instead of \$O(2^n)\$. One way to add memoization is to create a wrapper method that takes the same arguments as Decode. This method first looks up the given arguments in a dictionary, and if they're present, it can return the memoized result. If not, it will call Decode and store its result in the dictionary before returning it.

However, I would recommend removing NumDecodings and rewriting Decode so it only takes a single string parameter. That will simplify memoization and make it a little more efficient. For example, "412123" and "512123" both have the same suffix ("12123"), but because the 'sub-calls' ("412123", 1, 1) and ("512123", 1, 1) use different arguments (and thus different memoization keys) you won't benefit from memoization across those different inputs.

Other notes

Instead of passing the original input string and an offset and length, consider passing 'the rest of the string' instead. Decode can then call Decode(s.Substring(1)) if the leading digit is a valid unit, and Decode(s.Substring(2)) if the leading 2 digits are a valid unit.
There are various things in the current code that can be simplified:

if (i + len - 1 >= s.Length) to if (i + len > s.Length)
s.Substring(i, len)[0] == '0' to s[i] == '0'
else if (i + len - 1 == s.Length - 1 to else if (i + len == s.Length
jump1 = i + len - 1 + 1 to jump1 = i + len
jump2 = i + len - 1 + 2 to jump2 = i + len + 1

Moving s.Substring(i, len)[0] == '0' to an else if branch allows you to remove the sub < 27 && sub > 0 checks below.
Disabling code during development is normal, but it's a good idea to clean things up from time to time.
I would rename Decode to something more descriptive like ValidDecodingsCount - Decode implies that it actually decodes the given input, which is not the case. jump1 and jump2 aren't very descriptive names either, but it's a bit difficult to come up with better names. Maybe rest1Combinations and rest2Combinations?


Reducing code duplication for my C# math class

Depending on how many points you'll be dealing with, you could go one step further.  Since you're only using 2 points from the Vector3, it's fairly simple to cast the Vector3's into Vector2's.

public static float Area(List<Vector2> points)
{
    float a = 0;
    for (int i = 0; i < points.Count; i++)
    {
        var p1 = points[i];
        var p2 = points[(i + 1) % points.Count];

        a += p1.x * p2.y - p2.x * p1.y;
    }

    return a * 0.5f;
}

public static float Area(List<Vector3> points)
{

    return Area(points.Select(x => new Vector2(x.x,x.z)).ToList());
}

public static float Area(Vector3[] points)
{
    return Area(points.ToList());
}

public static float Area(Vector2[] points)
{
    return Area(points.ToList());
}

Upon further reflection the code reduction can be taken a step further by using IEnumerable<T>.  Now it becomes:

public static float Area(IEnumerable<Vector2> points)
{
    float a = 0;
    var first = points.First();
    var prev = first;
    foreach (var curr in points.Skip(1))
    {
        a += prev.x * curr.y - curr.x * prev.y;
        prev = curr;

    }
    a += prev.x * first.y - first.x * prev.y;
    return a * 0.5;
}

public static float Area(IEnumerable<Vector3> points)
{

    return Area(points.Select(x => new Vector2(x.x,x.z)));
}


Calling a Function to Calculate Multiple Coefficients

if the syntax for my pointers looks correct

The syntax for the pointers is correct in all the function parameters, however, the pointer syntax is incorrect or unnecessary in the two scanf statements. The two output variables passed into temperature(float *, float*) are already addresses of variables so in this case the proper code would be

    scanf("%f", ptrTc);
    scanf("%f", ptrTh);

You would only need & if this was in the main program and Tc and Th were being read directly.

    float Tc;
    scanf("%f", &Tc);

  if there's a more efficient way of writing my code

All four of the variables are related, it might be better to use a struct to contain them. That way if the program needed to be modified to loop through data it would be easier to build an array of all the values. Using a struct would also decrease the number of parameters for each function to one.

Error Checking
A best practice is to check all input data as it comes in and report any errors, especially for user input. Users can make errors such as entering characters rather than numbers. The temperature(float *, float*) function could return an integer the indicated success or failure.

Separate and Initialize in Variable Declarations
There are 2 things that can be improved in the following code:

    float Tc, //cold reservoir; user input
        Th, //hot reservoir; user input
        Rcp, //refrigeration cycle coefficient of performance
        Hcp; // Heat pump coefficient of performance

This code is hard to maintain because it is hard to add a variable to the list.

Not initializing variables can lead to hard to debug problems later, this is especially true of the C programming language because it does not automatically initialize variables to a zero or null value as some other languages do. Of the two problems this is actually the more serious one, the other might be considered style.

An possible example of an improved declaration is:

    float Tc = 0.0;  //cold reservoir; user input
    float Th = 0.0;  //hot reservoir; user input
    float Rcp = 0.0; //refrigeration cycle coefficient of performance
    float Hcp = 0.0; // Heat pump coefficient of performance

Spacing, Both Vertical and Horizontal
Within expressions is it common to put spaces between operators and operands, this makes the code more readable.

Vertical separation of one line between functions might make the code more readable as well.


Unfortunately my hard drive containing my savegames crashed yesterday, so I cannot look up my solution, but I can say that the things you consider ugly are because of the limitations of that old computer system. I am abusing nodes as temporary storage all the time and my solution pretty much looked the same (if I remember correctly). As the histograms show you are not that bad (especially on cycles).

We can optimize your solution in terms of # of instructions and maybe cycles as well, though. I am focussing on optimizing the existing algorithms, instead of creating a new program. I could not test my optimized solution, because I don't have Steam on this box, but they should work none-the-less:

Your temporary storage node can be simplified to:

MOV RIGHT RIGHT

This is a valid instruction and saves you one instruction.
I only save my ACC just before it would get overridden. This removes some duplicate code (namely at least one SAV in your counter) and simplifies control flow. My rewritten algorithm is one instruction less than yours:

L:
SAV          # Save counter
MOV LEFT ACC # Next item
JEZ EZ       # End of sequence
SWP          # Restore counter
ADD 1        # Increment
JMP L        # Loop
EZ:          # End of sequence
SWP          # Restore counter
MOV ACC DOWN # Output
SUB ACC      # Clear ACC

BAK is not needed in your summing node. You only need the value from your temporary storage node and the new value. Some reordering of instructions allows you to directly add the saved sum to the new value. I again saved the ACC in the very last moment:

L:
MOV ACC LEFT  # Save sum
MOV UP ACC    # Next item
JEZ EZ        # End of sequence
ADD LEFT      # Add sum
JMP L         # Loop
EZ:           # End of sequence
MOV LEFT DOWN # Output sum
SUB ACC       # Clear ACC

Getting rid of BAK saved us 3 instructions on this one!

Conclusion: Absolutely abuse the instruction set (e.g. my first bullet point) and possibilities of the game (storing values in the pipes) to achieve good scores in the different metrics. Don't try to optimize for everything, you have got three saves per level!


The number of permutations typically increases factorially. Since 3! = 6, 4! = 24, 5! = 120, 6! = 720, 7! = 5040, 8! = 40,320, 9! = 362,880, 10! = 3,628,800, 11! = 39,916,800, 12! = 479,001,600.

You can see that it get very large, very quickly. The output would be similarly huge.

The bottom line is, that past a certain point, there's just no way to keep the entire set in memory. A couple of numbers later, you wouldn't be able to afford a disk drive large enough to store it. A couple of number after that, there isn't enough paper on the planet to be able to print it. Somewhere in the 30's or 40's, there wouldn't be enough atoms in the entire universe to represent the results in an atomic scale computer.


Checking if a date was increased by date-constants

Here's how I would do it.  First make sure the reminderDate is after the activityDate.  Then check if the month, day, and time are the same.  If so you can do the year difference.  If not then you check if just the day and time are the same and do the month difference (along with the year difference times 12).  Otherwise subtract the dates and look at the TimeSpan.  If the minutes are not zero then return the TotalMinutes.  If the hours are not zero return the TotalHours.  If the number of days is divisible by 7 then do the weeks.  Otherwise just return the Days.

public static ReminderDTO ReverseAppointment(
    DateTime activityDate, DateTime reminderDate)
{
    if (reminderDate <= activityDate)
        throw new ArgumentException("reminder cannot be <= activity");

    if (reminderDate.Month == activityDate.Month
        && reminderDate.Day == activityDate.Day
        && reminderDate.TimeOfDay == activityDate.TimeOfDay)
    {
        return new ReminderDTO
                {
                    ReminderComboItem = ReminderComboItems.Years,
                    Frequency = reminderDate.Year - activityDate.Year
                };
    }

    if (reminderDate.Day == activityDate.Day
        && reminderDate.TimeOfDay == activityDate.TimeOfDay)
    {
        return new ReminderDTO
                {
                    ReminderComboItem = ReminderComboItems.Months,
                    Frequency =
                        (reminderDate.Month - activityDate.Month)
                        + (12 * (reminderDate.Year - activityDate.Year))
                };

    }

    var difference = reminderDate - activityDate;

    if (difference.Minutes != 0)
    {
        return new ReminderDTO
                {
                    ReminderComboItem = ReminderComboItems.Minutes,
                    Frequency = (int)difference.TotalMinutes
                };
    }
    if (difference.Hours != 0)
    {
        return new ReminderDTO
                {
                    ReminderComboItem = ReminderComboItems.Hours,
                    Frequency = (int)difference.TotalHours
                };
    }

    if (difference.Days % 7 == 0)
    {
        return new ReminderDTO
        {
            ReminderComboItem = ReminderComboItems.Weeks,
            Frequency = difference.Days / 7
        };
    }

    return new ReminderDTO
            {
                ReminderComboItem = ReminderComboItems.Days,
                Frequency = difference.Days
            };
}

Note that if the dates differ by less than a minute you'll end up with 0 days, but I'm assuming all you're dates will differ by at least one minute based on how they are generated.


Some things you could do :

remove these "add" and "multiply" functions
group operations when you read the file and when you split the input
use iterators on your splitted input
assign using the match statement
declare all your variables at once (it's debatable, but if you find it easier to read then go for it ! )
put info in your error message for the code (although it might not help much if you have a bug here, I admit)

It could look something like :

use std::fs;

fn run_program(memory: &mut Vec<i32>) -> i32 {
    for i in (0..memory.len()).step_by(4) {
        let (address_a, address_b, pos) = (memory[i + 1] as usize, memory[i + 2] as usize, memory[i + 3] as usize);
        memory[pos] = match memory[i] {
            1 => {
                memory[address_a] + memory[address_b]
            }
            2 => {
                memory[address_b] * memory[address_b]
            }
            99 => {
                return memory[0];
            }
            c => panic!("Invalid command value : {}", c)
        }
    }
    //return result of the program stored at address 0
    memory[0]
}

fn main() {
    let codes:Vec<i32> = fs::read_to_string("input.txt")
        .expect("Something went wrong reading the file")
        .split(',')
        .filter_map(|v| v.parse::<i32>().ok())
        .collect();

    let target_value = 19690720;

    for noun in 0..100 {
        for verb in 0..100 {
            let mut current_memory = codes.clone();
            //init noun and verb
            current_memory[1] = noun;
            current_memory[2] = verb;

            let current_result = run_program(&mut current_memory);

            if current_result == target_value {
                println!("Target value reached, noun: {}, verb {}", noun, verb);
                println!("Result = {}", 100*noun + verb);
                break;
            }
        }
    }
}

Note : the ".ok()" filter might be dangerous in your stream ! I had a problem for day 5 where I had used wrong types for the instructions, and when the parsing failed they were discarded : I was missing instructions in my "codes" Vec !
You might want to fail if this happens instead, it's way easier to debug...


How I can make file multiple of `segmentSize`

As far as I can understand (or better say: guess) what you mean, the optimum solution is a file size equal to the least common multiple of the given data size and the segment size: multiply your file N times:

\$ N = {segmentSize} / \operatorname{gcd}({dataSize}, \ {segmentSize}) \$

so you get a file of size

\$S = \operatorname{lcm}({dataSize}, \ {segmentSize})\$

which is \$M\$ full segments:

\$M = {dataSize} / \operatorname{gcd}({dataSize}, \ {segmentSize}) \$

For data size 48 million and segment size 12 Meg the greatest common divisor is 3,072 = 3*1024, so their least common multiple is:
\$196,608,000,000 = 2^{12} \times datasize = 5^6 \times segmentsize.\$


Script for automating regression testing

while : is a standard idiom for "loop forever" in bash. The colon (:) is a synonym for true.
Prefer $(command) to `command` ("backticks"). The former allows you to nest; the latter does not.
Though in your case, you don't need the backticks at all. These are for capturing the output of the command, which you don't use anywhere.
It isn't clear why you have the read SUBJECT inside each case -- you throw away the value in the very next statement.
Don't do this: lessc ccap-$BIO.less > ccap-$BIO.css. (It's a classic mistake in shell scripting; everyone's been bit by it.) This will nuke the file -- it will be truncated by the shell, overwriting the contents before lessc has the chance to read it.

Aside from your code: if your goal is to regenerate the output files whenever one of the input files has changed, you should consider learning make. With a 10-20 line makefile, you can automatically regenerate whichever of the output files need updating whenever one of the input files change.


Single function to read one, read all, or set

Here's one way to do it

public function temp($key = null , $value = null) {
    $args = func_get_args();
    if( count($args) === 2 ) {
        $this->temp[$key] = $value;
    } elseif( count($args) === 1 ) {
        return @$this->temp[$key];
    } else {
        return $this->temp;
    }
}

func_get_args() will return an array of the arguments that were actually passed - i.e. excluding default values. So if no arguments were passed, return the array; if there's 1 argument (the key), return the corresponding value; and if there are 2 arguments, set the key/value pair.

I'm using the warning-suppression @ instead of explicitly checking isset(). Again, the end result is the same; if you check with isset() and don't (explicitly) return anything for missing keys, the function still returns NULL. If you simply return $this->temp[$key]with no checking, but suppress the "undefined index" warning that might occur, you also get NULL.

I've also skipped the unset() call, since calling $obj->tmp("key", null) does pretty much the same thing. If you request a value that hasn't been set, you get NULL. If you set that value to NULL, you get NULL. If you were to unset the value, you'd also get NULL.
But if you want to keep the unset, you can just check $value === null in the first branch:

if( count($args) === 2 ) {
    if( $value === null ) {
        unset($this->temp[$key]);
    } else {
        $this->temp[$key] = $value;
    }
} // ...

If you skip the unset() part, it'll obviously keep the array keys around, so you won't know for sure if a key whose value is NULL was "deleted", or if it was explicitly set to NULL on purpose.
On the other hand, if you unset() when the passed value is NULL, you won't be able to set a value to NULL on purpose.

The simplest solution is to not use unset in the temp() function, but instead add an extra unset_temp_value($key) function that does the unset. Then you can use that to explicitly remove all traces of a key/value pair, while still being able to store NULLs "on purpose" using temp($key, null).

As mseancole points out below, a switch statement could be used too

public function temp($key = null, $value = null) {
  $args = func_get_args();
  switch( count($args) ) {
    case 2:
      return $this->temp[$key] = $value;
    case 1:
      return @$this->temp[$key];
    default:
      return $this->temp;
  }
}

Only difference is that this returns the value that's set in the first case (just because it's more compact then breaking)

And just for fun, here's the same thing again in Unreadable Mode™

public function temp($key = null, $value = null) {
  $args = count(func_get_args());
  return ($args==2?($this->temp[$key]=$value):($args==1?@$this->temp[$key]:$this->tmp));
}


What are the chances that more than one of your if statements would be true for each row?  It looks like you may risk overwriting some of your data if that is the case.

Dim ws As Worksheet
Dim wb2 As Workbook
Set wb = Application.Workbooks("Total Database Update_WORKING.xlsm")
Set ws = wb.Worksheets("Results")

Using variant your array will be able to size to whatever range you give it, but it will be 1 based.

Dim rng as Variant
Set rng = wb.worksheetS("Results").Range("B2:Your last column/row goes here")
Set wb2 = Application.Workbooks.Open("C:\Import Update.xlsx")
    i = 2
    ii = 2
    iii = 2
    iiii = 2
    iiiii = 2
    iiiiii = 2
    iiiiii = 2
    k = 2
    wb2.Activate
    dim row as long
    dim col as long
    For row = 1 to UBound(rng, 1)
        If rng(row, 4) = "No Match" Then
            wb2.Worksheets("AD UPDATE").Cells(i, 1) = rng(row, 1)
            wb2.Worksheets("AD UPDATE").Cells(i, 2) = rng(row, 2)
            i = i + 1
        End If
        k = k + 1
    Next Row

    wb2.Save
    Sleep (1000)
    wb2.Close SaveChanges:=True
    wb.Activate
End Sub


I like the idea.

First off, it appears that the get_instance() method isn't thread-safe:

std::shared_ptr<smart_singleton> smart_singleton::get_instance()
{
    if (auto existing_instance = weak_instance.lock()) {
        return existing_instance;
    } else {
        std::shared_ptr<smart_singleton> tmp_shared(new smart_singleton());
        weak_instance = tmp_shared;
        return tmp_shared;
    }
}

It's fine for it to not be thread-safe, but in that case, it is very important for the documentation to make it clear. If you are going that route, however, it might be worth separating the get_instance from creation like so:

std::shared_ptr<smart_singleton> smart_singleton::create_instance()
{
    if (weak_instance.lock()) {
        throw already_instantiated_error{}; // something better
    }
    std::shared_ptr<smart_singleton> tmp_shared(new smart_singleton());
    weak_instance = tmp_shared;
    return tmp_shared;
}

std::shared_ptr<smart_singleton> smart_singleton::get_instance()
{
    return weak_instance.lock();
}

Then you can note in the documentation that get_instance() returns a nullptr if there is no instance present; in a "global" scope (like main), they should call auto keep_alive = smart_singleton::create_instance();.

smart_singleton.h needs header-guards, and it should include <memory>:

#ifndef SMART_SINGLETON_H_
#define SMART_SINGLETON_H_

#include <memory>

...

#endif

To me, the main problem with this design is that it is so easy to use wrong. Any class caching a static copy of the singleton will make the unit tests fail. The unit tests have to go blindly in and assume that there are no offending constructs anywhere.

It might be a better idea to just have a smart_singleton::reset() which resets all the data stored in the singleton that the unit tests can call in the tear-down method.

If I was doing this, I'd actually make this a CRTP class so that it becomes very easy to create smart_singletons:

template<class T>
class smart_singleton
{
public:
    static std::shared_ptr<T> get_instance()
    {
        if (auto existing_instance = weak_instance.lock()) {
            return existing_instance;
        } else {
            std::shared_ptr<T> tmp_shared(new T());
            weak_instance = tmp_shared;
            return tmp_shared;
        }
    }
protected:
    smart_singleton() {}
private:
    smart_singleton(const smart_singleton<T>&) = delete;
    smart_singleton operator=(const smart_singleton<T>&) = delete;
    smart_singleton(smart_singleton<T>&&) = default;
    smart_singleton& operator=(smart_singleton<T>&&) = default;

    static std::weak_ptr<T> weak_instance;
};

template<class T>
std::weak_ptr<T> smart_singleton<T>::weak_instance;

Now to make a class a singleton, this is all I'd have to do:

class my_singleton : public smart_singleton<my_singleton>
{
    friend class smart_singleton<my_singleton>; // so that the smart-singleton can access the private constructor of this class
public:
    ...
private:
    my_singleton();
};


Review my "delayed for-loop" in JavaScript

My experience with Javascript isn't quite as developed as it is for other languages, but here's what I have to say about the code.

Why use setInterval() and clearInterval()?  You'd use those methods if you wanted to call a function repeatedly.  Since all you do is set it and immediately clear it, there's no point in really using it.  Better to use setTimeout() instead.

I'd consider rearranging your parameters so the delay was last.  That way you can make the delay optional, possibly provide a default delay instead.  Also consider making complatedCallback optional too.  It could be possible that you don't need the callback so you're forcing yourself to have to provide one.

I don't think you'd want to put a delay of the first invocation on the first item.  So probably should remove that initial timeout and just call the executor() directly.

DelayedLoop.forEach = function(collection, callback, completedCallback, delay) {
    var index = 0;

    var executor = function() {
        // Executes the callback, and gets the returned value to indicate what the next delay will be.
        var newInterval = callback(collection[index++]);

        // If they returned false, quit looping.
        if (typeof(newInterval) == "boolean" && newInterval == false) {
            return;
        }

        // If nothing / non-number is provided, re-use initial delay.
        if (typeof(newInterval) != "number") {
            newInterval = delay;
        } else if (newInterval < 0) { // If a negative number is returned, quit looping.
            return;
        }

        // If there are more elements to iterate, re-set delayed loop. Otherwise, call the "completed" callback.
        if (index < collection.length) {
            setTimeout(executor, newInterval);
        } else if (typeof(completedCallback) == "function") {
            completedCallback();
        }
    };

    // Initial loop setup.
    executor();
};

Otherwise I don't see anything glaringly wrong with the code.


Find the longest sequential same character array

The code has  a bug:

q q q u u u u u u
3
qqq

It should be

6
uuuuuu


"`panic!`ing" would normally be written as "panicking". Strangely, it doesn't appear your code actually... panics though? Seems your docs are misleading or outdated.
I dislike the common repetition in documentation for an X that starts with an equivalent of "The X is". Try removing those and improving the information density of the docs. We can already see it's an X from the doc tool itself.
Since the crate is so narrowly focused, I'd recommend moving at least one (if not all) the examples from the method to the crate level. This allows users to immediately see what it does and how to use it.
There's no reason to use self:: in the custom Result.
There's never a time where you'd implement this trait for anything but an iterator, so your trait should require Iterator as a supertrait. This has the benefit of unifying the Item types.
The note about "many iterators return references to the elements", seems out-of-place; that's just how iterators work. If someone doesn't understand that, it seems like they should re-read The Rust Programming Language. For similar reasons, I wouldn't explain how to use a trait or how to add dependencies to the Cargo.toml in my crate docs.
Avoid referencing your crate name in the doc prose. A user can choose to import it with whatever name they like.
Consider a nested match in the iterator implementation.
The majority of your code appears to be dealing with the error type. Perhaps a crate like quick-error would help tip the balance back towards the interesting code.
It's strange to have Display and Debug be the same value. Recall that Debug is for programmers; we'd expect to see the variant name. Display is for humans that see the error.
I'd delegate your Display implementation to Error::description as adding the names of the variants doesn't help the humans reading it.
I'm not a fan of multi-line expressions that aren't blocks in a match (like your write! or if). Would promote them to blocks.

//! Provides the `Single` trait for extracting the element from a
//! single-element iterator.

use std::{fmt, error, result};

type Result<T> = result::Result<T, Error>;

/// Extract the element from a single-element iterator.
pub trait Single: Iterator {
    /// Get the single element from a single-element iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// # use single::{ self, Single };
    /// # use std::iter;
    /// assert_eq!(iter::empty::<i32>().single(), Err(single::Error::NoElements));
    /// assert_eq!(iter::once(0).single(), Ok(0));
    /// assert_eq!(iter::repeat(0).single(), Err(single::Error::MultipleElements));
    /// ```
    fn single(self) -> Result<Self::Item>;
}

/// An error in the execution of [`Single::single`](trait.Single.html#tymethod.single).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// Asked empty iterator for single element.
    NoElements,
    /// Asked iterator with multiple elements for single element.
    MultipleElements,
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::NoElements => {
                write!(
                    f, "SingleError::NoElements: {}",
                    error::Error::description(self),
                )
            }
            Error::MultipleElements => {
                write!(
                    f, "SingleError::MultipleElements: {}",
                    error::Error::description(self),
                )
            }
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::NoElements =>
                "Asked empty iterator for single element",
            Error::MultipleElements =>
                "Asked iterator with multiple elements for single element",
        }
    }
    fn cause(&self) -> Option<&error::Error> { None }
}

impl<I> Single for I where I: Iterator {
    fn single(mut self) -> Result<Self::Item> {
        match self.next() {
            None => Err(Error::NoElements),
            Some(element) => {
                match self.next() {
                    None => Ok(element),
                    Some(_) => Err(Error::MultipleElements),
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::iter;
    use super::Single;

    #[test]
    #[should_panic(expected = "Asked empty iterator for single element")]
    fn panic_empty() { let _: i32 = iter::empty().single().unwrap(); }

    #[test]
    #[should_panic(expected = "Asked iterator with multiple elements for single element")]
    fn panic_multiple() { let _ = iter::repeat(0).single().unwrap(); }
}


Spring Data Redis - mapping object relationships?

There's nothing really wrong with your modelling approach. If you feel confident with the modelling you are good to go.

Data modelling in Redis depends on the functional and non-function requirements you need to meet. In Redis and your case this boils down to whether read performance is more important than write performance, and whether performance is an issue at all.

In my opinion (and after having developed quite a few commercial-grade products based on Redis), Redis has not been made with object relationships in mind. At its core it is just a very fast, efficient and lightweight key-value based database, i.e. you lookup a value by its (complex) key. That's it. Simple, plain and wonderful.

With this said, I would strongly recommend you to keep data models as simple as possible, when working with Redis. In classic database scheme design your are encouraged to perform database normalizations. However, Redis is not a RDMBS and thus is used most efficiently, when object relations are kept at a minimum (or even better avoided altogether, if possible).

The @Reference annotation actually is just a convenience to developers, taking care of automatically loading referenced objects from Redis database. On a side note, please keep in mind that referenced objects need to be updated/saved separately from the referencing object (related). Resolution of references in Spring Data Redis just mean additional queries under the hood and thus mean less read performance.

For maximum read performance, I would suggest the following changes to your model. Please note that this not necessarily the best model for your purpose, as many constraints of your project remain in the dark. Just consider it as an alternative to your "classic" model you may want to think about.

@RedisHash("messages")
public class Message {
    @Id String messageId;
    @Indexed String threadId;
    @Reference User user;
    String message;
    Date date;
    List<Score> userScores;
}

@RedisHash("users")
public class User {
    @Id String userId;
    String grade;
    List<Score> scores;
}

public class Score {
    String scoreId
    String messageId;
    Long score;
    User userId;
}

This approach basically eliminates the object relationships between Message and Score and User and Score by embedding Score information into the Message and User hash objects as standalone data. So you gain substantial read performance at the cost of data redundancy.

When querying a message (e.g. for message rendering) this means Redis Data just needs one lookup to fetch the full data from database (because message scores are already part of the stored value). The same is valid for querying a user for charting his/her scores. However, the drawback with this approach is, that you need to write/update the Score twice whenever a new score is added to a message by a user: once for the update to the user object and once for the update to the message object. However, using @Reference you still had to write the score object once, then write the updated references to User and Message, respectively.

Another (and probably more important) drawback is the increased memory usage due to the data duplication in User and Message objects. As Redis holds all its data in RAM at the time of this writing (albeit in a very efficient manner), this can become an issue if you deal with a huge amount of users and messages.

The proposed model should work particularly well in a strongly asymmetric producer-consumer model, where you have a lot more consumers (people just reading messages) than producers (users contributing messages and scores to messages). YMMV depending on the actual project style and setup.


What is the best option to replace a loop?

according to the query, it seems that the row count is either 0 or 1. so the loop would either have no iterations (the else part) or have exactly one iteration.
in terms of performance, I think that any improvement here is not dramatic.
however, in terms of choosing the right coding tools for the job, it seems that a loop is not the right tool.
maybe the following would be better:
@app.route("/")
@login_required
def index():
    """Queries the user's First Name to display in the title"""
    names = db.execute("""
        SELECT first_name
        FROM users
        WHERE id=:user_id
        """,
        user_id = session["user_id"]
    )
    first_name = names[0]["first_name"] if names else None
    return render_template("index.html", first_name = first_name)

and then:

  {% if first_name %}

{{ first_name }}'s Bookshelf

  {% else %}

Your Bookshelf

  {% endif %}

note: I didn't test the code.


A few quick comments:

Indeed, your solution doesn’t require \$N\$ to be odd. You’ve solved the slightly more general problem of finding a lonely integer in an array where every other element occurs at least twice, but could occur more often than that.

Likewise, the restriction that \$N \leq 100\$ isn’t used, but I can’t think of how that could be used in a solution.
I don’t know why you’ve defined a histogram() function, when you could swap it out for Counter(). That will make your code a little easier to read, because when I read Counter(), I immediately know what it does; if I see histogram() then I have to check I’ve understood the definition.
When you iterate over the histogram, you should use .iteritems() instead of .items(); in Python 2.7 the latter is slower and more memory-expensive.
You don’t need an explicit return None; Python will automatically return None if it drops out the end of a function.
Rather than iterating over the tuples in Counter(array).items() and picking out the element/frequency by numeric index, it would be better to use tuple unpacking in the for loop:

for elem, frequency in histogram(ary).items():
    if frequency == 1:
        return elem

You could also just use the most_common() method on Counter(), and take the last element of that – but at that point you’re barely doing any work, so that might not be in the spirit of the problem.


As far as BowlingGameScore goes, LGTM. I have no remarks. (And usually I have lots.)

In the tests, after each void (e.g. before game_no_pins_get_hit),
it's a bit odd to have a newline.

Also, a static import to turn Assertions.assertEquals into
a concise assertEquals would be convenient.


Reviewing the code as it is, rather than the problem with the statistical distribution.

Indentation

Your indentation is off and thus makes the code hard to read. Everything inside the method should be indented. Also it seems like some of the indentations are differently deep. Indentations in Java are usually 4 spaces.

Access modifiers

Your method does not have an access modifier (at least not explicitly), so I assume you forgot to add one. Access modifiers are important to control from where in the code the method (or class or member etc.) can be acccessed. Since your method does not have one, it implicitly has the default modifier, which is package-private. This might be correct, but if you just forgot it, use private if the method is only called within the same class.

Naming

Your variable names are unclear. In the context of float newgr = growth_rate; one might guess that newgr may mean something like "new growth rate", but without context it is completely unclear what it means. Use longer and more explicity names.

Also the names on the right part of the assignment are unconventional, because in Java you usually want to use camelCase for variables and methods, and UpperCamelCase aka PascalCase for classes and interfaces.

Your variable declarations should probably be something like this:

float newGrowthRate = growthRate;
float newMaxSpeed = maxSpeed;
int newstarveFrames = starveFrames;
int newLifeSpan = lifeSpan;

The same applies to some other variable names further down your code.

Your percentage variable is not really a percentage, because it can have values between 0 and 1. Percentages are values between 0 and 100, so you could change the scaling and use a random calue between 0 and 100, or simply rename the variable to something like factor or scaling. If you don't like any of those names and can't come up with a better one, change it to normalizedPercentage.

Style

In addition to the indentation, you are using newlines and whitespace in an unusual way.

For example

while(stats.size() > 1){

should be written like

while (stats.size() > 1) {

This makes the code more readible and consistent. Also around operators there should be spaces, like percentage * maxspeed_delta instead of percentage*maxspeed_delta.

Switch-Case

Using the switch-syntax you can make your code more readible where you are using many if-else blocks with integer comparison conditions.

So this

if(roll_stat == 0){           //gr
    newgr -= percentage*growth_rate_delta;
    if(newgr <= minimum_growth_rate){
        newgr = minimum_growth_rate;
    }
}
else if(roll_stat == 1){      //ms
    newms -= percentage*maxspeed_delta;
    if (newms <= minimum_maxspeed) {
        newms = minimum_maxspeed;
    }
}

can become this

switch (roll_stat) {
    case 0:
        newgr -= percentage * growth_rate_delta;
        if(newgr <= minimum_growth_rate){
            newgr = minimum_growth_rate;
        }
        break;
    case 1:
        newms -= percentage * maxspeed_delta;
        if (newms <= minimum_maxspeed) {
            newms = minimum_maxspeed;
        }
        break;
}

Don't forget the break after every case. If you have an else at the end (instead of an else if) use the default: case.

Comments

//get the value of a random element in the arraylist
roll_stat = stats.get(round(random(0, stats.size()-1)));

This comment is obsolete, because it just says what the code in the next line says anyway. Instead try to write self-documenting code, for example by selecting the random index first and saving it in a variable, so that the variable's name tells you what it is. Also you can directly get a random integer value, so you don't have to round. Then you get

Random random = new Random();
// nextInt(n) takes the upperbound exclusively, thus not stats.size() - 1
int randomIndex = random.nextInt(stats.size());
randomStat = stats.get(randomIndex);

Comments should tell why something is done, not what is done. What is done should be told by the code.

You are using //--------------LOSSES-------------// and //--------------GAINS-------------// to separate logical parts of your code. It is better to move these parts into methods and have the methods name explain what is done.

Removing items from ArrayList<Integer>

In a comment you ask whether you do this correctly. If I understand your intent correctly, then you are not doing it right, and it only makes no difference in your case because your items' values are the same as their indexes.

It is important to note that int and Integer are not the same thing. They are two different types, Integer being a wrapper for the primitive int. In some cases the JVM automatically "boxes" these ints into Integer objects or "unboxes" them the other way around. Since an ArrayList<Integer> contains Integer objects, when doing stats.remove(Integer.valueOf(roll_stat)); the ArrayList will search for the contained object if it exists in the list, and stats.remove(roll_stat); will remove the item at the index roll_stat. Since you randomly select an item by calculating a random index, you might as well save the index in a variable (see my example above where I do it for better readability anyway) and then remove by index.

Initializing your ArrayList

This seems a bit verbose:

ArrayList<Integer> stats = new ArrayList<Integer>();
stats.add(0);
stats.add(1);
stats.add(2);
stats.add(3);

Instead you can do this:

ArrayList<Integer> stats = new ArrayList<>(Arrays.asList(0, 1, 2, 3));


+1, good question.

The Prolog convention is to use underscores for readability. Why? because_it_is_easy_to_read_even_long_names_with_underscores, butItIsExtremelyHardToReadEvenShorterNamesWithMixedCaps!

A good naming convention is to use one noun per argument, declaratively describing what the argument stands for.

In SWI-Prolog, check out library(pio): The pure way to do what you want is to use a DCG to describe a list, and then to use phrase_from_file/2 to apply the DCG to a file.

The advantage is clear: You can then readily test your predicates on the toplevel alone, without even requiring a file, just by stating the input as a regular Prolog term.

This helps a lot also when writing test cases.

EDIT: I give you one example how DCGs can help you here. It is not yet completely pure, because this DCG contains output itself. However, it is much simpler than your code, and you can test this predicate without even needing a file, and then transparently apply the same code to a file too:

:- use_module(library(pio)).
:- set_prolog_flag(double_quotes, codes).

cat --> [].
cat --> [C], { put_char(C) }, cat.

This DCG describes a list of character codes, and outputs each code.

Sample use:

?- phrase(cat, "test").
test
true.

Now, with phrase_from_file/2 from Ulrich Neumerkel's library(pio), we can transparently apply the same DCG to a file too:

?- once(phrase_from_file(cat, 'cat.pl')).

With output:

:- use_module(library(pio)).
:- set_prolog_flag(double_quotes, codes).

cat --> [].
cat --> [C], { put_char(C) }, cat.

i.e., the same program as above, which I had saved it cat.pl.

I am using once/1 to commit to the first solution found (there is no further solution, but a choice-point left).


Complexity analysis

  the solution seems to be O(n^2) since I first traverse the entire list to get the size and then traverse it again to do the actual reversal.

That's not \$\mathcal{O}(n^2)\$.  That's \$\mathcal{O}(n)\$, because \$n + n\$ is still \$\mathcal{O}(n)\$.  It would be quadratic time if you traversed the entire list \$n\$ times because \$n \cdot n\$ is \$\mathcal{O}(n^2)\$.  But you only do so twice.  For complexity analysis, twice is no different from once.  We only care about things that vary with the input size.

If you said this to them, this is a potential interview fail.

Using for loops for iteration

public static int size(ListNode node) {
    ListNode current = node;
    int count = 0;
    while(current != null) {
        count++;
        current = current.getNext();
    }
    return count;
}

It doesn't make any functional difference, but consider

public static int size(ListNode node) {
    int count = 0;
    for (ListNode current = node; current != null; current = current.getNext()) {
        count++;
    }

    return count;
}

Now we can easily see that for every node in the list, we want to increment count.  It even gets the scope right.  The count can be seen outside the loop, but current can't.  We don't need it after the loop, and it is gone.  We do need count, and it is still there to be returned.

This puts all the loop definition in one line.  The original spreads it throughout the method.

I also added a bit of extra whitespace for readability.

Know your exit conditions

    if(node == null) return;
    int size = size(node);
    if(size == 1) return;

You can write this more briefly as

int size = size(node);
if (size < 2 * 2) {
    return;
}

You don't need to check if node is null, as the size check will handle that for you.  You also don't to check lists of size 2 or 3.  Such lists won't be any different, as the second half of the list is only one element long.

I prefer to always use the block form of control structures rather than the statement form.  Some prefer the way that you did it.  This is something that could potentially fail an interview, so try to determine their attitude before picking a style.

I would put a blank line after this section to separate it from the rest of the method.

Don't duplicate work

    ListNode middleOfList = null;
    ListNode currentNode = node;
    //traverse the first half of the list
    while(i < size/2) {
        middleOfList = currentNode;
        currentNode = currentNode.getNext();
        i++;
    }

Consider

    ListNode middle = null;
    for (size /= 2; size > 0; size--) {
        middle = middle.getNext();
    }

    ListNode current = middle.getNext();

Now, instead of updating two variables each time, we update one.  Then we set the second once, after the loop is done.

We get rid of i altogether.  But at the cost of a misleading value for size.  Perhaps replace size with i or remaining or similar.

A reverse method

    middleOfList.setNext(previous);

Consider what you would have to do to replace that with

    middle.setNext(reverse(middle.getNext()));

Then you'd have another general purpose algorithm like size that could be reused elsewhere.

Evaluating

I would consider this a reasonable solution.  Perhaps you could make slight performance tweaks, but you generally shouldn't need to do so.  You have to traverse the list at least once, so it's going to be linear time.  Your version is still linear time.  Your size method is well contained and reusable.

You are not thread safe (consider what happens if another thread cuts the list by two thirds after you get the size but before you find the middle), but it's not evident that you need to be.

Other than that and the two potential failing issues, my only other comment is that I'd prefer more paragraphing in the code.  Separate the method into code blocks with blank lines between.

I personally would put a space between control structures like if and while and the following open parenthesis.  But in interviewing, try to determine their style and match it with your code.  If they do it the way that I do, then match them.  If they do it the way that you do, then just do it how you normally would.


How many conditions in an "if clause" is acceptable?

You could put all of your variable names into an array and loop over it, something like this (pseudocode):

var names = { 'First', 'Second', 'Third' };

for (var name in names) {
    if (Request[names[name]] == null) {
        throw new ApplicationException('Error');
    }
}

// No errors if we reach here


Before going into any coding I would give you a quick hack for the diamond problem . Instead of making so many for looping and columns and keeping track of variables the diamond problem is a variant of a maths problem.
HERE

1*1 = 1
11*11 = 121
111*111 = 12321
1111*1111 = 1234321

and so on. SO if you use this formula you just need one for loop for spaces and one for increasing your num*10 +1 where num is 1 and then squaring it and you will get the diamond pattern. If you want I can code it for you but since you asked for an easier method this is the best you can get.


This is a great concept to work with. Creating an enum of comparators is a clever way to make it easy to manage the sort order of file collections.

The name concerns me. I realize that Sort is convenient, but enums are normally given a "noun" name. "Sort" is a verb - something you do, not a noun which is a "thing". I would call it Sorter, or even FileSorter. Adding File to it makes code more readable.

Additionally, enum members are normally in all-uppercase and under-score separated.... so, BY_FILE_NAME instead of ByFileName.

Adding the "File" to be FileSorter you no longer need to have File as part of the enum names, so you will have: FileSorter.BY_NAME.

I believe you have truncated some code from the ByFileName enum. It does not compile without the override of the compare method. I'll just claim it is because of how you summarized things for this question.

Now, about the functional aspects. I agree, the override is a mess, and can be sorted out quite easily. First up, what you want to do is pass a comparator in as the constructor for the enum, and then use that comparator as a tool in the compare function.... like this:

private final Comparator<File> comp;

private FileSorter(Comparator<File> comp) {
    this.comp = comp;
}

@Override
public int compare(File o1, File o2) {
    return comp.compare(o1, o2);
}

That makes the actual enum guts really simple, not it's just a case of setting up the enum members.... the ones that are easy are things like size, and name sorts:

BY_NAME(Comparator.comparing(File::getName))

and

BY_SIZE(Comparator.comparingLong(File::length))

Taking your base code though, for sorting by type, you had:

return Comparator.comparing((File f) -> {
    String probeContentType = null;
    try {
        probeContentType = Files.probeContentType(f.toPath());
        if (probeContentType ==null) {
            probeContentType = "probeContentTypeIsNull";
        }
    } catch (IOException e) {
    }
    return probeContentType;
});

That code is 'ugly' because it is hard to follow the logic through, the empty catch block is a mess, and the blocked lambda (File f) -> {....} type expressions make me want to create a function for them, so I do....

I created the function:

private static final String extractType(File f) {
    try {
        String probeContentType = Files.probeContentType(f.toPath());
        return probeContentType == null ? "probeContentTypeIsNull" : probeContentType;
    } catch (IOException e) {
        return null;
    }
}

Note how I have a correctly-scoped probeContentType variable, and I use a return in both the successful, and catch-side of the try/catch block. The logic is now very visible. That function extracts just the file's type. How is it used, though?

BY_TYPE(Comparator.comparing(FileSorter::extractType)),

Putting this all together, I have the following code which I believe is quite simple, and readable:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Comparator;

public enum FileSorter implements Comparator<File> {

    BY_TYPE(Comparator.comparing(FileSorter::extractType)),
    BY_NAME(Comparator.comparing(File::getName)),
    BY_SIZE(Comparator.comparingLong(File::length));

    private static final String extractType(File f) {
        try {
            String probeContentType = Files.probeContentType(f.toPath());
            return probeContentType == null ? "probeContentTypeIsNull" : probeContentType;
        } catch (IOException e) {
            return null;
        }
    }

    private final Comparator<File> comp;

    private FileSorter(Comparator<File> comp) {
        this.comp = comp;
    }

    @Override
    public int compare(File o1, File o2) {
        return comp.compare(o1, o2);
    }
}


Greasemonkey script to refresh page until target string is found

Right now, your code grabs everything HTML related in the document. However, from what I can tell, you only want to search the text on a webpage.

That being said, this code currently could potentially pick up a string that is embedded in the HTML code, but is not actually visible to the user on the screen.

To only grab the text, you can use either the innerText property of the textContent of the body:

var text = document.body.innerText || document.body.textContent;

Now, the text variable will contain all the text in the document, excluding the actual HTML code.

Now, I may be mistaken, but after some testing, it seems that count does not exist after the page resets. Therefore, you can just remove this variable and all interactions with it.

window.setTimeout(function(){window.location.reload() ;},300000) ;

Where did that 300000 come from? You should declare a constant at the top of your code.

return;

This is unnecessary and is confusing. This should be removed.

The console.logs seem to me that they were used for debugging, since they don't seem to be showing any important message to the user, and why would the user be looking in the console anyway?. These can be removed.

Now, this is what your code looks like:

// ==UserScript==
// @name           Magma Time Finder
// @namespace      Will.GG
// @description    Refreshes the page until target string is found
// @include        *www.website.com
// @include http://www.website.com
// @grant metadata
// ==/UserScript==

var FREQUENCY = 300000;

var text = document.body.innerHTMl || document.body.textContent;
var yourTime = new Date();

if (text.indexOf("Text to find here") < 0) {
    alert(yourTime);
} else {
    var lastCheck = document.createElement("div");
    lastCheck.innerHTML = "Last Check: " + yourTime.toString();
    var parent = document.getElementsByClassName("content")[0];
    parent.insertBefore(lastCheck, parent.children[1]);

    window.setTimeout(window.location.reload, FREQUENCY);
}


add paramater check

else if (index<0 || index>=size){
    throw new NullPointerException();
}

This isn't necessary, because get already catches these cases. You do the same in remove, where you check for isEmpty, which you already checked via the call to get.

You should also try to be consistent with your exceptions. get throws a NoSuchElementException in this case, while add throws  NullPointerException.

Oracles implementation throws an IndexOutOfBoundsException which makes a lot of sense (and if you want to stay close to the List interface, you should use it as Tavian Barnes pointed out), but you could make a case for a NullPointerException or IllegalArgumentException if you wanted to. NoSuchElementException on the other hand would not match the description (Thrown by the nextElement method of an Enumeration).

Don't return null

The only occasion you should return null is if the data inside the node is null. If a value is requested that doesn't exist, throw an exception. You violate this in get and remove, which will make it really difficult for a user in case they do store null in the list.

Naming

crntNode: just add the extra characters, its not that much longer: currentNode.

Assign value when declaring variables

Instead of

Node<T> crntNode;
Node<T> newNode = new Node<T>(data);
crntNode = getNode(index);

do this:

Node<T> crntNode = getNode(index);
Node<T> newNode = new Node<T>(data);

You do the same thing in get.

Performance

To increase performance, save the previous result of expensive method calls in local variables. For example, getNode is expensive, and you call it twice in add as well as remove.

index

You should get rid of index (not the parameter, but the node field).

In a linked list, nodes don't have an index, they only have a next node (and maybe previous if its doubly linked). Maintaining the index adds a lot of complexity and reduces performance, which can be avoided.

so just remove index, you are not using it anywhere anyways.


Slow Erlang code to find Pythagorean triplets

Erlang runs on a VM, so you will get better performance on such a pure arithmetic computation by compiling it into native code using HIPE.

From the command line:

erlc +native slow.erl

Or from the Erlang shell:

1> hipe:c(slow).

Or:

1> c(slow, [native]).


I would look to implement a structure with separate implementations for the three cases:

IBAN13
IBAN10
Neither of the above

You can provide that with something along these lines, in which IBAN#new is overridden to detect the number of integers provided, and to initialise the correct object to process it.

The real trick here is to provide the Invalid module, which responds to everything that you expect the Thirteen and Ten objects to respond to, in an implementation similar to a Nil Object pattern – in this case an Invalid Object.

I've omitted the implementation of the #valid? etc classes, but would point you to the Lisbn gem in which we have implemented an extremely fast algorithm https://github.com/ragalie/lisbn/blob/master/lib/lisbn/lisbn.rb#L111. Benchmarked against Enumerable-based methods, which often look quite elegant, this algorithm is incredibly fast – 40x faster than the same logic implemented in some ISBN gems.

Here's a code outline:

module IBAN
  def self.new(string)
    numeric = string.gsub(/[^0-9]/,"")
    case numeric.size
    when 13
      then Thirteen.new(string)
    when 10
      then Ten.new(string)
    else
      Invalid
    end
  end

  class Thirteen
    def initialize(number)
      @number = number
    end

    def checksum
      # TODO
    end

    def valid?
      # TODO
    end

    attr_reader :number
  end

  class Ten
    def initialize(number)
      @number = number
    end

    def checksum
      # TODO
    end

    def valid?
      # TODO
    end

    attr_reader :number
  end

  module Invalid
    def self.valid?
      false
    end

    def self.checksum
      nil
    end
  end
end

ps. You might prefer to implement Invalid as a singleton instead of as a module.

    ...
    else
      Invalid.instance
    end
    ...

  class Invalid
    include Singleton

    def valid?
      false
    end

    def checksum
      nil
    end
  end
end


Functionally find the index of the minimum value in an array

I think there's no need to use the match keyword here because you're not actually doing any pattern matching, only shadowing the name index with i. I've change it to use if/then/else.
Removing all of the type annotations makes the function more generic and more concise. I've done this below and used the function Array.length to allow the compiler to infer that array is an array. The input type has changed from int [] to 'a [] where 'a has comparison, making the function reusable for other array types. However, this also makes the function a lot slower for some reason so I've marked it as inline to get the re-usability benefits without the performance hit.
I think the findNext function isn't really necessary for readability, but that is probably down to personal preference. I noticed that it makes the function much much slower for a large array so I have removed it. Making it inline has a similar effect.

That leaves us with this:

let inline findMinimumValueIndex array =
    let rec find i minimumValueIndex =
        if i >= Array.length array then minimumValueIndex // base case
        elif array.[i] < array.[minimumValueIndex] then find (i + 1) i
        else find (i + 1) minimumValueIndex
    find 0 0

If I actually needed to do this in code, I would probably do this instead:

array |> Seq.indexed |> Seq.minBy snd |> fst

This is simple enough that it might not even be worth defining a function for, though it is quite slow compared to my refactoring of your function above.

However, for an empty input array this throws an exception, which isn't very functional. And your function returns 0 for an empty array, which can be ambiguous as it's also the result if the first item is smallest. So you could handle that case and return int option instead of int:

let inline minIndexSafe array =
    if array = [||] then None
    else array |> Seq.indexed |> Seq.minBy snd |> fst |> Some


You could change this:

for (int i = 0; i < count; i++) {
        scoreComparatorOne = (list.get(i)).getScore();
        if (i == 0) {
            scoreComparatorTwo = (list.get(i)).getScore();
        } else {
            scoreComparatorTwo = (list.get(i - 1)).getScore();
        }
        if (scoreComparatorOne.equals(scoreComparatorTwo)) {
            if (ranking == 0) {
                ranking += 1;
            } else {
                ranking = ranking;
            }
        } else {
            ranking = i + 1;
        }
    (list.get(i)).setRank(ranking);
    scoreList[i] = (list.get(i));
 }

Theres no need to verify all the time this conditional:

if (i == 0) {
                scoreComparatorTwo = (list.get(i)).getScore();
            } else {
                scoreComparatorTwo = (list.get(i - 1)).getScore();
            }

inside the loop. Since i it will be equal to 0 only once.

Modifying  to:

...
Double scoreComparatorOne = (list.get(0)).getScore();
Double scoreComparatorTwo = (list.get(0)).getScore();
ranking = getRating(scoreComparatorOne,scoreComparatorTwo,ranking,0);
(list.get(0)).setRank(ranking);
scoreList[0] = (list.get(0));

for (int i = 1; i < count; i++){
        scoreComparatorOne = (list.get(i)).getScore();
        scoreComparatorTwo = (list.get(i - 1)).getScore();
        ranking = getRating(scoreComparatorOne,scoreComparatorTwo,ranking,i);
        (list.get(i)).setRank(ranking);
        scoreList[i] = (list.get(i));
}

where getRating is:

 public Integer getRating (Double sCOne, Double sCTwo, Integer ranking, int i)
    {
           if(sCOne.equals(sCTwo))
              return (ranking == 0) ? 1 : ranking;
           else return i + 1;
    }

also you can turn your fillJournalList into (but this is not a major problem):

private static int fillJournalList(Journal[] journals,
    int LENGTH_OF_JOURNAL, ArrayList<Journal> list) {

for (int i = 0; i < LENGTH_OF_JOURNAL; i++){

    if (!journals[i].getIsReviewed())
        list.add(new Journal(new Integer(journals[i].getRank(),
                              new String(journals[i].getJournal(),
                              new Double(journals[i].getScore(),
                              false);

return list.size();

}

This way you only create the new Objects when you will insert them. Not in every for iteration. With the above modification there no need to this:

public class JournalAnalyzer {
    ...
    static String journalName;
    static Double journalScore;
    static Integer journalRank;
    static Boolean journalReview;

You can remove all four variables.


Simple function returning 1 if the Mean = Mode, or 0 if not

First of all, I don’t think this is reasonable:

  if unique values length is same as arr length, return 0

If your array consists of unique values only (e.g. [1, 2, 3, 4]), its mode is not unique, rather there is multiple modes (in this case [1, 2, 3, 4]). How you define what mode exactly means depends on your application so I’m going to ignore this for now.

Let’s look at your code. I’ll list some observations:

Function name. A name like meanEqualsMode would more clearly describe what the function does
Unused variables. There are a few unused variables. Line 3 uses three arguments for the map function’s callback, but the callback is only ever called with one argument: The current array element. You also never use i and a.
Single-letter variable names. This style of naming problematic for a variety of reasons. Most importantly, it’s harder to reason about your own code. For example, in line 21, the reduce function has a and c as callback arguments. sum and count would be better names.
Separation of concerns. Your meanMode function does multiple things. It calculates the mode and the mean. Instead, use separate functions to calculate the mode and mean separately. If your applications uses the check for equality of mode and mean a lot, this would be a third function calling the other two. I’ve done that in the updated code below.
Predictable results. You state that meanMode should return whether the mode and the mean are equal; however, it actually returns a Number (1 or 0). A comparison function (e.g. a function containing the words is, equal, or similar) should always return a boolean value (true or false). This again makes it easier to reason about your code. Just reading meanEqualsMode([2, 3, 5]) should tell you what the result of that function will be without the need to look at the actual implementation.

function meanEqualsMode(array) {
  const mode = arrayMode(array);
  const mean = arrayMean(array);

  return mode === mean;
}

function arrayMode(array) {
  const frequencies = new Map();

  for (const value of array) {
    const currentCount = frequencies.has(value) ? frequencies.get(value) : 0;
    frequencies.set(value, currentCount + 1);
  }

  let highestCount = 0;
  let mostOccurringValue;

  for (const [value, count] of frequencies) {
    if (count >= highestCount) {
      highestCount = count;
      mostOccurringValue = value;
    }
  }

  return mostOccurringValue;
}

function arrayMean(array) {
  return array.reduce((sum, value) => sum + value) / array.length;
}

Now, answering some of your questions:

  Was using a counts variable necessary?

Yes and no. In order to calculate the mode of a list of numbers, you need to know the number of occurrences for each number. However, it is possible to determine the mode while counting the occurences; thus, allowing you to calculate the mode without explicitly storing the occurences. To keep the code simple, I opted for not combining these steps.

  Are all variable keywords (const & let) optimal?

Probably not. You are using const and let. There is very, very little reason to also still use var at all. Most variables are assigned only once and can be defined using const. Some variables have to be declared using let because they’re (re-)assigned later.

  Is it wise to include comments to describe what the code does?

Yes. Take my code for example. Is there something you don’t understand? Then it could’ve maybe explained with a comment. You used a reduce function in your code which I often find hard to read. You need to ask yourself: Is my code dealing with a complex problem that needs explaining or is it just written in a hardly readable fashion? A complex problem is best explained with comments. Code which is hard to read and thus hard to reason about is better fixed by making it more readable and obvious.

  Was declaring the mode variable before assigning its value the best way? Its value depends on a condition

No, it wasn’t. The mode of a list of numbers always exists although it might not be unique. Therefor its value does not logically depend on a condition.


Is my design achieving Separation of Concerns in this MVC implementation?

Summary with answers below

MVC gone bad

I allready wrote an article on how MVC is abused, so I'm not going to repeat myself here.

So what is MVC?

MVC is a design pattern (or architectual pattern or even cake) that seperates our code into 3 distinct functionalities: Model, View and a Controller.

Model

The Model represents the Data. For instance a Student.

View

A view presents those Models. For instance in a table. It thus acts purely as representation layer.

Controller

The controller is the part that gets a command from the user/client and translates it to the correct internal command. e.g. "show user with id 4" => "pas the User Model with id 4 to the correct view"

Implementation

What MVC doesn't do is tell you anything about how you implement it. It also doesn't tell you how these different components interact.

MVC doesn't say anything about using other code. A lot people cram everything into MVC. So are you. Your Model is not a Model but a Repository (or Mapper or whatever you call it). Your Model acts as a layer to query your MySQL database that returns an object that represents your data.

Implementing the model:

the Student model will have method that will help you get information about the Model. For instance:

function getFullName() {
    return $this->firstName . ' ' . $this->lastName;
}

Retrieving the model

We ofcourse need a way of retrieving a Model. This could be done for instance using a Repository:

interface UserRepository
{
    public function find($id)

    public function getBy($key,$value)
}

and because we use Mysql, lets implement a repository that does all the fetching:

class MysqlUserRepository implements UserRepository
{
    public function find($id)
    {
        $result = $this->db->query('SELECT FROM users WHERE id = '.$id;
        return new User($result[0]);
    }

    public function getBy($key,$value) { ... }
}

This UserRepository could for instance be injected into the controller:

Implementing the controller

class UserController
{
    public function find($id)
    {
        $user = $this->repository->find($id);

        return ViewFactory::make('show.user', array('user'=>$user)));
    }
}

Here the UserController returns a View object. I opted for a Factory pattern approach here:

ViewFactory & view

class ViewFactory
{
    public static function make($viewName, $data) {
        $view = new View(VIEW_DIR . $viewName);
        $view->addData($data);
    }
}

And our view will look someting like this:

class View
{
    public function __construct($viewFile)
    {
        $this->viewFile = $viewFile;
    }

    public function addData($data)
    {
        $this->data = array_merge($data, $this->data);
    }

    public function render()
    {
        extract($this->data);
        include $this->viewFile;
    }
}

Implementing our view

  Because I don't like writing $this->data->.. stuff in my templates, I use the extract function in the render function.

views/dir/show.user.tpl.php

<?php echo $user->getFullName(); ?>

Age: <?php print $user->getAge(); ?>

Just an Example.

Now this is just an example - and it should be treated as one.

Summary

to answer your questions

  Do I require a getter or a setter, say $searchCritera, here so I can maintain Separation of Concerns?

No, why should searchCriteria be seperated? A searchCriteria needs context:

UserRepository::getById(4);

returns something completly different as

UserRepository::getOlderThenYears(4);

  Would it be wrong to simply query the model from the view with
  findStudentsByID(4);? Wouldn't that bind the two too much?

YES, very wrong. A view is a presentational piece of software. It is stupid an knows nothing. Only how to present a certain object to the screen. Nothing more.

Models

Instead of using getters/setters on a Model. One could simply use public variables (or emulate them using the magic methods (PHP)). Since a Model is a representation of data, you could simply change it's values. After changes are made one could pass it back to the repository:

$user = Repository::find(4);
$user->name = 'foobar';
Repository::save($user);


It looks from the data as if you do not need the numbers to be random, only unique.
A solution is to take the numbers from 1 to 1,000,000 but output them in base 29 using the allowed characters.

private static readonly char[] Values = {
        'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', '2',
        '3', '4', '5', '6', '7', '8', '9'
    };

private static readonly int ValueCount = Values.Length;

private IEnumerable<string> GenerateValues(int count) {
    for (var c = 0; c < count; c++) {
        yield return FormatNumber(c);
    }
}

private static string FormatNumber(int value) {

    var digits = new[] { Values[0], Values[0], Values[0], Values[0], Values[0], Values[0], Values[0], Values[0] };
    var slotCount = digits.Length;

    var current = value;
    var count = 0;
    while (current > 0) {
        int rem;
        current = Math.DivRem(current, ValueCount, out rem);
        digits[slotCount - ++count] = Values[rem];
    }

    return new string(digits);
}

This will generate:

BBBBBBBB  (0)
BBBBBBBC  (1)
BBBBBBBD  (2)
...
BBBCQBC3  (1,000,000)

you can modify it to start at any point and to generate different amount of Ids (up to \$29^8-1\$)


Using the same type for the deque contents and the sizes/indices (k, count, head, tail) feels wrong. At least, k and count should be std::vector::size_type.

Since you are backing up the deque with std::vector, making head and tail the std::vector::iterator looks more idiomatic.

k is not the most descriptive name. Consider capacity.

I am not sure that std::vector is the best container to back up the fixed size deque. After all, the point of std::vector is to have a dynamic size. std::array, or even a plain old C-style array, looks more natural.


Testability

Your repository implements an interface which will allow it to get stubbed out easily, so that's a very testable thing. However if you want to also (unit-test) your repositories themselves then you are stuck because you have a hardcoded dependency on DatabaseContext.

You should move that up one layer by abstracting it out as well and providing a custom DbContext for testing purposes or by mocking it out. More information on that here.

  I have read countless opinions about what a repository should do. Are there any pragmatic reasons why my implementation might be bad?

One thing that comes to mind is the long-lived DbContext object. Some say it isn't an exact necessity, others say you definitely should avoid it but generally accepted is the notion that you should dispose of your DbContext. A unit of work corresponds to one method inside your repository to wrap a using statement around it.

Note that this would interfere with testing the repository itself so it's worth considering using integration-tests to test your repository in particular.

  The PostsRepository needs to access the Tags database set. Am I allowing this in the correct way? Know that I plan to implement a TagsRepository in the future.

I am not familiar enough with EF to answer that.

  I throw an exception when the slug (which must be unique) is occupied. Should I return a bool to indicate failure instead? Would this not violate the command-query segregation principle?

It does not violate it because it is just the result of your command, it is not the result of a query. It holds exactly the same value as an exception.

There is a more interesting way though: create a "result"-object. This can be as simple as

class CallResult {
    bool Success { get; set; }
    string Message { get; set; }
}

Which will be more descriptive than bool since you can also send a message along. Whether you choose this or an exception depends on your own preference: using an exception will force you to have a try-catch around it somewhere which is rather ugly but then again it will prevent you from accidentally leaving out validation on the return type (either a try-catch or if(result.Success)) which is not enforced with a custom type.

  I am aware that the Edit method is hard to reason about and I am working on that. It is for this reason that my code does not currently adhere to DRY.

Since I don't see an Edit method I'll assume you haven't written it yet. DRY is nice and all but for some niche situations (CRUD actions, tests, ..) I would argue that readability is more important than having a few lines similar to eachother.

I suppose you could create a situation like this, but that depends on how different each action is.

void Process(Post post) {
    post.Slug = SlugConverter.Convert(post.Slug);

    if (context.Posts.Find(post.Slug) != null)
    {
        throw new Exception("tag already exists. choose another.");
    }

    post.Summary = Summarize(post.Content);
    AttachTags(post);
}

void Create(Post post) {
    Process(post);
    post.PublishedAt = DateTime.Now;
    context.Posts.Add(post);
    context.SaveChanges();
}

void Update(Post post) {
    Process(post);
    context.Posts.Add(post);
    context.SaveChanges();
}

Note how I performed the validation before doing the other work.

A method should be written as [action][context]. AllPublishedPosts makes me think it's a property, not a method. I would change this to GetAllPublishedPosts. I'm not speaking out about All since that's a special situation, I suppose.


Filter out URLs with any of some given file extensions

Strictly speaking, there is no direct correlation between the URL string and the type of the content you are going to get when following the URL - there can be, for instance, redirects; or the url leading to a, say, image file would not have the filename with an extension in it (example). And, keeping the list of disallowed extensions does not scale well.

An alternative, slower, but more reliable way would be to actually visit the URLs (we can use "lightweight" HEAD requests for it) and check the Content-Type header. Something like:

import requests

links = ["http://www.abc.com", "http://www.abc.com/file.pdf",
         "http://www.abc.com/file.png"]

with requests.Session() as session:
    links = [link for link in links
             if "text/html" in session.head(link).headers["Content-Type"]]
    print(links)

Note that to improve on speed, we are also using the same Session object, which reuses the underlying TCP connection:

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

Demo (using httpbin):

In [1]: import requests

In [2]: links = ["https://httpbin.org/html",
   ...:          "https://httpbin.org/image/png",
   ...:          "https://httpbin.org/image/svg",
   ...:          "https://httpbin.org/image"]

In [3]: with requests.Session() as session:
   ...:     links = [link for link in links
   ...:              if "text/html" in session.head(link).headers["Content-Type"]]
   ...:     print(links)
   ...:
['https://httpbin.org/html']

You can even take it a step further and solve it with asyncio and aiohttp:

import asyncio

import aiohttp

@asyncio.coroutine
def is_html(session, url):
    response = yield from session.head(url, compress=True)
    print(url, "text/html" in response.headers["Content-Type"])

if __name__ == '__main__':
    links = ["https://httpbin.org/html",
             "https://httpbin.org/image/png",
             "https://httpbin.org/image/svg",
             "https://httpbin.org/image"]
    loop = asyncio.get_event_loop()

    conn = aiohttp.TCPConnector(verify_ssl=False)
    with aiohttp.ClientSession(connector=conn, loop=loop) as session:
        f = asyncio.wait([is_html(session, link) for link in links])
        loop.run_until_complete(f)

Prints:

https://httpbin.org/image/svg False
https://httpbin.org/image False
https://httpbin.org/image/png False
https://httpbin.org/html True


Finding the maximum pairwise difference in a collection of colors

Ramos (2001) gives a \$O(n \log n)\$ algorithm, but the paper is not freely available, and apparently the algorithm is very complex. So take a look instead at Malandain and Boissonnat (2004) who give a simple algorithm that is \$O(n^2)\$ in the worst case, but apparently performs well for distributions found in practice.

E. A. Ramos (2001). "An Optimal Deterministic Algorithm for Computing the Diameter of a Three-Dimensional Point Set". Discrete and Computational Geometry, 26:2, pp. 233–244.
Grégoire Malandain and Jean-Daniel Boissonnat (2004). "Computing the Diameter of a Point Set". INRIA research report.


Try rewriting your script with an addEventListener instead of an onChange method.

However, keep in mind that an addEventListener is not compatible with IE lower then IE9. So don't use this yet in live sites.

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener?redirectlocale=en-US&redirectslug=DOM%2FEventTarget.addEventListener
http://coding.smashingmagazine.com/2013/11/12/an-introduction-to-dom-events/