Generate random numbers without repetitions

Updated answer in response to bounty: See Is that your final answer? at the end, and other changes - basically answer is significantly rewritten.

To break your problem down in to requirements:

you need a set of random numbers
the numbers need to be unique
the order of the returned numbers needs to be random

Your current code indicates that the range of random numbers is specified by Random.Next(), which returns values in the [0 .. Int32.MaxValue) range (note, it excludes Int32.MaxValue). This is significant for the purpose of this question, because other answers have assumed that the range is configurable, and 'small'.

If the range should be configurable, then the recommended algorithm would potentially be much larger.

Based on those assumptions, let's do a code review...

Code Style

do ... while

The most glaring problems here are the un-braced do-while loop. You already knew it, but this code is ugly:

    do number = random.Next();
    while (randomNumbers.Contains(number));

It really should be braced:

    do
    {
        number = random.Next();
    } while (randomNumbers.Contains(number));

This makes the statement clear, and significantly reduces confusion. Always use braces for 1-liners.

List Construction

The List class allows an initial capacity to be used. Since the capacity needs to just be count, it makes sense to initialize the list with this capacity:

List<int> randomNumbers = new List<int>(count);

Current Algorithm

This is where the most interesting observations can be made. Let's analyze your current algorithm:

Create a container for the results
repeat until you have selected N values:

Select a random value
check if it has been previously selected
if it is 'new', then add it to the container

This algorithm will produce random values, in a random order, and with good random characteristics (no skews, biases, gaps, etc.).

In other words, your results are good.

The problem is with performance....

There are two performance concerns here, one small, the other large:

the do-while loop to avoid collisions
the List container

do-while performance

The do-while has a very low impact on performance... almost negligible. This is hotly debated, but, the reality is that you would need a very, very large count before this becomes a problem. The reasoning is as follows:

Collisions happen when the random value was previously selected. For the specified range of [0 .. Int32.MaxValue), you would need a very large count before collisions actually happened. For example, count would have to be about 65,000 before there was better than a 50% chance that there was even a single collision.

In a general sense, given a Range of \$N\$, select \$M\$ numbers. If \$M < \sqrt{N}\$ then the probability of a single collision is < 50%. Since the Range is very large, the probability is small.

Obviously, if the range was small, then the probabilities would be significantly affected. But the range is fixed at Int32.MaxValue, so that's OK.

Additionally, if the count was large, then the probabilities would also be affected. How large would be very large? Well, you would be running in to very large arrays before you run in to significant problems..... I would venture you are hitting close to \$\frac{Int32.MaxValue}{2}\$ before you run in to a significant issue with performance.

List performance

This is without doubt your largest concern. You use the randomNumbers.Contains(number) call to determine whether a value was previously selected. This requires a scan of all previously-selected values to determine. As mentioned, this will almost always return false, and will thus have to scan the entire list.

As the count value increases, the length of time to perform the Contains will increase at an quadratic rate, \$O(n^2)\$ where n is count.

This performance problem will become critical much sooner than the random-collision problem.

Putting it together

The problem you have in your code is that you are trying to do too much at once, you are using a List because that is your return value, when a HashSet would be better. If you break the problem down in to stages, you will be able to solve things more elegantly.

If you add a duplicate value to a HashSet, it does not grow, and the operation performance is not dependent on the amount of data in the HashSet (it is \$O(1)\$). You can use the Count of the HashSet to manage the data uniqueness.

Once you have a clean set of unique random numbers, you can dump them in to a List, then shuffle the list using an efficient shuffle.

Combining these data structures, in the right way, leads to an overall \$O(n)\$ solution, which will scale fairly well.

Here is some code, which works in Ideone too. Note, my C# is weak, so I have tried to make the logic clear.

using System;
using System.Collections.Generic;

public class Test
{
    static Random random = new Random();

    public static List<int> GenerateRandom(int count)
    {
        // generate count random values.
        HashSet<int> candidates = new HashSet<int>();
        while (candidates.Count < count)
        {
            // May strike a duplicate.
            candidates.Add(random.Next());
        }

        // load them in to a list.
        List<int> result = new List<int>();
        result.AddRange(candidates);

        // shuffle the results:
        int i = result.Count;
        while (i > 1)
        {
            i--;
            int k = random.Next(i + 1);
            int value = result[k];
            result[k] = result[i];
            result[i] = value;
        }
        return result;
    }
    public static void Main()
    {
        List<int> vals = GenerateRandom(10);
        Console.WriteLine("Result: " + vals.Count);
        vals.ForEach(Console.WriteLine);
    }
}

The above code is my initial recommendation, and it will work well, and scale well for any reasonable number of values to return.

Second Alternate Algorithm

The problem with the above algorithm is threefold:

When count is very large, the probability of collision is increased, and performance may be affected
Data will need to be in both the HashSet and the List at some point, so the space usage is doubled.
The shuffle at the end is needed to keep the data in a random order (HashSet does not keep the data in any specific order, and the hashing algorithm will cause the order to become biased, and skewed).

These are only performance issues when the count is very large. Note that only the collisions at large count will impact the scalability of the solution (at large count it is no longer quite \$O(n)\$, and it will be come progressively worse when count approaches Int32.MaxValue. Note that in real life this will not likely ever happen.... and memory will become a problem before performance does.

@JerryCoffin pointed to an alternate algorithm  from Bob Floyd, where a trick is played to ensure that collisions never happen. This solves the problem of scalability at very large counts. It does not solve the need for both a HashSet and a List, and it does not solve the need for the shuffle.

The algorithm as presented:

initialize set S to empty
for J := N-M + 1 to N do
    T := RandInt(1, J)
    if T is not in S then
        insert T in S
    else
        insert J in S

assumes that RandInt(1, J) returns values inclusive of J.

To understand the above algorithm, you need to realize that you choose a random value from a range that is smaller than the full range, and then after each value, you extend that to include one more. In the event of a collision, you can safely insert the max because it was never possible to include it before.

The chances of a collision increase at the same rate that the number of values decreases, so the probability of any one number being in the result is not skewed, or biased.

Is this almost a final answer? No

So, using the above solution, in C#, would look like (in Ideone) (note, code is now different to Ideone):

public static List<int> GenerateRandom(int count)
{
    // generate count random values.
    HashSet<int> candidates = new HashSet<int>();
    for (Int32 top = Int32.MaxValue - count; top < Int32.MaxValue; top++)
    {
        Console.WriteLine(top);
        // May strike a duplicate.
        if (!candidates.Add(random.Next(top + 1)))
        {
            candidates.Add(top);
        }
    }

    // load them in to a list.
    List<int> result = candidates.ToList();

    // shuffle the results:
    int i = result.Count;
    while (i > 1)
    {
        i--;
        int k = random.Next(i + 1);
        int value = result[k];
        result[k] = result[i];
        result[i] = value;
    }
    return result;
}

Note that you need to shuffle the results still, so that the HashSet issue is resolved. Also note the need to do the fancy loop-condition top > 0 because at overflow time, things get messy.

Can you avoid the shuffle?

So, this solves the need to do the collision loop, but, what about the shuffle. Can that be solved by maintaining the HashSet and the List at the same time. No! Consider this function(in Ideone too):

public static List<int> GenerateRandom(int count)
{
    List<int> result = new List<int>(count);

    // generate count random values.
    HashSet<int> candidates = new HashSet<int>();
    for (Int32 top = Int32.MaxValue - count; top < Int32.MaxValue; top++)
    {
        // May strike a duplicate.
        int value = random.Next(top + 1);
        if (candidates.Add(value))
        {
            result.Add(value);
        }
        else
        {
            result.Add(top);
            candidates.Add(top);
        }
    }

    return result;
}

The above answer is never going to allow the first value in the result to have any of the Max - Count to Max values (because there will never be a collision on the first value, and the range is not complete at that point), and this is thus a broken random generator.

Even with this collision-avoiding algorithm, you still need to shuffle the results in order to ensure a clean bias on the numbers.

TL;DR

Is This Your Final Answer? Yes!

Having played with this code a lot, it is apparent that it is useful to have a range-based input, as well as a Int32.MaxValue system. Messing with large ranges leads to potential overflows in the 32-bit integer space as well.

Working with @mjolka, the following code would be the best of both worlds:

    static Random random = new Random();

    // Note, max is exclusive here!
    public static List<int> GenerateRandom(int count, int min, int max)
    {

        //  initialize set S to empty
        //  for J := N-M + 1 to N do
        //    T := RandInt(1, J)
        //    if T is not in S then
        //      insert T in S
        //    else
        //      insert J in S
        //
        // adapted for C# which does not have an inclusive Next(..)
        // and to make it from configurable range not just 1.

        if (max <= min || count < 0 ||
                // max - min > 0 required to avoid overflow
                (count > max - min && max - min > 0))
        {
            // need to use 64-bit to support big ranges (negative min, positive max)
            throw new ArgumentOutOfRangeException("Range " + min + " to " + max +
                    " (" + ((Int64)max - (Int64)min) + " values), or count " + count + " is illegal");
        }

        // generate count random values.
        HashSet<int> candidates = new HashSet<int>();

        // start count values before max, and end at max
        for (int top = max - count; top < max; top++)
        {
            // May strike a duplicate.
            // Need to add +1 to make inclusive generator
            // +1 is safe even for MaxVal max value because top < max
            if (!candidates.Add(random.Next(min, top + 1))) {
                // collision, add inclusive max.
                // which could not possibly have been added before.
                candidates.Add(top);
            }
        }

        // load them in to a list, to sort
        List<int> result = candidates.ToList();

        // shuffle the results because HashSet has messed
        // with the order, and the algorithm does not produce
        // random-ordered results (e.g. max-1 will never be the first value)
        for (int i = result.Count - 1; i > 0; i--)
        {
            int k = random.Next(i + 1);
            int tmp = result[k];
            result[k] = result[i];
            result[i] = tmp;
        }
        return result;
    }

    public static List<int> GenerateRandom(int count)
    {
        return GenerateRandom(count, 0, Int32.MaxValue);
    }


Constructing expressions that produce integers by only using digits in string '2017' and high school level operators and functions

Where your code is currently lacking is using all the knowledge you have. You already know that in the end the digits have to be in order and that in between the digits there can (or can not) be an operator.

This means, we only need to generate all strings of the form s = "{}2{}0{}1{}7{}", where the {} denote a place for an operator.

In addition, we know that certain operators will never make sense at the beginning (like /) and most will not make sense at the end either (basically, only ) makes sense there).

If we use this fact, we can end up with something like:

from collections import defaultdict
from itertools import product
from math import *

allowed_begin = set(["", "+", "-", "sin(", "cos(", "tan(", "exp(", "("])
allowed = allowed_begin | set(
    ["*", "/", "**", "*sin(", "*cos(", "*tan(", "*exp(", "*(", ")"])
allowed_end = set(["", ")"])

def find_expressions():
    expressions = defaultdict(list)
    template = "{}2{}0{}1{}7{}"
    for ops in product(allowed_begin, allowed, allowed, allowed, allowed_end):
        try:
            expression = template.format(*ops)
            n = eval(expression)
            if n >= 0 and n % 1 == 0:
                print n, x
                expressions[n].append(expression)
        except Exception:
            pass

    return expressions

if __name__ == "__main__":
    expressions = find_expressions()
    print sorted(expressions.keys())

This runs in about 0.5s on my machine and finds expressions for
0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20.0, 21, 26, 27, 28, 30, 34, 37, 120, 140, 160, 194, 208, 340, 1407, 2017, 32768, 1.1719142372802612e+16, 13107200000000000000000L, 6.327431707155585e+60, 1.7911398206275708e+84, 2.1540324218248465e+90, 4.572185553551339e+147. They are stored in expressions and all possible expressions for an existing key can be accesses via e.g. expressions[22].

Note that I chose to allow *( as an operator, meaning implicit multiplication (see comment on the question). If you think this is not allowed, just take them out of the allowed operators.

The loop approach has one advantage over itertools.permutations. It allows a == b == c == d. Whereas permutations does not:

>>> list(itertools.permutations([1,2], 2))
[(1,2), (2,1)]

Note the absence of (1,1) and (2,2).


HackerRank Caesar Cipher, not using map, filter, reduce, regex

Enumerating UTF-8 characters: Your code uses two nested loops to encrypt letters
(based on the UTF-8 code):

var  eMessage = ""
let arr = messageToCipher.characters.map { String($0) }
for ch in arr {
    for code in String(ch).utf8 {
        if (65<=code && code<=90) || (97<=code && code<=122) {
            // ... translate `code` and append to `eMessage` ...
        }
        else{
            eMessage = eMessage + ch
        }
    }
}

This is unnecessary complicated and has an unwanted side effect if the message contains
non-ASCII characters (which are encoded as 2 or more UTF-8 code units):

print(cipher(messageToCipher: "ä €  ", k: 2) )
// ää €€€

This could be solved by adding a break in the else-case. The better solution is to
enumerate the UTF-8 code units directly:

var encoded: [UInt8] = []
for code in messageToCipher.utf8 {
    if (65<=code && code<=90) || (97<=code && code<=122) {
        // ... translate `code` and append to `encoded` ...
    }
    else{
        encoded.append(code)
    }
}
return String(bytes: encoded, encoding: .utf8)!

Code duplication: There is some duplicate code in

            if k > 26{
                let value =  k % 26 == 0 ? k / 26 : k % 26
                var pCode  = ((Int(code))  + (value))
                if (pCode  > 122 && (97<=code && code<=122)) || (pCode  > 90 && (65<=code && code<=90)) {
                    pCode = pCode - 26
                }
                let s = String(UnicodeScalar(UInt8(pCode)))
                eMessage = eMessage + s
            }else
            {
                var pCode  = Int(code) + k
                if (pCode  > 122 && (97<=code && code<=122)) || (pCode  > 90 && (65<=code && code<=90)) {
                    pCode = pCode - 26
                }
                let s = String(UnicodeScalar(UInt8(pCode)))
                eMessage = eMessage + s
            }

which is not necessary. The if-part works for the case k <= 26 as well.

Exceptional key values: The special handling of the case k % 26 == 0 causes
unexpected results:

print(cipher(messageToCipher: "abc xyz ABC XYZ", k: 26) ) // abc xyz ABC XYZ
print(cipher(messageToCipher: "abc xyz ABC XYZ", k: 52) ) // cde zab CDE ZAB

and is not needed. Negative key values are not handled at all:

print(cipher(messageToCipher: "abc xyz ABC XYZ", k: -2) )   // _`a vwx ?@A VWX
print(cipher(messageToCipher: "abc xyz ABC XYZ", k: -200) )
// Fatal error: Negative value is not representable

Both issues can be solved by computing the remainder of k modulo 26, as a number
in the range 0...25:

var value = k % 26
if value < 0 { value += 26 }

In addition, this computation can be done once, before entering the loop.

Other issues:

I would use some different argument/variable names, e.g. message instead of
messageToCipher (it is clear from the context and the function name that this string
should be encrypted), or  key instead of k.
There are unnecessary parentheses, e.g. in

var pCode  = ((Int(code))  + (value))

The usage of white space is not consistent, e.g. in

if (pCode  > 122 && (97<=code && code<=122)) || (pCode  > 90 && (65<=code && code<=90)) {

Summarizing the suggestions so far, we have

func cipher(message: String, key: Int) -> String {

    var offset = key % 26
    if offset < 0 { offset += 26 }

    var encoded: [UInt8] = []
    for code in message.utf8 {
        if (65 <= code && code <= 90) || (97 <= code && code <= 122) {
                var pCode  = Int(code) + offset
                if (pCode > 122 && (97 <= code && code <= 122)) || (pCode > 90 && (65 <= code && code <= 90)) {
                    pCode -= 26
                }
                encoded.append(UInt8(pCode))
        } else {
            encoded.append(code)
        }
    }
    return String(bytes: encoded, encoding: .utf8)!
}

Make it functional: If the encryption of a single character is moved to a separate
function then one can apply this to the UTF-8 view with map():

func cipher(message: String, key: Int) -> String {

    var offset = key % 26
    if offset < 0 { offset += 26 }

    func utf8encrypt(code: UInt8) -> UInt8 {
        // ... compute and return encrypted character ...
    }

    return String(bytes: message.utf8.map(utf8encrypt), encoding: .utf8)!
}

Further suggestions:

Use a switch-statement with range patterns instead of the
if-conditions:

switch code {
case 65...90:
    // ...
case 97...122:
    // ...
default:
    // ...
}

Use constants instead of the literal numbers, e.g.

let letter_A = 65
let letter_Z = 90
let letter_a = 97
let letter_z = 122

so that a future reader of your code does not have to guess what the numbers stand for.


Code indentation for declaring inputs/outputs in an array

An argument against table-style alignment in code

Except when the editor/IDE helps maintain alignment with little work from the programmer, and all those who work with the code have that same facility, horizontal, table-like alignment in code is more trouble than it's worth, for these reasons:

Search/replace operations on the entire code-base (as when renaming a variable or method) will tend to leave such code in a mess that needs manual cleanup.
Anyone whose editor/IDE does not make horizontal alignment easy will spend a lot of time hitting space or DEL to make things line up when adding or deleting an entry.
When the entire table needs to be realigned (as when adding a new row that causes a column to grow), the version control system will show that the entire table changed.

For those reasons, I'm inclined to put up with a little bit of ugly:

 var equals = [ //input, output
   ["name:(John Smith)", "name:(John~ Smith~)"],
   ["name:Jon~0.1", "name:Jon~0.1"],
   //...
 ];

or, as @ChrisW suggests:

 var equals = [ //input, output
   [
     "name:(John Smith)",
     "name:(John~ Smith~)"
   ],
   [
     "name:Jon~0.1",
     "name:Jon~0.1"
   ],
   //...
 ];

But maybe data doesn't want to be in the code

Sometimes data wants its own home, a place where "rows and columns" are more natural than in code.  Perhaps that's a table in the database.  In your case, where the table is input to a test, a .csv file might be good.  A non-technical user could then view and edit the data with a spreadsheet program.


The JavaDoc of SortedSet.first() says "Returns the first (lowest) element currently in this set.". However in this case it is actually the highest score.

The definition of lowest and highest is determined by the comparator. If you put Integers in the sorted set, the first element will be the lowest, because the default comparator will be used. In your Item object however, you have a different definition of what is lower and higher:

@Override
public int compareTo(Item<T> i) {
    int x = -Double.compare(score, i.score);
    if(x==0) {x=c.<T>compareTo(i.c);}
    return x;
}

Your elements are still ordered from lowest to highest as dictated by your comparison method: practically you defined 0.7 to be lower than 0.3, that's all. As you noticed yourself, if you drop the negative sign in int x = -Double.compare(score, i.score); you effectively switch the ordering.

  If I compare the other way around, however, the user needs to reverse the SortedSet in order to do this common use case.

I'm wondering if you're aware of the .last() method. It seems that's what you're looking for.

By the way, you can also make a TreeSet sort items in reverse order, by constructing it like this:

SortedSet<Item<String>> items = new TreeSet<>(Collections.reverseOrder());

  If I only compare by score, the SortedSet can only have one item with the same score. However comparing by c strikes me as somehow arbitrary (not sure what I can do against that).

I'm not really sure what you mean by that. Since c is a String, comparison will be alphabetic by default.

I recommend this writing style (I also renamed variables):

@Override
public int compareTo(Item<T> item) {
    int cmp = -Double.compare(score, item.score);
    if (cmp == 0) {
        return c.<T>compareTo(item.c);
    }
    return cmp;
}


javascript is garbage collected, unless you're making huge(tens of MB of XML/JSON) data transfers every couple of seconds and keep references to that data, there should be "no memory leak" unless the browser is doing a lousy job.

I would put "items" array as global variable so that with each request, you overwrite it, in this way, old data will be discarded, i.e.

// moved globally
var items = [];
function list_stuff(data, type, where, order)
{
  // try to parse data as JSON
  try
  {
    items = jQuery.parseJSON(data);
    var index;
    var item;
    for ( index = 0; index < items.length; index++ )
    {
      item = items[index];
      // do something with "item"
    }
  }
  catch(e)
  {
    // handle error here
  }
}


Replace all usages of direct Values.

Try assiging values first to a named variable and then concating it, so its sustainable in the future like:

return $pieces['scheme'] . '://www.' . $regs['domain'] . '/favicon.ico';

could be:

$protocol = $pieces['scheme'];
$domainName = $regs['domain'];
$faviconName = . '/favicon.ico';
$favIconLink = $protocol. '://www.' .  $domainName . $faviconName
return  $favIconLink;

This would make it reusable and readable for other developers, and it reduces comments ;-) Currently you have many of them

$fav=$this->fav($ass_array['url']);

I love regex, but once written nobody understands it:

if(preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs))

i would add a comment which explaines detailed what this regex is suppose to do. So if there is an Problem with the Regex everybody can check if the regex is doing it's job or if there is a problem in the expression.

Throw an exception in your constructor, so the errormessage can be cought. Now the error Message is displayed in the frontcode.

function __construct($type)
{
parent::__construct();
switch ($type)
  {
  case "bookmraks":
    $this->bookmarks();
    break;
  case "tweets":
    $this->tweets();
    break;
  default:
    throw new Exception('Invalid View Type');
  }
}

Last but not least:

try using "'" for strings, so its more readable and you make less errors by escaping not escaping closing, whatever

 '
$a[fname] posted

$a[message]

'

instead of :

 "
$a[fname] posted

$a[message]

"


That looks about right. Your thread doesn't do very much, though, so you might want to consider something like so (untested):

def blink(abort, delay, count):
    while not abort.isSet():
        for x in range(0, count):
            print "blink", x + 1
            GPIO.output(BLUE_LED, True)
            sleep(.25)
            GPIO.output(BLUE_LED, False)
            sleep(.25)
        sleep(1) #pause between blinks
        abort.wait(delay)

Then later

thread_stop = Event()
b = threading.Thread.run(target=blink, args=(thread_stop, 1, 0))

which prevents need for the whole class. It's not a suggestion as much as a note that you did more than you needed to.

Note that your blink should really be using abort.wait and should cooperate with the other abort.wait to have sensible timings.


Join and map command line arguments in Rust

I've collected a few thoughts about possible refactors you could consider below.

Your if chain isn't the most efficient way

As you've written it, your code will only work for titles between one and four words long. This isn't a disaster, and it will probably work for most titles, but we can rewrite your code to be shorter and handle any length of title. A win-win!

We can use Iterator::skip() to throw away the executable name, as we don't care about it anyway. See skip() in the documentation.

let args: Vec<String> = env::args().skip(1).collect();

It'd be a good idea to check that we've been given enough arguments before continuing.

let arg_len: usize = args.len();
if arg_len < 2 {
    panic!("At least two arguments must be supplied!");
}

Now, we can be a bit clever and avoid your if chain all together. Using a range we can get a slice of our args vector corresponding to all but the last element. We can then use join() to turn that slice back into a String. For example, if we started with vec!["Song", "of", "Solomon", "2:2-4"] in args, we would take a slice to get ["Song", "of", "Solomon"] and rejoin them with " " in the middle to get "Song of Solomon".

let book = args[0..(arg_len - 1)].join(" ");

Try to avoid clone() unless necessary

The first thing I noticed when I took a look at your code was that you've used clone() in quite a few places. We've already got rid of a lot of them with the tweak above, and you should try to avoid them all together as allocating when you don't need to is a waste of time and memory. If you can use an &str, do that instead of insisting on all strings being String. As an aside, there is rarely any point bothering with &String — just use &str there.

Putting the above into action, we can let reference be an &str and avoid a clone.

let reference: &str = &args[args.len() - 1];

Let's also change get_book's method signature as suggested above.

fn get_file(book: &str) -> &str {

Now we can get rid of the unnecessary to_string() below.

books_to_files.get::<str>(&book.to_string()).unwrap()

And tweak this line in main() to accept an &str.

let file: &str = get_file(&book);

Avoiding unwrap

Ideally, get_book ought to return an Option instead, so the caller can choose how they want to handle the error. As it is fatal anyway, unwrapping makes little difference, but it's worth bearing in mind as a future improvement.

Try it Online


I focussed exclusively on your last bit of code. I'm afraid I only managed a ~1.8x speed increase. I think a lot of comes down to Ruby's itself not being the quickest thing going - at least not when it comes to this particular algorithm.

Long story short: Convert your number and letter strings to integer arrays. For whatever reason, that's where I found a performance increase. I'll leave the explanation to someone with deeper knowledge of Ruby's string handling.

There may be a totally different way to do this, which'll be super-fast in Ruby, but I haven't investigated that. Generally, though, Ruby aims for expressiveness and readability, and this algorithm doesn't play to Ruby's strengths.

Anyway, review time! I've only changed minor stuff to make it more Ruby-like; the algorithm itself is as it ever was (for good or bad)

You'll still find that the majority of the time is spent in that first method. For one, it's being called constantly, and for another, it's doing the most work. Anything else in the code is just loops and boolean logic. But check_number_with_partial_string is the one actually doing the real checking of numbers to letters. So it's no wonder it weighs heavy on the performance.

check_number_with_partial_string

The logic's iffy. By which I mean that there is literally one if too many. The number will be either 1 or 0, so why the extra check? Also, no need to (potentially) call include?('B') twice. Store it once, use it twice.
There might also be a micro-optimization here if we flip the second return value around. If we've stored includes?('B') already and it's false, we can check that first, and, since the expression uses &&, the check for includes?('A') doesn't need to run.
Should maybe just be called partial_match?

check_matching

For the sake of line-length, I'd probably just call the matrix matrix. It's not about to be confused with anything
Favor || over or for boolean logic (here's a good explanation)
matching_matrix[row][c] = false is unnecessary since the initial value of that index is nil which is already false'y. But since check_number_with_partial_string returns a bool, we can skip a bit and just assign its return value to the index.
The overall name is a bit misleading. I'd imagine it would return something, since it's called "check" - but it doesn't.

Read loop

Right now, the entire map must run before anything is printed. You can use IO#each_line instead of loading everything into memory at once. And print for each test case. I've changed it, but the original may be faster(!)
Use do..end for multiline blocks (though if you keep the puts outside, the lower precedence of do..end compared to {...} will trip you up)
Use Array.new with a block instead of creating and then mapping an array to fill it
Pull named variables from the split string to keep things readable (no opaque array indices)

In the end, I had:

def check_number_with_partial_string(number, string)
  includes_b = string.include?(66) # ASCII 'B'
  return !includes_b if number == 0
  !(includes_b && string.include?(65)) # ASCII 'A'
end

def check_matching(numbers, string, matrix, row = 0, column = 0)
  return if matrix[-1][-1]
  return if row >= matrix.size || column >= matrix[row].size
  return if matrix[row][column]

  (column...string.length).each do |c|
    matrix[row][c] = check_number_with_partial_string(numbers[row], string[column...(c + 1)])
    check_matching(numbers, string, matrix, row + 1, c + 1) if matrix[row][c]
  end
end

File.open(ARGV[0]).each_line do |line|
  digits, string = line.chomp.split
  digits = digits.chars.map(&:to_i)
  string = string.chars.map(&:ord)
  matrix = Array.new(digits.length) { Array.new(string.length) }
  check_matching(digits, string, matrix)
  puts matrix[-1][-1] ? 'Yes' : 'No'
end

Again, as far as I can tell, any increased performance came from mapping the two strings to integers.

For some sample input I generated (where everything always matches), I got ~43 sec for the code above, versus ~83 sec for the original. That's obviously not the most rigorous test, but it seemed consistent with different input sizes.

Maybe there are more gains to be had somewhere, but I didn't find 'em (but I didn't try to do more overall restructuring either). Maybe someone else will spot something. But again (again) this just seems to me to be an algorithm that doesn't play to Ruby's strengths.


You have reinvented a form of radix sort.
See that page for how to get rid of the two nested O(n) loops.

It is possible to get O(n) if the maximum length of the words to be sorted is assumed to be a constant.


Specialized version of the cross correlation function

Here's a crack at my own question that uses built-in functions from NumPy

Update

The function chain bincount(digitize(data,bins)) is equivalent to histogram, which allows for a more succinct expression.

 def xcorr(first,second,dt=0.001,window=0.2,savename=None):
      length = min(len(first),len(second))
      diffs = array([first[i]-second[j] for i in xrange(length) for j in xrange(length)])
      counts,edges = histogram(diffs,bins=arange(-window,window,dt))
      counts -= length**2*dt/float(first[length])
      if savename:
           cPickle.dump((counts,edges[:-1]),open(savename,'wb'))
      return (counts,edges[:-1])

The indexing in the return statement comes because I want to ignore the edge bins.


Multiple producer single consumer on the same thread

I took rob.earwaker's advice (thanks!), and I implemented it using a BlockingCollection. The code is much simpler now :)
class ThreadedWorker<T> where T : class
{
    private readonly object locker = new object();
    BlockingCollection<T> queue = new BlockingCollection<T>(new ConcurrentQueue<T>());
    private readonly WorkerLogic<T> logic;
    private readonly Thread actualThread;
    private bool started = false;
    private volatile bool shouldWork = true;

    public ThreadedWorker(WorkerLogic<T> logic)
    {

        this.logic = logic;
        actualThread = new Thread(Spin);

    }

    private void Spin()
    {
        while (shouldWork)
        {
            T item;
            var dequeued = queue.TryTake(out item, TimeSpan.FromMilliseconds(100));
            if (!dequeued) continue;
            try
            {
                logic.Work(item);
            }
            catch (Exception ex)
            {
                // log
            }

        }
    }

    public void Stop()
    {
        Stop(TimeSpan.FromMilliseconds(500));
    }

    public void Stop(TimeSpan timeout)
    {
        shouldWork = false;
        bool joined = actualThread.Join(timeout);
        if (!joined)
        {
            try
            {
                actualThread.Abort();
            }
            catch (ThreadStateException)
            {
                // swallow
            }
        }
    }

    public void Push(T item)
    {
        if (!started)
        {
            lock (locker)
            {
                if (!started)
                {
                    started = true;
                    actualThread.Start();
                }
            }
        }
        queue.Add(item);
    }
}


Implementing write sphere of values to 3D array

I find it suspicious that your "Dimension 0" is completely empty. I'd at least expect to see a small "+" of 5's there. Whatever shows up in this last dimension should also show up (assuming spherical symmetry), on the top, the bottom and the sides of the sphere. This will round-out your square.

Perhaps you just need to try

if ( ( w * w ) + ( h * h ) + ( d * d ) <= Radius * Radius )

(i.e. <= instead of just <)

But I think you also need to ask yourself - should a sphere of radius 0 have a single 5 at the origin? Should a sphere of radius 1? What exactly does your radius mean?


The only way to do what you are trying to do, and remove the duplication, is really to cast.

What I would do is to use this kind of map:

private final Map<Class<? extends Variable>, Map<String, Variable>> variables;

To add something to the map, you could do:

variables.get(NumberVariable.class).put("key", value);

And to get:

return (NumberVariable) variables.get(NumberVariable.class).get("key");

You could even write a generic method:

private <T> T getVariable(Class<T> clazz, String key) {
    return clazz.cast(variables.get(clazz).get(key));
}

Note that this shouldn't even give any compiler warnings.

Leaking inner variable

Considering your getVariableNames method, imagine if I would call your code like this:

myVariableSet.getVariableNames.clear();

Whoops! I broke it!

The simple fix is this:

public Set<String> getVariableNames() {
    return new HashSet<>(usedVariableNames);
}

That is, return a copy of the data, then I can manipulate it all I want - I won't break anything!

I wouldn't use a usedVariableNames at all though and just do a map.containsKey(key) directly. If you want to make sure that all variable names are unique though, even if they are of different classes, then go ahead and keep this variable.


Find consecutive numbers and turn them into ranges

Letting a single method do everything is not such a good idea. You should rather separate the logic for finding consecutive numbers from creating a string from ranges and let them produce the final result by chaining them as extensions.

The first extension only knows how to find ranges. If you don't have range class/struct yet then you can use tuples.

public static IEnumerable<(int Min, int Max)> ToRanges(this IEnumerable<int> source)
{
    using (var e = source.GetEnumerator())
    {
        if (!e.MoveNext())
        {
            yield break;
        }

        var previous = e.Current;

        var range = (Min: previous, Max: e.Current);

        while (e.MoveNext())
        {
            var isConsecutive = e.Current - previous == 1;
            if (isConsecutive)
            {
                range = (range.Min, e.Current);
            }
            else
            {
                yield return range;
                range = (e.Current, e.Current);
            }
            previous = e.Current;
        }

        yield return range;
    }
}

The other extension consumes the result of ToRanges and returns a string.

public static string Stringify(this IEnumerable<(int Min, int Max)> ranges)
{
    var values = ranges.Select(range => $"{(IsEmpty(range) ? $"{range.Min}" : $"{range.Min}-{range.Max}")}");
    return string.Join(", ", values);

    bool IsEmpty((int Min, int Max) range)
    {
        return range.Max - range.Min == 0;
    }
}

The advantages of having two separated methods are:
- you can focus on one task at a time
- you are now able to test only one feature at a time
- you can reuse ToRange to calculate their lengths if necessary

Other things that you should address are:
- variable names should not sound like they were methods, e.g. groupDataIntoAdjacentBlocks; a much better name would be adjacentBlocks or something along the same lines
- int? lastValue = arr.FirstOrDefault(); this is wrong since the default value for int is 0 and not null.
- the result of the GetArray() method does not make much sense; why would you return an array of strings if there is always only one item? I guess this is not your real code but the range finding part and you edited it for the sake of the question so I won't comment on that one.


Unnecessary Generator

You've got an unnecessary generator expression here:

def bezier_curve(control_points, number_of_curve_points):
    return [
        bezier_point(control_points, t)
        for t in (
            i / (number_of_curve_points - 1) for i in range(number_of_curve_points)
        )
    ]

You don't need to generate i / (n-1); you could simply pass that argument to the bezier_point() function:

def bezier_curve(control_points, number_of_curve_points):
    return [ bezier_point(control_points, i / (number_of_curve_points - 1))
             for i in range(number_of_curve_points)
           ]

Slight optimization: instead of computing number_of_curve_points - 1 \$O(N)\$ times (pure Python will not cache the result), precompute it:

def bezier_curve(control_points, number_of_curve_points):
    last_point = number_of_curve_points - 1
    return [ bezier_point(control_points, i / last_point )
             for i in range(number_of_curve_points)
           ]

Tail Recursion

Python does not do Tail Call Optimization, so with M control points, you will recursively enter and exit M calls, for each of the N points along your curve.  That is M*N unnecessary stack frame entry/exits.  You should do the looping yourself:

def bezier_point(control_points, t):
    while len(control_points) > 1:
        control_linestring = zip(control_points[:-1], control_points[1:])
        control_points = [(1 - t) * p1 + t * p2 for p1, p2 in control_linestring]
    return control_points[0]

Since we loop while len(control_points) > 1, it should be guaranteed that control_points will only have one point when the loop exits, so return control_points[0] is safe.  The exception is if the function is called with zero control points, but then control_points[0] will properly fail with an IndexError.


Add and enable/disable Windows Firewall rules with Python

I agree with @Ludisposed answer, but you have a few subprocess gotchas:

You don't need to spawn a shell in order to run the command, simply build your command as a list of arguments and it will be fine. This is especially important if your rules names may contains spaces as the command would be treated entirelly differently in your implementation;
Replace the old subprocess.call by subprocess.run;
You may be interested to run subprocess.run by specifying check=True in order to generate an exception and be alerted if something does not go according to plan.

Applying these changes to e.g. modify_rule can lead to:

def modify_rule(rule_name, enabled=True):
    """Enable or Disable a specific rule"""
    subprocess.run(
        [
            'netsh', 'advfirewall', 'firewall',
            'set', 'rule', f'name={rule_name}',
            'new', f'enable={"yes" if enabled else "no"}',
        ],
        check=True,
        stdout=DEVNULL,
        stderr=DEVNULL
    )

Also note that I removed the print call from the function as it impairs reusability. If the caller want this kind of messages, it should be responsible for printing them, not this function.


Code review for a collection manipulation tool in Javascript

To clarify the use of your global variable "collection" as a namespace for your library, you should assign it directly to a value returned by your Immediately Invoked Function Expression:

var collection = (function(){
  ...

  function collection(array) {
    return new Collections(array);
  }

  return collection;
}());


From a pure Python standpoint, a list is already a stack if you narrow its methods down to only pop and append.
l.append(x) will put x at the end of the list, and l.pop() will remove the last element of the list and return it.

So generally speaking, when you need a stack in Python, you'll just make a list and use append and pop.
The same goes for queues, but you'd use l.pop(0) instead of l.pop().

Considering this, I would say it's just plain unpythonic to implement a stack structure; instead, just use a list, that really is a dequeue and thus can be used as both a stack and a queue.

That said, I understand that append is not the common naming for the stack structure, and that push makes the intent of the method more clear.
Therefore, I would implement a stack as a direct subclass of list, and just "rename" the append method:

class Stack(list):
    def push(self, x):
        super().append(x)

If I wanted to make it more fool-proof, I'd also override pop so that it cannot take a parameter, unlike list.pop

class Stack(list):
    ...
    def pop(self):
        return super().pop()

Now the operation performed by the peek method can usually be done by stack[-1] (where stack is an instance of Stack), but it could be implemented just as follows:

class Stack(list):
    ...
    def peek(self):
        return self[-1]

Addendum

Some comments advising against subclassing list came out, notably mentioning the "composition over inheritance" principle.
That was an enriching discussion, and I'd like to amend my answer accordingly.

I'm no expert in design patterns, but as I understand it, this principle advocates the use of composition instead of inheritance to provide more flexibility.
One benefit of composition here is clearly to provide a cleaner API, with only the common stack methods and not insert, remove and so on that come from list and have no sense for stacks.

On the other hand, the inheritance I suggested happens to violate Liskov's substitution principle.
Although there's no problem with adding push and peek methods with respect to this principle, my implementation changes the signature of the pop method, which is not allowed by this principle.

From this perspective, I think that not only composition is valid here and adds in the benefit of a clean API, but also that inheritance is plain incorrect here.
Therefore, if I were forced to implement a stack class in Python, I'd go with composition and do as follows:

class Stack:
    def __init__(self):
        self._data = []

    def push(self, x):
        self._data.append(x)

    def pop(self):
        return self._data.pop()

    def peek(self)
        return self._data[-1]

    def __len__(self):
        return len(self._data)

But again, as I said, I would never do that in real life because a list can already serve as a stack, and stack = [] would perfectly convey how stack would be intended to be used.

References:

On the Liskov substitution principle:

https://en.wikipedia.org/wiki/Liskov_substitution_principle
https://stackoverflow.com/q/56860/7051394

On composition over inheritance:

https://en.wikipedia.org/wiki/Composition_over_inheritance
https://stackoverflow.com/a/53354/7051394 (also happens to mention Liskov principle)


You don't need pointers to character pointers at all:

int str_cmp(const char* s1, const char* s2)
{
    while (*s1 != '\0' && *s1 == *s2)
    {
        ++s1;
        ++s2;
    }

    if (*s1 == *s2)
    {
        return 0;
    }

    return *s1 < *s2 ? -1 : 1;
}

Also, there is a bug in your second implementation: it returns 1 on compareStrings("hello", "helloo"), when the correct result is -1.

Hope that helps.


Working C code dealing with lists: problem with memory leak

In your current code, I can't see the copying of lists repeatedly as you stated. You are using pointers here so you're not actually duplicating the list.

The freeList function should be called once you're done using your list (the one returned by holidayList()).

Side Note:
You can refactor the code by utilizing createNode function when creating nodes and adding it to the tail.


Read characters from stdin into an resizeable array

Unnecessary function

The only difference between increase_buffer_size() and realloc() is that the former returns a char* and the latter returns a void*. But you can just manually do the cast anyway, which will still be shorter to type.

buffer_pointer = (char*)realloc(buffer_pointer, buffer_size *= 2);

Avoid putting lots of things on on one line

Your reallocation line does three things: checks if you need to reallocate, doubles the buffer size, and reallocates. It'd be much better to just split that up. Don't write the bodies of your if statements on the same line either, unless the body is trivial (e.g. return;). Using {}s is a good habit to get into:

// check capacity and double it if maximum is reached
if (counter == buffer_size - 1) {
    buffer_size *= 2;
    buffer_pointer = (char*)realloc(buffer_pointer, buffer_size);
}

What if realloc fails?

It's possible for it to return a null pointer after all.


Making line by line replacements using values from multiple arrays

One bug I see is that you perform the string substitutions sequentially, rather than "simultaneously".  For example, suppose you had an input file with contents

abc

with substitution code

arrayOne = ["a", "b"]
arrayTwo = ["b", "c"]

…
replace(0, 1)

Most users would expect the output to be bcc.  However, your code actually produces ccc, which would probably be considered surprising.

The main problem, though, is that everything is tightly coupled, such that the code is not reusable.

For example, replace() is a closure that captures arrayOne and arrayTwo, as well as file f.  It doesn't generalize to perform one substitution or ≥ 3 substitutions.  The two parameters that it does accept are more annoying than helpful, as you have indicated that you expect to always call it as replace(0, 1).  Furthermore, replace() will only operate on the file that was opened as f at the time that the function was defined.

A better interface would be for replace() to accept a dict of substitutions to be performed.  Furthermore, it should just concern itself with string transformation, staying clear of all file operations.

I propose the following solution, which contains some rather advanced concepts.

from functools import partial
import re

def str_replacer(mapping):
    regex = re.compile('|'.join(re.escape(orig) for orig in mapping))
    return partial(regex.sub, lambda match: mapping[match.group(0)])

You would use it like this:

>>> replace = str_replacer({
...     'a': 'b',
...     'b': 'c',
...     'c': 'd',
... })
>>> print(replace('abc'))
bcd

Explanation: Performing "simultaneous" replacements means scanning the input string until any of the "old" strings is encountered.  If a substitution is performed, the scanning should recommence at the after where the newly spliced-in string ends.

That's tedious to do using low-level string manipulation, so I've opted to use re.sub() instead.  To use re.sub(), I have to do two things

Compose a regular expression that includes all of the "old" strings to look for.  That's what re.compile(…) does.
Create a callback function that specifies what the replacement for each old string should be.  That's the lambda.  match.group(0) is the old string that was found.  We look its corresponding "new" string in the mapping.

However, I don't want str_replacer() to call regex.sub(repl, input_string) just yet.  Instead, I want str_replacer() to return a function, that if called, performs the desired replacements.  Why? Because you will likely call the resulting function many times if you want to process a file a line at a time, and it would be more efficient to reuse the regex and the lambda.  That's what functools.partial() does: it creates a function that accepts an input string; when that function is called, then the regex.sub(lambda match: mapping[match.group(0)], input_string) actually happens.

replace = str_replacer({
    'old string one': 'new string one',
    'old string two': 'new string two',
})

with open(path, "r", encoding="utf8") as in_file, \
     open(path.replace(".xml", "-new.xml"), "w", encoding="utf8") as out_file:
    for line in in_file:
        out_file.write(replace(line))

Now the string replacement logic and the file manipulation logic are cleanly separated!


One thing that is undoubtedly slowing you down is that you are reprocessing found text that is already hyperlinked. You should check that Rng.Text isn't already hyperlinked before you do all that work.

Do While .Execute(findText:=SearchString, Forward:=False) = True
    If Rng.Hyperlinks.Count = 0 Then
        'do your processing here
    End If
Loop

Although that will still perform the search on all of your previous text even if it skips processing them.

If you know that your unlinked text will always and only be at the end of the document, you could use a Boolean flag to stop searching once you hit found text that is already hyperlinked. Something like this:

Dim newText As Boolean
newText = True

With Rng.Find
    .MatchWildcards = True
    Do While newText
        If .Execute(findText:=SearchString, Forward:=False) Then
            newText = (Rng.Hyperlinks.Count = 0)
        Else
            newText = False
        End If

        If newText Then
            Id = Rng.Text
            'add your hyperlinks here
        End If
    Loop
End With

That should speed things up even more.


Nitpicks

public function upload_avatar($file, $user_id = false, $maxbytes = 102400) {
global $sql;

These two lines are indented inconsistently.  The first line should be indented less than the second.  Perhaps a copy/paste error.

There's an argument that the global line should be used closer to where the $sql variable is used.

I personally don't like the use of $sql to represent a database connection.  To me, SQL is a language rather than a generic name for a database.

To be consistent with the other names (e.g. $user_id), $maxbytes should be $max_bytes.

I'd like this function better if it had more vertical whitespace.  In particular, I would expect a blank line after global $sql; to separate the declaration from the code that follows.  Then another line after the if block to separate the user ID check from the code relating to the getimagesize call.  This is called paragraphing, and it breaks your function into smaller segments that are easier to read and process.

$check = getimagesize($file);
if($check == false) {
    return false;
}

This is the security portion of your code.  It verifies that the file is something that getimagesize would consider to be an image.  You should probably comment this, as it is rather important in the context of this function.  It's also not immediately obvious that it is security related.  The more common interpretation would be that you are failing here purely because you can't get the size information.

I might call $check $image_data instead.  That would be clearer about what is being returned.

$width = $check[0];
$height = $check[1];

Technically speaking, this is unnecessary.  You only use those values once each and could just use them rather than reassigning them.  However, this does make it considerably clearer what the code is doing.

if(strlen($file) < $maxbytes) {

This is unlikely to be doing what you want.  Presumably you want to check if the image size is less than $maxbytes.  But what this actually does is check that the file name is less than $maxbytes.

        $q->bindParam(':user_id', $user_id);

This is binding $user_id as a string.  If $user_id is numeric, you may be better off telling it so.

Security Issues

As I said earlier, you are checking that $file is an image with the getimagesize function.  Unfortunately though, this might not work.  The problem is that in PHP $file can be either a local file or a remote file.  If it's a local file, then this should be fine so long as the file doesn't change from under you.  Since it's local, hopefully you can control that.

If it's a remote file, then someone else can answer the getimagesize with one file and then return a different file to the fopen.  They control the file, so the first access can be to a nice image and the second access to a dangerous file.  So if this function is actually doing the upload, because you are passing it a URL, then it is insecure.  You should get the file before doing the getimagesize (or do getimagesize twice:  once before and once after).  That way you can ensure that the getimagesize file is the same as the fopen file.

You can also use the filesize function to check the file size of a local file against $maxbytes.  That may not work with a remote file.

Performance

This approach does put more pressure on the database.  You are storing static image content in the database.  It's not clear that you need to do this.  It would generally be easier to store the image on your server and supply it from there.  If you have multiple servers, you could designate one to hold the content.  Or you can use a service like Amazon's S3 to hold your images and load them from there.

It's also unclear how you are going to display the image, but it will certainly require reading the image into memory from the database.  That can stomp over things like the query cache, displacing smaller, more cacheable content.

Display Issues

There are other issues that may impact performance and security based on how you display the image.  Rather than try to guess at the specifics of your method, I'll leave that to a future code review.  But you should be aware that there are additional issues that may arise depending on exactly how you display the image.  Since it is untrusted user data, this could include a security hole that is not visible from just this perspective.  We really need to know the whole sequence to evaluate it.

More context makes it easier to evaluate code.  Some problems may only appear in the interaction of two systems.  Or something may be an irrelevant comment because it's handled outside the code that we can see.


Getting a set of subscribers from a subscriberMap

private <E extends Event> void checkSubscriberMap(Class<E> type)

This method checks nothing. It ensures that there's a non-null value. Or it fixes or prepares something.

Note that you're using both contains and get every time. I guess, a method like

private <E extends Event> Set<E> safeGet(Class<E> type) {
   Set<E> result =
           (Set<Subscriber<E>>) (Object) subscriberMap.get(type);
   if (result == null) {
        result = new HashSet<>();
        subscriberMap.put(type, result);
   }
   return result;
}

would be better.

Consider using Guava's Multimap as it's been solved there.

@SuppressWarnings("unchecked")
private <E extends Event> Set<Subscriber<E>> getSubscribers(E event)
{
    return (Set<Subscriber<E>>) (Object) getSubscribers(event.getClass());
}

I'm afraid, that's right. The ugly double cast is needed as there's no way to tell the compiler that it works. Maybe the intermediate cast could be (non-generic) (Set).

  Assuming nobody uses reflection

If somebody does, that's not your fault.

What you did is similar in idea to the MutableClassToInstanceMap, except that you need Set<Subscriber<E>> instead of E itself and therefore you can't use type.cast(object) and have to resolve to an unchecked cast.


Executive summary

Passing by const is the fastest for Delphi string types.

Details

function myfunction(data: string): boolean;

  Slow since the data must be copied to another location in memory and passed to myfunction

That's not what happens. In fact the caller does nothing more than pass the string variable, stored as a pointer, to the function. What happens in myfunction is that the reference count  to the string is incremented on entry and decremented on exit. This requires an implicit try/finally to be written into the code to ensure that the decrement happens in case of exceptions. The reference counting code and the try/finally consume time.

Note that the string contents are not copied at all because Delphi strings are optimised to use copy-on-write. You only pay the price of copying them if you modify the string.

function myfunction(var data: string): boolean;

  Faster since a pointer to the original data is passed to the function and data is never copied

This is pretty much equivalent to the previous by value code above. The parameter (i.e. the pointer to the string) is passed by reference rather than value, but otherwise there are no differences.

function myfunction(const data: string): boolean;

And now we come to the winner. Since the function is not allowed to modify the contents of the string, the compiler can omit the reference counting code and the try/finally. So this is the fastest of all.


Keeping the average user from opening two copies of my program

I suggest you to use resource based locking. Consider the following:

your application uses well known TCP/UDP port. Only single process can bind it.
your application uses some configuration/database/whatever files in predefined places. flock them. Same stands for pid files under /var/run.

It is still possible to separate resources with chroot or containers. But if nothing is shared are there any benefits in forced locking?

  I'd like to keep mid-average users from being able to open more than one copy of my program at a time.

I guess mid-average users won't use network namespaces, chroots or containers. If they will - I bet they have the reasones so let them do the thing.


Getting a string from a range of possible paths

A few points:

your isString function isn't exactly checking if it's a string, as it's also returning false if not. The typeof check can be simplified to R.is(String)
It's probably better to push all the inputs to the edge of the logic, in this case making paths an argument too. Just splits out our logic an our inputs a bit better.
Instead of wrapping each path in R.path, you can make a function which turns all paths into path functions
For applying the list of path functions to the object, we can use R.juxt

Possible refactoring:

const isString = R.is(String)
const makePaths = R.map(R.path)

const extractStringFor = (paths) =>
  R.compose(
    R.defaultTo(false),
    R.find(isString),
    R.juxt(makePaths(paths))
  )

const firstObject = { description: 'some random description' };
const secondObject = { description: { text: 'some description within text' } };
const thirdObject = { foo: 'bar' };

const paths = [['description'], ['description', 'text']]
const extractString = extractStringFor(paths)

extractString(firstObject), // 'some random description'
extractString(secondObject), // 'some description within text'
extractString(thirdObject) // false

caveat: This runs all paths against each object, and then find the match that's a string. That could be optimised though, potentially with R.takeWhile/R.reduceWhile or something.


Comparing two arrays by index in python in a cleaner way

Don't use the loop-switch antipattern
If you have three different things that have to be done in order, just write them in that order. Don't put a loop around them with if-statements inside to check what has to be done that iteration; loops are for doing the same task over and over. What you are doing has a name: it is the loop-switch antipattern. Instead, just write:
#get data from dict and build first array
datadict={ 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], }

#get data from dict and build second array
datadict={ 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], }

#we now compare the arrays
...

I assume that's not the real code. If each of the three tasks is of course much longer than what you wrote, then it helps to put them in functions.
Split the problem up into smaller sections
It always helps to break up a problem into smaller sections, and for example you can then handle each sub-problem in a separate function. In this case, looping over the arrays can be split from deciding whether or not to keep a value. So:
keep_within_fifty_percent(a, b):
    fiftypercent = a // 2
    lower = a - fiftypercent
    upper = a + fiftypercent

    if b in range(lower, upper):
        return b;
    else:
        return 0

...

#we now compare the arrays
if len(array1) != len(array2):
    # handle error here
    ...

array3 = [keep_within_fifty_percent(a, b) for a, b in zip(array1, array2)]
print("final array: ", array3)


Registration and Login: Best way to separate responsibilities

As I read the code, it seems that what the Register method does is control the business flow as defined in the specifications.

Since all it does (at least as it is written here) is delegate the actual actions to other methods, I don't think 'it does too much' - its single responsibility is to control the flow of the registration process.

To answer your concerns about future maintenance, I see two possible kinds of new features - features that should affect all the service consumers, and features that affect only a single (or part) of the consumers, but not all.

In the first case - there is no problem - do your change in the code, and it will affect all consumers (if you move the code to the controllers that won't be true, since you'd need to change all the controllers...)

In the second case, it should be easy enough to create a new register method for that use case. Since all it does is delegate, the new method itself will be just as simple as the old one, with maybe a delegation to a new method, something like this:

public SignInStatus RegisterAsAdmin(UserRegistration data) {
    authService.SignOut();
    var result = userService.CreateUser(data); // User and profile....
    if (result.Succeeded) {
        result = userService.MakeAdmin();
    }
    if (result.Succeeded) {
        communicationService.SendWelcomeEmail(data);
        customerService.MergeSessionCustomerWithUserCustomer();
    }
    return authService.Login(data);
}

Then connect the relevant consumers to the new service.


Which solution is good to generate a list without None results from a function?

You can use an intermediate generator function:

[y for y in (complicated_function(x) for x in <my_iterable>) if y is not None]

An alternative is changing complicated_function to become a generator that accepts an iterable, instead of a pure function:

def complicated_function(iterable):
    for x in iterable:
        if x < 0:
            yield "a"
        elif x == 3.6:
            yield "b"
        elif x == 4:
            continue
        elif x > 10:
            yield "c"
        else:
            yield "d"

and then: list(complicated_function(<my_iterable>))


Some quick shots at the code

by retrieving the ReCaptchaLocationInclude property an ArgumentNullException is thrown, because you didn't initialize the ExtraClasses property. I would also like to suggest changing this property from autoimplemented to a normal one, so you can validate any set value.
bool passedReCaptcha = false; is not really a good name here. so I wouldn't use this variable at all. Instead I would replace this

if (reCaptchaResult.IndexOf("\"success\": true") > 0)
    passedReCaptcha = true;

with

    return (reCaptchaResult.IndexOf("\"success\": true") > 0);

and for the IDE's love add a return false; at the end of the method. If you don't want to do this, it is fine too, but you should replace the former if with passedReCaptcha = (reCaptchaResult.IndexOf("\"success\": true") > 0);


First of all, please remove all those semicolons. In Python, semicolons and newlines are two ways of indicating the end of a statement. Putting them both there is redundant.

Speaking of newlines, you should probably put one after your imports as a separator and probably another one between your len=10 and width=5. An interesting read is PEP 8, the official Python style guide.

As long as you're changing len=10 anyway, it's generally considered bad practice to define a variable with the same name as a built-in function because it masks the built-in. You use a full word for width; maybe it would be better to do the same for length.

There are some other spacing things I don't like. I would put some spaces around your operators, for example, and after the commas when passing arguments to xrange() and when creating your lists.

Now that we're done with style changes, on to the logic part.

I see some unnecessary +1s in your code. For example, your outer loop uses for i in xrange(1, width+1), yet the only place where i is used is y_curr=i-1. If you're just going to subtract 1 from it anyway, why add 1 to it in the first place? You can keep it simply for y_curr in xrange(width):.

Similarly, your second inner loop can be simplified as:

for j in xrange(len + 1):
    pts.append([len - j, y_curr])

You may notice now that your inner for loops are very similar. You can then simplify your code a little like this:

for y_curr in xrange(width):
    for j in xrange(len + 1):
        if y_curr % 2 == 0:
            pts.append((j, y_curr))
        else:
            pts.append((len - j, y_curr))

or even:

for y_curr in xrange(width):
    for j in xrange(len + 1):
        pts.append((j if y_curr % 2 == 0 else len - j, y_curr))

And if you're in the mood, you could use a list comprehension:

pts = [(j if y_curr % 2 == 0 else len - j, y_curr) for y_curr in xrange(width) for j in xrange(len + 1)]

though I don't recommend that because it is not at all readable.

I also decided to change to using tuples instead of lists. This is because the immutable nature of tuples makes them generally more efficient than lists. In addition, you probably noticed that I've used only one argument to xrange() in several places. When that is done, it assumes that the starting value is 0 and the stop is the supplied argument. This is the desired behavior in most cases, including yours.

I'm not sure why you're using NumPy here. You can do this very simply with standard Python:

plt.plot(*zip(*pts))

You could even keep separate lists in the first place:

x = []
y = []
for y_curr in xrange(width):
    for j in xrange(len + 1):
        x.append(j if y_curr % 2 == 0 else len - j)
        y.append(y_curr)

plt.plot(x, y)


Question of Completeness

Yes, your code covers all Unicode characters, including the supplementary characters U+10000 to U+10FFFF, because you "inherit" that functionality from the way such characters would be stored in Java's String class:

  Unicode Character Representations

  The char data type (and therefore the value that a Character object
  encapsulates) are based on the original Unicode specification, which
  defined characters as fixed-width 16-bit entities. The Unicode
  Standard has since been changed to allow for characters whose
  representation requires more than 16 bits. The range of legal code
  points is now U+0000 to U+10FFFF, known as Unicode scalar value.
  (Refer to the definition of the U+n notation in the Unicode Standard.)

  The set of characters from U+0000 to U+FFFF is sometimes referred to
  as the Basic Multilingual Plane (BMP). Characters whose code points
  are greater than U+FFFF are called supplementary characters. The Java
  platform uses the UTF-16 representation in char arrays and in the
  String and StringBuffer classes. In this representation, supplementary
  characters are represented as a pair of char values, the first from
  the high-surrogates range, (\uD800-\uDBFF), the second from the
  low-surrogates range (\uDC00-\uDFFF).

  A char value, therefore, represents Basic Multilingual Plane (BMP)
  code points, including the surrogate code points, or code units of the
  UTF-16 encoding. An int value represents all Unicode code points,
  including supplementary code points. […]

Reinventing the Wheel

Since you did not tag your question as reinventing-the-wheel, I'm obligated to mention that you could accomplish the task more simply using the built-in support for charsets.

private static final Charset UTF_16 = Charset.forName("UTF-16BE");

public static byte[] Encode(byte[] ByteArray , int offset ,String str) {
    byte[] bytes = str.getBytes(UTF_16);
    System.arraycopy(bytes, 0, ByteArray, offset, bytes.length);
    return ByteArray;
}

public static String Decode(byte[] ByteArray ,int len) {
    return new String(ByteArray, 0, 2 * len, UTF_16);
}


Generate all combinations of length N through M

Let's start with the core premise of what you're trying to do, which is program in C++ without the standard library for "learning purposes". The problem with this is that you're not learning much useful, really. It's a lot like if you were trying to learn to drive a car by manually doing the timing of the crankshaft and spark plugs... a neat trick, sure, but not one that's ever going to be of any practical use when actually driving a car.

Put another way, you can "learn" C++ by re-implementing std::strlen() (poorly)... but your time would be better spent learning to use the actual std::strlen() and all the other wonderful tools in the standard library, for two reasons:

Because any actual, non-trivial program you ever write will have to use those tools, so you might as well learn them.
Because you will learn more about being an actual good C++ programmer by observing how things are done in the standard library... which is a fantastically well-designed library (mostly), designed by the best C++ programmers in the world.

It's also worth noting that you are using the standard library. There is no such thing as "bare bones" in C or C++ - a truly "bare bones" C or C++ program would do literally nothing useful, and be optimized right down to an empty main() function. I'm not even talking about the use of std::ofstream (although that does make the point). I'm talking about all the hidden stuff you're using. Like, when you use new, you're using the global operator new in header <new>. You're also pulling in whatever new handler has been installed by the runtime, plus the exceptions library by virtue of std::bad_alloc, and more. And all that isn't even to mention all the stuff in the runtime that gets initialized before main().

What I'm saying is that "bare bones" C++ is a fantasy. There's no such thing. C++ (like C, and like everything else) needs a runtime - whether you use the standard one or write one yourself (such as for a very limited embedded system). You are using the standard library. You just don't realize it.

So trying to learn C++ without using the standard library is:

not teaching you how to actually write C++
not helping familiarize you with the tools that would actually be useful in writing real C++ programs; and
misleading you into thinking you're doing everything on your own like a bad-ass hacker, when in reality the standard library is secretly holding your hand the entire time.

But alright, you've chosen to do this without visibly using any standard library components, so let's do it.

void gen(std::ofstream& f_out, char* word, int pos=0)

This isn't really part of the meat of what you're doing, but it is part of real C++ programming. Taking any specific stream type (like ofstream) by reference is almost never the right thing to do. What you want to take here is std::ostream&. That allows this function to work with file streams, but also std::cout, string streams, network streams, and anything else.

int length=0;
for(int i=0; word[++i]; length++);

These two lines are std::strlen(). They really should be separated out into its own function. One function; one job. Right now gen() not only generates the next word, it also checks the length of the word - that's at least two jobs. Checking the word length is something useful on its own, so it should be separated into its own function.

However....

There is a questionable design decision here to have the generating function check the string length each time its called. There are two issues with that:

it requires the word to be null-terminated; and
whoever calls the function already knows how long the word is, so the function is just redoing work unnecessarily.

In modern C++ it is increasingly preferred to pass array data along with its size in some way - either as a pair of pointers, or a pointer and a size. This is exactly why std::string_view was added to C++17, and why std::span is coming in C++20.

If gen() took a pointer and a size, then the first few lines of the function could be:

void gen(std::ofstream& f_out, char* const word, int const length, int pos = 0)
{
    if(pos == length) return;
    while(word[pos]<='z') {
        // ...

That avoids the need to check the length and allows you to take non-null-terminated strings. It make the function faster and more flexible to use.

if(pos==length) f_out << word << std::endl;

Never use std::endl. It is basically always wrong. In this case, it should be:

if(pos==length) f_out << word << '\n';

But if you've refactored the function to take a pointer and a size (and thus, non-null-terminated strings), you would have to use:

if(pos==length) f_out.write(word, length) << '\n';

or:

if(pos==length) f_out.write(word, length).put('\n');

Down to main().

You never confirm that the file actually opened. You can either test is_open(), the fail bit, or you can set stream exceptions before trying to open it.

char* word;
int min=2, max=4;

Don't declare variables until they're needed. word is not needed until 5 lines later... and technically not even then.
Don't declare multiple variables on a single line. That causes all kinds of headaches with syntactic quirks, and makes it harder to see where variables come from.

I would also recommend that min and max be constexpr. You should also assert that max >= min, for safety.

If we remove word (because it's unnecessary), your main loop looks like this:

for(int i=min; i<=max; i++) {
    char* buffor = new char[i+1];
    for(int x=0; x<i; buffor[x]='a',  x++);
    buffor[i]='\0';
    gen(f_out, buffor);
    delete [] buffor;
}

If you refactor gen() to take a pointer and length, rather than just an implicitly null-terminated pointer, this simplifies to:

for(int i=min; i<=max; i++) {
    char* buffor = new char[i];
    for(int x=0; x<i; buffor[x]='a',  x++);
    gen(f_out, buffor, i);
    delete [] buffor;
}

The inner for loop is just std::fill_n() or std::memset(). It should be moved into its own function for clarity.

But there's a bigger issue here, and that's exception safety. If any exceptions are thrown after the allocation of buffor, the memory will leak.

There are multiple ways to fix this situation. The easiest way is to simply declare everything between the allocation and deallocation to be noexcept. Easy, but not really a good solution because noexcept implies "cannot fail"... and any output can fail.

A really ugly solution is to do this:

for(int i=min; i<=max; i++) {
    char* buffor = new char[i+1];
    try
    {
        for(int x=0; x<i; buffor[x]='a',  x++);
        gen(f_out, buffor, i);
        delete [] buffor;
    }
    catch (...)
    {
        delete [] buffor;
        throw;
    }
}

But the best solution is to create a RAII class for your buffer. Something like:

class buffer
{
public:
    explicit buffer(int size) :
        ptr_{new char[size]}
        size_{size}
    {}

    ~buffer()
    {
        if (ptr_)
            delete[] ptr_;
    }

    // Move ops are handy:
    buffer(buffer&& other) noexcept :
        ptr_{other.ptr_},
        size_{other.size_}
    {
        other.ptr_ = nullptr;
        other.size_ = 0;
    }

    buffer& operator=(buffer&& other) noexcept
    {
        // no std::swap, so we have to do this dance:

        auto const temp_ptr = ptr_;
        ptr_= other.ptr_;
        other.ptr_ = temp_ptr;

        auto const temp_size = size_;
        size_ = other.size_;
        other.size_ = temp_size

        return *this;
    }

    // Observers:
    auto pointer() const noexcept { return ptr_; }
    auto size() const noexcept { return size_; }

    // No copying.
    buffer(buffer const&) = delete;
    buffer& operator=(buffer const&) = delete;

private:
    char* ptr_ = nullptr;
    int size_ = 0;
};

That simplifies your main loop to:

for(int i=min; i<=max; i++) {
    auto buffor = buffer{i};
    fill_n(buffor.pointer(), i, 'a'); // for(int x=0; x<i; buffor.pointer()[x]='a',  x++);
    gen(f_out, buffor.pointer(), i);
}

and at the same time, gives you proper exception safety.

But here's an interesting observation. There is no point in allocating a buffer for each size between min and max. Why not just allocate a single buffer of max size, and reuse it?

auto buffor = buffer{max};
for(int i=min; i<=max; i++) {
    fill_n(buffor.pointer(), i, 'a');
    gen(f_out, buffor.pointer(), i);
}

That spares you the cost of deallocating and reallocating the buffer multiple times.

f_out.close();
return 0;

Both of these lines are unnecessary.

There are also a few more suggestions I'd make from a design and usability perspective.

The way your code is written, before someone can use gen() they have to prepare the buffer just right. That just makes gen() more difficult to use. It would be easier to use if gen() has a simpler interface, something like:

void gen(std::ostream& out, int min, int max);

and then gen() handled setting up the buffers, and called a helper function to do the actual recursion stuff.

Another thing that would be nice is if you could actually specify the set of characters to use in the generated strings. That would also sidestep a very technical bug in your code: you assume that the characters 'a' through 'z' have contiguous code points... that's not always true.

You could do something like this:

namespace detail_ {
namespace {

constexpr char DEFAULT_CHARS[] = "abcdefghijklmnopqrstuvwxyz";
constexpr auto DEFAULT_CHARS_SIZE = sizeof(DEFAULT_CHARS) - 1;

void gen_impl_(std::ostream& out, char* buffer, int size, char const* chars, int chars_size, int pos = 0)
{
    // algorithm here
}

} // anonymous namepsace
} // namespace detail_

void gen(std::ostream& out, int min, int max, char const* chars, int chars_size)
{
    // verify arguments

    // create the buffer
    for (auto i = min; i <= max; ++i) // could also check that the output stream is still good
    {
        // fill the buffer with the first char, then:
        detail_::gen_impl_(out, buffer, i, chars, chars_size);
    }
}

void gen(std::ostream& out, int min, int max)
{
    gen(out, min, max, detail_::DEFAULT_CHARS, detail_::DEFAULT_CHARS_SIZE);
}

Now I can use gen() like this:

// generate "aa" to "zzzz"
gen(out, 2, 4);

// generate hexadecimal numbers from 0 to FFFF
gen(out, 1, 4, "0123456789ABCDEF", 16);

without worrying about setting up buffers properly.

An even more interesting design would be to use callbacks, rather than having writing to a stream be the only option. For example:

// generate "aa" to "zzzz", and write them to f_out
gen(2, 4, [&f_out](auto ptr, auto size) { f_out.write(ptr, size).put('\n'); });

// generate hexadecimal numbers from 0 to FFFF, and make sure they're all
// valid hex numbers.
auto validate_hex_number(char const* ptr, int size)
{
    auto n = 0u;
    auto res = std::from_chars(ptr, ptr + size, n, 16);
    if (!res.ec)
    {
        if (n > 0xFFFFu || res.ptr != ptr + size)
            res.ec = std::make_error_code(std::errc::invalid_argument);
    }

    if (res.ec)
        throw std::system_error{res.ec};
}

gen(1, 4, "0123456789ABCDEF", 16, &validate_hex_number);

You could even design it so that if the callback returns false, you stop generating. This would be handy for brute force password cracking, for example.

Summary

Avoiding the standard library is a pointless exercise, because you'll end up reimplementing chunks of it anyway. Here you've had to implement crappy versions of std::strlen(), std::fill_n() (or std::memset()), and std::vector<char> (or std::string). There's no real gain from reimplmenting those things; your time would have been better served designing the gen() algorithm better - for example, having it take different character sets, or using a callback.

Use more functions. One function; one job. If you ever see a nested loop, or if a function is more than ~5 lines of functional code (not counting usings, variable declarations, lines with just braces, comments, and so on), that's a sign that it might be possible to break it into simpler functions.
Move work out of loops wherever possible.
Don't throw information away - if you know the size of a buffer before calling a function, there's no need to make the function recalculate it.
Use RAII. If you're writing C++ and you're not using RAII, you're writing garbage C++.


You can do as a decent compiler would: precompute some expressions, and reduce the "strength" of others.
For worse rather than better, most opportunities for this are in the constructor.
Part of the performance of on object depends on its interface - I've included an alternative function that finds the (position of the) next match, if any.
Benchmarking is difficult, micro or not: beware "printing" and use help.

import timeit

class RollingHash:
    '''A rolling hash for a window of constant length into a text,
        both specified at construction.
    '''
    adjust = ord("a") - 1
    alphabet = 26

    def __init__(self, text, size_word):
        '''Set up a rolling hash for a window of size_word into text.'''
        self.text = text
        if len(text) < size_word:
            self.hash = None
            return
        rk = 0
        for c in text[:size_word]:
            rk = rk * self.alphabet + ord(c) - self.adjust
        self.hash = rk
        self.pos = -1
        self.window_start = 0
        self.window_end = size_word
        self.multiplier = RollingHash.alphabet ** (size_word - 1)

    def move_window(self):
        '''Advance window by one position.'''
        if self.window_end < len(self.text):
            # remove left letter from hash value
            self.hash = \
                (self.hash - (ord(self.text[self.window_start])
                              - RollingHash.adjust) * self.multiplier) \
                * RollingHash.alphabet \
                + ord(self.text[self.window_end]) - RollingHash.adjust
            self.window_start += 1
            self.window_end += 1

    def window_text(self):
        '''Return current window text.'''
        return self.text[self.window_start:self.window_end]

    def match(self, other):
        '''Return position of next match, or none.'''
        roll = self.hash
        text = self.text
        # "local copies" may help or hinder readability and performance
        start = self.window_start
        end = self.window_end
        limit = len(self.text)
        result = None
        while end < limit:
            if self.pos < other.hash == roll \
                and other.text == text[start:end] \
                and self.pos < start:
                result = self.pos = start
                break;
            roll = (roll - (ord(text[start])
                            - RollingHash.adjust) * self.multiplier) \
                * RollingHash.alphabet \
                + ord(text[end]) - RollingHash.adjust
            start += 1
            end += 1
        self.window_start = start
        self.window_end = end
        return result

verbose = True

def rabin_karp(word, text):
    '''Print indexes of matches for word in text.'''
    if word == "" or text == "":
        return None
    size_word = len(word)
    if size_word > len(text):
        return None

    rolling_hash = RollingHash(text, size_word)
    word_hash = RollingHash(word, size_word)

    for i in range(len(text) - size_word + 1):
        if rolling_hash.hash == word_hash.hash:
            if rolling_hash.window_text() == word:
                if verbose:
                    print(i)
            else:
                print(rolling_hash.window_text(), '<>', word, "at", i)
        rolling_hash.move_window()
    return 'Pattern length: ', size_word

def karp_rabin(word, text):
    '''Print indexes of matches for word in text.'''
    size_word = len(word)
    if not 0 < size_word <= len(text):
        return None

    rolling_hash = RollingHash(text, size_word)
    word_hash = RollingHash(word, size_word)

    while True:
        position = rolling_hash.match(word_hash)
        if position is None:
            return 'Pattern length: ', size_word
        if verbose:
            print(position)

if __name__ == '__main__':
    text = input("Text: ")
    word = input("Pattern: ")
    print(rabin_karp(word, text))
    print(karp_rabin(word, text))
    verbose = False
    glob = globals()
    # have a look at timeit.Timer.repeat() and autorange(), too
    print(timeit.timeit('results = rabin_karp(word, text)',
                        globals=glob, number=9999))
    print(timeit.timeit('results = karp_rabin(word, text)',
                        globals=glob, number=9999))


Parsing a string with named sections and a key-value pair on each line

First, I'd like to point out that if are you storing this from your program and reading it back from a file later, you'd be better off Serializing it. But since you're being given this file, let's move on.

Infinite Loops

It's generally discouraged to use while(true) loops. It's not particularly bad (in fact it's sometimes better), but it's always best to look for an alternative for readability sake. Instead, let's use while ((line = reader.readLine()) != null).

Initializing variables as null

I also see you initialized a few variables as null, but that isn't necessary since it's implied for classes. (Also note primitive variables are implied as 0 during initialization).

Using the output format to your advantage

You also have a cut variable that gets the index of the tokens, and then skips the line if it's blank. However, we know that the output is always going to be grouped into three lines, and we always know what those lines are going to be. We also know the data you really want is going to be the first three characters for the name, and everything after the first five characters for the tokens. Let's use that and make everything clear!

Putting it all together

String response = restTemplate.getForObject(url, String.class);
BufferedReader reader = new BufferedReader(new StringReader(response));
NameMetrics current;
Map<String, String> metricsHolder;
List<NameMetrics> result = new ArrayList<>();

String name, load, peak;

String nameline;
while ((nameline = reader.readLine()) != null) {
    name = nameLine.substring(0, 3);
    load = reader.readLine().substring(5);
    peak = reader.readLine().substring(5);
    reader.readline(); //eat empty line

    current = new NameMetrics();
    metricsHolder = new HashMap<>();    //No need to repeat the stuff inside the diamond operator
    metricsHolder.put("Load", load);
    metricsHolder.put("Peak", peak);

    current.setName(name);
    current.setMetrics(metricsHolder);
    result.add(current);
}

Handling varying keys and names

When there are a variable number of keys, we still know that they're all generally in the same format of the name followed dashes, then a list of key:value lines, then a blank line. We can still use this to our advantage as follows:

String name;
String[] mapValues;

final int KEY = 0, VALUE = 1;
String nameline, keyLine;
while ((nameline = reader.readLine().trim()) != null) {    //Loop until the end of the file
    name = nameLine.substring(0, nameLine.indexOf("-") + 1); //Plus because substring excludes last index

    metricsHolder = new HashMap<>();    //No need to repeat the stuff inside the diamond operator
    while (!(keyLine = reader.readLine().trim()).isEmpty()) {   //Loop until block ends with an empty line
        mapValues = reader.readLine().split(":");   //Split key:value format
        metricsHolder.put(mapValues[KEY], mapValues[VALUE]);
    }

    current = new NameMetrics();
    current.setName(name);
    current.setMetrics(metricsHolder);
    result.add(current);
}


Change non-diagonal surrounding elements in a 2-D array

Copying the array
You are over-complicating the array copy.  Array.clone will copy the objects of the array (but not the object's objects).  Using it on array of objects might be problematical, but an array of ints will be fine.
new = a.map(&:clone)  # clone each row, return as an array

This line also removes the need of cleaning up your nils at the end
Additional Thoughts
While the logic is largely fine, stylistically your loops could be a little more idiomatic.
Unless you are using older ruby, you should tend to prefer .each.with_index over each_with_index.  They do the same thing but .with_index is a little more functional (programming).
Secondly, in general, try to chose better variable names than m, n, x, y.  You have comments describing what they are, but with better variable names, the code becomes self documenting.  (I've used ix_row and ix_col, but that's my personal naming convention for indexes; feel free to change it, just make sure it's purpose is obvious.)
Finally, you are overthinking your boundary checks as well.  All you need to do is simply check the index.
new.each.with_index do |row, ix_row|
  row.each.with_index do |cell, ix_col|
    if cell == 1
      new[ix_row][ix_col+1] = 1 unless ix_col+1 >= row.length #copy right
      new[ix_row+1][ix_col] = 1 unless ix_row+1 >= new.length # copy down
      new[ix_row][ix_col-1] = 1 unless ix_col.zero? # copy left
      new[ix_row-1][ix_col] = 1 unless ix_row.zero? #copy up
    end
  end
end


VBA - If value in sheet1 found in sheet2, then delete data from sheet2

My example you'll find below is based on most often working with large datasets and opts for speed in data handling. You didn't state the size of your Issues and Exclusions, so I worked with a large dataset in mind.

A couple quick things to get out of the way because these are good practices to make into consistent habits:

Always use Option Explicit
Avoid a "wall of declarations", plus the very useful other tips on that site
Establish specific object variables for the worksheets, instead of always using Sheets. Further, by only using Sheets you're implying that the code should operate on the currently ActiveWorksheet. This is quite often correct, but will trip you up at some point when you intend something different.

So I make a habit of defining exactly which workbook and worksheet I'm using by initializing variables with fully qualified references.

Dim exclusionsWS As Worksheet
Dim issuesWS As Worksheet
Set exclusionsWS = ThisWorkbook.Sheets("Exclusions")
Set issuesWS = ThisWorkbook.Sheets("Issues")

While I understand your rationale for handling the possible ShowAllData errors, I would much rather be clear about "why" you need to do this. So I'd avoid the On Error Resume Next by making it clear I'm checking for a possible AutoFilter:

With exclusionsWS
    If (.AutoFilterMode And .FilterMode) Or .FilterMode Then
        .AutoFilter.ShowAllData
    End If
End With
With issuesWS
    If (.AutoFilterMode And .FilterMode) Or .FilterMode Then
        .AutoFilter.ShowAllData
    End If
End With

Next, because there may be a large dataset, I would copy the data on the worksheet into a memory-based array. Working out of memory is MUCH faster than working with the Range object in Excel. Later, the process of checking to see if a value exists in another dataset is perfect for a Dictionary. So we'll loop through all the exclusions and create a dictionary item for each entry.

Dim exclusionData As Variant
exclusionData = exclusionsWS.UsedRange

Dim exclusion As Dictionary
Set exclusion = New Dictionary
Dim i As Long
For i = 2 To lastRow
    If Not exclusionData(i, 10) = vbNullString Then
        exclusion.Add exclusionData(i, 10), i
    End If
Next i

After that, my example shows checking each Issue against the Dictionary and clearing out any excluded Issues. In order to copy the remaining issues back to the worksheet, we have to clear ALL the issues first, then copy the array data to the worksheet.

Here's the whole routine in a single view:

Option Explicit

Public Sub RemoveExclusions()
    Dim exclusionsWS As Worksheet
    Dim issuesWS As Worksheet
    Set exclusionsWS = ThisWorkbook.Sheets("Exclusions")
    Set issuesWS = ThisWorkbook.Sheets("Issues")
    With exclusionsWS
        If (.AutoFilterMode And .FilterMode) Or .FilterMode Then
            .AutoFilter.ShowAllData
        End If
    End With
    With issuesWS
        If (.AutoFilterMode And .FilterMode) Or .FilterMode Then
            .AutoFilter.ShowAllData
        End If
    End With

    Dim lastRow As Long
    With exclusionsWS
        lastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
    End With

    '--- move the exclusion data to a memory-based array
    '    for processing into a dictionary
    Dim exclusionData As Variant
    exclusionData = exclusionsWS.UsedRange

    Dim exclusion As Dictionary
    Set exclusion = New Dictionary
    Dim i As Long
    For i = 2 To lastRow
        If Not exclusionData(i, 10) = vbNullString Then
            exclusion.Add exclusionData(i, 10), i
        End If
    Next i

    '--- move all the issues into a memory-based array also
    '    and clear the data from exclusion matches
    Dim issuesData As Variant
    Dim excludedCount As Long
    issuesData = issuesWS.UsedRange
    For i = 2 To UBound(issuesData, 1)
        If exclusion.Exists(issuesData(i, 10)) Then
            issuesData(i, 10) = vbNullString
            excludedCount = excludedCount + 1
        End If
    Next i

    '--- now collapse all the empty rows by copying the remaining
    '    issues into a new array, then copy the array back to the
    '    worksheet
    Dim remainingIssues As Variant
    ReDim remainingIssues(1 To UBound(issuesData, 1) - excludedCount, _
                          1 To UBound(issuesData, 2))
    Dim newIssue As Long
    newIssue = 1
    Dim j As Long
    For i = 1 To UBound(issuesData, 1)
        If Not issuesData(i, 10) = vbNullString Then
            For j = 1 To UBound(issuesData, 2)
                remainingIssues(newIssue, j) = issuesData(i, j)
            Next j
            newIssue = newIssue + 1
        End If
    Next i
    issuesWS.UsedRange.ClearContents
    issuesWS.Range("A1").Resize(UBound(remainingIssues, 1), _
                                UBound(remainingIssues, 2)) = remainingIssues
End Sub


When you've split a list into a smaller and a bigger halves, after sorting them  the elements in the first half are all still  smaller than all the elements in the second.

So, merging such sorted halves is just positional concatenation, i.e. putting the two halves beside each other so that in the resulting sequence, first go the elements of the first half (sorted), and then the second.

There's no need to compare the elements values in your merge, results of such comparisons are known in advance, predetermined by the  partition stage.

This is the essence of quicksort - partition by value, necessarily putting some effort into doing that, and then, after sorting the halves, join positionally, easily and simply.

The merge sort works the other way - it partitions the list simply, by position; and spends more effort merging the sorted parts, according to the elements' values:

                 mergesort             quicksort

partition        positional            by value

merge            by value              positional

Splitting into three parts is a good optimization, but changes nothing regarding the above.