How can I solve my constructor injection code architecture?

Your question isn't crystal-clear about what it is exactly that your code is supposed to be doing. We have to infer the functionality from this block of code:

public void Start()
{
    List<Network> networks = context.Networks.ToList();

    foreach (var network in networks)
    {
        // create new client...but also
        // new client gets injected with module factory
        // module factory then populates modules based on client
        IIrcClient ircClient = this.ircClientFactory.Create();
        ircClient.Connect(network);
        this.clients.Add(ircClient);
    }
}

This code involves [what appears to be] private fields that you haven't included. I'll assume the following:

private readonly Context context;
private readonly IrcClientFactory factory;

If I read this correctly, your Bot class is depending on concrete types; they should be abstractions, like IContext and IIrcClientFactory (the latter being an abstract factory).

  Naming - Private Fields

  This might be of personal preference, but I like my private fields prefixed with an underscore. Having _context and _factory removes the ambiguity in the constructor and then the this qualifier becomes redundant:

public Bot(Context context, IrcClientFactory factory)
{
    _factory = factory
    _context = context
}

The comment // injected factory is a useless one; prefer XML comments for that purpose:

 /// <summary>
 /// Creates a new instance of a Bot.
 /// </summary>
 /// <param name="context">The data context.</param>
 /// <param name="factory">A factory that creates IrcClient instances.</param>
 public Bot(Context context, IrcClientFactory factory)
 {
     _factory = factory
     _context = context
 }

As a bonus, you'll get instant IntelliSense support for your constructor and its parameters.

Back to the foreach loop; the code you have here doesn't seem to be using the fields you've initialized in your constructor:

IIrcClient ircClient = this.ircClientFactory.Create();

I would have expected:

IIrcClient ircClient = this.factory.Create();

I would rewrite it like this:

var client = _factory.Create();

  Implicit Typing

  The abstract factory shouldn't be revealing the implementation of its product to its client; the factory's Create() method should be returning an implementation for IClient, and shouldn't have to even know what possible implementations the factory can spit out. Your code is expecting an IIrcClient which is an abstraction, but from the rest of your code I infer that IIrcClient extends the IClient interface. Bottom line, the code doesn't care what type is returned, and it should be working against all implementations of IClient (assuming Connect(Network) is a member of IClient).

  Implicit typing not only makes your code shorter and easier to read, it also emphasize that you don't really care what the actual type is.

After creating a client, the loop's body passes the network to the client through its Connect method, and then the client gets added to yet another unmentioned field, assuming:

private readonly _clients = new List<IClient>();`

public void Start()
{
    var networks = context.Networks.ToList();
    foreach (var network in networks)
    {
        var client = _factory.Create();
        client.Connect(network);
        _clients.Add(client);
    }
}

If the network parameter is passed into a field of the client, and used anywhere other than in the Connect method, it would probably be best to constructor-inject the network into the client inside the factory method. If it's passed into a field of the client but isn't used anywhere other than the Connect method, it would be best to constructor-inject the network into the client inside the factory method; what I'm trying to get to, is that constructor injection should always be prioritized over other forms of injections, whenever possible. In this case, I'd probably call the IClient implementation something like ConnectedClient and inject the network through the Create method, which returns an IClient with a connection, as the ConnectedClient implementing class' name says.

Reviewing the rest of this code is very hard, I'm not seeing all the pieces of the puzzle that I'd like to see in order to be confident in anything else I'd have to say.


Artificial Neural Network Classifier in Matlab

I'm not a code reviewer, but I'd like to comment on the design of your network, which you certainly seem to be doing just fine.

It might be rather difficult to make any judgment, given that the application is undefined, while it seems you are designing a neural-network based detector.
Numerically speaking, you might focus on your validation performance, by constantly redesigning your network architecture (e.g., number of hidden layers, number of hidden neurons, reducing and increasing batch sizes, training functions/methods as you mentioned, etc.), input preprocessing (e.g., smoothing, input interpolation or extrapolation in case possible, artifact removal, etc.).
Not knowing what your datasets might be and how sophisticated that may be, you may focus on 10^-3 to 10^-6 convergence range. It might increase the performance (e.g., confusion matrices) of your network.

Overall, it seems your input is pretty stochastic. Input preprocessing may be worth looking into.


Script to group files by extension and unzip archives

I don't see where awk fits in this. I'm going to point out a few problems in your script, so you'll at least get something useful out of this. But please do tell us what you're actually trying to do.

IFS=$(echo -en "\n\b")

There's a simpler way of writing that in bash: IFS=$'\n\b'. I don't understand why you're setting $IFS to include a backspace character; and whatever need you may have found to set IFS is probably caused by other problems that I'll point out below.

echo "trigger took place in $(pwd)"

There's a variable $PWD that contains the current working directory. $PWD is equivalent to $pwd and a little faster.

for i in $( ls -1); do

Do not parse the output of ls. ls is a tool for displaying the attributes of files. The shell has a perfectly good construct for listing files in a directory: wildcards. Make this for i in *; do … This way has the advantage that it can cope with arbitrary file names; parsing the output of ls will always choke on some “strange” file names.

fileext=${i##*.}

You should use this variable below.

mkdir archive

If you run this part multiple times, the directory will already exist. Test for the directory's existence first, or call mkdir -p archive.

mkdir $(pwd)/archive/${i%%.*}

Again, $PWD. Except that there's no point in using it, a relative path would do. Also, you need double quotes around all variable and command substitutions; otherwise the shell splits the result of the substitution at $IFS characters, then interprets the pieces as glob patterns (file name wildcards) and expands them. Always put double quotes around variable and command substitutions unless you know why you need to leave them off.

Another point: ${i%%.*} strips everything after the first . in the file name. This is not compatible with the definition of $fileext. To get the file except for its last extension, use ${%.*} (truncate at the last .).

$(unzip $i -d $(pwd)/archive/${i%%.*})

I don't know what you're trying to do here, interpreting the output of unzip as a shell snippet. Again, double quotes around variable substitutions.

  mkdir ${i##*.}

Again, double quotes. Also, if the file name sans prefix happens to begin with a -, the mkdir command will interpret its argument as an option. To avoid this, use -- to indicate the end of the option list (this is a convention that most utilities respect): mkdir -- "${i##*.}"

Also, there's a case you don't handle: what if the file name contains no .? In that case, mkdir will attempt to overwrite the file (and fail). One solution is to create the directory with a temporary name, move the file, then rename it.

Here's the fixed code:

#!/bin/bash
#File sorter
set -e    # Abort in case of error
SECONDS=0
SAVEIFS=$IFS
echo "trigger took place in $PWD"
for i in *; do
  echo "processing $i ..."
  case $i in
    *.zip)
      [ -d archive ] || mkdir archive
      mkdir "archive/${i%.*}"
      unzip -d "archive/${i%.*}" "./$i";;
    *.*)
      mkdir -p "${i##*.}"
      mv -- "$i" "${i##*.}/";;
    *)
      tmp=$(TMPDIR=. mktemp -d)
      mv -- "$i" "$tmp/"
      mv -- "$tmp" "$i";;
  esac
done
echo "Done in $SECONDS seconds!"


Iterative implementation of the Ackermann function

The results of the Ackermann function can grow quite large. An int is only guaranteed to cover up to 32767.

A two-dimensional memorization table would probably be worthwhile.


Algorithm that generate all possible strings from N Tuples. Found Brute Force version, Recursive Version uses a Tree?

The operation you're looking for is known as a Cartesian product on sets. An implementation of Cartesian product for Java Lists is somewhat as follows (all Lists have the same generic type T, otherwise we have to violate type safety, see below):

import java.util.Set;
import java.util.List;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Arrays;

class CartesianProduct {
  // Set ensures that entries are unique
  private static <T> Set<List<T>> cartesianProduct2(Set<List<T>> accumulator, List<T> iterable) {
    // LinkedHashSet preserves insertion order, unlike HashSet
    Set<List<T>> product = new LinkedHashSet<>();
    for(List<T> elementAccumulator : accumulator) {
      for(T item : iterable) {
        // copy-on-write to ensure we don't change the arguments
        List<T> newElementAccumulator = new LinkedList<>(elementAccumulator);
        newElementAccumulator.add(item);
        product.add(newElementAccumulator);
      }
    }
    return product;
  }

  @SafeVarargs
  public static <T> Set<List<T>> cartesianProduct(List<T>... iterables) {
    // accumulator for fold
    Set<List<T>> product = new LinkedHashSet<>();
    // initialize accumulator to first iterable
    for(T item: iterables[0]) {
      // maintain the structure of the data
      List<T> elementAccumulator = new LinkedList<>();
      elementAccumulator.add(item);
      product.add(elementAccumulator);
    }
    // fold the rest of the iterables under the dyadic Cartesian product operation
    for(int i = 1; i < iterables.length; ++i) {
      product = cartesianProduct2(product, iterables[i]);
    }
    return product;
  }

  public static void main(String[] args) {
    List<String> set1 = Arrays.asList(new String[]{"A", "B", "C", "D"}),
                set2 = Arrays.asList(new String[]{"E", "F", "G", "H"}),
                set3 = Arrays.asList(new String[]{"I", "J", "K", "L"}),
                set4 = Arrays.asList(new String[]{"M", "N", "O", "P"});

    List<String> output1 = new ArrayList<>();
    for(List<String> item : cartesianProduct(set1, set2, set3, set4)) {
      output1.add(String.join("", item));
    }

    String[][] arr = { {"A", "B", "C", "D"}, {"E", "F", "G", "H"}, {"I", "J", "K", "L"}, {"M", "N", "O", "P"} };

    List<String> output2 = new ArrayList<>();
    for(int i = 0; i < 4; i++){
      for (int j = 0; j < 4; j++){
        for (int k = 0; k < 4; k++){
          for (int l = 0; l < 4; l++){
               output2.add(arr[0][i] + arr[1][j] + arr[2][k] + arr[3][l]);
          }
        }
      }
    }
    System.out.println("Actual -> Expected");
    for(int i = 0;i < Math.min(output1.size(), output2.size()); ++i) {
      System.out.println(output1.get(i) + " -> " + output2.get(i));
    }
    System.out.println(output1.size() == output2.size());
    System.out.println(output1.equals(output2));
  }
}

Unfortunately, this is more of a code dump, but this is the same thing itertools.product does in Python, and here's a more succinct Scala version of the core idea:

def cartesianProduct[S](vectors: Traversable[S]*): Traversable[Seq[_]] =
    cartesianProductMultiType(vectors)

  def cartesianProductMultiType(vectors: Traversable[Traversable[_]]): Traversable[Seq[_]] = {
    def cartesianProduct2[A, B](leftVector: IndexedSeq[IndexedSeq[A]], vector2: Traversable[B]): IndexedSeq[IndexedSeq[_]] =
      for {
        superSequence <- leftVector
        element <- vector2
      } yield superSequence :+ element

    vectors.foldLeft(IndexedSeq(IndexedSeq[Any]()))(cartesianProduct2(_, _)).distinct
  }

(This is in fact what I translated into Java, having coded this much earlier for a personal project).

This is not as memory-efficient as @coderodde's iterator version, but it is algorithmically simpler and easier to understand, I hope.

I put in a few tests in main so that you can check that this code does the same thing as yours.

Note that here you can replace the List<T> iterable and List<T>... iterables with Iterable<T> iterable and Iterable<T>... iterables to get an even more general version of the code which can find the Cartesian product of any collection of Iterables. Here, you should also swap

for(List<T> elementAccumulator : accumulator) {
      for(T item : iterable) {
          ...
      }
}

to

for(T item : iterable) {
      for(List<T> elementAccumulator : accumulator) {
          ...
      }
}

to ensure that you don't consume the iterator of iterable multiple times - creating the iterator might be expensive or slow, say reading from a file. This'll make the output come out in a different order from what you give us - it'll be a post-order traversal instead of a pre-order one (see below).

Since @coderodde has already addressed the main point of iterators and memory-efficiency, this is more educational as you were asking for a recursive solution. Although this particular solution is not recursive, it does utilize the concept of divide-and-conquer with a base case, so it should be helpful to you.

About trees: see if you can recognize the tree structure in this program.

Hint: it is a balanced \$n\$-level tree where \$n\$ is the number of tuples, with each node having \$\left|T_i\right|\$ children, where \$\left|T_i\right|\$ denotes the number of elements in tuple \$T_i\$. In fact, the \$i^\text{th}\$ level is just the elements of \$T_i\$ repeated as the children of every node of level \$i-1\$. The output of this program is a depth-first search with pre-order traversal of this tree, splitting the output into words at each backtrack (recursion unwind). The output at any given point during the execution is the path traversed in the tree till that point.

An exercise - try writing a program which explicitly makes this tree and prints every path from each root to each leaf, splitting the output into words at each backtrack.

Here's an example tree for the set of tuples {('A','B'), ('C', 'D'), ('E', 'F'})} (note how each required word is the pre-order path from the empty root to a leaf):

Also, take a look at these data structures - Trie and Suffix Tree.


How do I put $db in a central location, but maintain variable scope

You can't find the correct answer until your code is just a bunch simple PHP scripts. The ultimate solution would be is to use a dependency injection container and resolver where sou can say for example a PDO instance to keep in use until the request ends (in PHP this would be a singleton behavior).

If you can't rewrite your whole system to have an object oriented design to have the ability to use a DI container then the only thing you could do is to create a class loader in your bootstrap section to load a factory.

A Factory is a simple class which can build object instances like a DatabaseFactory::CreateNewConnection would return a new PDO instance. You can create a static factory but that would be as flexible as the pig-iron. A recommend you to have a static DatabaseBuilder class there you can register a DatabaseFactory class instance as the default database factory and your factory can hold a database class instance until the request ends. Here is the skeleton:

<?php

class DatabaseFactoryBuilder {

    private function __construct() {}

    public static function SetFactory(IDatabaseFactory $factory) {
        $this->_factory = $factory;
    }

    public static function GetFactory() {
        return $this->_factory;
    }

}

interface IDatabaseFactory {
    function GetDatabase();
}

class DatabaseFactory implements IDatabaseFactory {

    /* ... */

    private $_db;

    public function __construct($dbServer, $dbName, $dbUser, $dbPassword) {
        /* ... */
    }

    public function GetDatabase() {
        if ($this->_db == NULL) {
            $this->_db = new PDO(/* ... */);
        }

        return $this->_db;
    }

}

Ofcourse as you can se you have to create a decent way to set the connection properties for your database.


The most obvious mistake — which makes your code malformed HTML — is the extra < before TYPE:

<P>ADDRESS<INPUT

<TYPE="TEXT" … />

The next biggest issue, in my opinion, is that your <P> tags aren't consistently being closed.  Only in the earliest days of HTML was it acceptable to use an unclosed <P> as a line break.  These days, it's generally accepted that paragraphs should lie between <P> and </P>.

The next thing you should do is to add a doctype declaration at the very beginning, which tells the browser which version of the HTML standard is being used.  Without the doctype, browsers will interpret the document in slightly non-standard ways, especially if you use CSS.  If you have no preference for any particular doctype, use HTML5:

<!DOCTYPE html>
<html>
    ...
</html>

Once you have declared a doctype, you can then run the code through an HTML validator, which will tell you everything else that is syntactially incorrect.  For example, it's OK to say

<option selected="selected">...</option

or

<option selected>...</option>

but not

<option selected="true">

HTML is case-insensitive, but you should choose either uppercase or lowercase consistently anyway.  Since XHTML mandates lowercase, I recommend using lowercase everywhere too, even if you are using HTML instead of XHTML.

Oddly, your form has no <form> tag.


Formatting seconds as days hours minutes seconds

Try this. It uses a string-based stream to do formatted output. Let the stream put in leading zeroes. When you're done with your output, the str() method returns (a copy of) the embedded string.

#include <time.h>
#include <sstream>
#include <iomanip>

std::string eta_string ( int64_t s )
{
    time_t seconds ( s );
    tm p;
    gmtime_s ( &p, &seconds );

    std::ostringstream os;

    if ( p.tm_yday > 0 )
        os << p.tm_yday << (p.tm_yday == 1 ? " day " : " days ");

    os << std::setfill('0') << std::setw(2) << p.tm_hour << ':' <<
        std::setfill('0') << std::setw(2) << p.tm_min << ':' <<
        std::setfill('0') << std::setw(2) << p.tm_sec;

    return os.str();
}


Wordcloud from all answers of a user here on CR

Quick bits

You have some issues that some linters would pick up:

I would suggest moving your main code into a function. So that it doesn't pollute the global namespace.
You've got some trailing whitespace.
Add some docstrings to your code. Even something basic like "Fetch words in answers."
Your imports are kinda all over the place. I can't make any sense of them, and so I think they're just randomly placed there as and when you needed them.
I don't think print is the best tool for logging. I would suggest using logging.

Async

I'm not a fan of your current fetch and fetch_all functions. I would prefer it if fetch only called session.get. This may seem strange, but it means that you can change your code to allow for caching of objects or easier logging.

Given that I've not done any of this I've left it returning just a plain RequestContextManager. However if I were to expand on this I would change it to my own custom class. This is because then you can keep the data you want / need such as the page body in a cache. Using your own class also means that can guarantee values will exist, and hide ones you can't guarantee.

Moving the content of the old fetch into a fetch_all_words allows almost the exact same code, and allows us to build the word list without the use of a convoluted itertools and asyncio one-liner.

Interestingly since the majority of the content of the fetch_all_words function is not async code, there is little to no performance difference between using asyncio.as_completed and asyncio.gather. In a small test function I found that asyncio.as_completed performs as well or better than asyncio.gather.

Finally I make main an async function, as calling asyncio.run(main()) is simpler than building a loop and running until completion.

"""Stack Exchange word cloud generator."""
import asyncio
import logging
import itertools
import operator

import aiohttp
import bs4
import nltk.tokenize
import matplotlib.pyplot as plt
import stackexchange
import wordcloud

API_KEY = '**redacted**'
CR = stackexchange.Site("CodeReview", API_KEY)

STRAINER = bs4.SoupStrainer(
    'div',
    attrs={'class': ['answer', 'answer accepted-answer']}
)

async def fetch(session, url):
    return url, await session.get(url)

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        for task in asyncio.as_completed(tasks):
            yield await task

async def fetch_all_words(answers):
    words = []
    async for url, resp in fetch_all(answers):
        answer_id = answers[url]

        async with resp as response:
            page = await response.text()
        soup = bs4.BeautifulSoup(page, "lxml", parse_only=STRAINER)
        answer = soup.select_one(f'div#answer-{answer_id} div.post-text')
        try:
            answer_text = answer.text
        except AttributeError:
            logging.error(url)
            answer_words = []
        else:
            logging.info(url)
            answer_words = nltk.tokenize.word_tokenize(answer_text)
        words.extend(answer_words)
    return words

async def main():
    """Main code."""
    logging.getLogger().setLevel(logging.INFO)

    user = CR.user(42401)
    user.answers.fetch()

    answers = {
        answer.url.replace(CR.domain, "codereview.stackexchange.com"): answer.id
        for answer in user.answers
    }
    words = await fetch_all_words(answers)

    plt.figure()
    wc = wordcloud.WordCloud(width=480, height=480, colormap="Blues")
    wc = wc.generate(" ".join(words))
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.margins(x=0, y=0)
    plt.show()

if __name__ == "__main__":
    asyncio.run(main())

Additional comments

The code heavily violates the SRP principle. Given that this is, I assume, an untested one-off script this doesn't matter much.

However in the future I think the changes to fetch_all makes fetch_all_words easier to split up to achieve this.
I have butchered your style.
This may be hard to believe but I rewrote the code around three times. I've not changed much, but I don't think much needs to be changed. I mostly focused on trying to get fetch_all and fetch a way I like.

Whilst I like my style more, it's not intended to be some subtle hint yours is bad.
You have a bug apparently "n't", "ll", "n't use" and "ca n't" are words I commonly say.
Also, "n't" appears on your image too.
Thanks for posting this, it was a fun little puzzle. First time I'd really looked into asyncio too!


Deep nesting when looping over an object model coming from a 3rd part

First of all, I would realise that

var levelOneEnumerator = rootObject.GetEnumerator();
while (levelOneEnumerator.MoveNext())
{
    var levelOneItem = levelOneEnumerator.Current as Foo_LevelOneItem;
    if (levelOneItem == null) continue;

is equivalent to the much shorter

foreach (var levelOneItem in rootObject.OfType<Foo_LevelOneItem>())
{

Then you will realise that you have several nested foreach loops which make for nicely-readable single-line nestings. So factor all the multi-line code into methods of its own. The end-result I got looks like this:

foreach (var levelOneItem in rootObject.OfType<Foo_LevelOneItem>())
    foreach (var levelTwoItem in levelOneItem.LevelTwoItems.OfType<Foo_LevelTwoItem>())
        yield return new FooBarsCollection
        {
            Prop1 = levelTwoItem.Prop1,
            Prop2 = levelTwoItem.Prop2,
            Prop3 = levelTwoItem.Prop3,
            FooBars = getFoobars(levelTwoItem)
        };

[...]

private static List<FooBar> getFoobars(Foo_LevelTwoItem levelTwoItem)
{
    var foobars = new List<FooBar>();

    foreach (var levelThreeItem in levelTwoItem.LevelThreeItems.OfType<Foo_LevelThreeItem>())
        foreach (var levelFourItem in levelThreeItem.LevelFourItems.OfType<Foo_LevelFourItem>())
            foreach (var levelFiveItem in levelFourItem.LevelFiveItems.OfType<Foo_LevelFiveItem>())
                foreach (var levelSixItem in levelFiveItem.LevelSixItems.OfType<Foo_LevelSixItem>())
                    processLevelSixItem(foobars, levelFiveItem, levelSixItem.Key);

    return foobars;
}

private static void processLevelSixItem(List<FooBar> foobars, Foo_LevelFiveItem levelFiveItem, Foo_LevelSixItemKey levelSixKey)
{
    var foobar = foobars.Where(x => x.Key == levelSixKey).FirstOrDefault();
    if (foobar == null)
    {
        foobar = new FooBar
        {
            LevelSixKey = levelSixKey,
            TransDate = levelFiveItem.TransDate,
            PaidAmount = 0
        };
        foobars.Add(foobar);
    }

    // * -1 because value should be positive, while product reports a negative (and vice versa)
    foobar.PaidAmount += (levelFiveItem.PaidAmount ?? 0) * -1;
}

Of course, you could further change this into a much more LINQy expression involving either SelectMany or the from query syntax, but to be honest, in your particular case I would leave it like this. It is very clear. In case you still want the query syntax, here is just getFoobars to give you the idea:

private static List<FooBar> getFoobars(Foo_LevelTwoItem levelTwoItem)
{
    var foobars = new List<FooBar>();

    var query =
        from levelThreeItem in levelTwoItem.LevelThreeItems.OfType<Foo_LevelThreeItem>()
        from levelFourItem in levelThreeItem.LevelFourItems.OfType<Foo_LevelFourItem>()
        from levelFiveItem in levelFourItem.LevelFiveItems.OfType<Foo_LevelFiveItem>()
        from levelSixItem in levelFiveItem.LevelSixItems.OfType<Foo_LevelSixItem>()
        select new { LevelFiveItem = levelFiveItem, Key = levelSixItem.Key };

    foreach (var info in query)
        processLevelSixItem(foobars, info.LevelFiveItem, info.Key);

    return foobars;
}


How to deal with nested objects which might be string or undefined in a clean way?

Typescript has supported optional chaining for a while. To do this concisely and avoid the somewhat inelegant as string type assertion, extract the possibly nested value into a variable, then check its typeof against string:
const instanceId = data.InstanceStatuses?.[0].InstanceId;
if (typeof instanceId === 'string') {
  instanceIds.push(instanceId);
}

This way, instanceId will be either the nested value, or, if InstanceStatuses doesn't exist, it'll be undefined. So, it'll only push to the array if the nested value exists and the value is a string.


Make external js file in ASP.NET MVC with razor path

It's good to use data-* attributes for this kind of thing. I would highly recommend avoiding generic names like data-request-url in favor of something more explicit. You are generating two different heat maps:

Stops
Driving

This feels like two explicitly named attributes would be better:

<div id="map"
     data-heatmap-stops-url="@Url.Action(...)"
     data-heatmap-driving-url="@Url.Action(...)">
</div>

Now looking at your HTML source code will give you a better idea about what these custom attributes mean.

Cleaning up repetitive code

The code to get the map points between the stops and driving points is very similar. In fact, there are only two differences:

The URL
The property within the response used to render the heat map

Consider pulling this out into its own method, and parameterizing it:

function getHeatmapData(url, propertyName) {
    $.getJSON(url,
        function (data) {
            var marker = [];

            $.each(data,
                function (i, item) {
                    marker.push({
                        'location': new google.maps.LatLng(item.Latitude2, item.Longitude2),
                        'map': map,
                        'weight': item[propertyName],
                        'radius': 10
                    });
                });
            var pointArray = new google.maps.MVCArray(marker);

            heatmap = new google.maps.visualization.HeatmapLayer({
                data: pointArray
            });
            heatmap.setMap(map);
        });
}

Then the getStops and getDriving methods are much shorter:

function getStops() {
    var url = $('#map').data('heatmap-stops-url');

    getHeatmapData(url, "Stops");
}

function getDriving() {
    var url = $('#map').data('heatmap-driving');

    getHeatmapData(url, "Speed");
}

Just plain getting crazy

You could utilize a function closure and import only the symbols you need, throw in a 'use strict'; directive.

This will:

Give you bragging rights because you used 'use strict';. There are other benefits, but from the standpoint of your script it basically does nothing. Bragging right. That's it.
Remove the need for fully qualified class names like google.map.x.Foo.
Allow your code to function even if some other JavaScript library defines a $ function

(function ($, MVCArray, HeatmapLayer, LatLng) {
    'use strict';

    function getHeatmapData(url, propertyName) {
        $.getJSON(url,
            function (data) {
                var marker = [];

                $.each(data,
                    function (i, item) {
                        marker.push({
                            'location': new LatLng(item.Latitude2, item.Longitude2),
                            'map': map,
                            'weight': item[propertyName],
                            'radius': 10
                        });
                    });
                var pointArray = new MVCArray(marker);

                heatmap = new HeatmapLayer({
                    data: pointArray
                });
                heatmap.setMap(map);
            });
    }

    this.getStops = function () {
        var url = $('#map').data('heatmap-stops-url');

        getHeatmapData(url, "Stops");
    }

    this.getDriving = function () {
        var url = $('#map').data('heatmap-driving');

        getHeatmapData(url, "Speed");
    }

})(this.jQuery, this.google.maps.MVCArray, this.google.maps.visualization.HeatmapLayer, this.google.maps.LatLng);

But at this point, we're really just being crazy.


nBytesRead ignored!

        int nBytesRead;
        while ((nBytesRead = bis.read(buffer, 0, buffer.length)) >= 0) {
            os.write(buffer);
        }

You forgot to use the nBytesRead variable when writing to the other stream, putting garbage data in the target file.

        int nBytesRead;
        while ((nBytesRead = bis.read(buffer, 0, buffer.length)) >= 0) {
            os.write(buffer, 0, nBytesRead);
        }

zipDirectory() throws a NPE

Your code throws a NullPointerException if the directory doesn't exists. (Caused by dir.listFiles(); returning null, failing the for loop after)

You should check if dir.exists is true, before continuing with the method, and throw a FileNotFoundException if it is false.

Possible IndexOutOfBoundsException

String zipFile = file.getCanonicalPath().substring(dir.getCanonicalPath()
                        .length() + 1);

While this line usually works correctly, it fails on unix systems if the file is symlinked to a directory with less characters, this will throw a IndexOutOfBoundsException


Allow one thread to execute section while others wait and resume

Use std::once_flag
The std::once_flag class basically does what you want. However, there is no way nice way to reset it, except by using a trick like placement new, or by allocating a flag dynamically, and using a std::unique_ptr to point to it for example. As indi mentioned, it's not really "once" anymore then, but it does work for your specific case. Here is a drop-in replacement for your struct Executive:
struct Executive {
  Executive(int _Id, Target &_Tgt) : m_Id(_Id), m_Tgt(_Tgt) {}
  void update() {
        std::call_once(flag, [this]{ m_Tgt.hit(); });
  }
  void reset() {
    flag.~once_flag();
    new (&flag) std::once_flag;
  }

private:
  int m_Id;
  Target &m_Tgt;
  std::once_flag flag;
};

No need to write inline
If you include the full definition of a member function in a class or struct definition, you don't need to explicitly use the inline specifier, as it will implicitly be an inline function.
Write idiomatic code
There are a few things in your code that are not incorrect in any way, but are a rather unusual way to write things. For example, when declaring an int and initializing it, I would expect int n = 2 or int n{2}, but not int n(2).
Also, when repeating something a number of times, use a for-loop, like so:
for (int i = 0; i < n; ++i) {
    e.reset();
    ...
}

This completely describes how often the loop is run in a single line, which makes it easier to read.


Your solution looks overly complex. If I understood it correctly, you want to filter out all unavailable states except if it's the last element. A more declarative and idiomatic Ruby approach would be:

filtered_milestones = milestones.reject.with_index do |milestone, idx|
  is_last_milestone = (idx == milestones.size - 1)
  milestone[:state] == "unavailable" && !is_last_milestone
end


Web crawler that charts stock ticker data using matplotlib

Composing small functions

chartStocks would be more readable if you split it into a handful of smaller functions, roughly like this:

def chartStocks(*tickers):
    for ticker in tickers:
        page = getTickerPage(ticker)
        csv_url = findCSVUrl(page)
        csv = getCSV(csv_url)
        day, points = parseCSV(csv)
        plot_data(ticker, day, points)

        # Or, if you're allergic to temporary variables:
        day, points = parseCSV(getCSV(findCSVUrl(getTickerPage(ticker))))

This approach lets you clearly see the "pipeline" your data is passing through, and lets you test and reuse smaller pieces individually.

Arguably it would be even cleaner to define def chartStock(ticker) to handle the case of one ticker, so that chartStocks is just

def chartStocks(*tickers):
    for ticker in tickers:
        chartStock(ticker)

The only thing to be careful of here is to make sure to design your functions to handle errors properly -- either check that each return value is not None before calling the next function, or allow them to take None as a parameter and just return nothing in that case.

str.startswith

This:

# Find all links on the page
for link in soup.findAll('a'):
    href = link.get('href')
    link = []
    for c in href[:48]:
        link.append(c)
    link = ''.join(link)

    # Find the URL for the stock ticker CSV file and convert the data to text
    if link == "http://real-chart.finance.yahoo.com/table.csv?s=":
        # ...

could be simplified with str.startswith:

def findCSVUrl(soupPage):
    CSV_URL_PREFIX = 'http://real-chart.finance.yahoo.com/table.csv?s='
    for link in soupPage.findAll('a'):
        href = link.get('href', '')
        if href.startswith(CSV_URL_PREFIX):
            return href

I've also provided a not-found value of '' so that if link has no href, startswith won't get called on None.

Skipping first row

Instead of using a lineOne flag when looping over lines:

lineOne = True
for line in lines:
    if lineOne == True:
        lineOne = False
    else:
         # continue parsing line...

you can just start from after the first row with a slice:

for line in lines[1:]:
    # ... continue parsing line

CSV parsing

Python has a built-in CSV parsing module that could simplify a lot of your parsing. It would do the splitting-by-commas for you and return either a list or dict of fields for each row, depending on what you ask for. You would end up with roughly this:

def parseCSV(csv_text):
    csv_rows = csv.reader(csv_text.split('\n'))
    days = []
    points = []

    for day, row in enumerate(csv_rows):
        close = float(row[4])
        days.append(day)
        points.append(close)

    return days, points

where the enumerate function would give you the same zero-based days list as you currently have.

Actually, since it seems like days will just be the list [0 .. len(points)], you could skip the enumerate and simply define days after you've parsed all the points, and toss in a list comprehension if you'd like for good measure:

def parseCSV(csv_text):
    csv_rows = csv.reader(csv_text.split('\n'))

    points = [float(row[4]) for row in csv_rows]
    days = list(range(len(points)))

    return days, points


Writing a user's profile image to disk using nested Node.JS closures

First of all, you are correct. One way to prevent deep nesting is to pull out the callback into it's own named function. This allows you to only be as deep as 2-3 levels in blocks of code.

function task1(){
  async1(task2);
}

function task2(){
  async1(task3);
}

function task3(){
  async1(task4);
}

Another way to do it is by using flow-control libraries which take advantage of the concept of Futures/Deferreds/Promises. There are a lot of ways to call them, but they are the same thing most of the time.

The basic concept is that they usually stack up callbacks via utility functions and then run them, depending on the result of the previous or depending on the used utility function. The code will look linear and synchronous, but it actually is running async and the library controls the flow of calls and results. In jQuery, you can do something like

//Run an addition in the server
$.get('add.php',{
    op1 : 1,
    op2 : 2
  })
  .then(function(result){
    //get the addition result (3) and multiply it on the server (another async)
    return $.get('multiply.php'{
      op1 : result,
      op2 : 3
    });
  })
  .then(function(result){
    //get the multiplication result (9) and divide it on the server (another async)
    return $.get('divide.php'{
      op1 : result,
      op2 : 9
    });
  })
  .done(function(result){
    console.log(result); //1
  });


It does not improve readability to rename modules. There are a few common aliases used, usually to shorten the name: import numpy as np and import matplotlib.pyplot as plt. Apart from that you should stick to the module name.

I was searching your whole code for the initialization of plot and number, because they sound more like normal variables and not like modules. Especially plot sounds like an object.

You should also choose more descriptive variable names (and adhere to PEP8, Python's official style-guide). capitalization_permutations tells you immediately what the function does, permLet does not.

To iterate over the lines of a file, it is sufficient to do:

with open(inputFile, 'r') as info:
    for character in info:
        character = character.upper()
        # do something

But since you actually want the characters, you could just use collections.Counter here:

with open(inputFile, 'r') as info:
    count = collections.Counter(info.read().upper())

Instead of value = pprint.format(count); print(value) you can directly do pprint.pprint(count).

Currently your main code is all over the place. inputFile is defined in the beginning, followed by the function definitions, followed by more code.

Instead follow this build-up:

Module imports
CONSTANTS
Class definitions
function definitions
rest of the code

You could put all your code into a main function and call it like this:

def main():
    inputFile = input('File Name: ') # Delete whitespace at end of line here
    with open(inputFile, 'r') as info:
        count = collections.Counter(info.read().upper())
    pprint.pprint(count)
    ylimChoice(count)

if __name__ == "__main__":
    main()

This allows you to do e.g. import plot_parameters to use plot_parameters.ylimChoice() in another script without the main part of the code being run.

At the same time you can remove the reliance on the global variables by just passing the relevant object as parameters (e.g. count to ylimChoice and yCounts).

Lastly this monstrosity:

inputList = []
yesNo = input('Would you like to set custom ylim() arguments? ')
inputList.append(yesNo)
yes = list(permLet("yes"))
no = list(permLet("no"))

if any(yesNo in str({y: y for y in yes}.values()) for yesNo in inputList[0]):
    ...

What you want to know is if the user-choice is some permutation of yes with random capitalization. This is easiest achieved with if user_choice.lower() == 'yes'. At the same time you append the user_value to a list, and then iterate over the first element of that list to use in an any (with one element)(!). That's just too much overhead. Just use this:

user_input = input('Would you like to set custom ylim() arguments? ')
if user_input.lower() in ('y', 'yes'):
    yLimits(count)
else:
    ...
    # do other stuff

Note that I also allowed the user to just type y. Also, the other code will run on all other input. Your code does nothing (not even a notice that the user input was not recognized) if a wrong word is entered.


First, I'll start with an observation that applying these rewriting rules — in particular, removing trailing slashes in the URL — can break pages that reference relative URLs.  I assume you know that and want to proceed anyway.

In general, you should realize that every RewriteRule is conditional.  If the path does not match the pattern, the RewriteRule and all of its RewriteConds are skipped.  You should take advantage of that fact to eliminate a few superfluous RewriteConds.

You have seven RewriteRules:

Rule 1

# If it's a request to index(.html)
RewriteCond %{THE_REQUEST} \ /(.+/)?index(\.html)?(\?.*)?\  [NC]
# Remove it.
RewriteRule ^(.+/)?index(\.html)?$ /%1 [R=301,L]

It is highly unorthodox to use %{THE_REQUEST}, which works at the raw HTTP level (e.g., GET /index.html HTTP/1.1).  It contains the raw URL, whereas you usually care about the decoded path.  The fix is to remove the RewriteCond altogether, since it is redundant anyway.

I recommend incorporating Rule 6 into this rule as a simplification.
Rule 2

# if request has a trailing slash
RewriteCond %{REQUEST_URI} ^/(.*)/$
# but it isn't a directory
RewriteCond %{DOCUMENT_ROOT}/%1 !-d
# and if the trailing slash is removed and a .html appended to the end, it IS a file
RewriteCond %{DOCUMENT_ROOT}/%1.html -f
# redirect without trailing slash
RewriteRule ^ /%1 [L,R=301]

Again, the first RewriteCond should be incorporated into the RewriteRule instead.  There's no need to use %{REQUEST_URI}, since RewriteRule naturally works on paths.

Avoid hard-coding the assumption that the resources are relative to the document root.  They may have been remapped to another portion of the filesystem.
Rule 3

# Add missing trailing slashes to directories if a matching .html does not exist.
# If it's a request to a directory.
RewriteCond %{REQUEST_FILENAME}/ -d
# And a HTML file does not (!) exist.
RewriteCond %{REQUEST_FILENAME}/index.html !-f
# And there is not trailing slash redirect to add it.
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]

Avoid referencing %{REQUEST_URI} in the RewriteRule.  Instead, use regular expression capturing:

RewriteRule (.*[^/])$ $1/ [R=301,L]

Rule 4

RewriteCond %{REQUEST_FILENAME} -d
# And a HTML file exists.
RewriteCond %{REQUEST_FILENAME}/index.html -f
# And there is a trailing slash redirect to remove it.
RewriteRule ^(.*?)/$ /$1 [R=301,L]

The directory test is superfluous.  Also, since Rule 2 also strips trailing slashes, I would swap this with Rule 3 so that the rules to strip trailing slashes are placed together.
Rule 5

RewriteCond %{REQUEST_FILENAME} -d
# And a HTML file exists.
RewriteCond %{REQUEST_FILENAME}/index.html -f
# And there is no trailing slash show the index.html.
RewriteRule [^/]$ %{REQUEST_URI}/index.html [L]

Again, the directory test is superfluous, and you can avoid referencing %{REQUEST_URI} by using regular expression capturing.
Rule 6

# Remove HTML extensions.
# If it's a request from a browser, not an internal request by Apache/mod_rewrite.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
# And the request has a HTML extension. Redirect to remove it.
RewriteRule ^(.+)\.html$ /$1 [R=301,L]

As previously mentioned, this can be incorporated into Rule 1.
Rule 7

# If the request exists with a .html extension.
RewriteCond %{SCRIPT_FILENAME}.html -f
# And there is no trailing slash, rewrite to add the .html extension.
RewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L]

Use regular expression capturing.  Also, use of %{SCRIPT_FILENAME} is weird and inconsistent with the rest of the rules.

I found that the ruleset was prone to infinite redirects.  As you probably found, when the non-redirecting rules rewrite the URL, they trigger an internal subrequest in Apache, causing the entire ruleset to be evaluated again.  You probably encountered this problem and put in the check for %{ENV:REDIRECT_STATUS} as a workaround.  I would generalize that check by making it the very first rule.

Options +FollowSymLinks -MultiViews

<IfModule mod_rewrite.c>
  # Disable mod_dir adding missing trailing slashes to directory requests.
  DirectorySlash Off

  RewriteEngine On

  ######################################################################
  # Canonicalizing redirects
  ######################################################################

  # Skip all rewrites of internal subrequests (see below).
  RewriteCond %{ENV:REDIRECT_STATUS} .
  RewriteRule . - [L]

  # Strip .html or /index.html
  RewriteRule ^(.*?)(/index)?(\.html)$ $1 [NC,R=301,L]

  # Strip trailing slash if...
  # It isn't a directory, and if the trailing slash is removed and a .html
  # appended to the end, it IS a file.
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} (.*?)/?$
  RewriteCond %1.html -f [OR]
  RewriteRule (.*)/$ $1 [R=301,L]

  # Strip trailing slash if...
  # It is a directory that contains an index.html file.
  RewriteCond %{REQUEST_FILENAME} (.*?)/?$
  RewriteCond %1/index.html -f
  RewriteRule (.*)/$ $1 [R=301,L]

  # Add trailing slash if...
  # If is a directory and index.html does not exist.
  RewriteCond %{REQUEST_FILENAME} -d
  RewriteCond %{REQUEST_FILENAME}/index.html !-f
  RewriteRule (.*[^/])$ $1/ [R=301,L]

  ######################################################################
  # URL-to-filesystem mapping
  #
  # Even with the [L] flag, these mapping rules will trigger an internal
  # subrequest, causing the mod_rewrite ruleset to be re-evaluated.
  # Therefore, to prevent infinite recursion, the canonicalizing
  # redirect rules above need to skipped if %{ENV:REDIRECT_STATUS} is
  # set.
  ######################################################################

  # If there is no trailing slash, try appending /index.html
  RewriteCond %{REQUEST_FILENAME}/index.html -f
  RewriteRule (.*[^/])$ $1/index.html [L]

  # If there is no trailing slash, try appending .html
  RewriteCond %{REQUEST_FILENAME}.html -f
  RewriteRule (.*[^/])$ $1.html [QSA,L]
</IfModule>


Optimizing Dijkstra implementation using PriorityQueue in Java

This works, but there's definitely room for improvement.

Node class

A Node has a distanceFromSource, which means it's tied to the dijkstra algorithm, and the nodes can't be reused in other runs of the algorithm. This is not great and results in a relatively awkward interface, but we'll leave it for now.

private final char label;
private int distanceFromSource;
private final Map<Node, Integer> neighbourList;

You made label and neighbourList final, and I always love to see that! label should probably be a String, though, to make it a little more usable. (If you want to go the extra mile, you could use generics, which will make it a lot easier for any library that wants to use it.) Also, I don't see why the distances need to be integer; Dijkstra's algorithm doesn't require it, and it might be a pretty limiting factor in some applications. Also, distanceFromSource should probably be tentativeDistanceFromSource. The Node should also have a boolean visited set initially to false.

this.neighbourList = new LinkedHashMap<>();

Nice use of the diamond, but why does neighborList need to be a LinkedHashMap? We really don't care about the order of neighborList at all, so it could just be a HashMap.

public void addNeighbourer(Node node, int distance)
public Map<Node, Integer> getNeighbourerList()

It might just be me, but misspellings bug the hell out of me. The word you're looking for is neighbour (neighbor in the US).

Algorithm

public void findShortestDistances(PriorityQueue<Node> nodePriority, int noOfVertices) {

This raises a lot of questions. Why isn't this static? The Dijkstra class seems to be empty except for this, so it should be fine being static. Why don't I get the shortest distances back? If I'm using this program, I probably want the result to be returned. If I want to print it to the console, I can do that myself. Why should I have to give you a PriorityQueue to start with, instead of just a starting node? What is noOfVertices, and why do I have to supply it? As a consumer of this program, I probably want a function signature that looks more like

public static int findShortestDistance(Node start, Node final)

or, if I want to find the distances to multiple nodes at the same time, it might look like

public static Map<Node, Integer> findShortestDistances(Node start, Set<Node> destinations)

where the returned map will have all the elements of destinations as its keys.

Set<Node> MST = new LinkedHashSet<>();

What's MST? Why does it need to be a LinkedHashSet instead of just a HashSet? Luckily we can actually get rid of MST by changing the signature.

// list of nodes to be updated in nodePriority after iteration finishes.
List<Node> nodesToAdd = new ArrayList<>();
Iterator<Node> nodePriorityIterator = nodePriority.iterator();
while (nodePriorityIterator.hasNext()) {  // time complexity: O(n)
    Node node = nodePriorityIterator.next();
    if (minNode.getNeighbourerList().containsKey(node)) { // time complexity: O(log(n))
        //...
    }
}
nodePriority.addAll(nodesToAdd); // all updated nodes added to priority Queue.

This is a major issue. You should not be iterating through all the other nodes in the list and testing if the other node is in this node's neighbor list. (Also, that's O(1), not O(n), to check if a key exists in a hashmap.) Instead, iterate through the neighborList, possibly testing to see if the node is visited yet.

    Node updatedCopy = node; // original node copied.
    updatedCopy.setDistanceFromSource(adjacentNodeDistanceFromSource); // node copy updated with new value.
    nodesToAdd.add(updatedCopy); // updated node added to list.
    nodePriorityIterator.remove();  // time complexity: O(logn(n))

Whoa! Node updatedCopy = node; does not copy the node! Java passes objects by pointer! Luckily, this still works. Also, removing the node isn't quite necessary.

Result

public static int findShortestDistance(Node from, Node to) {
    Queue<Node> toVisit = new PriorityQueue<>();
    toVisit.add(from); // We have to populate the queue at the start. Thanks to nclark for pointing this out to me.

    while (!toVisit.isEmpty()) {
        Node min = toVisit.remove();
        if (min == to) {
            return min.getDistanceFromSource();
        }
        if (min.isVisited()) {
            continue;
        }
        min.setVisited(true);
        for (Map.Entry<Node, Integer> neighborEntry : min.getNeighborList().entrySet()) {
            int adjacentDistance = min.getDistanceFromSource() + neighborEntry.getValue();
            Node neighbor = neighborEntry.getKey();
            if (neighbor.getDistanceFromSource > adjacentDistance && !neighbor.isVisited()) {
                neighbor.setDistanceFromSource(adjacentDistance);
                toVisit.add(neighbor);
            }
        }
    }

    throw new RuntimeException("'to' node unreachable");
}

Nodes will be duplicated in the queue, but that's not that bad.


First up, I think you're doing too much in the button click handler. The logic for applying the mean filter should be moved to its own method, something like

private static Bitmap ApplyMeanFilter(Bitmap input, int windowSize)

Now it can be re-used and unit tested more easily.

I think this line is wrong

pixel_value = bmp.GetPixel(col+m, row+n)

in that bmp should be bmpOrig. The reasoning is that you're changing pixels in bmp as you go, which will have an effect on pixels that are processed later. That is, they won't be assigned the mean of their original surrounding pixels.

Assuming the bmp should be bmpOrig, we can optimise this quite a bit.

Say that instead of a bitmap, we have a 2D array of ints.

input

\begin{array}{c | c c c c}
  & 0 & 1 & 2 & 3 \\
\hline
0 & 1 & 2 & 3 & -1 \\
1 & 4 & 1 & 6 & -3 \\
2 & 4 & 5 & 9 & -3 \\
3 & 4 & -2 & 6 & -3
\end{array}

We can compute another 2D array such that the \$(i, j)\$-th entry is the sum of entries in the submatrix \$(0, 0), (i, j)\$:

var sums = new int[height, width];
for (var i = 0; i < height; i++)
{
    var sum = 0;
    for (var j = 0; j < width; j++)
    {
        sum += input[i, j];
        sums[i, j] = i > 0 ? sums[i - 1, j] + sum : sum;
    }
}

sums

\begin{array}{c | c c c c}
  & 0 & 1 & 2 & 3 \\
\hline
0 & 1 & 3 & 6 & 5 \\
1 & 5 & 8 & 17 & 13 \\
2 & 9 & 17 & 35 & 28 \\
3 & 13 & 19 & 43 & 33
\end{array}

Now suppose we want to find the sum of the values in the 3x3 square around entry \$(i, j) = (2, 2)\$:

\begin{array}{c | c c c c}
  & 0 & 1 & 2 & 3 \\
\hline
0 & 1 & 2 & 3 & -1 \\
1 & 4 & 1 & 6 & -3 \\
2 & 4 & 5 & \textbf{9} & -3 \\
3 & 4 & -2 & 6 & -3
\end{array}

We can do this quickly using the matrix we just computed. The answer is given by

  sums[3, 3] - sums[3, 0] - sums[0, 3] + sums[0, 0]
= 33 - 13 - 5 + 1
= 16

In general, if halfWindow = (windowSize - 1) / 2 then the sum of values in the windowSize * windowSize square around entry \$(i, j)\$ is given by

sums[i + halfWindow,     j + halfWindow] -
sums[i - halfWindow - 1, j + halfWindow] -
sums[i + halfWindow,     j - halfWindow - 1] +
sums[i - halfWindow - 1, j - halfWindow - 1]

The beauty is, computing the sum of the surrounding windowSize * windowSize values this way is independent of windowSize.

Getting back to the original problem of bitmaps, let's suppose we have a struct that will let us sum up the RGB values of the pixels. I named it Clr because I'm not very imaginative today; I'm sure you can think of a better name. Let's also assume we have operators +, - and / defined in the obvious way.

Putting it all together would look something like this

var sums = new Clr[input.Height, input.Width];
for (var i = 0; i < input.Height; i++)
{
    var sum = new Clr();
    for (var j = 0; j < input.Width; j++)
    {
        sum += Clr.FromColor(input.GetPixel(j, i));
        sums[i, j] = i > 0 ? sums[i - 1, j] + sum : sum;
    }
}

var output = new Bitmap(input);
var windowArea = windowSize * windowSize;
var halfWindow = (windowSize - 1) / 2;
for (var i = windowSize - 1; i < input.Height - windowSize; i++)
{
    for (var j = windowSize - 1; j < input.Width - windowSize; j++)
    {
        var clr = sums[i + halfWindow,     j + halfWindow] -
                  sums[i - halfWindow - 1, j + halfWindow] -
                  sums[i + halfWindow,     j - halfWindow - 1] +
                  sums[i - halfWindow - 1, j - halfWindow - 1];

        output.SetPixel(j, i, (clr / windowArea).ToColor());
    }
}

return output;

Running this on a 256x256 image, I got the following timings

windowSize       this               original
 3          00:00:00.0910750    00:00:00.4720078
 5          00:00:00.0899366    00:00:01.2674758
 7          00:00:00.0853111    00:00:02.2569419
 9          00:00:00.0938911    00:00:03.4408123
11          00:00:00.0840854    00:00:04.9614386

Other things to try that might improve performance:

Use a Clr[][] instead of a Clr[,]. See Why are multi-dimensional
arrays in .NET slower than normal
arrays?
Doing the above will let you move sums[i + halfWindow] and sums[i - halfWindow - 1] into variables outside the inner loop.
Compute the first row of sums separately to remove the conditional in this line sums[i, j] = i > 0 ? sums[i - 1, j] + sum : sum;


Parsing a slow-loading webpage with scrapy in combination with selenium

The spider is readable and understandable. I would only extract some of the things into separate methods for readability. For example, the "infinite scroll" should probably be just defined in a separate method.

And, the bare except can be replaced with handling a more specific TimeoutException:

def scroll_until_loaded(self):
    check_height = self.driver.execute_script("return document.body.scrollHeight;")
    while True:
        self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        try:
            self.wait.until(lambda driver: self.driver.execute_script("return document.body.scrollHeight;")  > check_height)
            check_height = self.driver.execute_script("return document.body.scrollHeight;")
        except TimeoutException:
             break

def parse(self, response):
    self.driver.get(response.url)
    self.scroll_until_loaded()

    for item in self.driver.find_elements_by_css_selector(".row"):
        name = item.find_element_by_css_selector(".company-title").text
        revenue = item.find_element_by_css_selector(".company-revenue").text
        yield {"Title":name,"Revenue":revenue}


Trie - code review request for improvement

The TrieNode[] alphabets can probably be changed to a Map<Character, TrieNode>.

This would have some important advantages:

First, you would not consume all characters domain space (256 in your sample code) unless you actually have nodes defined for all of them.
Second, if you use a HashMap or LinkedHashMap as implementation, the search algorithm is pretty fast, you won't have to iterate over the entire collection to find an element since the search is based on hashes.
Third, it will make it simpler to improve your code when you want to support other languages out there using more than just 256 characters.


Reading input fast in Java for competitive programming

In my experience, non-buffered I/O based on plain System.in and System.out are not fast enough for some competitive programming problems. I wrote a template based on BufferedReader and BufferedWriter, which are much faster. They aren't necessary for every problem, but I haven't found any downside to using them by default.

Some example code:

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in);
while (stdin.ready())
    String line = stdin.readLine();

BufferedWriter stdout = new BufferedWriter(new OutputStreamWriter(System.out));
stdout.write("test");
stdout.flush();
stdout.close();

I wrote a couple of blog posts with more details and some benchmark numbers:

Solving UVa 11340 in Java
Why is Java I/O Slow?


About the slowness...

I don't see obvious bottlenecks here. When you say "It takes about 1 second for 1 file..." do you mean:

A single song? In this case the MediaManager.getSong is a prime suspect. Add logging before and after to measure the difference.
An entire playlist file?

Are there many songs in a list?
Does it make a difference if all the files in the list are valid or invalid? Test with 100 valid files and 100 invalid files. If invalid files somehow cause MediaManager.getSong to be slow, you can try to add a check if the file exists before passing it to MediaManager.

These are mostly shots in the dark.

There are some other problems with your code that won't make your program faster but you should fix anyway.

Reading from streams

The documentation says this about inputStream.available():

  Returns an estimated number of bytes that can be read or skipped
  without blocking for more input.

  Note that this method provides such a weak guarantee that it is not
  very useful in practice.

Don't use it this way. Read like this instead:

FileInputStream inputStream = context.openFileInput(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
List<String> files = new ArrayList<String>();
while ((line = bufferedReader.readLine()) != null) {
    files.add(line);
}
bufferedReader.close();

Iterator<String> iter = files.iterator();
playlist.setName(iter.next());
while (iter.hasNext()) {
    String path = iter.next();
    Song song = MediaManager.getSong(context, path);
    if (song != null) {
        playlist.addSong(song);
    }
}

An important mistake you did there that you didn't close the input stream. Remember to close resources that you opened.

Use interface types instead of implementations

Instead of this:

ArrayList<Playlist> playlists = new ArrayList<Playlist>();

Use the interface type in declarations, like this:

List<Playlist> playlists = new ArrayList<Playlist>();

Style issues

This code doesn't follow the standard spacing rules, and the convention of using braces even for one-line statements:

for( String file : context.fileList() )
    if( file.endsWith(".playlist") )
        fileList.add(file);

This is the recommended style:

for (String file : context.fileList()) {
    if (file.endsWith(".playlist")) {
        fileList.add(file);
    }
}


Visualizing Newton-Raphson method for finding zeroes of a function

Conventions, coding patterns and readability

Overall, your code looks nice! I have never seen a code where you insert a line in the beginning to avoid the script being interpreted as a function. It works, but I wouldn't do it like that.

The two functions you have are very simple. There is 1: no recursion. 2: no loops 3: no handling of invalid input. For such functions you can simply create anonymous functions. This way you can avoid the first line of code in your script.

% The function to find zeroes of.
% The function is specifically chosen to not have any zeroes
% so as to show the weakness of Newton's method.
f = @(x) (x - 5).^2 + 5;

% The derivative of f(x)
fd = @(x) 2 * (x - 5);

You have very descriptive variable names. However, eps is not one of them, as eps is a built-in function and variable.

You have a growing vector in your loop xvals = [xvals; x1];. This is not recommended, as it is very slow. It's faster to pre-allocate memory for a vector that will be "large enough", and trim it down afterwards:

xvals = zeros(20,1);
while ...
...
end
xvals = xvals(1:iter);  % or xvals(iter+1:end) = [];

Also, if you don't want to pre-allocate memory, you can increase performance by substituting xvals = [xvals; x1] with:

xvals(end+1) = x1;

You should use < itermax instead of <= itermax in the loop condition. Otherwise you'll end up with itercount = itermax + 1.

Note: Always try to keep compatibility with MATLAB when programming in Octave.

Don't use itercount ++ instead of itercount = itercount + 1, because it's easier.
Don't do a = b = c = 0 because it's easier.
Don't do inline assignments b = (a=3) * a just because you can.
And it might not be recommended by everyone, but I recommend you to use end instead of endfunction, endif etc to keep compatibility with MATLAB.

This is all I can do for now... Good luck!


Does not work, can be mutated

You did not even test this object. Please take time to make sure the code you put up for review is at least working next time. :)

Bugs.

You don't tests if head is defined for the functions peek, and poll.

const q = new Queue();
q.peek(); // throws TypeError cannot read property val of null
q.poll(); // throws TypeError cannot read property next of null

Can only Get one object from the Queue per group of offer calls

q.offer("A");
q.offer("B");
q.poll(); // return "A"
q.peek(); // throws TypeError cannot read property val of null
q.poll(); // throws TypeError cannot read property next of null

// OR
q.offer("A");
q.offer("B");
q.poll(); // return "A"
q.offer("C");
q.poll(); // return "C"  What happened to "B"

Mutation

You have not encapsulated the object state and thus can be mutated in many ways to produce unexpected behaviours

const q = new Queue()
q.offer("foo");
q.head.tail = q.head;
while(!q.isEmpty()) { console.log(q.poll().val) } // never stops

// and
q.head = undefined;
q.isEmpty(); // incorrectly returns false

Bloated

The property Queue.tail does nothing and is just noise.

I am guessing you wanted to use it to make offer quicker without needing to step all the way down the links from head but that will require a doubly linked list.

You could just use an array.


Printing Command Line Unicode Chess Board

numpy
In this case there is no need to use. For an 8 by 8 board, filled with strings, there is no advantage to using it, apart from the possibility to index row and column at the same time
enums
You have a few properties wich would be best presented as an enum. The color and the type of the piece
import enum

class Color(enum.Enum):
    WHITE = 0
    BLACK = 1

class Piece(enum.Enum):
    EMPTY = enum.auto()
    PAWN = enum.auto()
    ROOK = enum.auto()
    KNIGHT = enum.auto()
    BISHOP = enum.auto()
    KING = enum.auto()
    QUEEN = enum.auto()

tuple
You have a chrs dictionary with keys that contain both the color and the piece. A better approach here would be to use tuples as keys
chrs = {
    (Color.WHITE, Piece.EMPTY): "\u25FB",
    (Color.WHITE, Piece.PAWN): "\u265F",
    (Color.WHITE, Piece.ROOK): "\u265C",
    (Color.WHITE, Piece.KNIGHT): "\u265E",
    (Color.WHITE, Piece.BISHOP): "\u265D",
    (Color.WHITE, Piece.KING): "\u265A",
    (Color.WHITE, Piece.QUEEN): "\u265B",
    (Color.BLACK, Piece.EMPTY): "\u25FC",
    (Color.BLACK, Piece.PAWN): "\u2659",
    (Color.BLACK, Piece.ROOK): "\u2656",
    (Color.BLACK, Piece.KNIGHT): "\u2658",
    (Color.BLACK, Piece.BISHOP): "\u2657",
    (Color.BLACK, Piece.KING): "\u2654",
    (Color.BLACK, Piece.QUEEN): "\u2655",
}

board
You keep a black and a white board. Better would be to keep one board, and just flip it at the time of presentation.
def board_begin():
    return (
        [
            [
                (Color.WHITE, Piece.ROOK),
                (Color.WHITE, Piece.KNIGHT),
                (Color.WHITE, Piece.BISHOP),
                (Color.WHITE, Piece.QUEEN),
                (Color.WHITE, Piece.KING),
                (Color.WHITE, Piece.BISHOP),
                (Color.WHITE, Piece.KNIGHT),
                (Color.WHITE, Piece.ROOK),
            ],
            [(Color.WHITE, Piece.PAWN) for _ in range(8)],
            *[[None] * 8 for _ in range(4)],
            [(Color.BLACK, Piece.PAWN) for _ in range(8)],
            [
                (Color.BLACK, Piece.ROOK),
                (Color.BLACK, Piece.KNIGHT),
                (Color.BLACK, Piece.BISHOP),
                (Color.BLACK, Piece.QUEEN),
                (Color.BLACK, Piece.KING),
                (Color.BLACK, Piece.BISHOP),
                (Color.BLACK, Piece.KNIGHT),
                (Color.BLACK, Piece.ROOK),
            ],
        ]
    )

Here I use None to represent an empty tile, and replace it by a white or black tile at the time of display.
flip board
If you use numpy to keep your board, you can np.flip, or a simple routine like this:
def flip(board):
    return [
        row[::-1] for row in reversed(board)
    ]

display the board
Here a simple routine, which takes a boolean flag on whether to flip it:
def display_board(board, flip_board=False):
    for i, row in enumerate(board if not flip_board else flip(board)):
        row_strings = [
            chrs.get(tile, chrs[(Color((i + j) % 2), Piece.EMPTY)])
            for j, tile in enumerate(row)
        ]
        print("".join(row_strings))

using dict.get to replace the empty tiles by the correct squares

board = board_begin()

[[(<Color.WHITE: 0>, <Piece.ROOK: 3>),
        (<Color.WHITE: 0>, <Piece.KNIGHT: 4>),
        (<Color.WHITE: 0>, <Piece.BISHOP: 5>),
        (<Color.WHITE: 0>, <Piece.QUEEN: 7>),
        (<Color.WHITE: 0>, <Piece.KING: 6>),
        (<Color.WHITE: 0>, <Piece.BISHOP: 5>),
        (<Color.WHITE: 0>, <Piece.KNIGHT: 4>),
        (<Color.WHITE: 0>, <Piece.ROOK: 3>)],
       [(<Color.WHITE: 0>, <Piece.PAWN: 2>),
        (<Color.WHITE: 0>, <Piece.PAWN: 2>),
        (<Color.WHITE: 0>, <Piece.PAWN: 2>),
        (<Color.WHITE: 0>, <Piece.PAWN: 2>),
        (<Color.WHITE: 0>, <Piece.PAWN: 2>),
        (<Color.WHITE: 0>, <Piece.PAWN: 2>),
        (<Color.WHITE: 0>, <Piece.PAWN: 2>),
        (<Color.WHITE: 0>, <Piece.PAWN: 2>)],
       [None, None, None, None, None, None, None, None],
       [None, None, None, None, None, None, None, None],
       [None, None, None, None, None, None, None, None],
       [None, None, None, None, None, None, None, None],
       [(<Color.BLACK: 1>, <Piece.PAWN: 2>),
        (<Color.BLACK: 1>, <Piece.PAWN: 2>),
        (<Color.BLACK: 1>, <Piece.PAWN: 2>),
        (<Color.BLACK: 1>, <Piece.PAWN: 2>),
        (<Color.BLACK: 1>, <Piece.PAWN: 2>),
        (<Color.BLACK: 1>, <Piece.PAWN: 2>),
        (<Color.BLACK: 1>, <Piece.PAWN: 2>),
        (<Color.BLACK: 1>, <Piece.PAWN: 2>)],
       [(<Color.BLACK: 1>, <Piece.ROOK: 3>),
        (<Color.BLACK: 1>, <Piece.KNIGHT: 4>),
        (<Color.BLACK: 1>, <Piece.BISHOP: 5>),
        (<Color.BLACK: 1>, <Piece.QUEEN: 7>),
        (<Color.BLACK: 1>, <Piece.KING: 6>),
        (<Color.BLACK: 1>, <Piece.BISHOP: 5>),
        (<Color.BLACK: 1>, <Piece.KNIGHT: 4>),
        (<Color.BLACK: 1>, <Piece.ROOK: 3>)]]

display_board(board, flip_board=False)

♜♞♝♛♚♝♞♜
♟♟♟♟♟♟♟♟
◻◼◻◼◻◼◻◼
◼◻◼◻◼◻◼◻
◻◼◻◼◻◼◻◼
◼◻◼◻◼◻◼◻
♙♙♙♙♙♙♙♙
♖♘♗♕♔♗♘♖

display_board(board, flip_board=True)

♖♘♗♔♕♗♘♖
♙♙♙♙♙♙♙♙
◻◼◻◼◻◼◻◼
◼◻◼◻◼◻◼◻
◻◼◻◼◻◼◻◼
◼◻◼◻◼◻◼◻
♟♟♟♟♟♟♟♟
♜♞♝♚♛♝♞♜

Board class
If you want to incorporate moves etc, it might pay to make a Class of the board, with it's own display, __getitem__ and move routines


Didn't test, but I would write it something like this:

function table($rows, $reverse = false, $fill = false, array $attr = null) {
    $c = '';
    $max_cols = sizeof(max($columns));

    foreach ($rows as $columns) {
        if ($fill && sizeof($columns) < $max_cols) {
            $columns = array_merge($columns, array_fill(0, $max_cols - sizeof($columns), ''));
        }
        if ($reverse) {
            $columns = array_reverse($columns);
        }
        $c .= '
' . implode('	', $columns) . '
';
    }

    return '
' . $c . '
';
}


You very rarely need to modify a variable from inside an each block.

Instead, check out all the methods available to you in Array and Enumerable.

Among them, there's #each_with_objects, which you can use like so:

a.each_with_object({}) do |(name, id), hash|
  hash[name] ||= []
  hash[name] << id
end

which'll produce the same hash as your current code.

You could also do:

a.group_by(&:first).map do |name, pairs|
  [name, pairs.map(&:last)]
end

That returns an array of arrays, but you can turn that into a Hash with Hash[]. You may not need to, though. A lot of things treat an Array object with [key, value]-style elements the same as a Hash object. Depends on your needs.


Python has a set of rules for how documentation strings should look like. These strings are called docstrings in Python and the corresponding PEP is PEP257. You basically just move your comments from above the function name inside and make them strings:

def display(self):
    """Calls the visible features."""
    self.top = Tk()
    self.labels()
    self.entries()
    self.buttons()
    # must remain at bottom or wont be displayed
    self.top.mainloop()

Python also has an official style-guide, PEP8, which recommends adding a single space after the # in a comment, as well as using a single blank line between class methods (and two between class or normal function definitions). It also recommends using a space after a comma in an argument list, but no spaces surrounding = for keyword arguments.

Your method display could be moved completely to the __init__, but it is also fine as a separate method, in case you ever want to call it again to reset your application / display it again after changing some values. I would swap the display and labels methods, though, it makes for easier reading.

Regarding your doubt if you are overusing self, i think you are rather underusing it than overusing. I'm not exactly sure how Tkinter handles objects, but in Python in general, objects can and will be garbage-collected once they go outside of scope. So, after e.g. the method labels ran, the local variable x_coord_label will be removed and the associated object deleted (unless it is still being referenced from somewhere else, like the Tk main loop for example). So I would store these labels/buttons etc also as class members. This is handy if you ever want to modify them as well (changing the text label on a button is a quite regular feature...).

In general, you should avoid using from X import *, because it clutters your global namespace and might lead to name conflicts. With Tkinter, many people use it anyway, mostly because one tends to use a lot of its functions, so selectively importing from TKinter import Button, Label, ... becomes too long and unreadable and always writing Tkinter.Button is also quite verbose. As a compromise you can use import Tkinter as tk, which is shorter and still has its own namespace.

Final code:

import Tkinter as tk

class MainFrame(object):

    def __init__(self):
        self.display()

    def display(self):
        """Calls the visible features."""
        self.top = tk.Tk()
        self.labels()
        self.entries()
        self.buttons()
        # must remain at bottom or wont be displayed
        self.top.mainloop()

    def labels(self):
        """Display all the labels for the main frame."""
        # adding x-cord label
        self.x_cord_label = tk.Label(
            self.top, text='X-Coordinate').grid(row=0, column=0)

    def entries(self):
        """Display all the entry boxes for the main frame."""
        self.x_cord_entry = tk.Entry(self.top, bd=5).grid(row=0, column=1)

    def buttons(self):
        self.x_cord_button = tk.Button(
            self.top, text='Enter').grid(row=0, column=2)

If you want to extend this further, you probably want to add more than one button. In this case, you will need to decide on a datastructure to hold your texts and buttons. So in the end it might look more like this:

class MainFrame(object):

    def __init__(self, button_texts):
        self.button_texts = button_texts
        self.top = tk.Tk()
        self.setup_rows()
        self.top.mainloop()

    def setup_rows(self):
        """
        Display all the rows with labels, entries and buttons
        for the main frame.
        """
        self.rows = []
        top = self.top
        for i, text in enumerate(self.button_texts):
            row = [tk.Label(top, text=text).grid(row=i, column=0),
                   tk.Entry(top, bd=5).grid(row=i, column=1),
                   tk.Button(top, text='Enter').grid(row=i, column=2)]
            self.rows.append(row)


Python code to find greatest common divisor of multiple numbers

It's more common to use Euler's method to find GCD, rather than factorising both numbers.  However, I'll continue reviewing with the existing algorithm, as there's useful insights to be found.

First, let's look at factors().
Our factors variable is being used as a counter or multiset, and Python provides us with a collections.Counter class for that.
With from collections import Counter, we can replace

        if f'{f}' in factors.keys():
            factors.update({f'{f}': factors[f'{f}'] + 1})
        else:
            factors[f'{f}'] = 1

with
        factors[f] += 1

(I've also changed to using the numbers themselves as keys, instead of converting to string).
The division int(n / f) can be rewritten using integer divide operator n // f (and we know the result will be exact, as we tested n % f == 0).  Also, we should use math.isqrt() rather than int(math.sqrt()) when we want an integer.
from collections import Counter

def factors(n):
    factors = Counter({1: 1, n: 1})
    for f in range(2, 1 + math.sqrt(n)):
        while n % f == 0:
            factors[f] += 1
            n = n // f
    return factors

Now let's look at gcd().
We are computing the intersection of the two multisets.  The operator & does exactly that for us:
common_factors = f1 & f2
cd = 1
for f in common_factors.keys():
    cd *= f ** common_factors[f]

When we iterate over a dictionary, we don't need to get the keys and then index again.  We can iterate over its items() instead, like this:
for f,count in common_factors.items():
    cd *= f ** count

Or we could expand the multiset using elements():
for f in common_factors.elements():
    cd *= f

This allows us to then use math.prod() instead of our own loop:
return math.prod(common_factors.elements())

The whole lot then becomes a one-liner:
def gcd(x, y):
    return math.prod((factors(x) & factors(y)).elements())

Next, main().  The heart of this function is what a functional programmer would call reduce, and - you guessed it - Python provides a reduce() function, in functools:
def main(args):
    args = map(int, args)
    print(reduce(gcd, args))

Finally, it's good practice to use a main guard, so the program can become a module:
if __name__ == "__main__":
    args = sys.argv[1:]
    main(args)

Simplified code
import math
import sys
from collections import Counter
from functools import reduce

def factors(n):
    factors = Counter({1: 1, n: 1})
    for f in range(2, int(math.sqrt(n))):
        while n % f == 0:
            factors[f] += 1
            n = n // f
    return factors

def gcd(x, y):
    return math.prod((factors(x) & factors(y)).elements())

if __name__ == "__main__":
    print(reduce(gcd, map(int, sys.argv[1:])))


Some notes:

YAML::load_file. Loading a file each time a method is called is dubious. I'd load it in the initialize of the class so it's only done once.
return exceptions[word.to_s] if exceptions.keys.include?(word) Inline conditionals are ok as guards (in a fact here it's kind of a guard), but as a general rule indented conditionals are more declarative (granted, at the cost of an indentation level and some lines).
+=, -=. Imperative programming. As always, I'd advise against in-place updates, try to avoid statements in favor of expressions (functional programming).

I'd write:

def count_syllables
  if @exceptions.has_key?(word)
    @exceptions[word]
  else
    counts = [
      count_vowels,
      (count_ys_in_vowel_role if contains_non_initial_y?)
      (+1 if contains_le_vowel_sound?),
      (+1 if begins_with_re_vowel?)
      (+1 if ends_in_sm?),
      (-1 if ends_in_silent_e?),
      (-count_diphthongs if contains_diphthongs?),
    ]
    [counts.compact.reduce(0, :+), 1].max
  end
end


In your code you often use the expressions len(m) and len(m[0]). The code would become clearer if you defined proper names for these expressions, like:

func (m Matrix) Rows() int { return len(m) }
func (m Matrix) Cols() int { return len(m[0]) }

This way, you can write zeros := matrix.Zeros(m.Rows(), m.Cols()), which make the code operate in mathematical terms instead of those of the implementing programming language. These additional methods won't affect the performance of your program since the compiler will generate equally efficient code for these method calls. You can verify this by looking at the generated assembly code using go tool objdump. And if there should really be a difference, file a bug report at https://github.com/golang/go/issues.

To see whether you defined a good API for your matrix package, you should write a corresponding unit test:

package matrix_test

import "testing"

func TestZeros(t *testing.T) {
    m := matrix.Zeros(3, 3)
    ...
}

Note that I wrote package matrix_test instead of the usual package matrix. This little change (which is also little-known) makes this test file a black-box test, which can only access the exported things from the matrix package.

At this point I thought that there were no way to access an individual element of the matrix. Therefore you should add another method:

func (m Matrix) At(row, col int) float64 { return m[row][col] }

Maybe it is possible to access the matrix elements using the [] operator, but I would not recommend this since you might want to implement the matrix later in a different way. Maybe you will mainly handle sparse matrices, where most of the elements are zero. Then you would need to change the implementation type to be more memory-efficient, and that change should not affect any code that already uses your package.

Another benefit of the At method is that it clearly defines that the ordering of the coordinates is row, col. I don't know whether mathematicians are always consistent about this little detail, so it's better to explicitly document it somewhere. Programmers definitely aren't consistent in this regard, not even after 60 years of confusion. There's (x, y), (top, left), (left, top), (height, width), (row, col), (col, row), and so on.


Tight loop, string manipulation and calculations

This code is effectively calculating a set of offsets from the origin and adding them in turn to get the final co-ordinates.  However, you're calculating the offsets each time for every flag and the question implies that this is done many times. Better to calculate them up-front, then iterate through them, applying the co-ordinates of the flag to each:

// Done once at initialization...
int[,] offsets = new int[6, 3] { { -48,   0,   0 },
                                 {  48,   0,   0 },
                                 {   0, -48,   0 },
                                 {   0,  48,   0 },
                                 {   0,   0, -48 },
                                 {   0,   0,  48 } }; ;

// Done for each flag in the game world...
string origin = "0 0 0";
double[] originParts = origin.Split(' ').Select(s => double.Parse(s)).ToArray();
List<string> origins = new List<string> { origin };

for(int idx = 0; idx < offsets.GetLength(0); idx++)
{
    origins.Add(String.Format("{0} {1} {2}",
        originParts[0] + offsets[idx, 0],
        originParts[1] + offsets[idx, 1],
        originParts[2] + offsets[idx, 2]));
}

You could, of course, build the array of offsets programmatically instead of hardcoding them like I did.

This gives you slightly more lines of code, but it reduces the number of calculations done on each loop, and separates the calculation of the offsets from the calculation of the final co-ordinate, which may make future modifications simpler (e.g. if the designer wants more co-ordinates added to the list, or co-ordinates should be read from a configuration file, and so on).


Predefined values for some values in a template function like with a #define macro (e.g. template)

The trick is to use a byte_repeater like here.

template<typename T, std::size_t count, int byte>
struct byte_repeater;

template<typename T, int byte>
struct byte_repeater<T, 1, byte> {
    static constexpr T value = byte;
};

template<typename T, std::size_t count, int byte>
struct byte_repeater {
    static constexpr auto value = (byte_repeater<T, count-1, byte>::value << CHAR_BIT) | byte;
};

Add a convenient function make_mask

template<typename T, int mask>
struct make_mask {
    static constexpr auto value = byte_repeater<typename std::make_unsigned<T>::type, sizeof(T), mask>::value;
};

And then the ostream<< operator becomes:

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& obj)
{
    static constexpr auto width = sizeof(T) * 2;
    static constexpr auto mask = make_mask<T,0xFF>::value;
    os << "[";
    std::for_each(obj.begin(), obj.end() - 1, [&os](const auto& elem) {
        os << "0x" << std::hex << std::uppercase << std::setw(width) << std::setfill('0') << (elem & mask) << ", ";
    });
    os << "0x" << std::hex << std::uppercase << std::setw(width) << std::setfill('0') << (obj.back() & mask);
    os << "]";
    return os;
}

LIVE DEMO


Although I'm not a C++ programmer I once held a course in computations with Matlab for physicists. So I can only give hints and thoughts on your code but I won't answer your question on efficiency.

As you mentioned that this code will be the basic of following exercises, I'm missing all sorts of documentation. If you are planning to teach someone (solving) ODEs with this code, you should at least refer to a physical or mathematical problem, which will be solved by your code and you should comment every function and what it does. However, if you want to teach writing clean code, you should separate your definitions from the implementation.
I'm the opinion that variables should have meaningful names even if you are referring to the standard variable names in physics (like g for gravity). This will ease the burden of understanding the code if you are not familiar with standard variable names.

Lastly, there is the call to the resize method of the vector. As I am no C++ programmer, so I can't say for sure, but I feel uncomfortable with this function. I searched in a C++ reference and found out about the method reserve which might be more appropriate in a safer way.


Fast evaluation of Euclidean distance with sparse data

Calling ContainsKey() on a dictionary if you need to get the value later on should be replaced with TryGetValue() to reduce the processing time.
See: what-is-more-efficient-dictionary-trygetvalue-or-containskeyitem

TryGetValue will be faster.
ContainsKey uses the same check as TryGetValue, which internally refers to the actual entry location. The Item property actually has nearly identical code functionality as TryGetValue, except that it will throw an exception instead of returning false.
Using ContainsKey followed by the item basically duplicates the lookup functionality, which is the bulk of the computation in this case

The next part to increase performance is to replace the call to Math.Pow() with multiplying the value by itself.
So instead of Math.Pow((kvp2.Value), 2) you should use kvp2.Value * kvp2.Value.
You just edited your question to do this but I will keep it in my review.

Using the said above will lead to
public static double Euclide(Dictionary<string, double> sp1, Dictionary<string, double> sp2)
{
    double distance = 0;

    foreach (KeyValuePair<string, double> kvp1 in sp1)
    {
        double possibleValue = 0.0d;
        sp2.TryGetValue(kvp1.Key, out possibleValue);

        double currentValue = kvp1.Value - possibleValue;

        distance += currentValue * currentValue;
    }

    foreach (KeyValuePair<string, double> kvp2 in sp2)
    {
        if (!sp1.ContainsKey(kvp2.Key))
        {
            distance += kvp2.Value * kvp2.Value;
        }
    }
    return distance;
}

This

double possibleValue = 0.0d;
sp2.TryGetValue(kvp1.Key, out possibleValue);

double currentValue = kvp1.Value - possibleValue;

will store the value of the searched key inside possibleValue if the key is in the dictionary. If TryGetValue() does not succeed it will return default(T) which for a double is 0.0.

I have added braces {} for the for and the if which makes the code less error prone. I would like to encourage you to always use braces.


Short review: The purpose of code is to tell other programmers what you're telling the computer to do. Your code here reads like you're trying show off all these cool things you can do - which makes for very difficult to read, unimplementable code. Don't perform multiple operations and checks on one line. Don't use member variables to do temporary state. Structure your code to make your intent as readily apparent to the reader as possible.

readInput

Seriously, just no:

while((std::cout << prompt) && (!(std::cin >> answer) || answer < 0 || answer > 99999999))

There is never any reason to write code like that. Why even pass a prompt to the function if you're going to write a different string anyway? I don't see a reason for the prompt.

main

You should write a function that looks like:

std::string convertNumber(int );

Having a streamable class is gratuitous.

NumberConverter

The flow of this class doesn't make much logical sense. You have a member variable mNumber, that you're modifying as you go. It's really more like an implicit argument to convert(). Same with all the member variables actually. Makes it very difficult to reason about the correctness of convert().

words[] doesn't make sense as an array. The three elements in the array have nothing to do with each other. You have the numbers under 20, you have the tens numbers (why the hyphen?) and the block identifiers. Declaring it this way means you have a bunch of cryptic words[2][0] or words[1][index] expressions. Prefer to make three different vectors and name them appropriately.

So convert() takes both a units and its string representation? That's not good design since you're basically passing the same/similar information twice. Prefer to restructure this call such that you're converting one "block" at a time (e.g. the millions block, then the thousands block, then the unit block). Redundant information is bad.

This fragment doesn't make sense either:

std::string word = words[1][index];

if (word[word.size() - 1] == '-')

Why are you using the specific word format as a signal for something? Also, all the words in words[1] end in a hyphen so you always go into this block.


Disallowing repeated characters and space after punctuation

Prevent repetead characters (all kind of characters) to 3.

If you mean replace 4 or more repeated characters with single character:

str.replace(/(.)\1{3,}/g, '$1');

  Add space after commas (,) or any kind of punctuation (!) (?) (.)

str.replace(/[,.!?:;](?=\S)/g, '$& ');


The pattern for i in range(n): for j in range(i+1, n): ... is better handled using itertools.combinations:

from itertools import combinations

def clean3(lst):
    lst = sorted(lst, key=lambda x: abs(x[4]), reverse=True) # the abs comparison is taken care off.
    remove = set() # for quicker membership checks
    for forces_i, forces_j in combinations(lst, 2):
        if forces_j not in remove: # the current entry might have already been removed
            if all(forces_i[x] < forces_j[x] for x in range(2, 4)):
                remove.add(forces_j)
    return list(set(lst) - remove)

I also removed the test for forces_i in removed since I feel you could have cases where it would fail to remove some forces_j. But if I'm wrong it's very easy to put back on the same line than the test for forces_j.


Consistent style

As a teacher, try to lead by example. Sometimes you put whitespace around operators (which is the norm), sometimes you don't, sometimes you prefix an opening brace with space, sometimes you don't. Whatever you do, make sure it is consistent (or configure a code format in your IDE and run the formatter over the whole code.)

Non-OO menu decision

In OO you don't just rip information out of an object to base your decision on it. Instead of

 if (m.getOption().equalsIgnoreCase(input))

add a method to the MenuOption, to let the option decide, whether it is suited for the input

 if(m.matchesInput(input))

Variable scope

In your loopUntilExit(), you declare the input String outside the loop - why? This should go to the minimal acceptable scope, that is in the line where you call sc.nextLine().

Law of least surprises

I don't like abusing the toString() method to create a multi-line screen menu. This is not what I'd expect of toString(). Thus, I suggest you create another method to do this, and call it explicitly.

One afterthought

In 20 years of programming Java, I have never seen the use of Scanner in real life (TM). Is it really necessary, that every teacher seems to love this object and base their classes on it? Yes, it is simple, straightforward to use, and probably an easy-to-explore way to teach other principles without the input getting in your way, but it does not hold any practical relevance (at least as far I am concerned.)


How to avoid carrying around a lock with my variable when multiple threads instantiation in Python?

Your concern seems legit. Fusing data that needs thread-safe operations and means of those operations would be nice.

However, this:

  Subclass dict and override get / set methods with an internal lock

will not work, because += - which you use - will not be atomic.

Things get worse with nested data structures: we actually have several objects and some of them carry references to others. If there are also some more references to those objects - how do we check that? Example:

a = [1,2,3]
b = {'a' : a} # or some crafty wrapper on top of that

If we make sure that every b['a'] is atomic, a can still be changed directly.

Making a wrapper that accepts mutation function and executes it in a locked context would not really work if you need in-place operations, not replacements of the whole object.

What you can do is take a closer look at context managers and try to create an object that is both dictionary and context manager.

Or simply do something like:

class FlexibleDict(dict):
    pass

shared_dict = FlexibleDict(shared_dict)
shared_dict.lock = lock

and pass that around.


Unique Paths II, dynamic programming problem, O(n^2) time, O(n^2) space

Nice solution, few suggestions:

Duplicated code: the functions len(memo) and len(memo[0]) are called several times. When working with a matrix is common to call m the number of rows (len(memo)) and n the number of columns (len(memo[0])). This can help to reduce the duplicated code. As @Manuel mentioned in the comments, m and n are also defined in the problem description.

Last element of a list: instead of memo[len(memo)-1] you can use memo[-1].

Input validation: this input validation:
if obstacleGrid[len(memo)-1][len(memo[0])-1] == 1:
    return 0

is done too late in the code, after the memo matrix is fully built. Better to move it up at the beginning of the function. BTW, with the previous suggestion, it can be shortened to:
if obstacleGrid[-1][-1] == 1:
    return 0

Naming: the row is called row in the helper function and j in the rest of the code. Same for the column. Use the same name to be consistent.

Throwaway variables: in the initialization of memo:
memo = [[-1 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))]

the variables i and j are not used. They can be replaced with _.

Type hints: the helper function is missing the type hints.

LRU cache: there is a handy annotation that does the memoization automatically, @lru_cache. Or the unbounded @cache in Python 3.9.

An example using @lru_cache:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
    m = len(obstacleGrid)
    n = len(obstacleGrid[0])

    if obstacleGrid[-1][-1] == 1:
        return 0

    @lru_cache(maxsize=None)
    def helper(row: int, col: int) -> int:
        if row == m - 1 and col == n - 1:
            return 1
        if row < m and col < n:
            if obstacleGrid[row][col] == 1:
                return 0
            return helper(row + 1, col) + helper(row, col + 1)
        return 0

    return helper(0, 0)

For dynamic programming solutions, you can have a look at the "Solution" section or "Discussion" section using tags python and dynamic programming.


Eliminate axis-aligned bounding box (AABB) variables

In a comment in your other question you claimed,

  Thank you, Caching vertMid and horzMid really helped.

Whether caching is helpful depends on:

How often you used the cached data
How tight your performance requirements are
Whether your cache implementation is reliable

One of your comments says,

// vertical mid, cached for quadtree

Only your testing can show whether that optimization is helpful.

From a performance point of view, in general:

If it's not used it's harmful to cache
If it's used once then it's harmless/useless to cache
If it's used several times then it's useful to cache

However making something bigger (by caching extra values) can also have some negative effect on performance, e.g. because you can't fit so many objects in the CPU cache (which is faster than memory): which is why you should profile/test to see whether caching makes it faster in practice as well as in theory.

If you want to eliminate duplicate variables, you only need 4 doubles:

min and max
or, x and either width or xwidth, and y and either height and yheight

I found your xwidth and yheight names confusing to read; I would have preferred 'right' and 'bottom'.

If you have large structs, you may improve performance by curing your habit of passing objects by value instead of by reference. For example, this ...

bool collides(AABB other)

... should be ...

bool collides(const AABB& other) const

You can also use different classes for different purposes. For example, the AABB bounds member of your Quadtree class needs getHorzMid() and getVertMid() members, but those methods aren't needed/used by the AABB which you return using Locatable::getAABB(). So you could use two classes, e.g. AABB (without getHorzMid and getVertMid members), and a SplittableAABB class (used as a member of Quadtree) which adds those members.

I don't much like AABB as a class name: partly because all-upper-case looks like a macro to me: consider Bounds or Rect or Rectangle instead.

Your current code creates but doesn't read the initialize the min and max data members.

Your move method doesn't update the data in these members (rendering that data untrue).

Maybe Vec2D min and Vec2D max should be (temporary) local variables of your init function, not (permanent) member data of the class.

The parameters passed to the AABB(Vec2D min, Vec2D max) constructor should probably be named one and two not min and max (and should possibly be passed by reference not by value).


src_len is not used..
the strlen in the return statement is not needed.. you know the length from dest_len.

IMHO very weird implementation :)


Handling signals in Python inside a function

What about implementing your signal handling code inside a class? This could look something like the following:

class GracefulExit:
    def __enter__(self):
        # set up signals here
        # store old signal handlers as instance variables

    def __exit__(self, type, value, traceback):
        # restore old signal handlers

You can then use this in your code as follows:

with GracefulExit():
    # Signals will be caught inside this block.

# Signals will no more be caught here.

You'll find more examples of how to use the with-statement on the web.