Ok, I had quite a few thoughts on this.

State

Your state seems more complex than it needs to be, and some of it is hiding outside of the state variable.
I think all you really need to keep track of are:
 - What order the images are in
 - Which images are currently selected
 - Which images have been guessed correctly

I don't really understand what tempCheckArr is, how it's different from compareImgArr, or why it's an instance variable.

Extract stuff

I think you have too much stuff crammed into one component.
I think you need to extract pieces of logic that can be self contained.

Prime example: shuffleArray

Why is shuffleArray declared inside componentWillMount?
This is creating a new shuffleArray function every time MemoryGame is mounted.
I think shuffleArray should at least be outside of this component, and really should be in a some sort of RandomUtil.js file.

Card component

I would also extract out a Card component that renders a card.
It should know:
 - What image to display
 - Whether or not it's selected
 - Whether or not it's been guessed correctly

This way you can keep your MemoryGame component about managing the state of the game while the Card component focuses on presentation.

Other Thoughts

Your  tag doesn't need a key prop because it's not the top level thing in an array.
Why is ImagePieces declared on this. It seems like it should be part of state.
(Also why is the I in ImagePieces uppercase? It seems like this should be imagePieces)
Why are you shuffling ImagePieces in componentWillMount and not just in the constructor?
It's kinda gross to reach into the DOM to compare the elements src attribute, and it makes it harder to understand what you actually want to compare: that the two images selected are of the same thing
Why are you converting integers to strings when you put them into tempCheckArr and converting them back when you take them out? Wouldn't it be easier to just put integers into the array?

How I would write it

const IMAGES = ["cat", "cat", "dog", "dog", "horse", "horse", "pig",
  "pig", "snake", "snake", "fish", "fish"];

class MemoryGame extends Component {
  constructor(props) {
    super(props);

    // You can simplify your state a lot
    this.state = {
      cards: shuffleArray(IMAGES.slice()),
      selected: [], // indexes which have been selected
      correct: [] // indexes which have been guessed correctly
    };
  }

  // Don't need a componentWillMount

  onCardClick(clickedIndex) {
    const { selected, cards, correct } = this.state;

    if (selected.length === 0) { // selecting a first card
      this.setState({ selected: [clickedIndex] })
    } else if (selected.length === 1) { // they're selecting a second card
      if (cards[selected[0]] === cards[clickedIndex]) {
        // It's a match :)
        // Add selected cards to `correct` and reset selection
        this.setState({
            correct: correct.concat([selected[0], clickedIndex]),
            selected: []
        });
      } else {
        // It's not a match :(
        // Select it for now, and reset selection in a bit
        this.setState({ selected: [selected[0], clickedIndex] });
        setTimeout(() => {
          this.setState({ selected: [] })
        }, 1500);
      }
    }
    // Otherwise they already have 2 selected and we don't wanna do anything
  }

  render() {
    const { correct, selected, cards } = this.state;
    return (

Memory Game

          {cards.map((image, i) => (
            <MemoryCard
              key={i}
              image={image}
              isCorrect={correct.includes(i)}
              isSelected={selected.includes(i)}
              onSelect={() => this.onCardClick(i)}
            />
          ))}

    );
  }
}

// Extracted into it's own component
const MemoryCard = ({ image, isSelected, isCorrect, onSelect }) => (

 {
      // You can only select a card that's not already correct and
      // isn't currently selected
      if (!isCorrect && !isSelected) {
        onSelect();
      }
    }}
  >

);

// Probably in a different file
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

export default MemoryGame;


Elevator Interview Problem OOP - Revised

Elevator program code challenge, revised:

where is that?

_sorted is a very very bad name. I have to read all the code to figure out exactly what that is.

public void AddRequest(int floor)

Rename the parameter to something like requestedFloor
Rename the method to something like CallElevator or RequestFloor

Does not account for which floor a call is coming from. I think it would matter if the elevator passing 2nd floor for the 7th, then a request comes for the 5th - originating from the 1st floor.

Looks like the code throws away requests for floors already in the list. But if I'm on the 1st floor asking for the 5th, why ignore my request just because the elevator is carrying someone to 5 already?

Fuzzy code

It is hard to tell exactly what the elevator logic is. And harder to tell if it meets requirements.

var min = _sorted.OrderBy(x => x.Key).First();

Clever but not clear. What is the elevator doing? What is the floor-stop choosing logic? This is "the bowels of the code" exposed at the highest logic level. I should be reading what the elevator is doing, not googling MSDN.

public int CurrentFloor { get; set; } = 1;
public Status Status { get; set; } = Status.Stopped;

Why are these public? In principle a well made OO class hides state and exposes functionality.

case Status.Stopped:
    if (CurrentFloor < floor)
        MoveUp();
    else
        MoveDown();
    break;

Flawed logic. If the floor (requested floor?) is the same as the current floor, the elevator goes down. Even if this code works is not the point. I should not have to use a debugger to know if the code covers edge cases.

P.S. what happens when we're on the 1st floor? Does it still go down?

Two collections makes sense: a queue of floor requests and an ordered list of floors the elevator is traversing. This fundamentally decouples two things that should not be conflated, but are so in this code.

Edit

Decisions on fundamental data structures strongly influences higher level design. In this case I think floor decision/prioritzation functionality would more likely end up in it's own class(es) - decoupling the decision logic from the elevator's movement.

This decoupling would make it easier to fix any issues due to incomplete/vague requirements. With the current code, things would break and change everywhere.

end Edit


UPDATE: Unity has built-in support for rebindable keys. I still urge you to setup rebindable keys, but a better way to do so would be through the system described by https://codereview.stackexchange.com/a/85568/35495.

One thing I really see happening with your code is that some poor gamer using a non-qwerty keyboard (like azerty or dvorak) will have an unplayable game because their keyboard has a different layout. for example, as an azerty-player I use ZQSD instead of WASD, and the W key is on the bottom line. In addition, there are players that use ESDF so they have a larger keyspace available for hotkeys.

The usual way of handling this is:

Make a .cfg or .ini file (basically a text file) in a config folder in your game

Put this code in there:

[Input]
button_W = forward;
button_S = back;
button_A = left;
button_D = right;
//any other buttons you need;

Then you load this into a dictionary when the game loads using a text file parser (plenty of examples for that online).

When the user then does any input, you check which button they pushed. Is it one of the configured buttons? then do the corresponding action. Is it a non-configured button? then return.

You can then use the default Unity launcher to configure these buttons, or you can configure these buttons using a custom config menu ingame.


Implement a function that prints all possible combinations of the characters in a string

I can suggest following project for combinations and permutations which is very efficient and easy to use:

http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G

Then it's simple as:

IList<Char> chars = "abc".ToList();
List<string> allCombinations = new List<String>();
for (int i = 1; i <= chars.Count; i++)
{
    var combis = new Facet.Combinatorics.Combinations<Char>(
        chars, i, Facet.Combinatorics.GenerateOption.WithRepetition);
    allCombinations.AddRange(combis.Select(c => string.Join("", c)));
}

foreach (var combi in allCombinations)
    Console.WriteLine(combi);

Output:

a
b
c
aa
ab
ac
bb
bc
cc
aaa
aab
aac
abb
abc
acc
bbb
bbc
bcc
ccc

If you don't want repetion you just have to change GenerateOption.WithRepetition to GenerateOption.WithoutRepetition and the result is:

a
b
c
ab
ac
bc
abc


Input validation

I find this an unusual way to validate script parameters:

if [ -z "$1" ] || [ -z "$2" ]; then

It's more common to verify that there are exactly two parameters:

if [ $# != 2 ]; then

Note that this is not exactly the same as the original.
The original verifies that neither $1 and $2 is empty,
and it silently allows more than 2 parameters.

Why echo a sub-shell?

What is the purpose of this echo:

echo `curl --silent $URL`

Instead of simply:

curl --silent $URL

If the purpose is to join multiple lines into one, I would use tr instead:

curl --silent "$URL" | tr -d '\n'
# or
curl --silent "$URL" | tr '\n' ' '

Writing this way make the intention more clear.
Another advantage is streamlined processing.
Note also that I added double-quotes around the $URL used as command parameter, as a good rule of thumb to protect from unexpected word splitting and globbing.

One sed to rule them all

Instead of this:

sed 's/.*\[(//' | sed 's/)\].*//'

You can do multiple expressions with a single sed using multiple -e parameters:

sed -e 's/.*\[(//' -e 's/)\].*//'

I use the -e even with single expressions,
for maximum clarity.


Avoid using namespace std; - it's a large namespace, and growing as new C++ standards appear.  Bringing all its names into the global namespace completely obviates the benefits of namespaces, and in the worst case, can silently change the meaning of a program.  Get used to using the (very short) namespace prefix std::.

When we call checkParentheses(), we have to provide a stack for it to use.  If we're not using the stack outside of the function, then it could just be a local variable.  Alternatively, we could choose to share it with the caller, so we could supply the input in chunks.  If we did that, we'd want to pass it by reference, so that the changed stack can be passed into the next call.

We're not modifying the string argument, so it makes sense to pass it as a reference to const.  When we use it, we're only interested in its characters in turn, so we can replace the for loop with a range-based for, eliminating the variable i:

for (char c: str) {
    if (c == '(' || c == '{' || c == '[') {
        s.push(c);
    }
    else

We can eliminate the flag variable, as whenever we set it, we immediately return:

        if(s.empty()) {
            return false;
        }

Before we remove it, I'll just make a small observation on the final test of flag, where we have two branches of an if test that result in the same behaviour:

else if (flag == 1) {
return false;
}
else {
return false;
}

Obviously, that could just be replaced with

else {
    return false;
}

In fact, we can simple replace that if/else with a single statement:

return s.empty() && !flag;

With the above changes, we've simplified it a bit:

bool checkParentheses(const std::string& str)
{
    std::stack<char> s;
    for (char c: str) {
        if (c == '(' || c == '{' || c == '[') {
            s.push(c);
        } else {
            if (s.empty()) {
                return false;
            }

            char  top = s.top();
            if (c == ')' && top == '(') {
                s.pop();
            } else if (c == '}' && top == '{') {
                s.pop();
            } else if (c == ']' && top == '[') {
                s.pop();
            } else {
                return false;
            }

        }
    }

    return s.empty();
}

We still have some quite repetitive code where we match a closing bracket against its opening one.  We can make this simpler and also more flexible (so that we could match « with », for example), by using a fixed map from opening to closing character:

static const std::map<char,char> pairs =
    { {'(', ')'},
      {'{', '}'},
      {'[', ']'} };

We can use this to replace the chained if/else if/else by storing the expected closing character on the stack and then simply comparing:

    if (pairs.count(c)) {
        s.push(pairs.at(c));
    } else {
        if (s.empty() || s.top() != c) {
            return false;
        }
        s.pop();
    }

Finally, the presentation can be improved.  Please be a bit more generous with space around operators - it really does make the code easier to read!  The indentation looks wrong, but perhaps that's an artefact of how it was copied into Stack Exchange.  If you used tabs for indentation, that can get corrupted (as SE has tab stops every 4 positions, rather than the normal 8).

Modified code

#include <map>
#include <stack>
#include <string>

bool checkParentheses(const std::string& str)
{
    static const std::map<char,char> pairs =
        { {'(', ')'},
          {'{', '}'},
          {'[', ']'} };

    std::stack<char> s;
    for (char c: str) {
        if (pairs.count(c)) {
            s.push(pairs.at(c));
        } else {
            if (s.empty() || s.top() != c) {
                return false;
            }
            s.pop();
        }
    }

    return s.empty();
}


You could try:

Using Multiple selectors
Moving the calculation logic to a function so that you can re-use it elsewhere or refactor/change in a single place if the need be.

Applying this you get something like the following:

row.children('[class*="size-"],[class*="offset-"],[class*="push-"],[class*="pull-"]').each(function () {
            columns += getCurrentSize(this);
        });

 function getCurrentSize(element){
     return Number($(element).attr('class').match(/\d+$/)[0]);
 }

However, if you want each class to be evaluated separately, as mentioned in the comments, you could first try adding these elements to an array and then perform a common action on them. Something like -

var uniqueClassColumns = [];
uniqueClassColumns.push($('[class*="size-"]'));
uniqueClassColumns.push($('[class*="offset-"]'));
uniqueClassColumns.push($('[class*="push-"]'));
uniqueClassColumns.push($('[class*="pull-"]'));

uniqueClassColumns.each(function () {
                columns += getCurrentSize(this);
            });

     function getCurrentSize(element){
         return Number($(element).attr('class').match(/\d+$/)[0]);
     }


I have a feeling there is a direct way to compute this amount, but I am not really into all the mathematics, you could possibly look it up. I'll talk about your code as is:

You should really remove all the superfluous white space, it hampers readability.
In Java, opening braces are not on a new line.
private before static.
Do not save te result of your recursive function in a variable, you can return at once.
The problem states you move from (0, 0) to (n,n). If you model your code the other way around, you can simplify it quite a bit. No need to pass n to your recursive function for example, as you can simply compare with 0.
Try to always use braces, even if you only have one line inside the block, as for example with the if part in your recursive function. It helps prevent unnoticed bugs due to formatting, and helps ease up modifying it later on.
In the else block, you do not need to check if x and y are valid, if you check for 0 up front.
In the recursive function, if the initial if succeeds, the result will always be 1. So you can return at once, it makes it more readable. Return early is a good thing in my opinion. The variable can then be put inside the else, reducing the scope.
You mention memoization, yet you do not seem to be using it. If you take the example, and the paths taken there:

“EEENNN”

“EEN|ENN”
“EEN|NEN”

“ENE|NEN”
“ENE|ENN”

Note that EEN will bring you to the same spot as ENE. You can see that each of those share the same second parts as well. This is duplication which we can use to speed up the algorithm.

If you think about it, there are generally multiple ways to get to some point (x,y). If you think of this as the starting point, the possible paths to the destination will obviously be the same, no matter how you get there. So what you can do is create a lookup table for a calculated location, so you calculate each one only once. This will give you an extreme amount of speedup I would think, on problems with a big amount of possible paths. Which you will get to quickly, even for small values of n.


Concurrent queue with pthread implementation

Correctly initialized members.

ThreadQueue() {
    pthread_mutex_init(&m_qmtx, NULL);
    pthread_cond_init(&m_condv, NULL);
}

But you don't check the error codes.
The object is potentially created with invalid members. Use exceptions to gurantee the state of your object.

Destructor does not do anything useful.

~ThreadQueue() {
    pthread_mutex_lock(&m_qmtx);
    m_queue.clear();
    pthread_mutex_unlock(&m_qmtx);
}

The destructr is supposed to clean resources.
It does not. You should destroy the mutex and condition variable in the destructor (reverse order of creation to be consistent).

Also locking before clearing the queue does not buy you anything. If at the point the destructor is called the object is still visible to other threads then it is going to break anyway. The queue is going to call clear in its own destructor so it is pointless doing it manually.

The call to signal should be inside the lock.

void push(T t_data) {
    pthread_mutex_lock(&m_qmtx);
    m_queue.push_back(t_data);
    pthread_mutex_unlock(&m_qmtx);

    pthread_cond_signal(&m_condv);
}

Since you should be using RAII for you locking anyway (See below) the signal is going to fall inside the lock stratergy unless you do something complex.

Also you should pass the parameter by const reference rather than value.

Normally front() is going to give you a reference to the front object.

T front() {
    T ret;
    pthread_mutex_lock(&m_qmtx);
    while (m_queue.empty()) {
        pthread_cond_wait(&m_condv, &m_qmtx);
    }
    ret = m_queue.front();
    pthread_mutex_unlock(&m_qmtx);
    return ret;
}

Returning a copy is probably not what you want (especially for anything interesting). But returning a reference is not really an option either as that opens you to situations where you have race conditions (you have a reference to the top object and another thread pops it (destroying it) just before you call a method).

So you need to provide a method for accessing the object while maintaining the lock (this will probably require the return of a wrapper object that maintains a lock on the queue) or alternatively removing this function.

Other non C++ things that should be addressed:

The mutex should be locked/unlocked using RAII. You are leaving your code open to exception handling problems. If an exception is generated by T which you have no control over then you could leave your queue in an unusable state with the mutex locked and no way to unlock it (because the stack of the locker has been unwound past the unlock because of an exception).

Yes this is correct:

   if (!m_queue.empty())
        m_queue.pop_front();

But don't get into bad habbits. No using the braces can lead to maintenance problems on C/C++ code because of macros. Best practice dictates that you always use {} for sub statements of if/while/for.

To make the code easy to read when including the code in the interface declaration put the variables at the top. Thus you can read the code in with the context of the variables and knowing their type. If you interface declaration is just an interface (and the code is put in the source file rather than the header) then it is fine to put the private variables at the bottom.


Fetching and formatting content from a database

I would make a single file with the MySQL server connection, so you can use the same connection in other functions, etc..

Also you should pass string variables directly.

$stmt->prepare("SELECT COUNT(*) AS count FROM public  $selection");

Did you know, that you can check every single called function if a error occurred?
For example:

if(!($stmt->execute()) {
   die('Unable to execute!'. $mysqli->error);
}

The next point is, why do you execute another query to count the result rows?
In the mysqli_stmt object $num_rows. http://php.net/manual/en/mysqli-stmt.num-rows.php


Review

Well written API, but I am not happy with this one:

traverse({ preorder, postorder, levelorder })

preorder and postorder can be combined, but they are always mutually exclusive with levelorder.

traverse({ preorder, postorder, levelorder }) {
  if (levelorder) {
      // levelorder ..
  }
  else {
      // preorder conditional and/or postorder conditional ..
  }
  return this;
}

Instead, use 2 separate methods, each doing their own well known type of traversal.

DFS

 traverseDepthFirst({ preorder, postorder })

BFS

 traverseBreadthFirst({ levelorder })

Some general thoughts:

should you allow cyclic graphs?
should you want to traverse up the ancestors?


Find the number surrounded by square braces using regex

You don't need the grouping here, and also you'd want to match for 1 or more digits: "\[\d+\]"


Shortening list of arguments to some kind of a variadic function

This will depend on whether or not all of the indicators you're interested in passing have the same generic type arguments. If they do then iSR5's solution is the simplest.
If not then you'll need a more complicated solution. On one hand I notice that you're not using any of the outputs of ComputeNextValue; you're only providing inputs to the indicators. Then one possible solution would be to define an interface with the void counterpart of ComputeNextValue which only takes an input and produces no output:
public abstract class IndicatorBase<TInput, TOutput> : IIndicatorBase<TInput>
    where TInput : struct
    where TOutput : struct
{
    public abstract TOutput ComputeNextValue(TInput input);
    public abstract void Reset();

    void IIndicatorBase<TInput>.ComputeNextValue(TInput input) =>
         ((IndicatorBase<TInput, TOutput>)this).ComputeNextValue(input);
}

public interface IIndicatorBase<TInput>
    where TInput: struct
{
    void ComputeNextValue(TInput input);
}

Then ImportAndPreload can become this: (I'm not sure what BinanceKline is, but the input type you're supplying to each indicator is the type of BinanceKline.Close, so that'd be the generic type argument for IIndicatorBase)
private void ImportAndPreload(string symbol, KlineInterval interval, params IIndicatorBase<TypeOfBinanceKlineDotClose>[] indicators)
{
    ...

    // Preload indicators
    for (int i = 0; i < candles.Count; i++)
    {
        foreach (var indicator in indicators)
        {
            indicator.ComputeNextValue(candles[i].Close);
        }
    }
}

...

ImportAndPreload(symbol, interval, macd, stoch, rsi, ema);

This will support any indicator whose input is the type of BinanceKline.Close.


Finding recessions in US GDP data using pandas

Your function does too many things: reading Excel file, filtering necessary rows, and calculating the "recession_start". My advice is to take the first two out.

Also, supply quarters and GDP as separate objects (pd.Series) to the function instead of the DataFrame. Like this you will remove hardcoded strings from your function, and, what's more important, you will get rid of SettingWithCopyWarning that you should get right now:

df = pd.read_excel('gdplev.xls',
                   names=['Quarter', 'GDP in 2009 dollars'],
                   usecols='E,G',
                   skiprows=7)
mask = df['Quarter'] >= '2000q1'
print(get_recession_start(quarters=df.loc[mask, 'Quarter'],
                          gdps=df.loc[mask, 'GDP in 2009 dollars']))

Note that I use usecols instead of parse_cols as it is deprecated. Also, I removed df.query in favor of boolean masking and .loc.

Then, the function would look like this:

def get_recession_start(quarters: pd.Series,
                        gdps: pd.Series) -> str:
    """
    Returns the year and quarter of the recession start time
    as a string value in a format such as 2005q3
    """
    growth = gdps.pct_change()
    recession = (growth < 0) & (growth.shift(-1) < 0)
    recession = recession.reset_index(drop=True)
    return quarters.iloc[recession.idxmax()]

Here I also used triple double quotes for the docstring and type hints. IMHO, this looks much cleaner.

Probably, it would also make sense to return only the recession.idxmax() index and get corresponding quarters value outside of the function.


Without locking, this works for me:

class proxy
{
public:
    proxy()
      : m_impl(make_impl()) {}

    void method()
    {
        m_impl.method();
    }
private:
    struct Impl
    {
        Impl() {}
        ~Impl() {}
        void method() {}
    };

    Impl& m_impl;
    Impl& make_impl()
    {
        static Impl impl;
        return impl;
    }
};

When locking, you need to synchronize access to the static impl in make_impl and you need to secure the call to m_impl.method().


As a key area of concern with this code, you really should be passing a cancellation token here, as it is a long running operation.

You need to worry about the client giving up on the request, let's say they navigated to the URL and decided they didn't mean to. The operation will still continue to run until the thread operation is complete.

This kind of issue can also lead to all kinds of problems.

Note that this can also occur when there multiple requests (say an impatient user hits refresh frequently) or a lot of traffic.


I'll first comment on only C++ usage.

vector -- Not exactly sure what you're trying to do by inserting into the front of an array (basically the worst case usage); if you're trying to append, the best way is
result.insert(result.end(), f1.begin(), f1.end());
Vectors are inserted at their end, not front.
map -- std::map is usually implemented as a tree offering O(lgn) queries, not O(1) as you might expect. If you're looking for a hashtable, use std::unordered_map. (however for small use cases and depending on the complexity of the type to hash, map might be faster).
uint32_t is an unsigned 32 bit integer. Use it if you want a guarantee on its size, as unsigned int, unsigned long, and the like depends on architecture and compiler. It is not necessary here (more on that later). This might be helpful:
On the contrary, you are doing it right by returning a std::vector by value. If it's not copy elisioned out entirely, standard library containers come with move constructors (C++11) that make them more efficient to pass out by value than by reference or pointer as some people are in the habit of doing.

OK onto the comments on style and algorithm

I personally find it easier to build programs using templates. For example,
template <typename Num>
std::vector<Num> primeFactorize(Num n)
is more intuitive for me than a function that's forced to take an int.
Avoid needless recursion (especially when it splits into 2 subproblems). Prime factorization can be done iteratively (and I'd argue more intuitively).
Avoid unbalanced divide and conquer algorithms. Here you're dividing the problem by primeFactorize(i), primeFactorize(n / i), which creates a tiny subproblem and a slightly smaller subproblem, which makes O(lgn) algorithms into O(n).
Write comments for yourself to read explaining the algorithm to ensure its correctness and function. For example, when n % i == 0, that means i is a divisor of n. If you wrote that down, you might come to the logical conclusion that you could safely result.push_back(i) and n /= i here instead of the relatively expensive recursion and inserts.
Design algorithms that have nice properties, for example that the factors come in sorted order. This prevents you from having to create the map, which seems terribly redundant (apart from perhaps educational uses). The alternative is the sort the factors, then iterate and count consecutive ones, which results in O(nlgn) operations, just as your map solution uses (as it loops through all n factors, and does a lookup in O(lgn) operations).

Here is my example implementation which gives the factors in sorted order using relatively cheap operations.

template <typename T>
std::vector<T> factorize(T num) {   // works great for smooth numbers
    vector<T> v;
    if (num < 4) { v.push_back(num); return v; }
    T d {2};
    while (num >= d * d) {
        while (num % d == 0) {  // remove all repeats of this divisor
            v.push_back(d);
            num /= d;
        }
        ++d;
        if (d * d > num && num > 1) { v.push_back(num); return v; }
    }
    return v;
}

Possible optimization suggested by Goswin with removing factors of 2

template <typename T>
vector<T> factorize(T num) {    // works great for small prime factors
    vector<T> v;
    if (num < 4) { v.push_back(num); return v; }
    while ((num & 1) == 0) { v.push_back(2); num >>= 1; }   // remove all factors of 2
    T d {3};
    while (num >= d * d) {
        while (num % d == 0) {  // remove all repeats of this divisor
            v.push_back(d);
            num /= d;
        }
        d += 2;
        if (d * d > num && num > 1) { v.push_back(num); return v; }
    }
    return v;
}

Note that you no longer need to use a std::map to find out how many of each factor there are since this algorithms gives them in sorted order. Using a std::map on top of this would just be an unnecessary layer.

For more straightforward(mostly) implementation of various algorithms (they could be quite educational), check out my simple algorithms library


Your class has 4 methods:

int[] LeftRotate(int, int[], int[])
int[] LeftRotate(int, int[])
int[] printArray(int[])
void main(String[])

The second method is never called, and can be removed.

The first and third methods (and the second) all return an int[], the a parameter, but the returned values are never assigned to anything.  This return value can be removed, and the methods declared to return void.

In the first method, you are looping over increasing i values, decrementing n1, and assigning to a[a.length - n1].  This “double negative” makes the code harder to understand; decrementing n1 increases the destination index value.  You already have a i index which in incrementing.  You could instead:

for(int i = 0; i < numberOfLeftRotations; i++) {
    a[a.length - numberOfLeftRotations + i] = b[i];
}

This is a little easier to understand; you are only changing i, increasing it, and adding it to a starting point for the destination.  We can make it a little clearer:

int dest_start = a.length - numberOfLeftRotations;
for(int i = 0; i < numberOfLeftRotations; i++) {
    a[dest_start + i] = b[i];
}

That is much more understandable.  Do the same for the second loop.

The above is just a cleanup of your existing code.  We can restructure / refactor the code to make it better and easier to use.

When you want to left-rotate an array, you always need to create a new array for the destination.  You can make the left-rotate function create the destination array for the caller.

int[] LeftRotate(int numberOfLeftRotations, int[] source) {
    int[] dest = new int[source.length];
    // ... copy rotated version from dest into source
    return dest;
}

And use it as:

int[] b = LeftRotation(l, a);

In fact, this is probably what was intended for your second method.  The code to copy the rotated version from dest to source could just be a call of the first “helper” method:

int[] LeftRotate(int numberOfLeftRotations, int[] source) {
    int[] dest = new int[source.length];
    LeftRotate(numberOfLeftRotations, dest, source);
    return dest;
}

Your first method should still be void, as it is not returning anything that wasn’t just passed to it.

Copying sequential elements from one array to another is a common operation, and Java provides a method which does just that: System.arraycopy().  Using this, your left rotation can be performed very efficiently in two statements:

System.arraycopy(source, 0, dest, dest.length - numberOfLeftRotations, numberOfLeftRotations);
System.arraycopy(source, numberOfLeftRotations, dest, 0, dest.length - numberOfLeftRotations);

Use better variable names.  a and b are unclear; source and dest give context to the reader.  numberOfLeftRotations is a very descriptive, but it is perhaps a little long.  numLeftRotations is just as clear and doesn’t result in lines becoming excessively long.  numRotations or rotations might be even better; the reader would know they are left rotations, because the variables are contained within a “left rotate” function.

Convention is for only Class names to begin with upper case letters; method names should not.  You should name the method leftRotate, not LeftRotate.


Decreasing the runtime of this non-abundant sums solution

After some tests (adding more time-points), we can find that the double for-loop used to find all abundant numbers is the slowest. Now we can think about speeding it up, by shortening the inner loop. We start with sum=1 and try every number we find can divide i upto sqrt(i). We immediatelly know that the product will of course divide the number as well, but need to take special care for numbers of the form i=j*j.

//  stop is the biggest integer such that stop*stop <= i
//  the reasoning behind using it is similar to the reasoning for using it in first phase
//  when marking all primes, but we need to take care for div=i/j when i%j == 0
    int sum = 1, stop = sqrt(i);
    for(int j = 2;;)
    {
        int div = i/j;         // divison and modulo will probably be optimized
        int mod = i%j;         // as one instruction (we could use some divmod built-in)

        if(mod == 0)           // when this condition is met we know that:
        {                      // i = j*div
            if(j == div)
            {                  // but can be i = j*j when j=div
                sum += j;      // we need to sum it only once in such case (e.g. 16=4*4)
                break;         // and can exit the loop, because j=stop here
            }
            sum += j+div;      // this is the tricky part when we sum both j and div
        }                      // e.g. for 15: 1 + 3+5 (j=3, div=5, stop=3 here)
        if(++j > stop)
            break;             // moving the condition here is another optimization
    }                          // ...and could be rewritten as do-while loop

The original code needed more than 8.8s on my old PC, but the current version needs only 0.11s. Full code:

#include <chrono>
#include <iostream>
#include <algorithm>

using the_clock = std::chrono::high_resolution_clock;
using time_point = the_clock::time_point;
using time_span = std::chrono::duration<double>;

// all integers greater than 28123 can be written as the sum of two abundant numbers
static const int LIMIT = 28124;
// smallest abundant number is 12
static const int minAbundant = 12;

// all prime numbers will have false in this array
static bool not_prime[LIMIT+1]; // zero initialized
static const int maxPrimeRoot = (int)sqrt(LIMIT);
static inline bool is_prime(int x) {
    return !not_prime[x];
}

// all abundant numbers
static const int abundantSz = 6965; // we know that, see final output
static int abundant[abundantSz];

// all numbers that are sum of abundant numbers will be marked true here
static bool isSumOfAb[LIMIT];

int main()
{
//  1. Mark all primes:
    time_point t1 = the_clock::now();

    for(int i = 2; i <= maxPrimeRoot; i++)
    {
        if(is_prime(i))
        {
            for(int j = (i*i); j <= LIMIT; j += i)
                not_prime[j] = true;
        }
    }

//  2. Find all abundant numbers
    time_point t2 = the_clock::now();

    abundant[0] = minAbundant;
    int count = 1;
    for(int i = minAbundant+1; i < LIMIT; ++i)
    {
        if(is_prime(i)) // Prime numbers won't be abundant, so next number
            continue;

    //  BIG CHANGE HERE
    //  we sum both the number we find can divide i
    //  and the product + stop after sqrt(i)
    //  we need to take special care for numbers of the form i*i (e.g. 16=4*4)
        int sum = 1, stop = sqrt(i);
        for(int j = 2;;)
        {
            int div = i/j;
            int mod = i%j;
            if(mod == 0) {
                if(j == div) {
                    sum += j;
                    break; }
                sum += j+div;
            }
            if(++j > stop)
                break;
        }

        if(sum > i)
        {
            abundant[count] = i;
            ++count;
        }
    }

//  3. Mark are numbers that are sum of abundant numbers
    time_point t3 = the_clock::now();

    for(int i = 0; i < count; ++i)
    {
        int a = abundant[i];

        for(int j = i; j < count; j++)
        {
            int c = a + abundant[j];
            if(c > LIMIT)
                break;
            isSumOfAb[c] = true;
        }
    }

//  4. Sum them all
    time_point t4 = the_clock::now();

    int sum = 0;
    for(int i = 24; i < LIMIT; ++i) //can start at 24, as that is the 1st sum of 2 abundant numbers
    {
        if(!isSumOfAb[i])
            sum += i;
    }

//  Output
    time_point t5 = the_clock::now();
    using std::cout;
    cout << "Sum: " <<  sum;
    cout << "\nIt took me " << time_span(t5-t1).count() << " seconds.";
    cout << "\nTimes: " << time_span(t2 - t1).count()
        << ", " << time_span(t3 - t2).count()
        << ", " << time_span(t4 - t3).count()
        << ", " << time_span(t5 - t4).count();
    cout << "\nAbundant count: " << count; // just a check

    if(sum != 4179595)
        cout << "\nERROR - bad sum\n";
}

You can see I have moved few variables outside main() and added few using to reduce the code a bit. But I am really not the one to talk about code-styling :D


Find the smallest number whose sum of digits add to a number

I am struggling to understand your algorithm. I don't fathom why you have to go through all that work of adding digits to values when the math behind this problem is so much simpler.

The smallest value will always be a digit followed by nines. The number of nines is the number of whole times 9 divides in to the value, and the first digit is the remainder.

Mathematically this translates to like:

public static int getVal(int val) {
    val = Math.abs(val);
    int ninecount =  val / 9;
    int remainder = val % 9;
    int scale = (int)Math.pow(10, ninecount);
    int result = remainder * scale + (scale - 1);
    return result;
}

Which is an O(1) operation (or, as has been pointed out by James, the complexity of this function is dependent on the complexity of Math.pow(...,...)). If you want to keep O(1) complexity you can precompute the scale for valid ranges of ninecount. The largest possible ninecount for an int result is 9, and for a long result it is 19. This is a small data set to keep in an indexed array accessed with int scale = scales[ninecount];


Mean of integers, ignoring the largest and smallest values

Well, whenever you want to know which function is better, you should test them.

First, your custom functions are just re-inventing the wheel, so you should only use them if you have to (either because it is mandated or they are actually faster, more secure, more memory-friendly, more whatever).

When running your functions with growing number of numbers, this is what I get:

Here, Input is the length of the numbers list, generated with numpy.random.random_integers(-10, 10, size=n), with \$n\in [10, 10000]\$.

So, for larger lists, the difference between your own function and the sorting function is negligible. The sorting should be \$\mathcal{O}(n\log n)\$, but I don't see why your function seems to show a similar behavior.

The sum/min/max function should be \$\mathcal{O}(3n)\$, so wins for large lists.

For smaller sizes, the two simple implementations perform similarly and your functions slightly slower:

This is for numpy.random.random_integers(-100, 100, size=n), with \$n\in [10, 100]\$.

All measurements were done in Python 2.7.13. I put your last two snippets into functions:

def centered_average_sum(numbers):
    return (sum(numbers) - max(numbers) - min(numbers)) // (len(numbers) - 2)

def centered_average_sort(numbers):
    centered_numbers = sorted(numbers)[1:-1]
    return sum(centered_numbers) // len(centered_numbers)

Note that I fixed a superfluous closing bracket on the second function.


Suggestions for improvement on Project Euler #7

You have a proliferation of cryptically named variables, making your code hard to follow.

Variables j and k are only ever used inside the while (true) loop, so they should be declared in a tighter scope.  There is no need to reset j after the loop.  Also, it would be easier to understand your code if you reset k = 0 before the loop rather than afterwards.  The while (true) loop could be simplified to:

for (int k = 0; ; k++) {
    int j = (i * i) + (k * i);
    if (j > n) {
        break;
    }
    primeMap.put(j, false);
}

Then, why not eliminate k altogether?

for (int j = i * i; j <= n; j += i) {
    primeMap.put(j, false);
}

I don't see why you set n = x ⌈√x / 10⌉.  It seems that you chose it as an estimate for the upper bound of your answer, though I don't understand the justification.  The answer should be somewhere around px ≈ x  ln(x).

In the end, it's not really important how you arrived at n, as long as it is large enough.  An explanatory comment would have been appreciated, though.

Using a HashMap to implement the Sieve of Eratosthenes is not a great idea, because:

You want to iterate through the results consecutively
All of the keys were initially consecutive
Internally, it will be hashing each key to another number

It would be a lot simpler if you simply used an array of booleans.


Typewriter animation, implemented using recursive asynchronous function

Recursion is a state stack.
Function context
Every time a function is called JS creates a new context (function state), even if the function does nothing, creates no variables, has no arguments, only calls another function, it still requires its own context. The process of creating and pushing to the heap costs memory and processing time.
The minimum memory cost varies between JS engines, but 1K is a reasonable estimate for an empty context.
Note The exception is Proper tail call Functions that by nature of the return, may not require their own context, they use the calling functions context. (No browser current lets you use this ES6 required standard feature)
Recursive state stack
In general recursion is used as a way create a state stack. Each iteration (recursive) call creates a new function context, with closure that is pushed to the heap.
When the a function exits its state is deleted popped from the heap and the calling function's state is reinstated from the heap.
Example showing states pushed and popped
The following illustrates the state stack. The state includes a random value. Each iteration waits 200ms before creating the next. When the recursion exits each state is popped from the heap, the functions complete execution until the stack is clear.

    function resolveAfter200ms(x) {
      return new Promise(resolve => {
        setTimeout(() => resolve() , 200);
      });
    };
    async function test(count){
        const rand = Math.random() * 100 | 0;
        log(` push ${rand}`);
        if(count < 10){

            await resolveAfter200ms(count);
            await test(count+1);
        } else {
           log("
Top of stack
Popping function context states from heap
");
        }
        log(` pop ${rand}`);

        if(count === 0){
           log("
Iteration complete");
        }
    }
    function log(data){
        document.body.innerHTML += `<span>${data}</span>`;
    }
    test(0);

Why this makes your function bad.
Saving state to a stack is great when you have complex or branching data structures that you need to iterate.
Saving an irreverent state on the other hand is not so great. In fact I would say using an aysnc function to step over animation frames via recursion is about the worst way to create an animation.
If you have 200 characters to animate by the time they have all completed (the last recursive call) you have 200 function states on the heap.
I would estimate that the memory usage of a 200 character animation to be about 200K +, though that is nothing, I have seen people chew 1Meg just to add two integers in JavaScript (crazy eh!).
Luckily JavaScript makes such wasteful resource usage transparent, by providing ample memory and a gaggle of resource management threads to contain and clean up so from your point of view everything is running slick..
Another way.
I am a little long in the tooth and come from a time where 1K was all we had. I can not write code without a device angel whispering thoughts of "conserve, speed and memory"
So I would have written your code as follows if the requirement was to use async functions, and assuming that the waitAfter value is many times greater than 60fps.
// Note dont need text position (n)
async function typeWriter(text, elementId, waitAfter) {
    var n = 0;
    // Following DOM query only done once saving lots of time
    const el = document.getElementById(elementId);

    const wait = () => new Promise(r => setTimeout(r, waitAfter));

    // Preventing re flow overhead by using textContent rather than innerHTML
    const render = () => el.textContent = (text.substring(0, n + 1));

    while (n < text.length) {
        requestAnimationFrame(render);  // Calls existing function
                                        // thus avoid unneeded function state capture
                                        // via closure

        await wait();

        n++;                            // add after await so render gets
                                        // the correct value
    }
}

From an external view its behaviour is identical, from a resource point of view its is remarkably different, will much lower memory use and associated GC overhead upon exit. It can also handle any size text, unlike the recursive method was limited to the available call stack size.


Reverse Polish Notation Calculator in Java

Your parseExpression() function isn't parsing anything.  Rather, it sanitizes the string.  Sanitizing input is a rather risky business.  For example, any decimal points will be discarded!  What if I try to use ! as the factorial operator?  That would be silently ignored as well.  If you can't handle the input in a reasonable way, it should be an error.

It's odd that you convert args from an array to a string, then split it up again.  You could either use args directly, or split just args[0].

Catching Throwable is probably a bad idea.  Anything that is not an Exception is generally not meant to be caught and handled.

It's actually not true that you cannot divide by zero.  That's an error only when performing integer arithmetic.  Why not let Double.POSITIVE_INFINITY be a valid result?

The code would be simpler if you didn't assign to variables firstOperand and secondOperand.  I'd write it more like this:

import java.util.*;

public class RPN {

    /**
     * Computes the outcome of a given expression in Reverse Polish Notation
     *
     * @param expr the expression to compute
     */
    public static void compute(String expr) throws
            ArithmeticException,
            EmptyStackException {
        Stack<Double> stack = new Stack<>();

        System.out.println(expr);
        System.out.println("Input\tOperation\tStack after");

        for (String token : expr.split("\\s+")) {
            System.out.print(token + "\t");
            switch (token) {
                case "+":
                    System.out.print("Operate\t\t");
                    stack.push(stack.pop() + stack.pop());
                    break;
                case "-":
                    System.out.print("Operate\t\t");
                    stack.push(-stack.pop() + stack.pop());
                    break;
                case "*":
                    System.out.print("Operate\t\t");
                    stack.push(stack.pop() * stack.pop());
                    break;
                case "/":
                    System.out.print("Operate\t\t");
                    double divisor = stack.pop();
                    stack.push(stack.pop() / divisor);
                    break;
                case "^":
                    System.out.print("Operate\t\t");
                    double exponent = stack.pop();
                    stack.push(Math.pow(stack.pop(), exponent));
                    break;
                default:
                    System.out.print("Push\t\t");
                    stack.push(Double.parseDouble(token));
                    break;
            }

            System.out.println(stack);
        }

        System.out.println("Final Answer: " + stack.pop());
    }

    /**
     * Runs the calculation for the RPN expression in args[0].
     */
    public static void main(String[] args) {
        try {
            compute(args[0]);
        } catch (Exception err) {
            System.out.println(err.getMessage());
        }
    }
}

Sample run:

$ java RPN '3 5 +'
3 5 +
Input   Operation   Stack after
3   Push        [3.0]
5   Push        [3.0, 5.0]
+   Operate     [8.0]
Final Answer: 8.0


Permutation of list in Python so that list[x] != list[x+1]

Would some pseudo-code be enough for you?

Build a collections.Counter (dictionary subclass) of the elements in the list.
output list = []
previous element = None
Loop for the length of the list:
    Pick the most frequent element that is not the previous one.
    Append this to the output list.
    Decrement its count.

return the output list

There are efficient ways to order the list count entries and maintain the ordering to facilitate choosing the proper next element.  A simple one is to order the initial list of counts by frequency.  At each iteration, choose the first element.  Decrement the count and sort it into the rest of the array, but insist on moving it down at least one position.  Repeat until all counts are 0.

I found a later use for this algorithm, so I coded it up.  I included a tracing print statement in the critical loop, so we can watch it in operation.

import collections

def unsort(in_list):
    size = len(in_list)
    if size == 0:
        return None

    # Build a list of pairs: value and count,
    #   in descending order of count.
    count_dict = collections.Counter(in_list)
    count_list = sorted(list(count_dict.iteritems()), key=lambda x: x[1], reverse=True)
    move_list = [[x[0], x[1]] for x in count_list]
    out_list = []

    # If the highest count is more than half the elements plus a half, no solution is possible.
    if move_list[0][1] * 2 > size + 1:
        print "No solution possible"
        return

    # In each iteration, grab the element at the head of the list.
    # Place that value into the output queue.
    # Sort the element back into the list,
    #   moving it at least one element down to avoid repetition.
    for _ in range(size):
        first = move_list.pop(0)
        out_list.append(first[0])
        first[1] -= 1
        for i in range(1, len(move_list)):
            if first[1] > move_list[i][1]:
                move_list.insert(i, first)
                break
        else:
            move_list.append(first)
        print move_list, out_list

    return out_list

# Main program -- test driver
a, b, c, = 'a', 'b', 'c'    # easier notation for test cases
test_case = [
    [],
    [c, c, b, b, b, a, b, c, b],
    [c, c, b, b, b, b, b, c, b],    # Too many b's'
]

for case in test_case:
    print unsort(case), '\n'

Output:

Input: []
None

Input: ['c', 'c', 'b', 'b', 'b', 'a', 'b', 'c', 'b']
[['c', 3], ['b', 4], ['a', 1]] ['b']
[['b', 4], ['c', 2], ['a', 1]] ['b', 'c']
[['c', 2], ['b', 3], ['a', 1]] ['b', 'c', 'b']
[['b', 3], ['a', 1], ['c', 1]] ['b', 'c', 'b', 'c']
[['a', 1], ['b', 2], ['c', 1]] ['b', 'c', 'b', 'c', 'b']
[['b', 2], ['c', 1], ['a', 0]] ['b', 'c', 'b', 'c', 'b', 'a']
[['c', 1], ['b', 1], ['a', 0]] ['b', 'c', 'b', 'c', 'b', 'a', 'b']
[['b', 1], ['a', 0], ['c', 0]] ['b', 'c', 'b', 'c', 'b', 'a', 'b', 'c']
[['a', 0], ['c', 0], ['b', 0]] ['b', 'c', 'b', 'c', 'b', 'a', 'b', 'c', 'b']
['b', 'c', 'b', 'c', 'b', 'a', 'b', 'c', 'b']

Input: ['c', 'c', 'b', 'b', 'b', 'b', 'b', 'c', 'b']
No solution possible
None


Python finding next word permutation with function generator

1. Review

The name nextperm is misleading as (i) it generates permutations that precede its argument; (ii) it generates multiple permutations, not just one. So a name like preceding_permutations would be clearer.
There is no need for try: ... finally: or raise StopIteration or return. If we try to get additional values from a generator that has finished, then Python automatically raises StopIteration. For example:

>>> def generator():
...     yield 1
>>> g = generator()
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

It's not necessary to convert word to a list on each iteration of the while loop, because on subsequent iterations we already have this list in the variable wordlist.
All the permutations are the same length, so it is not necessary to reassign length on each loop.
This loop goes all the way down to index_1:

for index_2 in range(length, index_1-1, -1):

But when index_2 == index_1, the condition wordlist[index_2] < wordlist[index_1] can never be true. So this iteration is wasted. It would be better to write the second loop like this:

for index_2 in range(length, index_1, -1):

Reversed ranges are quite tricky to reason about, and this kind of mistake is easy to make, so we should consider using reversed instead to make things simpler:

for index_2 in reversed(range(index_1 + 1, length + 1)):

(And similarly for index_1.)
When I read the name "length", I expect this to be the length of the word, not the length of the word minus one. So it would be easier to follow the logic if we had length = len(wordlist), and adjusted the ranges accordingly.
The code reverses the last part of wordlist, leaving the first part unchanged:

_first = wordlist[0:index_1+1]
_second = wordlist[-1:index_1:-1]
wordlist = _first + _second

It would make sense to implement this using a slice assignment:

wordlist[index_1 + 1:] = reversed(wordlist[index_1 + 1:])

This has several advantages: we avoid having to take the slice for the first part of the list, we reuse the memory in wordlist, and the use of reversed makes it clear what is happenig and reduces the risk of getting the slice indexes wrong.
The names index_1 and index_2 are used a lot: it would shorten the code and make it easier to read if we had names like i and j.
The stoploop logic can be removed if we introduce a local function that generates pairs of indexes:

def indexes():
    for i in reversed(range(length - 1)):
        for j in reversed(range(i + 1, length)):
            yield i, j

Now the two loops over the indexes can be combined into one:

for i, j in indexes():

and since we now have a single loop, we can break out of it using break, with no need for stoploop.

2. Revised code

def preceding_permutations(word):
    """Generate the permutations of word that precede it, in reverse
    lexicographical order.

    >>> ' '.join(preceding_permutations('bdca'))
    'bdac bcda bcad badc bacd adcb adbc acdb acbd abdc abcd'

    """
    word = list(word)
    length = len(word)
    def indexes():
        for i in reversed(range(length - 1)):
            for j in reversed(range(i + 1, length)):
                yield i, j
    while True:
        for i, j in indexes():
            if word[j] < word[i]:
                word[j], word[i] = word[i], word[j]
                word[i + 1:] = reversed(word[i + 1:])
                yield ''.join(word)
                break
        else:
            break


Converting Geographic Coordinates into Lambert2008 coordinates

Since the code is about implementing mathematical formulas I would make an exception and completely ignore the usual naming conventions. Instead, I would use the exact symbols as  that document.

This would mean a little bit copy/paste because it's difficult to write symbols like [ϕ, λ, θ] but the compiler can work with unicode.

I find that code like this:

var rad = 0.01745329252;

var ellipsoide = (a: 6378137, f: 1 / 298.257222101);
var ϕ1 = 49.8333333 * rad;
var ϕ2 = 51.1666667 * rad;
var ϕ0 = 50.797815 * rad;
var λ0 = 4.359215833 * rad;
var x0 = 649328;
var y0 = 665262;

is the most easy one to understand because you can compare it with the book almost without any translation.


Minimum number of letters removed, to make a string Peragram

The approach you are taking is to remove letters until at most one of them has an odd count. Once you realise that, the solution becomes obvious:

from collections import Counter

s = input() # don't call your own variable 'str'

c = Counter(s)

odds = [None for n in c.values() if n % 2]

if odds:
    print(len(odds) - 1)
else:
    print(0)

collections.Counter is a dict subclass to make counting the letters simpler. You don't actually need to create the substrings or check whether they are peragrams.

You should read and consider following the style guide, PEP-0008. For example:

if(IsPalindrome(str)):

should be:

if is_palindrome(s):


Count line of code for a JavaScript project

fileExt="*.js"
allFiles=$(find ./ -name $fileExt)

This is a bug.  The wildcard in $fileExt will be expanded by the shell, and cause a syntax error when the current directory has more than one matching file in it:

$ touch a.js b.js
$ fileExt="*.js"
$ find ./ -name $fileExt
find: paths must precede expression: `b.js'
find: possible unquoted pattern after predicate `-name'?

You need to quote the variable.  Better yet, use the globstar option to populate an array and eliminate find altogether:

fileExt="js"
shopt -s globstar
declare -a allFiles=( **/*.$fileExt )
grep … "${allFiles[@]}" # to use the array

This regex does not match blank lines:

  grep '^[[:space:]]*//'

Just /* is enough to start a multi-line comment in JavaScript (not /**).

The script reads every file four times.  That is slow.  Since you're using Perl already, just let it count everything.  Then you don't need to capture the file names at all, since they are used only once:

#!/bin/bash
shopt -s globstar
exec perl -nle '
    BEGIN {
        @ARGV=grep -f, @ARGV or die "no matching files\n";
        $comment = $blank = 0;
    }
    if    ( m{ ^\s*/\* }x .. m{ \*/ }x   or   m{ ^\s*// }x ) { $comment++ }
    elsif ( m{ ^\s*$ }x ) { $blank++ }
    END { print "$comment comment lines; $blank blank lines; $. total lines" }
' **/*.js

At this point we're barely using bash anymore, and the globbing can be moved inside the Perl script, using the File::Find module:

#!/usr/bin/perl -wnl
BEGIN {
  use strict;
  use File::Find;
  my $ext="js";
  my @dirs=( @ARGV ? @ARGV : '.' );
  @ARGV=();
  find(sub { -f and /\.$ext$/o and push @ARGV, $File::Find::name }, @dirs );
  our ($comment, $blank) = (0, 0);
}

if    ( m{ ^\s*/\* }x .. m{ \*/ }x   or   m{ ^\s*// }x ) { $comment++ }
elsif ( m{ ^\s*$ }x ) { $blank++ }

END {
  print "$comment comment lines; $blank blank lines; $. total lines";
}


Updated:

Seems like C# has its own format specifier "R" Round trip

  The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value. This format is supported only for the Single, Double, and BigInteger types.

public static double RoundTrip(double d)
{
    return Double.Parse(d.ToString("R"));
}

Original:

The way to represent floating point numbers exactly on a stream in readable format is to print out there representation in hex format (rather than decimal):

Not sure how it is done in C# or Java but I bet if you dig the exact same method is used down deep in these languages.

In C++ and C the methods are the same.
The C++ version.

double x = 5.6789;

std::cout << x << "\n";   // Human readable dot format.
                          // Has loss of precision as number may not
                          // be exactly representable in decimal.

// This the equivalent of using the "%a" string formatter.
// fprintf(stdout, "%a\n", x);
//
std::cout.flags(std::ios_base::fixed | std::ios_base::scientific);
std::cout << x << "\n";   // Hex Format human readable (well nearly human readable)
                          // Prints each part of the float as a hex value
                          // That can be represented exactly.
                          // on a stream of char

Updated after reading: Printing double without losing precision

// In C++11 there is an additional manipulator
// that achieves the same affect.
std::cout << std::hexfloat << x << "\n";

The results:

5.6789                    // Easy to read (not exact)

0x1.6b7318fc50481p+2      // Difficult to read (but exact).

0x1.6b7318fc50481p+2      // Difficult to read (but exact).


So I've made a few modifications; here are the explanations:

Used interfaces a bit more liberally (IDictionary)
Made BaseClass implement ICacheable so the subclasses don't explicitly have to
Made fields readonly as appropriate to declare intent
Made field data private and exposed as protected by way of a property
Chained the BaseCache constructors
Created the storage dictionary in the constructor (could do this in Add if you were looking for lazy creation)
sealed subclasses (if they're intended to be non-inheritable, of course)

The code:

public interface ICacheable<TK, TV>
{
    TV Get(TK key);

    void Add(TK key, TV val);
}

public abstract class BaseCache<TK, TV> : ICacheable<TK, TV>
{
    private static readonly IDictionary<Guid, IDictionary<TK, TV>> data = new Dictionary<Guid, IDictionary<TK, TV>>();

    private readonly Guid storageNameSpace;

    protected BaseCache(Guid storageNameSpace)
    {
        this.storageNameSpace = storageNameSpace;
        data[this.storageNameSpace] = new Dictionary<TK, TV>();
    }

    protected BaseCache() : this (Guid.NewGuid())
    {
    }

    protected static IDictionary<Guid, IDictionary<TK, TV>> Data
    {
        get
        {
            return data;
        }
    }

    public TV Get(TK key)
    {
        return data[this.storageNameSpace][key];
    }

    public void Add(TK key, TV val)
    {
        data[this.storageNameSpace].Add(key, val);
    }
}

public sealed class KeyValCacheStorage<TK, TV> : BaseCache<TK, TV>
{
}

public sealed class KeyValCacheStorageSingleton<TK, TV> : BaseCache<TK, TV>
{
    private static readonly Guid storageNameSpace = Guid.NewGuid();

    public KeyValCacheStorageSingleton() : base(storageNameSpace)
    {
    }
}


First of all, the requirements are specific in requiring that you "use functions". I'm pretty sure the intent of that was the exact opposite of how you've structured the code, with everything in main.

You might want to consider some (more or less) top-down style development, where you write a simple main that has practically nothing except calls to lower-level functions. I'd do this by thinking of a short (word or two) summary describing each step in the specification, and use those as function names.

int main(void) {
    house_t houses[2];

    // 1. put initial population in each house:
    populate(houses[0]);
    populate(houses[1]);

    for (week = 1; week < N; week++) {
        // 2. each week, each house's population increases
        increase_pop(houses[0]);
        increase_pop(houses[1]);

        // 3. each week, a percentage of the population may migrate between the houses
        do_migration(houses[0], houses[1]);

        // 4. every four weeks, an exterminator visits one of the houses
        if (week % 4 == 0)
            exterminate(random_choice(houses, 2));

        // 5. Presumably we want to show the data for each house weekly.
        show(houses[0]);
        show(houses[1]);
    }
}

A few things about that code may be open to question -- for example, the spec doesn't seem to specify how to choose which house is exterminated at any given time. I've used a random_choice, but perhaps you think strict alternation makes more sense. In any case, however, The important point is that what we see here should be about as close as possible to a direct translation of the steps outlined in the requirement into the syntax of the target language. From there, we can define the sub-parts in relative isolation from each other.

Right now, this makes life much easier for your teacher: it's fairly easy to look through main and figure out whether it fits the requirements. He can then glance through each of the functions and see whether that function does what it's supposed to as well.

I'd also note that the same basic idea applies when school is over and you're writing real code. The big difference here is that you will spend a lot of time doing what the teacher is doing now, reading and analyzing code, not just writing it. In school, you tend to write code and (almost) never look at it again. In real life, you live with the code after you've written it.

I suspect that you have the idea of writing the code and getting it working, then breaking it up into functions. I'd advise against that. It makes the job considerably more difficult.

I'd also note how this changes the situation if (for example) you need/want to change the parameters. For example, assume you have 5 (or 50) houses in a row, and wanted to run the situation for a year instead of 10 weeks. With the code as I've written it above, that would mostly mean rewriting most of the code that explicitly refers to houses[0] or houses[1] to instead use loops and refer to houses[i]. Don't try to go overboard with this idea though. If you can make the code more flexible like this without adding extra complexity, great. At the same time, don't spend (much) extra time or work writing against possible changes in requirements that may never happen.


Calculate the cost of cement for a project

Buffer overflow
Consider what entering "295.8" does.
#define MAXDIGITS 5
char inp[MAXDIGITS];
printf("Please input the value of cement: ");
scanf("%s", inp);

Code used the dangerous scanf("%s", inp); with no width limits.  scanf("%s", inp); being ignorant of the size of inp[], stored the 5 read characters and the appended null character.
This results in undefined behavior (UB).  Code may work as expected today and fail in strange ways tomorrow.
I recommend to only use fgets() for user input.  After reading a line of user input, it is saved as a string.  Then parse the string.
No need for such a tight buffer size.  Recommend twice the expected max width needed.
#define BUFFER_SIZE (2*MAXDIGITS + 1)
char buffer[BUFFER_SIZE];

printf("Please input the value of cement: ");
fflush(stdout);  // Insure output is seen before reading

fgets(buffer, sizeof buffer, stdin);
double val = strtod(buffer, NULL);


Looks good. Few initial things:

Indent inside control structures, so everything inside your if() statement would be prefixed by one tab. (You can use a fixed number of spaces, but that can cause problems if you share your code with people who use a different tab-spacing system).
It is a really good idea to split out your code into logic (or "controller") and template (or "view"). Your html would then go in a different file and be loaded by your PHP file - a good first step with this sort of thing is Smarty. From there you can progress to a proper PHP framework such as Symfony or Zend (but be aware the learning curve is steep).
Tags such as  and <big> tend to be discouraged - use CSS instead.
Keep your PHP statements in your view as small as possible. For example I'd rewrite your score thus:

    You have <?php echo $current ?> points!

You'll need to define a CSS class called 'points', of course.


Javascript bar graph representation using CSS

Too many temporary variables

Try to reduce the number of local temporary variables as they make the code muddy and unnecessary complicated and difficult to change.

Example, these four lines could probably be reduced to a single line:

var barHeight = $(bar).height();
...
var containerHeight = $('.graph').height();
var marginTop = containerHeight - barHeight;
$(bar).css('margin-top', marginTop);

Could be:

$(bar).css('margin-top', $('.graph').height() - $(bar).height());

Delegate tasks to functions

It is not a bad thing to sometimes delegate to functions for clearity at the exepence of minor performance hit:

var graph = $('#bar-graph');
var graphWidth = graph.width();
var barWidth = $(bar).width();
var marginRight = ( graphWidth - (barWidth * barCount) ) / ( barCount - 1 );
$(".graph ul li").css('margin-right', marginRight);
$(".graph ul li:nth-last-child(2)").css('margin-right', (marginRight - 1) );

Could become:

$(".graph ul li").css('margin-right', getRightMargin(bar, barCount));
$(".graph ul li:nth-last-child(2)").css('margin-right', (getRightMargin(bar, barCount) - 1) );
...
function getRightMargin(bar, barCount) {
    var graphWidth = $('#bar-graph').width();
    var barWidth = $(bar).width();
    return ( graphWidth - (barWidth * barCount) ) / ( barCount - 1 );
}

This way the margin calculation will be done twice, but the performance implication in this case is negligible, the code however will be less noisy and more approachable.


Find all pairs of numbers such that the number of binary 1's in their OR is maximum

I don't have much time, and don't see any quick performance suggestions, but,

mat = []
for i in range(n):
    mat.append(input())

Can be written more terse as a list comprehension:

mat = [input() for _ in range(n)]

And note how you never use i. If you don't use a variable, you can indicate that it isn't needed by calling it _. That's a placeholder convention to say that "I needed to create a variable, but I don't need it".

count=count+1

can be

count += 1

Also, please be more careful with spaces around operators. In some places, you use no spaces, in some places you use one on each side, and then in one case, you have

nm =input().split()

I prefer one per side, but regardless of what you choose, you should be consistent.


Monitoring (i.e. loading updates) to log files

Looking at your code, it appears to be a django log. I'm not sure why you are reading logs with a webpage when you can always read them using the terminal. cat, grep, tailf and a few other commands would be your friends in this case.

As @Flambino mentioned, direct access to the log is a problem. If you are going to pursue this method, you should at least have the server side validate your access. You could use a login system, and if the user isn't logged in, you can simply throw a 403 (Forbidden) as the result of the AJAX. Otherwise, return the log contents.

Now back to the code. First off, you could wrap everything in a closure. That way, nothing is modifiable from the global scope. That prevents naming collisions and all that. At least your code is protected from other code that may reside in your page.

;(function(){

  // all your code here

}());

Next, you can use an AJAX library to abstract out your XHR code. That way, you don't have to deal with all the intricacies of XHR. A good minimum that I use, which is also forward-compatible, is using a Promise and fetch polyfill. Promise is needed for fetch to work. It's just under 20kb when minified. Rather big but keeps you sane.

fetch(url).then(function(response){
  // This is a required intermediate parsing step for fetch
  return response.text();
}).then(function(responseText){
  // Do what needs to be done with the log
}).catch(function(error){
  // Do what needs to be done during error
});

Another suggestion is to use a <textarea> instead of a <div> as your log output. That way, you don't have to deal with formatting, collapsing of tabs, escaping of characters. You can always set it to readonly to prevent editing, and modify scrollTop on update if ever you always want the bottom to be visible.

Sever logs can be huge and will have impact on your fetching operation. This happens especially if your team is using the logger extensively for easy debugging. I suggest you have some server-side logic to paginate your results and not just dump everything into the page.

I noticed your funny little characters for the title bar. While they are fun, not all computers might have those glyphs built in. On my rig, this character () doesn't appear, just a box with a question mark (or just a box on others). You might want to consider being creative in the ascii range of characters and not totally rely on these non-ascii ones. For example, this sequence -\|/- for a rotating bar.

On a side note, it appears as though you're trying to achieve something similar to what Scalyr does - a web-based log monitoring and search.


int e = 0;

You're initializing e to default(int), which is redundant. This would be enough:

int e;

I'm not quite sure why you're incrementing e like this:

while (number >= 10.0)
{
    e += 1;
    number /= 10;
}

Why not just e++;?

And same thing here:

while (e > 0)
{
    number *= 10;
    e -= 1;
}

There's e--; to decrement.

But you know this already:

figures--;

Why? Why are you using both -= 1 and -- in the same method?

figures += 0 - e;

Looks like a pretty convoluted way to do figures -= e;.

And then we get to the return value...

return number.ToString($"f{figures}");

You're using C# 6.0 string interpolation here. A format string. The SO question you linked to has an accepted answer that uses a format string to do all the work: it seems string.Format("{0:G10}", number) would do the formatting part just right - I'd parameterize the length by making a method that builds a format string from the parameter (something like "{0:G" + digits + "}"), and uses that format string to return the formatted string.

I think it would be easier to read and to follow, than the whole logic you got there.

Or, don't use a format string. IMO using a formatted string here defeats the purpose of reinventing the wheel.


PHP DAO classes inherit from a generic DAO classes and only change the table name

If the only difference between subclasses of DAO_DBRecord is the table name I wouldn't use subclasses. I'd just pass the table name to to the constructor of DAO_DBRecord and use different instances for different tables.

If the only difference between subclasses of DAO_DBRecord is the table name I would pass the name of the table to the constructor of the parent class:

class UserDao extends DAO_DBRecord {

    public function __construct($db) {
        parent::__construct($db, 'users');
    }
}

Having different classes improves type safety. In Java you can't pass a UserDao to a method with an ArticleDao parameter(1), it does not compile. I don't know whether this kind of type safety exists in PHP or not, but it could be a good practice and could results more readable code.

(1) Of course except if UserDao is a subclass of ArticleDao

I don't feel that making DAO_DBRecord class abstract would make a big difference. If your clients wants to misuse the class they can create a dummy (non-abstract) subclass for that:

class AnyDao extends DAO_DBRecord {

    public function __construct($db, $tableName) {
        parent::__construct($db, $tableName);
    }
}

If you want to protect DAO_DBRecord from instantiation with unknown table names make its constructor private and create static factory functions for your tables inside the DAO_DBRecord:

class DAO_DBrecord {
        private $db;
        private $tableName;

        private function __construct($db, $tableName) {
            $this->db = $db;
            $this->tableName = $tableName;
        }

        public static function createUserDao($db) {
            return new DAO_DBrecord($db, 'users');
        }

        public static function createArticleDao($db) {
            return new DAO_DBrecord($db, 'articles');
        }
        ...
}

So, DAO_DBrecord cannot be used with other tables.

If you use your table names only once creating constants for them looks unnecessary in this case.


Clean up PHP & MYSQL code (Picked up by Swift as blog reader iOS app)

Consider this:

<?php
    $dbhost     = "website";
    $dbuser     = "user";
    $dbpass     = "password";
    $dbname     = "database";
    $connection = mysql_connect($dbhost, $dbuser, $dbpass);
    //Kill page if connection could not be established
    //I also added mysql_error() for it to display an error if there was an issue, so you can troubleshoot.
    if(!$connection) {
        die("Connection Failed:" . mysql_error());
    }

    $dbconnect = mysql_select_db($dbname, $connection);
    //Same as before, kill page if there was an issue, and display an error.
    //No need for the IF-ELSE statements, if the `die()` function is hit, the page stops loading anyways.
    if(!$dbconnect) {
        die("Unable to connect to Database: " . mysql_error());
    }

    $query     = "SELECT * FROM blogs";
    $resultset = mysql_query($query, $connection);
    $records   = array();
    // Loop and check all records and add to array
    while($r = mysql_fetch_assoc($resultset)) {
        $records[] = $r;
    }
    // Output data as JSON
    echo json_encode($records);
?>

But I highly recommend switching to mysqli_* or PDO statements:

Please, don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process, and mysql_* functions have been officially removed in PHP 7. Instead you should learn about prepared statements and use either PDO or mysqli_*. If you can't decide, this article will help to choose your best option.

Here is a refactor to mysqli_*

<?php
    $dbhost     = "website";
    $dbuser     = "user";
    $dbpass     = "password";
    $dbname     = "database";

    $records   = array();

    $connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if($connection->connect_errno > 0){
        die('Unable to connect to database [' . $connection->connect_error . ']');
    }
    $query     = "SELECT * FROM blogs";
    if(!$result = $connection->query($query)){
        die('There was an error running the query [' . $connection->error . ']');
    }
    while($row = $result->fetch_assoc()){
        $records[] = $row;
    }
    echo json_encode($records);
?>

There are a couple of differences here, the first connection checks for an actual connection to the database AND to the table in 1 statement.

Another difference is it shows an error specifically for the query if there was a problem, and not for a table connection error in the 2nd error check.

Here is a PDO refactor:

  NOTE: I don't actively develop with PDO, I may have missed something here.

<?php
    $dbhost     = "website";
    $dbuser     = "user";
    $dbpass     = "password";
    $dbname     = "database";
    $charset = 'utf8';

    $records   = array();

    $dsn = "mysql:host=$dbhost;dbname=$dbname;charset=$charset";
    $opt = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $pdo = new PDO($dsn, $dbuser, $dbpass, $opt);

    $query     = "SELECT * FROM blogs";
    $stmt = $pdo->query($query);
    while ($row = $stmt->fetch()) {
        $records[] = $row;
    }
?>


On comments

# On button pressed handler
def btn_pressed(self, button):

I think you could rename the function to on_btn_pressed and just remove the comment, as it doesn't add any information that isn't already apparent from the function name.

There are several other comments that doesn't add anything useful, like

# Initializes players
def init_players(self):

and

# Checks winner after every move...
def check_winner(self):

and

self.make_random_move(board) # Do a random move

The comments describing the build and on_start functions could do with some more explanation, as it's not apparent to me how these are used (I'm assuming they are used by kivy.app.App?).

if len(button.text.strip()) < 1: # If the button has no mark, stripping spaces...

I would extract the above check into a function, like this:

if is_button_unmarked(button):
    free_buttons.append(button)
...

def is_button_unmarked(self, button):
    return len(button.text.strip()) < 1

thus eliminating the need for a comment.

You should strive to make the code self-documenting, and use comments when you fail to do that. I recommend reading rolfl's excellent answer to a codereview question about comments.

Constructor vs method injection

I would inject the game board into the Ai constructor

self.bot = Ai(self.choices[rand_choice], board)

and set it as you do with the choice

class Ai:
    def __init__(self, choice, board):
        self.choice = choice
        self.board = board

This way you can do

self.bot.make_move()

instead of

self.bot.make_move(self.board)

which is easier to understand. As the board is used by all the functions in Ai, there's currently no good reason not to inject it in the constructor.

Reuse

Your popup_message function lets you pass any message, but the title is hardcoded. You should send the title in as an argument as well, to make the popup_message function useable by more than welcome messages (maybe you'd want to use it after deciding a winner in check_winner?).


naked malloc calls

Note that malloc() simply allocates memory - you have no guarantees about what the newly allocated memory contains. For that reason it is better to write a function which both allocates and initializes an new object, i.e.:

node* newNode(int v) {
  node* p = (node*) malloc( sizeof(node) );
  // assume malloc never fails
  p->val = v;
  p->next = NULL;
  return p;
}

Now use newNode() where you are using malloc() directly.

make_ll

First of all, does your make_ll work for len = 0?

For comparison, here is a recursive solution for make_ll:

node* make_ll(int len) {
  if (len <= 0) {
    return NULL;        // a list of length 0
  } else {
    node *tail = make_ll(len-1);
    node *head = newNode(len);
    head->next = tail;
    return head;
  }
}

And here is a way I would transform this into a loop which avoids double checking the exit condition:

node* make_ll(int len) {
  if (len <= 0) {
    return NULL;
  }
  node* head = newNode(len);
  node* last = head;
  for (; len > 0; --len) {
    node* n = newNode(len);
    last->next = n;
    last = n;
  }
  return head;
}

The idea is to keep track of the last node in the chain so you can update its next field when you create a new node.


Counting only weekend days between two timestamps

I found the logic of the set operations a bit hard confusing.  It appears that the goal is to take some set of days, named days, and remove entries from it.  So, start with days and remove entries from it.  You don't need the other sets named outsideDays and dates.

It's weird that it.numberOfDaysOutsideCVB returns a set rather than a number, as suggested by the method name.

The looping mechanism is cumbersome:

def xx = new GregorianCalendar()
xx.setTimeInMillis(f.time.next().time)
f = xx

The l day is always removed, regardless of the day of the week.  That deserves an explanatory comment.  Furthermore, f and l are somewhat cryptic variable names.

Set days = DateUtils.businessDaysBetweenDates(it.entryTimestamp, it.exitTimestamp)
days.removeAll(it.numberOfDaysOutsideCVB)

def children = QueueEntry.findAllByParent(QueueEntry.findById(it.id))
for (QueueEntry qe : children) {
    def entry = new GregorianCalendar()
    entry.setTimeInMillis(DateUtils.getClearedTime(qe.entryTimestamp))
    def exit = new GregorianCalendar()
    exit.setTimeInMillis(DateUtils.getClearedTime(qe.exitTimestamp))

    entry.upto(exit.previous()) { day ->
        switch (day.get(Calendar.DAY_OF_WEEK)) {
          case Calendar.SATURDAY:
          case Calendar.SUNDAY:
            break
          default:
            days.remove(day.time.time)
        }
    }
    // Remove the last day regardless of day of week. (Why?)
    days.remove(exit.time.time)
}
turnTimes << days.size()


Get K most frequent tokens from a token stream

I feel my code is not concise enough

The feeling is mutual.

I feel that this can be expressed much more succinctly.

  I am not experienced using some new features in C++11.

You seem to be using range based for so not bad in that regards.

But. You do "probably" have a memory leak.

hash_table[token] = TokenInfo::TokenInfoPtr(new TokenInfo(token))
                                            ^^^^

Don't see a delete anywhere in the code. To be honest I doubt you actually need that new at all. If you just made your container hold objects all these problems would go away.

  I would be very appreciative if anyone could any suggestions on the algorithm, coding style, object-oriented design, etc.

Not sure that heap is the correct structure.

Sure it does sound correct initially. But you can increase the count of items that are already in the heap (which means you have to rebuild it from scratch).

I would just keep a sorted list of the top n items. When a count increases you at most need to move one item in the list.

I can't really review more than that because your code snipet is missing the most important thing. TYPE information.


Implementing division without addition, multiplication, division or subtraction - follow-up

Seems like the approach you've taken is to implement the + operator yourself. And when using the + operator on negative numbers, you've implemented your own - operator.

I have to congratulate you for being able to implement these operators from scratch. Good job.

A slight bug is that your code returns incorrect result for divide(-42, 6)

I believe the source of this bug is that this code is inside the while:

if (isNeg) {
    sign=!sign;
}

Put it outside the while and it seems to work (at least for my test case)

if (a < b) return 0;
else{

You can save yourself some trouble indentation by removing that else. As you return, you can keep on going without adding indentation. (Which is why I love early returns)

Your spacing is a bit off, the easiest way to fix this is to press Ctrl + Shift + F if you're using Eclipse, or Alt + Shift + F if you're using Netbeans.

For example, this line:

while(Math.abs(s)>=Math.abs(divisor)){

Would look better like this:

while (Math.abs(s) >= Math.abs(divisor)) {

quotient = add(0, -quotient);

As you're using a - sign there already, why not replace all this with -quotient?

You have three boolean values related to the positive/negative issue:

boolean isNeg = false;
boolean sign = true;
boolean bothNegative = false;

Only one would be enough:

boolean swapSign = a < 0 ^ b < 0;

This is using the boolean XOR operator (^), so this will be true if a is negative or b is negative, but not if both are negative.

int quotient = 1;
if (a < b) {
    return 0;
}

You're using a < b as a special case, but that's not necessary.

int s;

That's not a readable name.

You can get rid of several unnecessary variables by directly operating on the a and b values. As they're ints, they're value-typed and therefore copied and not sent by reference, which means that you can modify them however you'd like inside your method. They can be used just like normal local variables.

The main part of your method can be simply this:

a = Math.abs(a);
b = Math.abs(b);

int result = 0;
while (a >= b) {
    a = add(a, -b);
    result = add(result, 1);
}

Your logic for what to return is a bit bloated:

if (bothNegative) {
    return quotient;
}
else if (isNeg && !sign) {
    quotient = add(0, -quotient);
}
return quotient;

This can be replaced with, by using the single swapSign variable:

if (swapSign) {
    return -result;
}
else {
    return result;
}

Or even simpler, using the ternary operator:

return swapSign ? -result : result;

End result:

private static int divide(int a, int b) {
    boolean swapSign = a < 0 ^ b < 0;
    a = Math.abs(a);
    b = Math.abs(b);
    int result = 0;
    while (a >= b) {
        a = add(a, -b);
        result = add(result, 1);
    }
    return swapSign ? -result : result;
}


type/class __repr__ formatter for Python objects

This was answered in comments, but for completeness:

The name of a class is given by its __name__ attribute.
It's not a good idea to rely on dir to show you all the special methods and attributes. If you read the documentation you'll see that it says:

  The resulting list is not necessarily complete.

The place to look for documentation on special methods is the Data model section of the Python Language Reference.
Python 3.3 added __qualname__, which gives the qualified name, which is more informative than __name__ for nested class definitions.
__name__ doesn't include the module name, so collections.Counter.__name__ is just "Counter". If you want to prepend the module name, find it using the __module__ attribute.
True if not i else False is a long-winded way to write not i.
If possible, iterate over objects, not over indexes. Instead of:

is_empty = [ True  if not i else False for i in objs ]
t = [ type(i).__name__ for i in objs ]
for i in range(len(objs)):
    print("{:<15} {:<6} {:<10s}".format(objs[i],str(is_empty[i]),t[i]))

write:

for obj in objs:
    print("{!r:15} {!r:6} {:10}".format(obj, not obj, type(obj).__name__))


I think a way to make this code generally more efficient and predictable is to have your classes have a more defined role.  For example, it seems like you're defining an instance of Guess as myGuess, then externally loading in a random number (RndNum), and the current guess (UserGuess = GetUserGuess()).

You should clearly define the goals for classes, such as:

Manage the Game lifecycle.
Handle user input, ensuring the user enters only numbers and is properly prompted, etc.

In this way, your code might look more like this psuedo-code:

class GuessingGame
{
    static void Main(string[] args)
    {
        game = new GuessingGame();
        game.run();
    }

    int numGuesses;
    int correctNumber;
    UserInputHandler userInputHandler;

    GuessingGame(numGuesses = 4)
    {
        Random random = new Random();
        this.correctNumber = random.Next(10);
        this.numGuesses = numGuesses;
        this.userInputHandler = new UserInputHandler();
    }

    void run()
    {
        for (int thisGuess = 0; thisGuess < numGuesses; ++thisGuess)
        {
            Console.WriteLine(string.Format("Guess #{0}!\n", thisGuess + 1));
            guess = this.userInputHandler.getGuess();
            if (guess < this.correctNumber)
            {
                Console.WriteLine("WRONG! Try a higher number!");
            }
            else if (guess > this.correctNumber)
            {
                Console.WriteLine("WRONG! Try a lower number!");
            }
            else
            {
                win();
                return();
            }
        }
        lose();
    }

    void win()
    {
        Console.WriteLine("You WIN!  The number was indeed " + this.correctNumber);
    }

    void lose()
    {
        Console.WriteLine("You LOSE!  The number was " + this.correctNumber);
    }
}

// UserInputHandler Source
class UserInputHandler
{
    public int getGuess()
    {
        // Handle user input, and ensure the guesses are actually numbers.
    }
}

The idea is that each class is responsible for encapsulating one piece of functionality around another class.  The Main program entry point doesn't care about how the game works, the GuessingGame class doesn't care about interacting with the user at all, while the UserInputHandler class doesn't care about the correct answer, etc.

I've also wrapped the win/loss messages into a single method, so that you're not repeating the victory message.

Some benefits include:

Having a clear understanding of the role of each class.
Being able to assert that with unit tests easily.
Code reuse.  You could plug the UserInputClass into a different game that requires simple user input, for example.
Collaboration.  Properly scoped and documented code means other developers could jump into your project with less friction.

Now this example is a bit much considering that a guessing game is fairly basic, but it's good practice for tackling larger projects.


In AngularJS, create lots of directives or use ng-controller?

AngularJS encourages slim controllers. They'd rather you have fat directives and services than controllers.

I think you are absolutely correct to have many directives.

In my angular apps, I have some directives without link to make my templates clean and readable. You can compress trees of HTML into their high-level meaning. Plus, if things get more complex later on, you can add a link function and add functionality with relative ease, and you don't have to change code in multiple places. As a Rails developer, I believe in DRY (don't repeat yourself). The fewer places the same code is, the easier it is to maintain.

So, directive or ng-controller?

If you are going to reuse a "widget" in multiple places, directives are ideal!

If it's a one-off or the main feature of the page, you're probably better off making it a ng-controller.


Your code looks clean. The suggested changes below mainly focuses on reducing it a bit, so IMO improving its readability.
But I'm not quite sure it'll also improve performance as you said you're interested to: I only hope some light gain could come from having suppressed your $makeanchor() function.

Changes I propose affect only your main paginationControl() function:

public function paginationControls(BaseList $list, $parameter = 'page') {

    if (!isset($list->pagination)) {
        return 'Error: List has not been supplied with pagination details.';
    }

    // if total results are less than the results displayed on each page
    // then do not render controls
    if ($list->pagination->perpage >= $list->pagination->total) {
        return null;
    }

    // Keep track of current query string parameters
    $query = preg_replace('/' . $parameter . '\=\d+\&?/', '', $_SERVER['QUERY_STRING']);
    if ($query) {
        $query .= '&';
    }
    $query .= $parameter . '=';

    $page = $list->pagination->page;
    $pages = ceil($list->pagination->total / $list->pagination->perpage);

    // Prepare link to first page, if needed
    if ($page > 3) {
      $pageSet['1...'] = FALSE;
    }
    // Prepare link to 3 pages before + current + 3 pages after
    for ($i = $page - 3; $i <= $page + 3; $i++) {
      if ($i AND $i <= $pages) {
        $pageSet[$i] = ($i == $page);
      }
    }
    // Prepare link to last page, if needed
    if ($i < $pages) {
      $pageSet['...' . $pages] = FALSE;
    }

    // Build output
    $output = NULL;
    $classes = 'pagination anchor';
    foreach ($pageSet as $pageNo => $current) {
      $output .= $this->a(
        ($current ? '#' : '?' . $query . $pageNo),
        $pageNo,
        NULL,
        ($classes . ($current ? 'current' : NULL))
      );
    }

    return $output;
}

Apart from the way to build pagination, you'll notice that:

I dropped trim(..., '&') from your $query = ..., since "&" has already suppressed by preg_replace(); otherwise it sounds like you suspect the whole query to abusively include an ending "&"
at the just next line, I dropped strlen() from if ($query), which is enough (and may be slightly faster, but it is only cosmetic)


Your main() code feels cumbersome, and the modelling seems unnatural to me.  I also find that .withSize(20).withBacon().withPepperoni() is hard to read, perhaps due to its placement after the definition of the anonymous subclass of Pizza.Builder.

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Factory myFactory = new Factory();

        Pizza myPizza = Pizza.makePizza(new Pizza.Builder(myFactory) {
            @Override
            public void prepareDough() {
                myFactory.prepareDough();
            }

            @Override
            public void prepareToppings() {
                myFactory.prepareToppings();
            }
        }.withSize(20).withBacon().withPepperoni());

        System.out.println(myPizza);
    }
}

Assuming that you are interested in constructing an immutable Pizza, I would prefer to see:

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Pizza myPizza = new PizzaBase(20).addTopping(Pizza.Topping.BACON)
                                         .addTopping(Pizza.Topping.PEPPERONI)
                                         .bake();
        System.out.println(myPizza);
    }
}

In particular:

This interface mimics the process of making a pizza.
The base is mandatory, and you must specify its size.  The toppings are optional.
Offering an .addTopping(…) method that accepts a parameter is more flexible.  You might even be able to .addTopping(CHEESE) twice to get extra cheese.
I'm not convinced that dependency injection for the Factory is worthwhile.


Scoring matches of a game - reducing duplicated code

You could put the statuses into a constant array and use the index variable to fetch them out:

void BlockParty::on_comboBox_currentIndexChanged(int index, Score* score)
{
  static const BlockPartyLogic value_table[] =
  {
    BlockPartyLogic::RAMP_OFF,      // Index 0
    BlockPartyLogic::RAMP_PARTIAL,  // Index 1
    BlockPartyLogic::RAMP_COMPLETE, // Index 2
  };
  if (index < sizeof(value_table) / sizeof(value_table[0]))
  {
    score->ramp_position_A = value_table[index];
  }
    score->update_internals();
}

If you want to select functionality based on an index you could use a static const array of function pointers or function objects.


This seems ok, depending on how precise you want it to be (some margin of error will always be needed since this is floating-point, but how much will depend on your needs)

Alternatively, you could check Math.Abs(1 - len) < 1e-14, but I suspect the same precision problems will remain.

I was somewhat surprised that 1 + 1e-15 equals 1, though, because doubles have 52 bits of precision, which should be more than enough to store a difference of 15 digits (-log2(1/10^15) gives me around 49.8, which is less than 52 bits).

So I double checked and 1 - 1.0e-15 does not give me 1.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(1 - 1.0e-15); //Does NOT print 1
        Console.Read();
    }
}

Same thing for 1 + 1.0e-15 (though this one is trickier)

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(1 + 1.0e-15); //Prints 1
        Console.WriteLine(1 + 1.0e-15 == 1); //...but this prints False
        Console.Read();
    }
}

I suspect Console.WriteLine is only printing a limited number of digits: less than the ones double can represent.

As a final note, Sqrt(1) == 1, so instead of using the Length you could use the SquaredLength and save a (potentially expensive) Sqrt operation.