Way too many calls to $

This pops up way too much in your code (or something like this):

$("#kit_model")

Normally, document.getElementById itself can be slow. However, this jQuery function is even slower because, not only does it have to traverse the DOM in search for a single element, but it also has to wrap it sugar another object for access to more methods/properties.

It'd be better to reduce your calls to this function. Instead, store the return from a single call in a variable and use that:

var kitModel = $("#kit_model");

Do this for the other elements that you grab more than once, too.

If you are in control of the highlight and restore functions, change them so they can accept the element itself through parameters. This will make your function more flexible, and also allows you to just continue to use this variable you have.

Tables for layout

If I understand correctly, you are using tables in your HTML code to correctly position your DOM elements. This is bad/old practice. You should instead be using CSS rules to position elements.

Tables are for data that belongs in tables.

Initialize attributes in HTML

Here, you are initializing your submit button to be disabled in your JavaScript code:

$('#kit_submit').prop("disabled", true);

Instead, you should simply just slap a disabled onto the element itself.

Unnecessary condition

Will this condition ever pass?

$("#custom_kit_form").submit(function() {
    if ($("#kit_model").val() == 0)

The submit button can't be clicked in the first place if the value of the kit model is 0 because the change listener will disable the button.

You can safely remove this part of the submit listener.


Efficiently compare 2 lists to replace and order

It sounds like you want the fruits unique to the first list to go at the end of the final list, and the fruits in both the first and second list go at the beginning of the final list.

For a problem like this, it might be better to use a LinkedList instead of an ArrayList, at least for the final list. Usually you're better off with an ArrayList, but in this case you can benefit from inserting an element at the front of the list is an \$O(1)\$ operation instead of \$O(n)\$.

You're on the right track with using a Map to speed this up with large data sets. Here is a potentially more efficient implementation:

Loop over the first list, filling a map firstMap with key: firstItem value: false
Loop over the second list, and for each item, insert the result of
firstMap.containsKey(secondItem) into firstMap with a key of secondItem
Finally, loop over the first array, if firstMap.get(firstItem) is true, insert the item at the front of the final list (it was in both lists). Else add it to the end of the final list (it was only in the first list).


For a power function with an integer exponent you can loop through the bits in the exponent instead of making a linear loop:

function pow(base, power) {
    if (power < 0) return 1 / pow(base, -power);
    var b = base, result = 1;
    while (power > 0) {
        if ((power & 1) != 0) {
            result *= b;
        }
        power >>= 1;
        b *= b;
    }
    return result;
}

This will only loop as many times as there are bits used in the exponent, for a value like 1000 that means 10 iterations instead of 1000.

Testing this with pow(2, 1000) in Firefox shows that it is about 70 times faster (but the built in method is still even 8 times faster).


I would recommend the following changes:

Math is your friend. Factorize the number into prime powers (a precalculated table of primes is of immence value for a lot of Project Euler problems), and use a formula from this article.
Memoize. As soon as you identify a single (prime) divisor of a number, and take the quotient, notice that the quotient was already inspected and factorized. A vector of tuples (prime, power) representing a factorization may also help a lot.

There could be other optimizations, but these two seem to be enough.


Assigning zero to random cells in a pandas.DataFrame

Right now, you are only setting a single cell to zero. If this is what you want, then your solution works well. However, if you want to randomly set cells to be 0, then the solutions below might be better.
For an arbitrary dimensional df:

# Create Random Mask
rand_zero_one_mask = np.random.randint(2, size=df.shape)
# Fill df with 0 where mask is 0
df = df.where(rand_zero_one_mask==0, 0)

Note: df.where is not to be confused with np.where


Making an efficient and healthy db call for a real-time browser game

The power of the aggregation framework is it's ability to iterate over the dataset in various useful ways without incurring extra round trips between the database and the app.

Your code uses one stage for aggregation (grouping by id1), and then jumps out of aggregation to iterate over the entire FUNDS collection for every user. That is very expensive, giving you exponential time complexity or worse.

The code below makes the database do all the heavy lifting in 3 aggregation framework stages, and returns an array with all the necessary data.

pivot over the user_id, calculating invest_amount, saving unique records in an array called records
unwind records. Now you have your original documents, but with a useful extra field.
calculate profit

Then we end up with an array of objects which can be iterated over, applying the the $inc update.

FUNDS.aggregate([
    {
        "$group": {
            "_id": '$id1',
            "invest_total": {"$sum": "$invest_amount"},
            "records": {"$push": "$$ROOT"}
        }
    },
    {
        "$unwind": "$records"
    },
    {
        "$project": {
            "invest_id": "$records.invest_id",
            "user_id": "$records.id1",
            "invest_total": "$invest_total",
            "invest_amount": "$records.invest_amount",
            "profit": {
                "$divide": [
                    { "$multiply": ["$records.invest_amount", AN_AMOUNT_FROM_SITE ] },
                    "$invest_total"
                ]
            }
        }
    }
]).exec(function(err,docs){
    docs.forEach(function(d){
        FUNDS.findOneAndUpdate(
            { "invest_id": d.invest_id},
            { "$inc": { 'invest_profit': d.profit } },
            function(e3){
                callback();
            }
        );
    });
});


concatenation of HTML from return functions

Use a template engine like Twig, Plates or Blade.

You should have base layouts, partials and templates.


Circular buffer implementation for buffering TCP socket messages

A few minor notes:

Comments like the following are unnecessary:

private T[] array; // storage

You could call the field as storage and remove the comment.
A "solution" for the warning in the constructor:

@SuppressWarnings("unchecked")
private T[] newArray(int length) {
    return (T[]) new Object[length];
}

Reference: Java how to: Generic Array creation
camelCase variable and method names are more common in Java than underscored ones. (Code Conventions for the Java Programming Language, 9 - Naming Conventions)
From Code Complete, 2nd Edition, p761:

  Use only one data declaration per line

  [...]

  It’s easier to modify declarations because each declaration is self-contained.

  [...]

  It’s easier to find specific variables because you can scan a single
  column rather than reading each line. It’s easier to find and fix
  syntax errors because the line number the compiler gives you has
  only one declaration on it.

Setting default integer field values to zero is unnecessary in the constructor since zero is the default int value:

getIdx = 0;
putIdx = 0;
count = 0;

Does it make sense to create a CircularBuffer instance with zero size? If not check it and throw an IllegalArgumentException in the constructor.
The second insert method might be a premature optimization.
I'd throw IllegalStateException instead of ArrayIndexOutOfBoundsException. The clients of the class should not know that it uses an array (or anything else) for storage.
Here are a few unit tests:

@Test(expected = IllegalArgumentException.class)
public void testZeroSize() {
    new CircularBuffer<String>(0);
}

@Test
public void testIsEmptyOnNewBuffer() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    assertTrue(buffer.isEmpty());
}

@Test
public void testIsFullOnNewBuffer() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    assertFalse(buffer.isFull());
}

@Test
public void testIsEmpty() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    assertFalse(buffer.isEmpty());
}

@Test
public void testIsFull() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.insert("b");
    buffer.insert("c");
    assertTrue(buffer.isFull());
}

@Test
public void testIsEmptyAfterReset() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.reset();
    assertTrue(buffer.isEmpty());
}

@Test
public void testIsFullAfterReset() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.insert("b");
    buffer.insert("c");
    buffer.reset();
    assertFalse(buffer.isFull());
}

@Test
public void testIsEmptyOnUsedBuffer() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.insert("b");
    buffer.insert("c");

    assertFalse("isEmpty 1", buffer.isEmpty());
    buffer.get();
    assertFalse("isEmpty 2", buffer.isEmpty());
    buffer.get();
    assertFalse("isEmpty 3", buffer.isEmpty());
    buffer.get();
    assertTrue("isEmpty 4", buffer.isEmpty());
}

@Test
public void testIsFullOnUsedBuffer() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.insert("b");
    buffer.insert("c");
    buffer.get();

    assertFalse("isFull 1", buffer.isFull());
    buffer.get();
    assertFalse("isFull 2", buffer.isFull());
    buffer.get();
    assertFalse("isFull 3", buffer.isFull());
}

@Test
public void testInsert() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.insert("b");
    buffer.insert("c");
}

@Test(expected = IllegalStateException.class)
public void testInsertFull() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.insert("b");
    buffer.insert("c");
    buffer.insert("d");
}

@Test(expected = IllegalStateException.class)
public void testGetOnEmptyBuffer() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.get();
}

@Test(expected = IllegalStateException.class)
public void testGetOnEmptyUsedBuffer() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.get();

    buffer.get();
}

@Test
public void testGet() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    assertEquals("a", buffer.get());
    buffer.insert("b");
    buffer.insert("c");
}

@Test
public void testDelayedGet() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.insert("b");
    buffer.insert("c");
    assertEquals("a", buffer.get());
}

@Test
public void testInsertAndGetTwice() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    buffer.insert("b");
    buffer.insert("c");
    assertEquals("a", buffer.get());
    assertEquals("b", buffer.get());
    assertEquals("c", buffer.get());

    buffer.insert("d");
    buffer.insert("e");
    buffer.insert("f");
    assertEquals("d", buffer.get());
    assertEquals("e", buffer.get());
    assertEquals("f", buffer.get());
}

@Test
public void testGetAndInsert() {
    final CircularBuffer<String> buffer = new CircularBuffer<String>(3);
    buffer.insert("a");
    assertEquals("a", buffer.get());

    buffer.insert("b");
    assertEquals("b", buffer.get());

    buffer.insert("c");
    assertEquals("c", buffer.get());

    buffer.insert("d");
    buffer.insert("e");
    assertEquals("d", buffer.get());
    assertEquals("e", buffer.get());

    buffer.insert("f");
    assertEquals("f", buffer.get());

    assertTrue("empty", buffer.isEmpty());
}

(I've renamed a few methods.)


This snippet of scheme calculates a value in pascal's triangle

Yes, those inner functions do get reassigned at each invocation, but that's cheap. In sane implementations, the inner function bodies are compiled just once, with a new lexical environment attached each time.

(In other sane implementations, the inner functions could be inlined into the outer function, but still, it's only compiled once, not for every invocation.)

So don't worry about the performance, it's not as bad as you may think. :-)


TL;DR:

Do not write explicit types!  Symbolic processing is easy in OCaml, use it to your advantage instead of mimicking cryptic algorithms which are only useful in languages where symbolic processing is a pain – as C, C++ or Java.

In OCaml, we never write explicitly write types, as they do in C++ or Java. There is usually no point to do that, since the compiler computes the types for you. If you want to see the types inferred, you can use the -i option of the compiler, or better, use merlin to see the types interactively.

When we write larger programs, we write signature files where we specify the signatures of public functions and abstract types, but this more a software engineering technique you should not bother much while you do your very first steps.

If you do not have to handle the typing information by yourself, your code is much easier to edit, take advantage of this freedom instead of binding yourself again with your old ties!

I could let your code run after a few minor modifications and found out it did not work as expected.  When I read your code, I have difficulties to understand what happens, it is probably a bit too clever – and broken.

There is an important object of the problem that does not appear in your code, it is the abstract syntactic tree (AST) associated to your expression.  If you can generate it from infix, it is trivial to generate the prefix or postfix expression out of it.  In languages like C, C++ or Java, working with ASTs is painful, but ML languages were designed to make this easy.

Here is how we define the type of arithmetic expressions:

  type t =
    | Integer of int
    | Binary of binary * t * t
  and binary =
    | Add
    | Sub
    | Mult
    | Div

It is very easy to handle, say if you want to evaluate an expression

  let rec eval = function
  | Integer(k) -> k
  | Binary(op, a, b) ->
     (match op with
      | Add -> ( + )
      | Sub -> ( - )
      | Mult -> ( * )
      | Div -> ( / )) (eval a) (eval b)

or implement algebraic expansion

  let rec expand = function
  | (Integer(_) | Binary((Add | Sub), _, _)) as a -> a
  | Binary(Mult, Binary(Add, a, b), c) -> …

I do not write the full function, but I hope you get the idea.

Now, the best way to solve our problem is to write a parser converting infix expression from their concrete syntax to an AST.  In practical situations, we should use ocamllex and ocamlyacc to generate the lexer and the parser for arithmetic expressions, but let us write everything manually.

The first step is lexing, which you got pretty right, but let me rewrite it this way, defining a type for tokens and using a more capable regular expression:

  type token =
    | INTEGER of int
    | ADD
    | SUB
    | MULT
    | DIV

  let lexer s =
    let open Str in
    split (regexp " +\\|\\b *") s
    |> List.map
      (function
        | "+" -> ADD
        | "-" -> SUB
        | "*" -> MULT
        | "/" -> DIV
        | n -> (try INTEGER(int_of_string n)
                with _ -> ksprintf failwith "lexer: Invalid token: %s" n))

You can see the \b code for word boundary, it allows to process correctly text with fewer spaces:

# lexer "1+41*2-5/ 7";;
- : token list =
[INTEGER 1; ADD; INTEGER 41; MULT; INTEGER 2; SUB; INTEGER 5; DIV; INTEGER 7]

Once we have converted the string to a token list, it is very easy to analyse its structure, using a continuation-passing-style-mutually-recursive-functions which is much easier as the pedantic designation I wrote can suggest it. :)

We first need a help function

  let _binop op a b =
    Binary(op, a, b)

Now the parser itself looks like this:

  let rec parser_entry cont =
    function
    | [] -> failwith "Unexpected end of input"
    | INTEGER(k) :: ADD :: tl -> cont(parser_entry (_binop Add (Integer(k))) tl)
    | INTEGER(k) :: SUB :: tl -> cont(parser_entry (_binop Sub (Integer(k))) tl)
    | INTEGER(k) :: MULT :: tl -> cont(parser_mult (_binop Mult (Integer(k))) tl)
    | INTEGER(k) :: DIV :: tl -> cont(parser_mult (_binop Div (Integer(k))) tl)
    | INTEGER(k) :: [] -> cont (Integer(k))
    | _ -> failwith "Syntax error"
  and parser_mult cont =
    function
    | [] ->  failwith "Unexpected end of input"
    | INTEGER(k) :: ADD :: tl ->
        (_binop Add (cont (Integer(k)))) (parser_entry (fun x -> x) tl)
    | INTEGER(k) :: SUB :: tl ->
        (_binop Sub (cont (Integer(k)))) (parser_entry (fun x -> x) tl)
    | INTEGER(k) :: MULT :: tl ->
        cont (parser_mult (_binop Mult (Integer(k))) tl)
    | INTEGER(k) :: DIV :: tl ->
        cont (parser_mult (_binop Div (Integer(k))) tl)
    | INTEGER(k) :: [] -> cont (Integer(k))
    | _ -> failwith "Syntax error"
  and parser lst =
    parser_entry (fun x -> x) lst

The parser_entry function is the entry point for the parser and parser_mult reads multiplications and divisions.  The functions have two parameters cont the famous continuation and the list of tokens they need to process.  The continuation encodes the current state of the parser, it is reminiscent of the stack found in LALR parsers. As you see, when parsing in the entry point, the continuation is the outermost function called but in when parsing operators with a priority, the continuation is deeply nested, which is how the priority is represented in the program. Let's try our parser:

# parser(lexer("1"));;
- : t = Integer 1
# parser(lexer("1 +2 - 3"));;
- : t =
Binary (Add, Integer 1, Binary (Sub, Integer 2, Integer 3))
# parser(lexer "1+41*2-5/ 7");;
- : t =
Binary (Add, Integer 1,
 Binary (Sub, Binary (Mult, Integer 41, Integer 2),
  Binary (Div, Integer 5, Integer 7)))

Now it is is trivial to convert an abstract expression to prefix notation:

  let rec to_prefix_string = function
    | Integer(k) -> string_of_int k
    | Binary(op, a, b) ->
        String.concat " " [
          (match op with
           | Add -> "+"
           | Sub -> "-"
           | Mult -> "*"
           | Div -> "/");
          to_prefix_string a;
          to_prefix_string b
        ]

The advantage of symbolic processing is that the code is very explicit!  Now we write a convenience function:

  let infix_to_prefix s =
    to_prefix_string(parser(lexer s))

and try it!

# infix_to_prefix "1+41*2-5/ 7";;
- : string = "+ 1 - * 41 2 / 5 7"


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

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Isolate platform-specific code

If you must have stdafx.h, consider wrapping it so that the code is portable:

#ifdef WINDOWS
#include "stdafx.h"
#endif

Make sure you have all required #includes

The code uses std::find but doesn't #include <algorithm>.

Be careful with signed and unsigned

In the current helper and interleave routines, the loop integer i and j are both signed int values, but they're being compared with size_t quantities (which are unsigned) s1.size() and s2.size().  Better would be to declare them all as size_t.

Understand how #include works

On most platforms, the difference between #include "iostream" and #include <iostream> is that the former looks first in the current directory.  So for system files such as iostream, you should really use #include <iostream> instead.  See this question for more details.

Rethink your algorithm

The result of this program is somewhat peculiar.  If we run it with ab and 12 we get this:

  a1b, ab1, a1b2, a12b

This seems to be incorrect because the first two don't include all of the input letters and none of the combinations begin with 1 and the combination ab12 is not listed. If this is intended, then it's just the description that is faulty.  If not, it's a bug and should be fixed.

Hide internal object details

If the sole purpose for the object is to create a vector of interleaved strings, it seems to me that interleave should actually return a vector of strings rather than keeping it as an internal object.  The helper function should also be made private if it's not intended to be used externally.  Finally, if the object has no data, as per this recommendation, the member functions can all be declared static so that no object instantiation need exist to use the function.

Pass by const reference where practical

All of the std::string arguments are being passed by value, which cause the argument to be duplicated. Better would be to make each of them const std::string & because they are not modified and don't need to be duplicated.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Find the cheapest shipping option based on item weight

premium_cost

There is no reason to include the return of this premium_cost in ground_shipping_cost. Use a different method here

DRY

You are correct. There are too many if statements. If you want to introduce an new threshold for the cost, this will include a adding an extra clause, and changing the limits for the preceding and following thresholds. This is just waiting for errors to pop up. Better would be to keep a dict of the thresholds, and iterate over them to get this price factor:

def ground_shipping_cost(weight):
    thresholds = {2: 1.5, 6: 3.0, 10: 4.0, float("inf"): 4.75}
    flat_cost = 20
    for threshold, factor in sorted(thresholds.items()):
        if weight <= threshold:
            break
    return flat_cost + weight * factor

thresholds is a dict, with the cost per weight unit as value, and the threshold as key.

The drone_shipping_cost can be tackled comparably.

Now you have 2 methods that, starting from a list of thresholds, tries to determine the cost factor. We can easily refactor this out:

def get_factor(thresholds, value):
    for threshold, factor in sorted(thresholds.items()):
        if value <= threshold:
            return factor

def ground_shipping_cost(weight):
    thresholds = {2: 1.5, 6: 3.0, 10: 4.0, float("inf"): 4.75}
    flat_cost = 20
    return flat_cost + get_factor(thresholds, weight)

def drone_shipping_cost(weight):
    thresholds = {2: 4.5, 6: 9.0, 10: 12.0, float("inf"): 14.75}
    return weight * get_factor(thresholds, weight)

Cheapest costs

Your cheapest_shipping method calculates the costs for the different shipping methods, finds the cheapest one and formats this into a string. This string formatting is also very repetitive, and should be done somewhere else. cheapest_shipping will be the most clear if it only returned which method is the cheapest, and the corresponding cost. This also allow you to test this method with unit tests further on.

Since methods are real objects in Python, and you can pass references to them on and store these in dicts, calculating the costs for the different methods can be simplified a lot:

def cheapest_shipping(weight):
    methods = {
        "drone": drone_shipping_cost,
        "standard ground": ground_shipping_cost,
        "premium ground": lambda weight: 125,
    }
    results = {method: calculation(weight) for method, calculation in methods.items()}

To look for the cheapest option among those, you can use the built-in min:

cheapest_method = min(results, key=lambda method: results[method])

return cheapest_method, results[cheapest_method]

Note: the lambda weight: 125 is the equivalent of

def premium_shipping(weight):
    return 125

and "premium ground": premium_shipping, in the methods dict

And this can be called and formatted using str.format or f-strings in Python 3.6+

method, cost = cheapest_shipping(4)
f"You should use {method} shipping as it will only cost {cost}"

'You should use standard ground shipping as it will only cost 23.0'

Further refactoring

You can even refactor this one step further, and have 1 generalized cost calculation method that take a flat_cost and thresholds as arguments

def get_shipping_cost(weight, thresholds=None, flat_cost=0):
    if thresholds is None:
        return flat_cost
    return flat_cost + weight * get_factor(thresholds, weight)

then you can define the different shipping methods like this:

shipping_methods = {
    "drone": {"thresholds": {2: 4.5, 6: 9.0, 10: 12.0, float("inf"): 14.75}},
    "standard ground": {
        "flat_cost": 20,
        "thresholds": {2: 1.5, 6: 3.0, 10: 4.0, float("inf"): 4.75},
    },
    "premium ground": {"flat_cost": 125},
}

def cheapest_shipping2(methods, weight):
    results = {
        method: get_shipping_cost(weight, **parameters)
        for method, parameters in methods.items()
    }
    cheapest_method = min(results, key=lambda method: results[method])
    return cheapest_method, results[cheapest_method]

method, cost = cheapest_shipping2(shipping_methods, 4)

different min

Instead of using min with the cost as key, you can reverse the results dictionary:

def cheapest_shipping2(methods, weight):
    results = {
        get_shipping_cost(weight, **parameters): method
        for method, parameters in methods.items()
    }

    cost, method = min(results.items())
    return method, cost

In case of an ex aequo, this can have different results than the other method

even further refactoring.

Now all shipping methods are calculated with get_shipping_cost. If you want to use different functions for the different shipping methods, you can do something like this:

def cheapest_shipping3(methods, weight, default_cost_method=get_shipping_cost):
    results = {
        parameters.pop("method", default_cost_method)(
            weight, **parameters
        ): method
        for method, parameters in methods.items()
    }
    cost, method = min(results.items())
    return method, cost

shipping_methods2 = {
    "drone": {"thresholds": {2: 4.5, 6: 9.0, 10: 12.0, float("inf"): 14.75}},
    "standard ground": {
        "flat_cost": 20,
        "thresholds": {2: 1.5, 6: 3.0, 10: 4.0, float("inf"): 4.75},
    },
    "premium ground": {"method": lambda weight: 125},
}

method, cost = cheapest_shipping3(shipping_methods2, 4)

please note that the parameters.pop mutates the original shipping_methods2 after the execution:

{
    "drone": {"thresholds": {2: 4.5, 6: 9.0, 10: 12.0, inf: 14.75}},
    "standard ground": {
        "flat_cost": 20,
        "thresholds": {2: 1.5, 6: 3.0, 10: 4.0, inf: 4.75},
    },
    "premium ground": {},
}

To prevent this, we need to make a copy of the methods:

def cheapest_shipping3(methods, weight, default_cost_method=get_shipping_cost):
    methods_copy = {
        method: parameters.copy()
        for method, parameters
        in methods.items()
    }
    results = {
        parameters.pop("method", default_cost_method)(
            weight, **parameters
        ): method
        for method, parameters in methods_copy.items()
    }
    cost, method = min(results.items())
    return method, cost


Stack implementation using arrays in Java

As mentioned in @rolfl's to your later question, there is limited value in this class as elements cannot be easily retrieved.

Putting aside the obvious improvements to the seemingly toy implementations, you have a mistake in describing whether the stack has 'overflow' or 'underflow': the meanings should be inversed. When you try to push(int) to a full stack, that is known as an overflow, and you need to check whether the stack is empty when pop()-ping instead of checking for 'overflows'.

To better indicate error conditions such as those mentioned above, you can make use of throwing Exceptions instead of a simple System.out.println(). In fact, I will suggest using System.err.println() at the very least to differentiate between normal and error 'outputs'.

A Java 8 way of printing the contents of the stack is to use Arrays.stream(int[]):

public void display() {
    Arrays.stream(stack).forEach(System.out::println);
}

This uses System.out.println(int) as a method reference to print each int value on the console.

Simply running through some test operations in the main() method is also barely enough, you should consider proper unit testing techniques such as using a testing framework that can arrange-act-assert for you.

Last but not least, you should also take a look at the standard JDK classes' stack implementations for greater inspiration, such as the Deque interface.


Instead of a count variable and reusing current,
I think it's neater to use two pointers:

Node runner = head;
for (int i = 0; i < n; i++) {
    runner = runner.next;
}
Node current = head;
while (runner.next != null) {
    runner = runner.next;
    current = current.next;
}
return current.data;

Other than that, your implementation is fine, except for a few tiny style points that are barely worth mentioning, but here we go anyway:

The commented out instructions about method-only submissions are unnecessary
Add a space after commas in parameter list


LeetCode heater binary search solution (w recursion) optimisation

Performance The main optimization that can be made here is to, while iterating over the sorted houses, to inch along the heaters one-by-one while testing their distance. Increment a heater index only if the difference between the house and the next heater is less than the difference between the house and the current heater. This way, whenever a heater is tested, if the distance between it and the current house has become too great, that heater never gets tested again.
For example, when iterating over 5 houses and 5 heaters, the persistent indicies for each collection being used by the algorithm could look like this:
Indicies being examined:
houses heaters
0      0
1      0
2      0
2      1   // at this point, heater 1 is found to be closer to house 2 than heater 0
2      2   // heater 2 is found to be closer to house 2 than heater 1
3      2
4      2
4      3
4      4
5      4
5      5

And that's it. And, of course, on every iteration, check the distance difference between the heater and the house, and call Math.max on that difference and the current distance record to get the new distance record.
This approach reduces the overall computational complexity from O(n log m) (a binary search for every house) to O(n + m).
function findRadius(houses, heaters) {
    houses.sort((a, b) => a - b);
    heaters.sort((a, b) => a - b);
    // Persistent variable of the current closest heater to the house being iterated over
    let closestHeater = heaters[0];
    // and its index
    let closestHeaterIndex = 0;
    // Current record of needed heater radius
    let requiredRadius = 0;

    for (let i = 0, len = houses.length; i < len; i++) {
        let lastDiff = Math.abs(houses[i] - closestHeater);
        // If we aren't at the end of the heater array,
        // test the next heater to see if we need to increment the heater index:
        while (heaters[closestHeaterIndex + 1]) {
            const nextDiff = Math.abs(heaters[closestHeaterIndex + 1] - houses[i]);
            if (nextDiff > lastDiff) break;
            // This heater is closer to houses[i] than the current one in closestHeater
            lastDiff = nextDiff;
            closestHeaterIndex++;
            closestHeater = heaters[closestHeaterIndex];
        }
        requiredRadius = Math.max(requiredRadius, lastDiff);
    }
    return requiredRadius;
}

Result (screenshot):

Runtime: 88 ms, faster than 98.89% of JavaScript online submissions for Heaters.

Memory Usage: 42.6 MB, less than 5.56% of JavaScript online submissions for Heaters.

A couple other notes regarding your code:
Save array length If performance is an issue (it rarely is except in these competitions), you can save the current length of the array in a for loop in a variable to save a bit of calculations, like I did above:
for (let i = 0, len = houses.length; i < len; i++) {

Branches are expensive Logical branches like if and else are often required, but keep in mind that they generally slow things down more than most other operations:

As a general rule of thumb, branches are slower than straight-line code (on all CPUs, and with all programming languages). -jmrk, V8 developer

If you have a lot of branches, your code may not be as fast as you'd want it to be. Reduce them when possible if performance really is an issue.
Braced blocks create environments - or environment records, which are internal mappings of identifiers to their variable names. If you follow the specification exactly, having such blocks results in a bit more operations being performed. I'm not sure if it's an issue with modern engines, or if they can optimize it away completely, but leaving off { and }s when the block contains only a single statement might make things a smidgen faster. (But on the other hand, leaving off braces arguably makes the code a bit harder to read...)
Use representative variable names You defined the function as
function findRadius  (houses, heater) {

but heater is a collection of heaters; seeing heater.sort((a,b) => a-b) confused me at first glance. Best to name collections something plural, probably.


How can I make this C++ code to obtain passwords more efficient?

Regarding your program's efficiency, remember that premature optimisation is the root of all evil. Looking at your program, I can tell that your program will be IO bound - meaning that the computer will spend longer waiting for the user to input the data than actually executing your program. Moreover, functions like std::cout which deal with output, include inevitable slow system calls, which will be far costly in time than your algorithm. So performance should not be a concern here ! :)
The only thing I would say about your program efficiency is const string PASSWORD = "PASSWORD"; which will use unnecessary copying and heap allocation. It is better to preserve the original type of the string like so:
const auto PASSWORD = "PASSWORD";  (Here auto (assuming c++11) deduces the type for you, but the real type of the string is const char* if you want to know)
CODE REVIEW
These are the style/ readability points I would make on your code.

Use proper indentation (this might due to copy pasting on codereview so I don't blame you for that)
Do not use using namespace std - this will lead to naming collisions and all sort of horrible errors. Better to use the std:: every-time instead.
You might consider to put the variable PASSWORD inside main as a static const variable, this will limit the visibility of PASSWORD.
Use a better variable name than c.
If your program gets bigger, consider wrapping your algorithm inside a function, this might help to make the main function a bit neater.

That's all! Well done, I would say generally this is very well written, readable c++ code.


I would say that the first one is a bit more readable, while the second one is a bit more extendable.

Note though that the functions are not actually the same. For example . a . will produce different results.

Also, personally, I would extract the array from the body of the second function to make it actually reusable:

$str = "my string";
$chars = array('.', ',', '-', '/');
$cleaned_str = str_cleaner($str, $array);

function str_cleaner($str, $chars)
{
    foreach($chars as $char) {
        $str = str_replace($char, '', trim($str));
    }
    return $str;
}

Of course, this is also more complex than it needs to be, as str_replace actually accepts an array:

$chars = array('.', ',', '-', '/');
$cleaned_str = str_replace($chars, "", $str);


You have such properties as ExerciseFilter and DateFilter that I guess return respecitively the ExerciseId and (EndDate - StartDate).TotalMinutes or something similar. Thus, I find it would be much easier to understand your filter class if you renamed the ExerciseFilter to ExerciseId and replaced both properties with CanApplyExerciseFilter and CanApplyDateFilter. This would result in a much cleaner code:

if (model.CanApplyExerciseFilter && !model.CanApplyDateFilter)
{
    baseFilter = baseFilter.AndAlso(exerciseFilter);
}

if (!model.CanApplyExerciseFilter && model.CanApplyDateFilter)
{
    baseFilter = baseFilter.AndAlso(timeSpanFilter);
}

if (model.CanApplyExerciseFilter && model.CanApplyDateFilter)
{
    baseFilter = baseFilter.AndAlso(timeSpanFilter).AndAlso(exerciseFilter);
}

which would finally lead us to just two lines of code here:

baseFilter =
    baseFilter
        .AndAlso(model.CanApplyExerciseFilter ? exerciseFilter : x => true)
        .AndAlso(model.CanApplyDateFilter ? timeSpanFilter : x => true);


correct - As far as I can tell, yes.
concise - A filter() followed by a .length (or .size) can be simplified:
large.sliding(small.length).count(_.diff(small).isEmpty)
fast - Could be faster, but it wouldn't be as concise.

Consider the following: findPermutations("abcxcba", "cab")
Under the current design that would be 5 invocations of _.diff(small).isEmpty, but 3 of the 5 are rather pointless. No test string containing a character not found in the target string is worth the effort.
It'd be nice if the sliding window could "jump" over non-target characters. Doable, but not trivial.


Pizza-making combining two builder patterns (Bloch's and Go4)

I'm not familiar with the given pattern, but there are still a few things that should be pointed out.

The method Maker in Pizza should not start with an uppercase letter.

The fields in the Recipe constructor are useless, as an int is automatically given the value of 0 if no other value is assigned to it.

public Recipe() {
    baseSize = 0;
    a = 0;
    b = 0;
    c = 0;
}

should be

public Recipe() {}

The class Recipe has the following methods: changeA(), changeB() and changeC(). However, it also has prepare1(), prepare2() and prepare3().

Though it is a wild guess from my part, I assume that prepare1() is related to the field a, prepare2() is related to b and prepare3() is related to c. Why are the methods not named prepareA(), prepareB() and prepareC() instead?

Which brings me to my next point:

Even if you are experimenting with a pattern, you should still take the time to use relevant method and field names.

Sure, you're learning on the moment, but tomorrow (or in the future), will you be able to make sense of the field names you used? Will you be able to remember what you learned if you base yourself on an unclear example?

Some good examples could have been:

changeToppings() and prepareToppings()
changeSauce() and prepareSauce()
changeCrust() and prepareCrust()

etc.

Obviously, I have no knowledge at all regarding cooking, but I am sure that a recipe with the fields baseSize, toppings, sauce and crust is much more descriptive than a recipe with baseSize, a, b and c.

The following is a tip, so take it or leave it.

When I experiment with patterns, I fully immerse myself in the example I create.

In your case, you decided to use pizzas. Commit to it - use fields like toppings, crust, sauce, cheese, etc. and methods like cook, cut, etc. If you're going to call your class Pizza, it has to be feel like a pizza -- and I've never seen a pizza made of a, b and c. If you really have no idea, then you could use toppingA, toppingB and toppingC, as long as it makes sense.

I don't know if this applies to everybody, but to me, I find it easier to learn/remember something new when I use full words rather than non-descriptive characters

e.g.:

The likelihood of remembering

  Oh yeah, that's right, the Pizza class had a topping, a crust and a sauce!

vs

  Oh yeah, that's right, the Pizza class had an a, a b and a c!"


I would consider creating an Arrow type from Arg[A] to Arg[B], something like:

import scalaz.Arrow // Also available in Cats

case class ArgArrow[A, B](run: Arg[A] => Arg[B])

object ArgArrow {
  implicit val arrowInstance: Arrow[ArgArrow] = new Arrow[ArgArrow] {
    def arrTry[A, B](f: A => Try[B]): ArgArrow[A, B] = ???
    def arrOption[A, B](f: A => Option[B]): ArgArrow[A, B] = ???
    // implement other required functions
  }
}

With Arrow, it will be very easy to assemble different things together, for example, you can easily combine an A => B, an A => Try[C], and an A => Option[D] into an ArgArrow[A, (B, C, D)].


The initial data is not formatted as proper JSON. There appear to be mismatched quotes around values like front, back, etc... try running the snippet below to see the error that is caused by this.

const blueprints = {
  12: {color: red, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
  231: {color: white, views: [{name: "front}, {name: "back}]},
  73: {color: black, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
  4: {color: silver, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
}

Also, unless red, white, black and silver are defined as variables, they need to be enclosed in quotes as string literals. See the rewrite below for a sample of this.

The indentation is inconsistent- the first level in the .map() callback is four spaces and then two spaces within the if block. Stick with one or the other.

You could use Array.prototype.reduce() to conditionally add the desired elements to an output array, reducing the need to call .filter():
const result = idArray.reduce((output,id) => {
  const bluePrint = bluePrints[id];
  //conditionally add to output and then return it
  return output;
}, []);

You could also use Object.keys() to iterate over the keys of bluePrints instead of idArray, though it appears to be slightly slower (see performance link below).
const result = Object.keys(bluePrints).reduce((output,id) => {
  const bluePrint = bluePrints[id];
  //conditionally add to output and then return it
  return output;
}, []);

See a comparison of the three snippets in this jsPerf.

One other change for readability would be to move that filter function outside the call to .map() or .reduce():
const viewIsTopOrBottom = view => view.name === 'top' || view.name === 'bottom'

Then that function can be called within the call to .some():
const exists = bluePrint.views.some(viewIsTopOrBottom);

And then that boolean exists could be eliminated by moving the call to .some() into the conditional statement of the if:
if (bluePrint.views.some(viewIsTopOrBottom)) {
  //add to array

Proposed Rewrite

const idArray = ["12", "231", "73", "4"];
  const bluePrints = {
    12: {color: "red", views: [{name: "front"}, {name: "back"}, {name: "top"}, {name: "bottom"}]},
    231: {color: "white", views: [{name: "front"}, {name: "back"}]},
    73: {color: "black", views: [{name: "front"}, {name: "back"}, {name: "top"}, {name: "bottom"}]},
    4: {color: "silver", views: [{name: "front"}, {name: "back"}, {name: "top"}, {name: "bottom"}]},
  };
const viewIsTopOrBottom = view => view.name === 'top' || view.name === 'bottom';
const result = idArray.reduce((output,id) => {
  const bluePrint = bluePrints[id];
  if (bluePrint.views.some(viewIsTopOrBottom)) {
    output.push({
      colorId: id,
      views: bluePrint.views
    });
  }
  return output;
}, []);
console.log('result,', result);


Bitwise operation to get the weekday name

days_name? Shouldn't that rather be day_names? Actually, given its function it should probably be weekdays
Shouldn't "sar" be "sat" for Saturday? Never seen it abbreviated "sar"
The opposite of "all" is "none" - not "no"
Day names are capitalized in English, so "Mon", "Tue", "Wed", etc.
You rarely need to create an array and then push items to it. It's easier to simply filter a complete array. But if you do need to create an empty array, just use [] - no need for Array.new

Sticking close to your current code, I'd do this

def weekdays(hex)
  value = hex.to_i(16)
  case value
  when 127
    'All'
  when 0
    'None'
  else
    days = %w(Mon Tue Wed Thu Fri Sat Sun)
    days.each_with_index.select { |_, i| value & 2**i > 0 }.map(&:first).join(" ")
  end
end

However, I'd probably prefer a method that simply returns an array of day names, rather than a string. Then let other code check and join the array as needed.

Something like this

def weekdays(hex)
  value = hex.to_i(16)
  days = %w(Mon Tue Wed Thu Fri Sat Sun)
  days.each_with_index.select { |_, i| value & 2**i > 0 }.map(&:first)
end

Update: As tokland points out in the comments, it'd be cleaner to use map.with_index plus compact, rather than each_with_index.select plus map. I.e.

def weekdays(hex)
  value = hex.to_i(16)
  days = %w(Mon Tue Wed Thu Fri Sat Sun)
  days.map.with_index { |day, i| day if value & 2**i > 0 }.compact
end

or, for the first code block

def weekdays(hex)
  value = hex.to_i(16)
  case value
  when 127
    'All'
  when 0
    'None'
  else
    days = %w(Mon Tue Wed Thu Fri Sat Sun)
    days.map.with_index { |day, i| day if value & 2**i > 0 }.compact.join(" ")
  end
end

As mentioned in the comments, I happened to make a gem for weekday bitmasks a while back, which you might find useful. The major difference is that the gem expects Sunday to be zero, Monday to be 1 and so forth (like Date#wday and most other date APIs).


Optimize function that does phrase-search and lists them

To improve the performance of code, a good plan is to:

Identify the hotspots, for example using profiling.
Prepare a representative test case and measure its performance.
Experiment with changes and see which ones improve the performace.

Step (2) is very important — if we don't have a representative test case then we might end up measuring the wrong thing. In this case I understand from the post that in the real program:

There are few sentences (tens), mostly 100 words or fewer.
There are many phrases (250,000), mostly with 5 words or fewer.
The matches are quite sparse (most sentences have no phrases).
The sentences change between calls to makeGsList but the phrases remain the same for each call.

So my test case is going to use your sentences list (8 elements is reasonably close to "10–20"), but I'm going to have to make my own phrases list, because you've only given me 7 elements which is nowhere near to 250,000.

>>> words = [line.strip().lower() for line in open('/usr/share/dict/words')]
>>> len(words)
235886
>>> from random import sample, randrange
>>> m_phrases = [' '.join(sample(words, randrange(1, 6))) for _ in range(250000)]

and then I'll time ten executions of makeGsList using Python's timeit module:

>>> from timeit import timeit
>>> timeit(lambda:makeGsList(sentences, 'm'), number=10)
2.7161848249379545

This is roughly similar to your reported results, so it might be representative enough. Now to try some changes.

First, let's tidy the code.

Instead of converting StartWords to a tuple for each sentence, convert it just once.
Instead of taking an org argument (and then checking it for each sentence), take a phrases argument.
Instead of maintaining a list gs_list2 and then converting it to a set to remove duplicates, maintain a set instead.

Revised code (this isn't noticeably faster, but it's in a better shape to work on):

def makeGsList2(sentences, phrases):
    "Return list of elements of phrases that appear in any of the sentences."
    start_words = tuple(StartWords)
    gs_set = set()
    for s in sentences:
        if s.startswith(start_words):
            s = s.lower()
            for phrase in phrases:
                if phrase in s:
                    gs_set.add(phrase)
    return list(gs_set)

It's clear that we have to avoid the loop over the phrases for each sentence. What we can do instead is to pre-process the phrases into a data structure that we can apply once to each sentence. What we need here is the Aho–Corasick algorithm. This isn't built into Python, but we could try one of the packages from PyPI. In the code below I'm using the pyahocorasick package; see the documentation for details.

import ahocorasick

def make_automaton(phrases):
    """Return an ahocorasick.Automaton that matches any of the phrases."""
    automaton = ahocorasick.Automaton()
    for phrase in phrases:
        automaton.add_word(phrase, phrase)
    automaton.make_automaton()
    return automaton

def makeGsList3(sentences, automaton):
    "Return list of unique matches of the automaton against the sentences."
    start_words = tuple(StartWords)
    gs_set = set()
    for s in sentences:
        if s.startswith(start_words):
            gs_set.update(phrase for _, phrase in automaton.iter(s.lower()))
    return list(gs_set)

Building the automaton takes a few seconds but it can be done just once for each list of phrases:

>>> m_automaton = make_automaton(m_phrases)

And then the actual search is very quick:

>>> timeit(lambda:makeGsList3(sentences, m_automaton), number=10)
0.0021720759104937315

This is about 1,200 times faster than the code in the post! Of course, this result only stands up to the extent that my test case is representative of the real system.


Scraping SEDE query results with caching

It shows that you've written code before, so style wise there is not much to comment upon. What I would like to comment upon is a few points on code structure:

Single responsibility concern – Your function is name fetch_sede_soup() and all actions are related to this. However it still creates the CACHE_DIR if needed, write output files, verifies validity in inner function. This could be separated into more functions, although it is not extremely large and hard to get the overview of.

One point I would at least add a new function is related to the return soup near the middle. Code after this seems to be error handling, but it is somewhat hidden by the return and as such it is not very clear. If you moved the remaining part into a function you would see a return soup followed by a else: clause calling the error handling.
Add comments and docstrings – As a side effect of the different aspects your function handles, I would at least add more comments within the code. This could justify keeping more within the larger function, whilst still maintaining readability
Add error handling around mkdir – Especially around external os calls, like mkdir, I would add try ... except code to handle potential error situations. This code related to creating the CACHE_DIR could possibly be done before this method is called as part of initialization.

But in general, nice, clean code, but a little thin on documentation and error handling of os-operations.


Run multiple python codes and Check with answer data

Here is something I would improve:

fix the variable naming - according to PEP8, use lower case and separate words with an underscore - e.g. _grade_file instead of _gradeFile
use argparse  module instead of manually reading from sys.argv - you will get the auto-generated command-line help for free and it is generally more readable, structured and scalable. As a bonus, you may avoid checking the length of the sys.argv and reading the "files" into variables. Something along these lines:

import argparse

def parse_arguments():
    parser = argparse.ArgumentParser()

    parser.add_argument('--source-files', nargs="+", type=str)
    parser.add_argument('--answer-file', type=argparse.FileType('r'))
    parser.add_argument('--grade-file', type=argparse.FileType('w'))

    return parser.parse_args()

Note the use of the special FileType argument type.

And, because of the use of nargs="+", you should change the way you pass python file names - instead of a comma-separated list, use space:

$ python --source-files test01.py test02.py --answer-file answer.dat --grade-file grade.md

use with context manager when opening files
try subprocess.Popen() instead of os.system() - with "popen" you may not need to temporarily write the result to a swap file and read the standard out and error directly
I understand that an underscore at the beginning of a variable name is a convention to mark "private variables", but, if the checker class would not be a part of a public-facing API, it would be okay to remove the underscores to improve on readability


Singleton implementation of Cache Dependency Manager

As CacheDependencyManager is a singleton it should be thread safe.

ConcurrentDictionary is a nice fit for this.

Using ConcurrentDictionarythe code would look like this:

private ConcurrentDictionary<string, ExplicitCacheDependency> _dependencies = new ConcurrentDictionary<string, ExplicitCacheDependency>();

public CacheDependency GetCacheDependency(string key)
{
    return _dependencies.GetOrAdd(key, k => new ExplicitCacheDependency(k));
}

public void InvalidateDependency(string key)
{
    ExplicitCacheDependency dependency;
    if (_dependencies.TryRemove(key, out dependency))
    {
        dependency.Invalidate();
        dependency.Dispose();
    }
}


Sort a list of objects to put parents first

You can make this faster quite a bit (in complexity terms) by precomputing which objects have which parent and then successively building your list instead of iterating all objects with pure chance. Your complexity in the worst case right now is \$O(n^3)\$. (n^2 for the nested loops, another n for the contains)

Consider the following:

void orderList(List<MyObject> toSort) {
    final MyObject nullPlaceholder = new MyObject();
    Map<MyObject, List<MyObject>> byParent = toSort.stream()
         .collect(Collectors.groupingBy(obj ->
           (obj.getParent() == null ? nullPlaceholder : obj.getParent())
           , Collectors.toList()));

    List<MyObject> ordered = new ArrayList<>();
    Queue<MyObject> processor = new LinkedList<>();
    byParent.get(nullPlaceholder).forEach(processor::add);
    while (!processor.isEmpty()) {
        MyObject tmp = processor.poll();
        byParent.getOrDefault(tmp, Collections.emptyList())
          .forEach(processor::add);
        ordered.add(tmp);
    }
    toSort.clear();
    toSort.addAll(ordered);
}

Notes:

You menitioned in comments, that null-keys are not supported in the groupingBy collector. This code works around by creating a "null object". more info at wikipedia
getOrDefault works around the fact that the last MyObjects won't have "children", meaning that they don't have elements in the map. With standard get that would return null. You could manually check, but that breaks the flow IMO, and I prefer it like this :)

This should boil down to a runtime complexity of \$O(n)\$, which should give you significant performance boosts for larger lists.

In addition to that I dislike reusing references you receive as input. I personally prefer to use value-returning methods instead of modifying references. As such I'd adjust your method to return a List<MyObject> and return ordered; at the end.


Reusing objects using a generic object pool

The choices of classes and other design patterns that you have made indicate to me that the books/tutorials you have been reading are pretty old. There are a number of things in your code which are almost ten years out of date in the Java 'world'.

Also, you are only showing us half of your implementation, you have not included the checkIn() code.

While I can't review the whole system without the checkIn() code, there is a lot to comment on without that still.

General

It is obvious that you are using an IDE to help you write your code because you have some code-template things like:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

Why is that still there? Why have you not fixed it, or removed it?

Now, your tool should also then be pointing out other a bunch of other issues that you are obviously ignoring.... why?

You have a semicolon out of place:

    ;
//   abstract boolean validate( Object o );
//   abstract void expire( Object o );

Generics

Your class is defined as: public class ObjectPool<T> { but you do not take full advantage of generics.

Your constructor should take the variable Class<T> clazz instead of the create(Class<T> clazz) method, which should take nothing.

The constructor should save away the clazz as a private final Class<T> clazz;;

Then, your create() method should be fixed in 2 ways:

it should return generic type T
it should do some validation.
it should not have any input parameters.

To save having the complicated exceptions on the create method I recommend adding the first value to the pool in the constructor, and making the constructor throw the complicated exceptions.... then the create() method will be simpler to use ....

Note the following in these examples:

the instance variables should be private final (note the final).
Use the clazz instance to cast the value.

Example code:

    private final long expirationTime;
    private final Hashtable locked, unlocked;
    private final Class<T> clazz;

    ObjectPool(Class<T> clazz) throws InstantiationException, IllegalAccessException {
        expirationTime = 30000; // 30 seconds
        locked = new Hashtable();
        unlocked = new Hashtable();
        this.clazz = clazz;
        // complicated constructors with thrown exceptions....
        T o = clazz.cast(clazz.newInstance());
        locked.put(o, new Long(now));
    }

    public T create()  {
        try {
            T obj = clazz.cast(clazz.newInstance());
            unlocked.put(clazz.newInstance(), expirationTime);

            return obj;
        } catch (InstantiationException ie) {
            throw new IllegalStateException("Even though were were able to do it in the constructor, "
                 + "we were not able to create a new instance of " + clazz.getName(), ie);
        } catch (IllegalAccessException iae) {
            throw new IllegalStateException("Even though were were able to do it in the constructor, "
                 + "we were not able to access the newInstance() " + clazz.getName(), ie);
        }

    }

Your checkOut() method should have the same generic patterns as above.

Now, the two Hashtables... they should be Generified (your IDE is giving a lot of warnings, right?)

 private Hashtable<T, Long> locked, unlocked;

Locking and Synchronization

Your two methods are synchronized differently. The 'checkOut()method is synchronized, but thecreate` method is not.

Also, you are using the (old, by the way) class Hashtable which is internally synchronized.

You should, for simplicity at the moment, just use synchronized methods:

public synchronized T create() {
    ...
}

public synchronized T checkOut() {
    ...
}

and your Hashtable instances should both just be the newer, faster, and better:

private final Map<T, Long> locked, unlocked;

Note, I would normally recommend the Map should be a HashMap, but, read the next section...

Class Choices and bugs

Your class choice of Hashtable is wrong, it should be HashMap. This will lead to Iterator instead of Enumeration as well.

Also, you are making big assumptions about Class<T> since you use it as the key to the table/map. This is a problem because the keys need to be immutable. I would recommend using an java.util.IdentityHashMap instead.

Conclusion...

There are a lot of things which can be done differently. The code has a lot of work to do still


Implement a string in reverse using pointers and recursion

General comments

This review might come across a little harsh, so I want to start out by saying that the code is overall pretty good. In particular, the first implementation is a completely reasonable implementation of a recursive approach to string reversal, and it's easy to read and follow.

Now, rather than comparing the two approaches (short version: the first one is vastly superior), I'm going to go over some design and style items.

Standard implementation

I assume this is a toy function. If not, you really should leverage the standard library instead:

std::string str("some string to be reversed");
std::copy(str.crbegin(), str.crend(), std::ostream_iterator<char>(std::cout));

Or if you want to use a C-style string:

const char str[] = "Some string to be reversed";
std::copy(std::reverse_iterator<const char*>(str + sizeof(str)),
          std::reverse_iterator<const char*>(str),
          std::ostream_iterator<char>(std::cout));

Side note: If you're importing individual names from std, great. If not, be very careful. using namespace std can be a dangerous option. Inside of implementations (i.e. source files) it's questionable; inside of headers, it's dangerous and harmful.

Bare pointer implementation

It seems you're always returning 0, and I can't think of a situation in which this function could fail (at least gracefully), so I wouldn't bother returning anything.

astring is a bit noisy (particularly the 'a'). I would just go with str. (string might be a questionable choice since it could shadow std::string in certain circumstances.)

achar is redundant (and like astring, I find the name a bit distracting -- instead, the typical option would be ch or chr, at least if it were actually a char and not a pointer to a char).

char* x and it's manipulation is unnecessary.

    display_string_reversep(str + 1);

I feel like the outputting could use a little more room to breathe:

std::cout << *str;

This is essentially opinion though.

Since you're not modifying the input, you should be taking a const char*.

It's typically good practice to keep manipulations and output separate. In other words, it would be more reusable if you had a function for reversing strings and then just output the reversed copy. Or, if you wanted to compromise, you could have it take an arbitrary std::ostream instead of being stuck on std::cout.

void display_string_reverse(const char* str, std::ostream& os);

(Note that the standard library version both keeps concerns separate and it avoids making a copy of the string -- iterators are a powerful thing.)

This can act as a decent intro-to-recursion thing, but otherwise, I would go with iteration. Recursion avoids an extra linear scan (if length isn't already known), so that's a bit nice, but the overhead is likely not worth it.

I'm not sure I get the name display_string_reversep. I would drop the p.

Recursive example

void display_string_reverse(const char* str, std::ostream& os) {
    if (str == nullptr || str[0] == '\0') { return; }
    display_string_reverse(str + 1);
    os << str[0];
}

(I tend to prefer str[0] over *str in situations like this -- either one is equally valid. str[0] just clicks a bit better with my brain.)

Iterative example

void display_string_reverse(const char* str, std::size_t len, std::ostream& os) {
    for (std::size_t idx = 1; idx <= len; ++idx) {
        os << str[len - idx];
    }
}

void display_string_reverse(const char* str, std::ostream& os) {
    display_string_revserse(str, std::strlen(str), os);
}

Typically when you operate on C style strings (or strings that don't carry around their own length in general), you want to allow the user to provide the length, and then for usability purposes, you can offer a strlen fallback (which I would probably not do in a real application -- I'd rather force the caller to know what he's doing). This allows for avoid an unnecessary linear scan when the length is already known.

Note that you could generalize this to use two pointers instead of a pointer and a length. Then you could extract out that pointer concept (via templating) and you'd find yourself getting eerily close to the mentality of the standard library based implementation :).

Note: you could also use for (char* chr = beg + len - 1; chr != str; --chr) { os << chr[0]; }.
Note: for (std::size_t idx = str + len - 1; idx >= 0; --idx) will underflow std::size_t and likely result in an ininite loop. If you were to go this route, care would have to be taken, or a signed type used (or use idx = str + len and then use idx - 1 inside of the loop instead of idx).

shared_ptr implementation

Correctness

I haven't tried to run it, but I'm going to guess that this segfaults. When you create a shared_ptr around a raw pointer, you're creating an ownership relation. When all of the shared pointers referencing the object go away, the object is cleaned up automatically. This is incredibly useful in certain situations, but you must be aware of the implications.

Your code is essentially doing this:

std::shared_ptr<char> ptr0(str);
std::shared_ptr<char> ptr1(str + 1);
std::shared_ptr<char> ptr2(str + 2);
// ...
std::shared_ptr<char> ptrn(str + n); // (str + strlen(str) - 1)

So what happens when all these shared_ptr go out of scope? Bad, bad things. In essence, str will be destructed n times. The problem is that the string isn't separate allocations of characters strung together. Instead it's either a C-string literal (so an automatically managed array of characters -- char[]), or it's a dynamically allocated array of characters. In the first situation, it should not be freed at all. In the second situation, it should be freed once and only once.

If you actually wanted to use smart pointers for this (and you shouldn't), you would have to use a single smart_ptr wrapping a dynamically allocated array of characters, and you would have to use either bare pointers or the smart pointer plus an offset.

In short, smart pointers are a powerful tool when they're required, but they are not only not required here, but, in my opinion, actively harmful. They convulute ownership semantics, introduce performance problems, and at the end of the day, a highly specialized smart pointer already exists for strings: std::string.

shared_ptr performance and semantics

Before you start passing around smart pointers, please go read this.

In short, you should only pass a shared_ptr by value if you're intending to share ownership with whatever you are passing it to. Since display_string_reversep has nothing to do with owning it's parameter, accepting a shared_ptr by value is incorrect both semantically and from a performance point of view. To make things worse a second shared_ptr is created.

shared_ptr is incredibly powerful for situations that truly require shared ownership semantics, but be mindful that its utility comes at a cost. Doing pretty much anything other than reading a shared pointer is very expensive compared to a bare pointer or a unique_ptr.

In this case, since there's not conditional logic of taking ownership of the shared pointer, you would still pass by a bare pointer.


Use multiprocessing.Pool
The multiprocessing library already has a worker pool implementation ready to be used. Your code could be rewritten as:
import time
from multiprocessing import Pool

def f(x):
    time.sleep(random.uniform(0.01, 0.5))
    return x * 12

if __name__ == "__main__":
    c = Pool(2)

    for i in range(5):
        n = random.randint(1, 20)
        r = c.map_async(f, list(range(n)))
        print(f"sent: {n}")
        print(f"got: {len(r.get())}")

While multiprocessing.Pool allows you to check if the results are ready by using .ready() on the result of an apply_async() or map_async() call, you can't get a partial result from map_async(). However, if you do want to process individual results as soon as they are ready, you can consider calling apply_async() with a callback function that handles the result.


Getting name from user, and handling any errors in C

Nitpick

void retreiveName(char* name)

This should be

void retrieveName(char* name)

Bugs

        if (name[index] != ' ' && name[index] != '\0')

What happens if I enter tabs or unprintable characters?  This code would pass a string of all tabs.  Is an all numbers string valid?

        if (isalpha(name[index]))

Now we check to see if there is a letter rather than excluding only two bad values.

The <ctype.h> header has this and other functions that you can use.  E.g.

        if (isprint(name[index]) && !isspace(name[index]))

This might be what you want if you have a really liberal definition of name.

Second call

What happens if you call retrieveName twice with the same character array?  In particular, let's give it an input of "Christopher".

#define BUFFSIZE 10

Christopher has eleven letters, so it overwhelms the buffer size.  That's OK the first time, but the second call would get the remainder of the first call, not a new name.  So the second time you'd be processing the string "r\0ristophe".  That includes a letter, so it will return true.  Not great, since we wanted a new name.

Now let's change that a bit.  Instead of Christopher, enter "  Chris    ".  Again, that's eleven characters.  It overwhelms the buffer.  The second call results in the string " \0Chris   ".  Now, you

    for (size_t index = 0; index < BUFFSIZE; ++index) {

When index is 2, it finds a C, which is neither a space nor a null.  So the function returns true on a string that everything else will interpret as " ".  Oops!

And note that this could also happen with two calls that don't overwhelm the buffer.  E.g. the strings "Chris" and " " will call it with " \0ris\0\0\0\0" the second time, assuming the character array was zero-initialized.

Consider instead

    for (size_t index = 0; index < BUFFSIZE && name[index] != '\0'; ++index) {

Then the loop will stop at the end of the buffer or the end of the string, whichever comes first.

What about other lengths?

bool isThereChars(const char * name)

This only works with one size of buffer.  It would make more sense to allow arbitrary length buffers.

bool hasLetter(const char * name, int bufferLength)

This allows the caller to specify a buffer length.

I also like the name hasLetter better than isThereChars.  Your mileage may vary.  Another option is hasAlpha, to match isalpha.

No need for a flag variable

    bool charCheck = false;
    for (size_t index = 0; index < BUFFSIZE; ++index) {
        if (name[index] != ' ' && name[index] != '\0')
            charCheck = true;
    }
    return charCheck;

I'd like this better as something like

    for (size_t index = 0; index < BUFFSIZE && name[index] != '\0'; ++index) {
        if (isalpha(name[index])) {
            return true;
        }
    }

    return false;

This also has the side effect of returning as soon as you find an alphabetic character rather than processing all the other characters even though they won't change the answer.


Here are a few possible improvements:

Use a set for the positions you want and make it a constant. (This will give you a small speed-boost, because in is O(n) for lists, but O(1) for sets.)
Don't use a list-comprehension with side-effects for a loop.
Follow Python's official style-guide, PEP8. Specifically:

a) Don't do multiple imports

b) Put spaces around your operators

c) Put a space after a comma in an argument list
Limit the scope of your try..except

With these fixes, here is the final code, as I would write it:

import re
import nltk
import html

POSITIONS = {'NN','NNP','NNS','NNPS','JJ','VBS','VBN','VBG','VBD'}

def extract_entities(text_list):
    entities = set()
    for sentence in text_list:
        try:
            tokens = nltk.word_tokenize(sentence)
            tagged = nltk.pos_tag(tokens)
        except Exception as e:
            print('stage 1', e)
            continue
        for word, pos in tagged:
            if pos in POSITIONS:
                entities.add(word.lower())
    return entities


I think this is better than about 99% of first tries I've ever seen!

Anyway, I've tried my best to address as many things as I saw, whether major or extremely minor.  If you have any questions on any points or want to clarify or defend any claims, let me know and I will expand the answer.

Assuming array indexes exist

Any array that comes from user input should never be directly accessed.  $_POST['key'] is not safe since you can't know for sure whether or not the user supplied the $_POST['key'].

With arrays that can contain null values, you must use array_key_exists, but since input arrays like $_POST and $_GET will always have either strings or arrays, you can safely use isset.

The following is how I tend to access request driven arrays:

$username = (isset($_POST['username']) && is_string($_POST['username'])) ? $_POST['username'] : null;
if (strlen($username) < 5) {
    //username's must be >= 5 charactes
} else if (strlen($username > 32)) {
    //username's must be < 32 characters
}

//If you wanted to check if the user even provided a username:
if ($username === null) {
    //A username element of the form was not provided.  Depending on specific context, this may imply form tampering.
}

Note that the is_string check is necessary so that the user cannot maliciously pass an array to the script. If that were to happen, then the strlen call would complain about not expecting an array.  Unfortunately you have to be rather paranoid about anything coming from users.

There's a longer discussion of this here in the last section.

It's also worth noting that some people prefer a filter_input approach.

SQL injection

There is no SQL injection possible in your code, but that may be by accident.  When putting strings into queries, it's good practice to always run them through mysql_real_escape_string.  That way if you change your business rules in a way that does make SQL injection possible, you don't have to worry about the change cascading down to your queries and opening a security hole.

More information about SQL injection can be found in a post I wrote the other day, here.

(Sorry if I'm assuming that you don't know about SQL injection and you do.)

MySQL Extension

The mysql_* extension is quite dated, and PDO offers many advantages.

Offers a cleaner API
Offers better error handling (the ability to have failed queries throw exceptions is wonderful)
Handles transactions SQL-dialect agnostically (for the most part)
Different RDBMS can be changed out relatively easily (switching from mysql_* to PostreSQL is extremely painful.  Switching from PDO with MySQL to PDO with PostreSQL isn't pleasant, but is care is taken to stay as dialect-agnostic as possible, it's reasonably easy)
Prepared statements

You can find more information here under the PDO section.

pre can be used to arrange spacing, however you should be aware that it typically uses a fixed width font, and there's a few other quirks with it (you can probably style it to use a different font though).  I suppose there's technically nothing wrong with it, but pre doesn't strike me as a good long term method for arranging elements.

ctype_alnum for a password

Why restrict users to a a-zA-Z0-9 password?  I'm a firm believe that passwords should be allowed to be just about anything.  Some restrictions may be in order, such as ASCII only or something of that nature, but if a user wants his password to be this is my password, then why not?  You're hashing it anyway, so the length doesn't matter.  By the same logic, why not allow non alpha numeric characters?  It's not like HTTP or PHP will have any issues handling things like !@#$%^&*()|_+=- and so on.

list column fields in inserts

$query = "INSERT INTO userlogin VALUES('','$username','$password')";

Listing columns explicitly allows for better maintainability and clarity.  What if in the future you add a birthday column after the username column?  Suddenly you're trying to insert passwords into the birthday column.  Also, if you're going to put an auto incrementing column in a query, it should be null.

I would write the query like this:

$query = "INSERT INTO userlogin (username, password) VALUES ('$username','$password')";

userlogin

This sounds like a logging table to me.  This sounds like it contains records of users logging in, not of actual user records. I would consider renaming this table to something like users or user_accounts.

escape html where necessary

echo "Thanks ".$username.", your account has been created!";

Once again, since it's limited to alphanumeric, this is definitely harmless, however, preparing for the future never hurts.  If at some point you allow users to create names that contain &, this could output invalid html.

(Once again, sorry if I'm telling you something you already know.)

always use brackets

It's hard to see on a short script with fairly simple logic, but I'm a firm believer that braces should always be used.

if {} else { statement }

Looks clearer and is less error prone than:

if {} else statement

html element's attributes should always be in quotes

value=yes should be value="yes"

MD5

Hashing algorithms should be computationally expensive enough that a brute force attack is infeasbile.  Due to rainbow tables and other factors, a single MD5 run of an alphanumeric password is not considered secure.

Consider using something like bcrypt that is a bit heavier algorithm, or at least use something like 512 bit SHA repeated a thousand (or more!) times.

Let f be your hashing function.  Let S = the set of all possible passwords.  The absolute worst case time to brute force a password, p, such that p is in S is size of S * time for f(x)

If f = MD5 then the time is very small. MD5 and even SHA are considered fairly fast hashes.  If you use a an algorithm such as one of those, you should at least repeat it.  This way f becomes a much longer operation.

There's a few really good posts on StackOverflow about this, so I'll try to find some and link them.

This is a pretty good explanation (thanks to luiscubal for finding the link).

More graceful error handling

For the errors, I would probably handle them a bit better than the old or die construct that tends to go along with the mysql_ functions.

The idiom I would follow (though I would use PDO with exceptions), would be something like:

$query = "...";
$resource = mysql_query($query);
if (!$resource) {
    //log the error including all necessary details
    //output a fairly vague error the user
}

trigger_error can be useful for this.

Error handling suggestion

I like to validate everything separately and independently such that all errors can be output at once.  For example, if my username is only 4 characters and my passwords don't match, it would be nice to see both errors at once instead of having to fix one error, resubmit the form, fix the second error then resubmit the form.

This is by no means perfect, but the structure I typically use for error handling is:

$errors = array();
$username = $password = null;

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    $username = ...;
    $password = ...;
    if (strlen($username) < 5) {
        $errors['username'][] = "Usernames must be 5 or more characters";
    }
    if (strlen($username) && !ctype_alnum($username)) {
        $errors['username'][] = "Usernames must be alphanumeric";
    }
    if (strlen($password) < 5) {
        $errors['password'][] = "Passwords must be 5 or more characters";
    }
    //More validations
    if (!count($errors)) {
        //No errors, so $username and $password are valid
        $insertionQuery = sprintf("INSERT INTO users (username, password) VALUES ('%s', '%s')", mysql_real_escape_string($username), mysql_real_escape_string($password));
        $insertionResult = mysql_query($insertionQuery);
        if (!$insertionResult) {
            trigger_error("MySQL query failed.  Query: [{$insertionQuery}].  Error: [" . mysql_error() . "]", E_USER_WARNING);
            $errors['db'][] = "There was an unexpected error. Please try again.";
        }
    }
}

Then, to render the errors, I typically just create a
 with each error as a
:

if (count($errors)) {
    echo '
';
    foreach ($errors as $element => $errs) {
        foreach ($errs as $err) {
            echo '
' . htmlspecialchars($err) . '
'
        }
    }
    echo '
';
}

The element name being the array key is useful because it means you can do things like style elements a certain way if they had an error:

<input type="text" name="username" value="<?php echo htmlspecialchars($username);"<?php if (array_key_exists('username', $errors)) { echo ' class="error"'; } ?>>

You could even take the idea farther and render errors around elements.

In general, it's a lot more flexible to aggregate the errors instead of immediately outputting them.

This philosophy touches into the area of MVC and separation of concerns.  MVC isn't particularly important for now, but the general idea of it (and in part SoC) is that each area of code should be concerned with one specific thing and nothing else.

A slight extension of this is the idea that logic and presentation should be separate.  Doing this allows many more degrees of freedom, and typically better code.  Consider for example if you wanted to have an AJAX interface for submitting the form, but still have an HTML fallback for users with JavaScript disabled.  If you were storing errors, you could do something simple like:

if (!empty($_POST['ajax'])) {
    echo json_encode(array('result' => 'errors', 'errors' => $errors));
    //set some kind of flag so that html output will not happen
    //(or, if it's a small script, I might just use `exit;`)
}

//Then later, if it's not AJAX
//render the errors as HTML inline in the form

If you intermix your logic and presentation code, the code is forever stuck rendering in exactly one way.  There's no way to reuse the same logic with a different presentation.  If they are separated, however, then the same logic can be used with infinite presentations.

Variable reuse

I'm definitely in the minority on this one, but I don't like to reuse variable names.  I would call the repeated query and result variables something like $existsQuery and $insertionQuery.  Nothing wrong at all with reusing the same name, just a personal preference (though the more descriptive a name, the better [within reasonable limits]).

header.php

This is not a very descriptive name.  I would consider calling it something like database.php or connect.php or something.  When I think of headers, I think content, not code.

Also, since the database connection is required for the page to function, require should be used instead of include.  A failed include will allow execution to continue, whereas a failed require will kill execution.

mysql_select_db

This should be with your database connection code.

login.php

No idea what "Login.php defines database log in numbers" means?  I'm a bit confused though about what this could be doing.  Also not sure why require_once instead of require?


No comment on what your call as I don't know what WriteFile() or WriteConsole() do.

But that is seriously abusing the && and !! operators.
I don't think I would ever let that code pass a review:

while (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) &&
    (nIn != 0) &&
    (WriteFile(hOutFile, buffer, nIn, &nOut, NULL) || WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL)));

// Why not write it like this:

// While we manage to read a good value:
while (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) && (nIn != 0))
{
     if (!(   (WriteFile(hOutFile, buffer, nIn, &nOut, NULL))
          || (WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL))
          )
        )
     {
          // Write Error
          break;
     }
}
// Now check for read errors to report.


It is good practice to mark as many fields as possible as final.

private final Activity activity;
private final LocationManager locationManager;
private final LocationListener locationListener;

I assume that freshLocation will be changed in your locationListener so that one should not be final.

All fields that only get initialized once can be marked final.

You seem to only be using your activity inside the constructor, so you don't need to keep that as a field at all.

Also, instead of passing an Activity, it's enough to pass a Context (Activity extends Context so you can still pass an activity). The only method you use on the activity is getSystemService which is part of the Context class. Contexts are often required to pass to various methods in Android, so that is perfectly fine. It is better to pass a Context than an Activity.

About this code:

this.locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {

It is totally fine to do it this way. This is an anonymous inner class. The alternative is to use an inner class (non-anonymous), this would reduce code from your constructor but that code would be added in other parts of the class instead so which way you go doesn't matter much. This is fine.


I think your interviewer meant that you can improve checking the winning situation and do it in \$O(1)\$ time by keeping track of the scores in rows, columns and both diagonals (total 8 variables for 3x3 board):

[row1, row2, row3, column1, column2, column3, diagonal, anti-diagonal]

Then, you can increment these value by 1 in case of "player 1" and decrement by one in case of "player 2". This will lead to only checking these 8 values (or you can also use the fact that you know where the last move took place) for 3 or -3 for a winning situation. You can find out more about this idea here.

Or, you can go over all the possible winning combinations like suggested here or here.


1. Comments on your code

No docstrings! What does your class do and how am I supposed to use it? Also, no doctests.
Wouldn't it be more natural for this class to be a set of primes, rather than a dictionary mapping primes to True and other keys to False?
There's only one set of primes, so this is a rare opportunity to make use of the Singleton pattern. That is, each call to PrimeDict() ought to return the same object.
By implementing __setitem__ like this:

def __setitem__(self, key, value):
    return self.__getitem__(key) #it's a read-only dict

you give callers the false impression that this operation succeeded:

>>> p = PrimeDict()
>>> p[1] = True
>>> # looks good, but:
>>> p[1]
False

Instead, you should raise an exception:

def __setitem__(self, key, value):
    raise TypeError("'PrimeDict' object doesn't support item assignment")

Similarly for __delitem__:

def __delitem__(self, key):
    raise TypeError("'PrimeDict' object doesn't support item deletion")

By deriving your class from Python's dict, you make all of the dict methods available. This means that a caller might accidentally bypass your attempt to make the dictionary read-only, by calling some other method that you haven't overridden. For example:

>>> p = PrimeDict()
>>> p.update({1: True})
>>> p[1]
True

The thing to do is not to subclass dict, but to subclass collections.abc.Mapping and have the actual dictionary be a member variable. Or, if you take my suggestion in point 2 above, subclass  collections.abc.Set and have the actual set as a member variable. I'll show how to do this in my revised code in section 2 below.
The method __find_primes has a private name. Why do you do that? The intended use of private names in Python is to "avoid name clashes of names with names defined by subclasses" but that's obviously not necessary here. All that the private name achieves here is to make your code a bit harder to debug:

>>> p = PrimeDict()
>>> p.__find_primes(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'PrimeDict' object has no attribute '__find_primes'
>>> p._PrimeDict__find_primes(10)
>>> p
{2: 2, 3: 3, 5: 5, 7: 7}

You start out by adding 2 to the set of primes and then set self.previous_max = 2. But it would be simpler to start out with the empty set of primes and self.previous_max = 1. The sieve of Eratosthenes is self-starting.
Instead of:

i = index ** 2
while i < n:
    sieve[i-self.previous_max] = 0
    i += index

make use of Python's range function, and write:

for i in range(index ** 2, n, index):
    sieve[i - self.previous_max] = 0

The code in __find_primes has to subtract self.previous_max from the array index every time it looks up something in sieve. It would be more efficient to do this subtraction once when setting up the loop bounds. For example, instead of the code that I suggested above:

for i in range(index ** 2, n, index):
    sieve[i - self.previous_max] = 0

you could write:

for i in range(index ** 2 - self.previous_max, n - self.previous_max, index):
    sieve[i] = 0

The line:

key = int(key)

can raise ValueError. Wouldn't it be better to return False if key can't be converted to an integer?

2. Revised code

try:
    from collections.abc import Set
except ImportError:
    from collections import Set # Python 3.2 or earlier

class PrimeSet(Set):
    """A PrimeSet object acts like the set of prime numbers:

        >>> p = PrimeSet()
        >>> 2 in p
        True
        >>> 4 in p
        False

    The object sieves for primes as needed. When iterated over, it
    yields the primes found so far:

        >>> 30 in p
        False
        >>> list(p)
        [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

    """
    # Singleton pattern: there is only one set of primes.
    instance = None
    def __new__(cls):
        if cls.instance is None:
            cls.instance = super(PrimeSet, cls).__new__(cls)
        return cls.instance

    def __init__(self):
        super(PrimeSet, self).__init__()
        self.max = 1            # Highest number sieved to so far.
        self.set = set()        # Set of primes up to self.max.

    def __iter__(self):
        return iter(self.set)

    def __len__(self):
        return len(self.set)

    def __contains__(self, key):
        try:
            key = int(key)
        except ValueError:
            return False
        if key > self.max:
            self.find_primes(key)
        return key in self.set

    def find_primes(self, n):
        """Sieve for primes from self.max + 1 up to and including n."""
        if n <= self.max:
            return
        sieve = [True] * (n - self.max)
        for p in self:
            for i in range(p - 1 - self.max % p, len(sieve), p):
                sieve[i] = False
        for p, isprime in enumerate(sieve):
            if isprime:
                p += self.max + 1
                self.set.add(p)
                for i in range(p * p - self.max - 1, len(sieve), p):
                    sieve[i] = False
        self.max = n


Functional organisation of JavaScript functions

Should I be using prototypes as well, even if there will only be one function ever?

No, you will only benefit from using the prototype when you create a lot of instances of a constructor function. I won't go in to the details of that, since it has already been discussed a lot in various SO posts.

Without more context, I suggest that you create a revealing module:

var app_editor = (function(window, ace, ace_editor, undefined){

    var aceRange, editor, marker, session;

    function init(){
        aceRange = ace.require('ace/range').Range;
        editor = ace_editor;
        marker = null;
        session = editor && editor.getSession();
    }

    function removeMarker () {
        if (marker && session) {
            session.removeMarker(marker);
            marker = null;
        }
    }

    return {
        init: init,
        removeMarker: removeMarker
    }

})(window, ace, ace_editor);

app_editor.init();

Now you can keep variables and methods private within your app_editor and only expose what you need to access from the outside. This is just a small sample to get you started.

Are ace and ace_editor already defined in the global namespace? If not, you probably want to pass them as arguments to the init methods. It's hard to say from your two examples.

Some other comments:

annotateLine = function(d) { - What's d? Use a more descriptive name.
You're chaining methods a lot, e.g. editor.getSession().clearAnnotations();. What if getSession() returns undefined? Do more checks rather than making assumptions.

Let me know if you want me to elaborate anything.

Update

Simple object literal example:

var app_editor = {

    aceRange: null,
    editor: null,

    init: function(aceRange, editor){
        this.aceRange = aceRange;
        this.editor = editor;
    },

    removeMarker: function(marker){
        if(!this.editor || !this.editor.session) return;
        this.editor.session.removeMarker(marker);
    }
};

You get the idea...


Register script security and optimization

Here are my recommendation,

you could make sure users password have a minimum length. 8 alphanumeric characters is ideal  If a users password is 1 char, it can easily be broken no matter how good the salt is
move you database connection and setup into a different class: In the database class, create two separate functions.

Does Email Exist and Return boolean
Create users returning a new user object

Database Connection Class uses the singleton design pattern. We only need 1 connection object to exist when our application is running. The singleton pattern is a design pattern that restricts the instantiation of a class to one object.

class Database
{
    private static $dbh = null;
    //TODO you should move this inside config file
    private $host = 'mysql:host=localhost;dbname=test';
    private $pwd  = '';
    private $user = '';

    public function __construct()
    {
        try
        {
            Database::$dbh = new PDO($this->host, $this->user, $this->pwd);
            Database::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        }
        catch (PDOException $e)
        {
            echo "Connection Error: " . $e->getMessage();
        }
    }

    public static function getInstance()
    {
        if (Database::$dbh === null) {
            new Database();
        }
        return Database::$dbh;
    }
}

//all of our sql code should be in a centralized location for easy updating
class SQLPreparedQuery {
    public static $EMAIL_EXIST = "SELECT email FROM user WHERE email=? LIMIT 1";
    public static $USER_ADD = "INSET INTO user (username, email, first, last) VALUES(?,?,?,?)";
}

require_once './Database.php';
require_once './SQLPreparedQuery.php';
class UserModel {
    public function doesEmailExist($email) {
        $doesEmailExist = false;
        try {
            $dbh = Database::getInstance();

            $stmt = $dbh->prepare(SQLPreparedQuery::$EMAIL_EXIST);
            $stmt->bindParam(1, $email, PDO::PARAM_INT);
            $stmt->execute();
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $doesEmailExist = (empty($result) ? false : true);
        }
        catch (PDOException $ex) {
            echo "An Error occured!" . $ex;
        }
        return $doesEmailExist;
    }

//USAGE
//This will return true if it exist and false if it doesn't

$userModel = new UserModel();
$status = $userModel->doesEmailExist('james@example.com');

CREATE TABLE `user` (
  `iduser` int(11) NOT NULL AUTO_INCREMENT,
  `first` varchar(45) DEFAULT NULL,
  `last` varchar(45) DEFAULT NULL,
  `email` varchar(45) NOT NULL,
  PRIMARY KEY (`iduser`),
  UNIQUE KEY `email_UNIQUE` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1$$

INSERT INTO `test`.`user` (`first`, `last`, `email`) VALUES ('james', 'brown', 'james@example.com');

You should always add UNIQUE constraints to usernames and email address to ensure uniqueness in your database.


Find maximum length of array where every entries are the same

You should use better function names ALG1 and ALG2 don't really say what they're performing.
You should keep the creation of A, n and result at the bottom of your code.
You should keep your 'main' code in a main guard block:

if __name__ == '__main__':
    A = [3,2,4,2,4,2,4,5,3]
    n= len(A)
    result = ALG1(A,n)
    print(result)

You should follow PEP 8, so that it's easier for others to read your code.
ALG2 can be simplified by slicing the array from i to j, A[i:j], and then checking if the set has a size of one.

def ALG2(A, i, j):
    return len(set(a[i:j])) == 1

Your entire code can be drastically simplified by using itertools.groupby.

import itertools

def ALG1(array):
    sizes = (
        sum(1 for _ in g)
        for _, g in itertools.groupby(array)
    )
    return max(sizes, default=0)


Usage of Interlocked.CompareExchange for deciding whether a property has been changed by another thread

In your code, the only way to have two threads update that value simultaneously is if TimeTick gets invoked twice in a very short amount of time.  Given a sane value for your time interval, this can't happen.  And if it can, you would typically use a Monitor and quickly exit the second handler.

It seems that you are invoking this timer at a much higher rate than necessary - every 200ms - because you want to do something else that frequently, so you have code to check if you should do your 5 minute job now.  There isn't a good reason to have one callback responsible for two totally different things.  You should be able to solve this by having a 5 minute timer for the database job and a 200 ms timer for the broadcast, and these would each call their own callback function.