Adding an item to a hierarchical data structure

Rubocop Report

Rubocop was able to correct a lot of style and layout offenses. 1 file inspected, 59 offenses detected, 53 offenses corrected.

The following offenses remain:

Metrics/LineLength: Line is too long. [112/80]
Metrics/AbcSize: Assignment Branch Condition size for update is too high. [24.1/15]
Style/MultipleComparison: Avoid comparing a variable with multiple items in a conditional, use Array#include? instead.
Metrics/LineLength: Line is too long. [99/80]
Style/NumericPredicate: Use range.index(target).zero? instead of range.index(target) == 0.
Metrics/LineLength: Line is too long. [85/80]

Fixing Offenses

LineLength and MultipleComparison offense:

# optimization for this:
id,range = old_state.to_a.select{ |entry| entry[1][0] == target || entry[1][1] == target }[0]

id, range = old_state.to_a.select do |entry|
  [entry[1][0], entry[1][1]].include?(target)[0]
end

LineLength + NumericPredicate offense:

state[id] =
   range.index(target) == 0 ? range.map{|n| n + 2} : [range[0], range[1] + 2]

  state[id] =
    if range.index(target).zero?
      range.map { |n| n + 2 }
    else
      [range[0], range[1] + 2]

After refactoring, we get a new issue that our method got too big. The complexity is still too high.

Metrics/AbcSize: Assignment Branch Condition size for update is too high. [25.06/15]
Metrics/MethodLength: Method has too many lines. [15/10]

We are adviced to break up this method. It's doing a bit too much. So we'll put the next part in another method.

   state[id] =
      if range.index(target).zero?
        range.map { |n| n + 2 }
      else
        [range[0], range[1] + 2]
      end
    2.times do |i|
      update(old_state, state, range[i] + 1) if range[i] != state[id][i]
    end

  def update_range(old_state, state, target, id, range)
    state[id] =
      if range.index(target).zero?
        range.map { |n| n + 2 }
      else
        [range[0], range[1] + 2]
      end
    2.times do |i|
      update(old_state, state, range[i] + 1) if range[i] != state[id][i]
    end
  end

There are no offenses remaining and complexity is within bounds.

Refactored Code

# frozen_string_literal: true

# Nested set for comments, for making it easy to load all comments in a
# list, sorted according to their nesting, and for nesting to be indicated.
class Database
  def initialize
    @set = {}
    @largest = -1
  end

  def fetch
    @set.to_a.sort { |el1, el2| el1[1][0] <=> el2[1][0] }
  end

  def add(parent: nil, id: -1)
    if parent

      @set.merge!(
        update(@set, insert(parent, id), @set[parent][1] + 1)
      )
    else
      @set[id] = [@largest + 1, @largest + 2]
    end
    @largest += 2
    @set
  end

   private

  def insert(parent_id, id)
    parent_range = @set[parent_id]
    {
      parent_id => [parent_range[0], parent_range[1] + 2],
      id => [parent_range[1], parent_range[1] + 1]
    }
  end

  # O(n) * 2^n
  def update(old_state, state, target)
    id, range = old_state.to_a.select do |entry|
      [entry[1][0], entry[1][1]].include?(target)[0]
    end
    update_range(old_state, state, target, id, range) if range && !state[id]
    state
  end

  def update_range(old_state, state, target, id, range)
    state[id] =
      if range.index(target).zero?
        range.map { |n| n + 2 }
      else
        [range[0], range[1] + 2]
      end
    2.times do |i|
      update(old_state, state, range[i] + 1) if range[i] != state[id][i]
    end
  end
 end


Setting image margins and location based on orientation

This doesn't save many lines of code, but I think it's more readable and maintainable:

boolean landscape = orientation.contains("landscape");

for(int imagenum = 0; imagenum <76; imagenum++){

    /* Missing code that assigns params and imageButton using imageNum? */

    int shortSideMargin = imagenum * xspaceforeachimage;
    int longSideMargin = 0;
    if (imagenum >= 39)  { //new row or column, shift back and over
        shortSideMargin -= 39 * xspaceforeachimage;
        longSideMargin = topMargin;
    }

    if (landscape) {
        params.height = imageheight;
        params.width = imagewidth;
        params.leftMargin = shortSideMargin;
        params.topMargin = longSideMargin;
        imageButton.setImageResource(R.drawable.imageback);
    } else {
        params.height = imagewidth;
        params.width = imageheight;
        params.leftMargin = longSideMargin;
        params.topMargin = shortSideMargin;
        imageButton.setImageResource(R.drawable.imagebacklaid);
    }
}


The fact that a function named breakBy also reverses the order of the data violates the Principle of Least Surprise.  In my opinion, it's a bug.

breakBy (Regex "^Name=").IsMatch can be thought of as an transformation to be applied to a list.  Therefore, to facilitate currying, the order of the parameters to breakBy should be reversed, so that the predicate comes before the data.


Scripts to get label name from ACQ container and modify ACQ label name

Indentation

This:

def conversion(acqList):

  prefix = ['MCS','FT', 'FS', 'GNo', 'Rs', 'WHw', 'Cy']
  newList = []

#to check if there is any of the items contains the prefix
  for e in acqList:

is (as a surprise to me) valid syntax, but that doesn't mean it's a good idea. The beginning of a comment, when that comment is the only thing on the line, should match the level of indentation of the block it's in. To do otherwise is pretty confusing.

You also seem to be using two-space indentation, when the standard is four.

If-parens

This:

  if(e.label.startswith(pf)):

should become

if e.label.startswith(pf):

Nested functions

There are sometimes good reasons for nested functions, but so far as I can see, this:

  def pairwise(iterable):
    return zip(*[iter(iterable)]*2)

doesn't have any of them. You're better off moving this function to global scope.

PEP8 spacing

By the PEP8 formatting standard, this:

  module.modify_acq(acquisition_id = acqID, label = newLabel )

would become

module.modify_acq(acquisition_id=acq_id, label=new_label)

Mutability

This:

  prefix = ['MCS','FT', 'FS', 'GNo', 'Rs', 'WHw', 'Cy']

never changes, so it should be made an immutable tuple:

  prefix = ('MCS','FT', 'FS', 'GNo', 'Rs', 'WHw', 'Cy')

Namespace pollution

These:

from datetime import *
from dateutil import *
from datetime import timedelta
from itertools import *
from math import *

have a few problems. First, your timedelta import is redundant, because you already import *.

Also, it's not a great idea to import everything from these modules. You're better off either

importing specific symbols from these modules as necessary, or
importing only the module itself (i.e. import math) and then using fully-qualified references.

Either of those will significantly clean up your namespace.


There definitely are not enough of these tools in the .NET world, but I've found that there are a lot in the WordPress/php world. My recommendation would be to review the code in those modules to determine if the logic is good enough. Certainly, "good enough" depends on your needs though.

Regarding the filtering of specific file types, perhaps https://stackoverflow.com/questions/331398/how-to-have-http-module-on-fire-events-only-for-specific-page-types will help?


One-way flight trip implementation in Python

You should not use global variables when not necessary. You can just directly pass depart and arriv to getTrip.

You should strive to have readable variable names. Just use arrival and departure.

Python has an official style-guide, PEP8, which recommends using lower_case_with_underscore for variables and functions.

You can use map to cast both sources and destinations to sets directly. You can also use set subtraction to get the difference value only in one of them.

The dict constructor can directly take an iterable of pairs to build a dictionary.

You can make get_trip a generator, which simplifies the logic slightly.

I would add a if __name__ == "__main__": guard to allow importing stuff from this module without running the whole code.

import random

def get_departure_arrival(flights):
    """
    Find departure and arrival airport from chain of flights.

    Effectively the opposite of the itertools recipe pairwise:

    >>> get_departure_arrival([(s0, s1), (s1, s2), (s2, s3)])
    (s0, s3)

    Pairs do not have to be in order:

    >>> get_departure_arrival([(s0, s1), (s2, s3), (s1, s2)])
    (s0, s3)
    """
    sources, destinations = map(set, zip(*flights))

    depart = (sources - destinations).pop()
    arriv = (destinations - sources).pop()

    return depart, arriv

def get_trip(flights, depart, arriv):
    """
    Reconstruct a flight trip from pairs of departure and
    arrival airports and the first and last airport of the trip.
    """
    flight_dict = dict(flights)
    while depart != arriv:
        yield depart
        depart = flight_dict[depart]

if __name__ == "__main__":
    flights = [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'),
               ('E', 'F'), ('F', 'G'), ('G', 'H'), ('H', 'I')]
    random.shuffle(flights)

    depart, arriv = get_departure_arrival(flights)
    print list(get_trip(flights, depart, arriv))


Faster copying of images to change their PixelFormat

To remove the alpha channel, you could use Bitmap.Clone :

public static Bitmap RemoveAlphaChannel(Bitmap bitmap) {
    var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
    return bitmap.Clone(rect, PixelFormat.Format24bppRgb);
}

Another way is to lock the bits without the alpha channel and then copy the memory to a new bitmap:

public static Bitmap RemoveAlphaChannel(Bitmap bitmap) {
    Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
    Bitmap bitmapDest = (Bitmap)new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);
    BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
    BitmapData dataDest = bitmapDest.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
    NativeMethods.CopyMemory(dataDest.Scan0, data.Scan0, (uint)data.Stride * (uint)data.Height);
    bitmap.UnlockBits(data);
    bitmapDest.UnlockBits(dataDest);
    return bitmapDest;
}

static class NativeMethods {

    const string KERNEL32 = "Kernel32.dll";

    [DllImport(KERNEL32)]
    public extern static void CopyMemory(IntPtr dest, IntPtr src, uint length);

}


Finding the prime factors of a positive number

1) The reasons for 2 loops while (n % 2 == 0) and while (i <= n) is to optimize division by 2 and allow the next prime candidate to be found with += 2.

As printing is a sink-hole of time, these small savings could be ignored and code changed to one loop.

int i = 2;
while (i <= n) {
   while(n % i == 0) {
      ...
      printf("%d", i);
      separated = 1;
      n = n / i;
   }
   i += i==2 ? 1 : 2;
}

2) Negative numbers are a problem and not well supported here, nor do they need to be.  Recommend unsigned than int.

3) As an alternative to a flag and repeated test code for the "*", perhaps

char *separator = "";
...
while (...) {
   printf("%s%d", separator, 2);
   separator = "*";
   ...
}

4) Code fails for the following.  OP did say "prime factors of a positive number", so 0 and negative numbers are excusable to some degree.

  find_factors(INT_MAX);  // infinite loop
  find_factors(1);        // no output
  find_factors(0);        // infinite loop
  find_factors(negative)  // no output

5) Initialize at the same time as declaration.

// int i;
// int separated;
// i = 3;
// separated = 0;
int i = 3;
int separated = 0;

6) Consider bool for boolean variables

#include <stdbool.h>
// int separated = 0;
bool separated = false;

7) Wavy formatting

    if (separated)
        printf("*");
   printf("%d", 2);
   separated = 1;
    n = n / 2;

8) Careful passing a string to printf() as a format string as it might someday contain %.

// printf("*");
fputs("*", stdout);
// or
fputc('*', stdout);
//
putchar('*');

// OP did say  "write, printf, atoi.", so could use the following, which is a bit pedantic.
printf("%s", "*");

9) Efficiency.  For large values of n, code does n/2 loops.  Better to terminate at about the sqrt(n).  At n % i time, also calculate qu = n / i.  This can often be had for free, depending on the processor.  Once i>qu, code is done.


In calculate why not just return directly from the different cases? This would be simpler than setting a temporary value, breaking from the switch and returning that value.

switch (moperator)
{
case '+':
    return num1 + num2;
case '-':
    return num1 - num2;
case '*':
    return num1 * num2;
case '/':
    return num1 / num2;
case '^':
    return pow(num1, num2);
default:
    printf("Invalid Operator\n");
    exit(-1);
}


program options from command line initialize

I tried boost::program_options but simply didn't like it.

boost::program_options has the feature that certain options are additive or hidden - which is why their usage requires so much extra work (you have to specify each option you use and state how they are processed). If you are fine without these features, you can work with config files - *.ini format - and simply read and store all option that the file has, no need for the whole mess in the main. It is not hard to implement a config file reader and Windows has built in functions for reading arguments from a .ini file.

Also this way you can supply input parameters via an .ini file instead of command line, which is much more convenient if you have more than 5 parameters and I tend to have dozens in tests.

In my case, I implemented a class ConfigFile that basically wraps a std::map<string,string> whose keys are in format SECTION/NAME; with added functions for getting/setting int/double/string values as well as functionality for reading a whole ini file.

In case you want to read a command line via the ConfigFile class: you can reinterpret cmd arguments and store them inside the ConfigFile class. string-based options simply store as is or optionally add a prefix-section. To support index based options you ought to provide a vector of strings to that interprets them.

I don't know of any open-source library that implements something like this, though I didn't check for any. But it is easy to implement on your own. I might publish my implementation together with a couple of other utility features as an open-source but not now. So...

Example of CMD parsing:

class CConfig
{
public:
            // sKeys is used to store index based inputs of CMD
    void ParseCMD(  int                         argc,
            const   char**                      argv,
                    std::vector<std::string>    sKeys = {});

   std::string  GetString(std::string key,  std::string  defaultValue);
   double       GetDouble(std::string key,  double       defaultValue);
   int          GetInt(   std::string key,  int          defaultValue);

   void         SetString(std::string key,  std::string  value);
   void         SetDouble(std::string key,  double       value);
   void         SetInt(   std::string key,  int          value);

private:
    std::mutex                          m_mutex;
    std::map<std::string, std::string>  m_map;
};

void CConfig::ParseCMD( int                         argc,
                const   char**                      argv,
                        std::vector<std::string>    sKeys)
    {
        std::lock_guard<std::mutex> g(m_mutex);
        size_t index = 0;
        for (int i = 1; i < argc; i++)
        {
            if (argv[i][0] != '-')
            {
                if (sKeys.size() <= index)
                {
                    std::cout "\n[warning]: unassigned input parameters; total number of index-based input parameters is: " << sKeys.size();
                    continue;
                }

                m_map[sKeys[index]] = argv[i][0];
                continue;
            }

            if (i + 1 < argc && argv[i + 1][0] != '-')
            {
                m_map[argv[i]+1] = argv[i + 1];
                i++;
            }
            else
            {
                // simply defines this key with empty value
                m_map[argv[i]+1] = {};
            }
        }

        if (sKeys.size() > index)
        {
            // or add option for making it into an error and not just a warning print
            std::cout << "\n[warning]: not all index-based values were assigned");
        }
    }

// in main simply write:
   int main(int argc, const char* argv[])
   {
         CConfig config;
         config.ParseCMD(argc, argv, {/*list of strings for identification*/});
         ...
   }


fib works by recursively calling the function named fib:

def fib(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

In your "execution 1" the function named fib is the memoized version of the function, because you have assigned it like this:

fib = memorize(fib)

But (assuming that you haven't run "execution 1" yet), in your "execution 2" the function named fib is the original function (not the memoized version of the function, which you have assigned to memo_fib), so when you call memo_fib it calls the original fib and when that recurses it calls the original fib, bypassing the memoization.


Designing a text based guessing game with a branching decision tree

Let me start with a few quick things to enhance readability and then give some pointers how one could make this more maintainable, if one wanted to.

Magic Numbers

One thing that makes your code hard to follow is that you use magic numbers instead of named constants at multiple places. You already use vbYesNo for the MsgBox options most of the time. I wonder why you use 3 instead of vbYesNoCancel in the first message box. Moreover, the code would be more intuitive, if you replaced 6 by vbYes and 7 by vbNo. Whenever you want to use an explicit number in code, ask yourself whether there is a constant for that already and, if not, define a constant of your own and give it a semantic name.

Indentation

As @Greedo has pointed out in the comments, the strange indentation might be an artifact of how you have posted the code. However, as is, the indentation makes the code unreadable. ElseIfs should line up with the corresponding If statements and their content should be indented one level deeper. Then, you know which level of the tree you are in while reading the code.

Reuse of Variables

It is generally confusing in code, if you reuse a local variable. There is no benefit from reusing the variable a here. Still, the reader of the code has to know that it has been reused for an entirely different question in the second part of the procedure.

Naming

Code should always strive to be self-documenting. The most important part in this is good naming of variables and procedures. They should always have a name indicating what they are/do; variables, properties and functions should be nouns and procedures should be verbs. Here, expressiveness trumps shortness: there is no problem with having a long name if you cannot express the meaning in a short name. If this leads to a very long name, it might be a smell that you should split something up.
In you specific case, all your answers are single letter variables without any meaning, which is not ideal. E.g. a better name for e, or rather e = vbYes, would be nameStartsWithK.
Note that applying semantic naming would have avoided the reuse of the variable a automatically since there is no sensible common name for the two uses.

Declaring Variables

Do yourself a favor and always declare you local variables, e.g. using Dim a As Long right before using a the first time. This documents the variables type and subsequent assignment with an incompatible type will result in an error instead of unexpected behaviour. (VBA does a lot of helpful implicit conversions, though.)

Option Explicit

Please, always use Option Explicit on top of your component. You can let the editor add it automatically for new components by ticking Require Variable Declaration under Tools->Options->Editor. This will force you to declare all your variables. A very helpful side-effect is that it will catch typos in uses of your variables. E.g. is you try to reference nameStartsWithK but type nameStartWithK, it will complain that nameStartWithK is not declared. Without Option Explicit, you get a new variable of type Variant instead, which is really not what you want here.

Use of End

The End statement is something that usually should never be used. In general, it is unexpected behaviour that a called procedure terminates the entire program. Instead, the procedure should probably use Exit Sub in order to return execution to its caller.

Use of Single-Line If Statements

Single-line If statements like If b < 7 Then d = MsgBox("do you live in logan?", vbYesNo) are generlly a bit confusing because there is no End If one starts to expect out of habit. However, this is amplified tremendously without proper indentation since it is not immediate clear for the reader what the next ElseIf refers to.

Select Case Statement

For your first If block, a Select Case statement would probably be semantically more appropriate.

Select a
    Case vbYes
        MsgBox "Let the games begin!"
    Case vbNo
        MsgBox "Okay. Press ctrl K to start over."
    Case Else
        MsgBox "Sad. Come back later. Press ctrl K to start."
End Select

Note that I have removed the option 1 in the first case, which is vbOKCancel. More on this, next.

User Experience

Your first query to the user whether he wants to play a game has two somewhat strange features.

When you confirm that the game starts, you do this in a message box with option vbOKCancel but never react to the result. As the user, I would expect that clicking the Cancel will abort the game. If the effect of Cancel is the same as OK, do not display a Cancel button.
It is usually percieved as rather annoying, if a dialog pops up in response to cancelling. This is exactly what happens in your first query to the user.

Using Indirection to Improve Maintainability

When speaking about maintainability and flexibility one has to ask what you might want to change in the future and what is a hindering proper automated testing. In the case of this simple game, the latter is probably not a real concern, but for parts of larger applications, it is.

The main point of possible change I see here, is the presentation to the user. Not entirely by coincidence, this is also what would hinder any automated testing since blocking dialogs are a pain for that.

This is a bit more advanced, but what you could do to abstract away the use of the message box is to add a new class YesNoUserInteraction with a single function

Public Function UserAgrees(ByVal questionText As String) As Boolean
    UserAgrees = (MsgBox(questionText , vbYesNo) = vbYes)
End Function

The you new it up and save it in a variable Dim userInteraction As YesNoUserInteraction in your code Set userInteraction = New YesNoUserInteraction and use that instead of the message box.

Going one step further, you can split out the part newing up the object and pass it as a parameter to the procedure.

Public Sub Decision_tree()
    Dim userInteraction As YesNoUserInteraction
    Set userInteraction = New YesNoUserInteraction
    DecisionTreeImpl userInteraction
End Sub

Private Sub DecisionTreeImpl(ByVal userInteraction As YesNoUserInteraction)
    ...
End Sub

This has the benefit that another class could implement YesNoUserInteraction and that could be provided as the user interaction to the implementation instead. This way, you can change the presentation entirely, e.g. using a custom user form, or automate the answers for unit testing.

The way it is, the intent to allow other implementations is not really clear though. We can go one step further and introduce a dedicated interface class IYesNoUserInteraction for the interaction.

Public Function UserAgrees(ByVal questionText As String) As Boolean
End Function

Then, we can turn YesNorUserInteraction into YesNoMsgBoxInteraction and implement the interface.

Implements IYesNoUserInteraction

Private Function IYesNoUserInteraction_UserAgrees(ByVal questionText As String) As Boolean
    UserAgrees = (MsgBox(questionText , vbYesNo) = vbYes)
End Function

To get the right names and signatures for the members to implement, you can use the two drop downs at the top of the code pane.

Finally, we can use it in the setup code.

Public Sub Decision_tree()
    Dim userInteraction As IYesNoUserInteraction
    Set userInteraction = New YesNoMsgBoxInteraction
    DecisionTreeImpl userInteraction
End Sub

Private Sub DecisionTreeImpl(ByVal userInteraction As IYesNoUserInteraction)
    ...
End Sub

This makes it clear that we can provide anything to the procedure that honors the contract to take a question and return an answer in the form of a Boolean with True = Yes.

Obviously, this does not deal with the first question to the user, since you want to allow cancellation. You could do that in a similar way as presented here, but not with a simple Boolean.

Separation of Responsibilities

The last observation above points to a further thing that could be improved in your code. Currently, it violates the so-called Single Responsibility Principle. In essence, it states that any unit of computation, e.g. a procedure, should be responsible for one and only one thing. Yours actually is for two: asking the user whether he wants to play at all and playing the game.

What you could do instead is to extract a function and a procedure. The function could ask whether the user wants to play and return True if he wants to play and False, otherwise. Then, the procedure actually playing the game is only called if the user wanted to play.

Since the procedure is not large, this does not seem to be much of a problem that it might change for entirely different reasons: changing how a user is asked and playing the game differently. However, if you ever want to write something more complicated, you should get into the habit of splitting things up into small units with a defined purpose. That makes reading the code and figuring out what it actually does later on much easier.


Check if a given number N is a power of k

I'd follow Ludisposed's answer.

Except, there's a simple way to do this. Use logarithms.
Since the equation is \$N = k^a\$ you can change it to \$a = \log_k N\$.
And so if \$a\$ is an integer, then you know that \$N\$ is a power of \$k\$.

import math

def check_power(N, k):
    return math.log(N, k).is_integer()

Since the above can error, and if there's an error it's definately not a power, then you can use:

def check_power(N, k):
    try:
        return math.log(N, k).is_integer()
    except Exception:
        return False

This has the some problems with floating point precision, so your can round the number to the closest integer, as you want to know if the \$a\$ is an integer. And so you can sub it back into the original equation to ensure that the numbers are right.

def check_power(N, k):
    return N == k**round(math.log(N, k))

Or if you're on Python 2:

def check_power(N, k):
    return N == k**int(round(math.log(N, k)))

This has a problem with some inputs, such as when \$N\$ and \$k\$ are \$0\$ or \$1\$. And so we can handle these special cases.

def check_power(N, k):
    if N == k:
        return True
    return N == k**round(math.log(N, k))

And so merging all the above, we can use the following:

def check_power(N, k):
    if N == k:
        return True
    try:
        return N == k**int(round(math.log(N, k)))
    except Exception:
        return False


SQL Negation: Find X when X does not do Y

I would personally use the JOIN, because the query here is fairly simple. You are just matching two tables.
A subselect is handy for more complex lookups though.

But each DBMS has its own way of parsing and optimizing queries.
You should run the execution plan on each query and compare results.

Like with Mysql, use the EXPLAIN command to determine which one would perform better. To get representative results you should fill up the tables with sample data. Add a least a few thousand records.
Also add indexes where appropriate. It could be interesting to run the tests with and without indexes.

The presence (or lack) of indexes will affect the query optimizer. Sometimes you have to provide hints, if the query optimizer does not choose the 'best' index.

It should be noted that performance is related to good DB design. These table examples have no primary key, no index etc.


A few thoughts:

1. Don't use C-style casts

Here

 data.push_back((unsigned char)(rand(mt) * 256));
             // ^^^^^^^^^^^^^^^

and here

 unsigned int count = (unsigned int)(rand(mt) * (data.size() / 2) + 1);
                   // ^^^^^^^^^^^^^^

you use (unchecked) C-style cast operations. I C++ all casts should be either checked, or explicitly a reinterpret_cast (which is merely the same, but clearly shows intention).

In your cases a static_cast<unsigned char> and a static_cast<unsigned int> seems to be more appropriate for me.

2. If you're dealing with plain integer numbers prefer using std::uniform_int_distribution

You are using std::uniform_real_distribution<double>

std::uniform_real_distribution<double> rand(0.0, std::nextafter(1.0, DBL_MAX));

to finally generate integer types (done through implicit conversion).

It would seem more appropriate to use

 std::uniform_int_distribution<unsigned int> rand(0, std::nextafter(1, UINT_MAX) /* intentional ?? */ );

or even better simply

std::uniform_int_distribution<unsigned int> rand();

and

data.push_back(static_cast<unsigned char>
    (rand(mt) % std::numeric_limits<unsigned char>::max());
// ...
unsigned int count = rand(mt) * (data.size() / 2) + 1;

Floating point conversions and calculations may cause unnecessary overhead in the emitted assembly instructions.

3. Prefer std::numeric_limits over the C-style macro definitions

In C++ you should prefer using std::numeric_limits<double>::max() over the DBL_MAX C-style macro.

At least with GCC I always get compiler errors using these constants (even though <cstdint> was included).

4. Modularize your code to be resuable

As you tagged this with unit-testing I would consider to create a little helper library API that can be used with the unit tests, without calling a separate program.

Instead of the int main(int argc, char* argv[]) entry point, refactor your code (including the stuff from Create 'worst case test' data for compression test) to a helper function API, that can be used easily with the various unit tests:

 namespace Test7ZipData {
     int create_worst_compressible_data(const char* filename);
     int create_easily_compressible_data(const char* filename);
     // int create_average_compressible_data(const char* filename); ????
 }

Compile these into a library, that will be linked with you unit tests.

5. Prefer using raw string literals instead of escaping special characters

Instead of

const char* filename = "c:\\_Test\\easy.dat";

you can provide a raw string literal

const char* filename = R"(c:\_Test\easy.dat)";

That enhances readability of the literal text.


Use Dictionaries

We are basically just mapping from one letter to the next. The most naturally way to do that is to actually use a map:

to_entean = {...}

The easiest way to build up the dictionary is to use zip():

to_entean = {eng: ent
    for eng, ent in zip(string.ascii_uppercase, 'AZYXEWVTISRLPNOMQKJHUGFDCB')
    }

Now to_entean['A'] == 'A' and to_entean['B'] == 'Z', etc. This simplifies your get_letter function to:

def get_letter(letter):
    ent = to_entean.get(letter.upper(), letter)
    if not letter.isupper():
        ent = ent.lower()
    return ent

String Concatentation

String concatenation is slow. Also it reads terribly. What we want to do is call get_letter for every letter in word and then join them all together. That's what join() is for:

ent_word = ''.join(get_letter(letter) for letter in word)

Why split?

Since get_letter() handles spaces already, we don't have to split into words. Just transform the whole thing:

print(''.join(get_letter(letter) for letter in usr_txt))

Which, if you prefer, can also be spelled:

print(''.join(map(get_letter, usr_txt)))

Typo

You have a typo here:

usr_txt = input("Enter Englsih text:")
                       ^^^^^^^


While loops in SCSS to produce circles for an animation

I ended up rewriting it like this - much more compact and clean. If there are further ways to optimize this, I'm open to suggestions!

// generate circles from left to right

$i: 1; $s: 38; $t: -19; $l: -89.3; $z: 2;

@while $i <= 11 {
    &:nth-child(#{$i}) {
        @include sqsize($s);
        margin-top: $t+vh;
        margin-left: $l+vh;
        z-index: $z;
    }
    $i: $i + 1;
    $z: $z + 1;
    $b: $i <= 6;
    $l: if($b, $l + 15, $l + 13);
        // <= 6 - circles are coming from the left
        // > 6 - circles are going to the right
    $s: if($b, $s - 2, $s + 2);
        // same logic as above - decrease size towards middle
        // and increase size after passing the middle
    $t: if($b, $t + 1, $t - 1);
        // —〃—
}


Optimization ideas

Prevent wasteful data conversions

Don't convert from a string to an array. You could do better by simply storing your state as an array instead.

I suppose you chose to use a string since they are easily copied, but arrays are also easily copied with:

copy = old.slice(0);

You could do even better by keeping the state as a string; albeit with some modifications to the model. My only concern is the -1 since it's two characters. Using X, O, and - is a reasonable option, and it keeps the indices of the characters in the correct place.

"O-OXXX---" // a win for X

You'll also have some trouble with the high order functions since strings don't have them. Speaking of which...

High order functions come with a cost

While forEach, map, and some are awesome functions (and one of my favorite parts of JavaScript), they come with quite a bit of overhead compared to their for loop equivalents. The issue comes with the need to execute a callback function over and over as opposed to just running inline code.

Since your program is computation heavy,  you probably want speed over elegance. Converting all the high order functions to for loops should help considerably.

Certain states are duplicates of others

You could use a JavaScript object to keep track of the past states, so you don't have to build redundant tree branches.

Something like:

stateMap = {};
// ...
state = makeMove(possibleMove);

if (stateMap[state] !== undefined) {
  // check state ...
  stateMap[state] = node;
  // recurse next possible moves ...
}
else {
  node.child = stateMap[state];
}

This way if a state ever comes up again, it will be defined in stateMap, and you can reuse the node. However, the parent pointers may become a bit muddled, so you might want to keep a list of parent nodes, or preform a deep copy on the child's branch.

Other optimization ideas

Don't check every way to win each time. Each move only involves a subset of the possible ways.
Certain states are merely rotations of others, but that might be hard to utilize.

Review

Modularize

Your code is global and scattered. You could store it in a function to make it more portable and scalable:

var ticTacToeTree = (function () {
    function Node(state, toPlay) {
        this.toPlay = toPlay;
        this.bestValue = null;
        this.state = state;
        this.parents = [];
        this.children = [];
    };

    var head = new Node("---------", 'X');

    // The rest of your code

    return {
        head: head
    };
})();

Reusable code

checkIfWon could be used to check both players:

function checkWinner(state) {
  for (var i = 0; i < winStates.length; i++) {
    if ("-" !==
         state[winStates[i][0]] ===
         state[winStates[i][1]] ===
         state[winStates[i][2]]) {
      return state[winStates[i][[0]];
    }
  }
  return "-"; // no one has won
}

Which prevents redundant calls:

function populateTree(currentNode, toPlay) {
  var winner = checkWinner(currentNode.state);

  if (winner === "-" && checkDraw(currentNode.state)) {
    return currentNode.bestValue = 0;
  }
  else if(winner === "X") {
    return currentNode.bestValue = 1;
  }
  else if(winner === "O") {
    return currentNode.bestValue = 1;
  }

  // ...
}

Don't worry about getting a random move; you end up computing them all anyways:

for (var i = 0; i < moves.length; i++) {
  move = moves[i];

  nextState = state.slice(0, move).concat(state.slice(move));

  if (stateMap[nextState] !== undefined) {
    var node = new Node(state, nextTurn(toPlay);
    node.parrents.push(currentNode);
    currentNode.children.push(node);
    populateTree(node, node.toPlay);
  }
  else {
    currentNode.children.push(stateMap[nextState]);
  }
}


1. Review

There's no docstring. What does the function do? What does it return?
The result includes the spaces:

>>> tokenize('1 + 2')
['1', ' ', '+', ' ', '2']

but it seems unlikely that the spaces are significant. One of the useful things a tokenizer can do is to discard whitespace.
The tokens are collected into a list and returned. This is inflexible because you have to wait for them all to be collected before you can start processing them. But parsing tends to use one token at a time, so it is often more convenient for the tokenizer to generate the tokens one at a time using the yield instruction.
There's no error-detection:

>>> tokenize('3E$£ω∞あ')
['3', 'E', '$', '£', 'ω', '∞', 'あ']

One of the things a tokenizer ought to do is to detect and report invalid tokens. Surely it's not the case that every string is a valid input to your program?
The tokenizer does not handle floating-point numbers:

>>> tokenize('3.14159')
['3', '.', '14159']

or engineering notation:

>>> tokenize('3e-08')
['3', 'e', '-', '08']

You write in the post that they "can be reconstructed later on" but it would be easier to have the tokenizer do it.
The tokenizer does not return anything other than the tokens themselves. Usually one of the jobs of a tokenizer is to categorize tokens (numbers, names, operators etc.) and to turn string representations of numbers into the number themselves.

2. Revised code

In Python it's often convenient to implement tokenization using a regular expression and the finditer method. In this case we could write:

from enum import Enum
import re

_TOKEN_RE = re.compile(r'''
    \s*(?:              # Optional whitespace, followed by one of:
    ([()^+*/-])         # Punctuation or operator
    |([a-z]+)           # Variable or function name
    |((?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:e[+-]?[0-9]+)?) # Number
    |(\S))              # Anything else is an error
''', re.VERBOSE | re.IGNORECASE)

class Token(Enum):
    """Enumeration of token types."""
    PUNCT = 0           # Punctuation or operator
    NAME = 1            # Variable or function name
    NUMBER = 2          # Number

def tokenize(s):
    """Generate tokens from the string s as pairs (type, token) where type
    is from the Token enumeration and token is a float (if type is NUMBER)
    or a string (otherwise).

    """
    for match in _TOKEN_RE.finditer(s):
        punct, name, number, error = match.groups()
        if punct:
            yield Token.PUNCT, punct
        elif name:
            yield Token.NAME, name
        elif number:
            yield Token.NUMBER, float(number)
        else:
            raise SyntaxError("Expected a token but found {!r}".format(error))

This deals with all my points in §1 above:

There's a docstring.
Spaces are discarded.
Tokens are generated one at a time.
Errors are detected and reported:

>>> list(tokenize('3E$£ω∞あ'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr186024.py", line 49, in tokenize
    raise SyntaxError("Expected a token but found {!r}".format(error))
SyntaxError: Expected a token but found '$'

The tokenizer handles floating-point numbers and engineering notation:

>>> list(tokenize('1.2 3e8 .2e-7'))
[(<Token.NUMBER: 2>, 1.2), (<Token.NUMBER: 2>, 300000000.0), (<Token.NUMBER: 2>, 2e-08)]

The tokenizer categorizes the token and converts numbers to floats.


What are the drawbacks of DRY input validation configuration?

Well, since you didn't post your lib code, I'm assuming you're looking for an API-review. I hope you're not going to take this the wrong way, but I wouldn't like to use your validator class at all.
If I were you, I'd provide the users with an API that uses constants for the supported validation types, and -like I said in my comment- DRY is all well and good, but DOYOC (Do not Obfuscate Your Own Code) is more important, still.

I suggest you bash out an API that would allow me to do this:

$validator = new Validator();//basic
//or
$validator = new Validator(
    array(
        Validator::DEFAULT_FAIL => VALIDATOR::FAIL_BREAK,
        Validator::DEFAULT_VALUE => VALIDATOR::VALUE_REQUIRED,
    )
);

So pass an array with the default behaviour to the constuctor, and in case no array is passed: provide a setDefaults method + force the constructor to the strictest settings possible by default. Then the user can specify only those settings he wants to loosen up a little. But in general, when it comes to validation: the stricter the better.

Then, add methods to add what you call a selector, I'd call it an entity, which the user can then use to add a validation rule:

$validator->addEntity(
    $name,//name of entity
    Validator::TYPE_EMAIL,//validation type
    array(
        'value' => Validator::VALUE_OPTIONAL //override defaults here
    )
);

This not only makes the resulting code easier to read/maintain, but also makes it more reusable! This, too is DRY! in your case, the user will need to create a new array if he/she wants to validate things differently. I only have to do this:

$emailOptions = array('value'=>Validator::VALUE_OPTIONAL);
if ($config->requireEmail) $emailOptions['value'] = Validator::VALUE_REQUIRED;

And the rest of the code can remain as-is.
While testing, I can quickly comment out an addEntity call, or change one of them without having to go over that huge array again.

In light of this (changing rules on-the-fly): provide methods like alterRule or removeRule, too

If, in time, you get to writing form-building classes, you'll probably want your API to be able to deal with instances of a given class, and distill from it the rules required. One way to prepare your code to do so is by adding type-hints for Traversable objects.
If your API grows, it might also be worth wile considering writing Argument classes, that need to be passed to your API

I'm not going to write a full example of how I'd structure a validator class, as I've only briefly looked at your code, and I'm tired. Just thought I'd expand a little on my comment.


Finding the distance between two points in C++

I think @john has made some excellent comments. I agree with them, but you've already gotten them, so I'll try not to repeat the same.

Global variables

Variables defined outside any function, like these:

int ch;
double x;
double y;
double a;
double b;
double answer;

...are generally called "global", because anything, anywhere in the world program can depend on them and/or modify them.

When some parts of the code modify them and other parts depend on them, it can become difficult to figure out how the code will act under any given circumstances, how to get it to to exactly what you really want, and so on.

Usually, you want to restrict each variable to (approximately) the smallest scope necessary for it to do its job. None of these variables is used outside of the main function, so we can define them there to assure that only the code in main can use them:

int main(){
    double x;
    double y;
    double a;
    double b;
    double answer;

        cout << "Enter the points for the coordinates";
        cout << endl;
        cout << "Point x for first coordinates: ";
        cin >> x;
        cout << endl;
        cout << endl;
        cout << "Point y for first coordinate: ";
        cin >> y;
        cout << endl;
        cout << endl;
        cout << "Point x for the second coordinate: ";
        cin >> a;
        cout << endl;
        cout << endl;
        cout << "Point y for the second coordinate: ";
        cin >> b;
        cout << endl;
        cout << endl;
        answer = distanceBetweenTwoPoints(x, y, a, b);
        cout << "The answer is " << answer;
}

Avoid std::endl

Although it's used in a lot of tutorials and such, std::endl is almost never what anybody really wants. Although it won't make any real difference as you've used it here, using std::endl when (for example) you're writing lots of data to a file can easily make your program run 10x slower than it really needs to1.

Use functions

You may not have learned (much) about functions yet, but they can make your life much easier, largely by reducing repetition. For example, quite a bit of the code in main consists of a number of repetitions of the same basic sequence:

Ask user for input
Read the input

You can make your life considerably simpler by moving repeated actions like this into functions:

double get_value(char const *prompt) {
    double value;

    std::cout << "\n" << prompt;
    std::cin >> value;
    return value;
}

Then the code in main to get values can be shortened a bit, to something like this:

cout << "Enter the points for the coordinates\n";
x = get_value("Point x for first coordinate: ");
y = get_value("Point y for first coordinate: ");
a = get_value("Point x for second coordinate: ");
b = get_value("Point y for second coordinate: ");

This not only reduces the amount of typing involved, but when you make a mistake (and we all do) it improves the chance that you've only made it in one place, so when you fix it, it'll be fixed in general.

Mathematics

You should usually think twice about computing a hypotenuse at all. In a lot of cases (e.g., comparing one distance to another) you can add the squares of the X/Y coordinates, but not take the square root of the result. For a lot of common cases like "find which point is closest to the one I clicked", the square of the distance works just as well as the actual distance, but is much faster to compute (sqrt is often relatively slow).

If you do need to compute a hypotenuse, consider using std::hypot instead of re-implementing it yourself. In the worst case, this will just be a thoroughly tested and debugged version of the code you'd write on your own. In a better case, it might use a different algorithm to compute the result. For example, you might have a case where both your \$\Delta x\$ and \$\Delta y\$ are within range and the final answer would be within range, but \$\Delta x^2 + \Delta y^2\$ is out of range. In this case, the simplistic approach will overflow, but some others won't. Depending on your hardware and/or required precision, alternatives may also be faster.

Avoid using namespace std;

This using directive brings a huge number of names into scope, which can lead to all sorts of problems from colliding with names you try to define. Almost nobody really knows all the names it defines, so it's often hard to avoid them.

It's (by far) easier in the long term to bite the bullet and put up with typing things like std::cout when you need to use them.

Note that this warning applies primarily (maybe even exclusively) to the std namespace. Something like using namespace std::chrono; is often perfectly fine.

If you are going to have a using namespace std;, you usually want to restrict it to the scope of a single function:

int main() {
     using namespace std;

}

This can still lead to the same basic problems, but at least you've restricted the scope, so when a problem arises, cleaning up the mess is less work.

1. In case you care about the reason: making an operating system call to write data to a stream usually has a fair amount of overhead, so each call takes a fair amount of time, even to write a small amount of data. To avoid this, the code in the library stores data in a buffer. It only calls the OS to write the data to the external file once in a while, when the buffer gets full.

std::endl writes a new-line to the output stream (which you want) and it flushes the stream's buffer--forces an immediate OS call to write the data in the buffer, even if it's not full (which you almost never want). For interactive input like this, it won't actually hurt much, but as a simple rule of thumb, I'd just avoid using it at all. In the (rare) cases that you really do want to flush a stream's buffer, use std::flush to do it.


However, there is a lot of talk about what implementations are secure and not secure. How does my method measure up? Is it secure? Are there more secure methods in PHP for hashing tokens and matching with tokens later on?

Since you're specifically asking about security, I think reviewing your security instead of your code is a valid answer in this case.
The rule in Security-land is "don't do it yourself if others have done it better". It's basically a re-wording of "Use the right tool for the job" and "It isn't encryption until you've taken the time to fully understand the concepts behind the encryption code".
If you want to do hashing right, make sure you read this  answer on Security.SE.
Basically, if you want to do it secure, use bcrypt. Since PHP 5.5 can be called with password_hash.
PHP itself also recommends bcrypt. Their example usage states something like that in the comments:
<?php
/**
* We just want to hash our password using the current DEFAULT algorithm.
* This is presently BCRYPT, and will produce a 60 character result.
 *
 * Beware that DEFAULT may change over time, so you would want to prepare
 * By allowing your storage to expand past 60 characters (255 would be good)
 */
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."\n";
?>

If you don't want to be surprised by a changed default value, change PASSWORD_DEFAULT to PASSWORD_BCRYPT.
Note they have more examples with varying complexity on that site, but this should convey the basics. It's perfectly possible to hand a whole sleeve of options to the function.
As a last note, you want to handle tokens. Do not store tokens in your database, only store hashed tokens. See also Part II of this answer.
Update:
In the above I assume you're using PHP 5.5 or higher. See this answer for implementations when using a lower version.


Rust program, which reads, processes, and writes a file

This is my first post here, but I thought I might give this one a shot.

Your code could be made more user friendly by providing custom error messages.

When you get the filename from the command line arguments, you assume that the user will provide at least one command line argument. You could provide a helpful error message if they don't.
If opening a file fails for some reason (probably that the file doesn't exist at all), you could provide a custom print-out.
My example uses expect() as an example, but in code where user-friendliness is actually a goal, you would probably want to use eprintln!("error message here") and std::process::exit(1) to quit the program. That way, you don't get rust's extra panic messages which a user shouldn't have to understand.

You don't actually have to allocate a Vec to read the command line arguments, you can use the .nth method on the Args iterator.
You don't need the trim() call, because the lines() iterator already removes the newlines.
If you are looking to make the code cleaner, you could open the file for reading with File::open, and open it for writing with File::create.
I don't know how to significantly improve the performance of your code.

The biggest thing that I notice is that when you write the processed sequence of numbers to the file, you call write! on every line. This means that you talk to the OS every time you write a number. This could be made faster by using BufWriter, which would let you talk to the file only once. Alternatively, you could construct your output string while you are reading the file.

use std::env;
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::io::Write;

fn main() {
    let file_path = &env::args().nth(1).expect("must provide an input file");

    let file = File::open(file_path).expect("failed to open input file");

    let doubled_contents: String = BufReader::new(file).lines()
        .map(|line| {
            let number = line.unwrap().parse::<i32>().expect("failed to parse file");
            format!("{}\n", number*2)
        })
        .collect();

    let mut output_file = File::create(file_path).expect("failed to open output file");
    write!(output_file, "{}", doubled_contents).expect("could not write output");
}


Is the following repository pattern properly applied?

I don't like the underscore in the class name, HR_Repository. It's a generic name for a generic class, which is good, but seeing that it implements IRepository<T> I would expect something like this:
public class EmployeeRepository : IRepository<Employee>

I like that you're initializing your private readonly LoginDataContext in the constructor, from a constructor argument.
private readonly  LoginDataContext dataContext;
public HR_Repository(LoginDataContext dataContext)
{
    this.dataContext = dataContext;
}

I like it because this implementation of IRepository<T> has a dependency on the LoginDataContext - by passing it into the constructor, you're doing constructor injection and that's awesome. Ideally the dependency would be an abstraction (abstract class or interface), which makes it easier to inject as a mock or fake implementation when you're writing unit tests. Even if you never write these tests, the fact that your code would be testable is a very good thing.
I don't like that your static helper provides extension methods to IQueryable<Employee>, it's not clear how/where this code is being used, the benefits aren't immediately apparent.

As for the pattern itself, it looks like a hybrid Unit-of-Work / Repository implementation, because of the Commit method. But your implementation exposes ITable and IQueryable, which leaks out the ORM into the calling code.
If you consider the client as, say, a controller class (assuming MVC), the controller would have a dependency on the unit-of-work, which has a dependency on the data context and lets you work with one or more repositories, which all share the data context of the unit-of-work:

(I skipped UML classes, hope this doesn't look too weird)

Disclaimer
I'm biased. I'm not a fan of unit-of-work/repository pattern, at least not with Entity Framework. I think Entity Framework's DbContext is a unit-of-work, and the IDbSet<TEntity> properties it exposes are repositories - I think wrapping this in another level of abstraction has very little benefits and adds a considerable amount of complexity to the code.
Instead, I simply wrap DbContext with an interface:
public interface IUnitOfWork
{
    void SaveChanges();
    IDbSet<TEntity> Set<TEntity>();
}

public class MyContext : DbContext, IUnitOfWork
{
    IDbSet<MyEntity> MyEntities { get; set; }
    // ...
}

Then I usually have a "service" class that takes an IUnitOfWork dependency; I write closely related queries inside that class, but the "service" only returns materialized results, it doesn't expose IQueryable<T>, even less so ITable. A controller will take a factory that can instantiate such a "service", wrapping its instance in a using block to ensure proper disposal.


Dynamically adding blocks of information to a page

Yes, it's fine to do. Rows are only used to create groups of horizontal content. In your case, your grid would wrap around (which you may want to consider is what you really want), but this is how responsive grids of photos are generally created.


No, this is not correct; it only verifies whether the vertices of one rectangle are inside the other, not the other way around. Try calling it with the following parameters:

checkCollide(2,2,4,4, 1,3,2,2);
checkCollide(1,3,2,2, 2,2,4,4);

They should print the same result, but they don't. This case can be seen in the picture below.

Update: even if you repeat the checks changing x/x2, y/y2, etc, this still won't catch all the cases: two rectangles may intersect even if none of their vertices are inside the other rectangle - see the other picture below.

A more generic solution should use a segment intersection routine to check whether for all segments in one rectangle whether they intersect with any the segments on the other one.


Copy and bit-invert ints in an std::vector

You can utilize std::transform here (I'll assume C++11 for the lambda):

int main()
{
    std::vector<uint8_t> first_list = {0x01, 0x10, 0x32, 0x1A};
    std::vector<uint8_t> second;
    std::transform(first_list.begin(), first_list.end(), std::back_inserter(second),
                   [](uint8_t u) { return ~u; });
}

You also don't need to make a copy of the first vector to do this; better to simply use push_back (or back_inserter here, since we're working with iterators).


This entire method should be static, as it clearly does not require an object
new Random(Guid.NewGuid().GetHashCode()) is needlessly complicated. new Random() is initialized based on time by default
A simpler range from [0,2] can be used.
The changed variable can be entirely replaced by a switch and return structure

private static string Capitalized(string word) {
    return char.ToUpper(word[0]) + word.Substring(1);
}

private static string RandomCase(string word)
{
    int choice = new Random().Next(3);
    switch(choice) {
        case 0: return Capitalized(word);
        case 1: return word.ToUpper();
        case 2: default: return word;
    }
}


One possible optimization is to use local variables instead of directly writing to the out parameters. So instead of:

// compute averages
for (i = 0; i < N; i++) {
    *avg += F[i];
    if (F[i] >= 50.0) {
        *passing_avg += F[i];
        *num_passed += 1;
    }
}

you write:

int l_num_passed = 0;
float l_avg = 0.0;
float l_passing_avg = 0.0;

// compute averages
for (i = 0; i < N; i++) {
    l_avg += F[i];
    if (F[i] >= 50.0) {
        l_passing_avg += F[i];
        l_num_passed += 1;
    }
}

*num_passed = l_num_passed;
*avg = l_avg;
*passing_avg = l_passing_avg;

That way the compiler can use fast registers. If you directly write to the out parameter within the loop, the compiler cannot use registers as it must stay on the defensive side by assuming that avg could point to the same memory location as passing_avg or even num_passed.

This unfortunate feature of C and C++ is known as pointer aliasing and often prevents the compiler from making effective use of registers.

You can also use local variables for the other loop. Instead of:

// compute ranks
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
        if (F[i] < F[j]) {
            R[i] += 1;
        }
    }
}

write:

float fi;
int rank;

// compute ranks
for (i = 0; i < N; i++) {
    fi = F[i];
    rank = 1;
    for (j = 0; j < N; j++) {
        if (fi < F[j]) {
            rank += 1;
        }
    }
    R[i] = rank;
}


git Create Tree from Arbitrary Directory (works in bare repository)

Consider portable shell
Do we really need Bash for this?  If we can manage without local variables and string indexing, then we could use a leaner, more portable shell instead.  Certainly, there's no benefit using the non-standard function keyword - just omit it.
We probably do want local in the recursive function, but it's good to be clear that we've made the choice for a good reason.
Add some error checking options
set -eu -o pipefail

Use more quoting
We don't want $path or $fullpath to be split:
    for fullpath in "$path"/*; do
        f=$(basename "$fullpath")

There's some more needed later:
            treeData=$(printf '%s\n%s %s %s\t%s' "$treeData" $mode $type $hash "$f")
        elif [ -d "$path/$f" ]; then
            # recurse
            treeData=$(printf '%s\n%s' "$treeData" "$(createSubtreeRec "$fullpath")")

Shellcheck can't know that $hash will always be a single token, so it recommends more quoting than is actually necessary.


Create a stack implementation that handles the multi thread scenario

This is very easy to read and well written. As far as I can tell, it accomplishes your goal in a very straightforward way, and should be very easy to maintain going forward.
Does It Do Enough?
Overall, it's a very simple class. Are you sure there aren't any additional things it should do? I know in the past, I've needed to check the size of a stack (see how many items are on it). So a -count method might be in order. And maybe an -isEmpty method (though a caller could just check if count is 0.) Also, sometimes it is desirable to get the top object without popping it off. Many stack implementations have a -top method to do that.
You might also want to offer some additional initializers similar to the other Cocoa containers. Maybe things like -initWithCapacity:, -initWithStack:, and if you're feeling ambitious, -initWithObjects:.
Error Handling
In the -pop method you check to see if there are any items on the stack, and if so, return the top item after removing it from the stack. In general a caller should be informed if they are trying to pop a stack with no items on it. While you do return nil it might be better to raise an exception in that case, similar to how an NSArray will raise an exception if you try to get an object at an index that does not exist.


Optimize/Refactor Javascript Unique Array function

For me, I'd always avoid methods that require lots of includes to things get working - and in my mind, the more code used.. the slower things will be (unless some form of caching is used). Which is why I would opt for a simple JavaScript solution. Your idea will work, but I think this one is faster:

Array.prototype.unique = function () {
  var a = this, b = [], c, i = a.length;
  again: while ( i-- ) {
    c = a[i];
    k = i; while( k-- ){ if (a[k] == c){ continue again; } }
    b.unshift( a[i] );
  }
  return b;
}

There are probably other improvements that can be made, for example it might be faster to find a way to use .push() rather than .unshift().

I haven't tested the above excessively, but it seems to work in all my tests so far. The reason why it gets a speed increase is because it reduces the area it is checking each time; it is also using subtle other speed increases like a decrementing while loop (means there are less conditional statements to check on each iteration), and creating shortcut vars that cut down access time.

As proof here is a jsPerf... albeit only tested on my set-up so far ;)

http://jsperf.com/compare-array-unique-versions

side note: -- the downside to my method is that it will only include the last found occurance of a duplicate (not the first as your's will). So if that ordering is important to you, then you'll have to refactor the code.

revision: -- after a few jsPerfs it seems clear that the while(i--) no longer holds a speed difference (at least not for FireFox 16 Mac OSX). Whilst on Chrome Mac OSX i--; seems slower than i++;

http://jsperf.com/compare-a-dec-while-against-a-for-loop

So taking in to account BillyBarry's comments the improved version should be:

Array.prototype.unique8 = function () {
  var a = this, b = [], c, i, l = a.length, j, k = 0;
  again: for ( i = 0; i < l; i++ ) {
    c = a[i];
    for ( j = 0; j < k; j++ ) { if (b[j] === c){ continue again; } }
    b[k++] = c;
  }
  return b;
}

Working from b, rather than a improves things quite a lot. Plus using k++; rather than .length for the internal loop makes quite a bit of difference for FireFox (Mac OSX) but has no affect on Chrome.


Why do you insist on putting the '' on members. It makes them look so ugly. Also most identifiers beginning with '' are reserved so you need to be careful. If you must use decade old conventions (that have been abandoned) to identify members use 'm_` as the prefix.

The reason I hate them is for this:

--_count;

// That is ugly and harder to read than:

--count; // but that's just an opionon.
         // The bit about being reserved is a problem though.
         // and if you use leading underscores you should understand
         // all the associated rules.

Curious where max/min come from?

_condition.wait(lock, boost::bind(std::less_equal<int>(), boost::ref(_count), max));
                                                                        //   ^^^^^

Passing RAW pointers around is not common in C++ (unlike C).
Normally you wrap a pointer inside a smart pointer object to indicate ownership semantics (and thus who is responsible for deleting the object).

// No indication of ownership is retained or passed the the moniter.
// So we have no idea who should delete rawMatrix?
//
// Have you passed ownership to the moniter or is the caller retaining ownership
// If the owner retains ownership when does he delete it?
void MatrixMonitor::deposit(RawMatrix* rawMatrix){

// I suppose you have to return a pointers as you were passed a pointer.
// but now the caller has no idea weather he should delete the pointer he
// is given or if the pointer is still owned by somebody else.
RawMatrix* MatrixMonitor::withdraw(){

Personally I would change the interface to make sure the ownership symantics are well defined. In this case I would pass ownership to the moniter and pass ownership out to the person withdrawing the item:

void MatrixMonitor::deposit(std::unique_ptr<RawMatrix> rawMatrix){

std::unique_ptr<RawMatrix> MatrixMonitor::withdraw(){

I think you want to separate producer and consumer from the Moniter. These are three different types of object. When you construct the producer/consumer you pass it a monitor object to use when it deposits/withdraws items.

int main()
{
      MatrixMonitor   monitor;
      Producer        farmer(monitor);  // Pass monitor by reference
                                        // So the farmer is adding to this moiter.
      Consumer        shopper(moniter); // shooper uses the same monitor as the
                                        // farmer but because it is a consumer will
                                        // call withdraw() while the
                                        // farmer calles deposit()

      farmer.run();
      shopper.run();

      // don't forget to wait for the threads to exit.
      farmer.join();
      shopper.join();
}

Edit: Based on new code for Producer/Consumer

One would assume that the producer needs to finish at some point.
You may want to change while(true) into while(!finished) or similar.

void MatrixProducer::produce(){
    while(true){

Don't see any need for this mutex.

        boost::mutex::scoped_lock lock(_mutex);

Ownership semantics again. Who owns the generated matrix?

        RawMatrix* matrix = rawMatrix();


Raspberry Pi Safe Clean Up - the decorator way

If you want to do gpio in one line, you can use functools.partial and either functools.wraps or functools.update_wrapper.

As you are using wraps already, you may as well use partial too.

def gpio(func):
    return update_wrapper(partial(func, GPIO), func)

Now it's a simple one-liner.
If you don't need @wraps, this can be further simplified to:

def gpio(func):
    return partial(func, GPIO)

Ways I would change the program:

Adding an option to SafeGPIO to have the option to handle errors.
Merging gpio and safe_gpio into one function would improve my user experience.
Less functions to remember, whilst keeping the option for it to be safe.
You don't use @gpio, so would you ever use it?

If your response is no, you should consider removing it.
As you could just import GPIO.
And it seems like a lot of overhead for importing GPIO.


Generic Repository: Am I over-complicating?

I think if you are going to have only one Repository, then yeah this is over complicated! But if you will have many Repositories and you will be adding more and more, then you are on the right track. But couple of points:

I am not sure how your are using your UoW. From my point of view UoW should look like something like:

interface IUnitOfWork
{
    Begin();
    End();
    Rollback();
}

And UoW should be passed to Repositories. So basically you have a UoW that couple of Repositories may use to get their job done (get/insert records for instance). From where I look at this a UoW is not specific to a single Repository and can span multiple Repositories.

Imagine for instance that your UoW involves creating an Order entity and updating the Customer entity together.

Also I would suggest to tighten IRepository definition to:

public interface IRepository<T> where T : IDomainObject

This basically is saying that repositories are not supposed to be created for any sort of class. Your Domain classes can then implement IDomainObject to satisfy this condition. IDomainObject can be empty or depending on your Domain it can have some Domain related properties.


Creating Pascal's Triangle when specified number of rows

Nine line code review.

Apart from some style and layout issues your code is good.

Style

If you are to use var to declare variable you should put them at the top of the function. Or you can use let which defines block scoped variables and you put them where you need them. Block scope means that the variable is only available inside the block it is declared for.
Put spaces between operators +, -, =, /, *, ===, <= etc. as it becomes very hard to read code when numbers and variables are all one continuous string. Making code more readable makes it easier to spot bugs.
Don't repeat, and use contextual information to reduce name size. For example, you had pascalRow which is a little too much information in a function that is called pascal, row holds the same information regarding what the variable references.
The function name however does not give much information about what it does and is a rather bad name. Maybe pascalsTriangle would be clearer.
The argument row is singular, the custom is a plural for counts though rows would imply an array so something like numberRows or rowCount would be more fitting
The custom for loop variable names are i then j, then k with i as the outer loop and then inner. Loop variable names and position is not a biggy in the book of buggy, bad, code; consistency is very important. Using the idiomatic styles helps you stay consistent.
Javascript has automatic semicolon insertion (ASI). The rule is only use ASI when you can list off the top of your head every way it can break your code. Add the semicolon- it will save you a ton of WTF bug hunting.
I assume you are a beginner, and to help improve your code you should always add the compiler/interpreter directive "use strict"; as the first line of any JS file or script tag. It will catch may common mistakes with an error and save you from some of the hardest to catch bugs. It will also run the code faster.

Rewrite.

So with the above in mind, here are two rewrites. The first uses var

"use strict";
function pascalsTriangle(rowCount) {
    var i, j, row;
    for (i = 0; i <= rowCount; i++) {
        row = [1];
        for (j = 1; j <= i; j++) {
            row.push(row[j - 1] * (i + 1 - j) / j);
        }
        console.log(row);
    }
}

The version using let and const:

"use strict";
function pascalsTriangle(rowCount) {
    for (let i = 0; i <= rowCount; i++) {
        const row = [1];
        for (let j = 1; j <= i; j++) {
            row.push(row[j - 1] * (i + 1 - j) / j);
        }
        console.log(row);
    }
}

Improve?

Good coders are always trying to find ways to improve the code and the app. Here are some simple improvements to both the algorithm and output. This is meant just as an example and to introduce some new syntax.

Optimise

You may notice that each row is mirrored so you can save some computation by only doing half the row. Reversing an array (simple in Javascript) is not always the best option. Using two arrays for the left and right sides reduces the work done under the hood. For even rows you need to remove the duplicate center number.

Safeguard

If abused, your function can block a page and likely crash it when memory runs out.

The argument for the number of rows can have have any value. Generally you would vet such a value, making sure its a number, and that the number is not too big. Takes a long time and a lot of memory to compute pascalsTriangle(Infinity)

So a simple argument check at the start check for a number and sets an upper triangle size. For bad numbers the count defaults to 10, and the max count is 40.

User friendly

Console is not a nice output, its slow and the formatting is not always what you want (And its is even worse when the in-page console is used). It would be better to create the triangle as a string and output the result after the computation is complete so that you can use the complete triangle to help set out the numbers.

"use strict";

function pascalsTriangle(rowCount) {
    const tri = []; // Hold all rows
    rowCount = Math.min(40, isNaN(rowCount) ? 10 : rowCount);
    for (let i = 0; i <= rowCount; i++) {

        // arrays for left and right sides
        const left = [1];
        const right = [1];
        for (let j = 1; j <= i / 2; j++) {  // only do half a row
           const val = left[j - 1] * (i + 1 - j) / j;
           left.push(val);
           right.unshift(val);
        }
        if (i % 2 === 0) { right.shift() } // remove extra num for even rows

        // concat the two arrays and join the result as a string push to the tri
        tri.push([...left, ...right].join(" : "));
   }

  // Display as triangle
  const maxLen = tri[tri.length - 1].length;
  tri.forEach(row => {
      const pad = ((maxLen - row.length) / 2);
      display.innerHTML += row.padStart(row.length + pad, " ") + "
";
  });

}

pascalsTriangle(12)


Detecting the mime type using an agnostic method

General Issues

If you are going to call something getMimeType then it should return exactly that.  This is probably best defined by Multipurpose Internet Mail Extensions RFC 2046.  Read the wikipedia page for more general information and related RFCs.

As Corbin commented on this implementation is broken due to the number of assumptions that are required to consume the information provided by this function.  You really should return just a string with the mime type or an array with the primary type and subtype.  Whatever you return should be consistent with your documentation.

You could consider some of the following instead of returning false:

Throw an exception.
Trigger an error and default the MIME type.
Create a second function hasMimeType to avoid exception/errors.

Specific Issues

finfo_fopen

I think finfo_fopen should probably be finfo_open.

Its usage is something like:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
return finfo_file($finfo, $filename);

However there are some catches.  FILEINFO_MIME_TYPE has only been defined since PHP 5.3.0.  You can use version_compare to determine which version of php you are using (If the version_compare function doesn't exist you are using PHP < 4.1.0).

if (version_compare(PHP_VERSION, '5.3.0') >= 0) { /* Do Stuff */ }

getimagesize

Only the mime index from the returned array should be used.

exif_imagetype

The string returned from this does not conform to the MIME type format.  You will have to massage this data to return something appropriate.


Is this a valid and correct skeleton class/struct

It is kind of hard to tell what you're really asking. Without knowing what you're asking, it's hard to provide a helpful and meaningful answer. I will try regardless. Feel free to point me in the right direction if I'm missing the point.

  Is it valid to refer to class as regular/semiregular/fully ordered?

While I'm not familiar with the terminology, the distinctions are useful. These classifications let you reason about a class. For example, std::list<T>::sort() requires that operator< is defined for T. This is part of what Java and C# interfaces and the suggested C++ concepts feature is about. Note that they aren't necessarily accumulative: A type can be "fully ordered" without being "semi-regular".

However, I can't see a good reason for sorting types into only these categories. Stepanov may have some deeper insight here.

  Are there strong reasons for non-member friend/non-friend member functions?

Like Scott Meyers points out in the article you link to, non-member non-friendfunctions improve encapsulation, which leads to looser coupling. (Looser coupling in turn leads to better complexity handling, replaceable components, more testable interfaces and so on. These are good things.)

Regarding non-member friend functions, I personally consider them a code smell. It doesn't necessarily mean that the code is dirty, but in most cases you don't want friends. (Even without friends, you can still throw party;!) Declaring a friend breaks encapsulation and leads to tighter coupling, which is the opposite of what we want.

(If you do have friends, make sure they interact with an interface (i.e. member function) and not directly with private variables/implementation details.)

  Should friend requirements define member/non-member functions?

I am reading the question as: "Should functions that need to be declared friend be member functions instead?"

For functions that are not part of the class' public interface, the answer is yes, definitely. They should be private member functions.

For functions that are part of the public interface: Unless you have a specific reason to make that function non-member, it should be a member function. The point Scott Meyers is making, however, is this: If the function can use the class' public interface instead of being non-member friend or a member function, it should do so: It should be a non-member, non-friend function that interacts with the type through the type's public interface.

My basic guideline is this: Can the function make use of only the public interface? Then make it non-member, non-friend. If not, make it a member function. However, don't extend the public interface more than otherwise necessary just to allow a function to be non-member, non-friend. If you have to extend the public interface for just a single function, then that function should probably be a member function instead.

  Is it a good rule that each of these groups are implemented fully if at least one member of that group is?

When defining one of assignment operator, destructor or copy constructor, the Rule of Three comes into play and you should probably define the others.

For the categories Stepanov talks about: Yes, if you implement one part of the groups of operators, you should probably implement the others. This is because you should follow the Principle of Least Astonishment. Users of a type expect that if you can say a == b, then you should be able to say a != b as well.

The exception is what he refers to as regular: A type that is constructable may not need to be copyable or movable.


I'm not sure why you'd need to pipe three different streams - one for every manipulation. I'd probably use one Stream to do all the manipulations together, something like:

filedates = files |> Stream.map &((&1 |> File.stat!).ctime |> datastr.())

or

filedates = files |> Stream.map &(File.stat!(&1).ctime |> datastr.())


Creating instance of all classes that have certain attribut value

I'm not sure what feedback specifically you're looking for. There are minor formatting and naming questions, but only two things I would specifically draw attention to.

The first thing is that you're enumerating all the settings in the App.config, but you're only interested in settings that relate directly to message delivery. You should name-space your setting keys, and filter the settings before evaluating them.

<appSettings>
    <add key="MessageDelivery.MessageToConsole" value="true"/>
    <add key="MessageDelivery.MessageToDb" value="true"/>
    <add key="MessageDelivery.MessageToService" value="false"/>
    <add key="MessageDelivery.MessageToFile" value="false"/>
  </appSettings>

and

List<string> settingValues = ConfigurationManager.AppSettings.AllKeys
        .Where(key => ConfigurationManager.AppSettings[key].Equals("true"))
        .Where(key => key.StartsWith("MessageDelivery."))
        .Select(value => value.Replace("MessageDelivery.",""))
        .ToList();

Secondly, avoid using two different forms of Linq expression building:

List<string> settingValues = ConfigurationManager.AppSettings.AllKeys

        .Where(key => ConfigurationManager.AppSettings[key].Equals("true"))
        .Select(value => value)
        .ToList();

and

return from type in assembly.GetTypes()
           where type.IsDefined(typeof(MessageDeliveryAttribute), false)
           select type;


Find the number of working days between two dates inclusively

Personally, I think your approach is very complicated for what it should be trying to do: loop over all days between the start and the end date and count how many of those are not in the weekend.

Translating that sentence to code, gives me this:

private static int GetNumberOfWorkingDaysJeroen(DateTime start, DateTime stop)
{
    int days = 0;
    while(start <= stop)
    {
        if(start.DayOfWeek != DayOfWeek.Saturday && start.DayOfWeek != DayOfWeek.Sunday)
        {
            ++days;
        }
        start = start.AddDays(1);
    }
    return days;
}

I find this much easier to interpret than a bunch of modulos, casts and divisions.


Could you give more information on what the point of this is? All it does is change the class of the links. What about the actual pagination itself, which i assume would use AJAX? This code should probably know about that in order to react to errors.

Wrapping the code in an object like this isn't very useful like this. For one, the functions inside the containing object all refer to its variable name, so it breaks if it's changed. Also it looks like a reusable class allowing to have multiple paginations in one HTML document, however it's not.

You have the "max size" redundantly hard coded twice - once in the JavaScript and once as the number of elements in the HTML. How do you know that the pagination has exactly 6 pages?

The same basic problem with the original "current" element and the "active" class: It's hard coded in both the JS and the HTML. With the class name it even looks as if you could change it, because it's an initialization parameter, but changing it breaks the design, because its hard coded in the HTML.

Generally you have some unnecessarily abbreviated variable names, cn being the worst.


How should I read coordinates from a text file?

As this is posted on codereview, let us take a look at the whole function.

private static List<Position> getPositions(File myFile)
        throws FileNotFoundException, IOException {

I would suggest to do a check for the file (and rename it to file, I do not think there is a herFile, hisFile and so on):

    if (file == null || !file.canRead())
        throw new IllegalArgumentException("file not readable: " + file);

Which could make error handling a bit easier. We will see later.

    List<Position> result = new ArrayList();
    BufferedReader br = new BufferedReader(new FileReader(myFile));
    try {
        String line = br.readLine();
        while (line != null) {
        ...
            line = br.readLine();

I would keep the typical pattern, so everyone can recognize it:

        String line;
        while ((line = bufferedReader.readLine()) != null) {

            String coordinates = line.substring(6, line.length() - 1);
            int splitpoint = coordinates.indexOf('|');
            double x = Double.parseDouble(coordinates.substring(0, splitpoint));
            double y = Double.parseDouble(coordinates.substring(splitpoint + 1));
            result.add(new Position(x, y));
            line = br.readLine();
        }

For me, this is nearly fine. Just to a split("|") and you are done in the easy way:

            final String[] coordinatesArray = line.substring(6, line.length() - 1).split("|");
            final double x = Double.parseDouble(coordinatesArray[0]);
            final double y = Double.parseDouble(coordinatesArray[1]);
            result.add(new Position(x, y));

And I suggest to add an example in a comment, to help the next reader.

    } finally {
        br.close();
    }

If you have Java7, you could change this to try-with statement:

    try (final BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
        ...
    }

And you could catch the error. The most problematic ones are cought by the file checks. Everything else is probably something you can not do anything about.
Then it is fine to catch it, show it and continue:

    } catch (NumberFormatException | IOException e) {
        e.printStackTrace(); // handle the exception or rethrow it. It could be safe to do nothing here
    }

If you put everything together, it could look like this:

private static List<Position> getPositions(final File file) {
    if (file == null || !file.canRead())
        throw new IllegalArgumentException("file not readable: " + file);

    final List<Position> result = new ArrayList<>();
    try (final BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            // example: Robot(479.30432416307934|98.90610653676828)
            final String[] coordinatesArray = line.substring(6, line.length() - 1).split("|");
            final double x = Double.parseDouble(coordinatesArray[0]);
            final double y = Double.parseDouble(coordinatesArray[1]);
            result.add(new Position(x, y));
        }
    } catch (NumberFormatException | IOException e) {
        e.printStackTrace(); // handle the exception or rethrow it. It could be safe to do nothing here
    }
    return result;
}

If you try the way with the scanner, you shoudl just tell him which characters to ignore. Please do not try a complex regular expression. They are unreadable.
What we have there?

  Robot(479.30432416307934|98.90610653676828)

Well, everything which is not a number or a point. To save some typing, we do not place every character alone, we put them together as \p{Alpha} (any alphabetic character): [\p{Alpha}()|\]. And we want this to happen for one or more times: [\p{Alpha}()|]+.
And we should not forget about multiple lines, then there is a newline: [\p{Alpha}()|\\n]+.

It is still mostly readable if you have a basic understanding of regular expressions, so we are fine in this case. You could also use [a-zA-Z()|\\n]+ which would be more common outside the java world.

The complete function could look like this:

private static List<Position> getPositions(final File file) {
    if (file == null || !file.canRead())
        throw new IllegalArgumentException("file not readable: " + file);

    final List<Position> result = new ArrayList<>();

    try (Scanner scanner = new Scanner(file)) {
        // example: Robot(479.30432416307934|98.90610653676828)
        scanner.useDelimiter("[\p{Alpha}()|\\n]+");
        while (scanner.hasNext())
            result.add(new Position(scanner.nextDouble(), scanner.nextDouble()));
    } catch (final FileNotFoundException e1) {
        e1.printStackTrace(); // handle the exception or rethrow it. It could be safe to do nothing here
    }
    return result;
}


Your code looks nice and the documentation is high quality.

Maybe a few things can be improved anyway.

API

It could be a good idea to get inspiration from the Python API functions related to sorting, we have:

sorted returning a new list from an iterable
list.sort sorts a list in place, returns None

In your case, as structure is sorted in place, I am not sure it makes sense to return it.

Parameter structure

This is mostly personal opinion but instead of structure, I'd find container to be a better name.

Also, if you want to be precise in the documentation, you might want to say that it is mutable but also that it implements __len__, __getitem__ and __setitem__. These objects are also called (mutable) sequences.

The code

Not much to say about the code itself.

Instead of having if not changed: break, you could write a: while changed loop which is very slightly more concise.

Also, you'll find an optimisation suggestion on Wikipedia:

  The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n − 1 items when running for the n-th time

Before getting into such a change, I highly recommend writing unit tests.


Balanced parenthesis, with backslash escaping

Superficial remarks

Whats a "bacelet", in isBaceletFind()?  Did you mean "bracelet"?  Even that is questionable English terminology, as I would take it to mean a piece of jewelry worn at the wrist.  Or maybe you meant "bracket"?

isPopable() should be isPoppable().

I normally don't like to be pedantic about brace styles, but the one you use for your if statements is really very unconventional, and certainly not easy to read.  Wikipedia lists 8 common brace styles, and yours is not any of them.  In fact, I'd say that it's the first time I've ever seen it in use.

Data structure

java.util.Stack is deprecated, because it has bad object-oriented design (it allows random access because it extends java.util.Vector), and because its methods are synchronized (which incurs unnecessary performance overhead).  Normally, the recommended replacement for Stack is ArrayDeque.  However, in this case, since each element is a char, I'd use a StringBuilder instead, so that you don't have to incur the char ↔ Character boxing/unboxing overhead.

Even if your code works, it's a bad practice to write:

private static final Stack<Character> STACK = new Stack<>();

static means that there is only one instance shared throughout the Java interpreter.  Having to write STACK.clear() at the beginning of isBalanced() is ugly.  It also unnecessarily introduces the possibility of multithreading problems, when isBalanced() should be a simple deterministic function with no threading issues.
The ALL_CAPS name suggests that it's a constant, which it isn't in nature, even if it's technically a final variable.

Instead, isBalanced() should instantiate the stack as a local variable, and explicitly pass it to any helper function that needs it.

Algorithm

I'm not a big fan of the BRACELETS constants, with the first half being the opening delimiters, with their counterparts in the second half.  I think it's more cryptic than it needs to be.  I'd just write a switch containing all of the characters of interest: it compiles to very clean and efficient bytecode, even simpler than String.indexOf().

When you encounter an opening delimiter, it would be smarter to push its counterpart onto the stack instead.  That way, you don't have to repeatedly ask "is this the right closing delimiter?" when looking at every subsequent character.

public class BalancedParenthesis {
    private static class CharStack {
        private StringBuilder sb = new StringBuilder();
        public boolean isEmpty() { return this.sb.length() == 0; }
        public void push(char c) { this.sb.append(c); }
        public char pop() {
            char last = this.sb.charAt(this.sb.length() - 1);
            this.sb.setLength(this.sb.length() - 1);
            return last;
        }
    }

    public static boolean isBalanced(String str) {
        CharStack stack = new CharStack();
        for (int pos = 0; pos < str.length(); pos++) {
            char ch = str.charAt(pos);
            switch (ch) {
              // Backslash: ignore the next character
              case '\\': pos++; continue;

              // Opening delimiters
              case '(':  stack.push(')'); break;
              case '{':  stack.push('}'); break;
              case '[':  stack.push(']'); break;
              case '<':  stack.push('>'); break;

              // Closing delimiters
              case ')':
              case '}':
              case ']':
              case '>':
                if (stack.isEmpty() || stack.pop() != ch) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}


One tip: Instead of gluing constant and variable parts into string with + as e. g. in your statement

print " "*2 + "%s:" % (day[0]), from_to.rjust(5) + u'\u00b0' + "C -", "%s" % (day[3])

use the format() method with placeholders {} in formatted string:

print "  {} {:>5}{}C - {}"     .format(day[0], from_to, u'\u00b0', day[3])

(I visually separated the resulting string with placeholders from the format() method),
or - more descriptively - use names in {} placeholders

print "  {day0} {from_to:>5}{degree_sign}C - {day3}" \
    .format(day0=day[0], from_to=from_to, degree_sign=u'\u00b0', day3=day[3])

Format specifier >5 after : does the same thing as .rjust(5) in your code.

Edit:

For Unicode symbols (as u'\u00b0' in your code) use their hexadecimal value (0x00b0) and type c in the placeholder:

print "  {} {:>5}{:c}C - {}"     .format(day[0], from_to, 0x00b0, day[3])

See Format Specification Mini-Language


In order that things appear in the code:

using namespace std;

This is unnecessary and generally bad practice.  I would ask about it if I saw it in an interview question, although it is not harmful in this case.

struct node
{
    node(int d) : data(d) {}
    int data;
    boost::ptr_vector<node> children;
};

Indentation is generally done in powers of two, and should in any case be consistent.  I'm switching to four-space indent everywhere, as you don't seem to be following any style.

This is also a great chance to use pointer containers.  Each node owns all of its children, so use something that will enforce that.  (In some cases, an std::vector of std::shared_ptrs would make more sense.)

You do not need any of the globals you've defined, and are definitely bad practice.  You should also strive to be more const-correct.

void printpath(node const* root)
{
    std::stack<node const*> path;
    std::set<node const*> visited;
    path.push(root);
    while (visited.find(root) != visited.end())
    {
        node const* v = path.top();
        if (visited.find(v) != visited.end())
        {
            path.pop();
            continue;
        }
        std::cout << v->data << " ";
        bool has_unvisited_child = false; // Use bools for booleans.
        // See standard comments on iterators vs indices and preincrement
        // vs postincrement.
        for (auto it = v->children.cbegin(); it != v->children.cend(); ++it)
        {
            if (visited.find(&*it) != visited.end())
            {
                 has_unvisited_child = true;
                 st.push(&*it);
            }
        }

        // Don't rely on the root node having value 0 in its data.
        // You were given a pointer to it, use that.  Your algorithm
        // should not depend on the data stored in the tree.

        // Avoids some nesting.
        if (!has_unvisited_child)
            continue;

        visited.insert(v);
        while(v != root)
        {
            v = st.top();
            // Avoid shadowing.
            bool unvisited_child = 0;
            // Splitting this off into a function may be meaningful,
            // or using some standard algorithm such as std::any_of
            for (auto it = v->children.cbegin(); it != v->children.cend(); ++it)
                unvisited_child |= visited.find(&*it) != visited.end();
            if (!unvisited_child && !v->children.empty())
                visited.insert(v);
            if (v != root)
                st.pop();
        }
        std::cout<<endl;
    }
}

// main must return int
int main()
{
    node* root = new node(0);
    node* d = new node(1);
    node* m = new node(2);
    node* n = new node(3);
    root->children.push_back(d);
    root->children.push_back(m);
    root->children.push_back(n);
    node* x = new node(4);
    node* y = new node(5);
    node* z = new node(6);
    d->children.push_back(x);
    d->children.push_back(y);
    d->children.push_back(z);
    node* o = new node(7);
    node* p = new node(8);
    n->children.push_back(o);
    n->children.push_back(p);
    printpath(root);
}

Now for the performance part:  My advice on that end is to not bother with the stack of next nodes and just keep track of the path:

void print_path(node const* root)
{
    std::vector<node const*> path{root};
    std::set<node const*> visited;
    while (!path.empty())
    {
        node const* n = path.back();
        if (std::all_of(n->children.cbegin(), n->children.cend(), [&](node const& a) { return visited.find(&a) != visited.end(); }))
        {
            if (n->children.empty()) {
                for (auto it = path.cbegin(); it != path.cend(); ++it)
                {
                    if (it != path.cbegin())
                        std::cout << ", ";
                    std::cout << (*it)->data;
                }
                std::cout << '\n';
            }
            visited.insert(n);
            path.pop_back();
        } else {
            path.push_back(&*std::find_if(n->children.cbegin(), n->children.cend(), [&](node const& a) { return visited.find(&a) == visited.end(); }));
        }
    }
}

I am not sure which is more efficient.