Handler for a control to pan a map in four directions

A few improvements:

replace magic numbers
extract repetition into a function
dynamically calculate dimensions

Example code:

function getDelta(clickPoint, controlDimension, threshold){
    var delta;
    if (clickPoint < threshold) {
        delta = +1;
    } else if (clickPoint > controlDimension- threshold) {
        delta = -1;
    } else {
        delta = 0;
    }
    return delta;
}

$(document).ready(function () {
    var control = $('#example');
    var controlHeight = control.height();
    var controlWidth = control.width();
    var widthThreshold = controlHeight/3;
    var heightThreshold = controlWidth/3;

    $(control).click(function (evt) {
        var clickPointX = (evt.layerX || evt.offsetX);
        var clickPointY = (evt.layerY || evt.offsetY);
        var deltaX = getDelta(clickPointX, controlWidth, widthThreshold);
        var deltaY = getDelta(clickPointY, controlHeight, heightThreshold);
        alert('delta x: ' + deltaX + '\n' + 'delta y: ' + deltaY);
        //map.panDirection(deltaX, deltaY);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<html>
    <div id='example' style='background-color: red; height: 50px; width: 50px;' />
</html>


Spacing

At first glance, it looks like you're creating a bunch of variables instead of creating an object and passing default parameters. You should reduce all this extra spacing to make it clear what you're doing. Have a look:

user = self.model(
    user_email=self.normalize_email(email),
    user_name=username,
    first_name=f_name,
    last_name=l_name
)

This goes for both of the places where you do this.

According to PEP 8 there should only be one space before and after the = operator. The issue with how you're creating variables is that all that spaces requires the reader to keep they're gaze straight and follow the line to make sure they know what is being assigned to what. Here's an example in your code:

user_email                  = models.EmailField(max_length = 120, unique = True)
user_name                   = models.CharField(max_length = 40, unique = True)
first_name                  = models.CharField(max_length = 60)
last_name                   = models.CharField(max_length = 60)
date_joined                 = models.DateTimeField(auto_now_add = True)
last_login                  = models.DateTimeField(auto_now = True)
is_admin                    = models.BooleanField(default = False)
is_active                   = models.BooleanField(default = True)
is_staff                    = models.BooleanField(default = False)
is_superuser                = models.BooleanField(default = False)

All this spacing really isn't necessary.

Parameter spacing is also an issue in your code. Contrary to the suggestions above, there should be no spaces when passing default parameters. Have a look:

user_email = models.EmailField(max_length=120, unique=True)
def has_perm(self, perm, obj=None):
user.save(using=self._db)

Type Hints

You can use type hints to display what types of parameters are accepted and what types are returned by a function. Have a look:

def create_superuser(
    self,
    email: str,
    username: str,
    f_name: str,
    l_name: str,
    password: str
) -> User:


Go program to find duplicated files in a directory (recursively)

1. declare all 'var' at once

instead of

var dir string
var workers int

you can do

var (
    dir string
    workers int
)

or even better, use local var instead of global var irectly in your main() function

dir := flag.String("dir", ".", "directory to search")
workers := flag.Int("workers", runtime.NumCPU(), "number of workers")

2. Make sure that arguments are valid

if worker is <= 0, the program will panic. A little check after flag.Parse() could prevent this:

if workers <= 0 {
    fmt.Printf("workers has to be > 0, was %d", workers)
}

3. Improve hash computing:

First, each worker only need a single instance of hash.Hash, as you can call Reset() on it after each file:

h := sha256.New()
for file := range input {
    ...
    results <- &Result{...}
    h.Reset()
}

Also, the hash of each file could be stored as a string instead of a [32]byte to avoid some operations:

results <- &Result{
    file:   file,
    sha256: fmt.Sprintf("%x", h.Sum(nil)),
}

4. Always specify the channel direction when you can

From the golang specifications:

  A channel provides a mechanism for concurrently executing functions
  to communicate by sending and receiving values of a specified element
  type. The value of an uninitialized channel is nil.

  ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType .

  The optional <- operator specifies the channel direction, send or
  receive. If no direction is given, the channel is bidirectional. A
  channel may be constrained only to send or only to receive by
  conversion or assignment.

Specify the channel direction helps understand what a method is doing

Here is the new version of the code:

package main

import (
    "crypto/sha256"
    "flag"
    "fmt"
    "io"
    "os"
    "path/filepath"
    "runtime"
    "sync"
)

type Result struct {
    file   string
    sha256 string
}

func search(dir string, input chan<- string) {
    filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
        } else if info.Mode().IsRegular() {
            input <- path
        }
        return nil
    })
    close(input)
}

func startWorker(input <-chan string, results chan<- *Result, wg *sync.WaitGroup) {
    h := sha256.New()
    for file := range input {
        f, err := os.Open("file.txt")
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            continue
        }
        if _, err := io.Copy(h, f); err != nil {
            fmt.Fprintln(os.Stderr, err)
            f.Close()
            continue
        }
        f.Close()
        results <- &Result{
            file:   file,
            sha256: fmt.Sprintf("%x", h.Sum(nil)),
        }
        h.Reset()
    }
    wg.Done()
}

func run(dir string, workers int) (map[string][]string, error) {

    input := make(chan string)
    go search(dir, input)

    counter := make(map[string][]string)
    results := make(chan *Result)
    go func() {
        for r := range results {
            counter[r.sha256] = append(counter[r.sha256], r.file)
        }
    }()

    var wg sync.WaitGroup
    wg.Add(workers)
    for i := 0; i < workers; i++ {
        go startWorker(input, results, &wg)
    }
    wg.Wait()
    close(results)

    return counter, nil
}

func main() {

    dir := flag.String("dir", ".", "directory to search")
    workers := flag.Int("workers", runtime.NumCPU(), "number of workers")
    flag.Parse()

    if *workers <= 0 {
        fmt.Printf("workers has to be > 0, was %d \n", workers)
        os.Exit(1)
    }
    fmt.Printf("Searching in %s using %d workers...\n", *dir, *workers)

    counter, err := run(*dir, *workers)
    if err != nil {
        fmt.Printf("failed! %v\n", err)
        os.Exit(1)
    }

    for sha, files := range counter {
        if len(files) > 1 {
            fmt.Printf("Found %d duplicates for %v: \n", len(files), sha)
            for _, f := range files {
                fmt.Println("-> ", f)
            }
        }
    }
}

Possible improvements:

Currently, if an error is thrown somewhere in the code, the program does not stop but just write the error to os.Stderr. It may be better to return this error and then call os.Exit(1)


Counting ambiguous Morse Code encodings, with and without Java Streams

Well, I do not want to be the one always hammering on using Streams, but your second solution was almost immediatly clear to me, whereas the first was not. It does help that with the second one you split it up into methods, a very good thing!

Nontheless, I still think you can improve the second solution:

First, I would save the morse code mapping in a field, as it is really a constant thing.
Second, collecting to a Set is not really necessary. A Stream has a count method, so you can use that. Of course, this will result in a wrong answer, because we only want to count the distinct number of morse code strings. How do we solve it? Call distinct first!
There is really no reason to shorten method names, nor variables. Use clear, useful names. Instead of getMC, use toMorseCode for example.
In this particular case, I think there is a slightly better way to calculate the index out of a character, namely subtracting with 'a', which also has an integer value of 97 but now I think it is perfectly clear what is happening, i.e. 'a' = 0, 'b' = 1, ....

Putting it all together, with a method reference here and a static import there:

import static java.util.Arrays.stream;
import static java.util.stream.Collectors.joining;

public final class Morse {

    private static final String[] CODE_TABLE = {
            ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
            ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
            "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."
    };

    public static long countUniqueMorseRepresentations(final String[] words) {
        return stream(words).map(Morse::toMorseCode).distinct().count();
    }

    private static String toMorseCode(final String string) {
        return string.chars().mapToObj(character -> CODE_TABLE[character - 'a']).collect(joining(""));
    }
}

A short comment about your first approach, using a StringBuilder would be a good thing, because concatenating Strings with + each time builds a new String object, whereas with a StringBuilder, you would only make a new String when you concatenated all parts.

In this very case though, pure performance wise, it might get optimized under the hood to use a StringBuilder anyway.


Find nth Fibonacci Number, using iteration and recursion

Why do most people (on the internet) recommend using recursion because it's simpler and easier to write the program? Logically I thought that we should write it in a way that is fast and simple.

This is a perceptive question.  I wrote an article about exactly this topic in 2004, which you can read here:

https://docs.microsoft.com/en-us/archive/blogs/ericlippert/how-not-to-teach-recursion

Summing up: there are two good reasons to teach people to use recursion to solve Fib:

First, because it clearly illustrates what you have learned today. A naive translation of a recursive definition into a recursive function can often lead to poor performance.  That's an important lesson for beginners to take away. (EXERCISE: How many additions does your naive recursive program execute for a given n? The answer may surprise you.)
Second, because the first lesson then gives us an opportunity to lead the beginner to learn how to write a recursive algorithm so that it performs well.

Unfortunately, as you have discovered, a great many people on the internet have not internalized that teaching recursion via fib is solely useful as an illustration of bad uses of recursion and how to fix them, and not in itself an example of a good use of recursion.

It would be much better if people attempting to teach recursion did so by providing a mix of good and bad recursive algorithms, and taught how to spot and avoid the bad ones.

  Is there a better way than these two methods?

Another lesson you'll quickly learn is that asking "which is better?" is a sure way to get back the reply: "can you describe a clear metric for betterness?"

So: can you describe a clear metric for betterness?

If the goal is to print out the nth fib number, you can do way "better" than either of your solutions:

unsigned long long fibs[] = { 1, 1, 2, 3, 5, 8, ... }
if (0 <= n && n < sizeof(fibs... blah blah blah))
   cout << fibs[n];

Done. There are only so many fib numbers that fit into a long. You can look them up on the internet, copy them into your program, and you've got a short, fast fib program with no loops at all.  That's "better" to me.

But remember, the point of this exercise is to teach you something about recursion, so by that metric my program is certainly not "better".

  are these methods complex?

By "these methods" I think you mean "methods of writing recursively-stated algorithms into code other than naive recursion and unrolling the recursion into a loop".

That's a matter of opinion. Let me put it this way.

I work on a compiler team, and I interview a lot of people. My standard coding question involves writing a simple recursive algorithm on binary trees that is inefficient when written the naive way, but can be made efficient by making a few simple refactorings.  If the candidate is unable to write that clear, straightforward, efficient code, that's an easy no-hire.

Where things get interesting is when I ask "suppose you had to remove the left-hand recursion from this tree traversal; how might you do it?"

There are standard techniques for removing recursions.  Dynamic programming reduces recursions. You could make an explicit stack and use a loop.   You could make the whole algorithm tail recursive and use a language that supports tailcalls. You could use a language with cocalls. You could use continuation passing style and build a "trampoline" execution loop.

Some of these techniques are, from the perspective of the novice, terribly complicated.  I ask the question because I want to know what is in the developer's toolbox.


How to sort and search in JavaScript large set

The following function sort of agrees with your function. Except that for example your function given
scores = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] and alice = [ 0, 0, 0, -1 ] gets 1,1,1,5, while I think it should be 1,1,1,2.
Anyway, it easily handles scores arrays of sizes 10^7 for scores and 10^5 for alice.
The idea is, we already know scores is sorted as per your comment. We can then go through the scores array. We sort the alices array while remembering the original order. Then we go through the scores array, we first look at the largest alice, once we hit an element >= it, it is time to note that down, we remember the score and whether it was a tie and the position it happened at. We continue traversing scores, now looking at the next biggest alice, etc.
At the end of this we know where each alice would be ranked in the original array. Now we just need to account for the rank increases that come from prior alices, basically the rule is, if you are alice 7, then you look at the previous scores from alices 1 to 6 which resulted in a rank increase, and count 1 each time their score was larger than yours. We can do this fairly quickly by maintaining a sorted array of the previous scores using a binary search to find where to insert the next element. Remembering to account for ties amongst Alices scores.
function binarySearch(array, targetValue) {
    if (array.length === 0) {
        return 0;
    }
    let min = 0;
    let max = array.length;
    let guess;

    while (max - min > 1) {
        guess = Math.floor((max + min) / 2);

        if (array[guess] > targetValue) {
            min = guess;
        } else {
            max = guess;
        }
    }

    return array[min] < targetValue ? min : min + 1;
}

function climbingLeaderboard(scores, alice) {
    if (alice.length === 0) {
        return [];
    }
    const sortedAliceWithIndex = alice.map((s, i) => [s, i]).sort(([a], [b]) => b - a);

    let aliceInd = 0;
    let currAlice = sortedAliceWithIndex[aliceInd][0];
    const ranks = [];
    let i = 0;
    let effectiveCount = 0;
    while (true) {
        const currScore = scores[i];
        if (currScore !== undefined && currScore > currAlice) {
            i++;
            if (!(scores[i] === scores[i - 1])) {
                effectiveCount++;
            }
            continue;
        }

        ranks.push([
            effectiveCount,
            sortedAliceWithIndex[aliceInd][1],
            currAlice === currScore,
            currAlice
        ]);
        aliceInd++;

        if (aliceInd >= alice.length) {
            break;
        }
        currAlice = sortedAliceWithIndex[aliceInd][0];
    }

    const inOriginalAliceOrder = ranks.sort(([, i1], [, i2]) => i1 - i2);

    const accountingForRanks = [];
    let rankIncreases = [];
    for (let [i, _, tie, score] of inOriginalAliceOrder) {
        let rankUp = binarySearch(rankIncreases, score);

        if (rankIncreases[rankUp - 1] === score) {
            accountingForRanks.push(i + rankUp);
        } else {
            accountingForRanks.push(i + rankUp + 1);
            if (!tie) {
                rankIncreases.splice(rankUp, 0, score);
            }
        }
    }
    return accountingForRanks;
}

The following runs in a couple of seconds for me.
function main() {
    let scores = new Array(10 ** 6);
    for (let i = 0; i < scores.length; i++) {
        scores[i] = 1 * Math.random();
    }
    scores.sort((a, b) => b - a);
    let alice = new Array(10 ** 5);
    for (let i = 0; i < alice.length; i++) {
        alice[i] = 2 * Math.random() - 1;
    }

    let result1 = climbingLeaderboard(scores, alice);

    console.log(result1);
}


Both arguments should be const char*. It's a search, it shouldn't be able to change str by accident.

Let's have a look at its use, though. Does it really work like strstr?

puts(istrstr("example", "please")); // prints "ple"

istrstr's behaviour completely differs from strstr. The latter will return NULL when the second string isn't completely in the first one. istrstr's name is therefore misleading and should be called istringoverlap or similar.

Unless you're going for performance, I suggest you to go for simplicity and write an additional helper:

/** @brief checks whether @a prefix is a prefix of @a str.
 *
 * @param str    a null-terminated string
 * @param prefix a null-terminated string
 * @returns 1 if @a prefix is a prefix of @a str
 * @returns 0 otherwise
 *
 * The check is case-insensitive.
 *
 * This function yields undefined behavior if tolower() yields undefined
 * behavior for any character in either str or prefix. If @a str
 * or @a prefix is not a null-terminated string, the behavior will be
 * undefined.
*/
int is_iprefix(const char * str, const char * prefix) {
    while(*str && *prefix) {
        if(tolower(*str) != tolower(*prefix)) {
            return 0;
        }
        prefix++;
        str++;
    }
    return (*prefix == '\0');
}

Why would I recommend to write another function? With only seven lines it's easy to check whether we got that right. We can re-use this function if we want to, and we can use it as a building block for our now istrstr variant:

const char * istrstr(const char * str, const char * substr) {
    while(*str) {
        if(is_iprefix(str,substr)) {
            return str;
        } else {            /* not really necessary, since return exits */
            str++;
        }
    }
    return NULL;
}

However, that's not going for maximum performance. If we're really interested in more performance, we have to stop as soon as str is shorter than substr. We can either use strlen and count down, e.g.

const char * istrstr(const char * str, const char * substr) {
    int diff = strlen(str) - strlen(substr);
    while(*str && diff-- >= 0) {
        if(is_iprefix(str,substr)) {
            return str;
        } else {
            str++;
        }
    }
    return NULL;
}

or we can inline is_iprefix and check whether str runs out of characters, but that's left as an exercise. Your code is almost there, by the way, you just need to fix the aforementioned bug.


Both the function name and the docstring are clear and informative. Good job there! However, there are a couple of typos in the examples. The function requires strings as input but the examples use ints. For example time_difference(1100, 1310) should be time_difference('1100', '1310'). A tool like doctest can help you check for mistakes like this automatically.

Generally people don't check the types of arguments in python. You are right to document the types expected by the function but after that I would just use the objects as if they are the right type and let python throw an error if they aren't. I say this because type checking often gets in the way of duck typing and reduces the flexibility and generality of your code. For example, in python 2.x, isinstance(time_start, str) returns False for unicode strings (isinstance(time_start, basestring) is a better alternative).

The try/except is unnecessary as you are simply reraising every exception you catch.

Rather than trying to parse the strings yourself (which is quite error prone as AdHominem pointed out), you can use the datetime library instead.

If we apply these changes the result looks like:

from datetime import datetime

def time_difference(time_start, time_end):
    '''Calculate the difference between two times on the same date.

    Args:
        time_start: the time to use as a starting point
        time_end: the time to use as an end point

    Returns:
        the difference between time_start and time_end. For example:

        >>> time_difference('1500', '1600')
        60

        >>> time_difference('1100', '1310')
        130
    '''

    start = datetime.strptime(time_start, "%H%M")
    end = datetime.strptime(time_end, "%H%M")
    difference = end - start
    minutes = difference.total_seconds() / 60
    return int(minutes)


Storing user permissions to hierarchically structured data in SQL Server

I would only make minor adjustments to your SQL.

Refrain from using KEYWORDS or RESERVED words as column or table aliases. If you already have them as column names, enclose them in square brackets e.g. [Name], [Path]
I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier.
If you put 1=1 at the top of a WHERE condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the 1=1 so it should have no performance impact.
I find it more convenient to see column alias's referenced from the left side
e.g.
, [Path] = CAST(pfdr.[Path] + fdr.[Name] + '/' AS NVARCHAR(4000))
Use a table expression instead of a correlated sub-query. It makes the select statement a bit more readable.
Check the Estimated Execution Plan Ctrl + L in Microsoft SQL Server Management Studio (SSMS) to check the performance of the query by pasting both SQL statements in a query window.

Here's an example.

Revised SQL

WITH
folder_paths
AS
(
    SELECT
          fdr.[Id]
        , fdr.[Name]
        , fdr.[AccountId]
        , f.[ParentFolderId]
        , [Path] = CAST('/' + fdr.[Name] + '/' AS NVARCHAR(4000))
    FROM
        dbo.[Folders] AS fdr
    WHERE
        1=1
        AND (fdr.[ParentFolderId] IS NULL)
    UNION ALL
    SELECT
          fdr.[Id]
        , fdr.[Name]
        , fdr.[AccountId]
        , fdr.[ParentFolderId]
        , [Path] = CAST(pfdr.[Path] + fdr.[Name] + '/' AS NVARCHAR(4000))
    FROM
        dbo.[Folders] AS fdr
        INNER JOIN folder_paths AS pfdr ON fdr.[ParentFolderId] = pfdr.[parent.Id]
)
,
user_folder_permissions
AS
(
    SELECT
          fprm.[UserId]
        , fdr.[Path]
        , fdr.[AccountId]
    FROM
        folder_paths AS fdr
        INNER JOIN dbo.[UserFolderPermissions] AS fprm ON fdr.[Id] = fprm.[FolderId]

)
SELECT
      [FileId] = fs.[Id]
    , fdr.[AccountId]
    , [FolderId] = fdr.[Id]
    , [Path] = fdr.[Path]
    , [AuthorizedUserId] = fprm.[UserId]
FROM
    folder_paths AS fdr
    LEFT JOIN dbo.Files AS fs ON fs.[FolderId] = fdr.[Id]
    LEFT JOIN user_folder_permissions AS fprm ON fdr.[AccountId] = fprm.[AccountId] AND fdr.[Path] LIKE fprm.[Path] + '%'


The indendation looks off - assuming it's not a paste glitch with tabs vs spaces, the scope-opening brace should line up with the method's signature:

public myClassFromXsd excelToMyClassFromXsd(String excelFile)
            {

Like this:

public myClassFromXsd excelToMyClassFromXsd(String excelFile)
{

Also, C# type names should be PascalCase, as well as any public members:

myClassFromXsd should be MyClassFromXsd
serializeXml should be SerializeXml
deserializeXml should be DeserializeXml

The get_Xxxx methods in the COM Interop interface aren't following this convention, but they're COM Interop methods, with their own conventions - they're not an example to follow for typical C# code.

I like that you're wrapping your StreamWriter in a using block. I don't understand why you're not doing the same with the StreamReader in the deserializeXml method - the reader.Close() call could then be removed:

    public myClassFromXsd deserializeXml(String xmlFile)
    {
        myClassFromXsd mcfx = new myClassFromXsd();
        XmlSerializer serializer = new XmlSerializer(typeof(myClassFromXsd));
        using (StreamReader reader = new StreamReader(xmlFile))
        {
            mcfx = (myClassFromXsd)serializer.Deserialize(reader);
        }
        return mcfx;
    }

I would give mcfx a meaningful name: as it stands it looks like it's just a shortened version of the return type's name - I like having a result for these kinds of things. Identifiers should have a pronounceable name that carries their meaning.


Replacing spaces with tabs. Exercise 1-21 in "The C Programming Language"

Welcome to Code Review! I'm always glad to see someone who reads the classics.

You made some interesting observations about the program.

The statement Use more "self-explaining" variable names is absolutely correct: the variable name nb could definitely be improved. I would like to point out that self-documenting might be better than self-explaining.

If the variable and symbolic constant names are improved it may not need any additional comments.

The header file <stdio.h> includes a symbolic constant BUFSIZ that might be a better length than 80. In some cases BUFSIZ may be the maximum line length for the system; this was true on older Unix systems.

Possible Bug

This code seems out of scope for the problem as it is defined, I would expect to see that it was outputing blanks.

            for (; blankCount > 0; --blankCount)
                putchar('x');

A Good Coding Practice

Code needs to be maintained. This may include adding additional lines to control structures such as if statements and loops. In C and C++ a good programming practice is to have code blocks (complex statements) in all if, else and loop statements even if it isn't currently necessary.

if (CONDITION)
{
    one statement
}
else
{
    one statement
}

while (CONDITION)
{
    one statement
}

Alternate Solution with Simplified Functions

It might be easier to read, write and modify entab() if it called a function to count all the blanks and print the necessary tabs and blanks. Programming in many cases is breaking down a problem into smaller and smaller pieces until each piece is easy to implement. While this may make the entire program a little more complex, each function is simplified.

This example uses a concept you haven't gotten to in the book yet called pointers.

void print_tabs_or_spaces(int tab_count, int out_value)
{
    for (int i = 0; i < tab_count; i++)
    {
        putchar(out_value);
    }
}

char* count_blanks_and_output_tabs_and_spaces(char *c)
{
    int blank_count = 0;

    while (*c == ' ')
    {
        ++blank_count;
        c++;
    }
    int tab_count = blank_count / TABSIZE;
    int space_count = blank_count % TABSIZE;

    print_tabs_or_spaces(tab_count, '\t');
    print_tabs_or_spaces(space_count, ' ');

    return c;
}

void entab(char str[])
{
    char *c = &str[0];
    while(*c != '\0')
    {
        if (*c == ' ')
        {
            c = count_blanks_and_output_tabs_and_spaces(c);
        }
        else
        {
            putchar(*c);
            c++;
        }
    }
}


Both of your versions will probably generate the same IL code. See: https://stackoverflow.com/a/7383090/2655508

The first version is still better, because you should declare variables as near as possible to their usage.

You shouldn't shorten variable names. You already have positions[] so why do you have pos instead of position?

You have some magic numbers in your code which should be extracted to some constants with meaningful names.


Calling restful web services efficiently

I think its the API, I've just benchmarked it using

$json = file_get_contents('http://demo.4ds.com/rema/1.1/rules/origins/b2c.json');
$data = json_decode($json);

I only ran 10 attempts but they seem to take between 1 and 5 seconds each.

php test.php  0.03s user 0.01s system 2% cpu 1.574 total
php test.php  0.03s user 0.01s system 1% cpu 3.303 total
php test.php  0.04s user 0.01s system 0% cpu 5.881 total
php test.php  0.04s user 0.01s system 2% cpu 1.646 total
php test.php  0.03s user 0.01s system 2% cpu 1.478 total
php test.php  0.03s user 0.01s system 2% cpu 1.516 total
php test.php  0.03s user 0.01s system 2% cpu 1.590 total
php test.php  0.04s user 0.01s system 1% cpu 3.659 total
php test.php  0.03s user 0.01s system 1% cpu 3.582 total
php test.php  0.03s user 0.01s system 2% cpu 1.526 total


REST apis usually have

GET /products - retrieves all products
GET /products/10 - retrieves product with id 10.

And thus I'd suggest that instead of requesting GET /product?id=10, you do GET /product/10.

Take a look at the URL in your webbrowser - this is GET /questions/119636/.


decode `IEnumerable` to string made of 1 byte characters (eg., ASCII)

Well, I could propose few improvements for you:

Try to use SelectMany instead of just Select;
No need to call ToArray since the string.Concat could consume IEnumerable;

public static string UintArrayToString(this IEnumerable<uint> x) =>
    string.Concat(x.SelectMany(BitConverter.GetBytes).Select(Convert.ToChar));


Naming

I strongly recommend you read through the official C# naming conventions. Here are a few rules to keep in mind:

Properties are UpperCamelCase
Private fields are lowerCamelCase, sometimes prepended with an underscore
Methods are UpperCamelCase
Local variables are lowerCamelCase
Test methods should be descriptive [more information]

Applied to your code, here are a few changes to make:

TestMethod1 -> TimeToWait_WithFiveMinutes_ShouldReturnZero
mycar -> currentCar
lengthbetweenLights -> lengthBetweenLights
getTravelTime -> GetTravelTime

Also keep in mind that your naming should make sense in light of the contest: MyCar does not really make sense in the sense of a Traffic analysis: what if I want to calculate it with someone else's car? Therefore I suggest making it CurrentCar instead.

This is part of the encapsulation I talk about next, but keep in mind that hiding the implementation details by not putting them in the variable's name, is also a form of encapsulation.

Right now you have a variable named LightList which tells me that it concerns a list of lights. Except, I already know it's a list because I can see the type. But what if you want to go more general and make it a ICollection instead? Or you want to group them with the amount of dogs that peed against it: Dictionary<Light, int>. Now your name doesn't fit anymore and you'll have to change it (and make version control ugly).

Methods are actions: you perform an action on the instance. What kind of action is TimeToWait? I would have expected it to be a property from the way it's worded. GetTimeToWait makes it clear that I will receive a value (and just that).

Encapsulation

Definitely read more on the topic of encapsulation, a cornerstone of OO-Programming. Your Traffic class has public fields which are open for modification. By forcing to do this through setters (an auto-generated property is a setter!) you can satisfy encapsulation and force whoever wants to modify it to go through your setter first. This means that you can add validation logic before touching the backing variable.

Instead what you should do is work with a public property like

public Car CurrentCar { get; set; };

[More information on fields and properties]

Events

Traffic lights that get their status updated every second sounds like a good option to put events in here. You could keep counters elapsedTime and switchTime and a flag isGreen so your light can articulate its state to callers. This would make your methods IsGreen() and GetTimeToWait() more intuitive: you don't have to call them with an argument to signify the current time.

Although this might be overdoing the assignment a little bit.


There's not a lot to review here, the only thing that's jumping at me is that this:

@Override
public void start(Stage primaryStage) {
    System.out.println("Hello world");
    Scanner scanner = new Scanner(System.in);
    scanner.nextLine();
    Platform.exit();
    }

Should be indented like this:

@Override
public void start(Stage primaryStage) {
    System.out.println("Hello world");
    Scanner scanner = new Scanner(System.in);
    scanner.nextLine();
    Platform.exit();
}

  Is this the minimum JavaFX code required to do shell?

Well technically printing "Hello world" and waiting for the ENTER key is not needed if what you want is the minimum code. But then, what would your program be doing :-)

  Am I missing something that's gonna bite me down the road (like some kind of object de-referencing: I am very new to JavaFX so I don't have a clue!)

I know nothing of JavaFX, but if garbage collection is anywhere like .net, you have nothing to worry about because AFAICT you're not creating any object that's holding on to a reference that would prevent its garbage collection.

  Is it OK to consider the start method as effectively now my main method?

Probably. But it's not immediately clear what happens to argv.


Move all zeros to the left with TDD approach

TDD is not for finding "elegant" solutions, but for finding working solutions that cover all edge cases. Without edge cases, solutions are often too naive and in the end won't work.

You missed some edge cases; the task states: "order of other elements in the array" (that are integer). How about Infinity and -Infinity? Are they numbers? :) isNaN(Infinity)?

Another thing is, that beauty lies in the eye of the beholder. For me elegant code, is code, that is easy to grasp and not overly complex. Whenever a problem can be solved in such a generic way, that edge case do not need any special handling this is good code. :)

Speaking of which - your problem is clearly about transforming an array - with JavaScript you have a good set of Array.fns() at you disposal and fat arrow functions. Thus I'd intuitively never use loops, but only array functions.

The original problem sounds very constructed to me - I guess some stupid code interview stuff. I guess it is about thinking of how to find zeros in an array and move them around.

However the solution is quite trivial if you are thinking outside the box (which you are!), that with the elements being numbers, the solution is not about moving around zeros (and thus maintain their reference, if it where not zeros but objects), but in filtering and reconstructing them.

const move_zeros_to_left = function(unsortedArray) {
  const numberOfZeros = unsortedArray.filter(item => item === 0).length;
  const nonZeroArray = unsortedArray.filter(item => item !== 0);
  return [...Array.from({length: numberOfZeros}).fill(0), ...nonZeroArray];
}

Covers all the edge cases and is readable. Your provided sample solution is the worst of all solution, because it neglects the fact, that JavaScript has a rich set of Array functions and thus it is neither readable nor idiomatic and I'd say thus not elegant all. :)


Nice script :-)

getstat is a bit odd:

It runs a grep and then a sed, when probably a single sed (or awk) could do the job
It replaces spaces with x, but not very clear why:

I see that extract uses x as the separator, but it could just as well use space for that
I also see that using x as the separator makes the change function slightly simpler, because it lets you write extract $ENDSTAT instead of extract "$ENDSTAT", but then again, having to quote doesn't seem a big problem

In extract, you run an echo and then a cut:

echo $1 | cut -d 'x' -f $2

In bash you can use here strings, which is better than using echo:

cut -d 'x' -f $2 <<< $1

But actually, if we keep the spaces as the separator in getstat, then we can rewrite both of these functions with fewer extra processes:

function getstat() {
    sed -ne '/^cpu  */s/^cpu  *//p' /proc/stat
    # that is:
    # -n to not print lines by default
    # for lines matching /^cpu  */, delete /^cpu  */, and print the line
}

function extract() {
    # example 1st param: "437797 1219 185341 549955584 58662 4 7083 0 0 0"
    # example 2nd param: 1, 2, 3, ... (the n-th column to use)
    n=$2          # saving the position param
    set -- $1     # reset positional params from $1, so that $1=437797, $2=1219, ...
    echo ${!n}    # echo the n-th positional param
}

function change() {
    local e=$(extract "$ENDSTAT" $1)
    local b=$(extract "$STARTSTAT" $1)
    echo $(( $e - $b ))
}


Notice that:

The length of a root must be a divisor of the length of the input string: you could skip other lengths. For example for the input string "abcabcabc" (length = 9), "ab" (length = 2) or "abcd" (length = 4) cannot be a root, so no need to check those
The length of a root must be less than equal to half the length of the input string, otherwise it's the input string itself (frequency = 1)

Taking the above into consideration, this implementation should be faster:

def sroot(text):
    text_len = len(text)
    for segment_len in range(1, text_len // 2 + 1):
        if text_len % segment_len != 0:
            continue
        frequency = text_len // segment_len
        if text[:segment_len] * frequency == text:
            return frequency
    return 1

This can be further improved too.
For example, instead of iterating until text_len // 2,
it would be enough to iterate until math.sqrt(text_len),
and when finding a divisor, also try its factor pair as a possible segment.
For example for text_len = 100,
when finding segment_len = 5,
also try segment_len = 100 / 5 = 20.
Iterating until 10 will be a lot faster than iterating until 50 as in the example implementation above.

There are several coding style issues in your code:

It's good to put the main logic inside a function. It makes it easier to test. For example you can add assertions like this to test your solution:

assert sroot('abcabcabcabc') == 4
assert sroot('abcdefgh012') == 1
assert sroot('aaaaaaaaaa') == 10
assert sroot('abcdefgh012abcdefgh012') == 2
assert sroot('abcdefgh012abcdefgh012x') == 1

Lots of unnecessary parentheses, for example in:

while (inputString !='*'):
if (len(inputString) == 1):

This can be simplified:

 if not scanned_string:
    scanned_string = scanned_string + current_symbol

to this:

 if not scanned_string:
    scanned_string = current_symbol

This can be simplified:

matched_characters = matched_characters + current_symbol

to this:

matched_characters += current_symbol


Computing even huger Fibonacci numbers in Java

public static String fibonacci(int n) {

Why? It makes far more sense for this method to return a BigInteger.

        if (n < 0) {
            throw new IllegalArgumentException(
                    "The (" + n + ")th Fibonacci number is not defined.");
        }

Negative-index Fibonacci numbers are perfectly well defined, so this error message is misleading. You could change the error message to something like "Negative indexes are not supported", but you might as well change the code to support them. It's just a case of negating n and using initial matrix [[0 1][1 -1]].

        switch (n) {
            case 0:
                return "0";

            case 1:
                return "1";
        }

I can understand having a special case for 0 because it saves you a special case in the matrix power code, but why the special case for 1?

    private static BigInteger[][]
        fibonacciMatrix(BigInteger[][] matrix, int n) {

The name of this method makes no sense to me. Why isn't it called pow or matrixPower?

        if ((n & 1) == 1) {
            // 'n' is odd.
            return multiply(matrix, fibonacciMatrix(matrix, n - 1));
        }

        // 'n' is even.
        BigInteger[][] tmp = fibonacciMatrix(matrix, n >> 1);
        return multiply(tmp, tmp);

Your argument in favour of recursion in the comments on an earlier answer is out by a factor of two, because you're potentially making twice as many calls as there are bits in n. Even if you don't want to do things iteratively, it makes sense to rewrite this as

        BigInteger[][] tmp = fibonacciMatrix(matrix, n >> 1);
        tmp = multiply(tmp, tmp);
        if ((n & 1) == 1) {
            tmp = multiply(matrix, tmp);
        }
        return tmp;

    public static void main(String[] args) {
        int n = -1;

        if (args.length > 0) {
            try {
                n = Integer.parseInt(args[0]);
            } catch (NumberFormatException ex) {

            }
        }

        System.out.println(fibonacci(n));
    }

If I supply no command-line arguments, or if I supply an invalid one, the output is The (-1)th Fibonacci number is not defined. That doesn't help me at all with figuring out my mistake. I'd rather have the NumberFormatException!


Unfortunately, the whole approach is broken. You should make your parallel tasks explicit in the code so that you don’t need cross-thread communication any more. Secondly, you are writing your own thread scheduler here. – Don’t. Schedulers already exist, take advantage of that.

Have a look at the Task Parallel Library, in particular the Task and TaskScheduler classes.

Better yet, try to model your algorithm to benefit from data parallelism and eschew explicit threading completely in favour of the automatically parallelised computations.


Reading CSV files pertaining to financial recorts

The point of filehandles is that it allows you to open more than one file simultaneously. So you could be reading the file list and the files you're searching through simultaneously.

Also, this:

if (grep /$TextToFind[$i]/, $_)

Is a a really convoluted way to write:

if (/$TextToFind[$i]/)

Overall, I'd do something like this:

#!/usr/bin/env perl

use strict;
use warnings;
use Text::CSV;

my $SrcDir = "/data03/adudata/live/work/";
my $RepDir = "/data03/adudata/live/archive/";
my $ReportList = 'pl_rec.list';

open my $list_fh, '<', $SrcDir.$ReportList
  or die "Could not open $ReportList: $!";

my %ReportData;
my $csv = Text::CSV->new();

while (my $row = $csv->getline( $list_fh ))
{
  my ($filename, $text, $rows_offset, $data_start, $data_end) = @$row;

  open my $fh, '<', $RepDir.$filename
    or die "Could not open $filename: $!";

  while (<$fh>)
  {
    next unless /\Q$text_to_find/;

    my $extractValue = substr($_, $data_start, $data_end);
    $extractValue =~ s/(^\s+)|(s+$)//g;
    $extractValue =~ s/,//g;

    $ReportData{$text} = $extractValue + 0;
  }
}

for (sort keys %ReportData)
{
  my $value = $ReportData{$_};
  print "$_,$value\n";
}


In need to speed up this code that filters the data of XML using XMLReader

Your code seems quite tidy and easy to understand, congratulations. But maybe you can check for built in functionality. XPath can search items for you:

http://www.php.net/manual/en/simplexmlelement.xpath.php
http://www.w3schools.com/xpath/xpath_syntax.asp


Ltree inverse crossing function using high order functions

I think this is a continuation-passing solution (simple parser) for writing build:

build :: [(a,Int)] -> LTree a
build xs = parseAt 0 xs fst

-- The first Int is the depth of the "root" of parseAt
parseAt :: Int -> [(a,Int)] -> ( (LTree a, [(a,Int)]) -> r ) -> r
parseAt r [] k = error "input too short"
parseAt r xs@((a,n):rest) k =
  case compare r n of
    GT -> error "depth too small"
    EQ -> k (Leaf a,rest)
    LT -> parseAt (succ r) xs (\ (left,rest1) ->
            parseAt (succ r) rest1 (\ (right,rest2) ->
              k (Fork left right, rest2)))


Getting the unique factors of a number recursively

An alternative (and probably more efficient) approach would be to derive all prime factors (hint: you could use divmod) and then create each of the possible factorings from that (hint: you could use itertools combinations).

Some notes:

If  you extract prime factors from smallest to largest, the remainder will always either be prime or be a composite with a smallest prime factor greater than or equal to the last one found.
One can also use the fact that all of the prime numbers except 2 are odd numbers to step through quickly.
The largest possible prime factor of any integer \$n\$ may be discovered by examining no more than \$\sqrt{n}\$ potential factors.

You might want to peek at this question for a Python-based prime factoring program.

Getting all factors from prime factorization

Starting with an example 60, we can easily determine that its prime factorization p = [2, 2, 3, 5].  Clearly, this is one possible factorization, which can easily be output in Python 3 as

print(*p, sep=' * ')

If you're using 2.6 or 2.7, you can still use this neat syntax, but you'll have to do this instead

from __future__ import print_function
print(*p, sep=' * ')

This prints:

2 * 2 * 3 * 5

So now all you need to do is create all possible unique lists of factors.  So for each two-factor combination, you could use this:

for i in itertools.permutations(p,len(p)):
    print(*[i[0],reduce(lambda x,y:x*y,i[1:])],sep=' * ')

That creates a list of all such two-factor combinations with exactly one prime factor, but they are not unique.  Because there is a repeated factor of 2 in the list, the product "2 * 30" is printed twice.  One way to handle this is to store each factor as it's used and suppress printing of non-unique factors.

Similarly, all non-unique 3-factor combinations with one prime factor:

for i in itertools.permutations(p,len(p)):
    print(*[i[0],i[1],reduce(lambda x,y:x*y,i[2:])],sep=' * ')

Or alternatively:

for i in itertools.permutations(p,len(p)):
    print(*(list(i[:2])+[reduce(lambda x,y:x*y,i[2:])]),sep=' * ')

This should give you enough of a clue as to how you might generate all possible factorizations.  A recursive approach is probably even better here.

Also, as an incidental note, factorings with 1 are typically omitted as trivial.


Entab.c - Program that replaces string of blanks by the min # of spaces & tabs to achieve identical output

A good implementation of this problem.  You've avoided some of the hurdles (such as remembering to store the result of getchar() in an int if you want to compare against EOF).
Most of what I say will be about style and readability.
Be consistent with your braces
We have a few different styles here:
int main()
{

Brace on its own line.  I like that for function definitions (though others differ).
    while((c = getchar()) != EOF)
    {

Another brace getting its own line.
        if(c == ' ') {
            //increase the space count
            ++ns;
        }
        //else if the character read in is not a space
        else {

Here, the brace shares the same line as the if.  And the else shares a line with only one of the braces.
            if(c == '\n')
                nc = ns = 0;
            else if(c != '\t')
                ++nc;

Here, we have no braces at all.  While that's legal, it's a good idea to always include braces (and I was reminded so recently, when I posted my own code for review!).
I would write the above like this:
int main()
{

    while((c = getchar()) != EOF) {

        if(c == ' ') {
            ++ns;
        } else {
            // not a space

            if(c == '\n') {
                nc = ns = 0;
            } else if(c != '\t') {
                ++nc;
            }

Alternatively, as:
int main()
{

    while((c = getchar()) != EOF)
    {

        if(c == ' ')
        {
            ++ns;
        }
        else
        {
            // not a space

            if(c == '\n')
            {
                nc = ns = 0;
            }
            else if(c != '\t')
            {
                ++nc;
            }

Naming
It's quite conventional to use c for a variable holding the current character.  But nc and ns are less obvious.  You could change the names; alternatively, add comments where they are declared:
    int nc = 0;                 /* number of characters read in this line */
    int ns = 0;                 /* number of consecutive spaces seen */

Comments
Generally the comments are pretty good.  I think you've over-commented a few things that are obvious to an experienced C programmer, but that's natural as you are learning - with experience, you'll recognise parts that are not idiomatic and concentrate your comments there, where they are most needed.
My personal taste is to avoid duplicating the code, so I wouldn't write "else" in the comment when it immediately follows an else in the code - I hope the samples below demonstrate what I mean.
Simplify loops
This loop is quite complex:
        //while one or more spaces are still "in buffer"
        while (ns > 0) {
            //decide whether gap in between chars is long enough for a space
            if (ns >= TABSIZE - nc) {
                //if it is, then place a tab, and remove that amount of spaces
                putchar('\t');
                ns -= TABSIZE;
            } else {
            // the gap is not big enough for spaces, just print them out individually
                putchar(' ');
                --ns;
            }
        }

We can replace with two simpler loops:
            //while one or more spaces are still "in buffer"
            while (ns >= TABSIZE - nc) {
                // place a tab, and remove as many spaces
                putchar('\t');
                ns -= TABSIZE;
            }
            while (ns > 0) {
                // use spaces
                putchar(' ');
                --ns;
            }

Finally
I'm not sure whether you've actually got the logic correct.  Remember that a tab jumps to the next tab stop - it may be equivalent to less than 8 spaces.  Have you tested with a variety of inputs (including tabs in input, and e.g. a run of 4 or 5 spaces after some non-space characters)?
The logic might be simpler if we keep track of current read column and current output column - at the end of a run of spaces we then just need to do the correct action to make the output column match the input column (using tabs where possible).
As a hint, if the current (0-based) column number is n, then a tab will advance the column number by TABSIZE - n % TABSIZE positions.


You should take a look at the possibility to name groups in regex patterns; your match pattern can then be a oneliner:

  const string pattern = @"^(?<name>\w+)\[(?<index>\d+)\]$";

  Match match = Regex.Match(command[2], pattern);

  if (match.Success)
  {
    string featureName = match.Groups["name"].Value;
    int index = int.Parse(match.Groups["index"].Value);

    try
    {
      // TODO: use the information
    }
    catch (Exception ex)
    {
       // TODO: Notify consumer
    }
  }
  else
  {
    // TODO: notify consumer
  }

As shown, the pattern for the index is changed from .*? to \d+ which is more precise and hence more efficient because it doesn't need the non-greedy operator ?.

if (command.Length < 5) //can't be more than 5 parameters
{
    return;
}

When meeting an error you just return from the method without doing anything. Shouldn't you notify the consumer/log the situation/condition?

You don't write from where the command information comes from, but if you read it from a text file, I think I would parse the string information while reading the file and then create a set of command objects defined as something like:

public class CommandInfo
{
  public string Action { get; set; }
  public string Type { get; set; }
  public string ListName { get; set; }
  public int Index { get; set; }
  public Point Vertex { get; set; }
}

Or whatever is suitable for your needs

This may not improve performance but it is more "type safe" than just dispatching an array of strings around.

According to efficiency:

You write, that you have thousands of commands for the same shape, but it seems that you requery a set of shapes inMemoryFeatureLayer.FeatureSource for every command. Whouldn't it be more efficient if you group the commands for each shape, so that you only have to query for the shape once and then can execute all the related commands?

TIP: If you are using Visual Studio 2019, you get help from intellisense and color coding if you compose the regex pattern directly in the call to Match or Matches:

Match match = Regex.Match(command[2], @"^(?<name>\w+)\[(?<index>\d+)\]$");

UPDATE

FYI: there has been some discussion in the comments to various answers about which approach is the most efficient, when extracting the name of the list of vertices and the index from a string like command[2] = "testLine[10]" => "testLine" and 10. So I ran some comparison tests for the following methods:

const string pattern = @"^(?<name>\w+)\[(?<index>\d+)\]$";

Regex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.Singleline);
void DoRegex()
{
  foreach (string item in data)
  {
    Match match = regex.Match(item);
    if (match.Success)
    {
      string featureName = match.Groups["name"].Value;
      int index = int.Parse(match.Groups["index"].Value);
      testResult += index ^ featureName.GetHashCode();
    }
    else
    {
      throw new InvalidOperationException("DoRegex match");
    }
  }
}

void DoSplitString()
{
  foreach (string item in data)
  {
    string[] split = item.Split('[', ']');
    string featureName = split[0];
    if (int.TryParse(split[1], out int index))
      testResult += index ^ featureName.GetHashCode();
    else
      throw new InvalidOperationException("DoSplitString TryParse");
  }
}

void DoIndexOf()
{
  foreach (string item in data)
  {
    int endIndex = item.IndexOf('[');
    string featureName = item.Substring(0, endIndex);
    if (int.TryParse(item.Substring(endIndex + 1, item.Length - endIndex - 2), out int index))
      testResult += index ^ featureName.GetHashCode();
    else
      throw new InvalidOperationException("DoIndexOf TryParse");
  }
}

void DoStringBuilder()
{
  foreach (string item in data)
  {
    string featureName = "";
    int index = 0;
    char stop = '[';

    StringBuilder builder = new StringBuilder();
    foreach (char ch in item)
    {
      if (ch == stop)
      {
        if (stop == '[')
        {
          featureName = builder.ToString();
          stop = ']';
        }
        else
        {
          if (int.TryParse(builder.ToString(), out index))
            testResult += index ^ featureName.GetHashCode();
          else
            throw new InvalidOperationException("DoStringBuilder TryParse");
          break;
        }
        builder.Clear();
      }
      else
      {
        builder.Append(ch);
      }
    }
  }
}

I use a compiled instance for Regex, which reduces the duration for this test with about 600 ms compared to an uncompiled version - when it is compiled once and the same instance is reused for all tests. testResult serves as a simple validation.

The dataset is generated as (the data creation is not part of the measures):

const int testCount = 2000;
const int randSeed = 5;
Random rand = new Random(randSeed);
IList<string> data;
int testResult = 0;

IEnumerable<string> CreateData(int count)
{
  string chars = "abcdefghijklmnopqrstuwxyz";

  for (int i = 0; i < count; i++)
  {
    yield return $"{(string.Join("", Enumerable.Range(1, rand.Next(10, 30)).Select(n => chars[rand.Next(0, chars.Length)])))}[{rand.Next(0, 100)}]";
  }
}

public void Run()
{
  data = CreateData(1000).ToList();
  ...

I ran each method 2000 times in order to measure some realistic averages with the same dataset with 1000 strings for all measures. The result is rather disappointing for the Regex approach:

testResult: 2052366768
Result for test DoSplitString:
Iterations:                      2000
Average:                      0,34116 Milliseconds
Min:                          0,29660 Milliseconds
Max:                          1,17520 Milliseconds
Total:                      682,31420 Milliseconds

testResult: 2052366768
Result for test DoRegex:
Iterations:                      2000
Average:                      1,69160 Milliseconds
Min:                          1,48380 Milliseconds
Max:                          6,16170 Milliseconds
Total:                     3383,19930 Milliseconds

testResult: 2052366768
Result for test DoIndexOf:
Iterations:                      2000
Average:                      0,22634 Milliseconds
Min:                          0,19200 Milliseconds
Max:                          0,93010 Milliseconds
Total:                      452,68460 Milliseconds

testResult: 2052366768
Result for test DoStringBuilder:
Iterations:                      2000
Average:                      0,36898 Milliseconds
Min:                          0,33100 Milliseconds
Max:                          1,36560 Milliseconds
Total:                      737,96910 Milliseconds

IndexOf is by far the most efficient

As t3chb0t writes in his comments, the regex pattern can be optimized significantly to

const string pattern = @"^(?<name>.+)\[(?<index>.+)\]$";

static readonly Regex regex = new Regex(pattern, RegexOptions.Compiled);

Running the test with this pattern gives this result:

testResult: 2052366768
Result for test DoRegex:
Iterations:                      2000
Average:                      0,97967 Milliseconds
Truncated Average:            0,97777 Milliseconds
Min:                          0,84020 Milliseconds
Max:                          4,91550 Milliseconds
Total:                     1959,33570 Milliseconds


I don't think there is a more succinct way to do that with Sidekiq, you will probably need to delete and recreate jobs.

Some comments

You probably don't need to check if old_jobs.present? when deleting. I am not familiar with ScheduledSet#select but I would imagine that it returns an empty array when no job is selected.

You don't need to update your jobs when the frequency is the same as the one already set. Even if you check it in the frontend it is a good idea to check it here to in case the view and the database are out of sync (read: in case someone changed the setting while your view was open).

Instead of using nested ifs, I like to use guards.
I also like to extract local variables into methods (see def setting).

Here is an example of how you could refactor it.

It may seem longer, but it is easier to understand when looking at the update_frequency method. If you need more precise understanding on what is considered as same_frequency, or reschedule_jobs, then you can dive into these methods. Otherwise looking at update_frequency probably gives you everything you need to understand when browsing the code (in 6 months when you will have forgotten of this part)

class DashboardController < ApplicationController
  def update_frequency
    return render_not_found unless setting
    return render_same_frequency if same_frequency?
    return render_update_failed unless update_model

    reschedule_jobs

    render json: { status: 200, msg: 'update frequency successful.' }
  end

  def render_not_found
    render json: { status: 404, msg: 'Not found.' }
  end

  def render_update_failed
    render json: { status: 500, msg: 'update frequency failed.' }
  end

  def render_same_frequency
    render json: { status: 200, msg: 'Frequency updated to the same value' }
  end

  def update_model
    setting.update_attributes(frequency: new_frequency)
  end

  def same_frequency?
    setting.frequency == params[:frequency].to_i
  end

  def setting
    @setting ||= Setting.find_by(id: params[:id])
  end

  def reschedule_jobs
    # find and delete all scheduled jobs
    Sidekiq::ScheduledSet.new
                         .select { |work| work.klass == 'HardWorker' }
                         .each(&:delete)

    # add new schedule job
    HardWorker.perform_in(setting.frequency.minutes)
  end
end


Historical Note
The very first comment on the OP's question -- long before any answers were posted -- was a question asked by myself, and it very pointedly asked:

Without using Integer.reverseBytes(cafeBabe)?

The question was two-fold:

Point out to the OP that a built-in method exists, and is likely the most optimal way of doing this.
Ask if they are trying to reinvent-the-wheel.

That comment/question has been removed.  If the OP responded to it, the response has been deleted as well and I never saw it.
This answer is not advocating the OP reinvent-the-wheel.  The Java JVM / JIT will have implemented the most efficient way of performing the operation, using internal features (such as @HotSpotIntrinsicCandidate) that are not necessarily available to the end-user.
Reinventing the wheel
public static int byteSwap(int a) {
    return ((a & 0xff000000) >>> 24) |
           ((a & 0x00ff0000) >>> 8)  |
           ((a & 0x0000ff00) << 8)   |
           ((a & 0x000000ff) << 24);
}

This function uses 6 distinct constants, 4 AND operations, 4 shifts, and 3 OR operations.
There is no point with the AND operation in ((a & 0xff000000) >>> 24) or in ((a & 0x000000ff) << 24) since the 24 bits which are being masked are immediately shifted out anyway.  This removes 2 constants, and 2 AND operations, which reduces the code to:
public static int byteSwap(int a) {
    return (a >>> 24)               |
           ((a & 0x00ff0000) >>> 8) |
           ((a & 0x0000ff00) << 8)  |
           (a << 24);
}

By reworking the order of second operation, we can remove another constant, the 0x00ff0000, and instead reuse the 0xff00 constant.  This eliminates the loading of the third bit mask constant, saving additional JVM byte code instructions:
public static int byteSwap(int a) {
    return (a >>> 24)           |
           ((a >>> 8) & 0xff00) |
           ((a & 0xff00) << 8)  |
           (a << 24);
}

This reworked version is very similar to the built-in Integer.reverseBytes() code in the system library:
@HotSpotIntrinsicCandidate
public static int reverseBytes(int i) {
    return (i << 24)            |
           ((i & 0xff00) << 8)  |
           ((i >>> 8) & 0xff00) |
           (i >>> 24);
}

I don't know if the difference in ordering gains any additional speed, but (dollars to donuts) the @HotSpotIntrinsicCandidate annotation probably does - so just use the built-in function.


Combining these Add and Remove methods into 1

It isn't a good idea to merge these methods. They do completely opposite things - you never want a method like:

public void DoSomething(bool arbitraryFlag)
{
    if (arbitraryFlag)
    {
        DoSomething1();
    }
    else
    {
        DoSomethingCompletelyDifferent();
    }
}

I will expand on what paritosh commented though.

private void GetUserAndGroupNames(int companyID, string userID, out string userName, out string groupName)

This signature smells because it returns void but has 2 out parameters.

A better signature would be like:

public class UserAndGroup
{
    public string Username { get; set; }
    public string GroupName { get; set; }
}

public UserAndGroup GetUserAndGroup(int companyId, string userId)
{
    var vipGroupSID = new MyDataAccess().GetVipGroupSID(companyID);
    if (string.IsNullOrEmpty(vipGroupSID))
    {
        // see edit
        throw new Exception(string.Format("Company id: {0} has no vips group in db", companyID));
    }

    var user = DBUser.LoadBySid(userID);
    var group = DBGroup.LoadBySid(vipGroupSID);

    return new UserAndGroup
    {
        Username = user.UserName,
        GroupName = group.Name
    };
}

Note that I've introduced var where they type is obvious, added braces around the if statements and removed the very confusing comment that was there.

Your other methods would then become something like:

public void RemoveFromVipGroup(int companyID, string userID, string auditTrailUrl)
{
    var userAndGroup = GetUserAndGroup(companyID, userID);
    GroupUtilities.RemoveUserFromGroup(userAndGroup.Username, userAndGroup.GroupName, auditTrailUrl);
}

I still think it's a bit weird though... Is there only one group? It's odd to add/remove a user to a group without being able to specify what that group is.

EDIT

You should never throw System.Exception - there is always a better, specific exception to throw. If there isn't, create one (as a last resort).

For example, you could create a GroupMissingException or something that makes sense for your domain.


Handing focusing and unfocusing of multiple form fields

Use a custom date attribue, lets say placeholder on your inputs, and then give them a common class as well:

<input type="text" id="email" data-placeholder="Email Address" class="required" />
<input type="text" id="name" data-placeholder="Full Name" class="required" />
<input type="text" id="subject" data-placeholder="Subject" class="required" />
<input type="text" id="msg" data-placeholder="Your Message" class="required" />

And then use 1 event for all!

$(".required").focus(function() {
    var placeholder = $(this).data("placeholder");
    if (this.value == placeholder) this.value = "";
}).blur(function() {
    if (this.value == "") this.value = $(this).data("placeholder");
}).blur(); //trigger on load

A fiddle: http://jsfiddle.net/odpu5gbn/


Firstly: There are a lot of magic numbers here. I'd stick those in variables and name them. For instance, I have no idea what 0.00891 is, but it's apparently to do with pump sizes? I guess? It'd also be nice to have them defined in one place. You have things like a general 1.6x cost multiplier, and a 2250 (presumably dollars) extra cost for a certain cistern type. Rather than hunt around in the code to find those if you need to update them (especially if used more than once!), it be nice to have them defined in one place - and labelled. E.g.

var COST_FACTOR = 1.6,
    TYPE_I_EXTRA_COST = 2250,
    // etc.

The names above are not very good, but it's just to illustrate the point.

And like Matt Zeunert said, the single-letter codes are very opaque as well. I'm sure they're some sort of industry code, but still.

For instance, the "primary use" code has quite a dramatic effect on things if it's exactly "I". Don't know why, but since it's a specific case your Cistern objects could perhaps benefit from an is... function (e.g. isForIrigation, or isForIndoorSkatingRink or whatever it is I stands for) that just returns true/false depending on whether primaryUse === "I". That'll make some later calculations much more expressive, because you can say "if the cistern isForIrigation, then...", rather than somewhat cryptically checking if a property happens to be an uppercase i.

Next, your Object.defineProperty usage is overwrought, it seems to me. Rather than recalculate everything whenever something is changed, it'd be easier to just calculate it when requested.

Sure, it mimics Excel quite well; change one cell, and the change ripples out (no water pun intended). But in whatever you're building, you'll be in charge of making those ripples happen. You'll have to ask for the updated values yourself. Sure, they get updated, but you won't see that until you access them. In which case it'd be simpler to just calculate them then.

On another note, the way you use this and _this betrays some confusion. The _this variable isn't necessary; you can use the plain this inside your update function as it refers to the same Cistern instance. In fact you do so by accident in one place already (a line that uses both _this.buildingStories and this.buildingStories in the same expression).

You can also structure your code more as a proper prototype by making update a true prototype method, rather than a property added by the constructor:

function Cistern() {
  // ...
}

Cistern.prototype = {
  update: function () {
    // ...
  }
};

However, as mentioned, I'd go a different route all together. Namely, I'd split update up, and flip the whole thing around: What's now being accessed with getters and setters becomes just plain properties, and what's now plain properties is replaced with getters - and only getters, since they're derived values and thus read-only. That way, your getters are responsible for calculating their value when you call them.

function Cistern (area) {
  this.area = area;
  this.maxRainEvent = 2;
  this.tankType = 'C';
  this.primaryUse = 'O';
  this.buildingStories = 3;
  this.fixtureNumber = 10;
  this.maintenanceLevel = 'M';

  var getters = {
    precipitationPerEvent: function () {
      return Math.ceil(7.48 * this.area * this.maxRainEvent / 12);
    },

    totalStorageNeeded: function () {
      return Math.ceil(this.precipitationPerEvent / 100) * 100;
    },

    tankCostPerGallon: function () {
      return { // this "table" should probably be extracted and put elsewhere
        'C': 1.66,
        'P': 1.43,
        'S': 2.51,
        'F': 1.33
      }[this.tankType];
    },

    tankCost: function () {
      return this.tankCostPerGallon * this.totalStorageNeeded;
    },

    pumpSize: function () {
      if(this.primaryUse !== 'I') {
        return 0.5;
      }

      // I simplified the math here, but the result should be the same
      return Math.ceil(5.5598 * Math.pow(this.buildingStories, 2) * this.fixtureNumber / 225);
    },

    pumpCost: function () {
      return -100.71 * Math.pow(this.pumpSize, 2) + 1327.7 * this.pumpSize - 39.38;
    },

    systemBaseCost: function () {
      var cost = Math.ceil(1.6 * this.tankCost + this.pumpCost);
      return this.primaryUse === 'I' ? cost + 2250 : cost;
    }
  };

  // create getters
  for(var property in getters) {
    Object.defineProperty(this, property, { get: getters[property] });
  }
}

Now you can update the public properties freely, and whenever you need a calculated value like, say, systemBaseCost, it'll be calculated on the fly, doing whatever intermediate calculations it needs along the way.


Your code defines in the second loop: for (int j = 5; j >= 0; j--) and  later you use j in this statement: macOctets.set(j - 1, ++macValue); If j==0 however, you will get an IndexOutOfBounceException as -1 is not a valid index. You avoid the exception by checking explicitely for j==0 and set the value to 0, though this check will be done for every segment of the mac address. This check therefore can be refactored out of the loop and to a later position.

Next, you split the input string twice. Why? Something like

String [] macSplit = macAddress.split(":");

int incPos = macAddress.split(":").length; // need to throw exception when the length is 0
if  (incPos >= 1) {
    ...
}

can be replaced with this:

String[] macSplit = macAddress.split(":");
if (macSplit.length >= 1) {
    ...
}

This will avoid splitting the input string multiple times.

I'd also initially fill the macOctet array with 0 values and then simply set the respective defined mac value like this:

for(int i=0; i<macSplit.length; i++)
{
    macOctets[i] = Integer.parseInt(macSplit[i], 16);
}

If I execute the below code and compare it to your original code:

public static List<String> getMacSequences(final String macAddress, final Integer count)
{
    List<String> macList = new ArrayList<String>();
    Integer[] macOctet = new Integer[] { 0, 0, 0, 0, 0, 0};
    String[] macSplit = macAddress.split(":");
    if (macSplit.length > 0)
    {
        for (int i=0; i<macSplit.length; i++)
        {
            macOctet[i] = Integer.parseInt(macSplit[i], 16);
        }
    }
    for (int i=0 ; i<count; i++)
    {
        macOctets[5]++;
        for (int j=5; j>0; j--)
        {
            if (macOctets[j] > 255)
            {
                macOctets[j] = 0;
                macOctets[j-1]++;
            }
            else
            {
                break;
            }
        }
        if (macOctets[0] > 255)
        {
            macOctets[0] = 0;
        }
        macList.add(String.format("%02X:%02X:%02X:%02X:%02X:%02X",  macOctets));
    }
    return macList;
}

I'll get the following times for 100000 iterations on 260 generated MAC addresses:

Original - Total: 71341.440878 ms, Average: 0.71341440878 ms
Modified - Total: 70220.091388 ms, Average: 0.70220091388 ms

While not a big speed improvement, at least a little faster then the original one.

Further speed improvements

I used Integer[] macOctets = new Integer[] { ... } over a simple int[] macOctets = new int[] { ... } in the sample code above as the string formatter has some issues with int arrays for some reasons with my version of Java (Oracle Java 8 Update 101).

I then implemented my own version of MAC string converter

private static String toHexString(int[] macOctets)
{
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<macOctets.length; i++)
    {
        sb.append(Integer.toHexString(0x100 | macOctets[i]).substring(1).toUpperCase());
        if (i != macOctets.length-1)
        {
            sb.append(":");
        }
    }
    return sb.toString();
}

and changed the initialization of the macOctets array to a simple

int[] macOctets = new int[6];

which internally will initialize each element with its default value, which is 0.

When re-running the comparison test described above, the following output is returned:

Original - Total: 71901.357327 ms, Average: 0.71901357327 ms
Modified - Total: 10287.282422 ms, Average: 0.10287282422 ms

The custom method makes use of a tiny hack in order to print the two byte pairs of a MAC segment.

It seems that the algorithm spends most of the time within the array to hex string formating. I'd therefore highly suggest to change from the String formatter to a custom one as this only requires a fraction of the time the Java native function requires.

For completeness I'll post the complete performance test main method so you can compare for yourself

public static void main(String ... args)
{
    int repetitions = 100000;
    String initialSequene = "A0";
    int macsToGenerate = 260;

    long startTime = System.nanoTime();
    for (int i=0; i<repetitions; i++)
    {
        getMacSequences(initialSequene, macsToGenerate);
    }
    long endTime = System.nanoTime();

    long duration = (endTime - startTime);
    double totalDurationInMs = (duration / 1000000.);
    System.out.println("Original - Total: " + totalDurationInMs + " ms, Average: " + (totalDurationInMs / repetitions) + " ms");

    startTime = System.nanoTime();
    for (int i=0; i<repetitions; i++)
    {
        getMacSequences2(initialSequene, macsToGenerate);
    }
    endTime = System.nanoTime();

    duration = (endTime - startTime);
    totalDurationInMs = (duration / 1000000.);
    System.out.println("Modified - Total: " + totalDurationInMs + " ms, Average: " + (totalDurationInMs / repetitions) + " ms");
}

where getMacSequences(...) is your version and getMacSequences2(...) is my modified version.


Lets say that there is room for improvement. ;)

The prompt method returns a string, but you want a number, so you should parse the string:
var n = parseInt(prompt("Enter n: "), 10);

Using indexOf on an array is slow. Instead of putting all the non-primes in a bucket and rummaging through it, you should use an array containing boolean values where the index is the number and the values tells you if it's a prime or not.
Accessing an array by index is an O(1) operation, while searching for a value in an array is an O(n) operaton. As n grows, this code will get slower and slower the longer you let it run.
As you are pushing a lot of duplicate non-primes in the array, an array of boolean values will actually use about 70% less memory eventhough the primes also takes up space in it.

This loop is pretty pointless:
for(var j = i ; i <= j ; j++){

The condition will never be false. You should instead use the i * j < n condition to break out of the loop:
for(var j = i; i * j < n; j++){
  notPrime[i * j] = true;
}

Edit:
You are still using the array as a kind of collection. You should set all values to true at start, and then set all non-primes to false. This code (based on the algorithm here) is about five times faster:
var n = parseInt(prompt("Enter n: "), 10);
var i, j;
var prime = new Array(n);
for (i = 2; i < n ; i++) prime[i] = true;

for (i = 2; i * i < n ; i++) {
  if (prime[i]) {
    for (j = 0; i * i + i * j < n ; j++) {
      prime[i * i + i * j] = false;
    }
  }
}

var cnt = 0;
for (i = 2 ; i < n ; i++) {
  if (prime[i]){
    console.log(i);
  }
}


Calculate all possible combinations of given characters

your code looks fine.

a slight performance improvement i'd do is pass a StringBuilder instead of a String - a String in java is immutable so every time you call curr += alphabet[i] youre actually allocating a new String object. instead you could append the character to a StringBuilder (and delete the last character when you leave) to save on the number of Objects created during the run
for(int i = 0; i < alphabet.length; i++) {} could be re-written as a more modern loop: for (char c : alphabet) {}, which would make for a more readable result


DRY
This repetitive code is an anti-pattern:
blueTotal = 0
greenTotal = 0
redTotal = 0
yellowTotal = 0

Please define
houses = 'blue green red yellow'.split()

and then you can use array access to perform "the same action" across all houses:
for house in houses:
    total[house] = 0

One could also assign total = collections.defaultdict(int), but that would
be a horse of a different color.
(https://docs.python.org/3/library/collections.html#collections.defaultdict)
global
The global keyword is usually not your friend,
it leads to unfortunate coupling.
Here, it is offering you a hint that you want to define a class,
set totals to zero in the __init__() constructor,
and then have places() access self.total[].
arg passing
This is a bit crazy:
    for competitors in competitorDetails:
        points()

Yes, you can treat competitors as an implicit argument
by making it global, but there is absolutely no reason to,
and the current code makes it extremely difficult for readers
to understand what is going on. Please, please make competitors
an explicit argument, passing it in with points(competitors).
formatting
Clearly this works:
print("blueTotal " + str(blueTotal))

but the explicit call to str is slightly verbose.
Consider re-phrasing such print statements in one of these ways:
print("blueTotal", blueTotal)
print(f'blueTotal {blueTotal}')


Open source Pastebin tool made in JSP and servlet

On the upside of your code, you kept it as simple as possible.
But there are a few flaws - and the upside doesn't come without consequences.

What's also good is that you already use PreparedStatement.

Security Risk

Hard-coding the username and password is not a good idea for another reason.
A misconfigured webserver could easily expose these critical credentials by accident.

Layered Architecture

We say that often, an architecture consists of 3+1 layers: UI, Business Logic / App, Persistence, plus Main.

In your case this is all mixed up.
The upside is that in your case it keeps things seemingly simple.
But this is a trap.

Someone needs to change the source code of the application in order to connect with a different password, different username, or to use a different SQL RDBMS than MySQL, or to use a different type of DBMS altogether.

ID Collisions likely

The way how you get your ID means that ID collisions are quite likely.
There are better ways to generate a unique ID.
In case of MySQL, and most other RDBMS for that matter, you can actually let the DBMS generate an ID for you.
In MySQL, the id column would need to be defined like this: id INT PRIMARY KEY AUTO_INCREMENT.

Usually, we say that using auto-incremental IDs is a security issue.
However, if pastes are public anyway, that's a different topic.
The pastes are not access-protected anyway.
So incremental IDs are fine in this case.

Otherwise, universally unique ids or hashes with unlikely collisions are far better user ids. One might still want to go for id INT PRIMARY KEY AUTO_INCREMENT hidden in the DBMS for relations and use a uuid VARCHAR(...) UNIQUE for the id visible outside the DBMS.

Error handling

You want to close your pstmt even in case of error, and you want to close your con in any case.

You can use Java 7 try-with-resources for that:

try (final Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
    try (final PreparedStatement pstmt = con.prepareStatement("INSERT INTO paste_tool(gen_key, title, source_codes) VALUES(?, ?, ?)")) {
        // ...
    }
}

This will close your PreparedStatement and your Connection automatically, regardless of whether they were successful or threw exceptions.

Code Conventions

In Java, we only use _ in names in these rare cases:

The name implements an API defined elsewhere and there the name already contains _.
The name is a compile time constant, as in public static final short MAX = 32767;
The _ replaces a comma in natural language, as in givenConnectedChatClient_whenSendingMessage_thenReceivesMessage().

In your case, you should rename things:

gen_key -> genKey
submit_code1 -> submitCode1
title_code -> titleCode

Why is it named submit_code1 anyway? Is there also non-submitted code? Is there also a submit_code0? A submit_code2? And why is it named submit_code1, when in the form it is named paste_code?

I think it that submitCode1 should actually be named pasteCode.
And submitCode2 should be renamed to htmlEscapedPasteCode - or removed, see next point.

When to replace the special characters

You replace the special characters in the paste code before storing the paste in the DBMS.
While this gives you a little bit of performance - you have to replace only once, upon storage, not many times upon each retrieval, I think it's not the best way how to handle it.

Consider you want to extend this with different interfaces.
Maybe you want to implement raw retrieval, or PDF export, or the facility that a user can fetch all his pastes as one big zip file?
Then you'd have to reverse the replacement of the special characters.

From an architecture perspective, the special characters are a presentation topic - it's because you use HTML as presentation.
Therefore it should be in the presentation layer, not in the persistence layer.
If you then add more presentation modules, they will not have to reverse presentations of other modules that are otherwise unrelated to them.
It would look awkward in a raw module or PDF module to first have to reverse the HTML special characters from what they get from the database.

So, I'd put the StringEscapeUtils.escapeHtml4() call in viewCode.jsp instead.

Error Handling 2

What happens in case of an ID collision (gen_key already used)?

Error Handling 3

What happens in case the form is submitted empty?

ISO-8859-1 vs. UTF-8

I'd really use UTF-8. Always. Everywhere. Unless there's a really good reason not to. And I don't think that here there is.

ASP-style JSPs vs. XML-style JSPs

I'd rather go for XML-style JSPs than ASP-style JSPs.
For many it may just be a matter of taste.
But to me there's the advantage that I can XSLT process the source of the JSP.


Most common words in a text file of about 1.1 million words

This is actually quite good. Good use of the collections module.

One improvement I can think of is switching to the with open(...) as: structure, that way the file will automatically be closed when finished processing.
Secondly it is standard in python to use a if __name__ == '__main__': block.
Lastly sys.argv will work ok for programs with not many arguments, but I'd recommend looking at the argparse module.


It seems the only two unique things about the blocks of code are the Tables that you are searching/adding to and how the SITE_IDs are obtained (from different types).  You could just make your method accept two additional parameters, the table that is being searched and a lambda which selects the SITE_ID.  You'll just have to rewrite some expressions.

public static void ExportData<TEntity, TSite>(
    ObjectSet<TEntity> table,
    Expression<Func<TEntity, TSite>> siteIdSelector,
    TEntity data)
    where TEntity : class
{
    var condition = GetCondition(siteIdSelector, data);
    var isInTable = table.Where(condition).Any();
    if (!isInTable)
    {
        table.AddObject(data);
        table.Context.SaveChanges();
    }
}

private static Expression<Func<TEntity, bool>> GetCondition<TEntity, TKey>(
    Expression<Func<TEntity, TKey>> keySelector,
    TEntity data)
    where TEntity : class
{
    var entity = Expression.Parameter(typeof(TEntity), "entity");
    var entityKey = BindParameter(keySelector, entity);
    var dataKey = BindParameter(keySelector, Expression.Constant(data));
    var body = Expression.Equal(entityKey , dataKey);
    return Expression.Lambda<Func<TEntity, bool>>(body, entity);
}

private static Expression BindParameter<TEntity, TKey>(
    Expression<Func<TEntity, TKey>> keySelector,
    Expression entity)
    where TEntity : class
{
    return new SubstitutionVisitor
    {
        OldExpr = keySelector.Parameters.Single(),
        NewExpr = entity,
    }.Visit(keySelector.Body);
}

public class SubstitutionVisitor : ExpressionVisitor
{
    public Expression OldExpr { get; set; }
    public Expression NewExpr { get; set; }

    public override Expression Visit(Expression node)
    {
        return (node == OldExpr) ? NewExpr : base.Visit(node);
    }
}

Then to use it, you could do something like this:

ExportData(_context.FLEX_INV_EXP_SITE, entity => entity.SITE_ID, siteData);
ExportData(_context.FLEX_INV_EXP_ADDRESS, entity => entity.SITE_ID, addressData);


Stripping Quotations from a List of Lists

I just always seem to mess up comprehensions when they have the = sign in them like this.

I found the best way to think about comprehensions is instead think of comprehensions as .appends.
Lets change your inner loop to use .append instead.
We don't need to use enumerate as we'll be building a new list.
def quote_strip(input_file):
    for k1, v1 in enumerate(input_file):
        inner_list = []
        for v2 in v1:
            inner_list.append(v2.lstrip('"').rstrip('"'))
        input_file[k1] = inner_list
    return input_file

We can now change the code to a comprehension.
I'll show you a pattern which we can just copy:
my_list = []
for item in other_list:
    my_list.append(item + 1)

becomes:
my_list = [
    item + 1
    for item in other_list
]

We just move whatever is in the append(...) to the top of the comprehension.
And move the for loop into the bottom of the list.
def quote_strip(input_file):
    for k1, v1 in enumerate(input_file):
        inner_list = [
            v2.lstrip('"').rstrip('"')
            for v2 in v1
        ]
        input_file[k1] = inner_list
    return input_file

You should notice we can remove the need for assigning to the name inner_list.
def quote_strip(input_file):
    for k1, v1 in enumerate(input_file):
        input_file[k1] = [
            v2.lstrip('"').rstrip('"')
            for v2 in v1
        ]
    return input_file

Now we can change the loop to use .append again.
def quote_strip(input_file):
    output_list = []
    for v1 in input_file:
        output_list.append([
            v2.lstrip('"').rstrip('"')
            for v2 in v1
        ])
    return output_list

And again we can change the code to a list comprehension.
def quote_strip(input_file):
    return [
        [
            v2.lstrip('"').rstrip('"')
            for v2 in v1
        ]
        for v1 in input_file
    ]

Extra

I am pretty sure there is a way of making this a single line

We can put the comprehension on one line but please do not do so.
How many lines of code you write is not important, how easy to read your code is.
Putting the comprehension on one line will make your code harder to read.


Since I think this is worth more than just a comment on another answer, in your codes_from_csv you are (ab)using the new walrus operator. Assignment expressions are not the right thing to do here. What they do is assign local variables (outside of the function!), and then the values of those local variables (but not their names) are passed by position to the function.

A small example of how this can lead to unexpected results:

def f(a, b):
    return a // b

# Normal positional arguments, order matters
f(3, 1)
# 3
f(1, 3)
# 0

# Keyword arguments, order does not matter, only name
f(a=3, b=1)
# 3
f(b=1, a=3)
# 3

# Using the walrus operator, variables are assigned,
# but are passed as positional arguments.
# The names of the (external) variables do not matter to the function!
f(a:=3, b:=1)
# 3
f(b:=1, a:=3)
# 0

In other words the last example is equivalent to:

b = 1
a = 3
f(b, a)
# 0

This might be what you want, but since you are using the names of the arguments of the function, it probably isn't. In your code it just so happens to work because you use the same order as in the function definition. This might be a source of bugs at some future point, which could be very hard to find!


Write a method to replace all spaces in a string with %20

Your strategy of counting the spaces and then back-looping to shift the characters right (and replace spaces with %20) is good. The basic algorithm  is probably as good as it gets as a character array system.

Your variable names are decent, and the code flows well.

On the other hand, there are some small things I would change.

Possible bug

Your code, given the input conversion("abc     ", 3) you would output "abc" but you should not remove any "extra" padding in the string, you should return "abc     "

In fact, you should only really have the one char[] array. The second one is making you do bad things ;-)

Enhanced fors

Use enhanced-for loops when possible, and always use {} blocks for if-statements, even 1-liners:

for(int i = 0; i < length; i++){
    if(strChars[i] == ' ')
        numSpaces++;
}

should be:

for (char c : strChars) {
    if (c == ' ') {
        numSpaces++;
    }
}

Comments

Comment unusual loops - your second for-loop is an odd one, and it often helps the reader if you comment why a loop is non-sequential (or even if you just make sure they are aware of it).

multiple indexes

Have you considered having a separate index for each position in the array - the position of the source character, and the position of where to insert it?

public static String conversion(String str, int length){

    char[] strChars = str.toCharArray();

    int numSpaces = 0;
    for (int i = 0; i < length; i++) {
        if(strChars[i] == ' ') {
            numSpaces++;
        }
    }

    int insert = length + 2 * numSpaces - 1;

    // loop backwards through source characters.
    for (int i = length - 1; i >= 0; i--) {
        char c = strChars[i];
        if (c == ' '){
            strChars[insert--] = '0';
            strChars[insert--] = '2';
            strChars[insert--] = '%';
        } else {
            strChars[insert--] = c;
        }
    }
    return String.valueOf(strChars);
}

The benefit of two indexes is that you can keep the logic more readable ... ("more" is relative) as each index moves by one character at a time... and a space counts as 3 characters.


I would call this method AcquireTimeSlot or similar, since the main action here is actually capturing a timely-limited resource. Result of the method specifies whether resource has been acquired or not. You may also call it TryAcquireTimeSlot to highlight the fact that acquisition may fail.

As a side note - you can rewrite the code without locks in case if that's the only place you use the lockObject. It will be a bit more verbose though...

public class TimeWindow
{
    private static readonly object _lockObject = new object();
    private long _timestampTicks;
    private int _windowCounter;

    private void CheckWindowExpiration(int windowSeconds)
    {
        long timestampTicks = _timestampTicks;
        while (TimeSpan.FromTicks(DateTime.Now.Ticks - timestampTicks).TotalSeconds > windowSeconds)
        {
            if (Interlocked.CompareExchange(ref _timestampTicks, DateTime.Now.Ticks, timestampTicks) == timestampTicks)
            {
                _windowCounter = 0;
                break;
            }

            timestampTicks = _timestampTicks;
        }
    }

    public bool TryAcquireTimeSlot(int windowSeconds)
    {
        CheckWindowExpiration(windowSeconds);

        int windowCounter = _windowCounter;
        while (windowCounter < 10)
        {
            if (Interlocked.CompareExchange(ref _windowCounter, windowCounter + 1, windowCounter) == windowCounter)
                return true;

            windowCounter = _windowCounter;
        }

        return false;
    }
}


Initialization of store as a list of None does not really buy you anything in terms of efficiency, but complicates the code quite a bit. I recommend to initialize it with empty lists instead.
put iterates the list twice. A single pass is sufficient:

    for i in list_at_index:
        if i == p:
            i.value = p.value
            return
    list_at_index.append(p)
    self.size += 1

store has 16 slots, but key_hash % 15 returns only 15 possible values. The last slot is never used.
Absence of delete is somewhat questionable.


Randomly sampling a population and keeping means: tidy up, generalize, document?

Making a generator version of random.sample() seems to be a much better idea:

from __future__ import division
from random import random
from math import ceil as _ceil, log as _log

def xsample(population, k):
    """A generator version of random.sample"""
    n = len(population)
    if not 0 <= k <= n:
        raise ValueError, "sample larger than population"
    _int = int
    setsize = 21        # size of a small set minus size of an empty list
    if k > 5:
        setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
    if n <= setsize or hasattr(population, "keys"):
        # An n-length list is smaller than a k-length set, or this is a
        # mapping type so the other algorithm wouldn't work.
        pool = list(population)
        for i in xrange(k):         # invariant:  non-selected at [0,n-i)
            j = _int(random() * (n-i))
            yield pool[j]
            pool[j] = pool[n-i-1]   # move non-selected item into vacancy
    else:
        try:
            selected = set()
            selected_add = selected.add
            for i in xrange(k):
                j = _int(random() * n)
                while j in selected:
                    j = _int(random() * n)
                selected_add(j)
                yield population[j]
        except (TypeError, KeyError):   # handle (at least) sets
            if isinstance(population, list):
                raise
            for x in sample(tuple(population), k):
                yield x

Taking a sampling mean then becomes trivial:

def sampling_mean(population, k, times):
    for t in xrange(times):
        yield sum(xsample(population, k))/k

That said, as a code review, not much can be said about your code as it is more or less taking directly from the Python source, which can be said to be authoritative. ;) It does have a lot of silly speed-ups that make the code harder to read.


Whiteboarding - Multiply all values in array except at the index for each

First of all, congrats on producing a solution that works correctly.
However, keep in mind that correctness is often not the only criteria for a successful candidate.
Other typical criteria include performance,
as well as the analysis of corner cases,
where this solution does poorly.

Time complexity analysis

What is the time complexity of your solution?

   \$O(n^2)\$

That's a typical question to expect at a programming interview.
The point of the question is not so much the accurate computation,
but an open discussion around this topic.

Would you describe this solution as optimal?

   No. It's a brute-force solution.

A likely next question is: can we do better?

Algorithm

  Here's the catch: You can't use division in your solution!

That's some sort of hint.
It's trying to guide you in a certain direction.

Without the catch, would you implement the solution the same way?
If we can use division,
it's easy to see a simple optimization:
first compute the product of all elements,
and then for each element,
divide the total product by the element.
That would have time complexity \$O(n)\$ instead of \$O(n^2)\$.

The catch prevents us from using the simple optimization. Why?
So that we find another way.
This is the hard part, to discover something clever under high pressure.
But at least it's important to reach this point by thinking out loud about time complexity, and the nature of the problem at hand.

You could compute "prefix products" \$L\$,
such that \$L[i]\$ is the product of all the values that are on the left of \$a[i]\$,
and "prefix products" \$R\$,
such that \$R[i]\$ is the product of all the values that are on the right of \$a[i]\$.
With these helper arrays, the target value to compute for each \$i\$ is \$L[i] * R[i]\$. No division needed, and time complexity of this solution is \$O(n)\$.

Then a discussion can follow about tradeoffs.
For example, how does this compare to your original solution?

   Time complexity is improved, but space complexity is now \$O(n)\$, instead of \$O(1)\$ of brute-force.

A likely next question is: can we do better?

Corner cases

Other important points an interviewer may look for:

Does the candidate look for corner cases?

If you don't look for them, the interviewer will probably nudge you to go look for them. It's important to recognize the nudge.

Is the candidate able to find corner cases?

If you are not able to, the interviewer will probably nudge you in the general direction. It's important to recognize the nudge, and then the general direction, and verbalize all that, thinking out loud.

Can the candidate correctly adapt the solution to handle the corner cases?

So what's an interesting corner case here?

   When computing products of numbers, there may be a risk of integer overflow.

At this point it's important to ask about the minimum and maximum values that may in the array, as well as the length of the array.
Based on that, the candidate should discuss about the possibility of integer overflows, and try to compute if it can happen or not.
And sure enough, if you are able to conclude that based on the input parameters integer overflow cannot happen,
the interviewer will adjust the parameters accordingly.
And then you need to discuss strategies to deal with the added complication.

You can expect the interviewer to keep adding twists to the problem,
raising more and more challenges.
The interview can branch and go in multiple possible directions,
often in directions where you seem least comfortable.
It's good to try to anticipate potential complications.
Trying to find corner cases is probably a good starting point.

Discussion

The posted question contains simply the problem description and the solution.
A discussion around the solution is missing,
maybe you didn't think it's important. But it is.
Thinking out loud, and expressing your logic clearly during a programming interview is usually just as important as the solution itself.