Pattern for storing object of varying type

What you are doing appears to be sane. The use of generics is primarily as a compile-time validator (and it makes some code simpler, like not having to cast things).

If you don't know the types of your data at compile time, then you can't use generics.

So, you have run-time specified data, and that's OK. Do you handle that as well as it can be handled? That is the real question.

Items I can see that raise question-marks:

Why are you saving away the Class name (as type) when you can save away the actual Class?
wasUpdated is not used.
type is a bad name for a Java variable. It conflicts with java.lang.Type, and you don't need it anyway if you are going to store the Class instead of its name.
if you do keep the class, then you can use the Class.isInstance(...) method to ensure the data types are correct, instead of specifying the class as part of the retrieval in the get(Class<T> clazz) method... or, you can confirm they are the same with a simple .equals() call instead of the name/isArray check.
the methods like return TakesAnInteger(...) should have a lower-case t to start with.... this is the Java convention for method names.
Similarly, Java convention is to put the opening brace { for a block on the same line as the method declaration.

Edit: with Class saved instead of name and isArray

Also, I note now that you are missing some semi-colons in your data declarations.... and also, you are missing return values from some of your methods.

public class DataParam {
    public String name;
    public Class<?> dataClass;
    public boolean wasUpdated;
    private Object data;

    public DataParam(String name, Class<?> typeClass) {
        this.name = name;
        dataClass = typeClass;
        data = null;
        wasUpdated = false;
    }

    public <T> T get(Class<T> typeClass) {
        if(dataClass.equals(typeClass)) {
            return typeClass.cast(data);
        }
        return null;
    }

    public <T> T set(T obj, Class<T> typeClass) {
        if(dataClass.equals(typeClass)) {
            T toreturn = typeClass.cast(data);
            data = obj;
            return toreturn;
        }
        return null;
    }

    public String doSomething() {
        //An example of doing different things based on type
        //.......
        return null;
    }
}


Mostly LGTM, with the following objections.

Names. Avoid which require a comment to be understood. I'd have no problem with int ax; because it clearly conveys the goal of being an index of a.
Conditionals.
You can statically prove that i > a.length is not possible. If by any chance it happens, it means that something really weird is going on. A good cause to raise an exception. Bottomline is, separate a == test from > one.
Once one of the ranges is exhausted, there's no need to test it again and again. Normally one would break a main loop and copy the remaining data separately

along the lines of:

while (A has data) and (B has data)
    calculate what to copy
    copy it to C

while (A has data)
    copy A to C

while (B has data)
    copy B to C

Types. The methods cry to be generic. If you didn't cover generics yet, disregard the objection.


Firstly, the official python style guide recommends 4-space indentation, and you are using 2. (No big deal but following the style guide is helpful)

class TreeNode(object):
  """ applicable to all tree nodes including root node """
  def __init__(self, value, left=None, right=None,root=False):

Your code never passes a left/right parameter. There are also doesn't seem to be a good reason why you would pass left/right parameters in the construction of the tree. I assume you would use this class by constructing an empty tree and inserting values into it, not by composing trees. As a result, I suggest eliminating left/right.

Also, you have a root parameter which is never used. It looks like something that you should eliminate.

Additionally, you cannot create an empty tree with this method.

    self.value = value
    TreeNode.check(left)
    TreeNode.check(right)
    self.left = left
    self.right = right
    self.root = root

  def inorder(self):
    s = list()

Use s = [], also don't use single letter variable names.

    if not self.left:

When checking for None, recommened practice is to do it like: if self.left is None:

      s.append('')
    else:
      s.append(self.left.inorder())

    s.append(str(self.value))

    if not self.right:
      s.append('')
    else:
      s.append(self.right.inorder())

    return ' '.join(s).strip()

The fact that you are trying to construct a string is kinda wierd. I'd expect this method to produce either an iterator or a list containing all the elements.

  # returns True if success, False otherwise
  def insert( self, new_value ):
    # TODO ?? what happens if we are inserting strings
    if not new_value and new_value != 0:
      return False

This is why you should "is None"

    if new_value == self.value:
      return False

    # need to find the right location in terms of binary tree ordering
    if new_value < self.value:
      if not self.left:
        self.left = TreeNode(new_value)
        return True
      else:
        return self.left.insert( new_value )
    elif new_value > self.value:

You've already established that this expression must be true, just use else

      if not self.right:
        self.right = TreeNode(new_value)
        return True
      return self.right.insert( new_value )

The previous branch had this inside an else. You should at least be consistent between branches

    return False

  @staticmethod
  def check(node):
    if not node:
      return
    if not isinstance(node, TreeNode):
      raise TypeError('only instances of TreeNode are allowed')

Explicitly checking types is frowned upon. All you manage is converting an AttributeError into a TypeError. However, a check method could usefully verify the invariants of a data structure. (Just only do it while debugging).

  def __repr__(self):
    return '(' + repr(self.left) + ',' + \
      str(self.value) + ',' + repr(self.right) + ')'

TreeNode seems to be a collection class, one that holds elements. The internal structure shouldn't matter to the world. However, repr spills the internal structure for the world to see. I'd suggest calling inorder to produce all of the elements inside the string and show that. Also repr's value should make it clear what class is being repr, by including "TreeMap" somewhere in its output.


SQL prepared statement to search songs by various text fields

Are there any risks of using function parameters for column names in prepared statement?

Well, of course you shouldn't. "Function parameters" is not a protection measure in any sensible way. It's just a transport, to deliver some value into a function. As is.

  Are there some kind of risks of this solution,

ANY of them. All kinds of SQL injection are welcome in this code.

Sorry for the harsh preface but I wanted to make it clear and make sure there are no such illusions left.

So you have to change the approach entirely. Luckily, it is not hard to implement.

For the field name and  order by, you will need a white list filtering.
For the limit, as it's not a column name, but a data literal, simply add it through a placeholder.

I've got an article that explains the white list approach in detail, Adding a field name in the ORDER BY clause based on the user's choice

Using a helper function from this article,

function white_list(&$value, $default, $allowed, $message) {
    if (empty($value)) {
        return $default;
    }
    $key = array_search($value, $allowed, true);
    if ($key === false) {
        throw new InvalidArgumentException($message);
    }
    return $value;
}

we can make your function 100% safe

function search($filter,$input,$type,$order,$sort,$limit)
{
    $fields = ['name', 'text', 'whatever'];
    $filter = white_list($filter, $fields[0], $fields, "Incorrect filter name");
    $order  = white_list($order, $fields[0], $fields, "Incorrect order name");
    $sort   = white_list($sort, "ASC", ["ASC","DESC"], "Invalid ORDER BY direction");

    $sql = "SELECT Title,Type,Youtube,Score,Ratings,Singer,ID
    FROM song WHERE $filter LIKE CONCAT('%',?,'%')
    AND Type=? ORDER BY $order $sort LIMIT ?"
    $st = $this->conn->prepare($sql);
    $st->execute([$input, $type, $limit]);
    return $st->fetchall();
}

Just edit the list of fields allowed (or make two lists if they have to be different for the filter and order) and you're set.


Here's the important part:

0→V
For(K,0,N-1
    A+KD+.5D→X
    V+fnInt(abs(Y₀-Y₉),X,A+KD,A+(K+1)D)fnInt(Y₈,Y,Y₀(X),Y₉(X))/(Y₀(X)-Y₉(X→V
End

I suggest you replace the fourth line with:

V+DfnInt(Y₈,Y,Y₀,Y₉)→V

Here's the reason: You should have thin enough slices that the volume in a single slice of width D can be approximated by DfnInt(Y₈,Y,Y₀,Y₉); that's more important than getting the area exactly right. This change will increase your overall speed by about 3x.

Once you've done that, you can drop the For( loop entirely, and use sum(seq( instead. This only helps the performance a little; your bottleneck is still the fnInt(. However it's better style.

Another trick: since your precision is limited more by the Midpoint rule calculation along the x axis than the accurate fnInt( along the Y axis, you may want to increase the tolerance of fnInt( to, say, .005. Then your entire loop becomes:

Dsum(seq(fnInt(Y₈,Y,Y₀,Y₉,.005),X,A+.5D,B,D→V

(This uses the optional 'step' argument to seq(.

Another possibility is to use the Midpoint rule on both axes instead of fnInt(. I'm not sure how much this would help speed or decrease accuracy, but I suspect the accuracy wouldn't be too much worse than using the Midpoint rule on one axis.


Computing the sentiment score of a sentence

TSV parsing
You should not need to do this yourself. The csv module accepts a delimiter that you can set to '\t'.
Context management
You use with in one out of three file opens - the other two would benefit.
Inner list
This:
set([line.rstrip() for line in lexiconpos])

can be
{line.rstrip() for line in lexiconpos}

The set literal and removal of the inner list will both express this better.


Implementation of Permutation Algorithm A from Topor, 1982

Echoing Henrik's answer, I'd agree that the implementation looks fairly idiomatic already.

The only material change I'd make is changing all uses of List.length to explicit pattern matching with an empty list case.  This is because List.length is an O(n) call due to the linked list implementation of F# Lists, when all you really care about is if the list is empty. As an example:

module AlgorithmA =
  let rec put a p q =
    if p = q then a :: q
    else p.Head :: (put a p.Tail q)

  // a: an element
  // p: a list of elements
  // q: a sublist of p
  // ps: a list of permutations
  let rec insert a p q ps =
    match q with
    | [] -> put a p [] :: ps
    | _::qs as q' -> put a p q' :: insert a p qs ps

  let rec mapInsert a ps =
    match ps with
    | [] -> []
    | x::xs -> insert a x x (mapInsert a xs)

  // x: a list of elements
  // returns a list of permutations
  let rec permute1 x =
    match x with
    | [] -> [[]] // return an list containing the empty list
    | x::xs -> mapInsert x (permute1 xs)


(Note: no code in this post has been run- beware errors.)

I have a couple of issues with your design, and with your review request.

First, you say that you are committed to using five different functions for the checking. That's unfortunate, since this problem is very amenable to being solved with iteration.

Next, you have a class GameOutcome that is being asked to identify a winner or tie. I disagree with this- this is something the game itself should do. The game outcome, IMO, would be a data class just collecting results. The name GameOutcome suggest that this class would have no knowledge of the sequence of moves, or the state of the game board.

With those out of the way, let's talk about your code.

Those names!

I hate your naming style. You have fallen into the trap of making excessively long names for no good purpose. I strongly suggest you review code written by other people (either here on CodeReview or look through github or the pypi repositories) to get a sense of how names should be chosen.

Consider this line:

    if self.check_row_containing_move_for_win():

The method check_row_containing_move_for_win is an internal method. It is not intended for use by arbitrary external callers, it is only a method in order to package up its code behind a name.

For an internal function, why not just call it _check_row.

Similarly, you have an externally callable method named find_winner_or_tie. The declaration:

def find_winner_or_tie(self, state_of_game, row_index_of_move, column_index_of_move):

Here's a better approach:

def find_winner_or_tie(self, state, row, col):
    """ Check if either player has won, or if a tie has been forced. Return 'X' or 'O'
        for a win, 'Tie' for a tie, and None when the game is not over.

        Parameters:
          state:  state of the game
          row:    row of the last move
          col:    column of the last move
    """

Providing in-depth explanation is the function of comments, not names. Your names should be as long as they need to be, but no longer.

Builtins any() and all()

You are writing code that checks for various conditions. Python supplies the any() and all() built-ins for situations like this. The trick is to learn to construct iterables in line, and that means using generator expressions.

A generator expression is an inside-out for loop in parentheses, like:

(abs(x) for x in somelist)

They resemble, and are related to, list, dictionary, and set comprehensions. In all cases there is an iteration keyword (for ... in ...) and some kind of leading expression. With a generator expression, you are constructing a generator in-line and storing it, evaluating it, or passing it as parameters.

How does this help you? Well, suppose you have a group of functions you want to evaluate for success. Say ... five of them? You might decide that you were going to return if any of those conditions were true. Well ...

def find_winner_or_tie(self, state, row, column):
    """ ... """
    self.set_board_and_move(state, row, column)

    checks = (self.check_row, self.check_column, self.check_diag_lr, self.check_diag_rl, self.check_tie)

    if any(check() for check in checks):   # If any check is true, we know the outcome
        return self.game_outcome

    return None

Less code, more data!

The thing about most games is that they are based on lots of data. And if you write your code correctly, you will find more and more data, with less and less code. That's the case here. Let's take a look at one of your check-functions:

def check_row_containing_move_for_win(self):
    total = 0
    for column in range(3):
        total = total + int(self.letter_dict[self.state_of_game.board[self.row_index_of_move][column]])
        if abs(total) == 3:
            winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]
            self.game_outcome = winning_letter
            return True
    return False

Honestly, that's so long that it's unreadable. So let's refactor out the names:

def check_row(self):
    """Check row containing latest move for a win."""
    bias = self.letter_dict
    board = self.state_of_game.board
    row = self.row_index_of_move

    total = 0
    for column in range(3):
        total = total + bias[board[row][column]]

    if abs(total) == 3:
        self.game_outcome = board[row][0]
        return True
    return False

I think some people have already pointed out sum and some other options. But let's actually spell out what the row and column choices are:

ROWS = [ ((0, 0), (0, 1), (0, 2)),
         ((1, 0), (1, 1), (1, 2)),
         ((2, 0), (2, 1), (2, 2)),
]

Now, you could write code to generate that. In one line, even! But that's not important. What's important is that we know that there's a ROWS variable that can be indexed by row-number and which has a sequence of (row, col) tuples identifying the cells to look at.

Now, how does that help? Well, it helps because you can write a helper function that does the checking for you given a sequence of cells. Like this:

def check_cells(self, indices):
    """ Return True if all gameboard[][] cells specified by indices have same value,
        else False.
    """
    board = self.state_of_game.board
    values = [board[row][col] for row,col in indices]
    v0 = values[0]
    return all(v == v0 for v in values)

Then you can write the check_ functions in terms of that:

def check_row(self):
    """Check row containing latest move for a win."""
    indices = ROWS[self.row_index_of_move]
    return self.check_cells(indices)

You'll have to put in some validation on the diagonals, so you only call the check_cells if the move really was on a diagonal. The key here is that this uses the check_ functions to provide more data to the underlying check_cells, and so the bottom level code where the work is getting done is mainly data-driven.

Extra credit: detect forced ties

Your tie-detector only triggers at the last minute. But there are plenty of circumstances where a tie is inevitable. Why not code your tie-checker to recognize them?


First, you are not storing &&, but rather &. Why? because plugin1 etc. are lvalue references, and because of the reference collapsing rules.

Second, you can use a tuple of references as you would use a reference itself. That is, everything is fine unless you return a tuple of references to local objects, in which case references are dangling.

Third, between forwarding (forward_as_tuple) and copying (make_tuple) there's another option:

template<class... A>
constexpr std::tuple<A...> auto_tuple(A&&... a)
{
    return std::tuple<A...>(std::forward<A>(a)...);
}

which keeps a reference to lvalues, and copies rvalues only. I find this most convenient.

In general, storing references or objects depends on what you want to do. Think of what you would choose if it was only one object, then keep the same choice for the tuple.

Check here for more.


You can pass data by const& as it's not being modified.
ARRAY_LENGTH should probably be an unsigned type, such as std::size_t.
Just to stay safe, terminate the program if the file cannot be opened:

if (!file)
{
    std::cerr << "file cannot be opened";
    return EXIT_FAILURE;
}

You do not really need to call close() here.  It would only be necessary for checking for errors, otherwise the destructor will do this for you.  It shouldn't leak any resources.


int test and double test are incompletely done.

errno = 0;
long val = strtol(argv[1], &p, 0);
if (errno) Fail();         // Range error (or possible other reasons)
if (argv[1] == p) Fail();  // no conversion
while (isspace((unsigned char) *p)) p++;
if (*p) Fail();            // Extra junk afterwards

if (*p) Fail(); Needs to be applied to both integer and FP test.

while (isspace((unsigned char) *p)) p++; allows trailing white-space.  Both strtol() and strtod() allow leading white-space.

Double is more complex as in the case of underflow like "1e-10000", the errno may set and that is usually not considered an error in many uses.  The returned value will be either +/-0.0 or a small double value.

double val2 = strtod(argv[1], &p);
if (errno == ERANGE && fabs(val2) <= DBL_MIN) NoFail();

Keep in mind a string may nicely translate to a long as well as a double.  Should "-0" be along 0 or double -0.0?  Aside from this case, I would favor long, especially if the test for extra junk is used.

Your test cases do not include big values "123...thousand_more...456", values like LONG_MIN (-1, +0, +1) and  LONG_MAX (-1, +0, +1), DBL_MAX, next_after(DBL_MAX,0), strings with trailing garbage "123xyz", -0.0.  BTW: a harsh check it to use (char) -1 in various places in the string. Or lead the string with (char) (x80 + ' ')

Nor does it test odd things like "++123", "0x0xABC", "08".  (multiple sign, 2-prefix, octal 8) and new emerging "0b0101"  (C14?)

Extreme FP strings include "0.000...0001e320", "" and "  " (white-space only strings.)

FP also has a hexadecimal format, see scanf("%a")/printf("%a") for additional strings.

Original request was for "double or integer".  Code conveniently uses long, but what if int was meant or intmax_t?  Example additional test for int

long val = strtol(argv[1], &p, 0);
if (val < INT_MIN || val > INT_MAX) RangeError();
int i = (int) val;
...

To cope with decimal separator as , or ., use setlocale() and that will adjust strtol() and strtod().  But that is a weak aspect of C.

Lastly, a given locale could have "additional subject sequences" that convert into numbers.


Switch statement for adding/removing operands to the text part of a label

So, as a start, I'd take my enum, which you've stuck at the bottom, and move it to the top.  It's great to use custom types, but sticking it at the bottom of the file does a disservice to readers.  And the fact that it has been placed at the bottom makes me think that the author may have undervalued this custom type (and judging by the code, I'd say the enum certainly appears undervalued).

So:

Move the enum to the top so that future readers can start there.

Next, what are we gaining by abbreviating the operand types?  Not a whole lot.  We only have to fully type it out once, and the rest of the time it will autocomplete for us, right?  Right.  By fully typing out the name the first time, we're going to increase the readability throughout everywhere that uses the enum.  And writing readable code is important.

So:

Move the enum to the top so that future readers can start there.
Don't abbreviate.

Finally, look at what we're doing.  We call our appendOperand and pass in one of our Operand enum values, and that does some work to eventually call an overloaded appendOperand method that takes a string.  A string which we're magically associating with the operand, and only doing so in this very weird way.  But why?  Swift enums can have a backing value associated with them (and there's no performance hit either for storing them or for passing them around... they still perform the same).  We can access that backing value using the rawValue property of enums.

So:

Move the enum to the top so that future readers can start there.
Don't abbreviate.
Use a backing value rather than magically associated strings.

Applying these three points gives us the following enum at the top of the file:

enum Operand: String {
    case Multiply = "x"
    case Divide = "/"
    case Add = "+"
    case Subtract = "-"
    case Evaluate = "="
}

Now, we take a close inspection of the appendOperand method, and I notice a few oddities...

We take a UIButton argument, but we don't use it.
We take an inout argument and return void (hint: don't take the argument and just return a value).
Now that we've fixed our enum, we can take the enum as an argument rather than a String.

There are more issues that can and should be addressed, but getting the enum right is so fundamental to this code that we need to take a breather after fixing that up, see what we can do after fixing that up, and reassess where we're at before we start making more changes.


A little C++ program to have timed rounds for a game

First, it's really not too bad for a beginner, there are functions with local variables and the function names are descriptive. I'm impressed with the fact that all if statements and loops use the braces ({ and }) to create compound statements even though it isn't strictly necessary, it does make maintenance much easier.

Initialize Local Variables
In the function collectnames() the variable continuenameloop is uninitialized. In some program languages this isn't a problem local variables are initialized with a null value which might make continuenameloop false (not what is desired in this case). In C++ all local variable are unitialized which means they are in an unknown state. This may have been a typo since the other local variables are initialized.

Prefer std::NAME over using namespace std;
If you are coding professionally you probably should get out of the habit of using the "using namespace std;" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This stack overflow question discusses this in more detail.

Global Variables
Generally global variables are considered a bad practice (2 references from stackexchange sites, stackoverflow and software engineering). In larger programs with multiple source files it is very difficult to write correct code, debug and maintain code using global variables. Finding where a variable value is altered becomes a huge task. A second problem with global variables in a multi-file program is that global variables are global in scope and can lead to duplicate definitions at link time. In an object oriented program all of these variables could have been global within the object but the scope would still be limited to the object itself.

In non-object oriented programming it might be better to declare the variables in functions or procedures and pass the values into sub functions.

Error Checking
There doesn't seem to be any error checking, users have been known to enter the wrong information. What happens if a negative value for roundtime is entered?

Use Objects
As the game gets more complex it might be a good idea to create classes to implement it. Most of the this current program might fit into a class called game. It might be beneficial if users were a separate class with scores, and possibly  elapsed times. Using objects will allow the code to be independent from other portions of the code, and details of the implementation can be hidden.


A few points:

Your EnterCriticalSection/LeaveCriticalSection code should be placed into a scoped RAII object. This saves you from explicitly calling leave, makes your code smaller, and avoids a deadlock if the synchronized code throws.

Do something similar with everything that requires cleanup (like mThreads = new HANDLE[mThreadCount];).

The interface of your class should receive the tasks by reference and store them by pointer within. This way, you make it clear to client code that the class doesn't take ownership of the tasks it receives. (see Third Edit below).

Use reinterpret_cast instead of C-style casts (because C-style casts = bad, mmmkay?!)

using namespace std;

Don't do this. It greatly restricts what client code (whoever includes your class) can write, and the errors generated in client code are almost always obscure. You're better off repeating that in local scopes (if you must) or (better still) not using it (consider writing using std::string; and similar, in the scopes you use the type, or simply declaring std::string x;).

Edit: If bool ThreadPool::ScheduleTask(Task* task) never returns false, why does it return bool? Shouldn't it be void?

Second Edit: Consder using an unsigned int for the number of threads (mThreadCount).

Third edit ( Hi Loki :) )

Regarding ownership of the threads and object lifetime management (how to implement safely and indicate it in the public interface of the class).

Consider this client code:

ThreadPool runner();

// bad bad code: don't call new with raw pointers like this in practice
// but easy to write to make my point below.
BackgroundTask *t = new BackgroundTask(); // class BackgroundTask: public Task
                                          // defined elsewhere

runner.ScheduleTask(t);

What you don't know looking at this code: should you delete t after the ThreadPool completes running? Will runner delete the task itself? If it does, t will point to deleted memory after runner finishes. If it doesn't, you will have to remember to check when runner has finished, and call delete explicitly, every single time you use the thread pool.

You could implement the ThreadPool to delete all tasks after execution, but then, an enterprising programmer (maybe yourself) could write:

ThreadPool runner();
BackgroundTask t();
runner.ScheduleTask(&t); // pass address of automatic storage object

and this will crash your program when your ThreadPool deletes the task.

Another client code alternative, this one much much worse:

void crashy(ThreadPool& pool) {
    BackgroundTask t;
    pool.ScheduleTask(&t);
} // t goes out of scope here and is destroyed but p still holds it's address

ThreadPool p;
crashy(p); // some compilers tend to happily accept this (maybe with a warning)
// p now has a pointer to a deleted BackgroundTask instance

The interface doesn't indicate ownership and makes you interrupt your coding, to look at the implementation, just so you know how to write client code that doesn't leak or crash.

Solutions:

You could change your interface to take a Task& instead. (Similar to passing by pointer), the only drawback is that you need to make sure the tasks you pass to ScheduleTask must still be in scope until the ThreadPool stops running (in other words, you can still write the nice crashy function).

This is better, as at least you don't need to wonder if it will delete the task (which passing by pointer may, or may not suggest).

Better yet, change your interface to take a std::unique_ptr instead:

class ThreadPool
{
public :
    bool ScheduleTask(std::unique_ptr<Task> task) // << std::unique_ptr by val.
    {
        EnterCriticalSection(&mCriticalSection);
        mTasks.push_back( std::move(task) ); // << notice std::move
        mNumberOfTasksNotFinished++;
        LeaveCriticalSection(&mCriticalSection); // also notice non-raii unlock;
                                                 // if push_back throws on
                                                 // allocating new list node,
                                                 // your whole app is deadlocked

        WakeConditionVariable(&mConditionVariable);
        return true;
    }

private :

    list<std::unique_ptr<Task>> mTasks; // << notice std::unique_ptr
    ...
};

Client code:

ThreadPool runner();
std::unique_ptr<Task> p(new BackgroundTask());
runner.ScheduleTask(std::move(p)); // works, no lifetime management problems
                                   // and no ambguity either

Since the function takes a unique_ptr now, you now know you need to pass a pointer and you also know you are passing ownership as well.


Finding the indices of multiple words in a string

Map<String, Stack<Integer>> dest = findWordsInString(words, phrase);

I don't see the need at all for a Stack here. And not a Map either.

Let's say that you would want to find the third occourance of the word, and then randomly the first, and the fifth, and the second... Then you would want to store the indices in a List, not a Stack.

And why deal with multiple words at the same time? The way that your method is written, it makes more sense to search for all occurances of one word at a time.

As for the very important for loop, while it is totally alright to write it like that, I would personally prefer a while loop with something like this: (there is a bunch of variations for how you could do this)

int loc = phrase.indexOf(word);
while (loc != -1) {
   locations.add(loc);
   loc = phrase.indexOf(word, loc + 1);
}

It makes it easier to read the code, in my opinion.


It looks like you have three distinct cases, two of which can be covered with one regex as @EmilyL pointed out already.

So unless I am missing something can't you just do the following?

private static String format(String unformattedStr) {
    return unformattedStr.replaceAll("(;?\\s)(\\d+[).])", "$1\\\\n$2");
}


Before rewriting the program, I'll start with some smaller issues.

Minor simplifications

Use print and '''long strings''' instead of multiple file.write() calls to get newlines.  Use r'' (raw strings) to avoid doubling backslashes.
I would just write the tables to standard output, and redirect the output to a file using the shell.  That avoids hard-coding 'table.txt' in your program.
Use for line in range(1, len(LINESIG0)) to skip the first line.
Ideally, you should rename your files to coincide with their column headings, so that you don't have to map 'STOC' → SummerStd_140PU_Scenario4.txt.

Bugs

The third column of a line would be line[2], not line[3].
Calling open() without calling close() results in file descriptor leaks.  Better yet, use a with block to open files, so that they will be closed automatically.  (For a small number of files like this, in a "throwaway" script, you won't run out of file descriptors.  It's a poor habit, though.)

Rewriting

exec() is a bad idea.  It's hard to interpret your code because I have to imagine what the generated code will look like before mentally executing it.  It's complicated further by the fact that some of the string handling happens when preparing the statement ("FILESIG"+str(a) in the line below) and some of it happens inside the evaluation (for example, +stringsig[a]+).

exec("FILESIG"+str(a)+" = open('SummerStd_'+stringpu[1]+'_'+stringsig[a]+'.txt', 'r')")

As you suspected, code that deals with many similar variables should be stored in a data structure such as a list (or multi-dimensional list) or dictionary, not multiple variables.

To generate two tables, you have duplicated the code.  A function should be defined instead.

def table(filenames, headings):
    data = []
    for fn in filenames:
        with open(fn) as f:
            data.append([line.split() for line in f])

    print r'''\begin{table}[h]
\centering
\begin{tabular}{|c|%s|}
\hline''' % ('|'.join('c' for _ in headings))
    print ' & '.join([''] + headings)

    for line in range(1, len(data[0])):
        print r'\hline'
        print ' & '.join([data[2][line][2]] + [f[line][3] for f in data])

    print r'''\hline
\end{tabular}
\end{table}'''

signal_filenames = ['SummerStd_140PU_%s.txt' % (s) for s in
     ['NM1', 'NM2', 'NM3', 'Scenario4', 'Scenario6']
]
table(signal_filenames, ['NM1', 'NM2', 'NM3', 'STOC', 'STC'])

background_filenames = ['SummerStd_140PU_%s.txt' % (s) for s in
     ['TTbar', 'DiBoson', 'TopJets', 'BosonJets']
]
table(signal_filenames, ["TTbar", "DiBoson", "TopJets", "BosonJets"])


The trie creation could by very pretty if you made it an extension then can call it on the array:

var trie = new string[]
{
    "trainee",
    "train",
    "tree"
}
.ToTrie();

The method itself can be simplified. You can use foreach to get rid of the indexes (unless performance really, really, really matters).

Sometimes it's also prettier to use the TryGetValue + else where you can assign all values in a single line to avoid duplication like:

    currentNode.Children[character] = new Node();
}
currentNode = currentNode.Children[character];

To my taste it doesn't look nice. Instead I suggest this where I also use currentNode instead of just node which I find is easier to understand.

public static Node ToTrie(this string[] values)
{
    var root = new Node();
    foreach (var value in values)
    {
        var currentNode = root;
        foreach (var c in value)
        {
            var node = (Node)null;
            if (currentNode.TryGetValue(c.ToString(), out node))
            {
                currentNode = node;
            }
            else
            {
                currentNode = (currentNode[c.ToString()] = new Node());
            }
        }
        currentNode.IsWord = true;
    }
    return root;
}

The Node can actually be simplified too by deriving it from a dictionary. By adding the search method to it you can easily use it on any node. I named it Contains.

Another adjustment you can make is to use string instead of the char so you can use one of the construtor overloads of the dictionary and make it case insensitive. This way you won't need the ToLower.

public class Node : Dictionary<string, Node>
{
    public Node() : base(StringComparer.OrdinalIgnoreCase) {}

    public bool IsWord { get; set; }

    public bool Contains(string value)
    {
        var currentNode = this;
        foreach (var c in value)
        {
            var node = (Node)null;
            if (currentNode.TryGetValue(c.ToString(), out node))
            {
                currentNode = node;
            }
            else
            {
                return false;
            }
        }
        return currentNode.IsWord;
    }
}

Usage:

var result1 = trie.Contains("train"); // True
var result2 = trie.Contains("TraINE"); // False
var result3 = trie.Contains("TRAINEE"); // True


Your code validates at the HTML and CSS validators, except for one thing:

You need to place a doctype at the top of the page:

You also need to provide head and body elements and place your code in the body tag, like this:

<!doctype html>

    <meta charset="UTF-8">
    <title>Page title</title>

I was unable to completely remove the position properties in the CSS, but I was able to remove one.  I also adjusted position of the progress bar as it was not lining up with the input bar nicely.

Here I changed the margin padding:

.time-progress {
    /* ... */
    padding-top: 30px;
    padding-left: 30px;
}

I removed two values from this class:

.time-slider {
    background: #ebebeb;
    height: 3px;
    flex: 1;
}

This is the adjusted .progress class:

.progress {
    background: #4ea6ea;
    height: 100%;
    vertical-align: top;
    position: relative;
}

This is the adjusted .time-range class:

.time-range {
    margin-left: 0px;
    padding: 0px;
    width: 100%;
    vertical-align: top;
}

I changed the progress div to this:

This prevents the blue bar from overlapping the button at the default position.

*, *:before, *:after {
    box-sizing: border-box;
}

input:focus, button:focus {
    outline: none
}

.time-progress {
    display: flex;
    align-items: center;
    width: 300px;
    padding-top: 30px;
    padding-left: 30px;
}

.time-label {
    margin: 0 5px;
}

.time-slider {
    background: #ebebeb;
    height: 3px;
    flex: 1;
}

.progress {
    background: #4ea6ea;
    height: 100%;
    margin-top: 0px;
    vertical-align: top;
    position: relative;
}

.time-range {
    margin-top: -2px;
    margin-left: 0px;
    padding: 0px;
    width: 100%;
    vertical-align: top;
}

input[type=range] {
    -webkit-appearance: none;
    background: transparent;
    height: 1px;
}

input[type=range]::-webkit-slider-thumb {
    -webkit-appearance: none;
    box-shadow: 0 0 5px #666666;
    background: #666666;
    border-radius: 100%;
    height: 10px;
    width: 10px;
}
<!doctype html>

    <meta charset="UTF-8">
    <title>Page title</title>

            01:47

            <input class="time-range" type="range" />

            03:36

Edit: The above is for FireFox, I didn't see the Chrome only section; however, it displays correctly in both FF and Chrome, so you may want to consider using it.  It also displays almost correctly in IE, but you should make the track as tall as you want the button to be in this case because the thumb is designed to be no taller than the bar.

To get rid of the position properties in Chrome, you should change the .time-range class to this:

.time-range {
    width: 100%;
}

Delete the position: relative; and the margin: 0 10px; in the .time-slider class.

Add this line to the input[type-range]::-webkit-slider-thumb property:

margin-top: -21px;

*, *:before, *:after {
    box-sizing: border-box;
}

input:focus, button:focus {
    outline: none
}

.time-progress {
    display: flex;
    align-items: center;
    width: 300px;
    margin-top: 30px;
    margin-left: 30px;
}

.time-label {
    margin: 0 5px;
}

.time-slider {
    background: #ebebeb;
    height: 3px;
    flex: 1;
}

.progress {
    background: #4ea6ea;
    height: 100%;
}

.time-range {
    width: 100%;
}

input[type=range] {
    -webkit-appearance: none;
    background: transparent;
    height: 1px;
}

input[type=range]::-webkit-slider-thumb {
    -webkit-appearance: none;
    box-shadow: 0 0 5px #666666;
    background: #666666;
    border-radius: 100%;
    height: 10px;
    width: 10px;
    margin-top: -18px;
}
<!doctype html>

    <meta charset="UTF-8">
    <title>Page title</title>

            01:47

            <input class="time-range" type="range" />

            03:36


I haven't extensively tested it, but there are a few things I've noted:

The class has two members which hold on to IDisposable resources. Therefore, the class must implement IDisposable as well and Dispose() of those members.
Many of the class members are assigned at construction time only. Mark them as readonly to signify intent and to potentially allow the runtime to perform some optimizations.
Current naming conventions favor camelCasing over Hungarian Notation for class members.
+= 1 and -= 1 can be simplified to ++ and --, respectively.
ApplicationException has been out of favor for quite a long time.
Identify your class members with the this keyword.
Forgot to put this bullet point in on the first cut: replace .Count() > 0 with .Any(). This is idiomatic to what you want, rather than how to do it. In other words, the implementation of the former could very well iterate over the entire collection to get the count, while the latter may just check for the existence of one in its collection.
Another omission: I replaced the declaration of HashSet<int> with ISet<int> since coding to interfaces allows for more flexibility in changing implementations later on.

All that being said, here's a first-cut rework:

public class OrderedLock : IDisposable
{
    private static readonly ConcurrentDictionary<int, object> createdLocks = new ConcurrentDictionary<int, object>();
    [ThreadStatic]
    private static ISet<int> acquiredLocks;

    private readonly ThreadLocal<int> refCount = new ThreadLocal<int>(false);
    private readonly ReaderWriterLockSlim locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
    private readonly int id;

    /// <exception cref="InvalidOperationException">Duplicate identifier detected</exception>
    public OrderedLock(int id)
    {
        if (!createdLocks.TryAdd(id, null))
        {
            throw new InvalidOperationException("Duplicate identifier detected");
        }

        this.id = id;
        this.refCount.Value = 0;
    }

    public void AcquireReadLock()
    {
        this.CheckLockOrder();
        this.locker.EnterReadLock();
    }

    public void AcquireWriteLock()
    {
        this.CheckLockOrder();
        this.locker.EnterWriteLock();
    }

    public void ReleaseReadLock()
    {
        this.refCount.Value--;
        this.locker.ExitReadLock();
        if (this.refCount.Value == 0)
        {
            acquiredLocks.Remove(this.id);
        }
    }

    public void ReleaseWriteLock()
    {
        this.refCount.Value--;
        this.locker.ExitWriteLock();
        if (this.refCount.Value == 0)
        {
            acquiredLocks.Remove(this.id);
        }
    }

    public void Dispose()
    {
        while (this.locker.IsWriteLockHeld)
        {
            this.ReleaseWriteLock();
        }

        while (this.locker.IsReadLockHeld)
        {
            ReleaseReadLock();
        }

        this.locker.Dispose();
        this.refCount.Dispose();
        GC.SuppressFinalize(this);
    }

    /// <exception cref="InvalidOperationException">Invalid order of locking detected</exception>
    private void CheckLockOrder()
    {
        if (acquiredLocks == null)
        {
            acquiredLocks = new HashSet<int>();
        }

        if (!acquiredLocks.Contains(this.id))
        {
            if (acquiredLocks.Any() && acquiredLocks.Max() > this.id)
            {
                throw new InvalidOperationException("Invalid order of locking detected");
            }

            acquiredLocks.Add(this.id);
        }

        this.refCount.Value++;
    }
}


Trying to use a generic array in Java, is a disaster waiting to happen. The T[] field is really an Object[] at runtime, and trying to do otherwise just hides this fact. It makes you think you're dealing with a T[], but it's a lie; you're really dealing with an Object[]. There are very good reasons not to use generic arrays. I'll add that if you peek into the current Oracle implementation of ArrayList or CopyOnWriteArrayList, you won't see a generic array being used, but Object[] explicitly. It makes it clear to the developers and to the readers that the array being handled does not have a generic type.

In your particular case, there are no unsafe operations done with it, so that's good. But be careful if you add a toArray() method in the future... Just take a look to see how easy it is to make a mistake: add the method

public T[] toArray() {
    return queue; // or queue.clone();
}

Looks fine. Even compiles without warnings. Now do:

Queue<String> queue = new Queue<>();
queue.push("foo");
String[] array = queue.toArray();

Looks also fine. Still no warnings. But this will fail at run-time:

  Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

Runtime is the worst moment to have those exceptions. It is always better to detect bugs as early as possible, and fail directly at compile-time. And this exception, is because the array really isn't a String[], but an Object[]. There are ways around that of course (the simpler being to return Object[] from the method), but the point is that you're opening yourself to a lot of unforeseen troubles. All in all, if you really want a backing array, don't lie to yourself and:

Just use Object[]. You'll have to cast when poping or pushing elements, but you can ensure that it is safe to do by having the proper generic type for the methods, just like you have in the current code.
If you want strong typing, pass the class of the elements as constructor to the Queue.

Couple of side-notes:

It would be preferable to throw an NoSuchElementException if the queue is empty inside peek, instead of failing with an out of bounds exception.
To copy arrays, you can use System.arraycopy, like mentioned in this other answer.


Variadic template for concisely defining a tuple whose components are all the same type

As nwp pointed out in a comment, std::array is a better choice for this.  I didn't need to write this template at all.


Making an array whose elements are defined by a struct

1D array:

check_t *enqueued = malloc(N * sizeof(*enqueued));
enqueued[0].x = 5;
enqueued[N - 1].x = 2;

2D array:

check_t **enqueued = malloc(N * sizeof(*enqueued));
for(int i = 0; i < N; i++)
    enqueued[i] = malloc(M * sizeof(**enqueued));
enqueued[0][0].x = 5;
enqueued[N - 1][M - 1].x = 2;


Bash script prepares virtual environment

There are a number of good practice items you are missing here, that would benefit your script.

First up, you should name your variables/parameters. The check you have to ensure that the project name and user are specified is OK, but you should rather pull the $1 and $2 values in to their own variables, say pname and puser.

pname=$1
puser=$2

Then it becomes easier to read the code... $pname is a lot easier to understand than $1.

The second issue I see is that you don't check for error conditions. A relatively easy handler is to add the exit-on-error flag to your shell script. Consider adding set -e at the beginning of the script (or a more elaborate system, but your script should be fine with set -e. For more information see: What does set -e mean in a bash script?

The third issue is a small one - why are you using both sudo and su in the same command..... sudo su .... seems rhetorical. Just use sudo --user $puser ....

Another little issue is that you should exit with a non-zero if the parameters are wrong (use exit 1 instead of exit)...

echo -e "mkve.sh - make virtual environment\nUsage: mkve.bash project_name user_name"
exit

should be:

echo -e "mkve.sh - make virtual environment\nUsage: mkve.bash project_name user_name"
exit 1

Yet another small issue is that it's normal to not have .sh as the extension for exectuable shell scripts. Why call your script mkve.sh instead of mkve? Also, you call it two different things in the error message, mkve.sh and mkve.bash.... which is right?

Finally, it is unconventional to put home directories in the /mnt folder. That folder has a special purpose when mounting file systems that are not normally mounted (things like CD's, USB drives, etc.). Using that folder for these home directories will probably lead to unexpected issues if/when someone mounts a drove over /mnt and all your home folders disappear.

The end code would be something like (untested):

#! /bin/bash

# exit if there's a failed command
set -e

if [ $# -lt 2 ]
  then
    echo -e "mkve - make virtual environment\nUsage: mkve project_name user_name"
    exit 2
fi

pname=$1
puser=$2

echo project name: $pname
echo project user: $puser

# create the webapp user and its home directory, and give it ownership
sudo useradd --system --gid webapps --shell /bin/bash --home /ves/$pname $puser
sudo mkdir -p /mnt/u1/$pname
sudo chown $puser /mnt/u1/$pname

# become the webapp user, create a virtual environment, start it, and install gunicorn and flask
sudo --user $puser bash -c "cd ~; virtualenv ./venv"
sudo --user $puser bash -c "cd ~;. venv/bin/activate; pip install gunicorn flask"

echo -e "Done! Start with:\n$ sudo -u $puser -i\n$ . venv/bin/activate"
echo -e "Or undo the whole kaboodle with:\n$ sudo userdel -r $puser"

# at this point, manual configuration is necessary, which is different for each project.


Console program, let users to enter prices calculate subtotal, tax, and total with C Sharp

This isn't bad for a beginner, but there is much room for improvement.

Organization

The app is small enough that everything can fit inside Main, but a more seasoned developer will have Main be more barebones, with calls to other methods.

You would also want to separate out the UI, that is the prompting for input values, from the other Logic, that is the addition and display of values.

Variable Declaration and Naming

The good news is that your variables have some meaning in their names.  The bad news is you begin local variables with a capital letter (known as PascalCasing), when it should be camelCasing.  Thus, FirstOperand should be firstOperand, etc.

Also, CodeReview prefer to see each variable declared on its own line.  What I would expect you to end up with is something like:

decimal firstOperand;
decimal secondOperand;
decimal result;

Checking for Valid Input

You have no checks for valid input.  What happens if someone enters "dog" instead of 123.45?  You may want to read up on the Decimal.TryParse method to help out with that.

Things not needed

As mentioned, there is no need for Result and result since result is already a Decimal.

This line is too confusing:

Console.WriteLine("Addition Result: {0}", string.Format("{0}", result));

There is an overload for Console.WriteLine that accepts a string format.  This would simplify the line to:

Console.WriteLine("Addition Result: {0}", result);

The link you provide is for C# 2012.  Newer versions of C# support Interpolated Strings, prefaced with a $".  So you could also do the above with:

Console.WriteLine($"Addition Result: {result}");

If you wanted to control formatting of the numbers, it could be done one of 2 ways:

Console.WriteLine($"Addition Result: {result.ToString("0.00")}");

Or

Console.WriteLine($"Addition Result: {result:0.00}");

More Reading

To learn more, I found a decent post here on CR 'Welcome to Buzzway Subs'.  I recommend reading the original code, AND then follow up by reading the good advice in the answers.


I'd need more context so please consider some suggestions as implicit questions.

In PipeLineStep class StepName property is a read-only property. If you just return a constant value you may want to make it a constructor parameter instead (where you may also include some sort of validation):

protected PipeLineStep(string name) {
    if (String.IsNullOrWhiteSpace(name))
        throw new ArgumentException("Step name must not be nor empty.", "name");

    StepName = name;
}

public string StepName {
    get;
    private set;
}

Property name itself is little bit redundant, you do not need to repeat Step* for a property of a class named *Step:

public string Name {
    get;
    private set;
}

In the same class WasSuccessful is a public read/write property. Does anyone (inside or outside its assembly) has right to both read and write this property? Assuming (because Run() is internal) that also WasSuccessful is set from within same assembly then I'd make its setter internal.

In the same class Run() method is internal. Because it's also abstract it seems that it's used only from the same assembly where class is declared and also that all derived classes are located in the same assembly. This arises a question: does it make sense to have a public abstract class that can be used and extended only from the same assembly? It may be - if other assemblies will access Name ans WasSuccessful properties - but if it's not then don't make this class public.

In general visibility issues won't make your code broken but they will help to make it safer (from usage point of view) and they communicate intent.

In RunStep method you're catching a generic Exception. You should formalize which exceptions each step will throw to possibly narrow down to a smaller set of exceptions, catching Exception you get everything, from OutOfMemoryException to ArgumentException and it's bad because they're exceptions that need a special handling. Also, knowing what you're catching will help you to determine corner cases and error scenarios: a very good exercise for you and for your tests.

You're mixing bool and Boolean (for example), they're equivalent then I'd suggest to use the style you prefer and be consistent, reader won't repeatedly ask himself why (variations are eye-catching, they must be justified).

Parameter isFullLoad is not meaningful without more context, I'd rename it to something else but I actually don't know what it means (and your future-you won't know either without re-reading surrounding code...)

You're using a parameter errorRerun to know if you're retrying because of a previous error. While it's not an issue in such simple scenario it may be confusing (see your handling logic) and it adds more parameters to a function that should be as simple (you already have four parameters, two/three more than what's good). I can't suggest anything without much more context and knowledge but it's a point I'd investigate further.

Expression is !isFullLoad && !errorRerun is used twice, it's a good chance to extract a local variable with a meaningful name (again, rename it according to its exact meaning):

bool canRunFullPipelineAgain = !fullLoad && !errorRerun;

In general you're using too many function arguments and too many of them are bool. Pick any line where you use them and you can't understand their meaning without jumping back and forward to called function prototype (see RunStep(), Run(), UpdateProgress() and Logging.Log().)

To reduce number of arguments you have various techniques for example (again it depends on surrounding code) errorRerun may be a class member property as context and isFullLoaded (you have classes, containers of methods and state, you don't need to pass everything as parameters). Your logging function is a good example of this: its prototype is waaaaay too complex and convoluted. If you really can't change it - at least - use named parameters.

Boolean parameters are easier to remove, you may use enum instead of them (eventually - when it makes sense - combined as Flags). For example:

var options = RunStepOptions.TableIsFullyLoaded | RunStepOptions.RetryOnError);
if (!RunStep(step1, context, options))
    return false;

Minor question: shouldn't PipeLine be Pipeline?

Free thinking: if Run() executes all steps in pipeline then why you're putting error handling in RunStep()? Isn't easier to write a method Run() without error handling and an outer method RunWithErrorHandling() which takes care of this? You may also introduce a StepExecutionException, almost pseudo-code:

private void RunWithErrorHandling() {
    try {
       Run();
    }
    catch (StepExecutionException e) {
        // Try again? I don't know your full logic here
        Run();
    }
}

private void Run() {
    foreach (var step in Steps)
        RunStep(step);
}

private void RunStep(PipelineStep step) {
    try {
    }
    catch (Exception e) { // !!!
        // Logging?
        throw new StepExecutionException("...", e);
    }
}

Without surrounding code and better understanding of its context I can't suggest another design, just take this as something to think about.


I know little about this language, but dealing with powers of 31 is surely no good idea. Most probably, it'll overflow or lose precession and you get pure garbage.

If there's something like long (64 bit integer), you can rewrite the Java implementation easily. The only relevant part is the loop doing

h = 31*h + val[off++];

Just reduce h after every iteration to the int range, so it doesn't crash your Windows overflow.

Actually, you need no long, a double (floating point with 56 bits of mantissa) would do. Simple float (24 bits mantissa) is unusable here.


A classy wine collection - Construction vs. Initialization

Code Review

Just wondering if there is an EC library inside windows.
Best to be descriptive and long winded here.

#ifndef WINEC_H_
#define WINEC_H_

Also you may want to put all your code inside a namespace.

In this scheme were you access the year and count you have to perform two array lookups. Not a big deal. But to me the logic seems the wrong way around.

typedef std::valarray<int> ArrayInt;
typedef Pair<ArrayInt, ArrayInt> PairArray;

I would have done this:

typedef Pair<int, int>         WineInfo;
typedef std::vector<WineInfo>  PairArray;

Now when you have the year (vintage) you have the count in the same object (better spacial locality).

Is this not simply the size of holdings?

    int yearsHeld;

I would not have a default constructor.
Is there a need to create an special "unnamed" object?

Sure you can pass by C-String

Wine::Wine(const char *l, int y)

But I usually make this a std::string const& then it can be used with strings and with C-Strings (the string is dynamically constructed in place). If you are worried about the copy you can always add a constructor that takes the parameter by r-value reference so it is moved into the object.

I don;t like passing y the number of years held. Then just creating a set of unitialized values. The year 0 is not really a valid value.

Wine::Wine(const char *l, int y)

What you could do is allow a list initializer. This takes a list of WineInfo that allows you to initialize the object.

Wine  myWine("Flore de Sole", {{2014,15},{2013,8},{2012,3},
                                {2011,1},{2010,1},{2009,1}}
            );

OK. So you try. But this is a very dangerous interface. There is no way to guarantee that the yrs array and the bot array are at least y size.

Wine::Wine(const char *l, int y, const int yrs[], const int bot[])
    : mLabel(l), yearsHeld(y)

You should pass references to objects of known size. You could pass a reference to an array of length y

template<int y>
Wine::Wine(const char *l, const int (yrs&)[y], const int (bot&)[y])
    : mLabel(l), yearsHeld(y)

Always hat getters. They break encapsulation.

std::string & Wine::label()
{
    return mLabel;
}

Also note you are returning a non cost reference. So the caller can alter the label dynamically.

w.label() = "Plop";

Sure. Always good to have a print function. But rather than fix it with std::cout pass the stream as a parameter. The default can always be std::cout

void Wine::show() const

I would write as

void Wine::show(std::ostream& out = std::cout) const

Always prefer \n over std::endl

    cout << "Wine: " << mLabel << endl;

The difference is that std::endl will also flush the buffer. This makes using streams very in-effecient. You practically never need to flush the buffer manually.

Rather than using a manual loop. Prefer to use an algorithm

    for (int i = 0; i < yearsHeld; i++)
    {
        sum += holdings.second()[i];
    }

Simpler to write:

    return std::accumulate(std::begin(holdings), std::end(holdings));

No need to copy if you just need a reference.

  T1 first() const { return a; }
  T2 second() const { return b; }

Just return by const reference. Then it can be used without having a copy made.

  T1 const& first() const { return a; }
  T2 const& second() const { return b; }


Execute script on remote host and obtain variables on localhost

This has numerous problems with it, one of which is the race condition. Imagine two clients connect to the server at the same time. Which client's tmp.json wins? The other client gets bad data.

Another problem with the current way of doing things is that you start a new PHP interpreter for each request. So, it's not as lightweight as you're envisioning.

You really need to develop a protocol for sending the two data streams back, and then implement that protocol. A temporary file should not be necessary.


Git pre-commit hook to check that changes to certain files only happen on the master branch

Use fewer abbreviations. It's certainly not bad in this case, but small stuff like production instead of prod (unless perhaps it's a naming convention for your production environment/server), and primary_branch (I guess?) instead of pri_branch. Or, at any rate, be consistent: You have development spelled out, but you shorten production?
Use parenthenses or at the very least spaces in method calls - and include? is just a method call. So this expression out_data.include?zone_files[key] looks weird right now.
When iterating a hash, the block will be passed the elements as [key, value] arrays. If you add a bit of array destructuring, you get key and value separately.

zone_files.each do |environment, file|
  # ...
end

But zone_files doesn't actually need to be a hash. Of course you can use one, and it may be worth it to label to two zone files. But it could just be an array. And you might want to make it constant while you're at it.
Get the current branch once. Right now it's being parsed for each of the zone files, since it's inside the loop.
And check the branch once - if it's the pri_branch then you can skip everything else.
You can use a heredoc for the warning

Here's my take

# Array of zone files to look for when a commit is attempted.
ZONE_FILES = %w(some_zone_file1 some_zone_file2).freeze

# The branch we're allowed to commit zone files on
PRIMARY_BRANCH = "master".freeze

# get the current branch
current_branch = %x{git branch}.match(/\* (.+?)\n/m)[1]

# stop here if we're committing to the primary branch
exit(0) if current_branch == PRIMARY_BRANCH

# execute git diff to determine files includes as part of commit.
commit_files = %x{git diff --cached --name-only}

# find out if any of the zone files are among the files
# being committed
committing_zone_file = ZONE_FILES.detect { |zone_file| commit_files.include?(zone_file) }

# and if we're committing a zone file, complain to the user
if committing_zone_file
  puts <<-EOT
Error: You have triggered a git pre-commit hook.
Your current branch is: #{current_branch}.
For DNS, ensure you commit on branch: #{PRIMARY_BRANCH}
Include '-n' to bypass this check.
Exiting...
  EOT

  exit(1)
end


I would probably have a custom control that wrapped instances of the controls instead of directly inheriting from one of two possible controls, if that makes sense.

This approach leaves your code more open in the future and allows you to add additional features as part of your control (like validation controls for example) that conditionally become applied when the mode is set to a TextBox.

Here is what I came up with (this should be a run-able example):

using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls.Web {

    [DesignTimeVisible(true)]
    [ToolboxData("<{0}:TextBoxLabel ID='' runat='server' />")]
    [DefaultProperty("Text")]
    public class TextBoxLabel : WebControl {

        #region --Instance Variables--

        private Label _ctlLabel;
        private TextBox _ctlTextBox;
        private TextBoxLabelModes _mode;
        private WebControl _renderedControl;
        private string _text;

        #endregion

        #region --Constructors--

        /// <summary>
        /// Creates a new instance of the TextBoxLabel class.
        /// </summary>
        public TextBoxLabel()
            : base() {
                _ctlLabel = new Label();
                _ctlTextBox = new TextBox();
                _mode = TextBoxLabelModes.Default;
                _renderedControl = null;
                _text = string.Empty;
        } // end constructor

        #endregion

        #region --Methods--

        protected override void CreateChildControls() {
            base.CreateChildControls();
            if (this._mode == TextBoxLabelModes.TextBox) {
                _renderedControl = this._ctlTextBox;
            } else {
                _renderedControl = this._ctlLabel;
            }
            _renderedControl.ID = this.ID;
        } // end method CreateChildControls

        public override void RenderControl(HtmlTextWriter writer) {
            _renderedControl.RenderControl(writer);
        } // end method RenderControl

        #endregion

        #region --Properties--

        [Category("Appearance")]
        public virtual TextBoxLabelModes ControlMode {
            get {
                return _mode;
            } set {
                _mode = value;
            }
        } // end property ControlMode

        [Category("Data")]
        public virtual string Text {
            get {
                return _text;
            } set {
                if (!string.IsNullOrWhiteSpace(value)) {
                    _text = value;
                    _ctlLabel.Text = value;
                    _ctlTextBox.Text = value;
                } // end if
            }
        } // end property Text

        #endregion

    } // end class TextBoxLabel

    public enum TextBoxLabelModes : int {

        Default = 0,

        Label = 1,

        TextBox = 2
    }

} // end namespace


Secure: Not yet, but it's a start. Your validation is too strict in some places, and may result in the wrong email address being used. In particular here:

$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
//a bit later on:
$email = str_replace(array("\r", "\n", "%0a", "%0d"), '', stripslashes($email));

If the value of $email is one of these examples of valid email addresses:

!#$%&'*+-/=?^_`{}|~@example.org
"()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org
"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com

you're stripping the slashes, which'll yield:

!#$%&'*+-=?^_`{}|~@example.org
"()<>[]:,;@"!#$%&'*+-=?^_`{}| ~.a"@example.org
"very.(),:;<>[]".VERY."very@ "very".unusual"@strange.example.com

Effectively changing the actual email address, and this may in turn turn a valid, though outlandish email address into an invalid one.
BTW: source for these email addresses is the email wiki

When it comes to email addresses: use filter_validate($emai, FILTER_VALIDATE_EMAIL) and rely on that function's ability to validate the string. Don't do any processing of your own, especially not after having sanitized and validated the email address.
Bottom line, if you want to validate an email address, while allowing users to pass an (accidental) \r char, use this:

$email = filter_var($_POST['email'], FILTER+_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    echo $jsonHelper->encode($email.' is an invalid address'));
}

On the other hand, you're not sanitizing the message and name as well as maybe you should. It's not unlikely your script is vulnerable to mail injection. A must-read on this subject can be found here.

Since we're all in the business of programming, I hope you'll understand I'm not going to repeat myself here, but I've dealt with mail injection previously on this site: read my answer to this question, which focusses on injection a bit more.

Some other niggles:

Please, as ever, try to stick to the coding standards as described by PHP-FIG. Most, if not all, major players subscribe to this standard, so should you. Check the standard here.
Things like public function foobar(){ are not accepted, the opening brace should go on the next line. It may seem silly to stumble over this, but really: it isn't.
don't use die in a method, and avoid using echo. I take it you're using a framework of sorts. Check if there's an ajax helper that outputs, or use the view to echo JSON content. And from within an action (controller method), don't call die, but rather return, signaling an uneventfull end of the controllers' job. die breaks the normal way of processing a request, which may cause problems down the road.


Not a proper methodology nor a code-review but I'll try to explain what I've done.

First, I've put your code in a function returning the (red, green, blue) tuple.

Then, I wrote a tiny bit of code to find the different values taken by the different colors :

prev_t = None
for i in range(362):  # Going a bit further than 360 just out of curiosity
    red, green, blue = foo(i)
    t = blue  # Change this if you care about a different color
    if t != prev_t:
        print(i, t)
    prev_t = t

For the blue color, I got :

(0, 0)
(180, 1)
(360, 0)

which led me to think that the blue value was 1 for values bigger than 180 (because the comments talked about wheels, it made sense to apply a modulo 360).

I got a bit lucky because I started with the blue color which was the easiest. Now, the blue value can be computed with :

angle_blue = angle % 360
blue = angle_blue >= 180

Then, I applied a pretty similar trick to other colors by changing the line t = blue and I realized that they could be computer with a similar logic but with an additional shifting.

Now, the code can be written :

def foo2(angle):
    angle_blue = angle % 360
    blue = angle_blue >= 180

    angle_green = (angle - 60) % 360
    green = angle_green < 180

    angle_red = (angle - 120) % 360
    red = angle_red >= 180

    return red, green, blue

(This code could be written in a more concise way but this version corresponds to the fact that I've progressed by handling one color at a time).

This seems to be working for all tested values as per the assert added to the loop I originally wrote :

for i in range(362):  # Going a bit further than 360 just out of curiosity
    red, green, blue = foo(i)
    red2, green2, blue2 = foo2(i)
    assert red == red2
    assert green == green2
    assert blue == blue2


Parsing of a (Linux) netlink hotplug uevent packet

The empty line after the first #include is a little odd.  They can all be kept together and still be grouped by type (system, library, and local).

Also, consider ordering these in some way for organization, such as alphabetically.
void parameters are not needed on C++, unlike in C.
C++11 now supports list initialization, which you've mostly done here with msg.  You can omit the = to make full use of this.
This for loop is way too long horizontally:

for ( auto it3 = it2 , it4 = std::find( it2 , msg.end() , '=' ) , it5 = std::find( it4+1 , msg.end() , '\0') ; it3 != msg.end() , it4 != msg.end() , it5 != msg.end() ; it3 = it5+1 , it4 = std::find( it3 , msg.end() , '=' ) , it5 = std::find( it4 , msg.end() , '\0' ) )

You may be better off just using a while loop and making the calls to std::find() within the body of the loop.  Another option would be to wrap this line, but that may also look ugly.


Let me start with some suggestions to improve your code a little bit in regards of scala/functional style. I will start with by class with the points that catched my eyes first and i might edit my post later on and add additional points.

Class structure and constructors

Instead of going with

class Bunny(inColor : Color.Value, inGender : Gender.Value, inAge : Int, inName : String, radioactive : Boolean){
    private val _color = inColor;
    private val _gender = inGender;
    private val _name = inName;
    private var _radioactive = radioactive;
    private var _age = inAge;

you can write it more concise like this:

class Bunny(val color : Color.Value, val gender : Gender.Value, var age : Int, val name : String, var radioactive : Boolean){

No need to declare them with other names inside the class. Notice however, that public getters and setters (for vars) will be created automatically. Going private val color : Color.Value on the other hand will create a private getter.

Instead of creating the adult variable on the fly (def adult : Boolean = {_age >= 2 && !(_radioactive)}) it may be better to make the main constructor accept an adult variable and to create a second constructor (which calls the main constructor) that does the logic above. One important benifit is, that it will be more easy to test when you can pass in the adult variable as is.

The getChild method in your BunnyFactory class seems to belong to your Bunny class. You could consider making a class for male and female bunnies because they behave different although they are both bunnies. Traits could be a good option here to add a functionality only to the female bunny class for creating new child bunnies.

Naming

In your Bunny class you have a method update(list : ListBuffer[Bunny]) : Unit. I would call that different. Maybe infectNeighbours or similar.

In your BunnyFactory class you could call the getInitial method createRandomBunny or so. Because getInitial makes me think "huh? What does it do?". Same for getChild

In your main game class don't use list but rather existingBunnies or something like this.

Shortcuts

In the toString method of Bunny class you use return s"${_color} ${_gender} Bunny ${_name}, ${_age} years old, Radioactive: ${_radioactive}".
The more scalaish way to do this is to omit the "return". It is not needed. The result of the last expression is used as return value anyways. Same goes for most of the other returns.

Now to your main game class.
I personally prefer using list methods instead of the for comprehension in most cases. So instead of for(i <- list){ I would do a list.forEach. But first what do we want? For example, do we really want our already dead bunnies to infect other bunnies before we remove them from the list?

Here comes the "functional thinking" into to game (assuming our var list is called existingBunnies):

//lets first get a list of bunnies that are still alive
val livingBunnies = existingBunnies.filter{ bunny =>
    if (bunny.dead)
        println(s"Bunny ${bunny.name} is dead with an age of ${bunny.age}!")

    bunny.dead == false
}

//Now create a list of bunnies that are born new. That can be solved using not var but val in a more pure functional style but to me that will make it more complicated so i stayed with the if condition.
var newBornBunnies = List() //We have no new born bunnies by default

//But if there is at least one mal left, each female bunny will create a child
if(livingBunnies.count(_.gender == Gender.Male) >= 1) {
    newBornBunnies = livingBunnies.filter( _.adult && _.gender == Gender.Female ).map( _ createChild )
}

//We add the new born bonnies to the existing living ones
existingBunnies = livingBunnies ++ newBornBunnies

//At the end with our new list of existing bunnies we let them infect each other
existingBunnies forEach (_ infectNeighbours existingBunnies)


Retrieving remote pages and parsing html

Really, the best way to optimize performance is to make the HTTP requests in parallel.  After you have done that, you could consider further optimizations with regards to parsing.

Consider using curl_multi_exec() or similar for this.

I have a REST client based on curl_multi_exec() that you can feel free to take a look at for inspiration (or just use as-is in your application based on MIT license).

https://github.com/mikecbrant/php-rest-client


Simple web based file browser with Flask

@Matthias has already mentioned this in the comments, and he is correct.

The code suffers from a Directory Traversal vulnerability

You can filter this in 2 ways:

Use os.path.realpath and check if the resolved path is different

def check_lfi(file_path):
    return os.path.realpath(file_path) != file_path

Use regex to filter out bad (../) Paths

import re
DIR_TRAVERSAL = re.compile(r"\.\.\/")
def check_lfi(file_path):
    return bool(DIR_TRAVERSAL.search(file_path))

My advice would be to use the first example, since blacklisting can be error prone (Unicode for instance)


Function to calculate energy for wind turbines

First, get rid of the double-spacing. I don't know if that's an artifact of posting on this site, or if you really coded it that way, but fix it!

def WindEnergy_calc(density, surfaceArea, windspeed, powerCoefficient):
    """
    This function returns the value of wind energy given density of the air,
    surface area of blades, and windspeed.

    Args:
    * density (float or int) - the value represents the density of the air
    * surface area (float or int) - the value represents the total surface area of turbine
    * windspeed (float or int) - the value represents the windspeed in the area
    *Power Coeffecient of turbine (float) - value cannot exceed

    Returns:
    * total possible kinetic energy created by the wind on the turbine
    * P = 1/2*row*A*V^3*C
    """
    try:
        if powerCoefficient > 0.59:
            powerCoefficient = "Not Possible" #to break code
    except:
        print "Power Coefficient must be less than 0.59 due to Betz limit"
        return()

    half = 0.5
    windEnergy = float(half*density*surfaceArea*windspeed**3)
    return(windEnergy)

Next, fix the name of your function. This is a function not a procedure. You aren't performing some "helper" operation and leaving your results in global variables or class members. You are performing a computation and returning the result! Pick an appropriate name:

def wind_energy():
def calculate_wind_energy():
def wind_energy_of():

In general, function names should include a verb and some supporting words - adverbs or nouns - to flesh out what is being done. For a "pure" function, it's possible that the verb is implicit: the word "compute" or "calculate". For example sqrt() and cos() have no verb, because the verb form would implicitly be compute_sqrt() or calculate_cosine(), which doesn't add much value. (On the other hand, we fopen() and fread() because the verb isn't quite so obvious.)
For a function taking lots of inputs, you want to have a really obvious ordering of the inputs. That is, open('foo.txt', 'r') should make it obvious that the filename is first, and the mode is second. (It doesn't, btw. But it should!)

In your case, you have four incoming parameters. None of them seem obvious to me. I'd suggest that you take advantage of python's named-only parameters to put a name on each one of them:

def wind_energy(*, density, area, velocity, power):

Above, the * marks the end of positional parameters - meaning there are none. Every parameter after the * is required to be named. So you call this like:

we = wind_energy(density=1.0, area=4.6, velocity=20, power=0.1)

Cite your sources! I found a website that I think contains your source equations:

http://formulas.tutorvista.com/physics/wind-energy-formula.html

You need to include this, and the name(s) of your equations, in your doc comment. Don't write this:

# No!
"""...returns the value of wind energy ... """

Instead, write this:

# Yes!
"""... return the wind energy computed with Farnsworth's Formula
(http://www.farnsworth.com/wind-energy-formula.html) ... """

Command your minions. This is purely a "social convention." But the standard convention for commit comments and function documentation is to use the Imperative Mood rather than passive voice. It's almost as if your program is telling the computer what to do. (Wait, what?)

Change this:

This function returns the value of wind energy...

Into this:

Return the value of wind energy ...

Likewise, when you commit your changes to Mercurial, don't write this:

I updated the code based on suggestions from codereview...

Instead, write this:

Make changes from codereview ...

Validate and rename!

You have two constraints, one explicit (the Betz limit) and the other implicit (all the parameters are numeric). Validate them!

I'll suggest you have a look at Python's numbers module, which provides abstract base classes for numeric types, and applies a "hierarchy" to them. The most appropriate type, since you use "float or int" a lot, seems to be Real. The Real type adds "conversion to float" which is right up our alley:

rho = float(density)
V = float(velocity)

(Also worth noting: rho is the name of a Greek letter. row is something you do in a boat.)

You might even consider the fact that Python supports unicode identifiers, like so:

 = float(density)

(Sadly, there's no good way to spell V³ except for V ** 3.)

For your explicit validation, you have totally bungled your code:

    try:
        if powerCoefficient > 0.59:
            powerCoefficient = "Not Possible" #to break code
    except:
        print "Power Coefficient must be less than 0.59 due to Betz limit"
        return()

First, try: / except: is used when you believe that the code inside the try: block will raise an exception. You have an if-statement inside the try block that will not raise.

Second, this is not a function that should ever call print. I understand you might insert print statements for debugging, but printing anything is outside the scope of this function. If your caller has passed you an invalid value, the correct behavior is to raise an exception - typically a ValueError - and let the caller deal with their own stupidity. (But make sure you document the limit in your doc comment!)

Try this, instead:

# Somewhere global, like outside the function or top of module:
BETZS_COEFFICIENT = 0.593
"""Betz's coefficient- see https://en.wikipedia.org/wiki/Betz's_law"""

# Inside your function:
if power > BETZS_COEFFICIENT:
    raise ValueError("Power coefficient must be <= Betz's coeff. It's the law!")

Also worth noting: when you invoke return() with empty parens, it doesn't mean "return nothing". It means "return a tuple with zero items". The () expression (note: expression) is an empty-tuple constructor. This is consistent with calling a function with no args, since positional args are a tuple:

>>> def f():
>>>     return()
...
...
>>> x = f()
>>> print(x)
()
>>> type(x)
<class 'tuple'>

What you meant to do was just a bare return. Except that was wrong, and what you really meant to do was raise, as above.


Limiting the save content of file to certain size

First: Crappy indentation makes it hard to read.

Your algorithm seems unnecessarily complicated. Why not work out how many items you want to serialize and just serialize those items.

 // Work out how many items we will need to drop.
 std::size_t  countOfItems      = objectMap.size();
 std::size_t  maxNumberOfItems  = Object::maxMemoryOfObjects/sizeof(Object);

 std::size_t  advance  = (countOfItems > maxNumberOfItems)
                             ? (countOfItems - maxNumberOfItems)
                             : 0;

 // Get an iterator to the first item
 // Then advance it forward the number of items we want t drop
 // These are the older items (as map is a sorted container).
 auto printer = objectMap.begin();
 std::advance(printer, advance);

 // Print all the items using std::copy and a stream iterator
 // May not work out the box for you but you should learn how to do this.
 std::copy(printer, objectMap.end(), std::ostream_iterator<Object>(outfile));

Memory Ownership

Your code is littered with pointers.
This is not a good idea in general (but hard to tell without more context in this case).

RAW Pointers are very rare in C++ as they do not convey object ownership. Usually pointers are managed by some owning object that manages their lifespan (as a result you never interact with them directly but via their owning object).

You should be using containers of object (not pointers) or if you have object hierarchies then use "pointer containers" that understand their content is a pointer and can act accordingly. If you don't have pointer containers available (they are in boost) then you should at least be using smart pointers to maintain the concept of ownership.

Looks like an error:

for (const auto& x : objectMap)
    outfile << x.first << ' ';
}

You are not serializing the object but only the ID. I think you meant:

for (const auto& x : objectMap)
    outfile << x.second << ' ';
}

But now you also need to define:

std::ostream operator<<(std::ostream& str, Object const& data)
{
   returns str << /* Serialize object */
}
std::istream operator>>(std::istream& str, Object& data)
{
   returns str >> /* De-Serialize object */
}

Looks like it might be an issue.

Object::totalMemoryOfObjects += sizeof(*object);

The size of an object in memory is always fixed. So you may as well count the number of objects. Note: sizeof() is computed at compile time not runtime. If you want to add up the number of bytes in things like strings you need to write your own method to do it.

But when you use operator<< the object is generally serialized and the number of bytes can vary (unless you write your object in binary fixed size format to the stream (but then you need to worry about machine peculiarities like endianness (so unless there is an extreme need for speed it is usually best to use a non binary format)).

Declare variables JUST before you use them

std::ofstream outfile ("Objects.txt");

// 500 lines of code not using outfile

outfile << objectMap.size() << std::endl;
for (const auto& x : objectMap)
    outfile << x.first << ' ';
}

Move the declaration of outfile to the point just before you tart using it. In C++ because of constructors/destructors the side affects may allocate resources. If you don't need them don't use them so wait until you need them.

It also has the benefit of making the declaration near the code that uses it so it makes it real easy to see the type of the object you are using (as it is just there with the code).

Encapsulation

struct Person {

You seem to be making all your objects publicly accessible. This does not help encapsulation. You should make all your data members private by default. Then provide methods (which are verbs) that act on the object.

class Object
{
    static int const maxMemoryOfObjects   = 200;
    static int       totalMemoryOfObjects = 0;
    static int       lastObjectID         = 0;

    static int allocateNextAvailableID()
    {
        return ++lastObjectID;
    }
    const int ID;
    public:
        Object()
            : ID(allocateNextAvailableID())
        {}

        // define an ordering on your objects.
        friend bool operator<(Object const& lhs, Object const& rhs)
        {
             // With an ordering you can use Object as the key.
             // in a sorted container.
             return lhs.ID < rhs.ID;
        }
};

int main()
{
    std::set<Object>     objectSet; // No need to allow access to the ID
                                    // to external entities that do not need to know.
                                    // provide the appropriate access method (in this
                                    // case `operator<()` that defines the ordering.
}


There are a few points worth mentioning:

Your code does not actually function the way you want it to.
$(".event_owner input[type='text']").length checks for the existence of that element, not whether its value is set.
Your radio buttons don't have a value attribute on them. They really should.
You should cache your selectors. You're querying for .event_owner a total of 7 times in your code, and an additional 4 times on every click.
Instead of listening for every click inside .event_owner, you should instead only listen for the change event of the radio buttons.
On page load, if there's a value in the input text field, all we have to do is check the correct radio button. The change event listener will take care of the rest.

With the above in mind, here's some sample code you might consider:

var $wrapper = $('.event_owner'),
    $textInput = $wrapper.find('input[type="text"]'),
    $radios = $wrapper.find('input[type="radio"]'),
    owner = $textInput.val();

$radios.on( 'change', function () {
    $textInput.val( $radios.filter(':checked').val() );
    $radios.each(function () {
        $(this).closest('p').css( 'opacity', this.checked ? 1 : .3 );
    });
});

if ( owner ) $radios.filter('#' + owner).prop('checked', true);

Here's the fiddle: http://jsfiddle.net/Zf4UE/8/


When you find a prime number, say 7, you begin crossing out all odd multiples of 7 from the primeCandidates vector.  You do this by incrementing index += loop, where loop is the prime number, and but primeCandidates only holds odd candidates, so the step size in natural numbers would be 2*loop.

The issue is you start by removing 7 from primeCandidates, then 21, then 35.  At this point in the sieve, you've already eliminated multiples of 3 and 5, so marking off 3*7=21 and 5*7=35 is just busy work.  And marking off 1*7=7 is just pointless.  What you should be doing is starting to eliminate at 7*7=49.  It saves only three eliminations during the 7 loop, but the saving get more substantial as the prime gets larger.  For instance, when you get to 199, you wouldn't eliminate 1*199, 3*199, 5*199, 7*199, ... 191*199, 193*199, 195*199, 197*199.  You would just start at 199*199 and go up from there.

Code change:

// Now strain out all factors of the prime we just found, starting with prime^2
index = loop * loop / 2

std::vector<std::size_t> is overkill for primeCandidates.  You only ever store 1 or 0, so allocating 4 or 8 bytes for each candidate is wasting memory.

std::vector<char> would reduce the memory load to 1 byte per candidate.

std::bitset<N> will reduce this to 1 bit per candidate.  Alternately, the vector specialization std::vector<bool> will also give 1 bit per candidate, with a non-compile-time fixed number of bits.


Realizing a SQL ResultSet into a Map in Scala

I don't have the time to test this, so I hope you can do that for me. I decided not to use HashMap straight away because type conversion makes things a bit more complicated than they should, but let me know if this is important for you and causes you trouble.

Here's option 1:

def realize(queryResult: ResultSet): Vector[Map[String, Object]] = {
    val md = queryResult.getMetaData
    val colNames = for (i <- 1 to md.getColumnCount) yield md.getColumnName(i)
    val buildMap = () => (for (n <- colNames) yield n -> queryResult.getObject(n)).toMap
    Iterator.continually(queryResult.next()).takeWhile(identity).map(_ => buildMap()).toVector
}

I don't like it much because some parts of the code rely on side effects of other parts of the code, so even if it works, it's still ugly.

Here's option 2, which I like more:

def buildMap(queryResult: ResultSet, colNames: Seq[String]): Option[Map[String, Object]] =
    if (queryResult.next())
        Some(colNames.map(n => n -> queryResult.getObject(n)).toMap)
    else
        None

def realize(queryResult: ResultSet): Vector[Map[String, Object]] = {
    val md = queryResult.getMetaData
    val colNames = (1 to md.getColumnCount) map md.getColumnName
    Iterator.continually(buildMap(queryResult, colNames)).takeWhile(!_.isEmpty).map(_.get).toVector
}

Nicer, IMHO, you can save some dots over there but I decided to keep them. Maybe something like this:

 (Iterator continually (buildMap(queryResult, colNames)) takeWhile (!_.isEmpty) map (_.get)).toVector

Again, I didn't test it, I don't know how to do it without a DB and I don't feel like setting one up now, sorry for that.

Finally, I'm not sure if you realized this, but "realize" is probably not the best name for this method (or for any method, unless you are programming some epistemic system, IMHO).


In general your script looks good when considering the style and structure, but there are a few issues:

Strange name for check_ntp_time – This holds the time since the last time you did time.time(), and in reality is a temporary variable for when you need to check it the last time. It doesn't convey the real purpose of the variable.

I would rather do time_to_check_ntp = time.time() + 86400, and let the condition be time.time() < time_to_check_ntp or similar, which reads easier as to whether we've come to that time already, or not.
Consider replacing toilet with python stuff – One option could be to use pyfiglet, and another could be to use fonts of your own based on script suggestions from "Is there a python library that allows to easily print ascii-art text?" and "ASCII Art With Letters".
New function for setterm & clear – Introduce a new function where you can set it to on or off, which would remove some repetition of code.
Replace call to date to get date with datetime module – In general I would like for python script to do most of it using python stuff. Some of it like clear and setterm, or setting the date needs to be done in the shell on the terminal, so some can't be avoided, but stuff like getting the date I think should be done using internal tools, if possible.
Avoid the recursivity – Both display_clock() and get_ntp_time() calls each other causing a bad recursivity. If you change display_clock to have a while True: loop you could have a if time.time() > time_to_check_ntp: which then calls get_ntp_time() which possibly should be named correct_time_using_ntp(), and sets a new time_to_check_ntp.
Remove output before clearing the terminal – No point in outputting text straight ahead of a terminal clear. Nobody would be able to catch these message, unless something fails. I would remove it, or add a logger to keep track of the history of the script.

I'm not going to propose new code, as I don't have the ability to test it, but I hope my suggestions are meaningful and you see how to implement it. If not, please do comment.


Parallel scheduler for running actions at designated times

processJobs_ logic

You want to make sure that microsecondTimeout is never negative, since according to the documentation a negative timeout means to wait indefinitely.

To guard against negative timeouts, I would write processJobs_ to have the following logic:

loop:
  if queue is empty:
    call readChan for a new job and add to queue
    goto loop
  else:
    now <- getPosixTime
    if queue minimum <= now:
      fire off all jobs in the queue with a time <= now
      goto loop
    else:
      readResult <- timeoutReadChan ...
      put new job onto the queue
      goto loop

priority queues

You might be interested in this SO question and answers discussing the merits of the various Haskell priority queue packages:

https://stackoverflow.com/questions/6976559/comparison-of-priority-queue-implementations-in-haskell