I see a number of things that may help you improve your code.

Avoid macros

The macros _X_UNTIL_Y and _ATOI do not help with readability. I'd advise not using macros like those, preferring functions instead.

Use more descriptive variable names

All of the single-letter variable names make it difficult to decipher the algorithm.  More meaningful variable names make the code easier to read and maintain.

Break up the code into smaller functions

Rather than having everything in one long main function, it would be easier to read and maintain if each discrete step were its own function.

Think of the user

If the user runs the code with no arguments, he or she is rewarded with a segfault and crash.  It would be much nicer instead to prompt the user with a string describing how the program is intended to be used instead.

Use idiomatic C

Lines like these:

if(argv[1][0] == 'x');
else{

are quite odd.  It would make it much easier to read and understand if it were written instead like this:

if(argv[1][0] != 'x') {

Add comments

Code like this is difficult enough to read for the reasons listed above.  Just a few well-placed comments about why the code is doing what it's doing would greatly aid readers of the code to understand your intent.

Eliminate return 0 at the end of main

Since C99, the compiler automatically generates the code corresponding to return 0 at the end of main so there is no need to explicitly write it.


Crossover and Mutation functions for Genetic Algorithm

I rewrote parts of your code obtaining an equivalent version with the focus of relying on char arrays instead of String objects to obtain a simpler code. I noticed you use the number 100 in both methods you posted, it could be preferrable declaring a const value like below:

private static final int BOUND = 100;

Your method crossChromosome is structured like the code below:

private String crossChromosome(String m, String f) {
    if (rnd.nextInt(100) < crossRate*100) {
        //here the body
   }
    else { return (rnd.nextInt(2) == 1) ? f : m; }
    return chrString.toString();
}

You can directly put the else body at the beginning of the method with the negation of the condition like the code below:

private String crossChromosome(String m, String f) {
    if (rnd.nextInt(BOUND) >= crossRate * BOUND) {
        return (rnd.nextInt(2) == 1) ? f : m;
    }

    //here the instructions of the body of your case

    return chrString.toString();
}

You can use char arrays instead of String objects avoiding calls of String methods like the code below:

char[] mArr = m.toCharArray();
char[] fArr = f.toCharArray();
final int mLength = mArr.length;
final int fLength = fArr.length;
final int crossPoint = rnd.nextInt(mLength - 2) + 2;
final int nextCrossPoint = rnd.nextInt(mLength - crossPoint) + crossPoint;

You can rewrite the loop of your method like below:

StringBuilder chrString = new StringBuilder();

for (int i = 0; i < fLength; i++) {
    boolean condition = (i < crossPoint);

    if (crType != 1 && !condition) {
        condition = (i >= nextCrossPoint);
    }
    char ch = condition ? fArr[i] : mArr[i];
    chrString.append(ch);
}

return chrString.toString();

Below the code of your method crossChromosome:

private String crossChromosome(String m, String f) {
    if (rnd.nextInt(BOUND) >= crossRate * BOUND) {
        return (rnd.nextInt(2) == 1) ? f : m;
    }

    char[] mArr = m.toCharArray();
    char[] fArr = f.toCharArray();
    final int mLength = mArr.length;
    final int fLength = fArr.length;
    final int crossPoint = rnd.nextInt(mLength - 2) + 2;
    final int nextCrossPoint = rnd.nextInt(mLength - crossPoint) + crossPoint;

    StringBuilder chrString = new StringBuilder();

    for (int i = 0; i < fLength; i++) {
        boolean condition = (i < crossPoint);

        if (crType != 1 && !condition) {
            condition = (i >= nextCrossPoint);
        }
        char ch = condition ? fArr[i] : mArr[i];
        chrString.append(ch);
    }

    return chrString.toString();
}

I put condition inside the loop and used the ternary operator.
Same suggestions for the method mutateChromosome, below my version:

private String mutateChromosome(String k) {
    final int mutatRateMulBound = mutatRate * BOUND;
    char[] kArr = k.toCharArray();

    StringBuilder chrString = new StringBuilder();

    for (char c : kArr) {
        boolean condition = rnd.nextInt(BOUND) < mutatRateMulBound;
        char ch = condition ? options.charAt(rnd.nextInt(27)) : c;
        chrString.append(ch);
    }

    return chrString.toString();
}


Properly managing a collection from deserialized XML file throughout app's lifetime

Both a singleton solution and a static instance are acceptable.  What I would recommend is that you add a static factory to Games, like:

public static Games LoadFromFile(String xmlFile);

You would call this near the top level of your application and then you would pass it into any of your other code that requires it.  It's essentially dependency injection, in that you design the code that's going to use the Games object to have it injected it.  It makes testing easier and it makes the design more flexible.


You actually hint at the primary concern with your note about std::make_tuple(), std::tuple_cat() and gradually building up the result.
The point is that you have much copying with a plethora of temporaries going on.

Also, quite a bit of recursion.

Use index_sequences, the power of template parameter pack expansion, and forwarding using std::forward_as_tuple() and you can flatten it, as well as only copy directly from the source to the destination without intermediate steps.

While you are at it, ponder noexcept.

#include <utility>
#include <tuple>

namespace detail {
    template <class T>
    constexpr std::size_t tuple_size_v = std::tuple_size_v<std::decay_t<T>>;

    template <std::size_t I, class T, std::size_t... N>
    static constexpr auto index_helper(std::index_sequence<N...>) noexcept {
        return (1 * ... * (I < N ? tuple_size_v<std::tuple_element_t<N, T>> : 1));
    }
    template <std::size_t N, std::size_t I, class T>
    static constexpr auto index() noexcept {
        return N
            / index_helper<I, T>(std::make_index_sequence<tuple_size_v<T>>())
            % tuple_size_v<std::tuple_element_t<I, T>>;
    }

    template <std::size_t N, class T, std::size_t... I>
    static constexpr auto cartesian_product(T t, std::index_sequence<I...>) noexcept {
        return std::forward_as_tuple(std::get<index<N, I, T>()>(std::get<I>(t))...);
    }
    template <class T, std::size_t... N>
    static constexpr auto cartesian_product(T t, std::index_sequence<N...>) noexcept {
        return std::make_tuple(cartesian_product<N>(t, std::make_index_sequence<tuple_size_v<T>>())...);
    }

    template <class T>
    auto tuple_no_ref(T t)
    { return std::apply([](auto&&... x){ return std::make_tuple(x...); }, t); }
    template <class T>
    auto tuple2_no_ref(T t)
    { return std::apply([](auto&&... x){ return std::make_tuple(tuple_no_ref(x)...); }, t); }
}

template <class... T>
constexpr auto cartesian_product_ref(T&&... t) noexcept {
    constexpr auto N = sizeof...(T) ? (1 * ... * detail::tuple_size_v<T>) : 0;
    return detail::cartesian_product(std::forward_as_tuple(t...), std::make_index_sequence<N>());
}

template <class... T>
constexpr auto cartesian_product(T&&... t)
noexcept(noexcept(decltype(detail::tuple2_no_ref(cartesian_product_ref(t...)))(cartesian_product_ref(t...))))
{
    auto r = cartesian_product_ref(t...);
    using R = decltype(detail::tuple2_no_ref(r));
    return R(r);
}


I find this code rather odd. I think there are a number of problems you can work out, which I'll outline below.

Functions

You put the recursive version into a function called perm() which is a good idea. I would do the same thing with the iterative version. This way your main() function becomes more clear. I'd rename the recursive one to recursive_perm() and make the new one iterative_perm(). Then your main() becomes:

int main(){

    bool x = false;
    bool y = false;

    if(recursive_perm(x,y) == true){
        puts("DONE\n");
    }

    puts("\n\n");

    x = false;
    y = false;
    if(iterative_perm(x,y) == true) {
        puts("DONE\n");
    }

    puts("NOTHING");

    return 0;
}

Now you don't need the comments saying "RECURSIVE SOLUTION" and "ITERATIVE SOLUTION" because it's obvious from the names.

Fix Your Recursion

You recursive version doesn't do the same thing as your iterative version. In fact, it does a lot of really weird things. Why are you copying the input variables into const members only to print them out? printf() takes its arguments by value, so printing them won't change their values locally.

Also, why are you printing logical XOR when you're performing logical AND? The ^ operator is XOR in C-based languages. Your print statement tells the user that the value of x exclusive-or-ed with y is equal to the value of x logically anded with y.

Next, why are you calling perm(y+1,x); before the return statement? You don't do anything with its return value, so none of the work it does is at all useful. You throw out the results (though it does have the side effect of printing out some stuff).

What do these incorrect lines accomplish?

if(x == true){ return x;}
if(y == true){ return y;}

They appear to check if only 1 of the values is true and then return true, ignoring the other parameter. Therefore it is not actually calculating the permutations that you want it to calculate.

Doing addition on bool values is not easy to read. I would not recommend doing that in the future. You can easily flip a boolean value from true to false by prepending it with the ! operator. Either that or change the function to take int instead of bool as you've done with the iterative version.

Testing bool

In general, it's considered better form to directly test a bool variable in an if statement rather than comparing it to true or false by doing this:

bool x = true;
bool y = false;
if (x) {
    // x was true, do something here
}
if (!y) {
    // y was false, do something here
}

What Does the Return Value Represent?

What does the return value of your perm() function represent? If all you want to do is iterate through all possible permutations, it's not clear to me that it needs to return a value. Reading this, I would assume that if it's functioning correctly, it iterated all the values, otherwise it wouldn't have returned yet. If you want to know which combination returned true, you should probably return a struct containing 2 values showing the final combination.


Helper extension to release Windsor component; not sure if it's over-kill

Style-wise everything looks good. The only note I'd make is that in C#, generally the convention is to start brackets on a new line rather than in-line, although obviously this is ultimately up to personal or team preference. XML comments on public members may be a good idea too, as it's not trivially obvious what the purpose of this class is unless you're very familiar with the container.

As to the actual usefulness of the helper, though, I'm doubtful:

It doesn't significantly reduce the amount of code you have to write
It is just as reliant on people remembering to use it
It does not improve readability, and if anything, slightly degrades it.

One alternative would be instead of providing a helper method to use inside UsingFactoryMethod, you provide an alternative version of that method. You'd probably need to tweak it, but a rough version might look like:

public static ComponentRegistration<TService> UsingFactoryMethod<TService, TResource, TImpl>(
        this ComponentRegistration<TService> component, Func<IKernel, TResource> resourceResolver,
        Func<IKernel, TResource, TImpl> factoryMethod)
        where TService : class
        where TImpl : TService
    {
        return component.UsingFactoryMethod(
            (kernel) =>
            {
                var resource = resourceResolver(kernel);
                var result = factoryMethod(kernel, resource);
                kernel.ReleaseComponent(resource);
                return result;
            });
    }

A bit of a mouthful, but then using it would look like:

Component.For<MyComponentType>()
    .UsingFactoryMethod(
         k => k.Resolve<SomeAlternativeComponent>(),
        (k, alt) => (new ImplementingComponentType(alt.RandomProperty)));

This reduces the amount of code to write a bit more, and it helps remind people to use it by being on their intellisense. I'd say it's somewhat a matter of judgement whether this is more or less readable than the helper method version. It is also less flexible if, for example, you need multiple different explicitly resolved resources inside a single factory method. But, as far as I can think, this kind of approach is likely to be the only fruitful way to achieve what you want.

UPDATE

Another alternative using the decorator pattern, which allows you to deal with multiple explictly resolved services by decorating the kernel:

public static ComponentRegistration<TService> UsingReleasingFactoryMethod<TService, TImpl>(
    this ComponentRegistration<TService> component, Func<IKernel, TImpl> factoryMethod)
    where TService : class
    where TImpl : TService
{
    Converter<IKernel, TImpl> safeMethod = (kernel) =>
    {
        var releasingKernel = new ReleasingKernel(kernel);
        var result = factoryMethod(kernel);
        releasingKernel.ReleaseAll();
        return result;
    };
    return component.UsingFactoryMethod(safeMethod);
}

Here ReleasingKernel is a decorator for Kernel which keeps track of all services resolved, and otherwise passes all calls through to the kernel. It also has a method which I'm calling ReleaseAll which calls to the contained kernel to release all services it has recorded.

This doesn't actually have to be a decorator, you could create your own class which only has a subset of the interface of IKernel available, if not all methods are needed.

So using this, your example would look like:

Component.For<MyComponentType>()
    .UsingReleasingFactoryMethod(k => {
        var altComponent = k.Resolve<SomeAlternativeComponent>();
        return new ImplementingComponentType(altComponent.RandomProperty);
    })

Definitely shorter and more readable. In terms of people remembering to use it, it will appear on the intellisense, but with a different name to UsingFactoryMethod.


Functional Re-Write in Scala: Rows of Strings with a Max Width

This is much more "Functional" than my first attempt:

  def combineStrings(strs: List[String], maxLen: Int)
  : List[String] = {
    import scala.collection.mutable.StringBuilder

    strs.map(_.trim).filter(_.nonEmpty)
      .aggregate(List[StringBuilder]())({ (lbs, s) =>
        s.length match {
          case l if (l > maxLen) =>
            new StringBuilder(s) :: lbs
          case l =>
            lbs.find(_.length <= maxLen - (l+2))
              .map { sb => sb ++= s", $s"; lbs }
              .getOrElse(new StringBuilder(s) :: lbs)
        }
      }, _ ++ _
    ).map(_.toString).reverse
  }

Not sure why I didn't do this the first time around. This solution even provides the desired output, and accounts for the ", " separators in the length calculations.

scala> val rows = combineStrings(List("Short", "This is a particularly long String...", "More", "Small", "Strings"), 35)
rows: List[String] = List(Short, More, Small, Strings, This is a particularly long String...)

scala> rows.foreach(println)
Short, More, Small, Strings
This is a particularly long String...


Creating a class object just based on the class type

The common argument for preferring one over the other for a dictionary (map) look up and a conditional (switch) look up is performance over maintainability.

The dictionary look up usually makes it easier to separate concerns. It also makes the code more concise and arguably more readable when invoking the factory functions.

The conditional look up avoids traversing a map and any types of indirection allowing for arguably faster access to object creation. It also avoids the overhead of creating the map/registering functions in the map.

There are also arguments for locality of reference vs. dependency management where the switch statement may keep object creation local to the call site, while the map approach passes off creation to a function or object that knows how to better handle the problem.

These are the typical arguments that I see for each of those different approaches to this problem.


Number of Integer Pairs with a Specific Difference

Your solution looks good already. I can only really give 2 small pointers.

The first is based on mdfst13's comment. You don't do any checks on the input parameters.
Since it's for a programming challenge for which we can safely assume correct inputs this is somewhat fine. Although it would probably be better to at least add a comment block on top of the method stating those limitations.

Alternatively you could also check for unwanted inputs at the start of the method and throw a relevant exception. (For example IllegalArgumentException). You can still add a method comment on top to mention those.

Another way is to first sanitise the input parameters with the most logical correction. For example:

if(values == null) {
    values = new int[0];
}
if(difference < 0){
    differences *= -1;
}

That way, even if someone calls the method with invalid input parameters, the program will not crash. This kind of solution is great if you want to have a process running automatically for a long time without looking at it anymore, and don't care if some cases are handled "wrong"(/perfectly right?). The biggest disadvantage is that you don't know if an input is "corrected", so if it should have been handled differently it would be really hard to detect afterwards.

The second small pointer is that your class and method name remind me of this picture:

Since your class just has 1 method, naming it is obviously going to be tricky. I would just keep the Solution as classname like they usually do in hackerrank.

If you do keep the class name, I would at least change the method name. Now you repeat yourself if you call it: PairDifferenceCounter.countPairsWithDifference(someList, difference);

It reads a bit easier if you used something like this: PairDifferenceCounter.count(someList, differene).

Perhaps rename both into something like this: ExtendedListUtils.countPairs(someList, difference);
Which isn't perfect either since it might not be immediatly obvious that it counts the number of pairs with a given distance if you don't call it with a variable named "difference".

I want to stress out once more that these are only minor issues with the code. Well done!


Find the dominator in an array of integers

I see a number of things that may help you improve your program.

Test thoroughly

There is a flaw in your program which causes it to fail on certain kinds of input.  Here's the test code I used:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

// solution() goes here

struct test {
    int expected;
    int N;
    int numbers[20];
};

struct test tests[] = {
    { -1, 6, { 3, 3, 0, 6, 9, 3 }},
    { 3, 8, { 3, 4, 3, 2, 3, -1, 3, 3 }},
    { 3, 8, { 3, 3, 4, 2, 3, 3, -1, 3 }},
    { 3, 7, { 3, 3, 4, 3, 3, -1, 3}},
    { 3, 7, { 3, 3, 4, 3, 3, -1, 0}},
    { 3, 6, { 3, 3, 4, 3, 3, -1 }},
    { 6, 2, { 6, 6}},
    { 8, 1, { 8}},
};

bool doTest(struct test* t) {
    int index = solution(t->numbers, t->N);
    if (t->expected == -1) {
        return index == -1;
    }
    return t->expected == t->numbers[index];
}

int main()
{
    int testcount = sizeof(tests) / sizeof(tests[0]);
    for (int i=0; i < testcount; ++i) {
        printf("Test %d: %s\n", i+1, doTest(&tests[i]) ? "OK " : "BAD");
    }
}

With your code as posted, tests 5 and 6 (of 8) fail.

Fix your formatting

The indentation of the code is not consistent, which makes it a little harder to read and understand than if you format the code consistently.

Read the problem statement carefully

The problem statement says that the return value can be any of the index values that point to the dominator number, so there's no need to store all of them as the code does in the index[] array.

Reduce redundant variables

The value, candidate and leader could all be collapsed to a single local variable which would make the code shorter and more understandable.

Minimize loops through arrays

The code attempts to identify a candidate and then does several more loops through the code to find the count and an index value to return.  The code could be simplified to this (although the bug still remains):

int solution(int A[], int N)
{
    int size = 0;
    int candidate = 0;
    for (int i = 0; i < N; i++) {
        if (size == 0) {
            size++;
            candidate = A[i];
        } else {
            if (candidate != A[i])
                size--;
        }
    }
    if (size <= 0) {
        return -1;
    }
    int count = 0;
    int index = -1;
    for (int i = 0; i < N; i++) {
        if (A[i] == candidate) {
            count++;
            index = i;
        }
    }
    if (count > (N / 2)) {
        return index;
    }
    return -1;
}

Consider a different algorithm

There is another approach that passes all of the tests I've tried.  It first sorts the array.  Because the array is now sorted, we know that if there is a dominator, more than half the sorted array must be the dominator value.  In other words, for an array size of N, the index A[N/2] of the sorted array must contain the dominator value if one exists.  Then all that remains is to verify that it is indeed a dominator and return an index into this sorted version of the original array.  (Alternatively, this can be done with a copy of the original array if you make the assumption that the passed array can't be modified.  The problem statement doesn't say and doesn't specify const for the array parameter.)  Here's the code:

int comp(const void *a, const void *b)
{
    return *(const int *)a - *(const int *)b;
}

int solution(int A[], int N)
{
    qsort(A, N, sizeof(int), comp);
    int count = 0;
    for (int i = 0; i < N && count <= N / 2; ++i) {
        if (A[i] == A[N / 2]) {
            ++count;
        }
    }
    return (count > N / 2) ? N / 2 : -1;
}

Note that the index of N / 2 is guaranteed to point to the dominator if it exists, and the specification says that one may return any element of A in which the dominator exists.

Put another way, if one has a 10 integer array, there is no way to place 6 contiguous numbers within that array without having one of them be at index 5.

The corrected original algorithm

As @vnp and @janos have pointed out, the algorithm above, while simple and correct, is not optimal in terms of performance, so by popular demand, here's a corrected version of your original algorithm:

int solution(int A[], int N)
{
    int count = 1;
    int candidate = A[0];
    int index = 0;
    for (int i = 1; i < N; i++) {
        if (A[i] == candidate) {
            ++count;
        } else if (count > 0) {
            --count;
        } else {
            candidate = A[i];
            index = i;
            count = 1;
        }
    }
    if (count > 0) {
        count = 0;
        for (int i = 0; i < N && count <= N / 2; ++i) {
            if (A[i] == candidate) {
                count++;
            }
        }
        if (count > (N / 2)) {
            return index;
        }
    }
    return -1;
}

Thanks to @JS1 who pointed out that an earlier version of this failed on an all zeroes input, reinforcing my first point: Test thoroughly!  :)  I've added the following line to my test array:

{0, 5, {0, 0, 0, 0, 0}},

Timing tests

I modified the test routines a bit to have them copy each test and then sort rather than using a pointer.  Then I had each version run 100000 (1e6) times over the test suite of 8 tests.  Timing was then noted on each version and, as expected, the qsort algorithm is slower.  Tests were all done on a 64-bit Linux machine with a quad-core i7 running at 3.40GHz.  Compiler was gcc version 5.3.1 with -O2 optimization.

qsort version: 1.25 seconds
Moore version: 0.77 seconds

Results are fairly consistently repeatable and independent of which algorithm is tested first.  Since qsort is \${\mathcal O}(n \log n)\$, it's likely that the difference would tilt even more toward the Moore algorithm if longer strings had been used.


Loop through all virtualhost log files and run goaccess on each file

The script has problems with quoting and wildcard expansion.  The script could break in unexpected ways if there are spaces or shell metacharacters in the paths.  In general, when writing shell scripts, anytime you want to write $variable, you should probably be writing "$variable" instead, expanding the variable in double-quoted context.  The only unquoted variable in this script should be $LOG_FILES, because you do want wildcard expansion to occur there.

I think you are manipulating variables too much.  For each $f, you are interested in the directory that will contain the output and the filename of the output.  I think that the following script would be shorter and more obvious.

LOG_FILES=/home/www/*/log/*access.log
NOW=$(date +%Y-%m)

for f in $LOG_FILES ; do
  path=`dirname "$f"`/../stats
  mkdir -p "$path"                                   # Creates directory as necessary

  case `basename "$f"` in
    ssl.access.log) output="$path/ssl$NOW.html" ; ;;
        access.log) output="$path/$NOW.html"    ; ;;
                 *) exit 1                           # Shouldn't be possible
  esac

  goaccess -f "$f" --date-format=%d/%b/%Y \
           --log-format='%h %^[%d:%^] "%r" %s %b "%R" "%u"' -a > "$output"
done


1 Algorithm

This is not Dijkstra's algorithm and that is not breadth-first search either. It's an unweighted brute-force shortest path algorithm. Basically, you generate all possible paths from the source node (top-left cell) to the target node (bottom-right) cell.

On my machine (2.5 GHz) the following maze takes about 300 milliseconds to solve:

int[][] mazePlan = {
    {0,1,0,0,0,0,0,0},
    {0,0,0,1,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {1,1,1,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
};

2 Coding

You should rename the fields minFoundLen, n and  m to something like shortestPathLengthSoFar mazeHeight and mazeWidth, respectively. Also, you do not have to initialize m and n to zero; Java initializes integer fields to zero by default.

Taking into consideration what you do with int[][] path, I suggest you rename it to boolean[][] visited.

System.out.println("shortest path is " + minFoundLen);

It's not funky to print the result of an algorithm to standard output; instead, return the actual result, and let the caller of the algorithm do whatever he/she wants.

You can always store maze and visited in the fields of your object; that way, helper asks only three arguments instead of five.

if(path[x][y]!=0){
    return;
}

There should be one space before and after a binary operator.
There should be one space before and after a parenthesized expression.

So, combining the two above points you should rather write:

if (path[x][y] != 0) {
    return;
}

You should also separate "logical blocks" by a single empty line; like this:

    if (maze[x][y] != 0) {
        return;
    }

    if (x == m - 1 && y == n - 1) {
        minFoundLen = Math.min(minFoundLen, pathLen);
        return;
    }

    path[x][y] = 1;

    helper(maze, x + 1, y, pathLen + 1, path);
    helper(maze, x - 1, y, pathLen + 1, path);
    helper(maze, x, y + 1, pathLen + 1, path);
    helper(maze, x, y - 1, pathLen + 1, path);

    path[x][y] = 0;

And don't forget that you should have a space after any comma.

3 Alternative impelmentation

I have gathered all the points and used breadth-first search for solving the maze. That it how it might look:

Maze.java:

import java.awt.Point;
import java.util.List;
import java.util.Objects;

public class Maze {

    private static final boolean CELL_OCCUPIED = true;

    private final boolean[][] maze;

    public Maze(final boolean[][] maze) {
        Objects.requireNonNull(maze, "The input maze is null.");

        final int numberOfRows = maze.length;

        if (numberOfRows == 0) {
            throw new IllegalArgumentException("The input maze is empty.");
        }

        int numberOfColumns = 0;

        for (int row = 0; row < maze.length; ++row) {
            numberOfColumns = Math.max(numberOfColumns, maze[row].length);
        }

        this.maze = new boolean[numberOfRows][numberOfColumns];

        for (int row = 0; row < numberOfRows; ++row) {
            for (int column = 0;
                     column < Math.min(numberOfColumns, maze[row].length);
                     column++) {
                this.maze[row][column] = maze[row][column];
            }
        }
    }

    public int getWidth() {
        return maze[0].length;
    }

    public int getHeight() {
        return maze.length;
    }

    public boolean cellIsFree(final Point p) {
        return cellIsFree(p.x, p.y);
    }

    public boolean cellIsWithinMaze(final Point p) {
        return p.x >= 0 && p.x < getWidth() && p.y >= 0 && p.y < getHeight();
    }

    public boolean cellIsTraversible(final Point p) {
        return cellIsWithinMaze(p) && cellIsFree(p);
    }

    public boolean cellIsFree(final int x, final int y) {
        checkXCoordinate(x);
        checkYCoordinate(y);
        return maze[y][x] != CELL_OCCUPIED;
    }

    public String withPath(final List<Point> path) {
        final char[][] matrix = new char[getHeight()][getWidth()];

        for (int i = 0; i < matrix.length; ++i) {
            for (int j = 0; j < matrix[0].length; ++j) {
                matrix[i][j] = maze[i][j] ? 'x' : '.';
            }
        }

        for (final Point p : path) {
            matrix[p.y][p.x] = 'o';
        }

        final StringBuilder sb = new StringBuilder();

        sb.append(new String(matrix[0]));

        for (int i = 1; i < matrix.length; ++i) {
            sb.append('\n');
            sb.append(new String(matrix[i]));
        }

        return sb.toString();
    }

    private void checkXCoordinate(final int x) {
        if (x < 0) {
            throw new IndexOutOfBoundsException(
                    "The x-coordinate is negative: " + x + ".");
        }

        if (x >= maze[0].length) {
            throw new IndexOutOfBoundsException(
                    "The x-coordinate is too large (" + x +
                    "). The amount of columns in this maze is " +
                    maze[0].length + ".");
        }
    }

    private void checkYCoordinate(final int y) {
        if (y < 0) {
            throw new IndexOutOfBoundsException(
                    "The y-coordinate is negative: " + y + ".");
        }

        if (y >= maze.length) {
            throw new IndexOutOfBoundsException(
                    "The y-coordinate is too large (" + y +
                    "). The amount of rows in this maze is " +
                    maze.length + ".");
        }
    }
}

MazePathFinder.java:

package review;

import java.awt.Point;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;

public class MazePathFinder {

    private Maze maze;
    private Point source;
    private Point target;
    private boolean[][] visited;
    private Map<Point, Point> parents;

    public MazePathFinder() {}

    private MazePathFinder(final Maze maze,
                           final Point source,
                           final Point target) {
        Objects.requireNonNull(maze, "The input maze is null.");
        Objects.requireNonNull(source, "The source node is null.");
        Objects.requireNonNull(target, "The target node is null.");

        this.maze = maze;
        this.source = source;
        this.target = target;

        checkSourceNode();
        checkTargetNode();

        this.visited = new boolean[maze.getHeight()][maze.getWidth()];
        this.parents = new HashMap<>();
        this.parents.put(source, null);
    }

    public List<Point> findPath(final Maze maze,
                                final Point source,
                                final Point target) {
        return new MazePathFinder(maze, source, target).compute();
    }

    private List<Point> compute() {
        final Queue<Point> queue = new ArrayDeque<>();
        final Map<Point, Integer> distances = new HashMap<>();

        queue.add(source);
        distances.put(source, 0);

        while (!queue.isEmpty()) {
            // Removes the head of the queue.
            final Point current = queue.remove();

            if (current.equals(target)) {
                return constructPath();
            }

            for (final Point child : generateChildren(current)) {
                if (!parents.containsKey(child)) {
                    parents.put(child, current);
                    // Appends 'child' to the end of this queue.
                    queue.add(child);
                }
            }
        }

        // null means that the target node is not reachable
        // from the source node.
        return null;
    }

    private List<Point> constructPath() {
        Point current = target;
        final List<Point> path = new ArrayList<>();

        while (current != null) {
            path.add(current);
            current = parents.get(current);
        }

        Collections.<Point>reverse(path);
        return path;
    }

    private Iterable<Point> generateChildren(final Point current) {
        final Point north = new Point(current.x, current.y - 1);
        final Point south = new Point(current.x, current.y + 1);
        final Point west = new Point(current.x - 1, current.y);
        final Point east = new Point(current.x + 1, current.y);

        final List<Point> childList = new ArrayList<>(4);

        if (maze.cellIsTraversible(north)) {
            childList.add(north);
        }

        if (maze.cellIsTraversible(south)) {
            childList.add(south);
        }

        if (maze.cellIsTraversible(west)) {
            childList.add(west);
        }

        if (maze.cellIsTraversible(east)) {
            childList.add(east);
        }

        return childList;
    }

    private void checkSourceNode() {
        checkNode(source,
                  "The source node (" + source + ") is outside the maze. " +
                  "The width of the maze is " + maze.getWidth() + " and " +
                  "the height of the maze is " + maze.getHeight() + ".");

        if (!maze.cellIsFree(source.x, source.y)) {
            throw new IllegalArgumentException(
                    "The source node (" + source + ") is at a occupied cell.");
        }
    }

    private void checkTargetNode() {
        checkNode(target,
                  "The target node (" + target + ") is outside the maze. " +
                  "The width of the maze is " + maze.getWidth() + " and " +
                  "the height of the maze is " + maze.getHeight() + ".");

        if (!maze.cellIsFree(target.x, target.y)) {
            throw new IllegalArgumentException(
                    "The target node (" + target + ") is at a occupied cell.");
        }
    }

    private void checkNode(final Point node, final String errorMessage) {
        if (node.x < 0
                || node.x >= maze.getWidth()
                || node.y < 0
                || node.y >= maze.getHeight()) {
            throw new IllegalArgumentException(errorMessage);
        }
    }

    public static void main(String[] args) {
        int[][] mazePlan = {
            {0,1,0,0,0,0,0,0},
            {0,0,0,1,0,0,0,0},
            {0,0,0,0,0,0,0,0},
            {1,1,1,0,0,0,0,0},
            {0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0},
        };

        boolean[][] maze2 = new boolean[mazePlan.length][mazePlan[0].length];

        for (int i = 0; i < maze2.length; ++i) {
            for (int j = 0; j < maze2[i].length; ++j) {
                maze2[i][j] = mazePlan[i][j] > 0;
            }
        }

        final Maze maze = new Maze(maze2);
        final Point source = new Point(); // Same as new Point(0, 0):
        final Point target = new Point(7, 5);

        long startTime = System.nanoTime();
        final List<Point> path = new MazePathFinder().findPath(maze,
                                                               source,
                                                               target);
        long endTime  = System.nanoTime();

        System.out.printf("BFS maze finder in %d milliseconds.\n",
                          (endTime - startTime) / 1_000_000L);

        System.out.println("Shortest path length: " + (path.size() - 1));
        System.out.println(maze.withPath(path));
    }
}

Hope that helps.


HTML and CSS markup for flexible form layout

Your code looks perfectly fine.  In fact, it all validates by the validators at W3C perfectly fine, with one exception - your HTML file should be structured like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Your Page Title Here</title>
        <!-- other code here -->
    </head>
    <body>
        <!-- your display code here -->
    </body>
</html>

The validators can be found here:

  HTML validator
  CSS validator

Your code seems perfectly fine the way it is, and I would say the only thing wrong with it is from the user's perspective.  You have the Category menu overlapping the Title menu, which is not good; you should adjust your columns to prevent this.


A very small crawler created using class

General

Imports should be grouped, and groups should be separated by a single blank line.1
Class names should use CamelCase.2
There shouldn't be a blank line following the class signature.
Top-level function and class definitions should be separated by two blank lines.3 You already correctly separate method definitions by a single blank line. :)
Assignment operators should be separated by whitespace.4
In wiseowl, no method ever needs access to self.start_url (the only exception being __init__(), of course). You might as well get rid of it.
If you want to cast an object to str, just pass the object to the str constructor:

str_obj = str(obj)

Rewrite

I've removed redundant code and improved code style.

from lxml import html

import requests

class WiseOwl:
    def __init__(self, start_url):
        self.links = [start_url]
        self.storage = []

    def crawl(self):
        # Calling get_link for every link in self.links
        for link in self.links :
            self.get_link(link)

    def get_link(self, link):
        print('Crawling: ' + link)
        url = "http://www.wiseowl.co.uk"
        response = requests.get(link)
        tree = html.fromstring(response.text)

        for items in tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']"):
            name = items.xpath(".//a/text()")[0]
            urls = url + items.xpath(".//a/@href")[0]
            docs = name , urls
            self.storage.append(docs)
            next_page = tree.xpath("//div[contains(concat(' ', @class, ' '), '
woPaging ')]//*[@class='woPagingItem' or @class='woPagingNext']/@href")

            for npage in next_page:
                if npage and url + npage not in self.links:
                # Avoid getting the same link twice
                    self.links += [url + npage]

    def __str__(self):
        return str(self.storage)

crawler = WiseOwl("http://www.wiseowl.co.uk/videos/")
crawler.crawl()
for item in crawler.storage:
    print(item)

References

1 PEP-8: Imports

2 PEP-8: Naming Conventions: Descriptive: Naming Styles

3 PEP-8: Blank Lines

4 PEP-8: Other Recommendations


Eliminating global variables in GUI program

A thing I like to do is instead of using four different JButtons is use an array of four JButtons that is initialized in the same method that you build the JPanel this would remove the need to have them as global variables. Also instead of using two different methods to create your JPanels just use one that returns a JPanel as you can see you can remove the JButtons and the two JPanels this way:

public JPanel buildOperatorPanel()
{
    JPanel operatorPanel = new JPanel();
    operatorPanel.setLayout(new FlowLayout());

    JButton[] buttons = new JButton[4];//the array of JButtons
    String[] buttonNames = {"+", "-", "/", "*"};//the names to be displayed on the JButtons
    for(int i = 0; i < buttons.length; i++)
    {
        buttons[i] = new JButton(buttonNames[i]);
        //buttons[i].addActionListener(yourActionListener)//for whenever you add event handling
        operatorPanel.add(buttons[i]);
    }
    return operatorPanel;
}

Another thing I could suggest is instead of named reference variables for your JLabels use anonymous objects so for operationLabel (this is only assuming your not going to use the JLabels later):

add(new JLabel("YOU HAVE PERFORMED SOME OPERATION", SwingConstants.CENTER), BorderLayout.SOUTH);

However I am going to suggest that you move the JTextFields to global variables. Based on what I'm assuming you have to do with this calculator you are going to want the JTextFields to be accessible to everything.
Here is my revision of your code:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public final class Calculator extends JFrame
{
    private JTextField operandOneText;//these get initialized in buildOperandPanel() method which is called in the constructor
    private JTextField operandTwoText;
    private JTextField answerText;

    //constructor to initialise the frame and add components into it
    public Calculator()
    {
        super("Clancy's Calculator");
        setLayout(new BorderLayout(5, 10));
        setResizable(false);
        setSize(370, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);

        add(buildOperatorPanel(), BorderLayout.NORTH);
        add(buildOperandPanel(), BorderLayout.CENTER);
        add(new JLabel("YOU HAVE PERFORMED SOME OPERATION", SwingConstants.CENTER), BorderLayout.SOUTH);

        pack();
    }

    //method builds and returns operatorPanel
    public JPanel buildOperatorPanel()
    {
        JPanel operatorPanel = new JPanel();//JPanels are FlowLayout by default

        JButton[] buttons = new JButton[4];
        String[] buttonNames = {"+", "-", "/", "*"};
        for(int i = 0; i < buttons.length; i++)
        {
            buttons[i] = new JButton(buttonNames[i]);//the array of JButtons
            //buttons[i].addActionListener(yourActionListener)//for whenever you add event handling
            operatorPanel.add(buttons[i]);
        }
        return operatorPanel;
    }

    //method builds and returns operandPanel
    public JPanel buildOperandPanel()
    {
        JPanel operandPanel = new JPanel();
        operandPanel.setLayout(new GridLayout(3, 2, 5, 5));

        //Initialize TEXT FIELDS
        operandOneText = new JTextField();  //retrieves one operand
        operandTwoText = new JTextField();  //retrieves another operand
        answerText = new JTextField();    //displays answer

        answerText.setEditable(false);  //ensure the answer field is not editable

        operandPanel.add(new JLabel("Enter the first Operand: "));
        operandPanel.add(operandOneText);
        operandPanel.add(new JLabel("Enter the second Operand: "));
        operandPanel.add(operandTwoText);
        operandPanel.add(new JLabel("ANSWER: "));
        operandPanel.add(answerText);

        return operandPanel;
    }

    /** main method */
    public static void main(String[] args)
    {
        new Calculator();
    }
}


Using Regexp to select the date from a string

The regular expression you used, although it works, it's not very specific. It matches the sequence of these:

\d = a digit
.+ = one or more of any character
\- = a literal - (btw you didn't need the \ here, it has no effect here)
\d{1,2} = one or two digits

Many non-dates can match this pattern too, for example these strings:

1abcdefg-4
2999999!@$$#$@#$-12
...

I would recommend to use a more strict pattern, for example:

\d{4}-\d{2}-\d{2}

This matches the sequence of these:

exactly 4 digits
literal -
exactly 2 digits
literal -
exactly 2 digits

Note that this is still not perfect. It won't prevent these invalid dates:

2014-02-31
9999-99-99

A bit more strict pattern would be:

2\d{3}-[01]\d-[0-3]\d

Which, of course, is still not perfect, because it will still allow 2014-19-39, for example. It's possible to be even more strict, but whether it's worth it / necessary or not depends on your use case.


discord.js/node : filter().map() best method

Maybe this is better :

let roles = msg.mentions.roles.filter(role => (args[2] === role.toString() || args[3] === role.toString())).map(role => role.id);

And use roles.length instead of nbArgs++ :

// Get text
let txtContent = msg.content.split(/ +/g).splice(roles.length + nbArgs).join(' ');


I see a number of things that may help you improve your program.

Don't use Hungarian notation

Read this for an explantion of why you shouldn't use Hungarian notation.

Use unsigned types where appropriate

It's unlikely that the values you are passing to ConvertShortToByte or ConvertIntToByte are intended to be signed values.  Signed values are treated differently than unsigned values when shifted because of sign extension.  In this case, that's almost certainly not what is needed.

Return something useful from functions

The conversion functions would be more useful if they returned a pointer just past the current value.  Also rather than a pointer and index, why not just pass a pointer?  Rewritten that would look like this:

BYTE *ConvertShortToByte(unsigned short value, BYTE* buffer)
{
  *buffer++ = value >> 8;
  *buffer++ = value;
  return buffer;
}

Eliminate "magic numbers"

This code has a number of "magic numbers," that is, unnamed constants such as 0x0B, 0xCA, 60 etc.  Generally it's better to avoid that and give such constants meaningful names.  That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "60" and then trying to determine if this particular 60 is relevant to the desired change or if it is some other constant that happens to have the same value.

Use an object

A packet is a natural for an object, so why not make a Packet class?  Here's one way to do it:

class Packet {
public:
    Packet (unsigned seq, unsigned time, const std::vector<unsigned short>& data)
    {
      BYTE *buff = buffer;
      *buff++ = MSG_TYPE;
      buff = ConvertIntToByte(time, buff);
      buff = ConvertIntToByte(seq, buff);
      buff = ConvertIntToByte(0, buff); // filler
      buff = ConvertShortToByte(data.size(), buff);
      for (const auto item : data) {
          buff = ConvertShortToByte(item, buff);
      }
      *buff++ = MSG_END;
    }
    size_t size() const { return 16 + (((buffer[13] << 8) + buffer[14]) << 1); }
    static constexpr BYTE MSG_TYPE = 0x0B;  // start of packet
    static constexpr BYTE MSG_END = 0xCA;  // end of packet
    static constexpr size_t BUFF_SIZE = 60;
private:
    BYTE buffer[BUFF_SIZE];
};

If you need access to the underlying buffer, there are a few ways to do it.  First, you could simply make the buffer a public data member (or alternatively make Packet a struct).  Second, you could provide a handle that would return a const * reference to the internal buffer.  Third, you could eliminate the need by providing, for example a write member function.  Fourth, you could declare the buffer in place and then use "placement new" which is a common idiom for communications protocols in which a packet is built in a fixed location buffer.  Since many people seem unfamiliar with the use of "placement new", I'll elaborate.

Use "placement new"

If a buffer is already allocated and you want to create a Packet in place, it can be done using "placement new":

BYTE ucXmtdat[60];
Packet *pkt = new (ucXmtdat) Packet(m_iMsgSequence, iUTCTime, m_data);

This creates a Packet at the location specified by ucXmtdat without allocating further memory.  Note that when this form is used, it is entirely up to you to make sure that the memory area is really big enough and it's entirely up to you to destroy the object when finished.  In this case, there's not really anything to do since ucXmtdat (which is not a very nice name, by the way) is local and will simply disappear when it goes out of scope.


Since you are asking about PyTorch's capabilities you are not taking advantage of, you might want to use:

torch.linspace(-10,0,300) instead of torch.tensor(np.linspace(-10,0,300))
torch.zeros(5, dtype=torch.long) instead of torch.tensor([0,0,0,0,0])
tensor operations instead of iterating over each element of the tensor in a loop. This might not matter much in unit-tests but is important if you want to get GPU acceleration:

self.assertTrue(torch.equal(tout_leqz, torch.zeros_like(tin_leqz)))


Extension methods for ReaderWriterLockSlim

It looks pretty good. I can't see anything less than great.
I'd just add that to your code:

    private static void Critical(Action criticalAction)
    {
        try
        {
            Thread.BeginCriticalRegion();
            criticalAction();
        }
        finally
        {
            Thread.EndCriticalRegion();
        }
    }

And i used the IsWriteLockHeld, IsReadLockHeld, etc, before exiting the lock.


I'd test if not result_sets_col in script.text and continue in that case, to remove a level of nesting:

for script in soup.findAll('script'):
    result_sets_col = 'resultSets'
    if not result_sets_col in script.text:
        continue

    start = script.text.rindex('{', 0, script.text.index(result_sets_col))


Find number of unique paths to reach opposite grid corner

Solution: recursion with memoization works really well! Many thanks to Samwise and vnp.

With the help of python lru_cache decorator:

@lru_cache(128)
def number_of_paths(m, n):
    if m == 1 and n == 1:  # border case
        result = 1

    elif m != 1 and n != 1:
        result = number_of_paths(m - 1, n) + number_of_paths(m, n - 1)

    elif m != 1 and n == 1:
        result = number_of_paths(m - 1, n)

    elif m == 1 and n != 1:
        result = number_of_paths(m, n - 1)

    else:
        raise Exception("Something went wrong!")

    return result

With the help of dictionary to store results:

storage = {}
def number_of_paths_no_lru(m, n):
    if storage.get((m, n,)):
        return storage[(m, n)]

    if m == 1 and n == 1:  # border case
        result = 1

    elif m != 1 and n != 1:
        result = number_of_paths_no_lru(m - 1, n) + number_of_paths_no_lru(m, n - 1)

    elif m != 1 and n == 1:
        result = number_of_paths_no_lru(m - 1, n)

    elif m == 1 and n != 1:
        result = number_of_paths_no_lru(m, n - 1)

    else:
        raise Exception("Something went wrong!")

    storage[(m, n, )] = result
    return result

Tests:

if __name__ == '__main__':
    print(number_of_paths(100, 100))
    print(number_of_paths_no_lru(100, 100))
    # Answers:
    # 22750883079422934966181954039568885395604168260154104734000
    # 22750883079422934966181954039568885395604168260154104734000


A running gene crossover function for a Genetic Algorithm

I tried writing it with a recursive loop. I personally find it a bit easier to read, but I guess it depends on how familiar you are with recursion.

(defn running-cross
    [genes other-genes cross-points]
    (loop [remaining-cross-points cross-points
           last-cross 0
           take-from-g1? true
           result []]
        (let [next-gene (if take-from-g1? genes other-genes)
              next-cross (first remaining-cross-points)]
            (if next-cross
                (recur (rest remaining-cross-points)
                       next-cross
                       (not take-from-g1?)
                       (concat result (subvec next-gene last-cross next-cross)))
                (concat result (subvec next-gene last-cross))))))

As for efficiency, my algorithm is a lot faster; especially when there are few cross-points. I believe this is mainly because it iterates over the cross-points instead of the full length of the genes, and then uses subvec and concat which are quite efficient when used on vectors.

Here are some times:

;; 5 000 000 length genes, crossing over on every index
user=> (do (time (running-cross-mine (vec (range 5000000)) (vec (range 5000000)) (vec (range 5000000)))) nil)
"Elapsed time: 3298.197955 msecs"
nil
user=> (do (time (running-cross-yours (vec (range 5000000)) (vec (range 5000000)) (vec (range 5000000)))) nil)
"Elapsed time: 11672.627633 msecs"
nil

;; 5 000 000 length genes, crossing over once
user=> (do (time (running-cross-mine (vec (range 5000000)) (vec (range 5000000)) [2500000])) nil)
"Elapsed time: 287.335904 msecs"
nil
user=> (do (time (running-cross-yours (vec (range 5000000)) (vec (range 5000000)) [2500000])) nil)
"Elapsed time: 6160.856827 msecs"
nil


Elementwise perfect forwarding of a member range

I'll start with some direct review of what you've implemented. After the bullets, however, I go into some concerns about whether this should be used. Thanks for the interesting idea; reviewing it made me re-examine several things I thought I already knew.

Like std::forward you should consider making forward_as a constexpr function.
You could avoid some of the pre-C++14 verbosity by using decltype inside forward_as (although the auto return type sounds better still):

    return static_cast<decltype(forward_as<T, U>(u))>(u);

How do you know whether for (auto&& r : t.range) will iterate over objects owned by t?
Admittedly a bikeshed point, I don't like the way the name forward_as<T>(u) reads; perhaps forward_if<T>(u) or even move_if_rvalue<T>(u) would help this not look like it returns an expression of a T-based type.

However like Kerrek SB's comment on the referenced question, I worry about the state of the main object when forwarding or moving its members. What are the rules for doing this safely? Your examples seem to show forwarding only a single member, but what are the rules when forwarding different parts of the same object? What are the code review guidelines to ensure that problems are not introduced in later edits?

To sum up, I mistrust this. It might just be my own lack of familiarity with such a use case. But it also reflects an uncertainty that optimizing for move is likely to be worth it in these cases. If this is actually a bottleneck or potential bottleneck in the code, are there better alternatives? Does bar even overload on r-value types? Should foo receive t.range instead of t, or will std::for_each be able to generate r-values automatically:

    std::for_each(std::begin(t.range), std::end(t.range), bar)

(If so, I haven't figured out the syntax to support it in your sample with bar as a function template. Using instead a struct with overloaded operator(), it appears to suggest we shouldn't assume the range contains r-values.)


Writing Custom functions to grab data from JSON

result[0] : result

This is a bad idea. This will keep users of your functions guessing and unnecessarily put in guard logic to check if it's a thing, or an array of things before proceeding. If you expect many results, then always return an array. If you expect just one result, return just one (regardless of how many match), and null if none.

  iterating the whole object to get a single field

Array searches are O(n) at worst. Tough luck if you're item is on the tip of the list. While we can't do anything in the complexity side of things, your code could be simplified. Seeing $vm.services appears to be an array, you can just use array.filter.

// Will always return an array, regardless of match count
function getWhere(field, value) {
  return $vm.services.filter(function(object){
    return object[field] === value;
  });
});

Alternatively, if you just really want one item among all matches, then array.find is your guy. It takes the same form as filter, but stops going through the array when it hits a match and just returns that one item, without wrapping it in an array.

// Will always return 1 item from the array, and undefined if none
function getWhere(field, value) {
  return $vm.services.find(function(object){
    return object[field] === value;
  });
});

  Is there a built-in solution in JS or VueJS for this kind of tasks, if Yes should i use those solutions or the function i posted here is okay to use.

Yes, filter and find are just a few of many. See array methods.


Number-guessing game with maximum and minimum values

You are inappropriately using the guessinggame() function as if it were a goto label.  After playing the game repeatedly, you will end up with a deep stack trace (which you can see by hitting ControlC), which is a bad sign.  A proper design would be:

def guessing_game():
    # Code to play one game

play = True
while play:
    guessing_game()
    play = ('y' == raw_input('Would you like to play again? (y/n): '))

Curiously, you check that the bounds are integers, but you don't bother to validate the guesses.  You also don't check that the minimum is less than the maximum.

All three prompts would benefit from a shared integer-prompting routine:

def prompt_int(prompt, err_msg='This must be an integer!'):
    while True:
        try:
            return int(raw_input(prompt))
        except ValueError:
            print err_msg

Getting that clutter out of the way makes your main function more readable:

def guessing_game():
    print "Welcome to the Guessing Game!."

    rnumber = None
    while rnumber is None:
        lower = prompt_int('What is the minimum number you want?: ')
        upper = prompt_int('What is the maximum number you want?: ')
        if lower < upper:
            rnumber = random.randint(lower, upper)
        else:
            print "The minimum must be less than the maximum!"

    tries = 0
    while True:
        guess = prompt_int("What is your guess?: ")
        tries += 1
        if guess < rnumber:
            print "Low!"
        elif guess > rnumber:
            print "High!"
        elif guess == rnumber:
            print "Correct!"
            print tries
            break

I've renamed numrange1 to lower, numrange2 to upper, i to tries, and x to guess.  Incrementing the loop counter is common to all three branches and can be factored out.


Implementing Haskell's \\ (Set Difference)

I find that to be a very succinct, readable definition. I probably would have written it too. Unfortunately it's wrong!

One of the more tedious requirements of beautiful code is that it be correct, so let's set up some really quick testing using QuickCheck. Since you've been reimplementing functions from base QuickCheck can generate a bunch of random test data and throw it at both the original function and your reimplementation and verify that the outputs match.

We'll start by defining a property that says the output from setDifference and \\ should always be the same.

prop_equal :: (Eq a) => [a] -> [a] -> Bool
prop_equal xs ys = setDifference xs ys == xs \\ ys

We can use this property ourselves in an interactive session, but that gets tedious fast. Instead, call quickCheck with the property and it will generate arbitrary data to test it with.

  GHCi

> :m +Test.QuickCheck
> quickCheck prop_equal
*** Failed! Falsifiable (after 9 tests and 4 shrinks):
[(),(),(),(),(),()]
[()]

Aha! QuickCheck has determined that our property doesn't always hold. Each line printed after "Failed!" corresponds to an argument to the property. This might appear a little confusing due to the use of () (the unit or void type). Because our property was polymorphic, GHC picked a default. You can specialize the property to get output with other types, try quickCheck (prop_equal :: String -> String -> Bool). (You may have gotten slightly different output, that is okay and expected due to the generation of arbitrary data having been random.)

By itself this might not tell us enough though, why did these two arguments produce a failure? You can get all of the cases that QuickCheck tried by using verboseCheck instead.

  GHCi

> verboseCheck (prop_equal :: String -> String -> Bool)
... pages ...

This will print a whole pile of text with various passing and failing cases until it gives up trying to shrink the test case. Run verboseCheck a couple of times and eyeball the output, you should be able to notice that it always reduces the failure to something like the following.

Passed:
"aa"
"b"
Failed:
"aa"
"a"

If you explore these examples manually in the repl or simulate them by hand (or imagination) you'll see that setDifference removes every instance of the elements from excludes from xs instead of just the first as \\ does. Now armed with the fact that the implementation is wrong, and knowing what's wrong with it we can head back to the drawing board to fix setDifference.

For a full exploration of QuickCheck check out Real World Haskell's chapter on QuickCheck.


refactor function so same code is written only once

Refactor the repeated code into its own private function:

@objc func didClickActionButton(sender: UITapGestureRecognizer) {
    guard let contents = contentList else { return }

    if contents[currentScreenIndex].customMeta["permission-location"] != nil {
        //request Permission
        ApiHelper.shared.initLocationHelperWithBeacon()
    }

    if contents[currentScreenIndex].customMeta["permission-notification"] != nil {
        PushNotificationHelper.requestNotificationAuthorization {
            DispatchQueue.main.async {
                self.advanceOnboarding()
            }
        }
        return
    }

    advanceOnboarding()
}

private func advanceOnboarding() {
    if currentScreenIndex == contents.count - 1 {
        finishOnboarding()
        return
    }

    currentScreenIndex += 1
    showScreenAtPosition(position: currentScreenIndex)
}

I’d also suggest the guard for the early exit, as shown above.

  Is it even worth it to refactor this?

Refactoring this code out into its own function not only avoids the unnecessary repetition (simplifying maintenance in the future), but it also makes this routine much easier to reason about. When first reading your code, it took a few seconds to figure out what you were trying to do, why that code was being repeated, etc. Giving that block of code a clear name makes it easier to grok what’s going on.


Is this the right way to implement a simple hash table in C++?

The biggest issue is, as mentioned in the comments, that you don't handle collisions. I'm not going to cover that, but I'll address some other issues.

IMO your hashtable should be templated on at least 3 types - the key type, the value type, and the hash functor.  This way you aren't limiting your users to having string keys or to rely on your hash function.

You should also use colon initialization - the data members will be default initialized at the starting curly brace of the constructor, but with colon initialization you skip the default initialization and the replacement with new values.  That would look something like this

HashTable(size_t amount) : size(amount), values(new Value*[size]) {
    for (size_t i = 0; i < size; ++i) {
        values[i] = nullptr;
    }
}

You'll notice I've replaced your ints with size_t - in these situations you don't need negative numbers.  I've also used the subscript notation instead of pointer arithmatic, which is much, much easier to read and reason about. You should strongly prefer subscript notation if it is possible to use it.

Your destructor doesn't need to check if the the values are not nullptr - there isn't a sensible reason it should be.

You should be using const functions - printValues should be, and you should provide a const version of getValue as well.

You also assume that the value type can be default initialized, which is not necessarily true. You might want to use placement new here instead. Alternatively, you could just split up the code a bit.

void addValue(const std::string & key, T value)
{
    int location = hash(key);

    if (values[location] == nullptr)
    {
        values[location] = new T(value);
    }
    else
    {
        *values[location] = value;
    }
}

This still requires that there be a copy constructor, however this is probably a less surprising requirement (most containers expect objects to be copy/move constructible).

You'll probably want to provide an iterator as well, but I'll leave that as an exercise for the reader.

Lastly, you should provide a method to find and erase, and probably resize your hash table.  Without those things the hash table doesn't have much use.


Create JSON file from WordPress ACF options

Your problem is likely making those API requests in a loop.  You might consider using a REST library which can support multiple concurrent calls to your end services (perhaps something based on curl_multi_exec()).  This would allow you to collapse overall API request time down to the length of whichever request happens to take the longest.

I am not familiar with Httpful which it seems you are using, but in glancing at the information available for that library, I didn't see support for making concurrent requests.  This may mean you need to change libraries or build something yourself to do this.

I will link to an example class I had once written in PHP to give you an idea for how this may be accomplished.

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

You are free to use it if you find it useful.


Searching in an array in less than O(n) time

While other answers make good points, I have to wonder why you are using recursion. This is such a simple problem to solve with a for loop.

I assume that you are not supposed to start from any index other than index 0, so consider the following routine:

public int searchArray(int[] arr, int elem) {

    for (int i = 0; i < arr.length; ) {
        if (arr[i] == elem) {
            return i;
        }
        i += Math.abs(elem - arr[i]);
    }
    return -1;
}

(If you need to start the search part-way through the array then you can add the offset input parameter again and start i from that).

The bottom line is that recursion is overkill, this system is \$O(n)\$, but the cost of each cycle is less than the same thing using recursion.

I am not aware of any way to solve the given problem with a system of better than \$O(n)\$ complexity.

Discussion on complexity - why this is \$O(n)\$

This answer has generated a lot of discussion about complexity, that this method only ever scans, at most, half the members of the input array, and thus it should be complexity \$O \left( \frac{n}{2} \right )\$ instead of \$O(n)\$. The argument given is something like:

  Consider the worst-case data 1,2,1,2,1,2,1,2,1,2,1,2 and the search term 3. For this situation the method will start at data[0], and then skip to data[2], then data[4], and so on. It will never inspect data[1], and other odd-indexed data points. If the search term is even more 'different' than the actual data (e.g. 100) then the method will do only one comparison at data[0] and will then return 'not found' -1.

This is an interesting observation, that the method only ever needs to scan half the data at most. This is especially interesting considering a 'naive' method which just scans the data one-member-at-a-time and returns when it finds the value. That 'naive' method most certainly has \$ O\left(n\right) \$ 'performance' and complexity, and the 'skip-method' will be more than twice as fast.

The important thing to note though, is how the algorithms scale relative to the amount of data, not relative to each other!

So, consider a hypothetical set of worst-case data 1,2,1,2,1,2,.... and the search-term 3. This hypothetical happens to be searched in 4 milliseconds by the skip-method, and in 8 milliseconds by the naive-method. Now we double the amount of data, what happens? The processing time for both methods will double!

In both cases, the performance of the algorithms will double for each doubling of the data volume. This is what makes both algorithms \$ O(n) \$ complexity. From Wikipedia:

  In computer science, big O notation is used to classify algorithms by how they respond (e.g., in their processing time or working space requirements) to changes in input size.

Reversing the argument, by suggesting the skip-method has \$O \left( \frac{n}{2} \right) \$ complexity, I would then expect that, if I double the data, the execution time would only increase by a half, or 50%. This is 'obviously' not true for the skip-method (nor the naive-method).

Both methods have \$O(n)\$ complexity because they both scale the same way with increasing volumes of data.

But, just because they scale the same way, does not mean that one method is not better than the other... obviously.


Finds the absolute max of the numbers in each file and outputs in specific format

What I would do in no particular order:

Use argparse for noob compatibility (also known as usability).
Run the file through pep8, then understand and apply everything it suggests (for example lower_case variable names). If you keep doing this you will reduce the mental overhead of anyone familiar with Python when dealing with your code (including your future self).
Pull out a minimalist main().
Create a class with instance methods to get the max number in a file and return a list of values (rather than printing them).
Print/save the return value in main() or a dedicated function. For scriptability the output should be as simple as possible, with no "fluff" like headers, and predictable, such as always integers with no surrounding punctuation.
I don't think you need to use .__str__() when formatting - Python knows it needs to convert to strings.
Use a context manager for opening files: with open(file, mode) as file_pointer.
Use variable names which are immediately understandable (see previous point).
Accumulating text into variables before printing/saving them wastes memory (very little in your case, but even so). Shift the bytes as quickly as possible. This way you'll also remove the need for intermediate variables, and can see the result of long-running processes as soon as any part of them is done.
I'm not very familiar with numpy, but it looks like you're reading the whole file before starting to process it. Treating files as streams instead will improve the speed and especially memory use when dealing with large files.


Your logic seems solid, but there's a couple of things I would do differently.

One obvious improvement is that you don't need to hold the full dynamic programming array in memory: it is enough to keep the previous row and the one you are working on. It also leads to a pretty neat handling of edge cases, as you'll see soon enough.

I am also a little weary about the approach of your allowed function: relying on a string representation just doesn't feel right. I also frown at your adding both the forward and the reverse paths to your banned set: the only reason you can use DP in the first place is because you can only move forward in both directions, so you might as well take advantage of that knowledge, and store only the direction you will eventually find.

A possible implementation of all that could be:

def banned_roads(banned_strings):
    banned_paths = {}
    for banned_string in banned_strings:
        banned_coords = [int(item) for item in banned_string.split()]
        banned_coords = [tuple(banned_coords[:2]), tuple(banned_coords[2:])]
        banned_coords.sort()  # we always move towards larger coords
        src, dst = banned_coords
        banned_srcs = banned_paths.setdefault(dst, [])
        banned_srcs.append(src)
    return banned_paths

def avoid_roads(rows, cols, banned_paths):
    rows += 1
    cols += 1
    prev_row = [1] + [0] * (cols - 1)
    for row in range(rows):
        this_row = []
        before = 0
        for col, above in enumerate(prev_row):
            banned_srcs = banned_paths.get((row, col), [])
            if (row, col - 1) in banned_srcs:
                before = 0
            if (row - 1, col) not in banned_srcs:
                before += above
            this_row.append(before)
        prev_row = this_row
    return prev_row[-1]

if __name__ == '__main__':
    assert 252 == avoid_roads(6, 6, banned_roads(['0 0 0 1', '6 6 5 6']))
    assert 2 == avoid_roads(1, 1, {}})
    assert 112186277816662845432 == avoid_roads(35, 31, {}})
    assert 0 == avoid_roads(6, 6, banned_roads(['0 0 1 0', '1 2 2 2',
                                                '1 1 2 1']))

Note how the initialization of prev_row and before spares us from having to check if we are at the first row or column, which I think makes the logic cleaner. I am also a big fan of enumerate over iterating over a range and extracting the entry via indexing, but YMMV.


It's not really clear what you mean by "functional".

The use of reduce is nifty, and correctly done, but it seem like cargo cult programming. The realization that a lot of loop-like actions can be represented in terms of reduce (fold, aggregate, etc) is important to functional programing, but it should no more be your first choice than a while-loop.

The fact that it's verbose isn't necessarily a problem. It suggests that you might be failing at a general goal:

  Write what you mean.

One of the things that makes functional programming good is that it helps us do that.
Javascript has limited tools for directly declaring lists. What you mean to do is declare a Dictionary from the Set of duration values to the Count of the source array Filtered by the respective duration. Or even better you could use a grouping function.

You could bring in a library for the task, which may be a good idea, or you could compromise a little.

function getCounts(items, key){
  let c = {};
  for(let item of items){
    c[key(item)] = items.filter(function(i){
        return key(i) === key(item);
      }).length;
  }
  return c;
};
counts = getCounts(durations, function(i){ return i['duration']; })'

You'll notice that that's quite inefficient. We could make it less wasteful, but it'd be less terse.


Finding number of times each string in an Array of strings occurs in a large stream of characters (i.e large string)

Given that you stated this was for an interview, I'm going to focus not on how to make this code as fast as possible, but instead, the types of things I'd be looking for in an interview candidate.

First, and most concerning, there is not function or method definition here.  Presumably, you just typed this code straight into the main function.  That'd be the first worrying thing for me if I'm in this interview.

Upon hearing the acceptance criteria, I'd immediately expect a function signature to be written out:

NSDictionary<NSString *, NSNumber *> * _Nonnull findStringsInString(
    NSArray<NSString *> * _Nonnull,
    NSString * _Nonnull
);

You're already getting bonus points from me if you type this out.

You've demonstrated that you have some understanding of what is expected.  At a minimum, you're completely clear on what sort of inputs and outputs make sense.  And the function name will give some indication that you know what's going on.
You've demonstrated above knowledge in the form of a function.  The next step of the interview could be writing some unit tests around the function.  Even if we don't get that far, even if you're not familiar with unit testing, if you can write your code in a testable manner, that's a plus.
You've taken into account Swift annotations so this method will show up nicely in Swift.  Even if it's not used from Swift, these annotations help self-document the function and lessen the need for comments.

I'd also be okay if you wrote this as an extension method on NSString.

- (NSDictionary<NSString *, NSNumber *> * _Nonnull)occurencesOfStrings:(NSArray<NSString *> * _Nonnull)strings;

Second problem (get ready to notice a theme here), you haven't broken your problem down into logical sub-problems.  How can we count the occurrences of an array of potential substrings if we can't yet even count the occurrences in a single potential substring?

The body of your findStringsInString function needs to really look simply like this:

NSDictionary<NSString *, NSNumber *> * _Nonnull findStringsInString(
    NSArray<NSString *> * _Nonnull substrings,
    NSString * _Nonnull string
) {
    NSDictionary * results = [NSMutableDictionary dictionary];
    for (NSString * substring in substrings) {
        results[substring] = countOccurrencesOfSubstringInString(substring, string);
    }
    return results;
}

Why should it be this simple?  Because the countOccurrencesOfSubstringInString also needs to be a very simple function that is easy to write tests around.  Finding the count for multiple strings is just a simple expansion over the problem of finding the count for a single string.

For the problem of finding the count of a substring in a string, I'll just point you toward this Stack Overflow question which has multiple good answers.

As for actually writing the unit tests for either of these functions, I wouldn't necessarily expect it during an interview, but I'd be delighted to hear the candidate ask about it.  Whether or not we did it would depend on whether the candidate asked about it, and completed the first part relatively quickly.  But the combination of writing easily testable functions and asking me about testing itself would be enough information about the candidate's attitude toward testing (which I find important).

You notice how I still haven't really addressed any performance issues?  As an interviewer, I simply have never cared.  When candidates ask me if I want to fastest possible solution to a programming challenge, I always respond with something like this:

  I want the solution that works with the least amount of your time invested.  After we have a working solution, we can talk about optimizations.

We'll usually have specific criteria on the minimum acceptable performance of our code.  That criteria is never phrased as "as fast as possible".  It comes with a benchmark.  It must perform in less than some measurable amount of time.  It's either below that and good enough or above that and not good enough.  For almost all things you do, there is never the requirement that a solution work as fast as possible.  (There is usually the requirement that it not be slow, and slow is a concrete value.)

So, let's talk about style, and the readability of your solution.

#define VALUE_KEY 1
#define COUNT_KEY 2

These #defines are weird and unnecessary.  As you'll read later, a better data structure makes these completely obsolete, but if we must use them, I much prefer solutions that aren't preprocessor find & replace.

I'd prefer

NSNumber * const kKeyValue = @1;
NSNumber * const kKeyCount = @2;

NSMutableArray *stringsToSearchFor = [@[[@{@VALUE_KEY: @"cat", @COUNT_KEY: @0} mutableCopy],[@{@VALUE_KEY: @"aca", @COUNT_KEY: @0} mutableCopy], [@{@VALUE_KEY: @"hello", @COUNT_KEY: @0} mutableCopy],[@{@VALUE_KEY: @"world", @COUNT_KEY: @0} mutableCopy]] mutableCopy];

This is an absolute mess on so many levels.

First of all, a little bit of whitespace breaks cleans this up a lot.

NSMutableArray *stringsToSearchFor = [@[
    [@{kKeyValue: @"cat", kKeyCount: @0} mutableCopy],
    [@{kKeyValue: @"aca", kKeyCount: @0} mutableCopy],
    [@{kKeyValue: @"hello", kKeyCount: @0} mutableCopy],
    [@{kKeyValue: @"world", kKeycount: @0} mutableCopy]
] mutableCopy]

But this is still far from ideal.  Read the problem statement again.

  Given a stream of characters (e.g. acacabcatghhellomvnsdb) and a list of words (e.g. ["aca","cat","hello","world"] )

We're not going to get this mutable array of mutable dictionaries as our input.  You just assumed this would be the input.  At this point, as an interviewer, I'd be a little irritated.  Your code is going to either take the time to build out this overly complicated data structure, or worse, you're going to expect input in this overly complicated data structure.  I say the latter is worse because it demonstrates no technical empathy (or indicates you misread the requirements, which is also very bad).  Be clear on the requirements, and if you're unsure, ask.  It won't make you look bad during an interview--it will make you look good to get clarification on anything that's unclear.  The 30 seconds it takes to ask a question can save days of work in the real world.

And the worst part is that as my earlier code snippet demonstrates, there's a very easy solution here for what our data structure looks like.  And you should never be creating dictionaries whose keys roughly translate into @"key", @"value".

Any time you have a dictionary with two key value pairs that looks something roughly like this:

@{@"key": someKey, @"value": someValue}

You've messed up.  Especially because you probably have an array of these dictionaries.  And it's extraordinarily hard to extract values out of an array of dictionaries that look like this (believe me, the current project has to deal with an API that provides some user settings to me in this format).

The dictionary should instead simply look like this:

@{someKey: someValue}

And now you don't need an array of these dictionaries.  You can just have a dictionary:

@{
    someKey: someValue,
    anotherKey: anotherValue
}

On most lines (but not all), you have placed a space before the semicolon.  These seems very strange to me.  It is generally preferred not to have this space.

else
{
    break ;
}

Given that there's nothing else in the while loop, these four lines of code are entirely unnecessary.

if(currentStringNumFound)
{
    nextDict[@COUNT_KEY] = @(currentStringNumFound) ;
}

I know this technically works, but I've got a couple issues with it.  First of all, this is hard to follow.  We're relying on the fact that in C, non-zero equates to true, and then we're immediately inserting that same variable into a dictionary as a count.  I'd much prefer it if we just wrote:

if (currentStringNumFound > 0)

This more clearly mirrors the actual logic you're applying here.  You only want to insert the value if it was found at least once.

So that can make the readability and intent more clear.  But I'm a little concerned here that this is perhaps not the intended behavior.  If I passed in a string and it wasn't found in the dictionary, how can I be confident that it was even checked at all?

In fairness, the result would give me nil for whatever key I was looking for, and that'd really translate equivalently to 0.  But it doesn't translate equivalently in the case that I wanted to call some prettify NSNumber extension I wrote on it.

So, for example, if I had an NSNumber extension something like this:

- (NSString * _Nonnull)prettifiedCount;

I might expect the result of calling this on an NSNumber representing zero to be @"zero", but if I called it on what I got out of your result for a string that wasn't found, I'd get nil.

And the thing is, it won't be nil in your dictionary because of that very strange data structure you set up in the beginning, but that data structure definitely needs to change, so keep this part in mind when you're changing your data structure.

Finally, logging.

I really don't want my utility functions spitting out logs.  Yeah, you probably need that log to demonstrate to the interviewer that it's working, but to be clear, if you rewrite this per the guidelines I've set forth throughout this answer, you'll have all of your logic wrapped up in these functions.  There shouldn't be any logging within those functions.  If you want to log the results after the fact, sure, go ahead... but not within the functions themselves.


I am not sure how efficient it is. Is there any solution that is more efficient?

Very inefficient.

First, you allocate buffers with new/delete. You should not do that. Second, you allocate in a loop. You shouldn't do that either.

Consider this code instead (function renamed to to_string, as what you do is not parsing - parsing would be the inverse operation - taking a string and extracting an integer from it):

auto print(char * buffer, int x)
{
    return sprintf(buffer, "%d", x);
}

auto print(wchar_t * buffer, int x)
{
    return wsprintf(buffer, "%d", x);
}

///Converts integer to std::string
///@param x the integer to convert
///@return std::string/std::wstring from the integer
template<typename C,
    typename T=std::char_traits<C>,
    typename A=std::allocator<C>>
std::basic_string<C,T,A> to_string(int x)
{
    C buffer[ 64 ] = { 0 }; // no new/delete required
                            // no loop required
                            // max int on 32bit architectures is
                            // 2,147,483,647; 64 bytes is "big enough"

    auto written = print(buffer, "%d", x);
    assert(written > 0); // should always be true
    return std::basic_string<C,T,A>{ buffer, buffer + written };
}

Advantages:

there is no code repetition (easier to maintain)
efficiency is linear in to_string (no loops)
code is simpler and more straight-forward


Scary?  In what way?  I don't really get that.

It's just syntax.  If you really care, just cast the arrays as stdClass objects

foreach ( $p['PostComment'] as $comment )
{
  $comment = (object) $comment;
  $this->Controls->Add( new CommentPanel(
      $comment->text
    , $comment->User->nickname
    , $comment->last_updated_ts
  ));
}


At first, I thought that you were going to implement division of two integers, each represented as a list of digits.  But then, you simply concatenate all of the elements of each operand to be parsed as a double.  If you're going to cheat on the arithmetic using the built-in floating-point support, then what's the point of the exercise?  In fact, it doesn't even care whether you pass in an ArrayList of individual digits {1, 2, 3, 4, 5} or an ArrayList of one element {12345} — either way, it all gets stringified and parsed as 12345.0d.


General notes:

use if __name__ == '__main__': to avoid the main() function to be executed when the module is imported
I'd pass around the credit card number as a string instead of converting it to string in every single validation step
add docstrings to each of the defined functions

Regarding check_provider() function:

you can check the length to be in range in one go:

if not(13 <= len(str(number)) <= 16):

I would improve the way you distinguish between cards by introducing a mapping between brands and regular expressions (like it was done in pycard module). Then, match each of the expressions one by one until you find a match or a brand was not found:

import re

BRANDS = {
    'Visa': re.compile(r'^4\d{12}(\d{3})?$'),
    'Mastercard': re.compile(r'''
        ^(5[1-5]\d{4}|677189)\d{10}$|  # Traditional 5-series + RU support
        ^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)\d{12}$  # 2016 2-series
    ''', re.VERBOSE),
    'American Express': re.compile(r'^3[47]\d{13}$'),
    'Discover': re.compile(r'^(6011|65\d{2})\d{12}$'),
}

def check_provider(number):
    """Checks a credit card number and returns a matching brand name, or INVALID if no brand matched."""
    for brand, regexp in BRANDS.items():
        if regexp.match(number):
            return brand
    return 'INVALID'

Regarding implementing the Luhn algorithm, check the pycard's implementation - it is quite clean and understandable.


There is a serious problem at:

def get_random(min, max):
    print "Coming up with a number."
    time.sleep(2)
    random_number = random.randint(min, max)
    print "Got it!"
    return random_number

This function mixes user interaction (printing and sleeping) and logic (returning a random number). This is basic separation of intents, and should be taught to beginners from the start.

The same can be seen at:

def hi_low_done(delta):
    if delta < 0:
        print "Guess lower."
        return False
    elif delta > 0:
        print "Guess higher."
        return False
    else:
        print "You got it!"
        return True

This function should only return a message, not return a message and print.

About to_int

def to_int(x):
    try:
        x = int(x)
        return x
    except ValueError:
        print "That is not a whole number."
        return False

While it is possible to return different types from a function in Python, it is a symptom of bad design. I reccomend writing a is_int method to return True or False if the argument is an int and then converting to int with int.

Further refactoring

Asking a user for yes or no is a common task and should be its own function, also using startswith is more flexible and allows 'yeah' and 'yup' for example.

Also you should write a function to generate the message. You then print it and break if guess and real number are equal.

Use Python 3

Python 3 is continually improved while Python 2 is deprecated, it makes more sense to teach 3 than 2 (The two are similar just use parens around print).

Avoid needless comments

Comments should tell why not what, if you write

# imports

You just add noise as it is obvious that the following lines are imports.

Define a main function and call it

It is a good habit to get into and allows the importing of scripts.

Like:

def number_guessing_game(minimum, maximum):
     # All your currently top level code

if __name__ == "__main__":
    number_guessing_game()


Searching for files across multiple code projects

For a base line, I modified your script so that it is not dominated by printing to the console:

open System
open System.IO

let directory = @"C:\Dev"

// this just keeps async operations from writing to the console concurrently (garbled result)
let agent = MailboxProcessor.Start(fun inbox ->
    // the message processing function
    let count = ref 0
    let rec messageLoop () = async {
        let! msg = inbox.Receive()
        count :=  !count + 1
        return! messageLoop()
    }
    // start the loop
    messageLoop ()
)

let checkIfContains value file = async {
    use reader = new StreamReader(File.OpenRead(file))
    let lineNum = ref -1
    let postResult (i, s) = sprintf "%s\r\n%i: %s\r\n" file i s |> agent.Post

    seq { while not reader.EndOfStream do
            incr lineNum
            yield (!lineNum, reader.ReadLine()) }
        |> Seq.filter (fun (_, s) -> s.Contains(value))
        |> Seq.iter postResult
}

let files =
   Directory.EnumerateFiles(directory, "*.cs", SearchOption.AllDirectories)

let value = "papa"

files
    |> Seq.map (checkIfContains value)
    |> Async.Parallel
    |> Async.RunSynchronously
    |> ignore

agent.Post "\r\nDone.\r\n\r\n"

This takes ~10 seconds on my machine.
Like Carsten said, there's no need for a MailboxProcessor. Removing it takes me down to ~7.5 seconds.
Next, there's no need for Async. There is no ! in that async comp expression. We could use Seq.AsParallel instead (in System.Linq namespace). Down to ~6.3 secs.

Now this task is dominated by IO, and AsParallel shouldn't help here. In fact, removing it yields the same result, ~6.3 secs.

Now, that seq inside of checkIfContains looks wasteful. Getting rid of that yields ~6.1 secs, so no big win.

I wouldn't consider this idiomatic code. I just took out some unused stuff, and wound up with this:

open System
open System.IO
open System.Linq
let directory = @"C:\Dev"
let count = ref 0
let print s = lock count (fun () -> count := !count + 1)

let checkIfContains value file =
    use reader = new StreamReader(File.OpenRead(file))
    let lineNum = ref -1
    let postResult i s = sprintf "%s\r\n%i: %s\r\n" file i s |> print
    while not reader.EndOfStream do
      incr lineNum
      let line = reader.ReadLine()
      if line.Contains(value) then postResult !lineNum line

let files = Directory.EnumerateFiles(directory, "*.cs", SearchOption.AllDirectories)
let value = "papa"
let f = files
              |> Seq.map (checkIfContains value)
              |> Seq.iter id


There is not much to be said actually, the concept-based polymorphism seems to be well implemented. You can slightly improve your push_back method by having it emplace_back the std::unique_ptr. It will be a little bit less verbose:

template<class T>
void push_back(T control){
    auto t = new drawable_model<T>(std::move(control));
    controls_.emplace_back(t);
}

Also, I suppose that a draw shouldn't alter the object being drawn. Therefore, you better const-qualify all of your draw methods.

You could also be more consistent with the way you use inline: you inlined drawable_forwarder's draw method but not drawable_model while it basically does the same thing.

One fun addition would be to write a method that would create the drawable_model object in-place. That would require to add the following constructor to drawable_model:

template<typename... Args>
drawable_model(Args&&... args):
    model_(std::forward<Args>(args)...)
{}

And the following method to graphics_surface (not sure about the name):

template<typename T, typename... Args>
void emplace_back(Args&&... args)
{
    auto t = new drawable_model<T>(std::forward<Args>(args)...);
    controls_.emplace_back(t);
}

Then, you could use it this way:

int main()
{
    graphics_surface surface;

    // Assume triangle and rectangle have complete constructors
    surface.emplace_back<triangle>(3.5, 6.8, 4.8, 3.2);
    surface.emplace_back<square>(/* whatever */);

    surface.render();
}


Capitalize the first letter of all words in a String

This is a cool little problem that needs Java8, and regex. ... promise.

First up, the Pattern.splitAsStream(...) method is new in Java8, and converts a string in to a stream of substrings, depending on the pattern, so, what's the pattern?

Well, the pattern is to match the beginning of any word that needs to be capitalized. Your code currently finds characters, after whitespace, but that is, as you admit, too naive. Words that need capitalization are things like:

This is 'quoted' -> This Is 'Quoted'
This has-joined-words -> This Has-Joined-Words
This should not 1800not1337 -> This Should Not 1800not1337

and so on.

So, your code would not deal well with the above examples.... but, how can it be better?

private static final Pattern bound = Pattern.compile("\\b(?=\\w)");

The above regular expression looks for a word-boundary that is followed by a character (where "a character" is a letter, digit, or underscore).

Then, you have a sequence of sentence parts that need captialization, and it can be streamed easily:

private static final Pattern bound = Pattern.compile("\\b(?=\\w)");

private static final String ucFirst(String input) {
    return input.substring(0,  1).toUpperCase() + input.substring(1);
};

public static String titleize(final String input) {
    return bound.splitAsStream(input)
          .map(StringCap::ucFirst)
          .collect(Collectors.joining());
}

You can see this running here: http://ideone.com/ilmBqi

Note: Using Java7 versions of Pattern matchers, it is also actually quite easy.... Consider this pattern, which stores the first-character as a pattern group, and then the "traditional" matching replacement loop:

private static final Pattern bound = Pattern.compile("\\b(\\w)");

public static String titleize(final String input) {
    StringBuffer sb = new StringBuffer(input.length());
    Matcher mat = bound.matcher(input);
    while (mat.find()) {
        mat.appendReplacement(sb, mat.group().toUpperCase());
    }
    mat.appendTail(sb);
    return sb.toString();
}

The above is able to capitalize the words in the same output as the Java8 version above.


C++ reduce repetitions of code for similar classes

Yes, there is. In fact, a very nice way to solve this code redundancy issue comes to mind if you consider that std::string is a just type alias for std::basic_string<char> and std::wstring an alias for std::basic_string<wchar_t>. Likewise, std::stringstream and std::wstringstream are also just aliases for std::basic_stringstream<char> and std::basic_stringstream<wchar_t>, respectively. This allows for an easy template-based approach to the problem.

What really suggests itself to me is keeping this alias-of-template-base-type pattern from the STL (although there may be other valid approaches as well), an implementation of which could look something like this:

#include <sstream>
#include <string>

namespace impl {

    template <typename CharType>
    class StringBuilderImpl {

        std::basic_stringstream<CharType> stream;

        public:
        template <typename T>
        StringBuilderImpl& operator<<(T const& t) {
            stream << t;
            return *this;
        }

        operator std::basic_string<CharType>() const {
            return stream.str();
        }
    };
}

using StringBuilder = impl::StringBuilderImpl<char>;
using WStringBuilder = impl::StringBuilderImpl<wchar_t>;

StringBuilderImpl corresponds somewhat to std::basic_[string/stringstream] and takes the underlying character type as a template argument. Your former classes StringBuilder and WstringBuilder are now only aliases for certain template specializations, just as std::[string/wstring] and std::[stringstream/wstringstream] are.

(In my code, StringBuilderImpl is kind of hidden away inside an impl namespace. If it serves your need, however, you could also make it part of the public interface of your program library, allowing further specifications such as StringBuilderImpl<char16_t>)