Since you are not showing a whole lot of the class itself, there is not to much fundamental to be done on the presented code.

Documentation

First, you should add documentation to your class and to its methods. Use the """...""" to write those docstrings as recommended in the official Style Guide.

Style

The Style Guide also has a section on variable naming (snake_case is recommended). You're mostly following this convention, and that's also the reason why Cookies as variable name almost immediately caught my attention while first screening the code. The widely accepted convention is to only use names with the first letter capitalized for class names.

Looping

While I was at it, the following piece of code caught my attention next.

Cookies = []
for hosti in range(len(hosts)):
    if hosts[hosti] in self.jar._cookies:
        Cookies.extend(self.jar._cookies_for_domain(hosts[hosti], w_r))

Since hosts is a list, and you're not trying to do anything fancy on the elements themselves, this can be simplified to

cookies = []
for host in hosts:
    if host in self.jar._cookies:
        cookies.extend(self.jar._cookies_for_domain(host, w_r))

which I find easier to read.

String formatting

This snippet comes a little bit earlier in the code: l_req_host = "%s%s" % (req_host, '.local'). It uses the old-old Python string formatting using %. Since you specifically tagged your question as Python 3, I strongly recommend to make use of the new f-string synthax which allows you to write that same line as l_req_host = f"{req_host}.local". Here is a nice blog post talking about all the different ways of string formatting in Python and their pros and cons.

if statements

Next up on my list would be if w_r.has_header("Cookie") == False. In general there is no need to do if sth == True or if sth == False in Python. Both can be conveniently expressed as if sth or if not sth. Usually this will also allow someone to read the expression almost as if it was text. If that doesn't work, maybe think about the name of your bool variable.

Minor tweaks

At the moment the last thing I could come up with was to change self.processed = self.processed + 1 to self.processed += + 1 which saves you a few characters of typing in the future.


Your code does indeed run forever. Regrettably you don't describe the method you're using, so I will have to get that from your code.

You start by getting all possible substring, of all possible sizes, out of the given input string and you store those substrings, its letters and position in an array.
You do a full matrix comparison of each array entry. You test if something is an anagram or not. If it is you store it in a second array.
You count what you stored in the second array.

Somewhere along the way you lost me there. Why all the complexity? You started out well, by getting all possible substrings, but after that it became somewhat messy. A full matrix comparison is certainly not needed. I'll explain.

What are we trying to accomplish here? Let's analyse the problem, taking the simply case of 'abba'. The possible substrings are 'a','b','b','a', 'ab','bb','ba' and 'abb','bba'. nine in total, let's number them 1 to 9.

A full matrix comparison would make 9 x 9 = 81 comparisons. But it is obvious that this would compare the same substrings twice. Comparing 2 to 5 is the same as comparing 5 to 2. So we can leave out at least half of these comparisons, cutting the time we need to do this in half. We also don't need to compare two strings of unequal length, so we won't.

So, in the case of 'abba' we have 3 sets we need to compare. For the 1 character set we have to do 6 comparisons, for the 2 character set 3, and for 3 character set 1. That's a total of 10 comparisons where you did 81. This number gets proportionally lower when the size of the input string increases. It is here where we can gain most of our speed.

Finally we get to the comparison itself. Suppose we want to compare 'ab' to 'ba'. By sorting the characters in both strings we can simply compare them. If they are equal that the strings must be an anagram, and must be counted. This is what you do as well.

So now we know what we will need: We need all possible sorted substrings and perform only the needed comparisons.

In basic Javascript code that would look like this:

function sherlockAndAnagrams(s) {
    var anagrams = 0;
    for (var len = 1; len < s.length; len++) {
        var parts = [];
        for (var pos = 0; pos <= s.length - len; pos++) {
            var part = s.substr(pos, len);
            parts.push(part.split('').sort().join(''));
        }
        for (var index1 = 0; index1 < parts.length; index1++) {
            var part1 = parts[index1];
            for (var index2 = index1 + 1; index2 < parts.length; index2++) {
                var part2 = parts[index2];
                if (part1 == part2) anagrams++;
            }
        }
    }
    return anagrams;
}

Notice how the outer loop goes through all the possible lengths of the substring. By working with one length of string, each time, I will never have to compare two differently sized strings.

The way I build the initial array with substrings looks very similar to what you have, but I only store the sorted substrings. That's all that is needed. By sorting the characters in the substring at this stage I save time.

The comparison of the substrings of one length is now quite simple. Notice how index2 starts at index1 + 1, preventing a full matrix comparison of the subset.

And that's it.

So, the major lesson here is to try to reduce the number of comparisons you have to make by first carefully analysing the problem. For an input string of 4 characters you did 81 comparisons, I do 10 (12%). If the input is 16 characters long this goes to 18,225 and 680 (4%), 32 characters gives 277,729 and 5,456 (2%). You can see where that is going. Almost all these coding challenges, for which basic solutions run too long, require such a careful analysis. They don't require fancy programming.


Is there a better way of implementing this control structure?

Kinda hard to know what you mean with better since you don't specify in what regard.

In regards to cleaner code:

FunctionName doSetInc is a bit weird, what does it do?
You are sending in 3 variables into the function, it's common practice to use as few as possible (rarely more than 2, 0 or 1 prefered).
You are always sending in "id" and "8" into the function, thus this function might not need those attributes and could be set in another way.

Other than that, since I find no easy mathematical similarities between these checks and what to do, I would say no, you can't improve it given this small piece of code and no other context.


Toggle logical NOT operator based on a boolean value

Using a function name as a variable name inside said function
This can be very confusing to someone reading your code(or you after having been away from your code for awhile)
Hither forth, getNumbers (the variable in the function) shall be referred to as showNumbers
XOR it baby
XOR is exactly what the current logic is doing anyway.
When showNumber is true invert other boolean value
//showNumber = true
T ^ showNumber == F
F ^ showNumber == T

Else leave as it was
//showNumber = false
T ^ showNumber == T
F ^ showNumber == F

var getNumbers = function(showNumbers) {
    return function(e) {
        return isNaN(e) ^ showNumbers ? e : null;
    };
};

Potential gotcha
Javascripts XOR(^) is bitwise NOT Logical


You're breaking some rules for good struct design - see them here.

X DO NOT define mutable value types.
✓ DO implement IEquatable on value types.

I'm going to disagree with everyone else and say that calling your struct a Hole is fine as it's a domain specific concept.
I think your method naturally belongs on the type itself. I'd call it Intersects to avoid the disjoint/overlap debate.
// using static System.Math; // Easy access to Pow.

public struct Hole : IEquatable<Hole>
{
    public float Radius => Diameter / 2;
    public float Diameter { get; }
    public float X { get; }
    public float Y { get; }

    public Hole(float x, float y, float diameter)
    {
        X = x;
        Y = y;
        Diameter = diameter;
    }

    public bool Intersects(Hole other)
    {
        var sumR = Radius + other.Radius;
        var deltaX = X - other.X;
        var deltaY = Y - other.Y;
        return Pow(sumR, 2) > Pow(deltaX, 2) + Pow(deltaY, 2);
    }

    public bool Equals(Hole other)
    {
        return Diameter.Equals(other.Diameter) && X.Equals(other.X) && Y.Equals(other.Y);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        return obj is Hole && Equals((Hole)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            var hashCode = Diameter.GetHashCode();
            hashCode = (hashCode * 397) ^ X.GetHashCode();
            hashCode = (hashCode * 397) ^ Y.GetHashCode();
            return hashCode;
        }
    }

    public static bool operator ==(Hole left, Hole right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(Hole left, Hole right)
    {
        return !left.Equals(right);
    }
}


Normalizing strings using PHP preg_replace and regex expressions

At first glance I would first trim without a mask and then stringtolower inside before the preg_replace.

$modded = preg_replace(array( '/[^a-z0-9 ]/','<\W+>'),array( ' ', '_' ), strtolower(trim( $myvar[$i])));

trim first, less characters to process when there is white space to
trim.
Then stringtolower() which allows '/[^a-zA-Z0-9 ]/i' to be
simplified to '/[^a-z0-9 ]/'

Case insensitive tasks require extra CPU cycles.
RegEx is the usually least efficient string function especially compared to stringtolower() and trim()
Using these two function before the RegEx gives the RegEx less work to do.
Consider giving the trim additional mask characters: e.g.
space, new line, carriage return, asterisk, ampersand, at mark, parenthesisPlus any other characters that could need to be trimmed (quote marks?).

This worked well for you test $myvar:

trim($str," \t\n\r\0\x0B\x28\x29\x26\x2a\x40\x5f")

RegEx is not my strong suit.  While it works well this does not make sense to me. '/[^a-z0-9 ]/','<\W+>' I'm not saying it is wrong, it's not broke,  I just do not fully understand.

some minor stuff that bugs me:
You do not need to concatenate simple variables in double quotes

echo "modded2 = " . $modded." [ ". $i ." ] = " .$myvar[$i]. "\n";

This is the same but cleaner:

echo "modded2 = $modded [$i] = $myvar[$i]\n";

This may be more efficient, (or may not, did not benchmark):

for( $i = 0; $i < sizeof( $myvar ); ++$i )

But this is cleaner, easier to see what is going on.

foreach($myvar as $key => $value){

My preference is count over sizeof, although they are the same.

In a test environment like this, instead of <br> I use "\n" with a plain text header:

header('Content-Type: text/plain; charset=utf-8');

It works will with print_r() and var_export(), var_dump() etc.

My Tested Code:

header('Content-Type: text/plain; charset=utf-8');
$myvar = array("Paxus-Demo","Paxus Demo","paxus_demo","Paxus  Demo",
    "paxus-Demo","paxus_ Demo","Paxus _Demo","*(&*&   (*Paxus-Demo   ",
    "@@Valid  _voice","Valid-Voice","PortaL-Demo","gui_demo",
    "Gui-Demo   ",    "VoiceInstance","vAlid Voice","  vaLid_  _voiCe  ");

foreach($myvar as $k => $before){
  $after = preg_replace( array( '/[^a-z0-9 ]/','<\W+>'), array( ' ', '_' ), strtolower(trim($before," \t\n\r\0\x0B\x28\x29\x26\x2a\x40\x5f" )));
//  echo "$k. $before => $after\n";
  echo "$k. $after <= \"$before\"\n";
}

The Result:

0. paxus_demo <= "Paxus-Demo"
1. paxus_demo <= "Paxus Demo"
2. paxus_demo <= "paxus_demo"
3. paxus_demo <= "Paxus  Demo"
4. paxus_demo <= "paxus-Demo"
5. paxus_demo <= "paxus_ Demo"
6. paxus_demo <= "Paxus _Demo"
7. paxus_demo <= "*(&*&   (*Paxus-Demo   "
8. valid_voice <= "@@Valid  _voice"
9. valid_voice <= "Valid-Voice"
10. portal_demo <= "PortaL-Demo"
11. gui_demo <= "gui_demo"
12. gui_demo <= "Gui-Demo   "
13. voiceinstance <= "VoiceInstance"
14. valid_voice <= "vAlid Voice"
15. valid_voice <= "  vaLid_  _voiCe  "


Customer segmentation using RFM analysis

This can be done a lot simpler.

Since all of rfm returns in result, you can do a copy. To make sure that even if you reorder things, they appear at the correct place, you use an index. Since Id is unique in the DataFrame, let's use this

result2 = datas.set_index("Id")

r_score

There is no use for the intermediate rfm_recency, or it's sorting, so including the r_score can be as simple as:

result2["r_score"] = 5 - pd.qcut(result2["Recency"], q=5, labels=False)

Doing this immediately in this result2 DataFrame instead of joining several intermediary DataFrames together.

f_score and m_score

The f_score and m_score are both linear interpolations, so can be done with this formula, instead of applying the scorefm method on each row individually

def fm_score(series):
    return (
        6 - series.sort_values(ascending=False).cumsum() / series.sum() * 5
    ).astype(int)

result2["f_score"] = fm_score(result2["Frequency"])
result2["m_score"] = fm_score(result2["Monetary"])

FM and RFM_Score

These are simple calculations, so can be done like this:

result2["FM"] = (result2["f_score"] + result2["m_score"]) / 2
result2["RFM_Score"] = result2["r_score"] * 10 + result2["FM"]

This can be all you need. If the shape needs to be exactly as the original result, a reset_index, sort and reindex can help:

result2 = result2.sort_index().reset_index().reindex(columns=result.columns)

where instead of result.columns you manually give a list of the columns in order

    Max_Date    Id  Member_id   Recency r_score Frequency   f_score Monetary    m_score FM  RFM_Score
0   2019-02-10  123 qwbe78  3   5   83  1   9251    2   1.5 51.5
1   2019-02-10  147 jkyu87  3   5   32  1   8678    2   1.5 51.5
2   2019-01-18  258 fwgs77  26  3   132 1   18100   3   2.0 32.0
3   2019-01-12  369 fbbr54  32  3   197 1   1019    1   1.0 31.0
4   2018-04-15  445 asfv41  304 1   246 2   10215   2   2.0 12.0
5   2019-01-21  456 dwfv84  23  4   261 2   4221    1   1.5 41.5
6   2018-04-10  589 sdqw88  309 1   80  1   19569   4   2.5 12.5
7   2018-05-20  741 dsdg46  269 2   282 3   3108    1   2.0 22.0
8   2019-02-05  753 yukh20  8   5   132 1   19871   5   3.0 53.0
9   2018-03-19  784 asdf48  331 1   413 4   8551    1   2.5 12.5
10  2019-01-25  789 adqw87  19  4   478 5   19195   3   4.0 44.0
11  2018-06-30  852 cvgo87  228 2   261 2   5975    1   1.5 21.5
12  2019-01-19  963 ewgs45  25  4   357 4   4405    1   2.5 42.5
13  2018-01-04  988 afdi25  40  2   321 3   3753    1   2.0 22.0


Speeding up forwarding of Ethernet frames in Python ARP spoof

I had the same problem. You need to set up a reusable scapy.L2socket socket and call send(pkt) on it, instead of using sendp.

It is much faster. Here you can see how to do it:

https://home.regit.org/2014/04/speeding-up-scapy-packets-sending/

The diff/change from using a normal sendp looks like this:

@@ -27,6 +27,7 @@ class replay:
     def run(self):
         # open filename
         filedesc = open(self.filename, 'r')
+        s = conf.L2socket(iface=self.iface)
         # loop on read line
         for line in filedesc:
             # Build and send packet
-            sendp(pkt, iface = self.iface, verbose = verbose)
+            s.send(pkt)


If you're using Java 8, you can use StringJoiner.

/**
 * JEcho writes any command line argument to the standard output; each argument
 * is separated by a single whitespace and end with a newline (you can
 * specify '-n' to suppress the newline).
 *
 * This program doesn't interpret common backslash-escaped characters (for
 * exampe '\n' or '\c').
 */
public class JEcho {
    public static void main(String[] args) {
        boolean printNewline = true;
        int posArgs = 0;

        if (args.length > 0 && args[0].equals("-n")) {
                printNewline = false;
                posArgs = 1;
        }

        StringJoiner outputBuilder = new StringJoiner(" ");

        for (; posArgs < args.length; posArgs++) {
            outputBuilder.add(args[posArgs]);
        }

        String output = outputBuilder.toString();

        if (printNewline)
            System.out.println(output);
        else
            System.out.print(output);
    }
}


An extension method to safely retrieve or add a dictionary value

Are there easier ways to achieve the thread-safety I'm looking for?

Yes, use the ConcurrentDictionary Class which is avaible since NET 4.0


You can substitute

if (existingResourceDictionary.Source.ToString().Contains("Light"))
{
    Settings.Default.Theme = true;
    Settings.Default.Save();
}
else
{
    Settings.Default.Theme = false;
    Settings.Default.Save();
}

by

Settings.Default.Theme = existingResourceDictionary.Source.ToString().Contains("Light");
Settings.Default.Save();

to shorten it a bit.


Replacing the vowels of a string with the letter "X"

Look into regular expressions, which Ruby is very good at:

def vowel_censor(string)
  string.gsub(/[aeiou]/i, "X") # case-insensitive
end

Or, even easier, more low-level and more efficient, use String#tr:

def vowel_censor(string)
  string.tr("aeiou", "X") # lowercase only; use "aeiouAEIOU" to handle both upper- and lowercase
end

For your current code:

The Ruby convention is 2 spaces of indentation. Not 4 spaces, not tabs
Your code doesn't handle uppercase vowels
join doesn't need an argument in this case
charachter is misspelt
Don't create a variable (result in this case) and modify it from inside a block unless you really, really have to. Do something like this instead:

sentence.chars.reduce([]) do |result, char| # reduce is also aliased as #inject
  result << vowels.include?(char) ? "X" : char
end.join

or (building a string instead of an array)

sentence.chars.reduce("") do |result, char|
  result += vowels.include?(char) ? "X" : char
end

or (using a method similar to reduce)

sentence.chars.each_with_object([]) do |result, char|
  result << vowels.include?(char) ? "X" : char
end.join


Let's take a step back and consider the API.

Suppose I want to test the BFS traversal on different graphs.

To call GraphTraverseBFS I need to first create a BFS object. But the BFS constructor creates its own graph and runs GraphTraverseBFS on that. There is no clean way for me to just test it on my own graph.

So let's say that's fixed. Now I want to write some unit tests for GraphTraverseBFS. I can't currently do this without redirecting where the output messages are written to, and then parsing the output. This is more work than I want to do. Ideally I would be able to write something like

CollectionAssert.AreEqual(new[] { 0, 1, 2, 3 }, BFS.Traverse(graph));

The same comments hold for DFS.

List<T> is (generally) an implementation detail.

Graph has a public field List<Node> list. The fact that you're storing nodes in a List is an implementation detail, and should not be exposed to users of this code.

The user now has full access to the methods of List, and can manipulate the list however they want. This is more power than they should have.
The user can reassign the field, e.g. graph.list = null.
It locks you in to your choice of graph representation, as the user may write code that depends on list being a List.

Similar comments hold for Node.neighbors.

One pattern I like for letting the user iterate over a collection, without exposing the choice of implementation is to

Have a private readonly field with your choice of collection type (List, HashSet, etc)
Have a public IEnumerable<T> read-only property that exposes the collection for iteration

In code, it looks like this

public class Graph
{
    private readonly List<Node> nodes = new List<Node>();

    public IEnumerable<Node> Nodes
    {
        get { return this.nodes; }
    }

    ...
}

This might not be entirely suitable for you needs, but this is the sort of API I would suggest

public class Graph
{
    // Creates a new graph with `count` vertices.
    public Graph(int count)

    public IEnumerable<int> GetNeighbors(int node);

    public void AddEdge(int n, int m);
}

public static class BFS
{
    public static IEnumerable<int> Traverse(Graph graph, int startNode = 0);
}

public static class DFS
{
    public static IEnumerable<int> Traverse(Graph graph, int startNode = 0);
}


I had a crack at it, I tried to replace the for loops with higher-order functions, and use ES6 let and const for variable declarations.  I feel like the efficiency of the functions could be improved, but this could be a good starting point to refactoring.  Also, fixed some formatting to make it a bit easier to read.

const AWS = require('aws-sdk');
const fs = require('fs');
const Singer = require('./Singer')
const YTAPI = require('node-youtubeapi-simplifier');

const credentials = new AWS.SharedIniFileCredentials();
const s3 = new AWS.S3({ apiVersion: '2006-03-01' }); //does s3 need to be declared as variable?

const APIKEY = 'AIzaSyDS1p3m9wnZLLCPc1hDQBX3K_UnS4j0CdY'

const bucketParams = {
  Bucket: 'pc-backend-exercises',
  Key: 'toSearch.json',
  ResponseContentType: 'application/json'
};

AWS.config.update({ region: "us-west-1" });
AWS.config.credentials = credentials;
YTAPI.setup(APIKEY);

const singers = []; //do you need this singers array?

s3.getObject(bucketParams, (err, data) => {
    if (err) {
      console.log(err, err.stack);
      return err;
    }

    let fileContents = data.Body.toString();
    let json = JSON.parse(fileContents);
    //I try to avoid for loops if possible
    json.Search.artists.forEach((artist, idx) => singers.push(new Singer(json.Search.artists[idx])));

    console.log('the list of the singers has %d singers',json.Search.artists.length);
    search10TopForASinger();
});

const setSongsArray = (data, songs) => {
  data.slice(0, 10).forEach((song) => songs.push(song.title));
}

const search10TopForASinger = () => {
  console.log('entered search10TopForASinger ')

  let promises = singers.map((singer, idx) => YTAPI.searchFunctions.simpleSearch(singers[idx].name));

  Promise.all(promises).then((results) => {
    console.log('all the threads of the youtube api are back')
    singers.forEach((singer, idx) => setSongsArray(results[idx], singers[idx].songs) )
    printJsonAndUpload();
    console.log('we are done you can test yourself with testGiladFile.js');
  }).catch((e) => {
    console.log(e)
  });
}

const printJsonAndUpload = () => {
  console.log('entered printJson')
  const data = {
    results: []
  };

  singers.forEach((singer, idx) => {
    let singerName = singers[idx].name;
    const singerObj = {};
    singerObj[singerName] = [];
    singers[idx].songs.forEach((song) => { //could use .reduce() here
      const songObj = {};
      songObj[song+1] = singers[i].songs[song];
      singerObj[singerName].push(songObj)
    });
    data.results.push(singerObj);
  });

  console.log('uploading file to s3')
  s3.putObject({ Bucket: 'pc-backend-exercises', Key:'gilad.json', Body: JSON.stringify(data), ContentType: "application/json" },
    (err, data) => {
      //console.log('error');
      //console.log(JSON.stringify(err)+" "+JSON.stringify(data));
    });
  console.log('the name of the file is gilad.json');
}


Writing information from a List of KeyValuePairs into a DataRow

I would approach this first by flattening the prices dictionary into a sequence of values eg { Key, Value, Key, Value, Key, Value }.

// This method is returning object for now since I'm not clear what types are in your data row..
IEnumerable<object> Flatten<K, V>(IEnumerable<KeyValuePair<K, V>> pairs)
{
    foreach (var pair in pairs)
    {
        yield return pair.Value;
        yield return pair.Key;
    }
}

Using this I can simply loop over the flattened dictionary and copy the values into the data row:

int offset = 8;
foreach (var x in Flatten(prices))
{
    res[offset++] = x;
}

I suspect there is a far better term than "flatten" for what I'm doing with the dictionary here.


Child/Parent relationship by adding an element to list

Here's how I might restructure it (note, I've removed many of the generics since it seems to be tied to Document - if you do need those classes to go for other types, go back to the generics, otherwise, YAGNI):

namespace DocumentToDocument
{
    using System;
    using System.Collections.Generic;

    public sealed class MyEventArgs : EventArgs
    {
        private readonly Document document;

        public MyEventArgs(Document document)
        {
            this.document = document;
        }

        public Document Document
        {
            get
            {
                return this.document;
            }
        }
    }

    public sealed class MyList : List<Document>
    {
        public event EventHandler<MyEventArgs> OnAdd;

        public new void Add(Document item)
        {
            var onAdd = this.OnAdd;

            if (onAdd != null)
            {
                onAdd(this, new MyEventArgs(item));
            }

            base.Add(item);
        }
    }

    public sealed class Document
    {
        private readonly MyList children = new MyList();

        private readonly string name;

        private Document parent;

        public Document(string name, Document parent = null)
        {
            this.name = name;
            this.parent = parent;
            if (this.parent != null)
            {
                this.parent.Children.Add(this);
            }

            this.children.OnAdd += (sender, e) => e.Document.Parent = this;
        }

        public string Name
        {
            get
            {
                return this.name;
            }
        }

        public Document Parent
        {
            get
            {
                return this.parent;
            }

            set
            {
                this.parent = value;
            }
        }

        public MyList Children
        {
            get
            {
                return this.children;
            }
        }
    }

    internal static class Program
    {
        private static void Main()
        {
            var d = new Document("I am a parent");
            var dd = new Document("I am a child", d);
        }
    }
}


I think I'd prefer to have the user pass a locale instead of a facet. In most typical cases, a user will deal only with locales, not with the individual facets that make up a particular locale. It's also relatively easy for a user to create a locale on demand, so the code looks something like:

std::string input{"Now is the time for every good man to come of the aid of his country."};

std::string result = upper(input, std::locale("en-us"));

or:

std::string result = upper(input, std::locale(""));

...though I suppose we can probably expect that the default parameter will be used a lot more often than not, in which case all of this is moot.

Anyway, using a locale as the parameter lets us move the use_facet call inside the function body and use auto for it instead of writing out its full type:

auto const& f = std::use_facet<std::ctype<typename String::value_type>>(locale);

Not a huge change, but somewhat simpler nonetheless. Given that you're depending on String being contiguous and supporting random access, it might be worth considering making use of that a little more explicitly, by replacing &str[0]+str.size() with &str[str.size()].

Although I'm somewhat on the fence about it, I'm also less than excited about the idea of using a trailing return type when it's not actually necessary. Maybe it's just a sign of my age, but I still tend to prefer the return type in its traditional location when possible.

Putting all those together, we'd end up with something on this order:

template<typename String>
String upper(String str, std::locale const &locale = std::locale())
{
    auto const& f = std::use_facet<std::ctype<typename String::value_type>>(locale);
    f.toupper(&str[0], &str[str.size()]);
    return str;
}

I'm not sure anybody could call that a huge improvement, but I do think it's at least a minor one, especially in convenience to the user.


First of all some style comments:

Please use spaces after commas and around operators – It is hard to read your sequence of values for the X and y lists when they are all compressed. And the same applies for the ([2,7]) when setting limits. It reads a lot better with [3, 3.2, 3.5, ..., 5.8, 5.9, 5] and ([2, 7])
Choose better names for variables – Why have you used uppercase X and then lowercase y? What does i, k, and m signify?  General recommendation is to use variable names meaning something, longer than one character long. For loop counters there is an exception for i, j, k, in that sequence.
Strange combination of i and k – When I read code having i and k, by convention I'm assuming there to be an j somewhere. This is missing. In addition the i is not a loop counter, but some predicate function for use with numpy's boolean arrays. Try finding a better name for i, possibly something like marker_range_predicate.

And then some considerations regarding your coding algorithm:

First of all I don't quite understand why you want to hide the y-value and replace it with a flat value of 1, and then use markers to denote the few distinct y-values. To me, intuitively, it would make more sense to add markers for given y-ranges, and interconnect markers of a given style with lines. This would show corresponding x-ranges and y-ranges of values

Limit the range of the plot – Your example plot has loads of empty space, which makes the entire plot look almost empty. If you use min and max, you can limit the plot better. If you want to avoid having the min and max values on the axes, you could cheat a little and subtract/add 0.5 to those values. (An even better version would be to calculate the range, and add/subtract a percentage of that range to be used as limits)

Separate x-ranges with different y-values for each marker – In a comment you state that you want to see if the values are linearly separable. To me that read as you might have overlapping x-ranges for different x-values, and you want to visualize this.
In your current code, if you switch the fourth element to y=2, the markers would overlap, so I suggest changing the 1 when you set flat to be the current marker index, i.e. k. This way you would easily see the line of a current marker, but can also see if they are overlapping.

Change size of markers – If adding a parameter, s, to your call to scatter, you can change the marker size, and make them a little more prominent. I found 200to a somewhat good size.

Adding more markers? – I don't know if it's an alternative for you to use even more markers, but I tried adding some more and extended your data array with two extra x-values with a y-value of 2.

Refactored code
import numpy as np
import matplotlib.pyplot as plt

%%matplotlib inline

fig = plt.figure()

axes = fig.add_axes((1, 1, 1, 1))

x = np.array([3, 3.2, 3.5, 3.7, 3.8, 3.9, 5, 5.5, 5.8, 5.9, 5, 5.8])
y = np.array([1, 1, 1, 3, 2, 1, 2, 2, 2, 1, 2, 3])

markers = ['^', 'o', 's', 'v', 'p']

for idx, marker in enumerate(markers):
    i = (y == idx + 1)
    flat = [idx + 1 for val in y[i]]
    axes.scatter(x[i], flat, marker=marker, s=200)

    axes.set_xlim([min(x) - 0.5, max(x) + 0.5])
    axes.set_ylim([min(y) - 0.5, max(y) + 0.5])

This resulted in the following figure:

As you can see there is a lot more empty space, bigger markers, and even easier to see that in my slightly changed base data the x-ranges are not totally separable.


PLZ HELP MEH IMPROVA MEH LOLCAT CODEZ, WHUCH CALCULUTS FAWCTORIALS

Your factorial function enters an infinite loop if passed a negative integer. Since the entire program seems to take 1 input and then exit, I think it would be best if the program gave an error message and then exited.


We have asked to keep the MVC controller as thin, so we decided to move all the service calling/business logic into the ViewModel class.

The concept of the "thin" controller is a guideline to help you avoid having business logic in your presentation layer - it is not as simple as "having more than a little code in controller actions is bad."

In moving this code to your view models, you have effectively coupled them to your service layer without solving the real problem. The controller is responsible for mediating between your services and your presentation logic (views and view models) - that is the entire reason for its existence. Do not just shift code around arbitrarily because of some naive desire to reduce the amount of code in your controller actions.

If you find your controller has too much code in it (or, more importantly, that it has business logic in it), then what you need is an application facade layer that sits between your controller and your service layer, co-ordinates your services and provides a simpler interface for your controllers.

Alternatively, if the code you're trying to move is presentation-layer logic (such as model validation, construction of view models, processing of form values, mapping of view models to service-layer entities etc.), then it does belong in your controller - even if there are more than a couple of lines of it. You can still simplify things by breaking it up into helpers if it's beneficial to do so, but don't do this just because someone told you that your controller actions shouldn't have more than five lines of code in them.


Is there a more elegant way of arranging my forms?

My bad, I think see now what you wanted. I just did not feel like reading your logic fully (too many details). After I did read it, I saw that you got the details right. All you needed was to stick your points into a list or enumerate over them, as in this example. This way, if you feel like adding more options - you can. Let me know if this works, so that I can delete the other answer.

private void Place_Form(Form formToPlaceNextTo, Form formToPlace)
{
    foreach (Point pointToTry in EnumerateFormPlacement(formToPlaceNextTo, formToPlace))
    {
        var rectToTry = new Rectangle(pointToTry.X, pointToTry.Y, formToPlace.Width, formtoPlace.Height);
        if (Screen.FromControl(formToPlace).WorkingArea.Contains(rectToTry))
        {
            formToPlace.Location = pointToTry;
            return;
        }
    }

    // Else no match, hence default location.
}

private IEnumerable<Point> EnumerateFormPlacement(Form formToPlaceNextTo, Form formToPlace)
{
    Point alignRightTop = new Point(
        formToPlaceNextTo.Location.X + formToPlaceNextTo.Width,
        formToPlaceNextTo.Location.Y);
    yield return alignRightTop;

    Point alignRightBottom = new Point(
        formToPlaceNextTo.Location.X + formToPlaceNextTo.Width,
        (formToPlaceNextTo.Location.Y + formToPlaceNextTo.Height) - formToPlace.Height);
    yield return alignRightBottom;

    Point alignLeftTop = new Point(
        formToPlaceNextTo.Location.X - formToPlace.Width,
        formToPlaceNextTo.Location.Y);
    yield return alignLeftTop;

    Point alignLeftBottom = new Point(
        formToPlaceNextTo.Location.X - formToPlace.Width,
        (formToPlaceNextTo.Location.Y + formToPlaceNextTo.Height) - formToPlace.Height);
    yield return alignLeftBottom;
}


Here's my take on your code. Longer, but in my opinion, easier to follow since it is written as a chain of operations on arrays.

In addition, I use array methods, which easily chain together. Their callbacks are moved out for clarity. They're also written in a way that a function doesn't use outside variables. Makes your code more predictable and easily modifiable without dragging along other stuff.

// The first phase of your code is just mapping obj into another form. Use map().
function inputMapper(obj) {
  var setting = {};
  // Using the bracket notation to keep it uniform.
  setting['ticked'] = true;
  setting[category] = obj;
  return setting;
}

// Removing items first will make further operations iterate less.
// Additionally, we use reduce to carry around the data, and the already-found categories
function duplicateCategoryRemover(carry, item) {
  if (!~carry.categoriesFound.indexOf(item.category)) {
    carry.items.push(item);
    carry.categoriesFound.push(item.category);
  }
  return carry;
}

// Nothing special, just your sorter moved out.
function categorySorter(a, b) {
  return (a[category] > b[category]) - (a[category] < b[category]);
}

// Now everything's in place, let's do the magic.
function inputSet(input, settings, category) {
  return input.map(inputMapper)
              .concat(settings)
              .reduce(duplicateCategoryRemover, { items: [], categoriesFound: [] })
              .items
              .sort(categorySorter);
};


The concept is good, but there is room for improvement. Here are some problems I see:
Misleading names
Clear names are very important in coding, because they make it easy or hard for other people (including your future self) to understand what you have written. Some of the names you have used do not match what the code actually does, which is confusing.

Based on the name of the Human class, I'd expect an instance of this class to represent one human, but that is not how it is used (see below).
Based on the name of the Player class, and the way it extends Human, I'd expect an instance of this class to represent one player; if so, then there should be 22 instances of the class, or one object for each name in the players list. Instead, it seems to represent all the players at once, which its name does not imply.
I would expect the name attribute of Human to store a single name, but Player stuffs an entire list of player names into that attribute.

At minimum, these names should be made plural (Humans, names, Players, etc.) to reflect their contents. It would be even better to give Player a name that describes what it actually does, or what it is responsible for within the program.
Unnecessary hierarchy, part 1: only one subclass
You mentioned in a comment that you are trying to practice your OOP skills, so "[you] want to force [yourself] to use classes even if it sounds silly". Practice is good, but part of good OOP is understanding why and how to use classes and objects effectively...and that includes knowing when not to use them, or when not to use certain parts of them.
For example: why do you need both a Human class and a Player subclass? In the program that you have now, the only humans are players; therefore there is no advantage to having two classes. You could do everything in the Player class and drop the Human class altogether, or vice versa. On the other hand, if you already have plans to expand your program to include non-player humans (e.g. coaches, referees), then a Human superclass might make sense. The structure of the code should fit your use case.
Unnecessary hierarchy, part 2: superclass does nothing
A subclass is supposed to have a "type of" or "kind of" relationship to its superclass, e.g. a Square is a kind of Rectangle, or a Dog is a kind of Animal. The problem is that your code does not gain much from defining Player as a kind of Human. Since Human has no defined behaviors and barely any data, inheriting from it doesn't provide many benefits. It would be simpler and more flexible to use composition instead of inheritance, by creating or importing a Human object inside the Player object.
Unnecessary use of internal state / object attributes
One of the nice things about objects is that they can create and maintain an internal state--a little chunk of data that it hides away from the rest of the program. (Keeping separate things separate is called encapsulation or separation of concerns, and it makes programs much easier to think about and easier to debug.) In Python, internal state is stored in object attributes, like Human's self.name. But you have to know when to use internal state and when not to use it. Keeping multiple copies of the same data in different places, or multiple references to the same data object, can cause confusion and lead to bugs.
Your get_team() method takes a list of players, splits the players between two known teams, and then returns a dict() with that information. This method is called only once in your entire program. So, what is the advantage of having the Player object store the list of player names inside itself? In the current code, there is no advantage. You could easily change get_team() to a class method (which can be called without instantiating an object) that takes the player names as a parameter.
Hardcoded assumptions
# list of teams
teams = ['A', 'B']

Since you defined this teams list at the top of the code, I would assume that editing that list would change the program output. But when I look closer, I can see that this list is not even used. Your get_team() method is explicitly written to split the players into two teams named 'A' and 'B', regardless of what is in the list above.
        teams['A'] = self.name[0::2]
        teams['B'] = self.name[1::2]
        return teams

This is not very flexible, especially if you want to import the team names from outside the program (e.g. from user input, or from a config file). A better method would take a list of teams as an input, count the number of teams, and then split the players accordingly.

Here's how I might write it:
TEAMS = ('A', 'B')  # Replaced mutable list with immutable tuple.
                    # Names of constants should be in all-caps.
PLAYERS = ('a', 'b', 'c', 'd', 'e',
           'f', 'g', 'h', 'i', 'j',
           'k', 'l', 'm', 'n', 'o',
           'p', 'q', 'r', 's', 't',
           'u', 'v')

class TeamAssigner:
    def assign_players_to_teams(teams, players):
        players_on_teams = dict()
        randomized_players = random.sample(players, len(players))  # changed to .sample because .shuffle doesn't work on tuples / immutable sequences
        for i, team in enumerate(teams):
            players_on_teams[team] = randomized_players[i::len(teams)]
        return players_on_teams

my_teams = TeamAssigner.assign_players_to_teams(TEAMS, PLAYERS)
for team, name in my_teams.items():
    print(team, name)

Of course, this is only what I would write if I was not planning to expand the program in the future. If you have plans to make the program bigger and make it do more things, then some of these decisions might be the wrong ones. For instance, if you wanted the ability to move players from one team to another after the initial split, then you would need a class that did keep an internal state of who is on which team...


I like this code;

There are perhaps a few too many newlines, especially here:

         });

      };

   }

}

work and auto are unfortunate function names, you could do better
slide = $('.slide'), <- I would have called that slides since you are almost bound to select more than 1 slide with this selector
The repeated magical constants 3000 and 200 should be identified, named and centralized


FEAR

This is a red flag.

Do Until IsSorted(collectionObject)

    ' Sorting algorithm

Loop

Your algorithm should return a sorted sequence and should not need to be checked.  If it fails the check you should rewrite your sorting algorithm and not simply try to do it again.

Abstracting Methods

This bit of code is used often enough to merit it's own sub routine

Sub AssignUnknown(ByRef dest As Variant, ByRef src As Variant)

    If IsObject(src) Then
        Set dest = src

    Else
        dest = src

    End If

End Sub

Now your code looks so much better!  It looks like a bubble sort but

For i = 1 To collectionObject.count
    index = i

    AssignUnknown item, collectionObject(i)

    For j = i To collectionObject.count

        AssignUnknown innerItem, collectionObject(j)

        If item > innerItem Then

            collectionObject.Add item, After:=j
            collectionObject.Remove index
            index = j

        End If

    Next j

Next i

Algorithm

it doesn't work, hence you needing to loop until it is sorted.  You are only a few steps away from true bubble sort though, which is IMO simpler.

    For i = collectionObject.count To 2 Step -1

        ' hasSwapped = False

        For j = 1 To i - 1

            If collectionObject(j) > collectionObject(j + 1) Then

                collectionObject.Add collectionObject(j), After:=j + 1
                collectionObject.Remove j
                ' hasSwapped = true

            End If

        Next j

        ' If Not hasSwapped Then goto sorted ' Exit For

    Next i

sorted:

In short, instead of bubbling up the same object each time, the BubbleSort drops the current item for the next one when it finds a larger item.  This means after each inner loop the item at position i is in the correct place, which is why the outer loop is counting down not up.

hasSwapped uncommented allows for early exit if the sequence is already sorted.  For more information on the bubble sort, wikipedia has a great article.  I also found this site with some cool animations while trying to figure out your sorting algo.

Also note that AssignUnknown is no longer needed.

Error Handling

As we discussed in the comments, the comparison operators will not be defined for objects that do not have a default property.  It can't be fixed, but we can raise a more descriptive error

    On Error Goto no_default_property

    ' bubble sort

sorted:
Exit Function
no_default_property:

    If Err.Number = 438 Then ' preferably use the vb constant that I don't know
        Err.Clear
        Err.Raise 438, "Sort", "An item in the collection does not have a default property"

    End If

End Function

After Thoughts

Consider writing CollectionToArray and ArrayToCollection functions so you don't need to duplicate sorting methods for Collections and Arrays.  Also consider a Sorted function that returns a sorted copy.

Sub Sorted(collec As Collection) As Collection

    Set Sorted = collec
    Sort Sorted

End Sub

I was tempted to insist you use a Swap function like this.

Sub Swap(ByRef a As Variant, ByRef b As Variant)

    Dim t as Variant
    t = a
    a = b
    b = t

End Sub

However, you are supporting objects in your collection, you will need to make that routine SwapUnknown that uses AssignUnknown.  You could avoid calling IsObject(a) twice but I prefer the simpler solution.

Sub SwapUnkown(ByRef a As Variant, ByRef b As Variant)

    Dim t as Variant
    AssignUnknown t, a
    AssignUnknown a, b
    AssignUnknown b, t

End Sub

I didn't include this because:

Your current swap method could be faster depending on how Collection is implemented
Abstracting your current method seems pointless.
It doesn't require AssignUnkown, which cuts out some ugly code.


<stdbool.h>

Unless you need compatibility with C89 for some reason, I would use bool for the return type of the function and true and false as the possible values.

It helps readability.

sscanf()

This one depends on your performance needs.  A solution using sscanf() will be much easier to understand with a simple look and also shorter in code, but may also be much slower (a benchmark would be appropriate).

Update: I would discard sscanf() because it would accept spaces before the numbers; better use inet_pton() as @vnp suggested.

<stdint.h>

Same as with bool: segs seems at first glance to be some string, but after some time I realized it's just an array of 8-bit unsigned integers.  You should use uint8_t for that.

In case of <stdint.h> I would say that if you don't have it, you should do the typedefs yourself (enclosed in some #if) anyway.  Don't do that with bool, however, which is very dangerous.

Unneeded cast

unsigned char *p;
int i;

...
*p = (unsigned char)i;

This cast is not needed.

Usually casts are very dangerous: they can hide bugs that otherwise the compiler would catch easily.  Don't ever cast, unless you know a very good reason to.

BUG! (No, I was wrong)

// Check numeric.
if (*str < '0' || *str > '9')
        return 0;

This line returns 0 at the first dot it finds.  The function doesn't work!

This if that comes later is always false due to that:

// Segment changeover.
if (*str == '.') {
        /// Unreachable code!!!
}

<ctype.h>

There are some functions in <ctype.h> that you should use:

// Check numeric.
if (*str < '0' || *str > '9')
        return 0;

That code above can be simplified to this one (and the comment is now even more obvious and therefore removed ;-):

if (!isdigit((unsigned char)*str))
        return 0;

  NOTES: The standards require that the argument c for these functions is either EOF or a value that is representable in the type unsigned char.  If the argument c is of type char, it must be cast to unsigned char.

  This is necessary because char may be the equivalent of signed char, in which case a byte where the top bit is set would be sign extended when converting to int, yielding a value that is outside the range of unsigned char.

See man isdigit.

If you're going to use these functions, I would create an unsigned char pointer to alias the char * parameter, so that you don't need to cast all the time.


Use lexical filehandles instead of typeglobs (read here for more about why; the biggest problem with typeglobs is that they are global in scope).

open (my $handle,'<:utf8', $file) || die "wrong filename";

You should close your filehandles sooner rather than waiting til the end of the program, if possible. For example, there's no reason to keep HDB open after its contents have been read into memory.
Consider changing @db to a hash, then using exists to check whether a word is in the exclude list. This should be faster than looping through the array (depending on how many words are in the exclude list and how often a word will be in the list). Since case is not important, you could call lc or uc before testing.

If you want to keep it as an array, then consider exiting the loop using last once the first match is found.
You sort the keys of %wordlist twice using the same criteria. Consider storing the sorted list in a new variable.


In large I think the sort function is right out of the book of bubblesort.

IMO your naming is a little overdone. The long names are for an inexperienced eye hard to read.

The ascending and descending sort loops are essentially the same except for the direction of the comparation, so no need for backward loop or special temporary variables etc.

The swap mechanism calls for a swap function.

All in all find below a revised version of the sort function.

Private Sub Swap(vector() As Double, i As Long, j As Long)
    Dim tmp As Double
    tmp = vector(i)
    vector(i) = vector(j)
    vector(j) = tmp
End Sub

Private Sub BubbleSortNumbers(vector() As Double, Optional sortAscending As Boolean = True)
    Dim index As Long
    Dim isChanged As Boolean
    Dim first As Long
    Dim last As Long

    first = 1
    last = UBound(vector) - 1

    If sortAscending Then
        Do
            isChanged = False
            For index = first To last
                If vector(index) > vector(index + 1) Then
                    isChanged = True
                    Swap vector, index, index + 1
                End If
            Next index
            last = last - 1 ' The not yet positioned largest value "rabbits" down to its final position for every loop, so there is no need for checking it again.
        Loop While isChanged
    Else
        Do
            isChanged = False
            For index = first To last
                If vector(index) < vector(index + 1) Then
                    isChanged = True
                    Swap vector, index, index + 1
                End If
            Next index
            last = last - 1
        Loop While isChanged
    End If
End Sub

All that said, bubble sort is not the most efficient algorithm, so if you have large data sets to sort I will suggest other more powerfull algorithms like quicksort, mergesort, heapsort or combsort where quicksort and combsort maybe are the easiest to implement (they are all well documented on Wikipedia).


Your equals method is not transitive (e.g. Point(2, 2) == Point.Wildcard and Point.Wildcard == Point(3, 3) but Point(2, 2) != Point(3, 3). See Any.equals - stdlib - Kotlin Programming Language for more details on the requirements for equals. You might also consider using EqualsTester from guava-testlib for testing your own implementations of equals.

If you define your own method instead of defining a custom, non-transitive equals implementation than your existing solution can become much simpler:

data class Point(val line: Int, val column: Int) {
    companion object {
        val wildcard = Point(-1, -1)
    }

    infix fun matches(other: Point): Boolean {
        return this == other || other === wildcard || this === wildcard
    }
}

Notes:

Point(2, 2) matches Point(-1, -1) will return false.
Point(2, 2) matches Point.wildcard will return true.
If you want both to return true then replace the === with == in matches.
Marking matches as infix is purely optional but it seems to me like a good fit.


You are asking if you can speed up the assignment into the array?
I don't think you will be able to get a notable speed improvement on this part no. This should be completely negligible compared to the data retrieval time.
What would give you a notable speed improvement is not using a cursor and doing this in a set based manner... however we would need to see your query to attempt to suggest something for this.


Suggesting you move to using promises instead of callbacks. This way, you don't have to do the tango with calling callbacks, collecting results and all. You can simply replace the request module with the request-promise module.

function getResult(options){
  ...
  return doRequest(options);
}

...

lotto(options).then(results => console.log(data), err => console.log(err));

There's little merit of putting doRequest inside getResults. It's only being used in getResults but it's not exposed anyways. Suggesting you move it out into the module.

JavaScript doesn't have default argument values (yet) but you can easily do the same thing using Object.assign. Provide a default object, and merge to a new object the defaults and the one from the arguments. This way, you avoid having to do a lot of default logic and value checks.

var defaults = {...}

function getResults(options){
  var mergedOptions = Object.assign({}, defaults, options);
  ...
}

Back to promises, firing multiple async calls in parallel using callbacks will require you to collect results and keep checking if all the requests have responded. When using Promises, you can easily use Promise.all to listen to an array of promises.

var request = require('request-promise');

function getResult(options){
  ...
  var drawRange = toDrawID - fromDrawID;

  // Create an array of drawIds and map them to promises
  var promises = Array(drawRange).fill(fromDrawID).map((fromDrawID, i) => {
    return request(url + (fromDrawID + i));
  });

  return Promise.all(promises);
}


I'm rather new to C#, and found relevant subclassing examples
  surprisingly hard to come by

You just needed to try a bit harder! You are doing pretty much what you were supposed to do logic wise. What you are trying to do here obviously (maybe), is a specialization of a RestClient, so the RestClient class is the best candidate to inherit from. From there you may override the Execute method.

Don't be afraid to use verbose variables. The rpm name could be firstly reminded as rotations per minute which doesn't really apply here. Also try to name your instances fields in camelCase, you may or may not prefix them with _.

I also didn't get why your pause is (60 * 1000) / rpm = 1000 with the default rpm, but one thing I know is that you don't need to store it in a field because it may be calculated. I would also recommend using Environment.TickCount instead of DateTime.Now.Ticks, which is more performant.

With those modifications the code would become the following:

public class ThrottledRestClient : RestClient
{
    private readonly int _requestsPerMinute;
    private int _lastRequestTime;

    public ThrottledRestClient(int requestsPerMinute)
    {
        _requestsPerMinute = requestsPerMinute;
    }
    public override IRestResponse Execute(IRestRequest request)
    {
        int elapsedTime = Environment.TickCount - _lastRequestTime;
        int pause = (60/_requestsPerMinute)*1000;
        int wait = pause - elapsedTime;
        if (wait > 0)
        {
            Thread.Sleep(wait);
        }
        var response = base.Execute(request);
        _lastRequestTime = Environment.TickCount;
        return response;
    }
}

EDIT: To answer you comment. You can use this client like you would use the previous one eg:

var client = new ThrottledRestClient(60);
client.Authenticator = new HttpBasicAuthenticator("user", "password");
//so on so forth;
client.BaseUrl = "http://google.pt";
client.Request(new RestRequest());


Putting data from 3 text files into 3 variables

For one thing, you can use file_get_contents:

$email_template = file_get_contents($template_filename);
$subject_template = file_get_contents($subject_filename);
$footer_template = file_get_contents($footer_filename);


Overview
Your code as written is perfectly fine (apart from the one bug in subtraction). Anything mentioned here is mainly to help future readers.
You overcomplicated the design by adding constructors to Vector2D.
The default constructors work perfectly and as expected in this type of situation.
There is an argument to make operators members of the class rather than free standing functions. But either work.
Your use of reference marker & is very C like. You put it next to the variable rather than next to the type. This is very subjective style thing (usually dictated by your style guide). But C++ guides skew one way while C guides skew the other.
 void doStuff(C const& param)
              ^^^^^^^^   param has a type: C const&

 void doStuff(C& param)
              ^^         param has a type: C&

This has happened because in C++ types are much more significant and important. So we pay much more attention to type things in C++.
Code Review
I am going to have to take your word that this is how concepts work. I look forward to this becoming available more consistently.
    template<typename T>
    concept Arithmetic = std::is_arithmetic_v<T>;

    template<Arithmetic T>
    struct Vector2D
    {

Sure but not needed if you don't define other constructors (see below).
        Vector2D() = default;

Sure but not needed as the brace initializers works and does this for you:
        Vector2D(T x, T y);

Sure: But not needed the default copy constructor should work here.
        Vector2D(const Vector2D<T> &other);

Don't need to declare these inline here. It has no effect. You put the inline next to the method definition to make sure that the compiler does not give you multiple definition warnings.
        inline T Magnitude() const;
        inline Vector2D<T> Normal() const;
    };

I would note that the inline keyword has nothing to do with in-lining the code. The compiler decides that without any help from the engineer (because it is better at than you).
I would have simplified that to:
    template<Arithmetic T>
    struct Vector2D
    {
        T  x;
        T  y;

        T Magnitude() const;
        Vector2D<T> Normal() const;
    };

Arithmetic Operators:
There is a debate about if these should be members or free standing functions. Either is fine. I will not ding you for doing it one way when I would have done it another.
There is an argument for making them free standing functions. But this is usually based around symmetry when using the operators.
   R = X + Y;

If you use methods:
If X is Vector2D and Y is not then the compiler can potentially convert Y into Vector2D and still apply the operation. But if it is the other way around: Y is Vector2D and X is not then the compiler can not convert X to a Vector2D.
If you use free standing functions:
Then if one parameter is Vector2D then the other can be converted to Vector2D and the function applied. This you have symmetrical conversions.
This is fine if the types are "Arithmetic" in nature and can easily convert from anything into your type; this is not the case here with Vector2D. So this argument does not stand. I would also argue that this applies to most types; you have to have a very good argument that your type should allow auto conversion (most types don't and use explicit on one argument constructors to prevent this).
Thus here you can use either technique and both are fine.
I personally would have made them members of the class (the sole reason is to add clarity so you can read the class and see all the things you can do to change them). You could argue you can have the same affect by adding all the declarations for arithmetic operations as friends to the class (or simply put the declarations directly under the class (and I could not argue against his).
Whatever way you decide. I would put the declarations beside the class and away from the definition so it is easy to see all the possible operations that apply to the class.

Normally we implement operator+ in terms of operator+=.
    template<Arithmetic T>
    inline Vector2D<T> operator+(const Vector2D<T> &first, const Vector2D<T> &second)
    {
        return Vector2D<T>(first.X + second.X, first.Y + second.Y);
    }

I would write like this:
    template<Arithmetic T>
    inline Vector2D<T>& operator+=(Vector2D<T>& first, Vector2D<T> const& second)
    {
        first.X += second.X;
        first.Y += second.Y;
        return first;
    }

    template<Arithmetic T>
    inline Vector2D<T> operator+(Vector2D<T> first, Vector2D<T> const& second)
    {
        // Note Pass first by value.
        // This automatically gets us a new version of the object.
        // The compiler will be able to detect if we can use move/copy
        // automatically to get this move version.
        //
        // We can then do the += on this new copy.
        // and perfectly return this value as output.
        return first += second;
    }

This seems like a bug:
    template<Arithmetic T>
    inline Vector2D<T> operator-(const Vector2D<T> &first, const Vector2D<T> &second)
    {
        // Should you not subtract here:
        return Vector2D<T>(first.X + second.X, first.Y + second.Y);
    }


Executing functions and declaring flags with a long battery of if conditions

This is bad.  Very bad.

It appears the original implementer doesn't quite understand arrays.  You should definitely refactor this.  Michael K's answer has the right approach.  In C# syntax:

// Hopefully these variables are already in an array or list already, otherwise:
MyType[] myVariables = new MyType[] { varOne, varTwo, /* ... */ varEight };

foreach (MyType variable in myVariables)
{
    if (variable == flag)
    {
        run_some_sql();
        set_some_flag = true;
    }
}

Note that if run_some_sql() only needs to be executed once, you can break out early and save some computation time:

foreach (MyType variable in myVariables)
{
    if (variable == flag)
    {
        run_some_sql();
        set_some_flag = true;

        break;
    }
}

If it is the case that you only need to execute run_some_sql() once, you can make the code even simpler using new LINQ syntax:

if (myVariables.Any(v => v == flag))
{
    run_some_sql();
    set_some_flag = true;
}

While refactoring, I'd also recommend choosing some better variable names than varOne, varTwo, flag, etc.  Though I assume these are just your examples. :)


Local Storage accessor and modifier helper

my two cents :

add .idea to your .gitignore. If someone else uses the same IDE as you and works on this code, it could get very frustrating.
your code is not minification-proof, which can be annoying for someone who plans to use it. See angular's doc (section "a note on minification") for directions on how to fix this.
you dynamically extend String.prototype - this kind of monkey-patching can create conflicts with other libs, and lead to unexpected behaviors. If you want people to use your code, you should avoid this, especially for such simple code that you only use once.
you have two different entities defined in the same file, but that's ok as the whole lib is very lightweight. For more complex projects, split up your code, one entity per file.
your code lacks tests, which is a major no-go for many people.
instead of the quirky ng-change directive, you can directly set a change handler during the linking phase using $scope.$watch('something', function(){...}).


There's very little to review.

Variable Names

Use full names for variables, avoid short forms of those words/abbreviations. For example, you wrote, $stmt, instead you could write $statement to increase the readability of the code.

Class Names

Your class name, addProfile is not really suitable to give the image of the class. Why not name it, CreateUserProfile since that is what it does?

Also, class names should be declared StudlyCaps.

Validation Checks

Why not perform validation checks for what user has input? For example check if the variables are empty or not.

Coding Standards

Your coding style does not meet the coding standards.

Working Code

You have not provided us with a working code, as there would be an error with bind_param() because you haven't used any '?' and directly injected the variables like this, which is vulnerable to SQL injection.

$stmt = $this->mysqli->prepare("INSERT INTO SendingProfiles (fromemail,Fromname,Profilename,replaytoemail)
    VALUES ('$profileName','$profileEmail','$profileFromName','$profileReplayToEmail')");

Instead, do this:

$stmt = $this->mysqli->prepare("INSERT INTO SendingProfiles(fromemail, Fromname, Profilename, replaytoemail) VALUES(?, ?, ?, ?)");


Selecting from a database into a DataGridView

Three possible problems that I see.

dbConnection = New SqlConnection("Data Source=connectionhere\sqlexpress;Initial Catalog=line_log;Integrated Security=True")

You have a hard-coded connection string. If you want a different database location then you need to edit the code. Perhaps it's better to have the connection string in an editable config file.

The original version which prompted this review ...

strSQL = "SELECT [item] FROM [table] WHERE ([item] = 'value')"

... seems to build the select statement by string manipulation of the value and therefore may be vulnerable to SQL injection.

You have SQL code and Form code in the same source file. It may be better to separate these into different classes so that they can be tested and re-used independently.


Reverse string in JavaScript without using reverse()

One array to rule them all
You do not need to create two arrays; one is enough. Simply swap slots until you've reached the "middle" of the array.

Declare your variables
It is better to use the var keyword to define your variables. Otherwise, they are declared on the top-level scope, i.e; they become global, and may be accessed and modified by other functions.

Why not use reverse()?
You do not say why you cannot use built-in functions. If you happen to have some base code which overrides native functions, then some groaning and roaring is in order.

function reverse(str) {
  var chars = str.split("");
  var length = chars.length;
  var half = length / 2;
  for (var ii = 0; ii < half; ii++) {
    var temp = chars[ii];
    var mirror = length - ii - 1;
    chars[ii] = chars[mirror];
    chars[mirror] = temp;
  }
  return chars.join("");
}

console.log(reverse("abcd"));
console.log(reverse("abcde"));


Finding the minimum number of moves to achieve equal array elements

The problem can be re-formulated into a much easier-to-conceptualize form.

Instead of

  Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

say instead

  where a move is decrementing a single element by 1

Do you see why these are the same?  Suppose we start with 1, 2, 3.  Adding 1, 1, 0 produces 2, 3, 3.  Adding 0, 0, -1 produces 1, 2, 2, which is effectively the same thing. However many moves it takes to make 2, 3, 3 all equal is surely the same number of moves as it takes to make 1, 2, 2, all equal, or 0, 1, 1, or 1000, 1001, 1001, or whatever. Where you start is irrelevant.

Once you know that the problem is actually "how many single decrements does it take to get all the elements equal?" the answer is easily seen. There is never any point in decrementing the smallest element, and every element will have to eventually equal the smallest element. Therefore the answer is: it's the sum of the differences of every element from the minimal element.

That's a trivial program in C#:

var min = nums.Min();
return nums.Select(x => x - min).Sum();

Or alternatively, in a single line:

return nums.Sum() - nums.Length * nums.Min();

(Though as noted in the comments, this second version can overflow. Consider doing all the math in longs or BigIntegers if you're worried about overflow cases.)


Adding a bookmark, or changing an existing one

It would be more natural to call isFound simply found.

If I understand correctly,
after the loop, there is more code in your application.
In which case, the function does too much.
There should be at least 3 functions:

A function with the loop, returning the position found, or else -1, as is pretty common with functions that search for something in a container
A function that takes a position found, and does something with it (the code you didn't post)
A function that calls the previous two

This way, you could get rid of the found and posFound state variables.
And in any case, no need to check bookmarks.length,
the iterating logic automatically takes care of the empty case.

The function then becomes:

function addBookmark(obj) {
    for (var j = 0; j < bookmarks.length; j++) {
        if (obj.mirror == bookmarks[j].mirror &&
            obj.url == bookmarks[j].url &&
            obj.chapUrl == bookmarks[j].chapUrl &&
            obj.type == bookmarks[j].type) {
            if (obj.type == "chapter" ||
                obj.scanUrl == bookmarks[j].scanUrl) {
                return j;
            }
        }
    }
    return -1;
}

For readability, I would also extract the complex conditions to a helper function with a descriptive name.
The name of the function would describe the meaning of those conditions.


NAddOdd - Topcoder - Single Round Match 714 Round 1 - Division I, Level Two

First the minor things about your coding style:

0l should be 0L to avoid confusing it with 01
ALWAYS use brackets after each if/for/while/...
variables are lowerCamelCase by convention. You don't need to copy the question literally. Using single capital letters usually means it's a generic type parameter. It does make sense to use l, r and k here instead of longer more readable names though, since the method is directly related to the given question.
throws InteruptedException can be removed since it's never thrown.
if(map.get(h)==null) is always true after the initial != null check. No need to check that again.
putting something in a map to then taking it out again right after seems silly. Just store it in a temp variable.

There are 2 small optimisations that reduce entries in the map without giving up speed.

The first optimisation is to first check if h is smaller than k and return 0 without storing it.

public static long solveInter(long h, long k) {
    if(h <= k){
        return 0L;
    }
    if(map.get(h) != null){
        return map.get(h);
    }

The second is for odd numbers to also do the following "even" step at the same time like this: map.put(h, 2 + solveInter((h+k)/2, k));

That way, no number larger than R is ever stored.

After a bit of testing it seems a lot more numbers don't need to be stored as well. For example running

public static void main(String[] args) throws Exception{
    System.out.println("total: "+ solve(1000000L, 1001000L, 1001));
    System.out.println("stored entries: " +map.size());
}

shows that this change alone reduces the entries from 15941 to 10962 and this for the total: 19478 steps in the solution.

That's about as much as I can save on your solution without making compromises. If you don't mind giving up a bit of speed to further reduce the number of stored results (to solve the memory issues) you can for example not store any even numbers. This changes the computation from this:

    if(h%2 == 0){
        int result = 1 + solveInter(h / 2, k);
        map.put(h, result);
        return result;
    }

    int result = 2 + solveInter((h + k) / 2L, k);
    map.put(h, result);
    return result;

into this:

    int result = 0;
    while(h%2 == 0){
        if(h <= k) {
            return result;
        }
        result ++;
        h /= 2;
    }

    result = result + 2 + solveInter((h + k) / 2L, k);
    map.put(h, result);
    return result;

This then get's the stored entries in the previous example down to 5730.

I didn't run this on the 4th example
(System.out.println("total: " + solve(1645805087361625L, 9060129311830846L, 74935));)
because those numbers are huge and will take a long time even if you would have a lookup table for all the solveInter results.

I have no idea about how many entries you can store in the map. I did notice that the chains are usually really short. Even for huge numbers like:

System.out.println("total: "+ solve(Long.MAX_VALUE-1, Long.MAX_VALUE-1, 1));

the total is only 66. This is because number goes down logarithmicaly. Even if you have a lot of odd numbers the total will only be 2 or 3 times as large. So to reduce the memory requirements further you could change the map to Map<Long, Short> (32000 will certainly be big enough to store the length of the chain).

Perhaps someone more math minded can come up with some more speed improvements by reducing the required calculations :)


I don't know exactly what you mean about semantic and modular, but I usually like to use object oriented programming. You could create multiple and isolated players.

function AudioPlayer(src, $control) {

  var _this = this;

  this.src = src;
  this.music = new Audio(src);

  this.btnPlay = $control.find('.button__play');
  this.btnPause = $control.find('.button__pause');
  this.btnStop = $control.find('.button__stop');
  this.btnRepeat = $control.find('.button__repeat');
  this.btnRate = $control.find('.button__rate');

  this.btnPlay.click(function(event){
    event.preventDefault();
    _this.music.play();
  });

  this.btnPause.click(function(event){
    event.preventDefault();
    _this.music.pause();
  });

  this.btnStop.click(function(event){
    event.preventDefault();
    _this.music.pause();
    _this.music.currentTime = 0;
  });

  this.btnRepeat.click(function(event){
    event.preventDefault();
    $(this).toggleClass('button__active');
  });

  this.btnRate.click(function(event){
    event.preventDefault();
    $(this).toggleClass('button__active');
  });

}

AudioPlayer.prototype.play = function() {

  this.music.play();
}

AudioPlayer.prototype.pause = function() {
  this.music.pause();
}

$(document).ready(function() {

  //Here you could create more isolated audio controls and instantiate them

  var controlPlayer1 = $('.container');
  var player1 = new AudioPlayer('http://www.w3schools.com/tags/horse.mp3', controlPlayer1);
})


Constructor

I wouldn't extract the POST values inside the constructor. For the calculator class, it shouldn't matter where the values come from (it could be POST, GET, the database, anywhere really).

I would just pass the arguments as variables like this:

public function __construct($number1, $number2, $prefix) {
    $this->number1 = $number1;
    $this->number2 = $number2;
    $this->prefix = $prefix;
}

Your constructor also defined $number1 etc without using it. If you want to stay with your approach, the assignments should look like this: $this->number1 = $_POST['number1'];

Input Checking

Right now, you just accept anything the user passes. For example:

prefix=*&number2=0xf&number1=0xd
-> 195
prefix=-&number2=5
-> -5
prefix=*
-> 0
prefix=/
-> error (because of the division by 0)

If this is your intention, then that is fine, but otherwise you should check if all values are set and if they are all decimal numbers.
At the least I would  check for division by 0.

Misc

I would call prefix command or operation.
it is customary to use CamelCase for class names, so 'calcdata' could be 'CalcData' (or something a bit more concrete like BasicCalculator).
your indentation is off. Any IDE can fix this, and it makes your code more readable.
you have unnecessary newlines (which makes your code a bit harder to read).

  is it wise to use the switch statement in a function?

In this case it's fine, but if you plan to create a more complex calculator class, I would just create public add, divide, negate (just one argument), log (three arguments), etc. methods, because a calculator should only have to calculate, it shouldn't actually be the calculators job to decide what it calculates. And it would be hard to manage once you have functions with more or less than two arguments.

So in that case I would extract the switch statement to a separate controller class which then decides what to calculate based on the user input.


Inserting an object pointer to a two-level map

General improvements

Names

C++ member and variable declarations don't tell you the type of an object; they tell you what operations on it are legal.  Prefer Block *newBlock (object dereferenceable to value of type Block) to Block* newBlock; the latter will only confuse you.

Tradition is to use all lowercase and separate words with underscores, but your naming convention is fine too.

Do you really mean "table"?

Technically, what you've written here is not a table, but closer to a jagged array.  You have no compile-time constraints forcing the members of each row to be of the same length, so you could have a table looking like this:

This image was pulled off the internet; the naming convention doesn't quite match your code.

Do you mean that to be the case?

It's not just the varying row lengths that's strange.  Because each row is a map to the values of each block, the idea of each block having a fixed index is wrong.  In short, make sure your data structure matches your mental image of it.

Finally, if you do want each block to have a fixed index and you want a rectangular table, I wouldn't bother with an intermediate data type RowBlock.  Instead, I would just have BlockTable manage the row/column distinction directly.  This also allows you to flatten your table, if performance demands: instead of n different rows of length n, you have a single array of length n*n.  What consumers of your class call the (r,c)th element is then internally at index n*r+c.  This reduces memory fragmentation.  I'm not going to flatten your tables for you, but it is something to consider.

Memory management

  I know it is not a C++ thing to play around with pointers but rather use const references, but again this is part of a bigger problem that we are trying to solve.

No!  The important thing is to be aware of the lifetime of your memory and ensure that your code architecture manages it correctly.  If you need mutable references, or just to allow nullptr sentinels, then pointers are the way to go.

Better still are the stdlib's smart pointers; choose std::unique_ptr or std::shared_ptr as appropriate.

A usual way to handle this is to assume that the lifetime of each block and row should be the lifetime of the enclosing row and table, respectively.  If a consumer wants to preserve data beyond that time, they'll need to copy or swap it away.

For example, you have lines like this:

const std::map<int, Block*> getList();

Never return large objects (like std::map) by value, if you can avoid it.

const std::map<int, Block*> &getList() const;

is better (and const-correct).

RAII

It should be hard to create your objects without initializing them.  (Ideally, it should be impossible, but for some of your objects,  induces undue performance limitations, so you'll have to trust your coworkers.)  This means you should support brace-initializion and swapping objects, so you don't need to create them twice.  For example, BlockTable should have lines looking something like this:

public:
    BlockTable() = default;
    BlockTable(std::initializer_list<std::pair<int,RowBlock>> &&elems) :
        m_BlockTable(elems)
    {}
    template<typename T>
    BlockTable(T start, T end) :
        m_BlockTable(start, end)
    {}
    friend std::swap<BlockTable>(BlockTable &&left, BlockTable &&right);

If you manage memory properly, using smart pointers, etc., your destructors should be trivial.  The long and complex ones you've written are a code smell.

Const-correctness

Your classes offer almost no support for const-correctness.  Make sure to mark procedures that do not mutate as such!  A consumer of your class who cares about const-correctness will have fits if you don't.

ABI?

You may want variants of these classes for different sizes of integers, i.e. long long int, short int.  The easy way to do this uses templates, but then compile-time constraints can be hidden by typos, and you do not have a consistent binary layout across compilers.  I'm going to assume that you specialized to int on purpose; the templated version is not much more than a find-and-replace if done correctly.

Synchronization

C++ is no longer a single-threaded language, but most code is still written that way.  I assume you externally synchronize any accesses to BlockTable objects in multithreaded contexts, in which case there is no problem.

I/O

C-style I/O (i.e. printf) has been superseded by <iostream>.  Prefer that, but if you aren't taking user input or writing anything complicated out, it doesn't matter too much.

MWE

You forgot to define Block::setvalue.  Did you mean

void Block::setvalue(int value)
{
    m_value=value;
}

perchance?  This also shows that your test suite (which appears to be main) is woefully incomplete.  Make sure the data structure behaves sanely with regard to inserted, non-random values!

Other stylistic tips

auto is your friend.  Use it.

The range-based for is your friend too.  Use that.

If you have to manipulate iterators by hand, prefer ++iter.  iter++ requires the iterator to spend a lot of effort copying itself, only for the old version to get promptly thrown away.

Specific rewriting

I don't understand the exact purpose of your data structure; the maps don't seem to do what your documentation in the question describes.  So I can't tell you how to make main more informative.  But even without understanding the most important semantics of your code, I can tell you that, if you can add a few constructors and automatic memory management to your data structures so that the following mechanical rewriting of main is correct, your code will be better.

void main()
{
    BlockTable newBlockTable;
    for (auto const i : {1, 2, 3, 4, 5})
    {
        newBlockTable.insertBlockRow(Block(i * 10));
        //or better:
        //newBlockTable.insertBlockRow({i * 10});
        //or maybe even:
        //newBlockTable.insertBlockRow(i * 10);
    }
    //or best of all:
    //BlockTable const newBlockTable{10, 20, 30, 40, 50};

    //The names of your variables were too uninformative; I've changed them
    auto const &row_map{newBlockTable.getList()}; //No need for complicated iterator types!
    for (auto const &key_and_row : row_map)
    {
        auto const &block_map{key_and_row.second->getList()};
        for (auto const &key_and_block : block_map)
            printf("%d\n", key_and_block.second->getvalue());
    }
    //If you aren't going to return anything but success, don't bother returning a value.
}


No, strategy pattern relies on an interface to allow composition to determine functionality at run time.  Notice that it is easier to extend with new speaking functionality; and can be used to execute at run time.  Here you are just using the array of the interface instantiations to do multiple validations.

I.E.

Interface for the pattern

public interface Speak {
  public void execute();
}

Implementations of the pattern

public class Quack extends Speak {
  public void execute() { /* Quack */ }
}

public class Bark extends Speak {
  public void execute() { /* bark */ }
}

Class that uses the strategy

public Animal {
  private Speak _speak;
  public Animal(Speak s) { _speak = s; }
}

Example usage

main() {
  new Animal(new Bark()); /* creates animal that barks */
  new Animal(new Quack()); /* creates animal that quacks */
}


The problem is:

  What is the largest prime factor of the number 600851475143?

Your solution has a function named lpf, which computes the complete prime factorization of the number and prints it and returns the largest prime factor. That is doing too many things! Your function should do one thing: find the largest prime factor.

Doing that, we can simplify your code a lot. Let's start with:

ceiling=int(math.floor(np.sqrt(n)))+1 #Don't check for prime factors larger than sqrt(n).
thelist=[]
for i in xrange(2,ceiling):
    thelist.append(i) #Make a list of integers from 2 up to floor(sqrt(n))+1.

You imported numpy just for sqrt, but math already has it. Is there a reason for that? int also truncates already, so you don't need floor on top of that. Furthermore, why loop through xrange when we can just use range? So a simpler one would be:

ceiling = int(math.sqrt(n)) + 1
thelist = range(2, ceiling)

Now, as saulspatz points out and I totally missed, sqrt(n) is a ceiling for determining if a number is prime. But it's not a ceiling for determining all the factors. For example, the largest prime factor of 10 is 5... but sqrt(10) ~ 3.16. A valid ceiling would be:

ceiling = n/2 + 1

We can refine the ceiling once we find the first prime factor as an optimization.

Next, what are you actually doing with thelist? It looks like you're sort of doing the Sieve of Eratosthenes. But not really. You're doing all sorts of removal from this list, and that's not entirely necessary. You could just use the sieve directly:

def lpf_me(n):
    largest = None
    ceiling = n/2 + 1
    thelist = [True] * ceiling
    for i in xrange(2, ceiling):
        if thelist[i]:                        # i is prime
            for j in xrange(2*i, ceiling, i): # turn off multiples of i
                thelist[j] = False
            if n % i == 0:
                largest = i                   # new largest prime factor
    return largest

Which when run:

>>> lpf(78618449)
31

Now, this is valid, but pretty slow (run with timeit, 10 times):

me                        148.2s

That's pretty bad. Can we build on this? Sure we can!

Let's go back to the drawing board with the sqrt(n). Any factor larger than that is either prime or divisible by something less than sqrt(n). But we've already put in the work to find all the primes less than sqrt(n)! So we can just reuse that work:

def lpf_me(n):
    largest = None
    ceiling = int(math.sqrt(n)) + 1
    thelist = [True] * ceiling
    others = []

    for i in xrange(2, ceiling):
        if thelist[i]:                        # i is prime
            for j in xrange(2*i, ceiling, i): # turn off multiples of i
                thelist[j] = False
            if n % i == 0:
                largest = i                   # new largest prime factor
                other = n/i
                if other > ceiling:           # hold onto this for later
                    others.append(other)

    for factor in others:
        for i in xrange(2, ceiling):
            if thelist[i] and factor % i == 0: # only have to check divisibility
                break                          # by primes.
        else:
            # this is prime and necessarily larger than largest
            return factor

    return largest

How fast is this? Pretty speedy. There aren't going to be very many candidates, and we can run through those pretty quickly:

up to n/2       148.22s
up to sqrt(n)
- holding on      0.02s
OP solution      21.83s ** note this is incorrect as stops at sqrt(n)
                        ** instead of n/2

I tried running on the original Euler problem value but yours never finished. But, to be fair, mine does less work. So let's actually do the prime factorization. We'll return a list of pairs like you did in the original:

def prime_factorization(n):

Now, again, we can use the Sieve approach. But instead of modifying n throughout, we can just write a helper function to do it for us:

def factor(num, p):
    exp = 0
    while num % p == 0:
        exp += 1
        num /= p
    return (p, exp) if exp > 0 else None

Simple. We don't have to touch n, keep an orig, or pollute our main function with extraneous logic. The flow of the function is the same - same sieve, except instead of keeping track of largest, we keep track of all_factors:

def factorize(n):
    def factor(num, p):
        exp = 0
        while num % p == 0:
            exp += 1
            num /= p
        return (p, exp) if exp > 0 else None

    ceiling = int(math.sqrt(n)) + 1
    thelist = [True] * ceiling
    all_factors = []
    others = []

    for i in xrange(2, ceiling):
        if thelist[i]:                        # i is prime
            for j in xrange(2*i, ceiling, i): # turn off multiples of i
                thelist[j] = False

            next_factor = factor(n, i)
            if next_factor:
                all_factors.append(next_factor)
                other = n/i
                if other > ceiling:           # hold onto this for later
                    others.append(other)

    for f in reversed(others):
        for i in xrange(2, ceiling):
            if thelist[i] and f % i == 0: # only have to check divisibility
                break                          # by primes.
        else:
            # this is prime
            all_factors.append(factor(n, f))

    return all_factors

Now it's a fair comparison, but mine still runs in 0.027s. It's all about algorithmic complexity.

Summary

Avoid erasing from lists. It's bad.
Break large functions up into smaller functions. It'll make your code easier to read and, in this case, even make the logic a lot simpler.
When you need to solve a problem, just solve the problem. Worry about extraneous similar problems when, and if, they come up.


Iterating over a range of integer ranges in Java

I think RangeCollection would be a better name than Ranges.

To my mind, the RangeIterator is doing too much.  It's iterating over a collection of ranges and over each range in the collection.  To me it would make more sense for the Range class to have its own iterator and the RangeCollection its own iterator


I imagine you're still checking window.DeviceOrientationEvent? Because if that doesn't exist, you can presumably skip everything else.
When using $.Deferred you should always return its .promise() - not the deferred object itself. The deferred object itself is "read/write" (i.e. you can call resolve and reject on it), while the promise it creates is "read-only" which is what you want to pass on to other code.
You don't need $.when unless you're waiting for several promises to resolve. You can simple call promise.done() (or .then or .fail or .always)
Since the idea is get a yes/no answer, I'd simply use the resolve/reject callbacks of the deferred and do all the checking in one place.
I don't know if it's relevant, but checking strictly against null will give you a false positive if alpha etc.are actually completely undefined. It might be better to check typeof alpha === 'number'.
Of course, you don't really need promises; a simple callback would do.

For instance:

var check = {
  gyroscope: function (callback) {
    function handler(event) {
      var hasGyro = typeof event.alpha === 'number'
                 && typeof event.beta  === 'number'
                 && typeof event.gamma === 'number';
      window.removeEventListener('deviceorientation', handler, false);
      callback(hasGyro);
    }
    window.addEventListener('deviceorientation', handler, false);
  }
};

check.gyroscope(function (hasGyroscope) {
  if(hasGyroscope) {
    console.log('Device has functional gyroscope.')
  } else {
    console.log('Device has no functional gyroscope.');
  }
});

If you do want to use $.Deferred, I'd recommend something like:

var check = {
  gyroscope: function () {
    var deferred = $.Deferred();

    function handler(event) {
      var hasGyro = typeof event.alpha === 'number'
                 && typeof event.beta  === 'number'
                 && typeof event.gamma === 'number';
      window.removeEventListener('deviceorientation', handler, false);
      hasGyro ? deferred.resolve() : deferred.reject();
    }

    window.addEventListener('deviceorientation', handler, false);
    return deferred.promise();
  }
};

check.gyroscope().then(function () {
  console.log('Device has functional gyroscope.')
}, function () {
  console.log('Device has no functional gyroscope.');
});


Merging many dictionaries

Instead of merging just 2 dictionaries, how about allowing to merge many?

def merge_dlist(*args):
    """Merge_dlist accepts dictionaries to be merged."""
    merged_dict = defaultdict(list)
    for dictionary in args:
        merged_dict = merge_type(dictionary, merged_dict)
    return merged_dict

Improving merge_type like this:

def merge_dictionary(dictionary, merged):
    """Merge dictionary keys. Append value items to value list."""
    for key, value in dictionary.items():
        if isinstance(value, list):
            merged[key].extend(value)
        else:
            merged[key].append(value)
    return merged

Improvements:

Naming: "merge_type" is a strange name, I don't know what it means. I think "merge_dictionary" makes more sense.
Instead of appending list items one by one with .append, it's better to add all at once using .extend
Why limit to string types? Why not append any kind of non-list values in general?


Leap year check in Java (functional style)

What do you think?

It certainly is clever. That is not always a good thing, because it might be harder to understand what is going on (you have to be at least as clever)

Is this readable?

Not really. I can't get from a glance that 100 is treated differently from 400 and why. Also there is no room for comments close to you code.

If you make a set of ifs you could do something like:

if (year % 400 ... ) // if 400 then a leap year
{..
..}

In your IntStream you could do something like:

   IntStream.of(  4,    //yes
                100,    //no
                400     //yes
               )

But then you kinda miss the 'one-liner' point of your solution.

Is it efficient?

Not per se. Most efficient would be to first check divisibility by 400, if true, return true, etc.

Prime factorization funny fact

This in incorrect; because it would label 1998 as leap year. Or do you mean something different?