Quick Sum TopCoder (Brute Force solution)

public static int minSums(String numbers, int sum) {
  int N = numbers.length();

variables should be named using camelCase casing so n would be better, but what does N/n represent ? Its the number of digits contained in the String numbers which isn't named correctly because there is only one number passed which consists of multiple digits. So a better way would be like so

public static int minSums(String number, int sum) {
  int digits = number.length();

but as the default indentation is 4 spaces this should be like so

public static int minSums(String number, int sum) {
    int digits = number.length();

This if..else if..else construct can be simplified because for the first cases you are returning a value the else if..else aren't needed and will save some horizontal spacing if removed. You should have the two cases where you check for N == 2 into one single if with a nested if..else like so

// changed N to digits

if (digits <= 3 && sum == Integer.parseInt(numbers)) {
    return 0;
}

if (digits == 2) {
    if (Integer.parseInt(numbers.substring(0, N - 1))
       + Integer.parseInt(numbers.substring(N - 1)) == sum) {
        return 1;
    } else {
        return -1;
    }
}

if (digits == 1 && Integer.parseInt(numbers) != sum) {
  return -1;
}

// solution

Commented out code is dead code and should be removed because it is only adding noise to the code which decreases readability.

Let your variables and operators have some space to breathe. Something like int offset = len-N+k; isn't just as readable as int offset = len -N + k;.


How can I simplify the following code that calculates standard deviation

If the method calculate standard desviation, it should return the value, not assign a global variable or instance variable.

Regards,


String 'expanding' - reinserting repeating characters

Your instincts are good here, in almost all respects. Your basic algorithm is good, and your suspicions that you are changing too often between String an char is also good.

Using the StringBuilder is the right thing to do, well done. Breaking the String in to chars is also good, but the way you do that is inconvenient.... In part that's because there is a convenient function in the standard Java Character class that you will find useful: Character.isDigit(char)

With that function, you can throw out your isNumber() function, and simplify the whole thing down to chars, strings, and ints.... something like:

public static String blowup(String str) {
    StringBuilder sb = new StringBuilder();
    int repeat = 0;
    for (char c : str.toCharArray()) {
        if (Character.isDigit(c)) {
            repeat = repeat * 10 + Character.getNumericValue(c);
        } else {
            while (repeat > 0) {
                sb.append(c);
                repeat--;
            }
            sb.append(c);
        }
    }
    return sb.toString();
}

(I put this in an Ideone here)

Note that it also keeps a counter outside the loop. This removes the need for the 'ugly' i + 1 offset on a repeating character count.

The code still assumes valid input (where the last character cannot be a digit, or it is lost). Additionally, I tweaked it to handle multiple digit input.... like 20z ... for fun.

Update: In my mind, I immediately 'threw out' your isNumeric() method, because it was not needed... but I have only now just read it.... Eeugh! Yuck!

You should never use exception handling (try/catch) to handle normal program flow. The try/parse/catch logic you have is very slow to run. Throwing an exception for every non-digit character will be a lot of overhead. Even though Java has improved in terms of performance, when processing exceptions, it is still much slower than the alternatives, like a regular expression, or some other mechanism...

Update 2: working with the original specs (thus ignoring the multi-digit repeat), the code would be (here in a different Ideone):

public static String blowup(String str) {
    StringBuilder sb = new StringBuilder();
    int repeat = -1;
    for (char c : str.toCharArray()) {
        if (repeat < 0 && Character.isDigit(c)) {
            repeat = Character.getNumericValue(c);
        } else {
            do {
                sb.append(c);
            } while (--repeat >= 0);
        }
    }
    return sb.toString();
}

Notes for this version:

Use the 'repeat' as a flag set to negative for nothing. This allows for input like ab01 which will output ab1 (which would be impossible without the 0-repeat option).
Note that the repeat is now also used as a flag for the isDigit check.
a do-while loop instead of a while-do loop (as per Josay's comment).


Summing a sequence of fractions to a limit n

I'm wondering if there's anything I can do for the edge case of n = 1?

Yes, I think you are considering it to much (see below: you can simply remove some branching)

  Also, looking at the types for each value, I'm wondering if I need to think more about the data types I chose to use, in terms of should I use a double for this, or an int?.

I think your current choice is fine: int for the denominator and double for the accumulator.

Following your program (my comments adress the previous block of code):

public static void sequenceSum(double n){
    if(n > 1.0){

I think you can simply remove this first condition (already well managed in the while loop)

        int denominator = 1;
        double accumulator = 0;
        System.out.print("1");
        while(accumulator < n) {
            accumulator += ( 1.0 / denominator);
            if(denominator > 1.0){

Your denominator is an int: you should compare it with 1 (and not 1.0)

                System.out.print(" + " + 1 + "/" + denominator);

You should integrate the 1 into the string: " + 1/".

            }
        denominator++;
        }
    System.out.printf(" = %1.3f", accumulator);
    } else if(n == 1.0){

This branch can simply be replaced with a condition at the very beginning to check if n < 1.0 and immediately return if it is the case.

        System.out.print("1 = 1.000");
    }
}

Miscellaneous

Instead of printing each time, you could append to a StringBuffer

You have good variable names, except for n. Maybe sumLimit is more appropriate? (or accumulatorLimit).

Simplifying > 1 conditions

You could start your denominator at 2 and your accumulator at 1.0, to get rid of the if condition inside your while loop (if n is 1.0, then the while loop will simply not be executed at all).


Python Optimizing/Speeding up the retrieval of values in a large string


Intersection of Array Question, limited only to methods

If you want to optimize you can : Use arrayCopy() from the System Class to create the final array and reduce variable. Here is my "solution" :

public static Object[] handleArrayIntersection(Object[] array1, Object[] array2) {
    Object[] dest;

    int itemCount = 0;
    Object[] intersect = new Object[array1.length < array2.length ? array1.length : array2.length];

    for(int i = 0; i < array1.length; i++) {
        Object arr1Val = array1[i];
        if(contains(array2, arr1Val) && !contains(intersect, arr1Val)) {
            intersect[itemCount++] = arr1Val;
        }
    }

    dest = new Object[itemCount];
    if(itemCount > 0) {
        System.arraycopy(intersect, 0, dest, 0, itemCount);
    }

    return dest;
}


Your biggest problem is that you are using static for everything.  Change all of the static variables to instance variables, and all of the static methods (apart from main) into instance methods.  Then have your main method create an instance of JournalAnalyzer and call the (now instance) methods on that instance.

That will make the code more testable.  Another thing you need to do to improve testability is to make the methods you want to test public.


Performance

What's the next power of 2 smaller than this number (binary presentation)?

0b00100101010010011

It's all the 1's reset except the first:

0b00100000000000000

What's the next power of 2 greater? It's smaller number shifted to left:

0b01000000000000000

The implementation of this logic will be both faster and simpler.

However, be mindful of the special cases when the target number is exactly a power of 2 or zero.

else if

This didn't work on my computer:

if (n - y) == (x - n)
    puts "#{x} and #{y} are the closest powers of 2 to #{n}."
else if (n - y) < (x - n)
    puts "#{y} is the closest power of 2 to #{n}."
else
    puts "#{x} is the closest power of 2 to #{n}."
end

I had to change the else if to elsif.

Don't repeat yourself

Instead of this:

if (n - y) == (x - n)
    puts "#{x} and #{y} are the closest powers of 2 to #{n}."
elsif (n - y) < (x - n)
    puts "#{y} is the closest power of 2 to #{n}."
else
    puts "#{x} is the closest power of 2 to #{n}."
end

It would be better to reduce the duplication in the printing:

if (n - y) == (x - n)
    puts "#{x} and #{y} are the closest powers of 2 to #{n}."
else
    if (n - y) < (x - n)
        result = y
    else
        result = x
    end
    puts "#{result} is the closest power of 2 to #{n}."
end


When I went through the WYAS48 I made the same decision of breaking the bits of eval off into smaller functions. I found this made testing easier since I could focus on just one function at a time.

I find that having a function be one massive bunch of logic is not helpful. In an imperative language the equivalent would be a single function with a ton of if/else or case/switch logic. Whenever I see that I tend to break things off into more manageable functions.

The issue that tends to happen is the little functions need some kind of state from the original big function. Finding this out and resolving it can be difficult at times and others just plain messy. The code is often better for it in the end.


Executing remote command using expect from C++

Consider using raw literals

Your expect_template is a prime candidate to be written as a raw string literal:

const char* expect_template =
R"(set timeout 60
spawn ssh %s@%s %s
expect {
   "*yes/no*"
   {
       send "yes\r"
       exp_continue
   }
   "*?assword:*"
   {
       send -- "%s\r"
       send -- "\r"
       expect eof
   }
}
)";

I may have missed something in the editing, but the basic idea is pretty simple: you don't use escapes at all, just insert exactly what you want the string to contain (including new-lines).

Given an R immediately before the quote, the compiler treats the content as a raw literal. The opening delimiter is the quote, other optional "stuff", and an open paren. The closing delimiter is a close paren, the same optional stuff, and the close quote. In your case, the optional "stuff" isn't needed--you'd use it if you might need to include )" as part of your string. In that case, you might have something like R"<^>( at the beginning so the end of the string would only be signaled by )<^>" (the exact content doesn't matter a whole lot--you just have to be sure it's something that can't occur inside the string).

Use of .c_str()

C++98/03 required that you use s.c_str() when passing s to a stream's constructor or open member function. C++11 eliminated that requirement, so you can just pass the string directly.

Passing strings as parameters

Absent a reason to do otherwise, I'd at least consider passing std::string const & as the parameter to (for one example) TempFile::TempFile. This can simplify some of the content a little, and still lets you pass a C-style string when/if you want:

explicit TempFile(std::string const &contents) {
    file_name = std::tmpnam(nullptr);
    std::ofstream f(file_name);
    if(!(f << contents)) {
        throw std::runtime_error("writing ofstream");
    }
}

Use of snprintf

You might want to consider using a stringstream instead of snprintf. This does ease at least a few parts of the job, although it's not exactly perfect either.

std::ostringstream s;

s <<
R("set timeout 60
spawn ssh )" << user << "@" host << " " command << R"(
expect {
   "*yes/no*"
   {
       send "yes\r"
       exp_continue
   }
   "*?assword:*"
   {
       send -- ")"
<< password << R"(\r"
        send -- "\r"
        expect eof
    }
}
)";

TempFile f(s.str());


constexpr everything

Apart from the #define, your code is quite good. But you miss on a really simple optimization by not using constexpr, which has different meanings in different contexts:

constexpr variables are compile-time constants. They're a good replacement for constant defining macros.

#define UPPER_BOUND 1000 // bad, because preprocessing leads to a lot of bugs
constexpr int upper_bound = 1000; // good, safe

constexpr functions can be executed at compile-time if their arguments are known at compile-time; the compiler will then substitute a constant to the function call in the code.

So let's extract a function from your main() and declare it constexpr:

constexpr int sum_of_multiples_of_3_and_5_under(int upper_bound) {
    int sum = 0;
    for (int i = 1; i < upper_bound; ++i) {
        if ( i % 3 == 0 || i % 5 == 0 ) {
            sum += i;
        }
    }
    return sum;
}

Now, whenever you call it with an upper_bound you know at compile-time, it will run at compile-time.

Generalize your code

Running your function at compile-time means a lot, because if you can't and need your code to run fast at run-time, you'll have to implement better algorithms. As @Dannnno pointed out, you could have used the algorithm to compute an arithmetic progression, which is O(1) instead of O(n) for your code:

constexpr int sum_multiples_under(int ratio, int upper_bound) {
    int nb_val = (upper_bound - 1) / ratio;
    int high = nb_val * ratio;
    int extremes = ratio + high;
    return nb_val * extremes / 2;
}

You can then compute the sum of the multiples of 3 and 5 with:

auto sum = sum_multiples_under(3,  1000)
         + sum_multiples_under(5,  1000)
         - sum_multiples_under(15, 1000);

It's quite easy to implement, even if it consumes a bit more brain-power than the for-loop. But let's say that we want to generalize our code, and make it work for any number of divisors, for instance the sum of the multiples of 3, 5 and 7. Then it becomes a lot harder: you have to add all members of one set, then subtract all members of two sets, then add all members of three sets... etc. That means computing combinations, applying functions to arrangements, etc. Whereas our for-loop scales quite comfortably.

Use fold expressions

With fold expressions (which require C++17), you can generalize your code fairly easily:

template <typename... Multiples>
constexpr int sum_of_multiples_under(int upper_bound, Multiples... multiples) {
    int sum = 0;
    for (int i = 1; i < upper_bound; ++i) {
        if ( ( ... || (i % multiples == 0)) ) {
            sum += i;
        }
    }
    return sum;
}

Multiples is a variadic template parameter. It can stand for any number of arguments. You can then expand the arguments' pack inside your function. Fold expressions allow you to expand it around an operator. In this case, the operator is ||. ( ... || (i % multiples == 0)) will be expanded into:

   (i % multiples_1 == 0)
|| (i % multiples_2 == 0)
|| ...
|| (i % multiples_N == 0)

Conclusion

constexpr is a really, really useful keyword, and is a sign of modern, optimized C++ code. Use it without moderation. If you want to know everything about it, there's a keynote on YouTube named "constexpr everyting".


C: Approxmation of Pi with stratified sampling

Bug #1

In your first test:

        if(pow((i+1) / g,2)+pow((j+1) / g,2) < 1){

you didn't convert (i+1)/g to a double correctly.  You are using integer math, so (i+1)/g is going to be zero until i reaches g-1.  What you wanted to do was this:

        if(pow((double)(i+1) / g,2)+pow((double)(j+1) / g,2) < 1){

Bug #2

In your second test:

        }else if(pow(i,2)+pow(j,2)>1){

you forgot to divide by g.  So it should have been:

        }else if(pow((double)i/g,2)+pow((double)j/g,2)>1){

Bug #3

Your last test was OK, but you added the wrong amount to inbound:

                if(pow(x,2)+pow(y,2)<=1){
                    inbound+=k;
                }

Here, it should have been:

                if(pow(x,2)+pow(y,2)<=1){
                    inbound++;
                }

Otherwise, later when you divide by the number of samples, the math won't work out right.

Potential overflow

When I used 10000 points and a grid size of 1000, the calculation overflowed because inbound exceeded the maximum integer value.  You might want to use a 64-bit value instead of an int.

pow(x,2)

I have a pet peeve against writing pow(x,2).  I think that x*x is both clearer and faster.  Check my profile and you'll see.

Rewrite

Here is a rewrite of your program with the following additional changes:

Sped up the inner loop by multiplying against a precomputed value in order to avoid costly divisions.
Cosmetic changes to spacing, braces, indentation, and location of variable declarations.
Added temp variables to simplify the lengthy equations.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <stdint.h>

const double pi_exactly=3.14159265358979323846;

int main(void)
{
    int      m       = 0;
    int      g       = 0;
    uint64_t inbound = 0;

    srand(time(NULL));

    printf("Quantity of random points per square: \n");
    scanf("%d", &m);

    printf("Gridsize: \n");
    scanf("%d", &g);

    double rand_multiplier = 1.0 / ((double) RAND_MAX * g);

    for (int i=0; i<g; i++) {
        double x  = (double) i / g;
        double x1 = (double) (i+1) / g;
        for (int j=0; j<g; ++j) {
            double y  = (double) j / g;
            double y1 = (double) (j+1) / g;

            if (x1*x1 + y1*y1 <= 1) {
                inbound += m;
                continue;
            } else if (x*x + y*y > 1) {
                break;
            }

            for (int k=0; k<m; k++) {
                double xr = x + rand() * rand_multiplier;
                double yr = y + rand() * rand_multiplier;

                if (xr*xr + yr*yr <= 1)
                    inbound++;
            }
        }
    }

    double pi = (double) inbound / ((double) m * g*g)*4;
    double uncertainty = pi - pi_exactly;

    printf("The approximation of pi is: %lf\n", pi);
    printf("Uncertainty: %e\n", uncertainty);
    return 0;
}


Would be cool as a class decorator.

@Lazy
class MyFoo:
    ...

To me it seems like it would fit nicely as a class decorator because it's independent of what the class is representing.  It has more to do with the way the class works internally than it does with the thing that the class embodies.


Dijkstra - shortest Path implementation - STL

First: Why use a class?

Graph graph(adjancecy_list, cost_vector);
const auto result = graph.shortest_path(source_node, target_node);

This could easily be refactored to a simple function call of:

const auto result = shortest_path(adjancency_list, cost_vector, source_node, target_node);

Since all shortest_path does is access the classes adjancency_list and cost_vector, which can just be passed in, queue, which should just be a local variable, and is_valid_node, which could just be inlined as you only called it once.

Where you have used the class, there are some minor mistakes. In your constructor, you have initialised adjancecy_list and then cost_list. This should be the other way around (Or you should swap the members). The constructor is also explicit for no reason.

class Graph {
public:
  Graph(const AdjacencyListType &input_list,
        const CostEdgeVector &input_cost_list)
    : adjancecy_list(input_list), cost_list(input_cost_list) {}
  // ...
private:
  // The other way around
  const AdjacencyListType &adjancecy_list;
  const CostEdgeVector &cost_list;
}

      const auto &current_node = queue.top();
      queue.pop();

Is undefined behaviour. You take the const reference of a node, and then you delete it with pop. current_node would then be garbage. Just take a copy:

      const auto current_node = queue.top();
      queue.pop();

You should probably not use reference at all. The objects are all ints or std::tuple<int, int>s, which are very cheap to copy.

This:

    try {
      const auto &target_distance = distance_node.at(target);
      result = target_distance == INFINITY_VALUE ? -1 : target_distance;
    } catch (...) {
      result = -1;
    }

Can be worded in a much clearer way. First, try to avoid catch (...) as much as possible. The only thing that would throw is at, which throws a std::out_of_range, so you can write catch (const std::out_of_range&). However, exceptions are very confusing here. It only throws if target is too big, so you can write something like:

    if (target >= distance_node.size()) {
      result = -1;
    } else {
      const auto target_distance = distance_node[size];
      result = target_distance == INFINITY_VALUE ? -1 : target_distance;
    }

Or even better, change if (!is_valid_node(source)) return -1 to if (!is_valid_node(source) || !is_valid_node(target)) return -1, so that the target will always be in distance_node.

And (this is personal preference) I would avoid the c-like pattern of declaring a result variable. Where you do result = at the end can be replaced with just return, and it's still very clear.

If you are able to control your input, it would probably be easier to, instead of having two vectors which name the neighbour and have the cost of the edge, have a list of neighbours of pairs of nodes and costs. I would declare a helper struct:

struct edge {
  NodeType neighbour;
  CostType cost;
};

// or `using edge = std::pair<NodeType, CostType>;`, but that has less meaning

And have one vector of vector of these.

Also, you use a std::tuple<int, int> for "CostNodeTuple". Since there are only 2 values, it might have been easier to use a std::pair, so std::get<0>(t) turns into t.first, and std::get<1>(t) turns into t.second.

And if you swapped the order, you wouldn't need a custom comparator (As a tuple or pair's operator< does mostly what you want)

If you can do even more refactoring, I would consider using unsigned instead of int, as this doesn't work for negative edge weights (i.e. if there is a negative loop, it should have a value of -infinity). Instead of returning -1 for failure, you could throw an error (if this is an exceptional circumstance) or returning a std::optional<unsigned> (if disjoint graphs are common). The current solution is fine as is though.

Currently, using signed integers, there are a bunch of places where they are implicitly converted to unsigned integers (to use for array indices). It's not too much of a problem, but it shouldn't be the case (Maybe use std::size_t for NodeType?)


Unit testing Roman-Arabic-Roman numeric converter

I have two suggestions:

I like tests to be very easily human-readable. Instead of separate arrays of input and output, which are not aligned with each other, find a way to put the input and the expected output on one line.

The easiest way in this case would be to add a method

private void testRomanToArabic(String input, int expectedOutput) {
    assertEquals(RomanNumbers.romanToArabic(input), expectedOutput);
}

and then use this method repeatedly like

testRomanToArabic("XXXIII", 33);

etc. There are other ways to put input and expected output next to each other (e.g. create an object holding both), but this is the simplest.

Don't catch the AssertionError and print the result yourself. The test should be run by a test runner which will handle this part for you. I always do this from the Eclipse IDE by selecting "Run As JUnit Test", but there is for sure a way to do the same thing from the command line.

By catching the AssertionError, you hide the error from external tools, meaning you have to read the output yourself. If the AssertionError is thrown, your testing framework is aware of the error, which becomes very important when you have hundreds of tests: it can highlight for you the handful that are failing.


As long as queue is actually Queue.Queue (or another collection with its own blocking mechanic), the event object is not required in the code you posted. I'd even say that it's used incorrectly. There is a racing condition when the server calls event.set() and a thread is just done with its current task, calling event.clear(). This leaves all threads waiting on the event, even though there's an item in the queue.

Edit: Bollocks, didn't think that one through. event.set() wakes up all threads that are hanging on event.wait(), causing them to continue waiting at queue.get(). One thread will fetch the item and process it. So, no racing condition. Just redundancy.


How can I improve my A* algorithm in Python?

class PathFinder():

Either but object in the () or drop them. Having them there empty makes me feel hollow inside.

    ## grid is a list of 8 sub-lists, each containing 8 nodes.
    ## start and goal are tuples representing the grid indexes of my start and goal.

    def __init__(self, start, goal, grid):
        ## I don't do anything with these yet,
        ## just thought they would be good to have.
        self.goal = goal
        self.start = start
        self.grid = grid

    def find_path(self, start, goal, path=[]):

Don't put mutable values like list as your default parameters. Python will not create a new list everytime this function is called, rather it will keep reusing the same list which is probably not what you want

        ## My seemingly hackish method of looping through
        ## the 8 cells surrounding the one I'm on.
        for row in (-1,0,1):
            for col in (-1,0,1):
                if row == 0 and col == 0:
                    continue

I suggest creating a global constant with the 8 directions and doing: for row, col in DIRECTIONS:

                cell = [start[0]+row,start[1]+col]

Don't use lists unless they are actually lists. This should be a tuple.

                ## Catching the inevitable exception when I try to examine
                ## the surroundings of cells that are already on the edge.
                try:
                   ## Skip if the cell is blocked ("X").
                    if self.grid[cell[0]][cell[1]] == "X":
                        continue
                except IndexError:
                    continue

I suggest a function get_blocked that you pass cell to which check for 'X' and also returns True if the cell is off the side of the map. Also catching IndexError may not be quite what you want because negative numbers are valid indexes, but probably not want you want. I suggest checking in the get_blocked function for inboundedness.

                path.append(cell)
                if cell == goal:
                    return path
                self.find_path(cell, goal, path)

def main():
    import Gridder2

Usually not a good idea to import anywhere but at the start of a file

    grid = Gridder2.board()
    start = (0,0)
    goal = (0,3)
    pt = PathFinder(start, goal, grid)

pt?

    print(pt.find_path(start, goal))

Decide whether the start/goal get passed to the constructor or the find method. Don't do both.

    return 0

if __name__ == '__main__':
    main()

If you are going to return a value from your main function, you should pass it to sys.exit() so that it actually functions as a return code.

And everything Thomas said.


Convolution Filter
In CG this type of processing is call a convolution filter and there are many strategies used to handle edges
As the previous answer points out for performance you are best to use typed arrays and avoid creating arrays for each cell you process.
In your example

for (let i = 1; i <= kernelSize; i++) {
    adjacentValues = adjacentValues.concat(this._getAdjacentValues(row, col, i, grid));
}
const average = adjacentValues.reduce((a, b) => a + b, 0) / adjacentValues.length;

You can do the reduce in the loop you create the sub array in, and avoid the 9 new arrays you create and the need to iterate again.
Example substitute value at edges.
const edgeVal = 0;
var val, sum = 0;
for (let i = 0; i < 9; i++) {
    val = grid[row + (i / 3 | 0) - 1];
    if (val !== undefined) {
         val = val[col + (i % 3) - 1];
         sum += val !== undefined ? val : edgeVal;
    } else {
         sum += edgeVal;
    }
}
const average = sum / 9;

Or ignore edges
var val;
var sum = 0;
var count = 0;
for (let i = 0; i < 9; i++) {
    val = grid[row + (i / 3 | 0) - 1];
    if (val !== undefined) {
         val = val[col + (i % 3) - 1];
         if (val !== undefined) {
            sum += val;
            count ++;
         }
    }
}
const average = sum / count;

Better yet, work on flattened arrays to avoid the double indexing for 2D arrays, and create the result array at the start rather than pushing to it each cell.
Workers
Convolution filters are ideally suited for parallel processing with an almost n / p performance increase (n is number of cells, p is number of processing nodes).
Using web workers on a i7 4 core (8 virtual cores) can give you a 8 times performance increase (On chrome (maybe others) you can get a core count at window.clientInformation.hardwareConcurrency)
Attempting to use more workers than available cores will result in slower processing.
GPU
For the ultimate performance the GPU, via webGL is available and will provide realtime processing of very large data sets (16M and above), A common non CG use is processing layers in convolutional neural network.
An example of a convolution filter (About halfway down the page) using webGL can easily be adapted to most data types, however doubles will only be available on a small number of hardware setups.


C++ fixed-size queue full/empty signaling

Use a semaphore to cause the producers to sleep when the queue is full, and another semaphore to cause the consumers to sleep when the queue is empty.
when the queue is neither full nor empty, the sem_post and sem_wait operations are nonblocking (in newer kernels)

#include <semaphore.h>

template<typename lock_free_container>
class blocking_lock_free
{
public:
    lock_free_queue_semaphore(size_t n) : container(n)
    {
        sem_init(&pop_semaphore, 0, 0);
        sem_init(&push_semaphore, 0, n);
    }

    ~lock_free_queue_semaphore()
    {
        sem_destroy(&pop_semaphore);
        sem_destroy(&push_semaphore);
    }

    bool push(const lock_free_container::value_type& v)
    {
        sem_wait(&push_semaphore);
        bool ret = container::bounded_push(v);
        ASSERT(ret);
        if (ret)
            sem_post(&pop_semaphore);
        else
            sem_post(&push_semaphore); // shouldn't happen
        return ret;
    }

    bool pop(lock_free_container::value_type& v)
    {
        sem_wait(&pop_semaphore);
        bool ret = container::pop(v);
        ASSERT(ret);
        if (ret)
            sem_post(&push_semaphore);
        else
            sem_post(&pop_semaphore); // shouldn't happen
        return ret;
    }
private:
    lock_free_container container;
    sem_t pop_semaphore;
    sem_t push_semaphore;
};


General

private static int newSize(int oldSize) {
    int result = oldSize + (oldSize>>3) + 4; // Grow by about 1/8 only.
    if (result-MAX_ARRAY_SIZE > 0) result = MAX_ARRAY_SIZE; // Handle overflow.
    if (result<=oldSize) throw new OutOfMemoryError();
    return result;
}

Alright, leaving aside the 1-liners (OK, I said it... it sucks), there are other things here too:

YOU THROW OutOfMemoryError

Ouch.
Additionally, the method is only called from one place (grow()), and the call-site has only one line of code. Moving this logic in to the grow() call would be fine.
Other methods call checkElementIndex(), but that method is not included with your code.
You have the Object[] data variable. This is a horrible datatype to use because it introduces the need to do the explicit casts in the rest of the code, like:

return (E) data[index];

it is now relatively common in Java to require the class is given at the same time as the constructor. If you have the following code:
private E[] data;

public ConcurrentIterable(Class<E> clazz) {
    @SuppressWarnings("unchecked")
    data = (E[])Array.newInstance(clazz, 4);
}

Then, when you want to create your list, you create it with:
ConcurrentIterable<MyClass> myiterable = new ConcurrentIterable<>(MyClass.class);

from that point on, the inner-content of the class never needs to do an explicit cast from the data store.
Synchronization
Synchronizing on the instance itself is an anti-pattern, generally. In your class, you have synchronized methods: public synchronized void add(E element), etc.
What this means is that anyone who has an instance of your class, can mess with your synchronization and create deadlocks. Someone does the following:
public class MyClass {
    private final ConcurrentIterable<String> iterable = new ConcurrentIterable<>();

    ....

    public void doSomething() {
        synchronized(iterable) {
            Thread.sleep(100000);
        }
    }

Now, suddenly, your code hangs and does not complete.
When using synchronization it is almost always a bug to have a synchronization point on a public/leaked instance.
Apart from that issue, the synchronization looks complete, but excessively scoped. You lock the whole data structure. Your instance is 'serialized', no matter how many threads you have, only one thread can be doing anything at any one time.
There has to be a better way....
Alternate scheme
If it was me, I would consider a combination of the AtomicReferenceArray an AtomicInteger, and a ReentrantLock. The system would look something like:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;

public class ConcurrentIterable<T> implements Iterable<T> {

    private static final int CONTAINER_SHIFT = 10; // 1024 per container.
    private static final int CONTAINER_SIZE = 1 << CONTAINER_SHIFT;
    private static final int CONTAINER_MASK = CONTAINER_SIZE - 1;

    private final AtomicInteger size = new AtomicInteger();
    private final ReentrantLock lock = new ReentrantLock();
    private final ArrayList<AtomicReferenceArray<T>> containers = new ArrayList<>();

    private final AtomicReferenceArray<T> getContainer(int index) {
        int cont = index >>> CONTAINER_SHIFT;
        lock.lock();
        try {
            while (cont >= containers.size()) {
                containers.add(new AtomicReferenceArray<T>(CONTAINER_SIZE));
            }
            return containers.get(cont);
        } finally {
            lock.unlock();
        }
    }

    private void checkIndex(final int index) {
        final int sz = size.get();
        if (index >= sz) {
            throw new NoSuchElementException(String.format("No element %d in structure of size %d", index, sz));
        }
    }

    public T get(final int index) {
        checkIndex(index);
        return getContainer(index).get(index & CONTAINER_MASK);
    }

    public T set(final int index, T value) {
        checkIndex(index);
        return getContainer(index).getAndSet(index & CONTAINER_MASK, value);
    }

    public void add(T value) {
        int index = size.getAndIncrement();
        getContainer(index).set(index & CONTAINER_MASK, value);
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {

            int next = 0;
            final int last = size.get();

            @Override
            public boolean hasNext() {
                return next < last;
            }

            @Override
            public T next() {
                return get(next++);
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }

        };
    }

}

There is a race condition in the above, but I would probably solve it with documentation, not logic. The race condition is that there is a moment when you add a member, the size will be incremented, but the get() could return null in one thread in the instant before the value is set to the new value in another thread.
If you document that the container can hold null values, and that the iterator/get may return a null before the value is added, then you have the bonus of being able to support null values in the data too.
Note, it would be relatively trivial for the calling code to handle null return values.
There's a second caveat. I set up the iterator to loop to the last value that was added when the iterator was created. If you change the line:
return next < last;

to be
return next < size.get();

then you will iterate over all values added up to the last add. (but with slightly more risk that the last values may be null)


Same dude, same code, same review (except I noticed hostingGames is not an object like I assumed in the first answer).

Never use for-in on arrays. You risk looping through properties in addition to the array items. Use a regular for loop with indexes, or better, array methods.

And when splicing an array multiple times, it's best you do it in reverse. You risk skipping items when you do it forwards.

Also, it's best not to leave any holes in the array. From a developer that knows nothing about the context of your app, why are they empty? Especially when cancelHostGame splices cancelled games?

server.em.addListener('cancelHostGame', function(userId, userName){
  for(let i = hostingGames.length; i--;){
    let game = hostingGames[i];
    if(!game || game.userId !== userId) continue;
    hostingGames.splice(i, 1);
  }
});

Now the first part of your code is somewhat different from the first review. But the advice from the first review still applies.

However, you've introduced the concept of "slots". But in reality, all your code does is limiting the number of hosted games. Slots is just an abstract way of putting it. A much easier approach is to just check if the hosted array length is at the limit. If not at the limit, just push to the array.

server.em.addListener('hostGame', function(settings){

  const slotsMaxed = hostingGames.length === MAX_SLOTS;
  if(slotsMaxed) return;

  const userHasGame = hostingGames.map(g => g.userId).includes(settings.userId);
  if(userHasGame) return;

  const hostGame = new HostGame();
  hostGame.initialise(settings.userId, settings.userName, settings.boardSize, settings.gameMode, settings.gameNote);
  hostingGames.push(hostGame);
  server.updateGamesList(hostingGames);

  server.consoleLog('APP', `${settings.userName} is hosting a game. ID: ${settings.userId}`);
});


Recording error messages from an exception

In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):

ver errorMessage =  exception.InnerException?.Message ??
                    exception.Message ??
                    exception.ToString();

Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...

If you fear that situation, you can always create an extension method for strings that will return null for empty strings:

public static string NullIfEmpty(this string str)
{
    return string.IsNullOrEmpty(str) ? null : str;
}

and then use it like this:

ver errorMessage =  exception.InnerException?.Message?.NullIfEmpty() ??
                    exception.Message?.NullIfEmpty() ??
                    exception.ToString();


Hibernate - entity design with multiple dependencies

I don't see anything wrong with your approach.

Another option is to add a PhoneNumberType to the PhoneNumber table.

In any case you should ensure the table has appropriate constraints added so that a PhoneNumber must relate to a table.


Two inputs, two buttons to set variables to input - with .each();

Just regarding your question of how to simplify the two set-functions to one, you can merge them in one function which reacts on clicks on both buttons and behaves different depending on the button which has been clicked.

This could look like this:

$("#setfrom, #setto").click(function(event){
    var value;
    if (event.target.id == "setfrom") {
        value = parseInt($('#from').val());
        f = value;
    } else {
        value = parseInt($('#to').val());
        t = value;
    }

    if (isNaN(value)) {
        $("#test").append("
You said you needed numbers, right
");
    } else {
        $("#test").append("
" + value + "
");
    }
});

To explain what has changed here, it is important to understand what is happening in the code.

$("#setfrom, #setto") selects all elements which have either "setfrom" or "setto" as the id (look for "id=" in your html code), those are the two buttons.

The next part .click(function(event) { says that the following code should be executed each time that one of these elements is clicked. event is automatically filled by jQuery to contain information about the click of the user. For example event.target contains the concrete element which has been clicked, in this case always one of the two buttons.

We use this to find out, which of the buttons was clicked by the user and read the value from the depending input field (again selected using the $("#something") syntax explained before).

We store the value in two variables:

value is used to check if the value is a number and to output either the error or the number
f or t (depending on which button was clicked) is (as in your code) stored for later counting from f to t

With broader changes you could avoid the need for the user to click the "OK" buttons by just reading the values whenever the "go!" button is clicked.

This will change the behavior of the formular, but I think it will help you to understand how you can further simplify your code.

To do so you can eliminiate the above function and put the relevant code inside the click handler for the "#count" button:

$("#count").click(function(){

    var from = parseInt($("#from").val());
    var to = parseInt($("#to").val());

    if (isNaN(from) || isNaN(to)) {
        $("#test").append("
You said you needed numbers, right
");
        return
    }

    $("#num").append("
Counting from " + from + " until " + to + "
");
    for (i=from; i<=to; i++) {

        $("#num").append("
" + i + "</div)");
    }
});

Whenever the button with the id "count" is clicked, the following happens:

The values of the two input fields are read and written to variables from and to. If one of these values is not a number, an error message is printed and the flow is aborted using the return statement.

Otherwise a message is printed showing the user the start and the end of the row to be printed. After that the count is done.

For sure the code and the functionality could be further improved, but I will leave that to you. Just some hints what could be your next steps to improve this code:

Not always appending the output, but replacing old output and thus avoiding the user to need to click the "delete!" button
Extracting the duplicate code of reading values from input fields using functions

For the style of your code, I would recommend a few points:

Make sure that every new command is on a new line. Putting multiple things in one line will make it a lot harder to find out what what is happening while reading your code. In most cases you will spend more time reading your code than writing it, thus readability is very important. This applies even for control structures and commands like this line in your code: } else {$("#test").append("
" + f + "
");
As already said in the comments (and afterwards heavily improved by you): Look for correct indentation of your code. The three lines following $("#delnum").click(function() { should each be indented one (more) level. This would make it even easier to see that those lines are somehow depending on this line.
Do give your variables a speaking name. E.g. f and t could be renamed to from and to. Even in a small program like this one that helps to understand what each variable means. Keep in mind that others might want/need to understand your code - including yourself in a later point of time, when you are not completely aware of what you did there anymore.


Shunting-yard algorithm for expression parser

isInteger is not needed. Use std::isdigit.
Trust the logic. An else if condition is mutually exclusive with if condition. There is no need to test for it - you already know it is true. A simple else is enough. But see also the next point.
Notice that all code paths in the else clause necessarily push(c). Factor it out:

if ((stack.size() > 0) {
    if ((op_precedence[stack_top()] >= op_precedence[c])) {
        output.push_back(stack.top());
        stack.pop();
    }
}
stack.push(c);


Program that tells if a date is valid in C

Validation is a specific task, distinct from receiving input, so it deserves to have its own function.

The code suffers from excessive nesting, which could be improved by putting else if at the same indentation level. However, another problem is that some of the checks are affirmative and some of them are negative, which makes the code harder to follow.

Since the validation depends mostly on the month, I'd write it this way, with a switch:

int isValid(int dd, int mm, int yy) {
    if (dd <= 0) return 0;
    switch (mm) {
      case 1: case 3: case 5: case 7:
      case 8: case 10: case 12:
        return dd <= 31;
      case 4: case 6: case 9: case 11:
        return dd <= 30;
      case 2:
        return dd <= 28 + (yy % 4 == 0);
      default:
        return 0;  /* invalid month */
    }
}

Then, in main():

if ( 3 == scanf("%d/%d/%d",&dd,&mm,&yy) &&
     isValid(dd, mm, yy) ) {
    puts("Valid date");
} else {
    puts("Invalid date");
}

Note that validating the return value from scanf() is important too.

The code doesn't handle the Gregorian correction properly, such as for year 1900.


Why not use an existing ajax file upload library, like Fine Uploader?
As for your code.
1)
I think you meant to return _this.methods.init.apply(this, arguments);.
2)
You should rewrite Uploader to not use arguments.callee for two reasons; it makes your code harder to read and for the browser to optimize.


Pattern for creating a globally accessible custom plugin

The usual way to create a plugin is to declare a namespace or use an existing and append to it. Usually done using the module pattern:

(function(ns){

  //private scoping
  var privVar = '...';
  function priv(){...}

  //expose a function
  ns.myFunc = function(){...};

}(this.myLib = this.myLib || {}));

//using the exposed myFunc
myLib.myFunc();

Issues with your code? Well, it depended on jQuery just to append methods. It's not really necessary to use extend. With the above pattern, you can cleanly add functions to the namespace.

If you really need just some parts of jQuery, you can grab their code and just use it directly. I usually interrogate the code and pick out only the parts that are necessary. Or you can roll your own jQuery build. They have instructions on their GitHub on how to roll your own mix of jQuery.

Now, for function callbacks, you should use the a technique similar to pub-sub or event emitters or jQuery's on method. The syntax looks like this:

myLib.on('fnName',function(){...});

where fnName is the function name that is equivalent to the function called.

Now how to implement?

Well, each of your functions should call a special internal function that fires callbacks collected in your library. Basically, the on, method of your library just collects callbacks and registers them in an internal cache id'ed with the name of the function. The implementation would look like this:

(function(){

  //handler cache
  var handlers = {};

  //our internal function that executes handlers with a given name
  function executeHandlers(eventName){
    //get all handlers with the selected name
    var handler = handlers[eventName] || []
      , len = handler.length
      , i
      ;
    //execute each
    for(i = 0; i< len; i++){
      //you can use apply to specify what "this" and parameters the callback gets
      handler[i].apply(this,[]);
    }
  }

  //our on function which collects handlers
  ns.on = function(eventName,handler){
    //if no handler collection exists, create one
    if(!handlers[eventName]){
      handlers[eventName] = [];
    }
    handlers[eventName].push(handler);
  }

  //so we expose a shout function
  ns.shout = function(){

    ...stuff shout does...

    //now we execute callbacks registered to shout
    executeHandlers('shout');
  }

}(this.myLib = this.myLib || {}));

//we register a callback
myLib.on('shout',function(){
  //executed after calling shout
});

//execute shout
myLib.shout();


ReactiveCocoa implementation of async function

/**
- TODO: Add OAuth2 towards GitHub as a protocol
- TODO: Make it RAC
- TODO: Store gistID in NSUserDefaults
*/

The right way to mark to-dos in Swift is like this:

// TODO: Some note about what you need to do.

Per this Stack Overflow answer, it is the most likely variant that Apple will eventually build into Xcode to automatically generate notes for, but additionally, a script is provided in that answer for generating this warning in the meantime.

public final class GistService: NSObject

It's great that this class is public.  It's the only way to use our classes across frameworks... but none of the properties or methods of this class are marked as public.  So realistically, the class really can't be used outside the framework it's in.
Why is this class final?  What's the specific problem with inheriting from this class?
Why is this class inheriting from NSObject?  That would make sense in Objective-C (where every class must inherit from NSObject), but I don't see what we're getting from NSObject here.  (In fact, later we'll see that inheriting from NSObject actually causes us problems.)
I'm not sure how much I like the name GistService.  Look at the names of Apple classes.  Are any of them "services"?

override init() {
    userDefaults = NSUserDefaults.standardUserDefaults()
    gistAPIURL = NSURL(string: "https://api.github.com/gists")!
    super.init()
}

convenience init(apiURL: String) {
    self.init()
    self.gistAPIURL = NSURL(string: apiURL)!
}

First of all, userDefaults is unused here and should be eliminated.

Second of all, I'm not sure how appropriate is to default to GitHub.  I just don't know at all how appropriate that is.  If someone using the library wants a more convenient way of instantiating with this (or any other) default base URL, they can always extend the class.

Third of all, strings are not URLs and should not be called as such.

Fourth, and absolutely most importantly, you've done this backwards.  You have the wrong init method marked as convenience.  I think that inheriting from NSObject prevents you from marking the zero-argument init has convenience (and if so, all the more reason not to inherit from NSObject).

The designated initializers should be the ones that take more arguments than anything else.  The convenience initializers call those designated initializers.  They are convenient because they take fewer arguments and assume default values for the arguments that the designated initializers require.

So, with all these things in mind... we should start with this init method:

required init(baseURL: NSURL) {
    self.gistAPIURL = baseURL
}

And I'd argue we don't want the zero-argument init at all.  (Why this is required, I'll address in a minute.)

If we really want to provide a means of instantiating with the GitHub url, then that should look something like this:

class func gitHubGist() -> Self {
    let gitHubURL = NSURL(string: "https://api.github.com/gists")!
    return self.init(baseURL: gitHubURL)
}

We want to return Self so that this works with inheritance.  And to do this properly, we have to call self.init.  The only way this works with the Self return type is if the init we're calling is marked as required.

So now, if I want a gist of my own choosing, I use this approach:

let myGist = GistService(baseURL: fooBarGistServiceAPIURL)

And if I want GitHub's, I can conveniently just do this:

let gitHubGist = GistService.gitHubGist()

//MARK:- Public API

This is not how you make methods public.  As I mentioned earlier, our class is public and can be seen outside of the framework... but none of its methods or properties are.  If these methods are intended to be part of the API, we need to start by marking them with public.

But that's not enough.  We should also use AppleDoc style comments so that without having to navigate to your website, or where ever you're keeping documentation, the user can get an overview of what this method or property is or does right there in Xcode.

I highly recommend you check out this NSHipster article on all of what you can do with AppleDocs, but in the meantime, here's a little preview:

The comments I provided in lines 5 through 12 generated the content for the pop-up box (which you get by holding Option and clicking the function name).  This documentation crosses file and framework boundaries.  It's the surest way to make sure your documentation is visible to the people actually using your code.  It's comment visible if you're browsing the source and documentation available when you're using the API.

//    userDefaults.removeObjectForKey("gistID")

If this code is unused, remove it.  Let source control manage the fact that it used to be there.  If you don't remove it, some maintainer will.  And if it doesn't need to be removed, it needs a comment explaining why it needs to stay.

//MARK:- Helper functions

func gistUpdate() -> Bool {
    guard let _ = self.gistID else { return false }
    return true
}

First, if these are "Helper" functions, they should almost certainly be private (they're probably not needed outside this file, are they?).  But problems exist beyond the access level of this method.

What's it even doing?  It's certainly not updating anything.

If I only see the method signature, I see this:

func gistUpdate() -> Bool

And that's about all I see when I come across it in code (where your library uses it).

So, let's look at the actual implementation:

guard let _ = self.gistID else { return false }
return true

This is arguably the most confusing way of writing:

return self.gistID != nil

But this is a really bad method.  We don't need a method for this.  We need optional binding.  If you're not comfortable with optional binding, it's definitely something you need to work on before you venture into anything more complicated in Swift.

So let's take a closer look at where you're calling this method.  Here's a place:

if self.gistUpdate() {
    let updateURL = NSURL(string: self.gistAPIURL.path! + self.gistID!)!
    request = NSMutableURLRequest(URL: updateURL)
    request.HTTPMethod = "PATCH"
}

And this is certainly wrong.  The better approach would start with:

if let gistID = self.gistID {
    // we know gistID is non-nil, and it's already unwrapped...
}

enum ConnectionError: ErrorType {

    case Bad(String)
    case Worse(String)
    case Terrible(String)
}

These classifications for errors are far from sufficient.  The severity of the error should be a sub-property of the classification of the error.  Our errors should be classified into more specific types.  For example:

No Internet.
No response from server.
Invalid credentials.
Invalid path.

Etc.  This is very simplified and probably not a complete list, but hopefully you get the point.  Now, these should probably still be in an enum and still be paired with human-readable string descriptions of the problem, and perhaps a severity indication... but we need to start by classifying the type of error.

Why?

Most importantly, because it will determine how someone using your library will respond to the error.  This will be a far better indicator of the best course of action for responding to the error than some vague severity that you're classifying yourself (and is probably highly subjective generally).


Get the most frequent number and least frequent duplicate in array

First, you should care about indentation.
Why slitting the numbers string while you can access individual char with numbers.charAt(n) ? It force you to work with String instead of char.
You don't check for validity of the string. Here, it's hard coded, but if you have to get it from a unknown source, a good habit is to validate it before using.
Also, you don't check if there's duplicates or not. If numbers is "1234567890" your program go for a infinite loop.
You compute the "Max" count into the main, and the "Min" in a function; try to be consistent.
For both computations, you make \$n*n\$ iterations (where \$n\$ is the numbers length) giving a complexity of \$ O(n^2)\$ for both.

Instead, try to construct a table of occurrences by traversing the table once.
After, simply search in this table the min and max values in one traversal.

There's a very naive implementation, but i think a lot simpler to understand than your, and surely more efficient.

public class X {
 public static void main(String[] args) {

   String data = "756655874075297346";
   int[] counts = new int[10];

   for (int i = 0; i < data.length(); i++) {
     char n = data.charAt(i);
     if (n >= '0' && n <= '9') {
        counts[n-'0']++;
     }
   }

   int min_index = 0;
   int max_index = 0;
   int min_count = Integer.MAX_VALUE;
   int max_count = 0;

   for (int i = 0; i < 10; i++) {
     if (counts[i] >= max_count) {
       max_index = i;
       max_count = counts[i];
     }
     if (counts[i] > 1 && counts[i] < min_count) {
       min_index = i;
       min_count = counts[i];
     }
   }
  System.out.println("Frequent number is: " + (char)(max_index + '0') + " It appeared " + max_count + " times");
  if (min_count < Integer.MAX_VALUE) {
    System.out.println("Min Frequent number is: " + (char)(min_index + '0') + " It appeared " + min_count + " times");
  }
  else {
    System.out.println("There's no duplicates!");
  }
 }
}

Here, the function print the higher number with the higher number of occurrences (in case of multiples char with maximal occurrence count). If instead you want to get the lower, change if (counts[i] >= max_count) for if (counts[i] > max_count).

Conversely, it print the lower duplicated number with the lower count, to get the higher duplicated with the lower count, change counts[i] < min_count with counts[i] <= min_count.


Worksheetfunction.Vlookup value on error

Your handling is not necessarily unelegant, but there are a couple of things to point out.

The main thing is that you're repeating code that really only needs to be there once. For example, you only need to write the VLookup statement once. Just set up a variable to define your range.

Your error handling can work, but you need to more clearly define what is a "normal exit" from your routine and what is an error exit. It's typical in this case to structure your error handling with the form shown below because there may be processing required during a normal exit only that you still might have to perform during an error exit.

Option Explicit

Function GetTiersAccount(TiersName As String, Clients As Boolean) As Long
    Dim lookupRange As Range
    If Clients = True Then
        Set lookupRange = wb.Sheets(1).Range("A1:B13")
    Else
        Set lookupRange = wb.Sheets(1).Range("D1:E94")
    End If

    On Error GoTo ERRRRR
    GetTiersAccount = WorksheetFunction.VLookup(TiersName, lookupRange, 2, False)

NormalExit:
    Exit Function

ERRRRR:
    GetTiersAccount = 471
    Resume NormalExit
End Function


Find two integers with the largest sum within a budget (breaking ties by smallest difference)

To change your algorithmic order, say from N^2 to N lg N, you must change your algorithm. A simple change will not suffice. But I can think of a better algorithm:

Let us accept the theorum that for each number x in your list, you have a number y such that x + y = z and no other y for the given x will produce a z' where z < z' < budget. That is to say, y is the perfect match for x.

We can use a binary search to find the best y for a given x once the array is sorted.

We can find the y for each x in the array, and the corresponding z. We can loop over these results to find the highest z that does not break the budget, assuming one exists.

The actual code is left as an exercise to the reader, but I think there should be sufficient details to craft it, considering you understand the problem enough to have created a naive solution.


Filtering lines in a log file using multiple regexes

I wouldn’t worry about performance of the loop here. The slow thing isn’t the loop, it’s the matching of the expressions.

That said, I’d express the nested loops via list comprehension instead.

def filter_lines(instream, filters):
    return ((line, regex) for regex in filters for line in instream if regex.match(line))

Or alternatively, using higher-order list functions:

def filter_lines(instream, filters):
    return filter(lambda (line, rx): rx.match(line), itertools.product(instream, filters))


Read with batches
Looping over Section.all.to_a is very memory greedy (it reads everything to memory before starting to process it). You will be far better off using batches:

Section.find_each do |section|
  # ...
end

Naming
Using member names like s, a, etc. is not very readable, and makes understanding what your code does very difficult. For that reason, it is very hard for us reviewers to give you an intelligent advice on how your code can be improved - we just don't understand what it does...

Shadowing
a.each do |a| - to add insult to injury, you shadow the a member when you loop over it. This makes your code totally unreadable. I still don't understand what that loop is all about.

Loop bloat
The line a = a.first.product(*a.drop(1)) is very suspicious, since it bloats the amount of data your are looping on by several scales. Are you sure that is what you want to do?

Where does your data go?
The new_string, which holds the result for each iteration is not seemed to be saved anywhere...

Filter your data
At the bottom line, you are substituting words in your input. Not all sections exist in all inputs, but you search for them over and over again. You might save a lot of calculations if you filter irrelevant sections in your code, before looping on them:

Section.find_each do |section|
  next unless word[section.part]
  alternate_array #...
end

Doing stuff over and over again
I'm pretty sure, though I might be wrong, that at the end s.gsub!(*pair) ends up running the same "pairs" more than once on the same string (or its duplicates). It will be better strategy to cache results, or maybe pre-process your data (build a template, and only set the variables, or something).

Edit
You could use a variant of gsub! which receives a hash as the replacement:

  If the second argument is a Hash, and the matched text is one of its
  keys, the corresponding value is the replacement string.

So you could write:

replace_regexp = Regexp.union(subs.keys)

replaced_words = a.map do |alts|
  word.gsub(replace_regexp, Hash[[subs.keys, alts].transpose])
end

This does a single gsub per combination (instead of once per key), and further reduces the run complexity of your code.


How I can short my code when request have many parameters

https://laravel.com/docs/5.7/queries#where-clauses

$where = [];
if($city) {
    $where[] = ['city_id', '=', $city];
}
if($sex) {
    $where[] = ['sex', '=', $sex];
}
if($ageFrom) {
    $where[] = ['birthday', '<=', date('Y-m-d', strtotime("-$ageFrom years"))];
}
if($ageTo) {
    $where[] = ['birthday', '>=', date('Y-m-d', strtotime("-$ageTo years"))];
}
$candidates = Candidate::where($where)->get();


I agree with @Gareth-Rees, so I'm going to comment on the comments as
well:  Most of them are fine if not a bit too detailed.  It could make
sense to move them into docstrings and separate functions if there
really is that much to say about it.  I kind of expected the whole
function to have a docstring anyway, since at the moment neither input
nor output is really documented.

In general, if you care about performance it'd be best to use a profiler
to find problematic parts.  That said the construction of all these
lists is probably not the best thing to do.  E.g. results_split is
only iterated over once.  Another general suggestion would be to avoid
linear search and rather use dictionaries for faster lookups.

The construction of terms is confusing.  If the only value used is
the first one, then just use that all the time.  Also, is the split(" ") significant, or could just split() be used as well (since it will remove any whitespace instead of just a single space, c.f. the docs)?

  str.split([sep[, maxsplit]])

  If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

I'm going to assume so.
The None default value in getlist is probably not necessary, as
the empty list already counts as a false value.
The definition of get_weight should be done with def as well.
Additionally, avoiding the list creation by using a normal loop may be
faster.
results can probably be calculated more efficiently by combining all
the queries instead of combining all the results?  In any case I'd
move this into a separate method.
list((index,)) is a very verbose way of saying [index].
The comment above results_split is wrong insofar as the index is
added to the set, thus isn't necessarily at the end of the resulting
list.  Changing the parenthesis slightly would fix this - however it
doesn't seem like the index is used anywhere else, so both adding the
index, as well as using enumerate aren't necessary.
search_terms[0] is used more than once, so it makes sense to store
the calculated values and reuse them.
The sort method can be used instead of sorted to avoid additional
allocations.
top_level_sorted sounds like it does something different than what
the code says, as there is nothing preventing an unsorted list in
those lines.  Also, it would be better to fetch all objects at once by
ID instead of fetching all of them and then removing duplicates with
the set.
all_results is bad.  It's searching for the index value in a list
that was explicitely constructed with that number at the end, so it
should be rewritten to make use of that fact.  Honestly I can't really
follow the logic here, I'll leave it out in the code below.

I tried to rewrite this a bit according to those points, however there's
a trade-off between readability and faster code.  Best thing would be to
merge all the steps that operate on the same lists one after another and
extract functionality into separate functions to make up for the lack of
readability.

def get_matching_items(self, term):
    return Item.objects.filter(Q(name__icontains=term) | Q(description__icontains=term))

def get_queryset(self):
    search_terms = self.request.GET.getlist('search')

    if not search_terms:
        return []

    terms = search_terms[0].lower().replace('/', '').split()
    terms_length = len(terms)

    # Builds weight for each term
    # Example: The search has 3 terms, Red, Shoes, Pants
    # Red would have a weight of 3 since it is the first word, shoes would be 2 and pants would be 1
    query_with_weights = {term: terms_length - index for index, term in enumerate(terms)}

    # Query that will go through each item to see if their name or description match contain the search terms
    results = get_matching_items(terms[0])
    for term in terms[1:]:
        results |= get_matching_items(term)

    # This section will go through and weigh each item based on name and description weight.
    # This may be problematic if the description uses the key word multiple times.
    #  It could result in things being weighed incorrectly. See the example below for more details.
    # Example 2: 'red pants' is the query.
    # We have, in no particular order, a red shoe item, a blue pants item, a red pants item, a red swim trunks item.
    # Each items description is sweet {{ item.name }} bro
    # The resulting weight would be Red: 2, Pants: 1
    # However, the returned result would be, in this order, [Red Pants, Red Shoe, Red Swim Trunks, Blue Pants]
    sorted_results = []
    for item in results:
        terms = set(item.name.lower().split())
        terms.update(item.description.lower().split())

        weighted_sum = sum(query_with_weights.get(y, 0) for term in terms)

        sorted_results.append((item, weighted_sum))

    sorted_results.sort(key=lambda lst: lst[1], reverse=True)

    ...

    # Gets the top level item for each sub item that hit in the results.
    #   If multiple sub items FK back to the a single master item we want to only display that master item once.
    top_level_ids = set()
    top_level_sorted = []
    for item in all_results:
        if not item.is_variant:
            continue
        top_level_id = item.get_top_level_item().id
        if top_level_id in top_level_ids:
            continue
        top_level_item = Item.objects.get(id=top_level_id)
        top_level_ids.add(top_level_id)
        top_level_sorted.append(top_level_item)

    return top_level_sorted


Classifying connectivity status based on online and connected status of multiple nodes

As a function
When you write code, even as an example, always write it as a function. A function is returnable, and thus can be written differently than non returnable flat execution.
Comment code mismatch

"Comments are just lies in waiting."
...by unknown guru.

Your comments do not match the code. The comments specify lowercase status, your code capitalists the status. Which is correct is anyone's guess. I will assume the comments are correct and that the status is formatted upon display. (It makes the solution simpler) Changed my mind and will assume the code has been tested and is correct.
Inefficiency === Inelegance
The nested statements are not inelegant (in a function it would not need any else statements), its the two Array.map and three Array.includes that are very inefficient for the task at hand, which to me is ugly inelegance.
Solution
It is the number of online, connected children that you need to know.
If the number of online children

is the same as the number of children then all are online.
is the less than as the number of children and not zero then some are online.
is zero then none are online

The same applies for connected children.
Thus count the two types and use the counts to return the status, as follows
function connectionStatus(clients) {
    const count = clients.length;
    var onC = 0, conC = 0;
    for (const {connected, online} of clients) {
        conC += connected;
        onC += online;
    }
    if (onC === count) {
        if (conC === count) { return "Connected" }
        return conC ? "Partially disconnected" : "Disconnected";
    }
    return onC ? "Partially offline" : "Offline";
}

connectionStatus(parent.children);


The code isn't well indented, but maybe that's only your post on codereview (if it isn't, please consider indenting your code, that helps!)

There's a flaw in your code: you thought about reimplementing Array's copy constructor (which is good), but you didn't think about the copy assignment operator (which is implicitly defined).
Currently, this code is legal, and is very likely to cause undefined behaviour (that may or may not "work", you don't know, usually you'll get a segfault when it doesn't):

#include "array.hpp" // let's say you moved the array definition there

void uselessAssignment(const Array& a) {
  Array b;
  b = a; // call to the implicitly defined assignment operator!
  // call to b destructor (you just deleted the memory allocated by a)
}

int main(int, char*[]) {
  complex complexNumbers[42];
  Array a(42, complexNumbers);
  uselessAssignment(a);
  a.printArray();
  return 0;
}

To correct that, either redefine the implicit assignment operator or mark it as delete.

Otherwise that seems like a fine minimal implementation, it could be improved though:
- you forgot a delete in the main, that's not extremely important because the OS will free the memory anyway when the program terminates, but that's not really clean
- i've learnt today that you should avoid prefixing your names with an underscore (stack overflow link)
- in complex.cpp you can use the initializer list to initialize the real and imaginary parts (your code works fine, i just personally find it cleaner):

complex::complex(float a, float b) :
real(a),
imaginary(b) {}

- you may want your complex number to use something else than a float to store the real and imaginary parts:

template<class Real = float, class Imaginary = Real>
struct complex {
  //...
  Real real;
  Imaginary imaginary;
};

- you can use std::vector to handle your array rather than allocating/deallocating yourself, it's a bit safer (you wouldn't have the problem with the copy assignment), but i often directly use dynamic allocation myself so i'm not one to talk
- rather than this:

float a, b;
for(int i=0;i<length;i++){
  cin>>a>>b;
  numbers[i]=complex(a,b);
}

you can overload operator>> for complex rather than using the assignment operator:

std::ostream& operator>>(std::ostream& output, complex& number) {
  float a, b;
  output >> a >> b;
  number = complex(a, b);
  return output;
}
// ...
int main(int, char*[]) {
  // ...
  for(int i = 0; i < length ; ++i )
    cin >> numbers[i];
  // ...
}

(you can also declare the operator>> as a friend in complex so that it can directly access its members; when the assignment isn't trivial, it may also slightly improve performance, but not here)
- of course you could define arithmetic operations on complex numbers

...and probably other changes, but that's a rather long list already (and that also depends on what you expect from your classes).

Edit:
Ah something important if you manually handle memory in your class, you may want to define the move constructor and the move assignment operator, that may improve performance in some cases:

Let's say you have some function which doubles each complex number in an array and returns a new array (it doesn't modify the original one), let's say its protoype is Array doubleEachComplex(Array&);
If you use it like this:

Array array;
// ...
array = doubleEachComplex(array);

The compiler will:
- construct array
- do things with array (initialize it for instance)
- call doubleEachComplex
- create a fresh Array object
- call the copy assignment operator of Array (if no move assignment operator is defined)
- delete the fresh Array object (used by the copy)

But the copy assignment operator can't modify the "source" object, so it will usually perform a deep copy. A better solution would be to swap the contents of each array since the second one is a temporary (that's what a move constructor could do).
Actually, in that case an even better solution would have been to modify it in place, but that's not always possible/a good idea.


I have a few suggestions:

In Deserialize() you swallow all types of exception.  Catching and swallowing all exceptions is generally considered to be a bad practice.  In fact, Microsoft has a compiler "design warning" for this: CA1031: Do not catch general exception types.  Instead, you should swallow exceptions that you might reasonably expect, and rethrow the rest.  E.g. if you were deserializing from a file, then it would be reasonable to catch and handle FileNotFoundException.

Swallowing all exceptions can mask future problems in the code.  For instance, if somebody were to modify BackgroundJobInfo and add a property whose type is not supported by the data contract serializer, or change the order of pre-existing properties thereby invalidating old XML (DataContractSerializer is order sensitive) then the resulting bug might not be immediately noticed.

For more, see Exception Handling and/or Is catching general exceptions really a bad thing?.
XmlTextReader and XmlTextWriter are both deprecated as of .Net 2.0.  Microsoft suggests using XmlReader.Create() and XmlWriter.Create() instead.
Your methods to serialize and deserialize XML from a string using DataContractSerializer look handy, and could usefully be made generic for reuse later.

Thus:

public class InfoSerializer : IInfoSerializer
{
    private static readonly ILogger _logger = LoggerFactory.Instance.GetCurrentClassLogger();

    public string Serialize(BackgroundJobInfo info)
    {
        return DataContractSerializerExtensions.SerializeXml(info, null); // If you want indentation, use new XmlWriterSettings { Indent = true, IndentChars = "    " };
    }

    public BackgroundJobInfo Deserialize(string info)
    {
        try
        {
            return DataContractSerializerExtensions.DeserializeXml<BackgroundJobInfo>(info);
        }
        catch (Exception e)
        {
            // hopefully, will never happen
            _logger.ErrorException(e, "Error when deserializing a BackgroundJobInfo object from string <{0}>", info);
            throw;
        }
    }
}

public static class DataContractSerializerExtensions
{
    public static string SerializeXml(this object obj, XmlWriterSettings settings = null)
    {
        if (obj == null)
            throw new ArgumentNullException("obj");
        using (var textWriter = new StringWriter())
        {
            using (var xmlWriter = XmlWriter.Create(textWriter, settings))
            {
                var serializer = new DataContractSerializer(obj.GetType());
                serializer.WriteObject(xmlWriter, obj);
            }
            return textWriter.ToString();
        }
    }

    public static T DeserializeXml<T>(string xml)
    {
        if (xml == null)
            throw new ArgumentNullException("xml");
        using (var textReader = new StringReader(xml))
        using (var xmlReader = XmlReader.Create(textReader))
        {
            var serializer = new DataContractSerializer(typeof(T));
            return (T)serializer.ReadObject(xmlReader);
        }
    }
}

Update

If you are using DataContractSerializer and wish to suppress the serialization of specific properties, you should apply data contract attributes, specifically [DataContract] to the type and [DataMember] to each member to be serialized.  Note that data contracts are opt-in so once you start to use data contract attributes, all members of a type to be serialized must be marked as data members.  For instance:

[DataContract]
public class BackgroundJobInfo
{
    [DataMember]
    public string JobName { get; set; }

    [DataMember]
    public int JobPriority { get; set; }

    // Not marked with DataMember so not serialized.
    public string Password { get; set; }
}

See Using Data Contracts.

As for creating a single static DataContractSerializer to be shared globally, I don't recommend it since there might be issues with threading.  From the docs:

  Thread Safety

  Instances of this class are thread safe except when the instance is used with an implementation of the IDataContractSurrogate or DataContractResolver.

Unless you have determined via profiling that you have performance issues due to excessive allocations, it would appear safer to not share this class between threads.

Throwing an exception trying to serialize a property with "password" in the name is not implemented out of the box with DataContractSerializer.  You should be able to adapt the XmlWriter from Custom xmlWriter to skip a certain element?, then throw an exception rather than skipping the element.


Remark on you DDD

I've never thought this is possible:

val email = Email("invalid") ?: throw IlllegalArgumentException

Kotlin was created with the intention of null-safety / explicit nullability, and your factory violates it. It allowes classes to be instanceated directly as NULL - this is really weird and for people admiring and working with Kotlin it's very confusing.

Improve current solution

I don't see an improvement for your current solution. I can only recommend to make a Factory class which would genereate all the boilterplate code for all of your generates classes, including converters. But I have a suggestion...

Suggestion

I would go away from extending a companion object and define 'Nullable' Builders, which inherit from generic one:

abstract class NullableValue<T, D>(
    private val init: () -> T,
    private val value: D,
    private val check: (D) -> Boolean
) {
    fun isValid(): Boolean = check(value)

    fun getOrNull(): T? = if (isValid()) init() else null
}

Define class and the builder:

class Email(val email: String)

class NullableEmail(val email: String) : NullableValue<Email, String>(
    init = { Email(email) },
    value = email,
    check = { "^.+@.+\\..+".toRegex().matches(it) }
)

class NonBlankString(val string: String)

class NullableNonBlankString(val string: String) : NullableValue<NonBlankString, String>(
    init = { NonBlankString(string) },
    value = string,
    check = String::isNotBlank
)

And you can use them:

    NullableEmail("").getOrNull() // will be null
    NullableNonBlankString("abc").getOrNull() // will be NonBlankString.class

    Converter<NonBlankString, String> { value ->
        value.toString()
    }

If you want more reusability, we can use strategy pattern:

interface Nullable<T> {

    fun isValid(): Boolean

    fun getOrNull() : T?
}

abstract class NullableValue<T, D> (
    private val init: () -> T,
    private val value: D,
    private val check: (D) -> Boolean
) : Nullable<T>  {
    override fun isValid(): Boolean = check(value)

    override fun getOrNull(): T? = if (isValid()) init() else null
}

class NullableEmail(val email: String) : Nullable<Email> by NullableByRegex<Email> (
    init = { Email(email) },
    value = email
)


To address your immediate concerns,

Using the return stack for storing your temporaries is a perfectly valid technique.

pick is always frown upon (as well as tuck, roll, and friends). It seems that the len parameter to bubblesort does not participate in computation - except the very beginning - and mostly just stays in the way. Consider
 : bubblesort
     dup >r 1-
     ....

and use over instead of 2 pick (don't forget to r> the length at the end).

I prefer a slightly different formatting of conditional. Consider
2dup > if
    r@ c! r> 1 + c!  else
    r> drop 2drop then ;

Same for the loops. Consider
: bubblesort ( string len -- string len )
    dup 1 - begin
    dup 0> while
        dup 0 do
            2 pick i compare-and-swap-next
        loop
        1 -
    repeat
drop ;

Keeping control words together with their respective conditions/actions looks more Forthy for me.

r> drop is also known as rdrop.
rot rot is also known as -rot.


The main area where you code can be improved is in your database calls. Currently your making 3 database calls. When you use

var lastItem = ctx.Logging.Where(x => x.Datatype == Datatype.Stop).AsEnumerable().LastOrDefault();

your loading all the records into memory (using .AsEnumerable()) in order to get the last one then throwing all the rest away, and then making another database query using

var filteredQuery = allitems.Where(...)

which fetches those records all over again. You only need the one database call to materialize the records to memory, and then you can get the first and last records from that collection.

Your also not testing for null when you use .FirstOrDefault() and .LastOrDefault() which has the potential to throw an exception in the code following those queries.

You can also simplify some code such as

var midnight = new DateTime(firstitem.CurrentDateTime.Year, firstitem.CurrentDateTime.Month, firstitem.CurrentDateTime.Day, 00, 00, 00);

which can be rewritten as

var midnight = firstitem.CurrentDateTime.Date;

You could re-write your method to have only one database call as

public List<HeatMapViewModel> GetStops()
{
    using (TraxgoDB ctx = new TraxgoDB())
    {
        List<HeatMapViewModel> items = new List<HeatMapViewModel>();
        var logs = ctx.Logging.Where(x => x.Datatype == Datatype.Start || x.Datatype == Datatype.Stop).OrderByDescending(x => x.LogID).ToList();
        if (logs.Count < 2)
        {
            return items; // or return null;?
        }
        var first = logs.First();
        var currentDateTime = first.CurrentDateTime;
        double minutes = (first.CurrentDateTime - first.CurrentDateTime.Date).TotalMinutes;
        items.Add(new HeatMapViewModel
        {
            Latitude2 = first.Latitude,
            Longitude2 = first.Longitude,
            Difference = (int)minutes,
            Date = currentDateTime
        });
        var last = logs.Last();
        minutes = (last.CurrentDateTime.Date.AddDays(1) - last.CurrentDateTime).TotalMinutes;
        items.Add(new HeatMapViewModel
        {
            Latitude2 = last.Latitude,
            Longitude2 = last.Longitude,
            Difference = (int)minutes,
            Date = currentDateTime
        });
        for (int i = 1; i < logs.Count; i++)
        {
            var previous = logs[i - 1];
            var current = logs[i];
            if (current.Datatype == Datatype.Stop && previous.Datatype == Datatype.Start)
            {
                minutes = (previous.CurrentDateTime - current.CurrentDateTime).TotalMinutes;

                items.Add(new HeatMapViewModel
                {
                    Latitude2 = current.Latitude,
                    Longitude2 = current.Longitude,
                    Difference = (int)minutes,
                    Date = currentDateTime
                });
            }
        }
        return items;
    }
}

Note that I have assumed that if there were less than 2 items in the table, then your data would not make sense in a view which is the purpose of if (logs.Count < 2). That check will also prevent exceptions in the code that follows.

I have also assumed (based on the description in the question) that .First() will always return an item with DataType.Start and .Last() will always return an item with DataType.Stop so I have excluded checks for that in the code above


Determine if a string of characters are unique using quicksort

Complexity

If the intent was to meet an \$O(N log N)\$ requirement, you've technically failed--quicksort has an expected complexity proportional to N log N, but big-O deals strictly with the worst-case complexity--and worst-case complexity of quicksort is \$O(N^2)\$.

Class Design

One of the old basic ideas of how to do object-oriented design is to start by writing down a one-page (or less) description of what the program is supposed to do. You then pick out the nouns that form the major themes in that description. Those are your classes.

The point of that is to note that most classes should normally represent nouns1. Things that exist. Objects. In a typical case they should not represent verbs.

In this case, however, you have one primary class--and its name is a verb, not a noun. This leads to a lot of question over whether it makes sense for this class to be a class, or whether we have kind of a conglomeration of "stuff" thrown together into something that says it's a class, but isn't doesn't form a particularly coherent...thing.

Standard Containers

Good uses for C style arrays in C++ are quite rare. Your arr doesn't strike me as one of them. If you really need a fixed-size array, you should probably use std::array instead. Otherwise, you're probably best off using std::vector.

Standard Algorithms

The standard library already has algorithms to handle the job at hand. Most code should just use st::sort followed by std::unique, rather than attempting to craft the same on your own.

Self-defeating design

Right now, you've limited the collection size to only 15 elements. For such a small size, a simpler sorting algorithm (e.g., insertion sort) will almost always be at least a little faster than a quicksort. In short, combining the elements you have in the way you have just doesn't make sense.

Use of strlen

If you insist on using strlen at all, you shouldn't call it in the condition of a for loop, like:

for (int i=0; i<strlen(foo); i++)

A few compilers know how to optimize this by hoisting the call to strlen out of the loop, but most don't. With those compilers, this loop will have \$O(N^2)\$ complexity instead of the O(N) you probably want/expect.

Note that if you used std::vector or std::string for your storage, this wouldn't be a problem. Unlike strlen, both these guarantee that you can find the size with \$O(1)\$ complexity instead of \$O(N)\$.

Side Effect-ridden code

Most of your functions implicitly modify FindUniqueCharInString::arr. It's generally much better to avoid this when possible--and it's pretty trivial in most of these cases. Just for a trivial example, right now your swap is passed to integers, i and j, and it swaps arr[i] with arr[j]. It would be much better to pass (for example) pointers or references to the contents, so the modifications are explicit:

swap(i, j); // ambiguous, implicit side effects on `arr`

swap(arr[i], arr[j]); // clear, effect on `arr` is obvious.

Summary

At least in my opinion, the other issues pale compared to just making good use of the standard library.

std::string arr {"SOMESTRING"};
std::sort(arr.begin(), arr.end());
auto end = std::unique(arr.begin(), arr.end());

// show the unique characters
std::copy(arr.begin(), end, std::ostream_iterator<char>(std::cout, "\n"));

1. The primary exception to this is function objects--i.e., classes that act mostly like a function, including overloading operator() to do whatever it is they do


Shellcheck reports quite a few issues you might want to correct:
shellcheck -f gcc  197939.sh
197939.sh:2:5: warning: Assigning an array to a string! Assign as array, or use * instead of @ to concatenate. [SC2124]
197939.sh:5:24: note: Backslash is literal in "\.". Prefer explicit escaping: "\\.". [SC1117]
197939.sh:5:36: note: Backslash is literal in "\.". Prefer explicit escaping: "\\.". [SC1117]
197939.sh:5:48: note: Backslash is literal in "\.". Prefer explicit escaping: "\\.". [SC1117]
197939.sh:8:14: error: Double quote array expansions to avoid re-splitting elements. [SC2068]
197939.sh:10:17: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:10:22: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:10:25: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:13:38: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:14:28: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:14:38: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:15:38: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:16:22: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:16:29: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:16:38: note: egrep is non-standard and deprecated. Use grep -E instead. [SC2196]
197939.sh:17:39: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:25:13: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:25:19: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:26:11: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:26:33: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:27:26: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:28:16: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:28:38: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:29:27: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:32:10: error: Double quote array expansions to avoid re-splitting elements. [SC2068]
197939.sh:34:27: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:35:14: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:35:33: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:47:11: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:48:23: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:49:9: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:49:19: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:54:13: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:54:22: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:55:26: note: Double quote to prevent globbing and word splitting. [SC2086]

Additionally, I recommend making regexp, nameserver, IPADD, ServerName and DATA local within check() (and giving most of them better names, or inlining the single-use ones), and making Pinging, IPADD and ServerName local within check2():
check ()
{
    local regexp='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
    local nameserver=('@ns1.ournameserver.com' '@ns2.ournameserver.com' '@ns3.ournameserver.com')

    for j in "${nameserver[@]}"
    do
        local IPADD
        IPADD=$(dig "$j" "$i" +noall +answer | grep "A" | awk '{print $5}')
        if [[ $IPADD =~ $regexp ]]
        then
            echo "IP Address = $IPADD"
            echo "ServerName = $(nslookup "$IPADD" | grep -o -P '(?<=\=).*(?=.)')"
            echo "Data Center = $(whois "$IPADD" | grep -E 'org-name|OrgName' | awk '{print $2.$3}')"
            break
        fi
    done
}

check2 ()
{
    local Pinging
    Pinging=$(ping "$i" -c 1 | grep 'from' | cut -d$' ' -f4-5| tr '\(|\)' ' ')
    echo "IP Address = $(awk '{print $2}' <<<"$Pinging")"
    echo "Server Name = $(awk '{print $1}' <<<"$Pinging")"
}

Prefer to pass "$i" as an argument to check(), rather than communicating via global variables.  And communicate the $IPADD from the last successful nameserver by other means.
Instead of extracting substrings using grep, then testing them with [[ =~ ]], simply use grep -q for the test.
Improved code
There's still plenty left to work on (for example, repeated whois invocations).
#!/bin/bash

check ()
{
    local regexp='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
    local nameserver=('ns1.ournameserver.com' 'ns2.ournameserver.com' 'ns3.ournameserver.com')

    for j in "${nameserver[@]}"
    do
        local IPADD
        IPADD=$(dig "@$j" "$1" +noall +answer | grep -w 'A' | awk '$4=="A" {print $5}')
        if [[ $IPADD =~ $regexp ]]
        then
            echo "IP Address = $IPADD"
            echo "ServerName = $(nslookup "$IPADD" | grep -o -P '(?<=\=).*(?=.)')"
            echo "Data Center = $(whois "$IPADD" | grep -E 'org-name|OrgName' | awk '{print $2.$3}')"
            return 0
        fi
    done
    return 1
}

check2 ()
{
    local Pinging
    Pinging=$(ping "$1" -c 1 | grep 'from' | cut -d$' ' -f4-5| tr '()' ' ')
    echo "IP Address = $(awk '{print $2}' <<<"$Pinging")"
    echo "Server Name = $(awk '{print $1}' <<<"$Pinging")"
}

for i in "$@"
do
    echo "Domain Name = $i"
    if nslookup -type=ns "$i" | grep -q 'nameserver.*cloudflare.com'
    then
        check "$i" || echo "This Domain does not belong to this server."
    else
        check2 "$i"
    fi

    whois "$i" | grep "Registrant Name"
    nslookup -type=ns "$i" | grep nameserver | awk '{print $2,$3,$4}'
    if curl -sL "http://$i" | grep -q '<title>.*Account.*Suspended'
    then
        echo "Status = Account Suspended"
    else
        echo "Status = $(curl -I "$i" 2>/dev/null | head -n 1 | cut -d$' ' -f2-3)"
    fi
    printf '%*s\n' 100 | tr ' ' '#'
done


public boolean hasWon(Seed theSeed) {

What is a Seed?  The way that you are using it, I'd expect a Player object.

    for (int col = 0; col < COLS; ++col) {               //check columns
        if (cells[currentRow][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
    }

A more common format would be

    //check squares in currentRow
    for (int col = 0; col < COLS; ++col) {
        if (cells[currentRow][col].content == theSeed) {
            count++;
        } else {
            count = 0;
        }

        if (count == WIN_SIZE) {
            return true;
        }
    }

I added the else because I would expect a match to need to be consecutive.  As is, you would accept any row containing WIN_SIZE total matches.  Maybe that's what you want, but it's not what I would expect.

You iterate over columns when you are checking a row.  The original comment was a bit confusing on that aspect.

While there is a single statement form of control structures (if), it is often recommended not to use it.  It's less clear about what goes with what and it's easier to edit in a way that causes problems but is syntactically correct.

    count = 0;

    int row = currentRow;

    for (int col = currentCol; col >= 0; --col) {      //check forward diagonal
        if (cells[row][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
        row--;
        if (row < 0)
            break;
    }
    row = currentRow;
    count--;
    for (int col = currentCol; col < COLS; ++col) {
        if (cells[row][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
        row++;
        if (row == ROWS)
            break;
    }

This looks more complicated than it needs to be.  Consider

    // check forward diagonal
    for (int col = currentCol, row = currentRow; col >= 0 && row >= 0; --col, --row) {
        if (cells[row][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
    }

    for (int col = currentCol + 1, row = currentRow + 1; col < COLS && row < ROWS; ++col, ++row) {
        if (cells[row][col].content == theSeed)
            count++;
        if (count == WIN_SIZE)
            return true;
    }

Yes, you can use two variables in one for loop.

Rather than decrementing the count, this skips the current square in the second loop.

Or do the whole thing in one loop.

    // check forward diagonal
    count = 0;
    int col = 0;
    int row = 0;
    if (currentCol >= currentRow) {
        col = currentCol - currentRow;
    } else {
        row = currentRow - currentCol;
    }

    for (; col < COLS && row < ROWS; ++col, ++row) {
        if (cells[row][col].content == theSeed) {
            count++;
        }

        if (count == WIN_SIZE) {
            return true;
        }
    }

More work up front to figure out the first square in the diagonal, but only a single loop.

I left off the else case, as I'm not sure whether the current behavior is intentional or not.  The single loop version works with the else as before.  The double loop versions don't.