What's the most idiomatic way to call a function an arbitrary number of times with the previous result?

I general, I agree with what mavnn said in his answer, I just think the function can be written in a simpler way:

let rec performOptimizations ast =
    let optimized = optimizeAst ast
    if ast = optimized then
        ast
    else
        performOptimizations optimized

This method also sounds like a good candidate for making it more generic, something like:

let rec doWhileNotSame seed getNextValue =
    let nextValue = getNextValue seed
    if seed = nextValue then
        seed
    else
        doWhileNotSame nextValue getNextValue


Chunking a list into separate lists of 5, and then iterating through each

Separate the mechanics and the semantics of the code. Here's my very well used Batch<T> extension method on IEnumerable<T>:

public static class EnumerableExtensions
{
    public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> enumerable, int batchSize)
    {
        if (enumerable == null) throw new ArgumentNullException(nameof(enumerable));
        if (batchSize <= 0) throw new ArgumentOutOfRangeException(nameof(batchSize));
        return enumerable.BatchCore(batchSize);
    }

    private static IEnumerable<IEnumerable<T>> BatchCore<T>(this IEnumerable<T> enumerable, int batchSize)
    {
        var c = 0;
        var batch = new List<T>();
        foreach (var item in enumerable)
        {
            batch.Add(item);
            if (++c % batchSize == 0)
            {
                yield return batch;
                batch = new List<T>();
            }
        }
        if (batch.Count != 0)
        {
            yield return batch;
        }
    }
}

Now that's the batching taken care of, we need to sort out the loop. What would we like it to look like?

foreach (var batch in latLongList.Batch(5))
{
    SetupCaseFileUpdateTransaction(transactionCode, fileType, fileNumber, commentText1, commentText2, transactionDate, username, password);
    SetWebServiceBatch(batch.ToList());
    CallWebService();
}

Great! The main method is now much shorter and easier to reason about. However, we've just moved the problem elsewhere. So let's look at the SetWebServiceBatch piece:

// Typed directly into CR so may not compile/be 100% right.
private void SetWebServiceBatch(List<LatLongEntry> latLongs)
{
    if(latLongs.Count > 5) throw new ArgumentException(nameof(latLongs));
    for (var i = 0; i < latLongs.Count; i++)
    {
        if (i < 3)
        {
            SetCode(1 + i * 2, latLongs[i].Latitude);
            SetCode(2 + i * 2, latLongs[i].Longitude);
        }
        else
        {
            SetMisc(1 + (i - 3) * 2, latLongs[i].Latitude);
            SetMisc(2 + (i - 3) * 2, latLongs[i].Longitude);
        }
    }
}

Note that I've assumed that skipping SetCode(3 was a mistake and that you want to set code 1,2,3,4,5,6 and set misc 1,2,3,4. If that's not the case you'll need to slightly modify the for loop to take into account this discontinuity.


Dynamically generated controls based on data from dictionary

This will work, but it may be hard to scale.  At a minimum, I'd create a separate class for the work you're doing in the enumerate loop so that the dialog class is only concerned with populating a widget list and the details of what the widgets look like internally are handled in a class that just pops out book widgets - that will make for cleaner code and easier maintenance.

The more 'modern' way to do this is some variant on the MVC (Model-View-Controller) or MVVM (Model -view - viewmodel) patterns.  The basic idea is the same -  create a factory which produces display widgets for the items in a list of some kind. The main difference its that the MVVM pattern encourages you to split out the different aspects of the problem -- managing the contents of the list, displaying parts of the list, and interactng with the list items -- into distinct parts of the code (the 'model', the 'view' and the 'viewmodel' or 'controller') respectively.  (There's a whole lot of programmer-on-programmer controversy about MVC vs MVVM - background here.)

In this example, going with an MV* pattern offers  facilities like filtering a list ('show only books from 2013'), enabling/disabling list items ('gray out the books over $50') without lots of tedious looping codes.  Plus you could potentially do things like design your widgets in the QT designer for better layout, etc without touching the code directly.

All this lets you decouple the UI functionality (views, filters, appearance) from the data.  As your lists get bigger, and the need to manage their contents gets more complex, this is a big help in staying sane.

Yasin from TAO has nice, detailed Youtube tutorial on this approach.


First of all, this is a very nicely written code.

Before writing about the cur implementation, a few notes:

I do not think n and m should be in main. It creates shadowing in the function.
I added type annotation to the return value of the function. Since it's a generator it should be: Iterator[List[int]].

So you said you do not like the way cur is implemented in your code, I thought of a way to take it out of the function declaration.
I created a sub function that is recursive taken out the cur variable. This is how it turned out:

def permutations_with_replacement(n: int, m: int) -> Iterator[List[int]]:
    cur = []

    def permutations_with_replacement_rec(n_rec: int, m_rec: int) -> Iterator[List[int]]:
        nonlocal cur

        if n_rec == 0:
            yield cur
            return

        for i in range(1, m_rec + 1):
            cur = cur + [i]
            yield from permutations_with_replacement_rec(n_rec - 1, m_rec)
            cur.pop()

    yield from permutations_with_replacement_rec(n, m)

Now notice that I needed to add a pop to the variable since now it keeps the elements after the call to the function.
Also I needed to use the nonlocal term so the function will know the cur variable.

The full code (with tests):

from itertools import product
from typing import Iterator, List

from sys import setrecursionlimit
setrecursionlimit(10 ** 9)

def permutations_with_replacement(n: int, m: int) -> Iterator[List[int]]:
    cur = []

    def permutations_with_replacement_rec(n_rec: int, m_rec: int) -> Iterator[List[int]]:
        nonlocal cur

        if n_rec == 0:
            yield cur
            return

        for i in range(1, m_rec + 1):
            cur = cur + [i]
            yield from permutations_with_replacement_rec(n_rec - 1, m_rec)
            cur.pop()

    yield from permutations_with_replacement_rec(n, m)

def test_permutations_with_replacement():
    n = 3
    m = 4
    assert set(product(list(range(1, m + 1)), repeat=n)) == set(tuple(i) for i in permutations_with_replacement(n, m))

def main():
    n = int(input("Please enter 'N': "))
    m = int(input("Please enter 'M': "))

    for i in permutations_with_replacement(n, m):
        print(*i)

if __name__ == '__main__':
    main()


As 200 said, the predicate should be first. Think of filter, takeWhile, dropWhile and similar functions. They take the predicate first.

Also, it's usually a good idea to get rid of arguments that get repeated in every recursive call. GHC should take care of that, but we can help it a little bit:

quicksort :: (a -> a -> Bool) -> [a] -> [a]
quicksort pf = go
  where
    go [] = []
    go (x:xs) = go left ++ [x] ++ go right
      where (left, right) = partition (comp x) xs

However, we're sorting. Therefore calling the comparison function a  predicate is a misnomer. A predicate is a function a -> Bool, whereas a -> a -> Bool is a comparison. But a -> a -> Bool doesn't convey its meaning by its type. Do we return True if the first shall come first in the sorted arrangement? Or do we return False? Will quickSort (>) sort ascending or descending?

Those questions are easier to answer if we use a -> a -> Ord instead. This signature follows compare's, so we have a pretty good feeling what x `compare` y = LT means, namely that x < y holds true.

If we keep that in mind, we can write the following variants:

quicksortBy :: (a -> a -> Ord) -> [a] ->  [a]
quicksortBy comp = go
  where
    go []     = []
    go (x:xs) = go lesser ++ (x : equal) ++ go greater
      where
        (lesser, equal, greater) = partitionOrd (`comp` x) xs

quicksort :: Ord a => [a] -> [a]
quicksort = quicksortBy compare

The definition of partitionOrd :: (a -> Ord) -> [a] -> ([a], [a], [a]) is left as an exercise. Other than that, well done. Keep in mind that this isn't really Quicksort, though.


Using the RAII design pattern in VBA to automatically restore settings

I would point out that the naming convention is inconsistent -- we have Activate and a Shutdown --- they don't say the same thing to me. I'd expect corresponding actions to have names like Activate -> Deactivate, Enable -> Disable, Startup -> Shutdown. Given the nature of the class, Enable/Disable pair seems the best suited for what your class is going to do, since it's basically toggling an application level state.

Your Shutdown has an On Error Resume Next but says nothing if it was successful. I would at least expect the procedure to exit with something like ShutDown = (Err.Number = 0) so that the calling client can at least know there was a clean exit or not. However, I'm more inclined to encourage to rethink whether you really want a Resume Next there, because you are dealing with altering the application's state, so it is crucial to know that the alterations were successful so that the clients can proceed with the assumption that they are in the correct state.

The other thing that occurs to me is that you probably don't actually need the methods at all. You only need the Class_Initialize and Class_Terminate. Your calling code then becomes...

Set booster = New ExcelTurboBooster
'Do lot of complicated stuff....
Set booster = Nothing

Look, ma, no methods! In fact, technically you only need the first line. The last line is superficial because when your procedure that instantiate the object exits (even if it exited badly), the instance will go poof and the application state should be reset. The biggest downside of that method, though, is that error handling becomes somehow strange inside the Initialize/Terminate events, so it could be difficult to communicate to your clients there has been a problem.

The downside with the no-method approach is that it totally can't go into a public field of any standard module or maybe long-lived classes either because then they will persist too much longer. One'd have to take discipline to use it only as a local variable inside procedure so that it will be destroyed at the end of the procedure. Otherwise, you've built up a new layer of complication for nothing.


ASP.NET WebAPI `In` Validation Attribute

if (!@in.Any())
{
    throw new ArgumentNullException("in");
}

This won't work the way you expect it.

It should be either C# 6

 if (@in?.Any())

or for previous versions

 if (@in == null || !@in.Any())

return new ValidationResult("" + validationContext.DisplayName + " cant be null");

Why the empty string at the beginning?

One time you do

return new ValidationResult("" + validationContext.DisplayName + " cant be null");

and the other time

return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));

I thought you forgot to use the FormatErrorMessage in the first case but it produces a completely different error message.

Create another method and name it accordignly like FormatNullValueErrorMessage and the other one FormatNotInErrorMessage.

ErrorMessage = "{1} is invalid value.")

I don't think this parameter has any value and is actually very error prone because the user of this attribute has to know that he can use the {1} and what it means. I'd stick to an automatic message about the value not beeing allowed.

private readonly int[] testArray;

I would rename this field to soemthing like _allowedValues. As I first time saw it I thought it's a test code. Reserve the test for tests or really rare cases when there is no better word.

_toTest = Convert.ToInt32(value);

It's not necessary to store the value locally. Pass it as a paramter to the FormatXErrorMessage.


What would be a correct C++ style for function loading file contents?

Here are some of the C-style features of your code:

FILE
fopen
char buf [128]
fclose

I personally liked the answer that was given in @Jamal's link.

std::ifstream fin(fileName);
std::ostringstream oss;

oss << fin.rdbuf();
out = oss.str();

The only problem with this is that it doesn't work well with binary files.
You could make out be a std::vector <char> instead.

std::vector <char> loadFileContents (const std::string &filename)
{
    std::ifstream ifile ;
    ifile.exceptions (std::ifstream::badbit | std::ifstream::failbit) ;

    std::vector <char> vecBuffer ;
    typedef std::vector <char>::size_type size_type ;

    try {
        ifile.open (filename) ;
        ifile.seekg (0, ifile.end) ;
        size_type size = static_cast <size_type> (ifile.tellg ()) ;
        ifile.seekg (0, ifile.beg) ;
        vecBuffer.resize (size) ;
        ifile.read (&vecBuffer [0], size) ;
    }

    catch (std::ios_base::failure &e) {
        std::cerr << e.what () << std::endl ;
    }

    return vecBuffer ;
}

NRVO allows us not to worry about returning the std::vector <char> by value.

If you have access to C++11, then you could do:

std::vector <char> loadFileContents (const std::string &filename)
{
    std::ifstream ifile ;
    ifile.exceptions (std::ifstream::badbit | std::ifstream::failbit) ;

    std::vector <char> vecBuffer ;

    try {
        ifile.open (filename) ;
        std::istreambuf_iterator <char> iter (ifile) ;
        std::istreambuf_iterator <char> eos ;
        vecBuffer = std::move (std::vector <char> (iter, eos)) ;
    }

    catch (std::ios_base::failure &e) {
        std::cerr << e.what () << std::endl ;
    }

    return vecBuffer ;
}

If you want to enter template territory, then you could try this:

template <typename Container>
Container loadFileContents (const std::string &filename)
{
    std::ifstream ifile ;
    ifile.exceptions (std::ifstream::badbit | std::ifstream::failbit) ;

    try {
        ifile.open (filename) ;
        std::istreambuf_iterator <char> iter (ifile) ;
        std::istreambuf_iterator <char> eos ;
        return Container (iter, eos) ;
    }

    catch (std::ios_base::failure &e) {
        std::cerr << e.what () << std::endl ;
    }

    return Container () ;
}

Then in your main, you could do:

int main (void)
{
    std::string strData = loadFileContents <std::string> (FILENAME) ;
    std::vector <char> vecData = loadFileContents <std::vector <char> > (FILENAME) ;

    return 0 ;
}

If we choose to not return the Container, then we could do:

template <typename Container>
void loadFileContents (const std::string &filename, Container &container)
{
    std::ifstream ifile ;
    ifile.exceptions (std::ifstream::badbit | std::ifstream::failbit) ;

    try {
        ifile.open (filename) ;
        std::istreambuf_iterator <char> iter (ifile) ;
        std::istreambuf_iterator <char> eos ;
        container = Container (iter, eos) ;
    }

    catch (std::ios_base::failure &e) {
        std::cerr << e.what () << std::endl ;
    }
}

int main (void)
{
    std::string strData ;
    std::vector <char> vecData ;

    loadFileContents (FILENAME, strData) ;
    loadFileContents (FILENAME, vecData) ;

    return 0 ;
}

The benefit of this one is that we wouldn't have to supply template arguments in main.


Define if post extract from a bilingual Facebook page are in English using Python

Here are some comments on your code. First some stylistic comments, and afterwards some related to the logic of your code.

Method names should follow snake_case – According to the PEP8 standard, your method should be named extract_sentence_english, and slightly better worded, extract_english_sentences
Naming is hard – Most of the names seems to be slightly random. Why log, split_list, df, dat... They are not conveying anything sensible, or indicate how you've processed the original sentences.
Add vertical space – You have some, but could have more vertical space.
Better comments – For example, related to the split_list (renamed to all_words and log (renamed to is_english_words), I would rather write something like this:

# Make a list of all single words based upon the sentences
all_words = [word for sentence in list_of_sentence
                     for word in sentence.split(' ')]

# Make a corresponding list with True if the word is English,
# or False if not
is_english_words = [word in words.words() for word in all_words]

Now the comments explain the contents of the list, and what is happening on the next code lines.  I've also used a list comprehension to create the alternative to log, and with better variable names it is easier to see, and should not as expensive as the original for loop. By the way, range defaults to starting at 0 so it could simply have been range(len(split_list)).

Same kind of logic (and list comprehension) could apply to the creation of df, which could be renamed to sentence_lengths.
Why all the DataFrame mumble jumble? – I don't really see the need for all the usage of DataFrame (and don't understand what is happening besides the reconnection of words and sentences). More on this in alternate solution below.
Please add space after commas, , – In some of the parameter listings you don't add space after the comma, which makes the code harder to read. Be consistent, and always add space after comma.

Alternative logic

If I've understood your request properly you are getting a whole lot of sentences, and want to return all the English sentences (and loose the French sentences?). You go about this task by removing everything which isn't a-z, splitting into words and checking against a dictionary, and if the English word frequency is above 0.75 you'll return that sentence (without punctuation).

Doing it that way eliminates on a good indicator of French sentences. French sentences uses loads of accented characters. English doesn't. That is a very good indicator (if the Facebook guys care to write those characters), which you are missing out on.

Your solution also checks against an entire dictionary, which is kind of expensive. A simpler solution would be to keep two smaller list of typical English words and French words, and make sure to remove non-French or non-English words from these lists. I know very little French, but here is an attempt at some trigger word lists:

english_words = ["you", "are", "not", "the", "is", "what", "who", "that"]
french_words = ["le", "ce", "un", "la", "et", "au", "à", "toute"]

The idea is to have enough specific typical words in either list, so that it eases detection of the language.

So how could this look in an alternate version? Well, here is some code for you to work with:

import re
import random

sample_sentences = ['hi there, how are you mister', 'some none triggering english sentence', 'And another long english statement', 'This is not plain English', 'say','bonjour mister','sauf','tu am      belle','I suis cool', 'Hey YOU', u'Worst trip.ever je, à deteste AirTransat! ce sont les pires', u"Toute personne a droit à l´éducation"]

ENGLISH_WORDS = ["you", "are", "not", "the", "is", "what", "who", "that"]
FRENCH_WORDS = ["le", "ce", "un", "la", "et", "au", u"à", u"é", "toute"]

REQUIRED_NUMBER_OF_WORDS = 1
REQUIRED_ENGLISH_PERCENTAGE = 0.75

def extract_english_sentences(sentences):

  # Compile a pattern of all non-alphanumerics in Unicode
  pattern = re.compile('\W+', re.UNICODE)

  result = []
  print sentences

  # Loop on each sentence, and determine if it English or not
  for sentence in sentences:
    # Get a simplified sentence with only unicode alphanumerics,
    # which are lowercased
    no_punctuation = pattern.sub(' ', sentence).lower()

    # Split into single words
    words_in_sentence = no_punctuation.split()
    number_words = len(words_in_sentence)

    print ("\n>{}<".format(no_punctuation.encode('utf8', 'replace')))

    is_english = None

    # Check whether word is in either trigger list
    for word in words_in_sentence:
      if word in FRENCH_WORDS:
        print "in french words"
        is_english = False
        break

      if word in ENGLISH_WORDS:
        print "in english words"
        is_english = True
        break

    if is_english is not None and is_english:
      result.append(sentence)
      continue

    # If it didn't match anything in trigger list,
    # and we have more than 5 words, lets check the
    # percentage of English words
    if is_english is None and number_words > REQUIRED_NUMBER_OF_WORDS:
      # Count occurences of each word in the dictionary
      # give by words.words()
      #sum_english_words = sum(word in words.words()
      #                          for word in words_in_sentence)

      # Don't have dictionary, guess... :-)
      sum_english_words = random.randint(1, number_words)
      print "{} vs {}".format(sum_english_words, number_words)

      if sum_english_words / number_words > REQUIRED_ENGLISH_PERCENTAGE:
        print "Dictionary says English"
        result.append(sentence)
        continue

    if is_english is not None and not is_english:
      print "French!"
    else:
      print "Couldn't decide"

  return result

print extract_english_sentences(sample_sentences)

As I didn't have any words.words() available, I've commented out that segment, and use a random generator instead. This in combination a lot of print statements should show that in most cases it would continue with next sentence in a lot of the cases, and hopefully not fall through to the dictionary test or "Couldn't decide" very often.

When deployed to production all of the print statements should be removed. Do also note that this code is written in Python 2.7, so no parentheses are needed for the print statements, and some strings needs to be declared as unicode strings. But you didn't state which python version you are using, so I made this in the older variant. Hope this helps you along the way.

Alternate trigger word list tests

At the cost of looping twice through the words_in_sentence list, one could remove the inner for loop, and all other code related to is_english:

# Check whether word is in either trigger list
if any(word in FRENCH_WORDS for word in words_in_sentence):
  print "in french words"
  continue

if any(word in ENGLISH_WORDS for word in words_in_sentence):
  print "in english words"
  result.append(sentence)

Possible major speedup

I just realized that you could get a major speedup related to the dictionary lookup. It is very expensive to get the complete word list, words.words(), for every sentence. This should be done once, and created into a set, which then is used to check for existence within dictionary.

It's late in the night locally for me, so the following code is untested:

WORDS_SET = set(words.words())

...

sum_english_words = sum(word in WORDS_SET)

This should avoid the repeated loading of the words for every word of every sentence... Will try to test this tomorrow.


Brightness adjustment control for multiple UI elements

Why did you assume that only Map will ever want to observe the brightness value? As your code hints, you will possibly have not only multiple maps at one point, but also multiple points from which the brightness could be controlled. Which in return would also want to register with that service to update their displayed state in case of external control.

What you did forget to implement in that specific service, is an oldBrigthness != newBrightness test. If the control is set to the same value again, you don't want to propagate. Even less so if the scenario mentioned above occurs, and the self-adjustment of a brightness control could possibly broadcast another update.

I probably wouldn't use the old Observable and Observer classes, their interface predates the introduction of generics in 1.5, and as you noticed isn't even type safe yet.

You should revise on the API design on your service. You now have the odd situation where the BrightnessService needs to be aware of Map, while on the other side the controlling sites need to be aware of BrightnessService.

This is a rather unfortunate situation, since you now created a dependency chain from BrightnessSlider via BrightnessService to Map. This means a BrightnessSlider can't exist, without Map existing in the same application.

The solution to break this chain, is to make Map instead aware of BrightnessService, respectively define a generic interface in the package of BrightnessService which allows other components to register with this service. Now both the BrightnessSlider and the Map can exist and access the BrightnessService without the other component being part of the same application. As a side effect, this also solves the case where BrightnessSlider wants to observes the currently set brightness as well.

private static final List<Map> OBSERVERS;

Caps lock is for constants, not for mere static class variables. At least not if they can be considered "variable", and not constant.

Well, actually something as a static class variable  shouldn't exist in your application to begin with. You should try to keep your classes always instantiable and free from side effects. This also applies to this service.

If you actually need to ensure that only a single instance of this service can exist, use the Singleton pattern. This is about the only exception to the rule where static final may be used to declare something else than a constant.

There are quite a few reasons for that, among others that the BrightnessSlider and Map classes usually would also want to hold a reference onto the BrightnessService they have been registered with (and be it only to provide a clean shutdown by unsuscribing themselves!).

It also allows you to move freely between Singleton and other techniques, such as dependency injection, should your code base require that later on. As the call sites already work on a specific instance of BrightnessService (with disregard as where they obtained it from!), there is little friction in changing that later on.

Furthermore, static methods should also be free of side effects, by convention.
Performing constant calculations, or returning a constant result/reference? Good.
Mutating some global state directly? Not good.


Reading in a file and ranking result to output file

In this console application it might not be that important but later you should always take care of any resources and dispose them propertly. Closing it isn't enough so you should wrap the streams in usings:

using (var file = new StreamReader(@"/Users/aaronmk2/Projects/skateboard/skateboard/sample-input.txt"))
{
    ...
}

Be consistent. Either use var everywhere or nowhere. You also don't always need the entire namespace. Add a using System.IO; to other usings to avoid lengthy lines.

string teamOne = lines[0].Substring(0, lines[0].Length - 2);
int teamOneScore = Convert.ToInt32(lines[0][lines[0].Length - 1] - '0');
DoesTeamExist(dictionary, teamOne);
string teamTwo = lines[1].Substring(1, lines[1].Length - 2);
int teamTwoScore = Convert.ToInt32(lines[1][lines[1].Length - 1] - '0');

You should define a class for the results. It would help to explain all the magic indexes [0] above and encapsulate some logic. It's extremely hard to follow in its current form.

lines[0].Substring(0, lines[0].Length - 2)

Assuming that the score is always a space and a number like 1 is a very bad idea. Use regex instead. The TeamScore class could look like this:

class TeamScore
{
    public string Name { get; set; }
    public int Points { get; set; }

    public static TeamScore Parse(string value)
    {
        var scoreMatch = Regex.Match(value, @"(?<name>.+?)(?<points>\d+)");
        return new TeamScore
        {
            Name = scoreMatch.Groups["name"].Value.Trim(),
            Points = Convert.ToInt32(scoreMatch.Groups["points"].Value)
        };
    }
}

This has now huge implications as it will affect the entire application and make it much easier to understand:

The new Main becomes:

public static void Main(string[] args)
{
    var counter = 0;
    var teamScores = new Dictionary<string, TeamScore>();

    // create constants for indicies
    const int teamOneIndex = 0;
    const int teamTwoIndex = 1;

    using (var file = new StreamReader(@"/Users/aaronmk2/Projects/skateboard/skateboard/sample-input.txt"))
    {
        // define the variable as close to the usage as possible
        string line;
        while ((line = file.ReadLine()) != null)
        {
            // name it appropriately, it's "teams" not just a "line"
            var teams = line.Split(',').Select(TeamScore.Parse).ToList();

            // add both teams to the dictionary if not already there
            foreach (var team in teams)
            {
                if (!teamScores.ContainsKey(team.Name))
                {
                    teamScores.Add(team.Name, team);
                }
            }

            AwardPoints(teamScores, teams[teamOneIndex], teams[teamTwoIndex]);
            counter++;
        }
    }

    // don't name it just items, write what items they are
    var sortedTeamScores =
        from teamScore in teamScores
        orderby teamScore.Value.Points descending, teamScore.Key ascending
        select teamScore;

    using (var write = new System.IO.StreamWriter(@"/Users/aaronmk2/Projects/skateboard/skateboard/test-output.txt"))
    {
        // Display results.
        foreach (var teamScore in sortedTeamScores)
        {
            Console.WriteLine("{0}: {1}", teamScore.Key, teamScore.Value);
            if (teamScore.Value.Points == 1)
            {
                write.WriteLine("{0}: {1} pt", teamScore.Key, teamScore.Value.Points);
            }
            else
            {
                write.WriteLine("{0}: {1} pts", teamScore.Key, teamScore.Value.Points);
            }

        }
    }
}

and the helper method is:

static void AwardPoints(Dictionary<string, TeamScore> dictionary, TeamScore teamOne, TeamScore teamTwo)
{
    if (teamOne.Points == teamTwo.Points)
    {
        dictionary[teamOne.Name].Points += 1;
        dictionary[teamTwo.Name].Points += 1;
    }
    else if (teamOne.Points > teamTwo.Points)
    {
        dictionary[teamOne.Name].Points += 2;
    }
    else
    {
        dictionary[teamTwo.Name].Points += 2;
    }
}

There still other improvements possible like:
- separate the saving from the console output into two methods
- encapsulate the file reading in another method

The final version should look like this:

void Main(string[] args)
{
    var fileName = @"...";
    var teamScores = ImportTeamScores(fileName);
    var sortedTeamScores = SortTeamScores(teamScores);
    SaveTeamScore(sortedTeamScores);
    PrintTeamScore(sortedTeamScores);
}

It will make the maintenace much easier as you can now adjust only one feature at a time witout affecting the others.

I hope I have the logic correct after all the refactoring.


Merge Sort Implementation Efficiency In Python

PEP-8

The Style Guide for Python Code enumerates a set of rules that all Python programs should follow.  Of particular note is the Naming Conventions, which indicates that function names and variable names should all be snake_case, not CapitalizedWords.  So MergeSort should be renamed merge_sort, and MyList should be renamed my_list.

Private functions

merge is an internal helper function for MergeSort.  PEP-8 also recommends naming internal helpers with a leading underscore, to indicate it is private, and should not be used externally, so merge should be named _merge.

Repeated computations and lookups

    while len(left) > i and len(right) > j:
        if left[i] > right[j]:
            sorted_list.append(right[j])
            j += 1
        else:
            sorted_list.append(left[i])
            i += 1

This code has some inefficiencies.

Every iteration is recomputing len(left) and len(right).
Every iteration is performing 3 indexing operations, first looking up left[i] and right[j], and then looking up either left[i] or right[j] depending on which branch of the if/else is taken.

You only need to test len(left) > i when i changes, and len(right) > j when j changes:

    while True:
        if left[i] > right[j]:
            sorted_list.append(right[j])
            j += 1
            if len(right) > j:
                break
        else:
            sorted_list.append(left[i])
            i += 1:
            if len(left) > i:
                break

Now, the len() function should be called half as often, and only the part of the expression that is changing is being evaluated, and so this code, while longer, should actually run faster.

Similarly, we can remove the repeated indexing operations, by only performing the indexing operation when the corresponding index changes:

    left_value = left[i]
    right_value = right[j]

    while True:
        if left_value > right_value:
            sorted_list.append(right_value)
            j += 1
            if len(right) > j:
                break
            right_value = right[j]
        else:
            sorted_list.append(left_value)
            i += 1:
            if len(left) > i:
                break
            left_value = left[i]

Again, more code, but it should run faster.

Iterators

The above code is complicate because we are responsible for testing if the indices get to the end of the list, looking up the values at the given indices, and incrementing the indices.

Python has iterators, which do all of these operations for us!  So the above code could simply be written as:

    left_iter = iter(left)
    right_iter = iter(right)

    left_value = next(left_iter)
    right_value = next(right_iter)

    while True:
        if left_value > right_value:
            sorted_list.append(right_value)
            right_value = next(right_iter)
        else:
            sorted_list.append(left_value)
            left_value = next(left_iter)

This takes the left and right lists, creates iterators for them, extracts the first values of each, and then adds the smaller of the two values to the sorted_list, and then fetches the next value from the corresponding iterator.

The only problem is it will raise a StopIteration exception when one of the two iterators runs out.  We just need to catch this, and add the remaining entries from the non-expired iterator.  But which one?  Actually this is easy, since the values for left_value and right_value haven't changed, left_value > right_value will reveal which branch of the if/else the exception was raised in.

The only "tricky" part to remember is that if the next(left_iter) raised an exception, then right_value should be added to the sorted_list before the rest of the values from right_iter, and vis-versa. sorted_list.extend() is an easy way of adding the remaining items from the non-expired iterator.

def _merge(left, right):
    left_iter = iter(left)
    right_iter = iter(right)

    sorted_list = []

    # These should never fail because both left & right have one or more elements.
    left_value = next(left_iter)
    right_value = next(right_iter)

    try:
        while True:
            if left_value > right_value:
                sorted_list.append(right_value)
                right_value = next(right_iter)
            else:
                sorted_list.append(left_value)
                left_value = next(left_iter)

    except StopIteration:
        if left_value > right_value:
            sorted_list.append(left_value)
            sorted_list.extend(left_iter)
        else:
            sorted_list.append(right_value)
            sorted_list.extend(right_iter)

    return sorted_list

We've approximately double the number of lines of code in _merge(left, right), but the code should be faster, since all of the indexing, is now being handled by Python itself.


Find diagonal positions for bishop movement

The biggest problem you have is you have five lines that are nearly identical, four times.

row = coord[0]
col = coord[1]

while row > 0 and col > 0:
    row -= 1
    col -= 1

There is two ways to come at this. (1) make a function that yield the rows and columns. (2) use zip and range.

The first way you need to enter a start, limit and step for both the x and y axis.
You then need to limit all inputs by 0 < x < x_limit, and the same for the y axis too.
This is as we don't really know what direction we're going.
We then add the step to x each iteration.
This can make:

def _diagonal(x, y, x_limit, y_limit, x_diff, y_diff):
    while 0 < x < x_limit and 0 < y < y_limit:
        x += x_diff
        y += y_diff
        yield (x, y)

Where you'd use it like:

for x, y in _diagonal(row, col, limit, limit, 1, 1):
    coords.append((x, y))

However this is quite alike to range, we enter a start, limit and step in both.
Take range(row + 1, limit, 1).
To then get both x and y you need to use zip which works perfectly as it stops iterating when any of the inputs stop.
And so you can get:

for x, y in zip(range(row + 1, limit, 1), range(col + 1, limit, 1)):
    coords.append((x, y))

This I would say is better than creating your own function as you don't really have to implement anything yourself.

Either way you'll want to remove the duplicate code to append to coords.
To do this you can use itertools.chain.
This lets you chain iterators to become one iterator.
So since you want a list as output you'll have to 'wrap' the call in a list call.

This can get you:

from itertools import chain

def diagonals(coord, size):
    x, y = coord
    return list(chain(
        [(x, y)],
        zip(range(x - 1, -1, -1), range(y - 1, -1, -1)),
        zip(range(x + 1, size, 1), range(y + 1, size, 1)),
        zip(range(x + 1, size, 1), range(y - 1, -1, -1)),
        zip(range(x - 1, -1, -1), range(y + 1, size, 1)),
    ))

print(diagonals((3, 4), 8))


Project Euler #9 in Swift - Special Pythagorean triplet

Your program is quite fast, but that is a bit of a lucky coincidence. The
Pythagorean triplet with sum 1000 is (200, 375, 425). This is not a primitive
Pythagorean triplet  but (8, 15, 17) multiplied by 25.

So your program finds (8, 15, 17) quickly and from there "jumps" to the solution.
That is fine and solves the Project Euler problem. But if you want a solution
for arbitrary sums then one can do better. On my computer, your program
needs

0.0004 seconds to find the solution for sum = 1000, but
0.014 seconds to find the solution for sum = 928, and
1.9 seconds to find that there is no solution for sum = 1001.

The key point is that your method uses three nested loops, which is not necessary
because only two of the variables a, b, c can be chosen freely and the last
is determined by \$ a+b+c = \text{sum} \$.

From the condition a < b < c one can also restrict the possible ranges.
If we start with a in the outermost loop then

$$
    \text{sum} = a + b + c \ge a + (a + 1) + (a + 2) = 3 \, a + 3 \implies a \le (\text{sum} - 3)/3
$$

and for b we have

$$
    \text{sum} = a + b + c \ge a + b + (b + 1) = a + 2 \, b + 1
    \implies b \le (\text{sum} - 1 - a)/2 \quad .
$$

So your function would be

func getSpecialPythagoreanTriplet(sum:Int) -> Int {

    for var a = 1; a <= (sum - 3)/3; a++ {
        for var b = a + 1; b <= (sum-1-a)/2; b++ {
            let c = sum - a - b
            if a*a + b*b == c*c {
                return a*b*c
            }
        }
    }
    return -1
}

This method needs about 0.0002 seconds to find the solution (or it's non-existence) in all three test cases (sum = 1000, 928, 1001).

One note regarding your function name: It might be unclear what is "special"
in getSpecialPythagoreanTriplet().
Also the "Coding Guidelines for Cocoa" recommend the "get" prefix only for functions
that return some value indirectly. A better name for your function would
be something like

func pythagoreanTripletWithSum(sum:Int) -> Int


First missing positive integer in linear time and constant space

It would be good to have some comments in the code explaining why (a) it works; (b) it takes linear time.

        int i = 0;
        for (i = 0; i < n; i++) {

I would prefer to use for (int i = 0; ...) and similarly for the other loop over i: they don't need to use the same variable, and keeping scopes as small as possible helps understanding and maintenance. But if you prefer to keep the variable in the wider scope, there's no need to initialise it twice. Either of

        int i = 0;
        for (; i < n; i++) {

or

        int i;
        for (i = 0; i < n; i++) {

works fine.

            if (val <= 0 || val > n)
                continue;
            while (val != arr[val - 1]) {
                int nextval = arr[val - 1];
                arr[val - 1] = val;
                val = nextval;
                if (val <= 0 || val > n) {
                    break;
                }
            }

It's a bit inelegant to apply the range test twice. A simple refactor gives

        while (val > 0 && val <= n && val != arr[val - 1]) {
            int nextval = arr[val - 1];
            arr[val - 1] = val;
            val = nextval;
        }

        }
        return n+1;

    }

For consistency I would add whitespace around +. The blank line makes more sense to me before the return rather than after it, and I would also add a blank line separating the two loops.

The fact that I'm nitpicking whitespace like this is a good sign: I haven't found anything which I consider to be a major problem.


Largest product in a grid: Project Euler 11


Finding the largest jacobian in a finite element mesh

Welcome to the wonderful world of C programming where you have to do everything yourself.

The C programming language is basically a high level assembly language, there is no garbage collection and the programmer has to manage the memory themselves.

The Good

Before I start discussing what can be improved, I'll mention the good things:
 - The code is quite readable
 - No casts from malloc() to the receiving variable
 - The code follows the Single Responsibility and KISS principles, lots of nice small functions, although the function struct Mesh generate_mesh(double* coordinates, int num_nodes, int num_elements) could have 2 sub-functions to implement it, each of the for loops could be a function.
 - There is only one Magic Number, and that one is forgivable, the 5000000 used to initalize the variable num_elements

Error Checking

The allocation functions malloc(), calloc() and realloc() have been known to fail. This happens less often now than historically because computers generally have more memory than they used to, but there are still cases of limited memory such as in embedded programming.

When an allocation function fails it returns NULL. Reference through a NULL pointer causes unknown behavior, and generally the program will terminate without an explanation. It is a good habit to test the results of the allocation before using the pointer in code:

    double* coordinates = malloc(num_nodes * sizeof(double));
    if (!coordinates)
    {
        fprintf(stderr, "Allocation of coordinates failed, exiting program\n");
        exit(EXIT_FAILURE);
    }

    for (int i=0; i < num_nodes; i++)
    {
        coordinates[i] = (double) rand() / RAND_MAX;
    }

There are other ways to handle this error, you might want to learn about setjmp and longjmp. There is a discussion about setjmp and longjmp in this stackoverflow question. There are problems using exit() in some cases.

Prevent Memory Leaks

As mentioned above, C doesn't have garbage collection, the programmer is responsible for de-allocating memory through the use of free(). If this program was part of a larger more complex program there would be memory leaks because none of the allocated memory is ever freed. This could lead to other memory allocation failing.

In reference to the edit, you could free the nodes array after the content of the nodes were copied into the elements.

Prefer calloc Over malloc for Arrays

The function calloc(size_t num, size_t size) is generally preferred over malloc(size_t size) for arrays. The first parameter is the number of items to allocate, the second number is the size of the items. The parameters obviously make sense for arrays. One of the benefits of calloc() is that it zeros out each element of the array when the memory is allocated.

When allocating memory the code become more maintainable when the sizeof() function contains the variable the memory is being assigned to rather than the actual type. This allows the programmer or maintainer t change the type of the variable without having to change the code of the allocation itself. An example is :

    double* coordinates = calloc(num_nodes, sizeof(*coordinates));
    if (!coordinates)
    {
        fprintf(stderr, "Allocation of coordinates failed, exiting program\n");
        exit(EXIT_FAILURE);
    }

In the code above changing the type of the variable coordinates automatically changes the size of the items being allocated.


usort($sortArray, function($a, $b){
  return $a[0] - $b[0];
});

$sortArray = array_reverse($sortArray);

Minor thoughts:

Instead of sorting by $a[0]-$b[0] and reversing, why not sort by $b[0]-$a[0] in the first place? However...
You could just return $b[0] <=> $a[0].


Improve page-specific CSS for different color schemes

Some days passed and I feel like I should share the changes I have made so far.

Naming

I started using page names instead of color names on classes and variables. This leaves me with the benefit of being able to change the color scheme of an entire page only by changing the value of the color variable.

.page--home       -> .page--blog
.nav__item--green -> .nav__item--blog
$green-color      -> $blog-color

Generating page-specific CSS with a mixin

I need to style certain elements depending on the class I assign to the root element (e.g. <html class=page--blog>)
The needed arguments I pass to the mixin are $element (a selector like .site-nav or h1) and $property (a CSS property like color)
There also is an optional argument which allows me to switch to light color variations

Mixin:

@mixin themify($element, $property, $light-colors: false) {
    $pages: null;
    @if $light-colors == true {
        $pages: blog      $green-color-light,
                portfolio $orange-color-light,
                profil    $blue-color-light,
                impressum $red-color-light;
    } @else {
        $pages: blog      $green-color,
                portfolio $orange-color,
                profil    $blue-color,
                impressum $red-color;
    }

    @each $page in $pages {
        .page--#{nth($page, 1)} #{$element} {
            #{$property}: nth($page, 2);
        }
    }
}

/* Call the mixin without optional argument */
@include themify(site-nav, background-color);

/* ...use the light colors instead of the normal ones */
@include themify(site-nav, background-color, $light-color: true);

Problems with the mixin:

I can't pass a list of selectors like a, h1, h2, h3, h4, h5, h6 – Didn't find a solution so far (probably going to involve multi-dimensional lists)
Still creates the bloated CSS, but eases my work

I still would love to hear some suggestions/improvements.


Since you have basically the same statements over and over with different parameters, this can be turned into a loop. You can pair the pattern and the string you want to use to replace in a dict. This makes it clear what is paired with what. Take a look:

import re

def strip_html(raw_html: str) -> str:
    pairs = {
        '<.*?>': ' ',
        '&amp;': '&',
        '\n': ' ',
        '&nbsp;': ' ',
        '&#8217;': '\'',
        '&#8230;': '...',
        '&#8216;': '\'',
        '&#8221;': '\'',
        '&#8220;': '\'',
        '&#8211;': '\'',
        '&#8212;': '\'',
        '&#38;': '&',
        '&#2026;': '...',
        '&#160;': ' ',
        '&#038;': '&'
    }
    previous = raw_html
    for pattern in pairs:
        clean_text = re.sub(re.compile(pattern), pairs[pattern], previous)
        previous = clean_text
    return clean_text.strip()


Function to validate a GUID, an EntityState, and some data

It makes sense to use these arguments and throw ArgumentException or ArgumentNullException instead of just Exception:

private static void Validate(Guid userId, EntityState state, object data)
{
    if (userId == Guid.Empty)
        throw new ArgumentException("Token unrecognized!", nameof(userId));
    if (state == EntityState.Detached)
        throw new ArgumentException("Action unrecognized!", nameof(state));
    if (data == null)
        throw new ArgumentNullException(nameof(data), "Data unrecognized!");
}

Since the nameof() is a C#6 feature, in the previous versions of C# you should use argument name string instead: "userId", "state", "data".


What do you think of my EventAggregator implementation in C#?

I haven't thoroughly looked at it but these are my initial thoughts.

Minor points

I would initialise the private variables inline like this private object _syncLock = new Object(); because they don't depend on parameters given to the constructor.

For readability I wouldn't use the LockAround method, I would just lock _syncObject.

In GetListeners is there any reason you are adding a list to the dictionary when no events have been registered for that type? Also, you could make it generic by pulling in the typeof from Raise like so _listeners.TryGetValue(typeof(TEvent), out result).

In Register<TEvent> what is the purpose of (Action<TEvent>)wr.Target == eventAction? I think if someone wants to register the same event handler twice then they should be able to.

You might want to make your event aggregator a singleton or use a dependency injection framework to ensure there is only ever one instance in existence.

Worries

In Raise<TEvent> the following line worries me targets.ForEach(wr => ((Action<TEvent>)wr.Target)(ev));. I'm not sure there is any guarantee the weak reference will still be alive at this point. You probably want to solidify the reference and check that it is not null before calling it.

Finally

Have you looked at Microsoft's event aggregator and unity dependency injection framework? I think they probably do what you are looking for and will save you from reinventing the wheel.


Wherever you place static will change the behaviour of your program tremendously. In the end, we have \$2^3 = 8\$ combinations, so let's check some of them.

A random_device may fall back to a pseudorandom engine if no hardware-device for random numbers is available. If you don't use static on random_device in this case, all your strings may end up the same, as the pseudorandom engine may get initialized with a implementation defined fixed seed, e.g.

 std::random_device a;
 std::random_device b;
 assert(a() == b());  // worst case if no hardware-device or a low-effort implementation is used

In this case, a mt19937 would get seeded with the same value all the time, and we end up with the same string in every call. This changes if either mt19937 or random_device is static, and may change if dist is static, as a uniform_int_distribution can use several calls to the generator for its internal state.

Of course, if mt19937 is static, you may as well change random_device to a static variant, as it will get evaluated only once. This is the closest your get to a single srand() call at the start of your program. Your uniform_int_distribution still loses its internal state, though.

In the end, it depends on whether we want two generateRandomChar calls to correlate to each other. If they shall not correlate at all, we need to reseed our PRNG with a new non-deterministic number and cannot use static at all.

Or, to put it in another way: if we use static for all three values, then

generateRandomChar(10) + generateRandomChar(10)

is the same as
    generateRandomChar(20)
If we use static on mt19937, then both may be the same, depending on both _len and dist.

Either way, if you want to have more control over the generation, you can just provide a generator in your function:

template <typename Generator>
std::string generateRandomChar(Generator & gen, const unsigned int _len)
    {
        ...
    }

Same holds for the distribution.

Other than that, I'd use sizeof instead of 61 to make sure that I don't accidentally change the pool of possible characters without changing the number bounds in dist's constructor:

static constexpr char alphanum[] = "0123456789"
                                   "abcdefghijklmnopqrstuvwxyz"
                                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, sizeof(alphanum) - 1);


Generating URL and status for an S3 bucket

Your code is well-written overall, but the users are going to forget to close the url_connection; I would provide automatic closing by implementing the magic methods __enter__ and __exit__ that allow use with with as a context manager.


Pattern matching deeply nested arguments in Elixir

I've just taken a whack at cleaning up my original code after a few days.

edit: Now including refactor suggestions from alxndr.

Set everything in motion

  def run(job) do
    HTTPStatusCheck.run(job)
    |> update_db
    |> send_alerts
  end

(The new run method seen here handles what was previously done by query and parse.)

The new HTTPStatusCheck.run/1 method:

  def run(job) do
    method = :head
    url = job.url
    body = ""
    headers = [@user_agent]
    options = @http_options

    HTTPoison.request(method, url, body, headers, options)
    |> parse
  end

(You can see it calls parse internally now, as I cannot find a reason anything else would ever need to work with the unparsed results object.)

The new HTTPStatusCheck.parse/1 definitions:

  defp parse({:ok, %Response{status_code: c}} = resp) do
    %HTTPCheckResult{}
    |> add_http_code(c)
    |> add_http_response(resp)
  end

  defp parse({:error, %HTTPoison.Error{reason: reason}} = resp) do
    %HTTPCheckResult{}
    |> add_http_response(resp)
    |> add_error(reason)
  end

  defp parse(_) do
    %HTTPCheckResult{}
    |> add_error("unknown")
  end

(I feel these are much better, as the method signature and definition code are now much shorter and more readable. The suggestions from alxndr were implemented here and in the next section of helper methods.)

Helper methods for HTTPStatusCheck.parse/1:

  defp add_result(result, val), do: %{result | result: val}
  defp add_http_response(result, response), do: %{result | http_response: response}

  defp add_http_code(result, code) do
    %{result | code: code}
    |> handle_http_code(code)
  end

  defp handle_http_code(result, code) when code in @up do
    result
    |> add_result(:up)
  end
  defp handle_http_code(result, code) when code in @down do
    result
    |> add_result(:down)
  end
  defp handle_http_code(result, code) do
    result
    |> add_error("unhandled http code #{c}")
  end

  defp add_error(result, error) do
    %{result | error: error}
    |> add_result(:error)
  end

%HTTPCheckResult{} is improved too:

There is no longer the need to indicate parsed: false or parsed: true on this struct.


Instead of writing your own lock_guard-like object specifically to use with a CMutex, I'd write a wrapper for CMutex to give it the Lockable interface, then just use it with a normal std::lock_guard:

namespace mfc {
class mutex {
    CMutex m;
public:
    mutex(BOOL bInitiallyOwn = FALSE,
          LPCTSTR lpszName = NULL,
          LPSECURITY_ATTRIBUTES lpsaAttribute = NULL)
        : m(bInitiallyOwn, lpszName, lpsaAttribute)
    {}

    void lock() { m.Lock(); }
    void unlock() { m.Unlock(); }
};

Then you can just lock it like you would an std:mutex:

// Define the mutex
mfc::mutex m;

void foo() {
    std::lock_guard<mfc::mutex> L(m);
    // use whatever m is protecting
}

You may not even need that though. You may have run into the fact that a Windows-native mutex is always a recursive mutex, and a std::mutex is not. If you replace it with std::recursive_mutex instead of std::mutex, it may work just fine (or depending on how you do your locking, you may need a recursive_timed_mutex).


Thinking this more, there are three things affecting the appeal.

A[i]
A[j]
i - j

Since A[i] + A[j] is the same as A[j] + A[i], you don't need to traverse the whole array in the inner loop.

Since the third component increases the appeal only when j < i, you can restrict the inner loop to run from 0 to i.

You also need to take into account the fact that all cities may have negative appeal. Integer.MIN_VALUE is safe initial value, as the lowest valid value (2 * -1000000000 - 100000) is still greater than that.

Using Math.max would have been more readable.

    int highestAppeal = Integer.MIN_VALUE;

    for (int i = 0; i < A.length; i++) {
        for (int j = 0; j <= i; j++) {
            final int currentAppeal = A[i] + A[j] + (i - j);
            highestAppeal = Math.max(highestAppeal, currentAppeal);
        }
    }

    return highestAppeal;

And you can't overestimate the value of commented code in an interview answer.


Overall this is a really good approach.  There is one main thing you can do to improve the implementation of this algorithm.  You are copying the array at each level of recursion, but it is unnecessary in this case.  Instead try an in-place approach.  This improves cache locality and saves the tiniest amount of memory.
Secondly, things like (i//3)*3:(3+(i//3)*3) can be confusing.  Extracting out a variable name puts less burden on the reader and optimizer as (i//3)*3 is repeated.
You can also break the function up into smaller functions, but where you draw the line is up to you.  Your use of reduce here is extremely readable and elegant way of implementing this algorithm.  There are better algorithms for solving Sudoku, but since brute force is so fast, this is a good choice for its simplicity.
Here is an example:
import numpy as np
from functools import reduce

def get_candidates(search_space):
    return np.setdiff1d(np.arange(1, 10), reduce(np.union1d, search_space))

def solve(board):
    missing = get_missing(board)

    if not had_missing(missing):
        return True

    missing_col = get_missing_col(missing)
    missing_row = get_missing_row(missing)

    search_space = (
            get_col(board, missing_col),
            get_row(board, missing_row),
            get_square(board, missing_col, missing_row)
        )

    for candidate in get_candidates(search_space):
        board[missing_row, missing_col] = candidate
        if solve(board):
            return True

    board[missing_row, missing_col] = 0
    return False

def get_col(board, idx):
    return board[:, idx].reshape(9)

def get_row(board, idx):
    return board[idx, :].reshape(9)

def get_square(board, col, row):
    col = col // 3 * 3
    row = row // 3 * 3
    return board[row:row+3, col:col+3].reshape(9)

def get_missing(board):
    return np.where(board == 0)

def had_missing(missing):
    return len(missing[0])

def get_missing_col(missing):
    return missing[1][0]

def get_missing_row(missing):
    return missing[0][0]

board = np.array([
    [5,3,0, 0,7,0, 0,0,0],
    [6,0,0, 1,9,5, 0,0,0],
    [0,9,8, 0,0,0, 0,6,0],

    [8,0,0, 0,6,0, 0,0,3],
    [4,0,0, 8,0,3, 0,0,1],
    [7,0,0, 0,2,0, 0,0,6],

    [0,6,0, 0,0,0, 2,8,0],
    [0,0,0, 4,1,9, 0,0,5],
    [0,0,0, 0,8,0, 0,7,9]
])

solve(board)
print(board)
```


There is a neat trick in many computer algorithms called memoization - the remembering of critical aspects of one computation, to reuse them in another. Memoization can help a lot in this problem. To explain this, consider the basic algorithm you have...

start at the top-left of the matrix
scan every position in the matrix
for each position, check whether it is the top-left of an increasing square of set values.
keep track of the maximum.

This process is effective, but not very efficient. What if I were to tell you there is a way to solve the problem without having to do step 3, just by remembering what you did in previous iterations of step 1 and 2?

The way we do things, is to remember the size of previously-computed squares of set positions. We remember the previous row, and the current row only. No need to remember more than that....

Looking at your example:

1 0 1 0 1
1 1 1 0 1
1 0 1 1 1
1 0 1 1 1
1 0 1 1 1

It is a matrix of size 5. We create two temporary arrays to record the previous and current memoization:

int[] previous = new int[5];
int[] current = new int[5];

Now, we compute the values for the current memoization - it works like this:

if the cell in the current column is not set, then the square at the current position is size 0.
if the cell is set, then it is 1 more than the smallest square above , above-left, or left of it. This needs a picture.....

As you can see, I have marked 3 squares - red, blue, and purple. Each of them is 2x2. The position at the bottom right, is the end of the 3x3 square. it is 1 + the minimum size of the blue, red, and purple squares.

So, it becomes relatively simple to identify squares, we only need to check three values for each cell.... the code is surprisingly simple, even if the concept is hard...

private static Square getLargestSquare(int[][] matrix) {
    if (matrix == null || matrix.length == 0) {
        return null;
    }

    final int height = matrix.length;
    final int width = matrix[0].length;

    Square max = null;

    // cheat, here, and use the first matrix row as 'current'
    // this will become 'previous' in the loop, and will not be changed.
    // note that the y-loop starts from 1, not 0.
    int[] previous = null;
    int[] current = matrix[0];

    for (int y = 1; y < height; y++) {
        // prepare the memoization space.
        // Forget the previous, move current back, and make a new current
        previous = current;
        current = new int[width];
        for (int x = 0; x < width; x++) {
            if (matrix[y][x] == 1) {
                int span = 1;
                if (x > 0) {
                    // no need to check the left-most column, if set, it is always size 1.
                    span = 1 + Math.min(current[x - 1], Math.min(previous[x], previous[x - 1]));
                }
                if (max == null || span > max.size) {
                    // because we find the max at x, and y, which are the bottom-right,
                    // we need to subtract the span to get to the top-left instead.
                    max = new Square(x - span + 1, y - span + 1, span);
                }
                current[x] = span;
            }
        }
    }

    return max;
}

Note that I have created a container-class Square to hold the result:

private static final class Square {
    private final int x, y, size;

    public Square(int x, int y, int size) {
        super();
        this.x = x;
        this.y = y;
        this.size = size;
    }

    @Override
    public String toString() {
        return String.format("Square at (%d,%d) is size %d", x, y, size);
    }

}

Additionally, the main method is now simple:

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

    Square sq = getLargestSquare(matrix);

    System.out.println("Largest square: " + sq);
}

You can see the whole thing on ideone: Largest Square


Function that shortens a String based on a term/abbreviation mapping

Some observations (partly covered in @RoToRa's answer):

A placeholder String such as "<remove>" doesn't communicate at a glance whether a subsequence can be removed or not. Consider if you are scanning through your code:

map.put("Another Bored Cat", "ABC");
map.put("Another Bad Coral", "<remove>");
map.put("Another Berry Can", "ABC");

You may miss out that "Another Bad Coral" needs to be removed, purely by looking at the length of the line. It's arguably easier to read as such:

map.put("Another Bored Cat", "ABC");
map.put("Another Bad Coral", "");
map.put("Another Berry Can", "ABC");

In this case, it also removes the ambiguity (as unlikely as that may seem initially) that "Another Bad Coral" will be substituted with "<remove>".
Not particularly efficient uses for StringBuilder, especially when you builder.append(" " + aString) when you can do builder.apppend(' ').append(aString). Furthermore, you are also creating a StringBuilder for every tokenized word.
Related to the previous point, your explicit concatentation of " " characters forces you to repetitively do builder.deleteCharAt(0), which also leads to buggy derivation.
Usage of Map/HashMap can be enhanced so as to reduce the explicit looping that you are currently doing by tokenizing the input String. As you mentioned, you want to "takes the most words as the key in the HashMap", so if there's a way to actually iterate in that order from the Map...

Alternative implementation (Java 8 features ahead)

You can then use a TreeMap with a suitable Comparator implementation to persist and iterate with. For example:

private static final Comparator<String> KEY_COMPARATOR = (s1, s2) -> {
    int diff = Integer.compare(s2.length(), s1.length());
    return diff == 0 ? s1.compareToIgnoreCase(s2) : diff;
};

Or in the form of an anonymous class:

private static final Comparator<String> KEY_COMPARATOR = new Comparator<String>() {

    @Override
    public int compare(String s1, String s2) {
        int diff = Integer.compare(s2.length(), s1.length());
        return diff == 0 ? s1.compareToIgnoreCase(s2) : diff;
    }
};

This literally does what is required: if the lengths of both Strings are the same, we'll use a case-insensitive comparison between the both of them, else we simply rank the longer String to be greater than the other. This means that a Map such as:

private static final Map<String, String> MAPPER = getMapper();

private static Map<String, String> getMapper() {
    Map<String, String> mapper = new TreeMap<>(KEY_COMPARATOR);
    mapper.put("THE", "");
    mapper.put("AUTOMATIC", "AUTO");
    mapper.put("ZOOKEEPER", "ZK");
    mapper.put("AUTOMATIC GAIN CONTROL", "AGC");
    mapper.put("IDENTIFIER", "ID");
    return mapper;
}

Will give us the following desired iteration order:

// MAPPER.forEach((key, value) -> System.out.printf("%s => %s\n", key, value));
AUTOMATIC GAIN CONTROL => AGC
IDENTIFIER => ID
AUTOMATIC => AUTO
ZOOKEEPER => ZK
THE =>

With this Map implementation, the overall solution is half-complete. What is left is to replace any matching keys (as a subsequence) in the input String with the shortened value. For this, you can consider using regular expressions to perform the substitution on just one instance of StringBuilder:

private static String shorten(String input) {
    StringBuilder result = new StringBuilder(input);
    MAPPER.forEach((key, value) -> {
        Matcher matcher = Pattern.compile("(?i)\\b" + key + "\\b").matcher(result);
        while (matcher.reset().find()) {
            result.replace(matcher.start(), matcher.end(), value);
            if (value.isEmpty() && result.length() != 0) {
                result.deleteCharAt(Math.max(0, matcher.start() - 1));
            }
        }
    });
    return result.toString();
}

Use a case-insensitive ((?i)) Pattern instance to apply on the StringBuilder via Pattern.matcher(CharSequence). The \\b word boundary is important to make sure we only match on a complete expression demarcated by whitespaces.
Loop through each match, taking care to reset() the Matcher instance first.
Replace the contents of the StringBuilder instance using the results matcher.start() and matcher.end().
For cases where we are removing text, we also need to remember to delete the previous character, or the first, so long as the StringBuilder instance is non-empty.

Unit-testing

In case this is not done yet, remember to unit test this method too! For example, using a combination of TestNG and Hamcrest matchers library to perform the required assertions:

@Test
public void testInput() {
    String test = "There is the Automatic Automatic Gain Control Zookeeper Identifier";
    assertThat(shorten(test + " " + test),
                    equalsTo("There is AUTO AGC ZK ID There is AUTO AGC ZK ID"));
    // the middle whitespace is effectively trimmed away
    assertThat(shorten("the the"), equalsTo(""));
    assertThat(shorten("The Automatic Gain Control identifier value"),
                    equalsTo("AGC ID value"));
}


Refactoring string incrementing and duplicating function

You should consider using consistent indentation when writing code - it makes it much easier for people to read (not only for other maintainers, but for you as well). For example

let loop = 0;
for (; loop < 155; loop++) {
let n = 00;
// ...
zz ="00";
        if (loop > 0 ) {
        x+=loop;
    console.log('one loop ' + loop );

should be something like

let loop = 0;
for (; loop < 155; loop++) {
  let n = 00;
  // ...
  zz ="00";
  if (loop > 0 ) {
    x+=loop;
    console.log('one loop ' + loop );

Lots of IDEs provide an automatic tidying function.

In this section, since you aren't using str2, str3, or str4, you may as well remove those assignments from the inside of the loop here, since they aren't used and only add to cognitive overhead.

Best to always declare variables before you use them - you have a number of variables which are not declared, which will either assign to properties of the global object (in sloppy mode), or will throw an error (in strict mode). (Consider always using strict mode so that these sorts of potential bugs can be fixed early.) Specifically, lines like:

str1 = "https://site.com/content/2018/02/"; /* groups 1-155*/

where you use a variable for the first time should be prefixed with const, let, or var:

const str1 = "https://site.com/content/2018/02/"; /* groups 1-155*/

If you're going to use ES2015 syntax to declare some variables like let (which is great, you should), don't use var anywhere; var has numerous potential gotchas which can cause bugs, and doesn't really have anything positive going for it (other than compatibility with ancient browsers - but if you need that sort of compatibility, use Babel to transpile to ES5 automatically - best to keep source code in readable, pretty, modern syntax).

When you have a for loop, if you need to declare a variable at the beginning that's then used inside that loop, you should put the declaration inside the for loop declaration. That is:

let loop = 0;
for (; loop < 155; loop++) {

should be

for (let loop = 0; loop < 155; loop++) {

You have

let n = 00;
let x = 000;

Leading zeros have no effect in numeric literals. Those are equal to

let n = 0;
let x = 0;

You declare the zz variable 3 times, but you only have one binding for it - duplicate variable declarations with var are ignored. If you just want assignment, then only use the assignment operator with =.

The x variable starts at 0 and gets loop assigned to it once, on every iteration:

let x = 0;
// ...
if (loop > 0) {
  x += loop;

So, it's equivalent to loop. Best to just remove that variable completely, since it isn't doing anything useful - use the one loop variable completely. The if (loop > 0) { test is superfluous too, since the tests inside that block if(x >= 9){ if(x >= 99){ are only fulfilled if loop is greater than 0 anyway.

Use meaningful variable names. It is very difficult to tell at a glance what loop, n, x, z, or zz are meant to represent. Maybe call them group (the number that goes from 1 to 155) and subgroup (the number that goes from 1 to 11) instead.

The main block there is meant to ensure that the zz variable for padding the string has the right number of zeros. But there's a much easier way to do that, without creating extra variables: just use String.prototype.padStart. When you need to construct

000_01
154_12

from variables 0 and 1, and from variables 154 and 12, add the leading zeros by calling padStart(length, '0') on them:

`${String(group).padStart(3, '0')}_${String(subgroup).padStart(2, '0')}`

Or, without a template literal:

String(group).padStart(3, '0') + '_' + String(subgroup).padStart(2, '0')

The loop over subgroups (or n in your original code) assigns a variable and increments it every iteration, breaking after a condition. This is a prime spot to be refactored into a for loop instead:

for (let subgroup = 1; subgroup <= 12; subgroup++) {

Since the str1 never changes, and nor does the ext, you may as well declare them outside of the loop, rather than re-declare them every time there's another iteration:

In full:

'use strict';

const str1 = "https://site.com/content/2018/02/"; /* groups 1-155*/
const ext = ".jpg"
for (let group = 0; group < 155; group++) {
  console.log('one loop ' + group);
  for (let subgroup = 1; subgroup <= 12; subgroup++) {
    console.log(`${str1}${String(group).padStart(3, '0')}_${String(subgroup).padStart(2, '0')}${ext}`);
  }
}


Read .csv files and convert the rows into dict for looping

Welcome to CR!

As others recommended, you need to be more clear. I can give you some stylistic critique.

I like that you are using type hinting in the parameters. I recommend you also hint the return types for your functions like:

def _trim_row(self, row: dict) -> list:
            trimmed_row = dict.fromkeys(self.FIELDS, None)
            for field in self.FIELDS:
                if field in row:
                     trimmed_row[field] = row[field]
            return trimmed_row

Now, more importantly I recommend you create strong documentation for your code so that we can understand the idea behind it, what bugs it has, as well as its efficiency failures (you can use codetags such as # BUG: or # FIXME:).

For your convenience, you can also edit your code in an IDE that enables pylinting, where you can get suggestions about how stylistically good your code is, I recommend VS Code with the Python and autoDocstring extensions.

By putting your code in VS Code, I got the following suggestions for improvements:

""" [INSERT MODULE DESCRIPTION] """

import os
from csv import DictReader

class CSVHandler:
    """[INSERT CLASS DESCRIPTION]
    """
    DELIMIT = ','  # delimiter for csv
    FIELDS = set(list(['foo', 'bar']))  # fields that I want

    def __init__(self, file_path: str):
        """[summary]

        Arguments:
            file_path {str} -- [description]
        """
        self.file_path = file_path
        self.file_obj = None
        self.reader = DictReader([])

    def read_file(self):
        """[summary]

        Returns:
            [type] -- [description]
        """
        if self._is_file_ok:
            try:
                self.file_obj = open(self.file_path, newline='')
                self.reader = DictReader(self.file_obj)
                unmatched = self._is_fields_ok
                if isinstance(unmatched, set):
                    print(f"Warning : field set's unmatched! {unmatched}")
            except IOError:
                print(f'Unable to open/read file : "{self.file_path}"')
        else:
            print(f'Invalid file : "{self.file_path}"')
        return self

    @property
    def _is_file_ok(self):
        """[summary]

        Returns:
            [type] -- [description]
        """
        if os.path.isfile(self.file_path):
            if os.path.exists(self.file_path):
                if self.file_path.endswith('.csv'):
                    return True
        return False

    @property
    def _is_fields_ok(self):
        """[summary]

        Returns:
            [type] -- [description]
        """
        if self.reader or not self.FIELDS:
            return self.FIELDS - set(self.reader.fieldnames)
        return False

    def _trim_row(self, row: dict):
        """[summary]

        Arguments:
            row {dict} -- [description]

        Returns:
            [type] -- [description]
        """
        trimmed_row = dict.fromkeys(self.FIELDS, None)
        for field in self.FIELDS:
            if field in row:
                trimmed_row[field] = row[field]
        return trimmed_row

    def __enter__(self):
        return self

    def __iter__(self):
        return (self._trim_row(dict(row)) for row in self.reader)

    def __next__(self):
        return self._trim_row(dict(next(self.reader)))

    def __len__(self):
        return len(list(self.reader))

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file_obj is not None:
            self.file_obj.close()

if __name__ == '__main__':
    with CSVHandler('file_name.csv').read_file() as csv_h:
        for rows in csv_h:
            pass

Another suggestion that I can give you is to know what you are importing and import just what you need. So, import os should be replaced with from os import path and remove os. from if os.path.isfile(self.file_path): and if os.path.exists(self.file_path):.

Following this, you will understand your code better, and you will be able to ask more specific questions about it.


Basic functions (sum, len, etc.) with recursively-flattened arguments

That is an inappropriate use of an assertion. You should only assert conditions that you know must be true. Furthermore, you must not rely on assertions for correct execution of your program, since assertions can be disabled.

I would also add that I find the execution flow in flatten() difficult to follow.


Your stack implementation is terrible, and so is @hc_dev: neither handles memory correctly.

Resource Handling

It is generally frowned upon to call new and delete directly, simply because doing it correctly is hard.

Proper resource handling requires:

Thinking about moves.
Thinking about copies.
Thinking about destruction.

This used to be called the Rule of 3 in C++03 (Copy Constructor, Copy Assignment Operator and Destructor) and is called the Rule of 5 since C++11 (+Move Constructor, +Move Assignment Operator).

Your current Stack implements neither of those 5 operations correctly -- it doesn't implement them at all, and the default generated operations are buggy due to your use of a raw pointer.

The best advice for resource handling, though, is to use the Rule of Zero: just delegate it to something that works!

In your case, look into std::unique_ptr and std::make_unique!

Corrected resource management:

struct StackElement {
    char value;
    std::unique_ptr<StackElement> next;

    StackElement(char value, std::unique_ptr<StackElement> next) :
        value(value), next(std::move(next)) {}
};

struct Stack {
    std::unique_ptr<StackElement> top = nullptr;

    bool isEmpty() { return top == nullptr; }

    void push(char value) {
        top = std::make_unique<StackElement>(value, std::move(top));
    }

    char pop() {
        assert(!isEmpty());

        char toBeReturned = top->value;

        top = std::move(top->next);

        return toBeReturned;
    }
};

This struct is no longer copiable, as std::unique_ptr is not copiable.

Limited stack depth.

The previous rewrite is good, but its destructor suffers from stack overflow (!).

That is, when the destructor is executed, you get:

Call destructor of Stack
Call destructor of Stack::top
Call destructor of StackElement (stack->top)
Call destructor of StackElement::next.
Call destructor of StackElement (stack->top->next)
...

To handle this, create a clear method, and manually write the destructor.

struct Stack {
    // ...

    Stack(Stack&&) = default; // automatic generation is disabled when
                              // the destructor is explicit, so explicitly
                              // ask for it.

    Stack& operator=(Stack&&) = default; // automatic generation...

    ~Stack() { clear(); }

    void clear() {
        while (!isEmpty()) {
            pop();
        }
    }
};

General

Once you have the memory part correct, further improvements:

Encapsulation: do not expose your privates.
Generalization: make it work for any type.

This yields:

//  No need for a class here, it's internal.
template <typename T>
struct StackElement {
    StackElement(T value, std::unique_ptr<StackElement> next):
        value(std::move(value)), next(std::move(next)) {}

    T value;
    std::unique_ptr<StackElement<T>> next;
};

template <typename T>
class Stack {
public:
    ~Stack() { this->clear(); }

    Stack() = default;

    Stack(Stack&&) = default;
    Stack& operator=(Stack&&) = default;

    bool isEmpty() const { return this->head == nullptr; }

    T const& top() const {
        assert(!this->isEmpty());

        return this->head->value;
    }

    void clear() {
        while (!isEmpty()) {
            this->pop();
        }
    }

    void push(T value) {
        //  Create empty node first, in case moving `value` throws an exception.
        auto neo = std::make_unique<StackElement<T>>(std::move(value), nullptr);

        neo->next = std::move(this->head);
        this->head = std::move(neo);
    }

    T pop() {
        assert(!isEmpty());

        //  Pop top first, in case moving `current->value` throws an exception.
        auto current = std::move(this->head);
        this->head = std::move(current->next);

        return std::move(current->value);
    }

private:
    std::unique_ptr<StackElement<T>> head;
};

Miscellaneous

There are few nits in your main:

There is no need to allocate Stack on the heap, just Stack stack; works.
Don't use std::endl, just use '\n' or "\n".

std::endl both appends \n and calls flush, the latter kills all performance benefit of internally buffering.

With that in mind, the rewritten main is:

int main() {
    Stack<char> stack;
    std::cout << "Created a stack at " << &stack << "\n";

    int number_of_inputs;
    std::cout << "Enter the number of elements you want to push at the stack: ";
    std::cin >> number_of_inputs;

    for (int i = 0; i < number_of_inputs; i++) {
        char input;
        std::cin >> input;
        stack.push(input);
    }

    std::cout << "- - - - - - - - - - - - - - - - " << "\n";
    std::cout << "Displaying content of the stack: " << "\n";

    while (!stack.isEmpty()) {
        std::cout << stack.pop() << "\n";
    }

    return 0;
}


You can use CASE statements in the ORDER BY clauses to decide which sort order to use:

  SELECT (...)
ORDER BY CASE @OrderBy
           WHEN 'JobNumberDESC' THEN sk.jobnumber
           WHEN (etc.)
         END DESC,
         CASE @OrderBy
           WHEN 'JobNumberASC' THEN sk.jobnumber
           WHEN (etc.)
         END ASC;

(You would have to split up the ascending and descending sort options like that)

One issue with that approach, though, is that in your original statement, I count four places where the ORDER BY statement occurs.  That would mean repeating the long CASE statement a lot.  I think we can fix that, though.

First off, sorting in a subquery usually doesn't make much sense.  I don't see any reason to have keys and selectedkeys sorted, so let's remove those ORDER BY statements.

Now we're left with two ORDER BYs: the one used in the ROW_NUMBER function and the final sort.  No matter what, you need to include the ORDER BY in the ROW_NUMBER function to make sure your paging works correctly, but here's the thing: now you can use that row number to sort the final result (i.e., change the final ORDER BY sk.jobnumber DESC to ORDER BY sk.rn).  Now there's only one place where you need the dynamic ORDER BY clause, which is a lot better than four!

Disclaimer: I haven't tested these ideas; just brainstorming.

Another option would be to use dynamic SQL.  Then you'd have something like this:

DECLARE @OrderByClause varchar(500),
        @sql           varchar(max);

SET @OrderByClause =
    CASE @OrderBy
      WHEN 'JobNumberDESC' THEN 'sk.jobnumber DESC'
      WHEN (etc)
    END;

SET @sql = 'WITH keys
    AS (SELECT TOP (@PageNumber * @PageSize)
        ROW_NUMBER() OVER (ORDER BY ' + @OrderByClause + ') AS rn' +
    (etc.);

EXEC sp_executesql @sql, (etc.);

Just make sure you pay attention to the SQL injection threat.


Reg expression for finding expression in sentence

Since you only have two characters to compete with, namely, < and >, use a character set. Other than that, you might consider \d matching your digits, instead of 0-9 as \d covers the numerical characters across the entire UTF8 range.

The final expression would be:

duration\s*([<>])\s*(\d+)

I've left the matching groups in place, considering that you might be referencing them in your later code.


One thing you could do is create functions to call instead of writing each sub function out every time you want to animate something.

var hideText = function(element) {

    $('#menu ' + element).stop().animate({
      width: '0px',
      opacity: 0
    }, $('#menu ' + element).hide);
}

var showText = function(element, elementWidth) {

    $('#menu ' + element).stop().show().animate({
      width: elementWidth,
      opacity: 1
    });
}

Now you can call this like this, with less repeated code:

  $('#menu').hover(
    function() { // mouseenter

      hideText('span');
      showText('a', '100px');
    },
    function() { //mouseleave

      hideText('a');
      showText('span', '250px');
    });
});

$(document).ready(function() {

  var hideText = function(element) {

      $('#menu ' + element).stop().animate({
        width: '0px',
        opacity: 0
      }, $('#menu ' + element).hide);
  }

  var showText = function(element, elementWidth) {

      $('#menu ' + element).stop().show().animate({
        width: elementWidth,
        opacity: 1
      });
  }

  $('#menu').hover(
    function() { // mouseenter

      hideText('span');
      showText('a', '100px');
    },
    function() { //mouseleave

      hideText('a');
      showText('span', '250px');
    });
});
#menu {
  width: auto;
}
#menu * {
  overflow: hidden;
  white-space: nowrap;
  font-size: 30px;
  text-align: center;
}
#menu a {
  display: none;
  width: 0px;
  opacity: 0;
}
#menu span {
  display: inline-block;
  width: 250px;
}

    Hover for items!
    Item 1
    Item 2
    Item 3


Creating an enumerator based on an ATL collection

Okay, I finally got this working. Here are my results after hours of trying to get this right:

Alternatively it is possible to use a while-loop, which feels somehow more natural, a little bit like a foreach loop:

POSITION pos = m_coll.GetStartPosition();

while (pos != nullptr)
{
    IItem* entry = m_coll.GetNextValue(pos);
    entry->get_Address(&address);
}

Speaking of foreach, I wrote a small macro that makes it possible to actually write it like a foreach-loop:

#define FOREACH(T, entry, collection) \
    POSITION pos = collection.GetHeadPosition(); \
    T entry; \
    while (pos != nullptr && (entry = collection.GetNextValue(pos)) != nullptr)

Now a loop can be written like this:

FOREACH(IItem*, item, m_coll)
{
    item->FooBar();
}

However this only works for CRBMaps, for CAtlMap you have to change the macro to use GetStartPosition() instead (Hooray consistent design!). For other collections this needs to be changed entirely. Also for initializing the enumerator is easier with the traditional for-based apprach, as shown below.
Turns out that the best way appears to be using a traditional old-fashioned array, because that's the fastest and simplest way to store data inside the enumerator. The initialization then receives a pointer to the first and a pointer to the first element after the last one of the array. The third parameter is used to keep the host of the enumerator (typically the creator/this) alive. If IUnknown is ambigouos here, use this->GetUnknown();.
The flag was chosen right in this scenario, because the array storing a snapshot of entries that can be iterated is out of control after the enumerator has been created and therefor also needs to released by the enumerator.
That's another plus for an traditional array.

Here's the complete code:

STDMETHODIMP CCollectionOnATL::get_NewEnum(IEnumITEM** enumerator)
{
    // Define the type of the enumerator.
    typedef CComEnum<IEnumITEM, &IID_IEnumITEM, IItem*, _CopyInterface<IItem>> IItemEnumerator;

    // Copy all elements to an array that can be iterated.
    size_t elements = m_coll.GetCount();
    IItem** items = new IItem*[elements];
    POSITION pos = m_coll.GetHeadPosition();

    for (size_t element = 0; element < elements; element++)
    {
        IItem* item = m_coll.GetNextValue(pos);

        // Add a reference of the current item to the enumeration.
        item->AddRef();
        items[element] = item;
    }

    // Create an enumerator for the array.
    CComObject<IItemEnumerator>* pEnum = new CComObject<IItemEnumerator>();
    HRESULT hr;

    if (FAILED(hr = pEnum->Init(&items[0], &items[elements], this->GetUnknown(), ATL::AtlFlagTakeOwnership)))
        return hr;

    return pEnum->QueryInterface(enumerator);
}


Throw an exception which contains a nested set of previous exceptions

The other way you could do this, noting that you don't actually use the return value of useOption, is to have it return an error message or false, along the lines of:

function findAnOption()
{
    $problems = array();

    $possibilities = array(1, 2, 3, 4);
    foreach ($possibilities as $possibility)
    {
        $problem = useOption($possibility);
        if ($problem === false) return $possibility;
        $problems[] = $problem;
    }
    throw new SomeExceptionType($problems);
}

function useOption($x)
{
    if ($x < 5) {
        return "useOption(): $x is too small";
    }

    // No problems
    return false;
}

The exception approach can certainly be clearer, and I wouldn't discard it just because it's "using exceptions for control flow". Exceptions are always control flow: the question is whether they're the appropriate one for a given case.

However, I would make one change: I prefer the name AggregateException (stolen unashamedly from Microsoft's .Net API) to ExceptionWithCauses.


Getting the dominant RGB color of a bitmap

If we look at your for loop very carefully we can see that you can eliminate two multiplications:

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        for (int color = 0; color < 3; color++) {
            int idx = (y * stride) + x * 4 + color;
            totals[color] += p[idx];
        }
    }
}

You don't use y except for y * stride, and you don't use x except for x * 4, rewrite the for loop and you can eliminate those entirely.

var heightLimit = height * stride;
var widthLimit = width * 4;

for (int y = 0; y < heightLimit; y += stride) {
    for (int x = 0; x < widthLimit; x += 4) {
        for (int color = 0; color < 3; color++) {
            int idx = y + x + color;
            totals[color] += p[idx];
        }
    }
}

By removing all three multiplication operations, we effectively reduce the amount of work we do by a significant portion. (There are roughly 8 instructions in the original, and 6 in the reduced, so we've eliminated 25% of our work.)

Other than that, there really isn't much you can do. You could consider chunking the work, then only recalculate the regions that were re-drawn if that's reasonable, you could also chunk and thread it (this wouldn't reduce CPU usage but it would reduce time spend on this method).

With as frequently as you call this method, the next lines may be a potential for optimization as well:

int avgB = totals[0] / (width * height);
int avgG = totals[1] / (width * height);
int avgR = totals[2] / (width * height);

Why do width * height in all three calculations? Why not store var pixelCount = width * height; then divide by pixelCount? Of course, division is still slow, but you're not using floating-point math so we can't use the reciprocal of it.

You could consider, as mentioned in a comment, using CUDA/OpenGL/GPU-level work. Basically, operating on the GPU itself instead of using the CPU to do what could be very efficient on the GPU. (It's built specifically for this type of processing.) There is at least one Stack Overflow question on running C# code on the GPU, it's not very easy or simple, but it can give you a lot of power.


Determine if Class B uses Class A ( Java Reflection)

Is my test holistic, that is, did I test for everything?

Currently, this is what you're testing for:

Declared fields on the class with getDeclaredFields();
A superclass with getSuperclass();
The parameters of the declared constructors with getDeclaredConstructors();
The parameters of the declared methods with getDeclaredMethods().

This is what you are not testing for:

Inherited fields: they are not returned by the call to getDeclaredFields(), so fields inherited from superclasses are not considered;
The method return type: you are just checking for the type of the parameters but not the return type with getGenericReturnType();
Annotations on the method (getAnnotations()), on the method parameters (getParameterAnnotations()) or on the method return type (getAnnotatedReturnType());
Annotations on the class itself with getAnnotations();
Exceptions declared to be thrown by the methods with getGenericExceptionTypes(), in the same way, the exceptions declared to be thrown by the declared constructors are also not considered;
All the hierarchy of the class: you are only testing for the potential superclass, but not for the potential implemented interfaces or the super-superclasses;
If the given class is an array type, you are not testing its component type with getComponentType().
For the generic types returned by getDeclaredFields() or getGenericReturnType() for example, you can access the actual type argument by casting the type to ParameterizedType and call getActualTypeArguments(). This will return an array of all the type argument of the parameterized type. For example, if a declared field is a Map<String, Integer>, it will return the array [class java.lang.String, class java.lang.Integer].

  Are there any bugs in the code?

Yes, there is a potential bug: getSuperclass can return null:

  If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned

so you need to take care about handling that. Your current code is

if(b.getSuperclass().getName().equals(a.getName()))

which could throw a NullPointerException.

Other comments:

Make sure to always use curly braces, even if it is not strictly needed here. It will make the code less error-prone for the future.
This only uses the Reflection API. Determining whether a given class A truly uses a given class B or not would require going into the byte-code to see if there are any references through chained method calls, import statements or local variables.


Stack implemented using linked list in x86_64 assembly

The code is generally well written and easy to understand, but I have a few comments on it that could help improve it.

Eliminate "magic numbers"

In the StackCreate routine, the first instruction is mov rdi,24 but it's not clear what 24 signifies in this context.  Either a comment or a named constant or both would help with that.

Add more meaningful comments

The stack structure is not very clear from the comments.  We can infer that the stack consists of nodes, but it's not easy to tell from the code or the comments.

Also, consider the user of the stack code.  There isn't currently enough within the code to understand the calling sequence, register usage or return values.  All of those would be useful to have in the comments.  If you're intending to use a standard ABI, it would be useful to say which one.

Use rep ret as appropriate

The gcc compiler emits rep ret when the ret could be the target of a jump.  This seems weird (and it is!) but the reason is that the branch prediction logic on both AMD and Intel processors works better when the ret is not the target of branch.  So this means the StackFirst_end label in your code should actually have a rep prefix just before the ret.

Use struc as appropriate

Because your stack uses two structures, it would benefit from using NASM's struc/endstruc macros.  This would both make it more clear when the code is manipulating data structures and also eliminate quite a few of the "magic numbers" I mentioned earlier.

Consider refactoring StackFirst and StackNext

Other than minor differences in specific register selection, the StackFirst and StackNext routines are very similar.  It may be possible to combine them to eliminate some code.

Reduce use of malloc and free

The malloc and free calls tend to be relatively computationally expensive, especially relative to the assembly code you've got.  For that reason, it would probably make more sense to either allocate and manage a block rather than calling malloc for every stack push, or to replace calls to malloc and free with some other memory allocation scheme that might be user-replaceable for speed.

Rearrange the loop to avoid unconditional jumps

The current pushing_loop looks like this:

    pushing_loop:
      test r13, r13
      jz pushing_done
      mov rdi, r14
      mov rsi, [r12]
      call StackPush
      add r12, 8
      dec r13
      jmp pushing_loop
    pushing_done:

However, it could be slightly rearranged to eliminate one of the jumps:

      inc r13
      jmp push_test

    pushing_loop:
      mov rdi, r14
      mov rsi, [r12]
      call StackPush
      add r12, 8
    push_test:
      dec r13
      jnz pushing_loop

The unconditional jump is only made once at the top of the loop and all other iterations use only the conditional test at the bottom of the loop.  There are a few other places in the code this could be applied.