Very nice:

Few minor changes I would make.

In isAvailable() I would check row/col/box all at the same time.

int isAvailable(int sudoku[][9], int row, int col, int num)
{
    //checking in the grid
    int rowStart = (row/3) * 3;
    int colStart = (col/3) * 3;

    int i, j;
    for(i=0; i<9; ++i)
    {
        if (sudoku[row][i] == num)                             return 0;
        if (sudoku[i][col] == num)                             return 0;
        if (sudoku[rowStart + (i%3)][colStart + (i/3)] == num) return 0;
    }

    return 1;
}

Which brings my to my first comment:
I prefer to have sub statments of while/for/if inside block quotes.

if( sudoku[i][j] == num )
            return 0;

// I prefer this:
if( sudoku[i][j] == num )
{   return 0;
}

This way there is not chance of accidentally putting a macro that expands and is not all executed.

Your code for moving to the next square is in multiple places in the code:

        if( (col+1)<9 )
           STUFF(row, col+1);
        else if( (row+1)<9 )
            STUFF(row+1, 0);
        else
            WIN

Because it is multiple places you have redundancy. I would move this check to one location. The easiest way to do that is move it to the first few lines of code in the function. Then you always make a recursive call like this fillsudoku(sudoku, row, col+1).

int fillsudoku(int sudoku[][9], int row, int col)
{
    if (col >= 9)
    {
         col = 0;
         ++row;
         if (row >= 9)
         {
             return 1;
         }
    }

    // Original code.
    // When doing a recursive call use ` fillsudoku(sudoku, row, col+1)`
    // You know the start of the code will test it.

Next I would exit early rather than have nested code.
This is a debatable point on style but I don;t think having to scroll down a long way to see a one lineer for failure helps in readability. And since you already exit early that is not a problem.

        if( sudoku[row][col] != 0) //pre filled
        {
            return fillsudoku(sudoku, row, col+1);
        }
        else
        {
            for(i=0; i<9; ++i)
            {
                if( isAvailable(sudoku, row, col, i+1) )
                {
                    sudoku[row][col] = i+1;

                    int good = fillsudoku(sudoku, row, col +1);
                    if (good)
                    {   return 1;
                    }
                    sudoku[row][col] = 0;
                }
            }
        }
        return 0;
}


Is this code efficient for file parsing?

ofstream outfile;

Why is this declared global? The variable is only used in writedata. Declare it in this scope.
ofstream out;

What is the purpose of this stream? It is opened (multiple times!) in the code but never written to.
string tmp;
string data;
string filename;
string name;
size_t found;

You should declare objects in the narrowest scope that they need to exist, instead of the function head.
while (input >> line)

The operator >> will read one word at a time, not a whole line. If you want to read whole lines, you should use while(std::getline(input, line)).
found = line.find_last_of("pmf");

I think this doesn't do what you expect it to do. It finds the position of the last character in line which is equal to either of the single characters in "pmf". You probably want to use line.rfind("pmf") instead, which returns the position of the last occurrence of the full string "pmf".

Looking at your example file however I believe you actually want to check whether the beginning of the line is "pmf" (consider the work string might include "pmf"), so you would use line.find("pmf") and check it against 0 instead of string::npos.
name = line.substr(found + 1, line.length());
filename = line.substr(found + 1, line.length());

These two strings are the same? Why? In the following code they are used interchangeable, so stick to one and remove the other. Even if they were used differently you could still use filename = name.

Also you are trying to get a substring of the same length as the whole line (the second argument to substr is the length of the substring to be extracted), which obviously doesn't work. However substr truncates in this case such that a substring ending at the end of the input string is returned.

The supposed filename you are extracting should be the part after pmf in pmfwork1. However you start the substring one position after the position of the last occurrence of pmf, which would be result in "mf" being part of the string. However with the particular example file you provided and in combination with the semantic error I laid out in 5., you actually get the expected result. Here two errors cancel each other. For different input however you would have very unexpected results.
for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)
    if (name.compare(it->first) == 0)

The whole purpose of a map is to be able to access the values via a key instead of iterating over them. You should use this functionality:

auto it = MyFileMap.find(name);
if(it != MyFileMap.end())
    // "name" found it is at "it"
else
    // "name" is not in "MyFileMap"!

while (input >> tmp && tmp.compare("pme"))

Again the input is one word each instead of lines. Data which includes the word "pme" would trigger the end.
if (it == MyFileMap.end() || MyFileMap.empty())

The second condition is redundant. If MyFileMap.empty() is true, then also it == MyFileMap.begin() == MyFileMap.end() at this point.
cout << "Data push " << data << " to " << it->second << endl;

Here you try to dereference it, which you previously checked to be MyFileMap.end(). Dereferencing the end() iterator invokes undefined behaviour. Since I guess these lines are debug output only anyway, just remove that part.
MyFileMap[name] = filename;
for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)
{
    if (name.compare(it->first) == 0)
    {
        writedata(data, it->second);
        data.clear();
        break;
    }
}

What is the purpose of this loop? You just inserted the key name into the map and now you search it again. Why not simply access it directly:

MyFileMap[name] = filename;
writedata(data, MyFileMap[name]);
data.clear();

Note however that this is the same as, but in general slower than:

MyFileMap[name] = filename;
writedata(data, filename);
data.clear();

system("pause");

In order to use std::system you need to #include<cstdlib>.
What is the purpose of the MyFileMap at all? It stores the names as keys and filenames as values. The only difference between the two is that filename has an ".txt" added. Why do you need to save this? You can append the ".txt" each time you have a new name. This would be much easier to read and much faster.
If you are trying to minimize the number of open calls you might want to store all the opened ofstreams in the map and access them as you need them, closing all at the end of the function. Notice however that ofstream is not copyable, so you need to store references to them in the map, instead of the objects themself.

If the input files are not that big, you might also consider saving all the parsed data in memory first and then writing it to the output files in one go. While parsing you can use a string-string map to save the data for each file.
You are lacking any check of syntax errors in the input file. You probably should add code that reports back if the syntax is not as expected instead.

In summary:

Your code will likely not do what you expect it to do in many cases. You should generate more diverse test cases. (try pmfworkm instead of pmfwork1 in your example file and report what happens).

Several parts of the code are redundant (all the map-iterating loops) and at the same time they might be very time costly for large input files (since the map might grow rapidly).


How can I make my filter search code more efficient?

1) Avoid unnecessary document.querySelector and document.querySelectorAll. Store its results if you sure there won't be any changes.

Element searching in the DOM is relatively hard operation (it is extremely optimized, but still). So you should avoid it if you can.

You've already done a lot for that, but I still can see unsaved document.querySelector(".page-header.cf")

2) Use event delegation pattern.

You don't have to add event listeners to each element on the page. Especially if they are in the same container.

const parent = document.querySelector('#parent');

parent.addEventListener('click', (e) => {
  const target = e.target.closest('a');

  if (!target) return;

  if (target.matches('.active')) {
    target.classList.remove('active');

    resetPage();
  } else {
    target.classList.add('active');

    const page = target.textContent;

    displayPage(page);
  }
});

  1
  1

As a bonus, you don't have to add event listeners on newly created links or remove it from removed links.

3) Do not modify elements content as HTML string if you can avoid it.

In your case you can move li.no-results outside of studentList and show/hide it with display: none/block property. Or at least remove/append this element as a node, not as HTML-string. It is much faster.

4) Use debounce.

You don't need to trigger the search on each keyup. You need to trigger it only when user stops typing. So when you have event series with, let's say, 200 ms interval, you need to trigger search only for the last one. You can use lodash/debounce for that or write your own implementation

5) Learn how to use Chrome Profiling Tool
It helps to find bottlenecks of your app and fix them.


It seems that in both branches you're doing the same calculation, so might want to begin by pushing the conditional in, obtaining:

let rec rev_int num =
  if num / 10 == 0 then
    num
  else
    let temp = num mod 10 in

    let numDigits = String.length(string_of_int num) - 1 in

    let numDigits = numDigits - (if num < 0 then 1 else 0) in
    let num = (num - temp) / 10 in
    temp * int_of_float(10.0 ** float_of_int numDigits) + rev_int num

Just an initial thought to get you started on improving the code.


Calculate the continued fraction using the function indicators

Don't use using namespace std
Prefer prefix over postfix
return 0 is not needed at the end of main
Prefer using \n over std::endl
Don't use printf in C++ code
As Reinderien already mentioned the exit variable is not needed. I.e.

for (;;) {
        // [...]
        if (n == 0) {
            break;
        }
        // [...]

will be sufficient.


Function to lock a file using memcache, Version 2

logical flaw

If an exception happens, your key could remain locked.

You use

def addToCart(filename, username):
    ableToLock = memcache.add(filename, username)
    if ableToLock:
        # ableToLock can happen if the file is still present
        # or if it was already processed.
        if os.file.ispath(filename):
            # I have a lock and file exists. Think of Cart as a
            # JS Object from where you can pick items to "process".
            return "Added To Cart"
        else:
            # I have a lock but looks like file was processed already.
            # So removing the residual "key" created.
            memcache.delete(filename)
            return "Processed by another user."
    else:
        ...

def process(source):
    shutil.move(source, destination)
    # filename => source
    memcache.delete(filename)

What if shutil.move throws an exception? Or print?

Better would be

if ableToLock:
    try:
        # ableToLock can happen if the file is still present
        # or if it was already processed.
        if os.file.ispath(filename):
            # I have a lock and file exists. Think of Cart as a
            # JS Object from where you can pick items to "process".
            return "Added To Cart"
        else:
            return "Processed by another user."
    finally:
        memcache.delete(filename)


Implementing simplified Jaipur board game

Here are a couple of first-glance observations:

Use enum. If you are going to have all-caps names with integers, you might as well import the module and get all the benefits.
Don't pass classes by name. Pass them by value. Change this: game = Jaipur('Player', 'Player') into something like game = Jaipur(Player, Player) (note: no quotes).

Classes are first-class objects in Python. You can pass them around just like any other object.
Use the game class to enforce the rules. You have code in your Player class to check on things like the minimum number of commodities to trade. Put that in the game class instead. Also, make the game class the keeper of records. If your Player class is supposed to be an AI, then let the game handle the record-keeping and have the player just tell the game what it wants.
(An example of the Single Responsibility Principle.)
Don't import numpy just to use argmax! Python defines a max() builtin.


It is things like this which drive me nuts, and I agree with you, your solution is good, but ugly. Your solution is also probably close to being as efficient as possible in Java, using the StringBuilder, etc.

There are a couple of things through that you can do to xhange the way you code it. Note that your solution may well be the fastest.... (well, it would be the fastest if you specified a starteing capactity of 23 for the StringBuilder like new StringBuilder(23) ...

How about a for-loop:

private static String formatID(String id) {
    StringBuilder sb = new StringBuilder(25);
    for (int i = 0; i < id.length(); i += 4) {
        sb.append(id.substring(i, Math.min(i + 4, id.length())));
        sb.append(" ");
    }
    sb.setLength(23);
    return sb.toString();
}

The last setLength(23) removes the trailing space on the output.

The actual suggestion I prefer, though, is using a format String, like:

private static String formatFID(String id) {
    return String.format("%s %s %s %s %s", id.substring(0, 4), id.substring(4,  8),
            id.substring(8,  12), id.substring(12,  16), id.substring(16, 19));
}

Finally, for completeness, you can actually use a regex to split the input string at 4-char boundaries. Then, in Java 8, stream the results, and join them with a space:

private static final Pattern FOUR = Pattern.compile("(?<=\\G.{4})");

private static String formatRID(String id) {
    return Stream.of(FOUR.split(id)).collect(Collectors.joining(" "));
}

That's a concise way of doing it.....


The modern way to attach onLoad and onUnload handlers is to use window.addEventListener('load', onloadFunction) and window.addEventListener('unload', onunloadFunction).  Unlike window.onload, you can attach multiple handlers, saving you the work of writing your own support for multiple handlers.

Unfortunately, Internet Explorer only added support for addEventListener() in IE 9.  Therefore, you'll probably need a shim.  That would be a common shim that supports a standard interface, rather than your own hack, so I would still consider it an improvement.


If this is not just a learning exercise, I have to point out that C++ already has a sorting function in its standard library and in real code you should use that. So for the rest of this answer I'm going to assume that this is in fact just a learning exercise.

Now first a note on the algorithm: Usually quicksort is implemented in-place for better performance. Even if you want a sorting function which does not modify its argument, it's quicker to just copy the argument and then run an in-place quicksort on the argument.

Further you're creating a lot more copies of your vectors than you need to, even when using this choice of algorithm: Every time you pass a vector by value, it is copied. Every time you pass a vector, which you do not want to modify, you should rather pass it by const reference, so as not to create an unnecessary copy.

On the same note concatenate also creates an unnecessary copy by returning the result vector by value. This can be avoided by passing an empty vector by non-const reference and filling that instead of using a return value.

Lastly there is a bit of code duplication in your main function: You're printing a vector separated by pipes twice - once during its creation and once after sorting. I would define a helper function print_vector, which prints a vector separated by pipes, and call that twice: once after creating the vector and once after sorting it. This way the first printing will have to happen after the vector creation, not during, but that's okay as doing it during the creation gives very little performance benefit (if any) and having the creation be a separate step from printing the vector improves code cleanliness.


This Project Euler question is an excellent one to think about computational efficiency of algorithms.  It's a horrible place to make decisions based on benchmarks, though.

Sure, your second method is faster.  But you're basically cheating with the magic number 2520.  It's not a particularly insightful implementation for mathematical learning, either, as it's guessing rather than computing.

To illustrate what I mean, let's consider two more implementations.

"Fast and Crappy"

This algorithm computes the LCM of \$\mathrm{numbers}_i\$ based on the principle that

$$ \mathrm{LCM}(a, b) = \prod p_j^{\max(e_{j,a}, e_{j,b})} $$

when numbers are factorized as \$a = \prod p_j^{e_{j,a}}\$ and \$b = \prod p_j^{e_{j,b}}\$.

  Why do I call it "crappy"? Because it is using the same strategy as this nice-looking Ruby code, but it would take a lot of work to make it look as good in Java.

   require 'prime'

lcm_factors = Hash.new(0)       # Default entry is 0
(1..20).each do |n|
  Prime.prime_division(n).each do |factor|
    prime, exponent = *factor
    lcm_factors[prime] = [lcm_factors[prime], exponent].max
  end
end
puts lcm_factors.map { |prime, max_exponent| prime ** max_exponent }
                .inject(:*)

public class FastCrappyEuler5 {
    private static final int[] PSEUDOPRIMES_BELOW_20 = new int[] {
        2, 3, 5, 7, 11, 13, 17, 19
        // 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19
    };

    public static long lcmOfNumbersUpTo(int rangeMax) {
        if (rangeMax > 20) {
            throw new IllegalArgumentException("TODO: FIXME");
        }

        int[] numbers = new int[rangeMax];
        for (int n = 1; n <= rangeMax; n++) {
            numbers[n - 1] = n;
        }

        long lcm = 1;
        for (int p : PSEUDOPRIMES_BELOW_20) {
            int maxExponent = 0;
            for (int i = 0; i < numbers.length; i++) {
                int exponent;
                for (exponent = 0; numbers[i] % p == 0; exponent++) {
                    numbers[i] /= p;
                }
                maxExponent = Math.max(maxExponent, exponent);
            }

            while (maxExponent --> 0) {
                lcm *= p;
            }
        }

        return lcm;
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        System.out.println(lcmOfNumbersUpTo(20));
        System.err.println(System.nanoTime() - start);
    }
}

This takes about 6 times as long as your fast implementation.  (For me, it's on the order of ~105 nanoseconds.)  I've taken a shortcut of hard-coding the primes below 20 — a "fair" move, I think, as most people know them by heart.

If you replace the pseudoprimes list with a list of all integers from 2 to 20, you get the same answer, with no significant difference in running time.

Using streams

This implements exactly the same algorithm as FastCrappyEuler5, but does so using Java 8 streams to be more elegant.

import java.util.stream.IntStream;
import java.util.stream.LongStream;

public class StreamsEuler5 {
    private static LongStream pseudoPrimesBelow(int max) {
        // We should be more selective, but as we saw above,
        // it shouldn't make much difference.
        return LongStream.range(2, max);
    }

    private static long pow(long base, /* unsigned */ int exponent) {
        long power = 1;
        while (exponent --> 0) {
            power *= base;
        }
        return power;
    }

    public static long lcmOfNumbersUpTo(int rangeMax) {
        final int[] numbers = IntStream.rangeClosed(1, rangeMax).toArray();

        // Warning: computation is not parallelizable
        return pseudoPrimesBelow(rangeMax).map((p) -> {
            int maxExponent = 0;
            for (int i = 0; i < numbers.length; i++) {
                int exponent;
                for (exponent = 0; numbers[i] % p == 0; exponent++) {
                    numbers[i] /= p;
                }
                maxExponent = Math.max(maxExponent, exponent);
            }
            return pow(p, maxExponent);
        }).reduce(1, (a, b) -> a * b);
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        System.out.println(lcmOfNumbersUpTo(20));
        System.err.println(System.nanoTime() - start);
    }
}

Unfortunately, it's two orders of magnitude slower! (For me, it's on the order of 5 ⨉ 107 nanoseconds.)

Conclusion

$$\begin{array}{l|r}
\textrm{Implementation}                & \textrm{Approx. running time} \\
\hline
\textrm{Legato's streams}              & 1 \times 10^8 \mathrm{ns} \\
\textrm{Legato's cheat-and-guess}      & 5 \times 10^4 \mathrm{ns} \\
\textrm{200_success's fast-and-crappy} & 1 \times 10^5 \mathrm{ns} \\
\textrm{200_success's streams}         & 5 \times 10^7 \mathrm{ns} \\
\end{array}$$

Are the streams-based implementations worse because they are slower?  I don't think so.  The overhead of the streams seems to dwarf everything else.  But I don't mind waiting a few million nanoseconds if it means that I like the code better.  My streams-based solution is the same algorithm as "Fast and Crappy", so the complexity must be the same.  Presumably, the startup costs would be inconsequential for larger problems.

Basically, do the "right thing" for readability, maintainability, and educational value.  Time measurements mean nothing when you haven't taken scalability into account.  Worry about speed when it's noticeably slow.


last_thing
You define last_thing and use it to initialise your array, which is fine, however you also use it within your actual bubble_sort function.  This seems wrong, it would be better to use the length of the supplied array in order to determine when to stop.  This will make your code more portable and able to handle different sized arrays.
When to check for correct_order
You only need to check if the array is sorted at the end of each pass.  As it stands, you're checking if the array is sorted for each entry you're processing, even if you haven't done anything with the array.  Which feels like you're turning an O(n^2) algorithm into an O(n^3) solution.  Another approach you can use is to keep track of whether or not you've actually done a swap on a given pass, if you haven't then you know it's because the list is already sorted.
looping
This is probably very subjective, but I don't like this:
if d>=last_thing-1:
    d=0

To me, it makes the start of each pass through the list less obvious than other methods.
Generalisability
Algorithms are used to solve general problems.  There are several instances where you've tied your solution to the exact problem (such as your use of last_thing) you're solving which means it can't solve the general problem. The way you've implemented correct_order is another good example of this.  You iterate through the list and make sure that each item in the list has the same value as it's position in the list.  This works for your exact problem, but makes your algorithm useless if you wanted to sort [8,2,4,6].  Consider writing unit tests so that you can actually exercise your code with different inputs to make sure they can be handled.  This will help you to build code that is not so tightly coupled to the specific problem you're solving.
Odds and Bobs

You've imported time, but you're not using it.  Redundant code adds unnecessary noise, consider removing the unused import.
Names matter. a and d aren't very descriptive, consider expanding the names to describe what it is they represent.
If you just need two values (0, 1), consider using a boolean instead (False/True).
Try to standardise on your spacing, sometimes you have spaces around operators sometimes you don't... it can make the code look messy.

Taking some of the above into account, a refactored version of your code might look something like this:
def bubble_sort(array):
    while not correct_order(array):
        for index in range(len(array) - 1):
            if array[0+index] > array[1+index]:
                array[0+index],array[1+index] = array[1+index],array[0+index]
    return(array)

def correct_order(array):
    for i in range(len(array)-1):
        if array[i] > array[i+1]:
            return(False)
    return(True)


Welcome to Rust!
Code Formatting
There are some inconsistencies in your formatting — I have run
cargo fmt to get rid of them.
Naming
There's no need to prefix everything with My or my_ — in
Rust, your names won't as easily clash with existing names as might be
the case in certain other languages.
Error handling
For applications, I suggest using the anyhow crate to manage
errors — it reduces much of the boilerplate.  Just add
anyhow = "1.0"

to the [dependencies] section of your Cargo.toml.
Helper functions
The my_read_line function can be simplified with the ? operator:
use anyhow::Result;

fn read_line() -> Result<String> {
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    Ok(input)
}

my_read_u32_line can be similarly simplified:
fn read_u32() -> Result<u32> {
    Ok(read_line()?.trim().parse()?)
}

Magic numbers
We can define constants for the range of the number:
const MIN: u32 = 1;
const MAX: u32 = 100;

// later
let secret_number = rand::thread_rng().gen_range(MIN, MAX + 1);

Organization
I might reorganize the main function to reduce indentation:
loop {
    println!("Please input your guess.");

    let guess = match read_u32() {
        Ok(guess) => guess,
        Err(_) => {
            println!(
                "Sorry I couldn't read a u32 from your input! \
                Please try again."
            );
            continue;
        }
    };

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => {
            println!("You win!");
            break;
        }
    };
}

Final result
use anyhow::Result;
use rand::Rng;
use std::cmp::Ordering;
use std::io;

const MIN: u32 = 1;
const MAX: u32 = 100;

fn read_line() -> Result<String> {
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    Ok(input)
}

fn read_u32() -> Result<u32> {
    Ok(read_line()?.trim().parse()?)
}

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(MIN, MAX + 1);

    loop {
        println!("Please input your guess.");

        let guess = match read_u32() {
            Ok(guess) => guess,
            Err(_) => {
                println!(
                    "Sorry I couldn't read a u32 from your input! \
                    Please try again."
                );
                continue;
            }
        };

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        };
    }
}


I see a number of things that may help you improve your code.

Use a stack pointer as a parameter

Right now, one can only have one stack at a time.  Worse, if one calls stack_init after some items have already been pushed onto the stack, there will be a memory leak.  An alternative scheme would be to have stack_init() return a pointer to a Stack and then use that as a parameter for all other calls.  That way, one could have multiple stacks simultaneously, making it that much more useful.

Initialize all values before use

In the stack_init routine, the head variable is initialized, but neither head->element nor head->next are initialized.  It's also probably a good idea to explicitly zero the size.  Although it's already zeroed at the moment because it's a file scope variable, if you follow the other advice on this list, you'll have to initialize it yourself.

Provide a way to free memory

Right now, the only way to free memory is to repeatedly call pop().  Unfortunately, the calling program has no way to know how many items are on the stack or to know when the stack is empty, so it's not going to be able to know how many times to do so.  I'd suggest providing at least an explicit isEmpty() call.

Provide a complete interface

At the moment, there isn't any way to actually use the stack except to call print_stack() which limits its usefulness in the extreme.  I'd suggest that adding a means of examining the top of the stack, as with a call to top() that returns the value for that item might be a good idea.

Don't access freed memory

These lines have a problem:

free(head);
head = head->next;

The problem is that after you've freed head, you dereference it to get the next pointer.  This is undefined behavior -- anything could happen and it probably won't be good!  Better would be to save a copy of the pointer, do your housekeeping and then free the copy like this:

struct Node* temp = head;
head = head->next;
free(temp);

Separate printing from data manipulation

There is no way at the moment to use pop without it printing something.  In a real program that use such a stack, that's unlikely to be the desired effect.  Better would be to have pop() just do what it needs to do and leave printing to the calling program.

Return something useful from functions

Most of your non-void functions return something useful, but pop always returns 0 which isn't very useful.

Encapsulate related data in a structure

The size and head elements are closely related items.  For that reason (and to accomodate suggestion #1 on this list), I'd recommend combining them into a struct instead like this:

struct Stack {
    struct Node* head;
    int size;
};

Use a typedef to simplify your code

If you use a typedef like this:

typedef struct {
    struct Node* head;
    int size;
} Stack;

the code can refer to simply Stack instead of struct Stack.  It's not necessary, but it does tend to make things a little easier to write and to read.


Don't put console.log calls in you functions unless there's a really good reason to. In this case, you're just printing the input, which is pretty pointless. It can also contribute greatly to the function's running time, since printing a large array isn't exactly free (a lot depends on how the runtime handles output)
You can simplify the code. You can do without slicing, reversing and applying chunks of the array

I'd just use two for-loops:

function selReverse(array, chunkSize) {
  var output = [],
      l = array.length;

  for(var i = 0 ; i < l ; i += chunkSize) {
    var start = Math.min(i + chunkSize, l) - 1;
    for(var j = start ; j >= i ; j--) {
      output.push(array[j]);
    }
  }
  return output;
}

Edit: The code above doesn't work, but I thought it was due to very large inputs or something, but that's not the case.

The simple solution is basically, that the for loop - both in my code and the original code - goes into an infinite loop if the chunkSize is zero. This works, though:

function selReverse(array, chunkSize) {
  var output = [],
      l = array.length;

  if(chunkSize === 0) return array.slice(); // could also do <= 0 to be safer

  for(var i = 0 ; i < l ; i += chunkSize) {
    var start = Math.min(i + chunkSize, l) - 1;
    for(var j = start ; j >= i ; j--) {
      output.push(array[j]);
    }
  }
  return output;
}

Since it's got nothing to do with large inputs, I imagine the original code works just as well, as long as it too checks for the chunkSize.


Simple repository for a small/medium sized ASP.NET MVC site

Keep your disposables short lived and you'll never have to implement IDisposable yourself.

In other words, avoid keeping disposable objects as members. Always try to wrap them in a using statement. If you do that, you'll find that your Unit of Work doesn't need to be disposable.

I can't ignore the obvious here though. There is no reason for any of this code to exist. It literally does nothing but pass through to the DbContext. Entity Framework is already a repository & unit of work.

That's not to say that you shouldn't hide the fact that you're using EF from your controller though. It's much better to create a domain specific API to decouple your controller from the persistence. In our projects we'll often have things like FooService.GetByName(string name) and FooService.GetMostRecent(int numberToRetrieve) kinds of methods. It makes for pleasant reading and easy implementation changes.


Thanks for sharing your code.

Your example is a typical case of duplicated code you have two places where the code looks very similar (and is logically the same) but has some minor differences.

On the other hand your example is a special case because we can simply convert the input of one of the duplicated parts to the form of the other one:

public class Sort {
    private static <E extends Comparable<E>> void swap(List<E> sequence,
                                                       int positionOne, int positionTwo) {
        E temp = sequence.get(positionOne);
        sequence.set(positionOne, sequence.get(positionTwo));
        sequence.set(positionTwo, temp);
    }
    public static <E extends Comparable<E>> List<E> selectionSort(List<E> sequence) {
        for (int i = 0; i < sequence.size(); i++) {
            int minPosition = -1;
            E minValue = sequence.get(i);
            for (int j = i + 1; j < sequence.size(); j++) {
                E secondPosition = sequence.get(j);
                if (minValue.compareTo(secondPosition) > 0) {
                    minPosition = j;
                    minValue = sequence.get(j);
                }
            }
            if (minPosition >= 0) {
                swap(sequence, i, minPosition);
            }
        }
        return sequence;
    }

    public static <E extends Comparable<E>> E[] selectionSort(E[] sequence) {
        return selectionSort(new ArrayList(Arrays.asList(sequence))).toArray(new E[sequence.length]);
    }

    public static void main(String[] args) {
        Integer[] integers = {1, 6, 88, 7, 44, 3, 11};
        System.out.println("Before: " + Arrays.toString(integers));
        Sort.selectionSort(integers);
        System.out.println("Later: " + Arrays.toString(integers));
    }
}

However...

The more general approach is to refactor one (or both) of the similar  code fragments to make them (partially) the same.

In your example the difference at both places is the way the elements are addressed and accessed. We need to introduce an indirection, to provide an input type independent way to do this.

In this example an interface is the way to go:

interface MySequence<E extends Comparable<E>>{
  E getElementAt(int index);
  void setElementAt(int index, E element);
  int elementCount();
}

You could "reuse" method names from one of the duplicated parts but I intentionally use different names to make my point...

Now in each of the methods we first create an anonymous inner class from this interface. Lets start with the two swap() methods:

private static <E extends Comparable<E>> void swap(List<E> sequence, int positionOne, int positionTwo) {
    MySequence<E> mySequence = new MySequence<E>() {
        public E getElementAt(int index) {
            return sequence.get(index);
        }

        public void setElementAt(int index, E element) {
            sequence.set(index, element);
        }

        public int elementCount() {
            return sequence.size();
        }
    };
    E temp = sequence.get(positionOne);
    sequence.set(positionOne, sequence.get(positionTwo));
    sequence.set(positionTwo, temp);
}

private static <E extends Comparable<E>> void swap(E[] sequence, int positionOne, int positionTwo) {
    MySequence<E> mySequence = new MySequence<E>() {
        public E getElementAt(int index) {
            return sequence[index];
        }

        public void setElementAt(int index, E element) {
            sequence[index] = element;
        }

        public int elementCount() {
            return sequence.length;
        }
    };
    E temp = sequence[positionOne];
    sequence[positionOne] = sequence[positionTwo];
    sequence[positionTwo] = temp;
}

Then we replace any following occurrence of sequence in that method with mySequence:

  private static <E extends Comparable<E>> void swap(List<E> sequence, int positionOne, int positionTwo) {
    MySequence<E> mySequence = new MySequence<E>() {
        public E getElementAt(int index) {
            return sequence.get(index);
        }

        public void setElementAt(int index, E element) {
            sequence.set(index, element);
        }

        public int elementCount() {
            return sequence.size();
        }
    };
    E temp = mySequence.getElementAt(positionOne);
    mySequence.setElementAt(positionOne, mySequence.getElementAt(positionTwo));
    mySequence.setElementAt(positionTwo, temp);
}

You hopefully can do this for the other version of swap() yourself...

Now both swap() methods had a differing part (the anonymous inner class of type MySequence) and a equal part (the thee following lines).

Actually we have more code then before, but we are going to reduce it in a few minutes...

Select the three identical lines in one of the methods and
apply your IDEs automated refactoring extract method to create a new version of swap():

private static <E extends Comparable<E>> void swap(MySequence<E> mySequence, int positionOne, int positionTwo) {
    E temp = mySequence.getElementAt(positionOne);
    mySequence.setElementAt(positionOne, mySequence.getElementAt(positionTwo));
    mySequence.setElementAt(positionTwo, temp);
}

 private static  <E extends Comparable<E>> void swap(List<E> sequence, int positionOne, int positionTwo) {
    MySequence<E> mySequence = new MySequence<E>() {
        public E getElementAt(int index) {
            return sequence.get(index);
        }

        public void setElementAt(int index, E element) {
            sequence.set(index, element);
        }

        public int elementCount() {
            return sequence.size();
        }
    };
    swap(mySequence, positionOne, positionTwo);
}

The replace the three  duplicated lines in the other original swap() method with a call to the new one too.

private  static <E extends Comparable<E>> void swap(E[] sequence, int positionOne, int positionTwo) {
    MySequence<E> mySequence = new MySequence<E>() {
        public E getElementAt(int index) {
            return sequence[index];
        }

        public void setElementAt(int index, E element) {
            sequence[index] = element;
        }

        public int elementCount() {
            return sequence.length;
        }
    };
    swap(mySequence, positionOne, positionTwo);
}

Next step is to remove the old versions of swap(). click on the name if one of these and invoke your IDEs automated refactoring inline method. Repeat this with the otehr old version too.

Now your selectionSort() methods look like this:

public static <E extends Comparable<E>> List<E> selectionSort(List<E> sequence) {
    for (int i = 0; i < sequence.size(); i++) {
        int minPosition = -1;
        E minValue = sequence.get(i);
        for (int j = i + 1; j < sequence.size(); j++) {
            E secondPosition = sequence.get(j);
            if (minValue.compareTo(secondPosition) > 0) {
                minPosition = j;
                minValue = sequence.get(j);
            }
        }
        if (minPosition >= 0) {
            MySequence<E> mySequence = new MySequence<E>() {
                public E getElementAt(int index) {
                    return sequence.get(index);
                }

                public void setElementAt(int index, E element) {
                    sequence.set(index, element);
                }

                public int elementCount() {
                    return sequence.size();
                }
            };
            swap(mySequence, i, minPosition);
        }
    }
    return sequence;
}

Here we move the instantiation of MySequence to the top of each method:

public static <E extends Comparable<E>> List<E> selectionSort(List<E> sequence) {
    MySequence<E> mySequence = new MySequence<E>() {
        public E getElementAt(int index) {
            return sequence.get(index);
        }

        public void setElementAt(int index, E element) {
            sequence.set(index, element);
        }

        public int elementCount() {
            return sequence.size();
        }
    };
    for (int i = 0; i < sequence.size(); i++) {
        int minPosition = -1;
        E minValue = sequence.get(i);
        for (int j = i + 1; j < sequence.size(); j++) {
            E secondPosition = sequence.get(j);
            if (minValue.compareTo(secondPosition) > 0) {
                minPosition = j;
                minValue = sequence.get(j);
            }
        }
        if (minPosition >= 0) {
            swap(mySequence, i, minPosition);
        }
    }
    return sequence;
}

And again we change any further occurence of sequence within each method to mySequence:

public static <E extends Comparable<E>> List<E> selectionSort(List<E> sequence) {
    MySequence<E> mySequence = new MySequence<E>() {
        public E getElementAt(int index) {
            return sequence.get(index);
        }

        public void setElementAt(int index, E element) {
            sequence.set(index, element);
        }

        public int elementCount() {
            return sequence.size();
        }
    };
    for (int i = 0; i < mySequence.elementCount(); i++) {
        int minPosition = -1;
        E minValue = mySequence.getElementAt(i);
        for (int j = i + 1; j < mySequence.elementCount(); j++) {
            E secondPosition = mySequence.getElementAt(i);
            if (minValue.compareTo(secondPosition) > 0) {
                minPosition = j;
                minValue = mySequence.getElementAt(i);
            }
        }
        if (minPosition >= 0) {
            swap(mySequence, i, minPosition);
        }
    }
    return sequence;
}

No we apply the same technique as with the swap() method. Move the identical lines of both methods to a new method using your IDEs  automated refactoring extract method:

private static <E extends Comparable<E>> void selectionSort(MySequence<E> mySequence) {
    for (int i = 0; i < mySequence.elementCount(); i++) {
        int minPosition = -1;
        E minValue = mySequence.getElementAt(i);
        for (int j = i + 1; j < mySequence.elementCount(); j++) {
            E secondPosition = mySequence.getElementAt(i);
            if (minValue.compareTo(secondPosition) > 0) {
                minPosition = j;
                minValue = mySequence.getElementAt(i);
            }
        }
        if (minPosition >= 0) {
            swap(mySequence, i, minPosition);
        }
    }
}

public static <E extends Comparable<E>> List<E> selectionSort(List<E> sequence) {
    MySequence<E> mySequence = new MySequence<E>() {
        public E getElementAt(int index) {
            return sequence.get(index);
        }

        public void setElementAt(int index, E element) {
            sequence.set(index, element);
        }

        public int elementCount() {
            return sequence.size();
        }
    };
    selectionSort(mySequence);
    return sequence; // ATTENTION! this line is NOT identical because of the type of sequence...
}

And replace the extracted part in the other original selectionSort() method too.

Thats it!

The code might even be shorter if we would use tree functional interfaces and lambda expression at the cost of more parameters at the new methods instead of one interface. But I doubt that it would increase readability and it definitely would add possibilities for errors.

The important insight is that we did not change the logic of the program since all changes we did are safe in that respect.

Nevertheless you should always have a set of automated UnitTest to guard your refactorings...


This is a good start for a script. The next step should be separating in-/output from the functions doing the actual work.

In addition, whenever you make multiple requests to the same server, you should use a requests.Session, which will re-use the connection. You can also pass a dictionary params which will be the URL-encoded parameters for the request. The Session can take a default value for that.

You should always use with when opening a file or resource. This way it is ensured that it is closed properly, even if an exception occurs during the intervening code.

You can write multiple rows at once using writelines. You can even pass an iterable to this function and it will iterate for you.

I would write your script something like this:

import requests

URL = "https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/"
PARAMS = {"key": "removed"}

def url_available(session, url):
    response = session.get(URL, params={"vanityurl": url}).json()
    return response['response']['success'] == 42

def main():
    session = requests.Session()
    session.params = PARAMS
    with open('ok.txt') as in_file, open('www.txt', 'w') as out_file:
        out_file.writelines(url for url in in_file
                            if url_available(session, url.strip()))

if __name__ == "__main__":
    with Timer("main"):
        main()

To this you should add a docstring to each function describing what it does, but that is left as an exercise :).

Here Timer is a simple class that starts a timer when the context is entered and reports the result when the with block is finished:

from time import perf_counter

class Timer:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.start = perf_counter

    def __exit__(self, *args):
        diff = round(perf_counter() - self.start, 2)
        print(f'{self.name} finished in {diff} second(s)')


Writing image pixel data to printer code

Start with storing the '\xff' * 72 string as a constant; Python strings are immutable, recreating that string each time is not necessary.

Next, use a list to collect all strings, then join at the end; this is cheaper than constant string concatenation.

Last, avoid attribute lookups in critical sections; assign any attribute lookups done more than once to a local name:

from operator import itemgetter

bgr = itemgetter(1,2,0)

pix = image.getdata()
rowstart = '\xff' * 72
f_write = f.write
empty_join = ''.join
for y in xrange(1800):
    row = [rowstart]
    r_extend = row.extend
    for x in xrange(1200):
        r_extend(map(chr, bgr(pix[y*1200+x])))
    r.append(rowstart)

    f_write(empty_join(row))

You can experiment with joining the whole row (including rowstart) or writing out rowstart values separately; the following version might be faster still depending on write speed versus list concatenation speed:

for y in xrange(1800):
    f_write(rowstart)
    row = []
    r_extend = row.extend
    for x in xrange(1200):
        r_extend(map(chr, bgr(pix[y*1200+x])))
    f_write(empty_join(row))
    f_write(rowstart)


A while back, I went through these exercises about functional programming in JS and since then I strive to use those techniques whenever possible. Bear in mind that functional techniques can lead to slower code, since a function call is made for each iteration instead of just running code within a loop block, but hopefully it is easier to work with each array element in that fashion - e.g. would you read/type if($rootScope.watchlist[i]['id'] == titleID) { or if(element['id'] == titleID) {?

After reading Igor's answer as well as this article about break with respect to functional programming, I believe the following should work:

$rootScope
.watchlist
.slice()         //  copy before reverse(), because reverse() is mutating
.reverse()
.some(function(element, i) {
    if(element['id'] == titleID) {
        $rootScope.watchlist.splice($rootScope.watchlist.length - 1 - i, 1);
        return true;
    }
});

Edit:

Igor suggests simplifying that callback passed to some(). You can use an ES-6 arrow function and a ternary operator to eliminate a few lines, like this:

.some((element, i) => (element['id'] == titleID)? $rootScope.watchlist.splice($rootScope.watchlist.length - 1 - i, 1) : false);

See a demonstration in this plunker. Click the button labeled remove watcher and see how the watcher is removed. This code presumes  $rootScope.watchlist is equivalent to $rootScope.$$watchers...


You can simplify the solution if, instead of checking for a presence of the slash, you would str.strip() the slashes from both sides of each argument and then str.join() the arguments:

def slash_join(*args):
    return "/".join(arg.strip("/") for arg in args)

urljoin() unfortunately does not allow to join more than 2 url parts - it can only do a base and one more part. There is though this clever functools.reduce() usage that may help to adapt it here:

from urllib.parse import urljoin
from functools import reduce

def slash_join(*args):
    return reduce(urljoin, args).rstrip("/")

Note that I'm explicitly stripping a possible right slash but not sure if it is actually needed since the url with a trailing slash would still be valid - e.g. http://foo.com/test/.


Sorry for no explanation. Not really sure why I wrote this. Just saw your post, got in the zone, and suddenly I have a chunk of code! Hope it is insightful.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

const int SEN_LEN = 80;
const int MAX_SEN = 20;

const char* ARTICLES[] = {"the", "a", "one", "some", "any"};
const char* NOUNS[] =  {"boy", "girl", "dog", "town", "car"};
const char* VERBS[] =  {"drove", "jumped", "ran", "walked", "skipped"};
const char* PREPOSITIONS[] =  {"to", "from", "over", "under", "on"};
const int ARTICLES_SIZE = sizeof(ARTICLES)/sizeof(ARTICLES[0]);
const int NOUNS_SIZE = sizeof(NOUNS)/sizeof(NOUNS[0]);
const int VERBS_SIZE = sizeof(VERBS)/sizeof(VERBS[0]);
const int PREPOSITIONS_SIZE = sizeof(PREPOSITIONS)/sizeof(PREPOSITIONS[0]);

char* generateSentence() {
  char* sentence = calloc((SEN_LEN+1), sizeof(char));

  //Build Sentence
  strcat(sentence, ARTICLES[rand()%ARTICLES_SIZE]);

  strcat(sentence, " ");
  strcat(sentence, NOUNS[rand()%NOUNS_SIZE]);

  strcat(sentence, " ");
  strcat(sentence, VERBS[rand()%VERBS_SIZE]);

  strcat(sentence, " ");
  strcat(sentence, PREPOSITIONS[rand()%PREPOSITIONS_SIZE]);

  //Capitalize first letter
  sentence[0] = toupper(sentence[0]);

  return sentence;
}

int main(int argc, char* argv[]) {
    srand(time(NULL));

    for(int i = 0; i < MAX_SEN; i++) {
        char* sentence = generateSentence();
        printf("%s.\n", sentence);
        free(sentence);
    }

    return 0;
}

Requires C99. (-std=c99 on gcc)


Shortest prime number generator we could come up with?

0. Quick comments on your code

Clearer function names and
variables in your code. What does p mean, and what is s? I can
guess, but please.
Include a docstring or some indication of what your code does
Use the  if __name__ == "__main__": module.

I did some quick speed comparisons of your function which you can see below.

magic1            21.9095528103 ms
magic2            26.5589244423 ms
Joseph Farah    1030.95786404   ms

I did 10 runs with primes up to \$2\$ million. Now note the big gap between the optimized functions and yours. Even if you were to speed up your code tenfold you would still be 10 times slower than the other functions.

  You can add as many horses you want to your cart, but it will never beat a ferrari.

With this in mind i propose three solutions

Implement a better algorithm
Use Import
Give up

1. New algorithm

Wikipedia can shed some light on how to find larger primes.

  For the large primes used in cryptography, it is usual to use a
  modified form of sieving: a randomly chosen range of odd numbers of
  the desired size is sieved against a number of relatively small primes
  (typically all primes less than \$65,000\$). The remaining candidate
  primes are tested in random order with a standard probabilistic
  primality test such as the Baillie-PSW primality test or the
  Miller-Rabin primality test for probable primes.

So in short you use for an example Wheel factorization to find possible primes, then use the Rabin_primality_test to test whether the candidates are primes. Without going too technical the Rabin_primality_test is a probabilistic test. If the function returns True p might be prime, if False we are guaranteed it is not. If n is composite then the Miller–Rabin primality test declares n probably prime with a probability at most \$4^{−k}\$. A friend told me banks used tested primes 80 times. The chances of a composite number passing \$80\$ tests is \$4^{-80}\$ which is in incredibly low number.

A comparison of many different sieves and ways to find primes can be found here https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n. I used the fastest one on my machine primesfrom2to to generate the results above

import numpy as np
def magic1(n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)
    sieve[0] = False
    for i in xrange(int(n**0.5)/3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[      ((k*k)/3)      ::2*k] = False
            sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False
    return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]

2. Use Import

Python is magical in the sense that you can find libaries which pretty much do anything. The best part is that installing new packages is easy as \$\pi\$. There are many libaries for primes, I will mention a few below

primesieve
primefac
pyprimesieve

primesieve] is Python bindings for the primesieve C++ library. It can generate list of primes at an incredible speed, and also has fast nthprime implementation. primefac is incredibly good at factoring primes, it can also generate primes, but is rather slow. pyprimesieve
has functions such as prime_sum and has many nifty specialized functions.

So if you want a golfed answer the best you can get in terms of speed is

from primesieve import generate_primes

if __name__ == '__main__':

    print generate_primes(2*10**6)

3. Give up

Even if you are in your prime finding and generating large primes are incredibly hard. However this is a good thing as primes are incredibly important in internet security. If by some miracle you were to find an incredibly, incredibly fast prime generator it would break all the large banks and make payments over the net unsafe.

So perhaps it is a good thing your code is slow ;)


main

On very first lines of main you test for provided enviroment variables and write error message to stdout if any are missing. It is more common to write error messages to stderr. stdout is for main program output (none in your case).

You can write to stderr with io.Stderr:

io.WriteString(os.Stderr, "You need to supply output file and hash to serve application.\n")
os.Exit(1)

Note: os.Exit won't call any deferred functions

You can read more about stdout and stderr usage at Stack Overflow and in this article.

In a for loop you start a routine to handle each new connection separetly, so nothing will block. But one line before the go handleMessage(conn) you write to conn with io.WriteString. This is blocking I/O operation and in some cases it may block for a long time.

I suggest you to move all interactions with new conn to a separate routine.

handleMessage

handleMessage function is an entry point for routine that handles new connections. Instead of calling conn.Close() multiple times across different functions consider using a defer statement:

function handleMessage(conn net.Conn) {
    defer conn.Close()
    // function body goes here
}

This way when handleMessage function returns or panics the conn will be closed.

buffer := make([]byte, 1024)

You allocate 1024 bytes long buffer to read provided input from conn. If selected hash value is greater then 1024 you won't be able to read it and all connections will fail with non matching hashes.

buffer := make([]byte, len(SECRET_HASH))

You call conn.Read method to read provided input. The Read documentation states only specific details, to find out more let's see io.Reader interface documentation.

Some highlights:

  Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

As stated by documentation Read method can return too early. To handle this let's use io.ReadFull, which returns error only when fewer bytes were read.

_, err := io.ReadFull(conn, buffer)
if err != nil {
    // handle error
}

printFromFile

Reading whole file into memory has several pitfalls:

files larger than availiable memory won't be processed
on large number of concurent connections program will use lost of memory

To resolve this issues you may use io.Copy. It will read file in small chunks and write it directly to conn until EOF or error happens. nil error value indicates all gone fine.

func printFromFile(conn net.Conn) {
    file, err := io.Open(OUTPUT_FILE)
    if err != nil {
        // handle error
    }
    defer file.Close()

    _, err = io.Copy(conn, file)
    if err != nil {
      // handle error
    }
}

Example rewrite

package main

import(
    "io"
    "log"
    "net"
    "os"
)

var (
    outputFile = os.Getenv("OUTPUT_FILE")
    hash = os.Getenv("SECRET_HASH")
)

func handleConn(conn net.Conn) (err error) {

    defer conn.Close()

    _, err = io.WriteString(conn, "Please type unique identifier:")
    if err != nil { return }

    buf := make([]byte, len(hash))

    _, err = io.ReadFull(conn, buf)
    if err != nil { return }

    if string(buf) != hash {
        _, err = io.WriteString(conn, "Invalid hash\n")
        return
    }

    file, err := os.Open(outputFile)
    if err != nil { return }
    defer file.Close()

    _, err = io.Copy(conn, file)
    return
}

func main() {

    if len(outputFile) == 0 || len(hash) == 0 {
        io.WriteString(os.Stderr, "You need to supply output file and hash to serve application.\n")
        os.Exit(1)
    }

    ln, err := net.Listen("tcp", ":8080")
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    defer ln.Close()

    for {
        conn, err := ln.Accept()
        if err != nil {
            log.Println(err)
            continue
        }

        go func(conn net.Conn) {
            err := handleConn(conn)
            if err != nil {
                log.Println(err)
            }
        }(conn)
    }
}

Points of interest:

simplified error handling
less functions (main, handleConn)
less memory usage
less number of imported packages


Check if any of the coordinates are within a certain distance using apply in Python pandas with two data frames

You need to drop your use of geopy. So far as I can see it does not support vectorised inverse geodesics. Instead use cartopy which inherently supports this.
The following example code uses random instead of real data, but with the same size as your real data, and completes in about one second. distances and close are both matrices whose rows correspond to vessels and columns correspond to ports. close is a matrix of booleans for vessel-port pairs that are proximate.
import numpy as np
from cartopy.geodesic import Geodesic
from numpy.random import default_rng

N_VESSELS = 4_800
N_PORTS = 137

rand = default_rng(seed=0)

vessels = rand.random((N_VESSELS, 2)) + (1, -51)
ports = rand.random((N_PORTS, 2)) + (1, -51)
source = vessels.repeat(N_PORTS, axis=0)
dest = np.tile(ports, (N_VESSELS, 1))

geo = Geodesic()
distances = geo.inverse(source, dest).base[:, 0].reshape((N_VESSELS, N_PORTS))
close = distances < 3_000


CPU Load Bug: Wrong Usage of Timer and repaint()

repaint() calls paintComponent(). The way your code is written, your Java program is repainting all the time, consuming a CPU core completely. Instead it should repaint only when a change happens, and that is if the user changed the color or the timer was triggered. The call to repaint() should not be in paintComponent() but in actionPerformed().

It also means that the call to date() is in the wrong method. While it works being in paintComponent(), it should actually be in actionPerformed() - the timestamp shall be updated when the timer expires, not when the paint happens, because painting might happen much more frequently.

Remove unused symbols

Your fields button and time are not used and their initializations involve no (relevant) side-effects, you can remove them completely.

Fields should be private

All your fields are public. Fields should be private. Technically you can make public fields, but that's considered bad design: It violates data hiding, one of the fundamental principles of object-oriented design. The consequence would be a breach of encapsulation and cohesion with too tight coupling to internals.

Prefer delegation over inheritance (and follow LSP)

It's often misunderstood that inheritance is at the core of OOP. It's not. What's at the core of OOP is polymorphic abstraction. Inheritance is the cream on top of it, and just as too much cream isn't healthy for the body, too much inheritance is not healthy for a design.

Using inheritance can also lead to a violation of the LSP - Liskov Substitution Principle. Subclasses are to be able to replace their superclasses in all cases. But your Clock class cannot be used or extended by yet another class to get an even more specialized version of a Window (or Frame or JFrame) in a meaningful way.

Another sign of wrong inheritance is that your class Clock does not add any behavior to its base class JFrame.

So, instead, you should not inherit from JFrame but just use a JFrame in your main method.

Also, pick the right superclass: Use JComponent instead of JPanel.

Your ScreenSaver is actually not a JPanel. A JPanel is a component designed to be a container with a layout for reuse. What you want as superclass is JComponent. You have multiple components, and that's possible with JComponent, but you don't want anyone to take your ScreenSaver and mess around with its LayoutManager and its contained components.

Think of data structures for replacing switch case - OCP

switch case you might ask? You have a long chain of if else which is just a switch case in disguise. In this case, it could easily be replaced by a Map<String, Color>. You could even use that map to initialize the JComboBox.

This is also related to a principle known as OCP - Open Closed Principle. It was first described by Bertrand Meyer and is one of the first five principles of object-oriented class design collected by Robert C. Martin. It says that, when a new feature needs to be implemented, a class (or actually any software entity on its level of abstraction) should be open for extension but closed for modification. It can also be seen as a special case of the SRP - Single Responsibility Principle: a class (or actually any software entity on its level of abstraction) should have only one reason to change. Which is interesting, as in a side track that defines responsibility as reason to change.

Now what is that theoratical babble all about? Imagine you want to add a new color: In your program you have to make a change in two (actually three) places:

The list of items given to the JComboBox,
and the color names actionPerformed() method that selects the color,
and the actual colors in the actionPerformed() method.

That can easily get out of sync. But even worse: There could also be more subtile errors, like in the JComboBox grey being written as "Grey", and in the actionPerformed() method grey being written as "Gray". Such errors can be very difficult to spot.

When you use a single central Map<String, Color>, then in your system there will be only one authority over the information of colors and their display names. Nothing can get out of sync. Much easier to maintain, much less error prone. You could even later easily load this stuff from a file then.

Use verbs for method names

Your method date is a noun. Okay, it can be argued that date actually works very very well as a verb, too. Just maybe not in this context, in this context date is thought of as a noun. So you could use updateDate instead.

Avoid mutable static fields

Mutable static fields are a dangerous source of error. They prevent multiple instances of the class to work properly independent of each other.

You might argue that in this case, there would never be two instances with different values for date and df. It would still be wrong, for two reasons:

You might want to run two instances in the same VM on different clocks (see below for Java 8 datetime API), for example to show different time zones, or just for testing. Then sharing the data between the instances would be wrong.
While the fields are global (once), there still are multiple Timers (one for each instance of Clock).

Reduce scope as much as possible - use local variables.

The variables panel, date and df do not need to be global, you can turn them into local variables of the respective methods.

Put the right amount of code inside the try-Block.

That you initialize font with null, then catch exceptions, which means font might still be null, and then continue using font afterwards, means that the remaining code eventually uses null. null should be avoided as much as possible, and those situations where null cannot be avoided, should be contained and controlled as much as possible.

Load and Initialize Only Once.

You do not need to load the font and register it with the graphics environment every time the component is repainted. It's sufficient to load and register the font once during application startup.

Similarly you do not need to create a new DateFormat every time the Timer calls your actionPerformed() method. It's sufficient to create only one global DateFormat object.

Collapse catch blocks

You can use Java 7 multicatch to collapse multiple catch blocks into one when the code executed for the catch blocks is identical.

try {
    // some code
} catch (Exception1 e) {
    e.printStackTrace();
} catch (Exception2 e) {
    e.printStackTrace();
}

can be replaced with

try {
    // some code
} catch (Exception1 | Exception2 e) {
    e.printStackTrace();
}

Make smaller methods

Your methods are quite big. Ideal methods do only one thing, they do it well and they do it only. For example, loading the font (including registering) is one thing, handling the exceptions in case the font couldn't be loaded, and when it was loaded successfully, setting it for the component, is another thing.

Make the change of color immediate

It feels a bit weird for a user to change the color and not seeing anything happening (until the second expires). For me, a second is a pretty long time. I can type 10 characters in a second, or shoot 3 people in Unreal Tournament when I'm lucky. You could change your program in a way that changes to the color become immediate.

Let Swing keep track of what it can

Swing can keep track of a lot of stuff. Explore the API. Your ScreenSaver is a JPanel. A JPanel is a JComponent. As such, it has font, foreground color and background color. You can just set the font and the color, and the Graphics object for the paintComponent() method will be initialized accordingly.

You might also want to consider simply involving a JLabel.

Add @Override annotation when implementing or overriding methods

This way the tools can help you when you misspell your method name and for example override paintcomponent(Graphics g) instead of paintComponent(Graphics g).

Consider import static

Often, it's plain obvious where static methods and constants are coming from. For example, in your context, it's plain obvious that RED is coming from class Color. In cases where it is plain obvious, import static can help making the source code more terse without losing clarity.

The Timer should only be running while the component is visible

So you should have a ComponentListener which starts the timer in componentShown() and stops the timer in componentHidden().

Refer to static symbols via the declaring class.

It's better to refer to symbols via the declaring class and not via any of the subclasses. For example, EXIT_ON_CLOSE is declared in interface WindowConstants. So it should be referred to as WindowConstants.EXIT_ON_CLOSE and not JFrame.EXIT_ON_CLOSE.

Prefer DISPOSE_ON_CLOSE over EXIT_ON_CLOSE.

It's better to use DISPOSE_ON_CLOSE then EXIT_ON_CLOSE. Yes, it is harder to program correctly with DISPOSE_ON_CLOSE, but that's exactly the intention: When your application doesn't properly stop and exit with DISPOSE_ON_CLOSE, there's a flaw (usually in the threading model). Using EXIT_ON_CLOSE instead of DISPOSE_ON_CLOSE just bypasses that flaw. That can even be error-prone if there is another thread in the application that's still busy doing important stuff (like saving a user's file). That thread would be terminated in the middle of its work.

Prefer main(String... args) over main(String[] args)

That's not really big and important. It's just easier for testing:

With main(String[] args) a no args test-call is main(new String[0]).
With main(String... args) a no args test-call is simply main().

Consider using final for variables as much as possible

It helps reducing programming mistakes and drives you towards the functional programming paradigm.

Split ScreenSaver in 2-3 classes

Actually ScreenSaver is doing more than one thing. It's displaying the date in a color of the user's liking, and it's enabling the user to pick the color of their liking. While initially it requires some thought of how to split this, in the end the code will become simpler if you achieve this.

Names: Is ScreenSaver really a screen saver? And is the Clock really a Clock?

Also, I would avoid using names that are in the API already, and there already is a class called Clock in the API. It isn't always possible (and sometimes not even intended) to avoid name-clashes, obviously. Just a thought.

Use Java 8 Date API

The classes Date, Calendar and such are actually horrible, and code that uses them is difficult to test.
You may consider using the new Java 8 API for datetimes, java.time.
It is really awesome.

Calling deriveFont() the right way

In case your font couldn't be loaded, the default font will have the default size instead of 30pt.
I think that's not intended.
It's better to call setFont(...) and then derive the font by setting it again using setFont(getFont().deriveFont(30f)).

Use the correct thread for the job

The setup of your application runs in the main thread. Ideally, modifications (and even reads) on Swing components happen only on the AWT Event Thread, unless the method that's called is explicitely documented as being thread-safe.

In your case it will probably not matter. But it's still safer and best practice to even create the UI not in the main thread but on the AWT Event Thread. The class SwingUtilities provides the methods invokeAndWait() and invokeLater() for that.

Your main() method could look like this:

public static void main(String... args) {
    SwingUtilities.invokeLater(() -> {
        JFrame frame = new JFrame();
        frame.setContentPane(new ScreenSaver());
        frame.setSize(685, 80);
        frame.setUndecorated(true);
        frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        frame.setBackground(Color.BLACK);
        frame.setResizable(false);
        frame.setVisible(true);
        frame.toFront();
    });
}

Or, putting the code for setting up the UI in a separate method, like this:

public static void main(String... args) {
    SwingUtilities.invokeLater(Clock::setupUI);
}

private static void setupUI() {
    JFrame frame = new JFrame();
    frame.setContentPane(new ScreenSaver());
    frame.setSize(685, 80);
    frame.setUndecorated(true);
    frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    frame.setBackground(Color.BLACK);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.toFront();
}

Last but not least

Consider testing your application.
The most popular test frameworks (test runners) for Java probably are JUnit, Cucumber and TestNG.


VBA code to import data, doing lookups to detect duplicates

This should be twice as fast:

dlr = wb1.Worksheets("INPUT_DATA").Cells(Rows.Count, 1).End(xlUp).Row
wb1.Worksheets("INPUT_DATA").Range("A2:S" & dlr).ClearFormats

'check duplicate values before import to TOTAL_DATA
    Tlr = wb1.Worksheets("TOTAL_DATA").Cells(Rows.Count, 1).End(xlUp).Row
    countMatch = 0
    countUnmatch = 0

For cell = 2 To dlr
    Cells(cell, 20).Formula = "=CONCAT(RC[-19], ""__"",RC[-18])"

    Cells(cell, 21).Formula = "=IF(ISNA(VLOOKUP(RC[-1],TOTAL_DATA!C30,1,FALSE)), ""No"", ""Yes"")"
    If Cells(cell, 21).Value = "Yes" Then
        Cells(cell, 20).Font.Color = vbRed
        countMatch = countMatch + 1
    Else
        Range("A" & cell, "T" & cell).Cut Destination:=wb1.Worksheets("TOTAL_DATA").Range("A" & Tlr + 1)
        Tlr = Tlr + 1
        countUnmatch = countUnmatch + 1
    End If
Next cell

Because in here we loop only once from 2 to dlr.


Determining a salary for buying a house in 36 months

I don't think your code is an inefficient bisection search.  The example which needed fewer iterations could simply be getting lucky and getting within the $100 terminal condition on one of its earlier steps.  That said, here are a couple of implementation pointers:
Don't recalulate salary
The salary used in the loop, increases every six months.  But it does not change based on savings rate, so is the same for every guess.  Therefore calculate it once before starting the guessing.  It could look something like this:
monthly_salary = [annual_salary / 12]
for month in range(2, 37):
    monthly_salary.append(monthly_salary[-1])
    if month % 6 == 1:
        monthly_salary[-1] *= (1 + semi_annual_raise)

Or using itertools, something like this:
import itertools as it
import operator
salaries = [annual_salary / 12] + [1 + semi_annual_raise] * 5
monthly_salaries = list(it.chain.from_iterable(
    (x,) * 6 for x in it.accumulate(salaries, operator.mul)))

Consider using itertools.accumulate()
The loop which sums up the savings can be done using itertools.accumulate().  Basically you define a function which is passed the previous total and an element from an iterable.  Then returns the next total.
def accum(total, salary):
    return total * (1 + r / 12) + salary * portion_saved

Then the function, and an iterable is passed to accumulate:
*_, current_savings = it.accumulate(monthly_salaries, accum)

Finally the *_, current_savings = ... can be used to gather the last item in an iterable.
The *_ is rather cryptic.  The _ is just a variable name that is often used in Python to indicate that it is unneeded.  The * is used for variable expansion.  See Pep 448 for more details.
Revamped code:
annual_salary = 150000
total_cost = 1000000
semi_annual_raise = .07
portion_down_payment = total_cost * 0.25
current_savings = 0
r = 0.04
guesses = 0
low = 0
high = 1

import itertools as it
import operator
salaries = [annual_salary / 12] + [1 + semi_annual_raise] * 5
monthly_salaries = [0] + list(it.chain.from_iterable(
    (x,) * 6 for x in it.accumulate(salaries, operator.mul)))

portion_saved = (low + high) / 2
while abs(portion_down_payment - current_savings) > 100:

    def accum(total, salary):
        return total * (1 + r / 12) + salary * portion_saved

    *_, current_savings = it.accumulate(monthly_salaries, accum)

    if current_savings >= portion_down_payment:
        high = portion_saved
    else:
        low = portion_saved

    portion_saved = (low + high) / 2
    guesses += 1

print(portion_saved, guesses)


Simplify

In this loop, the loop condition is practically useless:

while(temp1 != 0 && temp2 != 0)
{
    if(temp1->data <= temp2->data){
        head->next = temp1;
        head = temp1;
        if(temp1->next != NULL)
            temp1 = temp1->next;
        else{
            head->next = temp2;
            break;
        }
    }
    else{
        head->next = temp2;
        head = temp2;
        if(temp2->next != NULL)
            temp2 = temp2->next;
        else{
            head->next = temp1;
            break;
        }
    }
}

The statements before the loop have already checked that temp1 and temp2 are not null. So the condition will be true for the first time.
Then in each cycle, you check if the next value of temp1 or temp2 will be null and if yes then break out. So you could as well change the loop condition to while (true), and the program will still work.

But instead of doing that,
it would be simpler to move those checks out of the loop body,
and let the loop condition be useful:

do {
    if (temp1->data <= temp2->data) {
        head->next = temp1;
        head = temp1;
        temp1 = temp1->next;
    } else {
        head->next = temp2;
        head = temp2;
        temp2 = temp2->next;
    }
} while (temp1 != NULL && temp2 != NULL);

head->next = temp1 != NULL ? temp1 : temp2;

Taking it one step further, head can be updated outside of the if-else, like this:

do {
    if (temp1->data <= temp2->data) {
        head->next = temp1;
        temp1 = temp1->next;
    } else {
        head->next = temp2;
        temp2 = temp2->next;
    }
    head = head->next;
} while (temp1 != NULL && temp2 != NULL);

head->next = temp1 != NULL ? temp1 : temp2;

You have this comment:

//temp1 should always point to head with smaller value

Nope, not really! This would work just as well:

if(headA->data <= headB->data) {
  originalHead = headA;
} else {
  originalHead = headB;
}
temp1 = headA;
temp2 = headB;

Memory management

You created a new Node for head, but you forgot to delete it.

Suggested implementation

Some further simplifications and improvements are possible:

No need to check if one of the heads are null. It's possible to rewrite using a dummy a node to handle such cases naturally without special treatment
The variable names can be improved

Implementation:

Node* MergeLists(Node *headA, Node* headB)
{
    Node *dummy = new Node();
    Node *node = dummy;

    Node *nodeA = headA;
    Node *nodeB = headB;
    while (nodeA != NULL && nodeB != NULL) {
        if (nodeA->data <= nodeB->data) {
            node->next = nodeA;
            nodeA = nodeA->next;
        } else {
            node->next = nodeB;
            nodeB = nodeB->next;
        }
        node = node->next;
    }

    node->next = nodeA != NULL ? nodeA : nodeB;

    Node *head = dummy->next;
    delete dummy;
    return head;
}


Here are some things that may help you improve your code.

Fix the bug

Once memory is freed, it should not be referenced again.  Unfortunately, your code allocates memory and then frees it and then returns a pointer to the freed memory.  That's a serious bug!  To fix it, simply omit the free within the function and make sure the caller calls free instead.  Alternatively, you could avoid all of that by reversing the passed string in place.

Use the required #includes

The code uses strlen which means that it should #include <string.h> and malloc and free which means that it should #include <stdlib.h>.  It was not difficult to infer, but it helps reviewers if the code is complete.

Use const where practical

In your revere_string routine, the string passed into the function is not and should not be altered.  You should indicate that fact by declaring it like this:

char* reverse_string(const char* string)

Check for NULL pointers

The code must avoid dereferencing a NULL pointer if the call to malloc fails.  The only indication that it has failed is if malloc returns NULL; if it does, it would probably make most sense to immediately return that NULL pointer.

Learn to use pointers instead of indexing

Using pointers effectively is an important C programming skill.  This code could be made much simpler by doing an in-place reversal of the passed string and by using pointers:

char* reverse_string(char* string) {
    if (string == NULL)
        return string;
    char *fwd = string;
    char *rev = &string[strlen(string)-1];

    while (rev > fwd) {
        char tmp = *rev;
        *rev-- = *fwd;
        *fwd++ = tmp;
    }
    return string;
}


Your code should be as similar to the spec as possible so:

else if (numHours >19)
     garageCost = 10;

Should be removed and you should add:

return Math.min(garageCost, 10)

My final version is:

public static double calculateCharges (double numHours)
{
    if (numHours <= 3)
    {
         return 2;
    }
    double garageCost = 2.0 + 0.5 * (numHours - 3);
    return Math.min(garageCost, 10);
}


UI

Instead of a number input, a range input could be used - with the minimum value being zero and the maximum value being half of the lesser of the height and width - in this case 88 pixels (i.e. 175px / 2). With such an input there is no need to validate user input to ensure non-numeric characters are entered.

With the current interface, the event handler that fires when a key is pressed does not execute when the value changes from other means (e.g. mouse click). To be thorough, it might be better to observe the change event on the input as well.

Code

The JavaScript code makes good use of const for values that don't get re-assigned, and uses getElementById() (as I mentioned in a review of your Nav scroll code). I like how the constant for the warning time is in all capitals, and all lines are terminated with a semi-colon.

The regular expression could be simplified slightly to use the shorthand character class \d instead of [0-9].


Some of the numbers might seem plucked out of thin air but they aren't

Still better have them explained. I can understand 3.6 and even 19.6 (it is \$2g\$, isn't it?), but I have no idea what 98/490 stands for. Declare them as symbolic constants with meaningful names.
I don't see a need for abs in

    reaction_time = round(abs(diff.total_seconds()), 2)

Here diff may not be negative. If it is, I'd rather throw an exception, because the result is meaningless anyways.
You are rounding too early. There is no penalty computing Rt with reaction time not being rounded, but rounding leads to loss of precision. Only round when printing results.
You have too many parenthesis. Sd = Bd + Rd is much cleaner than Sd = ((Rd)+(Bd)).


Representation of the formula P(n) = (n!)(6^n) in C

Because the result is on the order of \$10^{34}\$, as you have correctly noted, even a double will not be able to accurately represent all digits of such a large result.  We know this because it would take
$$\frac{34}{\log_{10}2} \approx 113 \text{ bits}$$
to represent such a result, and a double isn't that large on any architecture you're likely to be using.

This then requires that we resort to multiple precision math.  Just as with multiple-digit multiplication you learned when you were very young, multiple-precision multiplication is the same principle: multiply digit by digit, adding the carry from the previous result.  In this sample code, rather than having a "digit" be 10, I've chosen 1000 which results in fewer math operations.

// calculate P(n) = (n!)(6^n)
#include <stdio.h>

typedef unsigned int uint;

const uint OVERFLOWVALUE = 1000;

void multiply(uint *a, unsigned adigits, uint b)
{
    uint carry = 0;
    for ( ; adigits; --adigits, ++a) {
        *a = *a * b + carry;
        if (*a >= OVERFLOWVALUE) {
            carry = *a / OVERFLOWVALUE;
            *a = *a % OVERFLOWVALUE;
        } else {
            carry = 0;
        }
    }
}

void print(uint *P, unsigned digits)
{
    // print results
    for (unsigned i = digits; i; --i)
        printf("%3.3u ", P[i-1]);
    putchar('\n');
}

int main()
{
    const unsigned digits = 12;
    uint P[digits];
    // initialize P
    for (unsigned i = 0; i < digits; ++i)
        P[i] = 0;

    uint n=20;

    printf("{n!*n^6, n=%u} = ", n);
    for (P[0] = 1; n; --n) {
        multiply(P, digits, n*6);
    }
    print(P, digits);
}

The result on this machine:

{n!*n^6, n=20} = 008 895 075 211 041 185 783 708 532 080 640 000

This agrees precisely with the Wolfram Alpha result.

More mathematical explanation

The multiply routine multiplies a multiple-precision result pointed to by a with adigits values by single value b.  It does not check for mathematical overflow in its calculations, so we need to be careful about the range.

For calculation purpose, suppose that a uint type has 32 bits.  If we assume that a is well-formed before the calculation, how big can b be without risking numerical overflow?  In this case, the largest number that can be in any "digit" is 1000, so overflow will happen whenever \$b * 1000 > 2^{32}\$.  This implies that to avoid overflow, $$b < \frac{2^{32}}{1000}$$ $$b <= 4294967$$.  With this maximum possible value, the carry value would be 4294, which is greater than 1000, so to be pedantic, the code should actually check each digit before each multiplication to normalize the value.

Without this precaution, however, the calculation is still free from overflow as long as \$(999+6n)6n < 2^{32}\$.  This is a simple quadratic equation, with the largest positive root being just over 10839, so as long as \$n<10839\$ this code will work correctly as is.


The most Pythonic way to do is to define a (reusable) dictionary. Most often this dictionary contains callables, but not necessarily.

The least efficient way to do it, though, is to loop over each possibility as you do. It computes in \$O(n)\$ rather than \$O(1)\$ as a dictionnary can offer. And avoid the capability of short-circuit a succession of if...elif...elif...else can offer.

So, at the very least, use something like

def switch(value, **cases):
    try:
        statement = cases[value]
    except KeyError:
        pass
    else:
        exec(statement)

However, I find that defining the various statements at each call is innefficient. As I said, it's better to be able to define a reusable dictionary. I would also advise against the use of exec and make the function more generic; letting the user decide what to do with the retrived value:

def switch(value, cases, default=None):
    try:
        return cases[value]
    except KeyError:
        return default

Usage being:

PRINT_STUFF = {
    'a': lambda: print("It's a!"),
    'b': lambda: print("It's b!"),
}

switch('a', PRINT_STUFF, lambda: None)()
switch('b', PRINT_STUFF, lambda: None)()
switch('c', PRINT_STUFF, lambda: None)()

But way... This try..except reminds me of something... Oh the dict.get method. So there is really no need for switch:

PRINT_STUFF.get('a', lambda: None)()
PRINT_STUFF.get('b', lambda: None)()
PRINT_STUFF.get('c', lambda: None)()

Or, if you trully insist on using strings rather than real callable objects:

PRINT_STUFF = {
    'a': 'print("It\'s a!")',
    'b': 'print("It\'s b!")',
}

exec(PRINT_STUFF.get('a', 'pass'))
exec(PRINT_STUFF.get('b', 'pass'))
exec(PRINT_STUFF.get('c', 'pass'))


A lightweight CRUD, based on the Table Data Gateway pattern

In list(), because $page is a single-use variable, I don't know that it is worth decrementing.  Perhaps write just one line as:
$offset = ($page - 1) * $limit;

but then again $offset is a single-use variable.  If you prefer the declarative coding style, leave it as is.  Alternatively, you could just write the arithmetic directly in the execute() call.  (either way, don't forget to add the space between offset and limit arguments)
$stmt->execute([($page - 1) * $limit, $limit]);

or because of precedence, you can pre-decrement to avoid parentheses:
$stmt->execute([--$page * $limit, $limit]);

or as stated in comments, "list can internally call listBySql" from @hjpotter92:
public function list(int $page = 1, int $limit = 50): array
{
    return listBySQL("SELECT * FROM `$this->table` LIMIT ?,?", [--$page * $limit, $limit]);
}

Please add the int type declaration to the $id argument in read().  I think that read() can be reduced to this:
return reset($this->listBySQL("SELECT * FROM `$this->table` WHERE `$this->primary`=?", [$id])) ?: null;

because if fetchAll() delivers an empty array, then reset() will return false in which case the Elvis operator can return the desired null value.  This is more of a style preference alternative rather than a functional gain -- the only real benefit is removing the $ret variable.

I would prefer that update() return int instead of void (even if your demo doesn't seek this information).  In my projects, I always return the number of affected rows.  This is integral in knowing if the query was actually successful in making changes or if there were no changes from the valid query.  I find this to be as important as insert() returning the new id.

Please add the array type declaration on $data in insert() and remove the blank line after returning the new id in insert().

Please add the int type declaration on $id in delete().

There is some inconsistency regarding when you declare a $sql variable and when you write the sql string directly into the prepare() call.  I think you should pick one style or the other.  My leanings, of course, bias toward removing single-use variables.

validate()'s incoming argument should have an array type declaration.  The implode() call in the thrown exception could use some glue -- a comma at minimum.


Find the date for the nearest day of the week, in this case Fri & Sat

I think dateOfNearestDay would be more intuitive and useful if it would return the date object,
after all you are dealing with dates here. This would also simplify the caller code, who now works with a date object instead of an array.

Keep a separated method to format the date the way you want to and you are good to go.
Besides of this two things you wrote nice code overall.

(function() {

  var startingDate = new Date();

  function dateOfNearestDay(startingDate, nearestDay) {
    var nearestTime = new Date(startingDate.getTime());

    if (startingDate.getDay() == 6 && nearestDay == 5) {
        nearestTime.setDate((startingDate.getDate() +
           (7 + nearestDay - startingDate.getDay()) % 7) - 7);
    }
    else {
        nearestTime.setDate(startingDate.getDate() +
           (7 + nearestDay - startingDate.getDay()) % 7);
    }

    return nearestTime;
  }

  function getMonthAndDay(date){
      var monthNames = ['January', 'February', 'March', 'April',
      'May', 'June', 'July', 'August', 'September',
      'October', 'November', 'December'];

      return monthNames[date.getMonth()]+ " " + date.getDate();
  }

  var nearestDateFriday = dateOfNearestDay(startingDate, 5);
  var nearestDateSaturday = dateOfNearestDay(startingDate, 6);

  var fridaysDate = document.getElementById('fridaysDate');
  var saturdaysDate = document.getElementById('saturdaysDate');

  fridaysDate.textContent = getMonthAndDay(nearestDateFriday );
  saturdaysDate.textContent = getMonthAndDay(nearestDateSaturday );

}());


Optimize K-Mean for large number of clusters

First, some Python improvements. You do repeated lookups of the kind cluster_dict[cluster]. If you were to directly iterate over cluster_dict.values() these would all be not needed. Also, list comprehensions are usually faster than building a simple list with a for loop. And finally, docstrings go inside the function:
def update_center(self, cluster_dict):
    """Gives new centroids with each new iteration."""
    cluster_center = []

    for cluster in cluster_dict.values():
        cluster_list = [self.arr[sample] for sample in cluster]

        # Mean of samples in a given cluster.
        cluster_mean = np.mean(np.array(cluster_list), axis=0).tolist()

        # Find which sample is closest to mean of cluster.
        smallest_distance_from_mean = np.argmin([self.distance(cluster_mean, sample)
                                                 for sample in cluster_list])

        # Build an updated list of cluster centers.
        cluster_center.append(cluster[smallest_distance_from_mean])

    return cluster_center

Another small improvement is not to calculate the sqrt in your distance function, since you only ever need the minimum value, so the squared values work just fine.
def distance(self, arr1, arr2):
    """Squared distance between two arrays"""
    return np.sum(np.subtract(arr1, arr2) ** 2)

However, the greatest improvements are probably to be gained by not using lists everywhere, but to use numpy wherever you can:
class KMeans:
    def __init__(self, arr, k):
        self.arr = np.array(arr)
        self.k = k

    def loop_over_centers(self, max_iter):

        # Choose random centroids.
        chosen_centers = np.random.choice(len(self.arr), self.k, replace=False)

        # Iterate till a certain max number of iterations.
        for _ in range(max_iter):

            cluster_dict = defaultdict(list)

            # Assign samples to cluster centers based on minimum distance
            centers = self.arr[chosen_centers]
            for i, sample in enumerate(self.arr):
                closest_center = np.argmin(np.sum((centers - sample)**2, axis=1))
                cluster_dict[chosen_centers[closest_center]].append(i)
            chosen_centers = self.update_center(cluster_dict)

        return cluster_dict

    def update_center(self, cluster_dict):
        """Gives new centroids with each new iteration."""
        cluster_center = []

        for cluster in cluster_dict.values():
            samples = self.arr[cluster]
            # Mean of samples in a given cluster.
            cluster_mean = np.mean(samples, axis=0)
            closest_sample = np.argmin(np.sum((samples - cluster_mean)**2, axis=1))
            cluster_center.append(cluster[closest_sample])

        return cluster_center

Your code takes 391 ms ± 21.7 ms on my machine, the first two changes drop this down to 340 ms ± 15.9 ms and the final change to 145 µs ± 588 ns, faster by a factor 2700!
You could go even further by doing this part without the for loop using only array operations as well:
        for i, sample in enumerate(self.arr):
            closest_center = np.argmin(np.sum((centers - sample)**2, axis=1))
            cluster_dict[chosen_centers[closest_center]].append(i)

However, this will then take k * len(arr) * dim(arr) memory, which may be a bit too much if both are very large.
Note: You can factor out the distance into a function again, I just don't want to rerun the timings...


Testing whether a string contains valid JSON by calling json_decode()

I strongly agree with comment by @Iwrestledabearonce.  When dealing with input, there are normally other means to understand content type (content type headers, additional input fields, or other means to express an explicit contract).  Having forked code paths like this probably means you have a bad design and you should make sure the contract with data source is clear around how to convey what type of data is being passed.  That doesn't mean that the data passed still doesn't need to be validated as hex or JSON input, just that you shouldn't have to rely on performing JSON decoding or regex matching to determine your input data type.

This is especially exacerbated by the fact you mention 1 in 1000 request may have JSON.  Do you really want to perform json_decode() step on all 999 other requests?


Here are some observations and suggestions that may help you improve your code.

Use objects

The program is written much more in the procedural style of C rather than in the object-oriented style of C++.  The list itself could be an object (as could the individual nodes), with most of the procedures as functions of that object.  This would reduce coupling and make the program easier to understand.  Not least, instead of requiring the user to explicitly call deallocateList(), the object's destructor could automatically be called.

Make sure all paths return a value

Both the printNode() and deallocateList() functions claim to return an int but neither of them actually do.  Either return a meaningful int value or change the function signature to void.

Match new and delete

As mentioned in comments to this question, new should be matched with delete and not delete[] which is a different operation.

Use better naming

The function named printNode is not well named.  A better name might be printList since it actually prints the entire list and not just a single node.

Avoid using raw pointers

In modern C++, we don't tend to use raw pointers as much as in C.  Instead, we either use smart pointers or objects.  In this case, I'd say that if you created objects, it would be better to return an object from sumLists() and intToList() rather than a pointer to a node.

Use const where practical

In almost all of your functions, one parameter is a reference to a pointer to an intNode which is the beginning node of a list.  In all cases, that list is unmodified by the function and so can (and should) be declared as const.

Understand references and pointers

Almost all of your functions take an intNode *& as an argument.  I would highly recommend that you use either pointers or references but not references to pointers.

Use nullptr rather than NULL

Modern C++ uses nullptr rather than NULL.  See this answer for why and how it's useful.

Minimize duplication of code

The current append looks like this:

void append(intNode *&s, int n) {
    if (s == NULL) {
        s = new intNode;
        s->num = n;
        s->next = NULL;
    }
    else {
        intNode *nNode = new intNode;
        nNode->num = n;
        nNode->next = s;
        s = nNode;
    }
}

However, most of the code is functionally identical whether s is NULL or not.  I'd rewrite it like this:

void append(intNode *&s, int n) {
    s = new intNode{n, s};
}

Avoid pointless numeric conversions

In the intConversionHelper() routine, we inexplicably have a conversion to float which is then converted back to an int when the value is returned.  Just use int and avoid the conversions.

Rethink your interface

Right now, only numbers that fit in an int are representable within this code, severely restricting the use of the list and functions such as sumLists.  Instead, consider adding digit at a time without converting each list to an int first.