First of all, I would rename the bounds to be more meaningful, from gte to min_value, and from lte to max_value.

Function 1 comes close to being a good idea, but could be implemented more smartly.  The special treatment of any falsy value (notably 0) to skip filtering is probably a bad idea.  The set intersection operation should be avoidable.

def func1_improved(data, min_value=None, max_value=None):
    if min_value is not None:
        data = {(k, v) for k, v in data if v >= min_value}
    if max_value is not None:
        data = {(k, v) for k, v in data if v <= max_value}
    return data.keys()

Function 2 is not equivalent to the other two: it returns a dictionary rather than a key set.  It suffers from the problem that it sometimes returns the original dictionary, and sometimes returns a copy.  It also treats 0 as a special parameter value.

def func2_improved(data, min_value=None, max_value=None):
    data = dict(data)    # Make a copy
    for k, v in data.items():
        if min_value is not None and v <= min_value:
                del data[k]
        if max_value is not None and v >= max_value:
                del data[k]
    return data.keys()

Function 3 is quite good, especially when formatted as a one-liner using a set comprehension:

def func3_improved(data, min_value=float('-inf'), max_value=float('inf')):
    return set(k for (k, v) in data.items() if min_value <= v <= max_value)

That is my recommendation.  You could eliminate some comparisons by making special cases for when min_value or max_value is missing, but I'd prefer not to ruin the elegance of the one-line solution.


This can get worse than \$\operatorname{O}(\log \verb~pow~)\$. [Remark: in \$\operatorname{O}\$-notation, the base of an logarithm is irrelevant, since it represents only a multiplication with a constant]

Let \$\verb~pow~ = 2^n - 1\$ for some \$n\$. Then you're computing the following powers:

\$1, 2, 4,\dots, 2^{n-1}\$, followed by a function call for \$\verb~pow~ = (2^n-1) - 2^{n-1} = 2^{n-1} - 1\$;
\$1, 2, 4,\dots, 2^{n-2}\$, followed by a function call for \$\verb~pow~ = (2^{n-1}-1) - 2^{n-2} = 2^{n-2} - 1\$;
\$1, 2, 4,\dots, 2^{n-3}\$, followed by a function call for \$\verb~pow~ = (2^{n-2}-1) - 2^{n-3} = 2^{n-3} - 1\$;
...

All in all, \$n + (n-1) + ... + 1 = n(n+1)/2\$ calls of the inner loop. In terms of pow, this is \$\operatorname{O}(\log^2 \verb~pow~)\$.

Instead, observe pow as a binary number. I don't do Java, so I'll just sketch this in C, which is quite like it.

double px = x; // current power of x
double result = 1;
while (pow > 0) {
    if (pow % 2) result *= px;
    pow /= 2;
    px *= px;
}

So, you are observing \$x, x^2, x^4, x^8,...\$ and multiplying with them if the corresponding binary digit of pow is equal to \$1\$. This has \$\operatorname{O}(\log \verb~pow~)\$ steps.

By the way, I don't think \$2^7\$ is expected to be \$16\$. ;-)


Regular expression to parse guid and other attributes

TL;DR; list of adjustments:

.NET RegEx support named capture groups. make use of them.
Make use of the GUID format specification.
Simplify retrieval with non-capturing groups.
Make assumptions explicit in character classes. Prefer negated chargroups to non-greedy matching

I propose the following regular expression instead:

(?<guid>[a-f0-9]{8}(?:\-[a-f0-9]{4}){3}\-[a-f0-9]{12})\/(?<type>[^\/]+)\/(?<name>[^;]+);version=(?<version>\d*)

While this regex is somewhat longer it matches both examples in 62 steps (as opposed to 117). This may only seem like a minor improvement, but it's not all that happens:

This regex uses named capturing groups that allow a much more natural and clear pattern extraction. Instead of accessing groups by magic indices, you can access them by name and the construction of matchEntity is accomplished as follows:

let matchEntity (m: Match) =
    { id= m.Groups.["guid"].Value;
      eType = m.Groups.["type"].Value;
      name= m.Groups.["name"].Value;
      version = m.Groups.["version"].Value }

Last but not least this regex also does not match incorrect GUID specifications


Some things to consider:

for (char len = 1; len <= MAX_LEN; len++) is extremely dangerous as you could easily overflow len here since MAX_LEN has type unsigned. Currently, the value of MAX_LEN is 20, and your code is safe; however, if you decide to change this value at any point, you will likely overflow len here, leading to undefined behavior either because of overflow of a signed type if char is signed or because of the fact that infinite loops (into which this one will turn) that do not do IO are ub in the case of an unsigned char type.
In C, you do not need to cast the return value of malloc. Simple assignment will do. In fact, don't actively cast the return value of malloc because it clutters your code with casts, which is a symptom of bad code in general, and can hide a bug related to implicit functions (only before C11).
Actually, that loop from point 1 I mentioned can be removed altogether. This follows from recognizing that you are adding all integer values starting from one up to MAX_LEN, for which there is an easy to compute formula: S = n(n + 1)/2. Translated into code, this would be

maxNum = MAX_LEN * (MAX_LEN + 1) / 2;

which is not only shorter, but also more efficient to compute.
Why do you define almost all your variables at the top of your function, although they are not used until much later? This is a bad practice, because it increases the mental load everyone reading your code has to deal with. I don't want to remember the types of eight or nine different variables while focusing on code that doesn't even use them. Just define them right were they need to be defined.
Overall, you use char too much. Only use char when you are working with characters or single bytes, otherwise use int, unsigned and everything larger or equal in bit size. You are not gaining anything through your use of char except a high chance to trigger ub several times over in your code (You are likely not even saving space because of alignment concerns on most common modern platforms.)
Don't printf a single character; that's wasteful. Use putchar for that.
Don't include stdafx.h. Unless you have a concrete compilation performance concern, it won't do anything for you. And even then, it is not standard, and most people who use compiler other than MSVC will likely complain about it.
Split your code up into functions. main() is not the right place to write problem-solving code, only to put things together. Do yourself a favor and organize your code a little more, it will help you keep a good overview over which part does what and make other readers not turn away on sight of that huge main god-function.


In 'exist' function, instead of looping through the entire board every time for the first character match, you can build a lookup map with char vs it's indices in  the board. I modified your exist method as below and I could see better performance.

#include <iostream>
#include <vector>
#include <map>

using namespace std;

class Solution {
  public:
   bool DFS(vector<vector<char>> &board, string word, vector<vector<bool>> visited, int i, int j, int curr)
   {
          if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size()) {
              return false;
          }
          if (visited[i][j] || board[i][j] != word[curr]) {
             return false;
          }
          visited[i][j] = true;
          ++curr;
          if (curr == word.size()) {
             return true;
          }

          return DFS(board, word, visited, i + 1, j, curr) || // Down
                 DFS(board, word, visited, i, j + 1, curr) || // Right
                 DFS(board, word, visited, i - 1, j, curr) || // Up
                 DFS(board, word, visited, i, j - 1, curr);   // Left
    }

    void buildFirstCharIndexMap(const vector<vector<char>> &board)
    {
         firstCharIndex.clear();
         for (int i=0; i<board.size(); ++i){
             for (int j=0; j<board[i].size(); ++j){
                  firstCharIndex.emplace(make_pair(board[i][j], make_pair(i,j)));
             }
         }
    }

    bool exist (vector<vector<char>> &board, string word) {
        // get the indices for the first character.
        auto range_itr = firstCharIndex.equal_range(word[0]);

        for (auto it = range_itr.first; it != range_itr.second; ++it){
             auto cur_index_pair = it->second;

              vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
              if (DFS(board, word, visited, cur_index_pair.first, cur_index_pair.second, 0)) {
                    return true;
              }
         }
         return false;
     }
  private:
     // lookup table for each char and it's location in the board
     multimap<char, pair<int, int>> firstCharIndex;
  };

  int main() {
       vector<vector <char>> board = {
                                  {'A','B','C','E'},
                                  {'S','F','C','S'},
                                  {'A','D','E','E'}
                                };
       Solution s;
       // build the look up table
       s.buildFirstCharIndexMap(board);
       cout << s.exist(board, "SEE") << endl;
       cout << s.exist(board, "ABCCED") << endl;
       cout << s.exist(board, "ADCB") << endl;
       return 0;
    }


Receive data from SQL and CSV and send it to MySQL database using Python

Externalize your connection strings

This information:

  host="SVR",
  user="root",
  passwd="",
  database="production"

    "Driver={SQL Server Native Client 11.0};"
    "Server=svr;"
    "Database=SQL_Server;"
    "Trusted_Connection=yes;")

'G:/Technical/Labels/Production/Data/CSVExport.csv'

should not be baked into your program, for multiple reasons:

configurability and maintainability
security

Put these into a configuration file, a command-line argument, or an environmental variable.

Typo

#SQL Sevrer -> #SQL Server

Context management

Doing a search through the MySQL Connector Python source code as well as their bug tracker, it seems that the library has a deficiency where cursors cannot be used as context managers. You can do the next-best thing: try/finally whenever you make a connection or cursor that needs to be closed, or (probably better) make your own small context manager utilities for such cases.

The situation for pyodbc seems to be better. Connections and cursors should be used in with statements.

In all cases you should prefer this to explicit close() calls.

Multi-line strings

Since this is SQL:

    SqlData.execute("select p.id, p.code,p.description, p.searchRef1, so.number, c.code, c.name \
         from salesorderline sol join \
         salesorder so \
         on sol.salesorderid = so.id join \
         product p \
         on sol.productid = p.id join \
         customer c \
         on so.customerid = c.id \
         where so.orderdate > dateadd(dd,-10,cast(getdate() as date));")

Indentation does not matter. Your current string literal includes indentation, and it might as well stay that way but losing the continuation escapes and using a multi-line string:

    SqlData.execute("""
        select p.id, p.code,p.description, p.searchRef1, so.number, c.code, c.name
        from salesorderline sol
        join salesorder so on sol.salesorderid = so.id
        join product p on sol.productid = p.id
        join customer c on so.customerid = c.id
        where so.orderdate > dateadd(dd,-10,cast(getdate() as date));
    """)

I also think it is clearer and more logical to line-break before the join keyword rather than after, and include the on with its corresponding join.

Unpacking

This:

a,b,c,d,e,f,g = x

is not helpful. Either give these meaningful names, or don't unpack at all:

MySQLcursor2.execute("""
    insert into SQL_Server (
        product_id, product_code, product_description, product_weight,
        salesorder_number, customer_code, customer_name
    ) values (%s,%s,%s,%s,%s,%s,%s);
    """,
    x
)

Magic numbers and home-rolled time math

Do not do this:

    time.sleep(240 - ((time.time() - starttime) % 240))

It's difficult to understand. I guess 240 seconds is 4 minutes. You're

finding the elapsed time since the start,
modulating that by 4 minutes? Why?
subtracting that from 4 minutes.

At a wild guess, what you are trying to do is "wait until 4 minutes have passed since the start of the program", which would actually require

from datetime import datetime
from time import sleep

start_time = datetime.now()
# ...

elapsed = datetime.now() - start_time
until_4m = (timedelta(minutes=4) - elapsed).total_seconds()
if until_4m > 0:
    sleep(until_4m)


Shared Pointer based Object Pool Implementation with fixed object count

Small nitpicks

The constructor and create could profit from perfect forwarding args (so references of all kinds can be used.

template<typename... E>
Section(size_t size, E&&... args) :
    std::enable_shared_from_this<Section<T>>(),
    m_mem(size, T(std::forward<E>(args)...))
    { /* ... */ }

Do you have any specific reason to prefer std::list<T> over std::vector<T> for m_mem? std::vector<T> would use less memory (no pointers from each element to the next), and the memory used would be contiguous (so iterating over it is very likely faster due to cache effects).

Correctness

Every std::shared_ptr<T> returned by Section<T>::create() might be dangling. This can happen if the Section<T> gets destroyed while there are still std::shared_ptr<T> pointing to contained objects.

This is a result of the std::shared_ptr<T> not owning the pointer.

If you can guarantee that there won't be any std::shared_ptr<T> pointing into the Section<T> when the Section<T> is destroyed, this problem easily disappears.

If this can't be guaranteed, there are two options:

Introducing your own smart pointer type that checks the Section<T> for validity every time it's dereferenced, as the standard smart pointers (std::unique_ptr, std::shared_ptr and std::weak_ptr) are not designed for this task.
(Ab-)using the returned std::shared_ptr<T> to keep the section alive. This can be done in the lamda init capture of the custom deleter.

return std::shared_ptr<T>(obj, [section = shared_from_this()](T *ptr) -> void
{
    section->destroy(ptr);
    std::unique_lock<std::mutex> lk(section->m_lock);
    section->m_objs.push(ptr);
});

Note: This might keep the section alive far longer than intended! (Some might also say that this is an ugly hack...)


This code is performing a long-polling technique.  The server gets a client request, the server method is checking for any changes in data, and when found, returns it to the client.  In short-polling, the client is constantly sending requests for data on a timer basis; in long-polling, the client makes one request and waits for the server to return any new data it has.

For example, in your method getJsonUsers(), it is running a query that looks for new data, and upon finding it, returns it to the user.  If it doesn't find data, it waits a finite amount of time, and tries again.  The client won't get notified of anything until data is actually returned, or it will timeout.  This is a normal pattern for long-polling.  If your program was using a short-polling technique, the server method would just return (either data or no data, depending on the results of the query you're running), and not wait to actually get something to give back to the client.

Your client code on the other hand, in the case of short-polling, would keep making requests to the server, and after a certain amount of time, would make another request.  Long-polling uses an event-based mechanism (that is, it waits for data to be present prior to returning) for alerting the client of data, whereas the short-polling method just keeps hitting the server regardless of what it gets back or not.

This website has good information on polling techniques, including an example of long-polling:  CoderTalks:  Long Polling vs Short Polling


Structure

Hmm.
OK. Property bag so its OK

struct NodeTemplate{
  string ID;
  string NodeID;
  string latitude;
  string longitude;
};

But are lat/long really string? Would they not be numbers? Also ID sounds like a number type thing.

Global Variables:

vector <NodeTemplate> NodesOut;

Global variables are bad. Don't do this.
They make the code hard to test. Side affects will cause problems.

Prefer return over out parameters.

void split(const string& s, char c,
           vector<string>& v) {

Out parameters are hard to spot and maintian. Also its not very expensive to return a vector (there is no copy the compiler will elide it (assuming you enabled optimization)). Check out RVO and NRVO.

Also in C++11 and C++14 move semantics kick in and even if you can't optimize it with RVO or NRVO then it will be moved back to the calling function rather copied.

Standard functions

A lot of this work made trivial by the standard functions and some lambda's

   while (j != string::npos) {
      v.push_back(s.substr(i, j-i));
      i = ++j;
      j = s.find(c, j);

      if (j == string::npos)
         v.push_back(s.substr(i, s.length()));
   }
}

How about:

// Use the string as a stream
std::stringstream stream(s);
// Copy "Item" objets from the stream into the vector.
std::copy(std::istream_iterator<Item<c>>(stream), std::istream_iterator<Item<c>>,
          std::back_inserter(v))

Not you can simply define an Item.

template<char c>
struct Item
{
    std::string   value;
    // Converts an Item into a string
    operator std::string const& {return value;}
    // Reads one item from the stream.
    friend std::istream& operator>>(std::istream& str, Item& data)
    {
        return std::genline(str, data.value, c);
    }
}

Use constructors.

      string filenameIn="ways.txt";
      ifstream myfile ((filenameIn).c_str( ));

Much easier to write as:

      ifstream myfile("ways.txt");

Also C++11 allows you to construct the stream object with a std::string so you don't need to call c_str() if you really want to use the variable name.

I don't see the point of opening and closing the file to truncate it.

      myfile3.open(fileNameNodes2.c_str(),fstream::out | fstream::trunc);
      myfile3.close();

      myfile3.open(fileNameNodes2.c_str(),fstream::out | fstream::app);

By default a file will truncate an existing file. So all the above can be replaced by the single line:

      std::ofstream  myfile3("nodes2.txt");

This is a useless test:

      if (myfile.is_open())

I would be OK if you used it to generate an error message. But as it stands it is just protecting the while loop. You don't need to do that. The while loop will just not be entered because getline() will fail to read from an empty file.

As discussed above:

                    string s1=line1;   // usless copy.
                    vector<string> v1;
                    split(s1, ';', v1);

Much easier to write as:

                    vector<string> v1 = split(line1, ';');
                    vector<string> v2 = split(v1[4], ',');

Though personally I would probably have written an input operator that read everything directly from the stream. Rather than copy strings all over the place.

Conversion is hurting.

 if(atoi(v2[t].c_str())==atoi((NodesOut[tt].ID).c_str()))

You are converting this every time!!!!!
You should convert it once when you read it in. Conversion is really expensive. (I mean the calls atoi())

Don't manually flush the stream

 myfile3.flush();

This will cause very inefficient use of the underlying buffer. Let the stream flush itself. It is much better at the job then you are.

Better Soltion

This is how I would expect the code to be written.

class DataNode
{
     // Values
     //   With the correct types NOT string
     friend std::istream& operator>>(std::istream& str, DataNode& data)
     {
          // read from the stream into a Data Node  "data".
          // Just one object.
          return str;
     }
     friend std::ostream& operator<<(std::ostream& str, DataNode const& data)
     {
          // Write the Data Node "data" to the stream.
          return str;
     }
}

int main()
{
    std::ifstream    input("inputfile");

    DataNode   data;
    std::unordered_set<DataNode>  dataNodes;

    while(input >> data) {
    {
        if (!dataNodes.find(data))
        {
            dataNodes.insert(std::move(data));
        }
    }

    std::ofstream    output("outputfile");
    std::copy(std::begin(dataNodes), std::end(dataNodes),
              std::ostream_iterator<DataNode>(output));
}


Passing around context.Context in Golang

You've actually improved the design, because now unit tests can inject their own context and thus the shutdown() becomes testable. Pure gold.

But your stated reasons make me wary. I'd pass a parameter (e.g. struct) to Start() or NewServer()  There aren't many good uses of WithValue that make your code more readable and neater.

Also docs for WithValue warn that "The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context." So that's a big problem with your example.


Cleanly passing in a large number of mutable parameters through a python class

I'm going to address your existing code in a manner that generally goes from most minimal to most significant changes. I'd strongly recommend actually using the solution at the very bottom of this post; the minimal changes are more useful:

From a historical (pre-dataclasses) perspective
For understanding how classes and inheritance work

but there's no reason to torture yourself hand-writing all of this when dataclasses will do the work for you.
Delegating to defaults of super class
When you're inheriting __init__ from another class, you typically don't want to reproduce their parameters explicitly; it creates too much confusion and too much interdependency (making more opportunities for code to get out of sync). There are two standard solutions here:
Option 1: Explicitly delegate via **kwargs
When Functionality doesn't make direct use of any parameter, don't accept it by name. Just accept **kwargs (when you're talking about this many defaulted parameters, no one should be passing arguments positionally anyway; it's a nightmare for readability/maintainability) and pass it along. So Functionality would look like:
class Functionality(Attributes):
    def __init__(self, **kwargs):
        # Other stuff required for initialization
        super().__init__(**kwargs)  # Python 3.x doesn't require you to pass args to super in most cases
        # Other stuff required for initialization

    # Methods that give functionality to the class

Option 2: Inherit __init__ implicitly
In this case, it might be even simpler though; the __init__ of Functionality doesn't do anything beyond delegate to Attributes. If your real code is the same (nothing but a super().__init__ call), you'd just omit the definition of __init__ on Functionality and let it inherit Attributes's __init__ directly.
class Functionality(Attributes):
    # No __init__ defined at all; uses Attributes.__init__ automatically

    # Methods that give functionality to the class

Either way, you're no longer using separate defaults for each class.
Note: If the parent class must not accept default arguments, but the child class should, see the end of this answer for Preferred solution (especially if the child must not have defaults, and the parent class should): dataclasses everywhere (not described here since it relies on techniques for solving your mutable defaults problem, which I haven't gotten to yet).

Avoid problems with mutable defaults
There are two simple solutions for avoiding the problems with mutable defaults.
Option 1: Deep copy unconditionally
For the defaulted class itself, go ahead and use mutable arguments as defaults, but the safe way, making deep copies. This is often safer even when not passed as defaults, since without copying, you'd be aliasing values from the caller, and changes made by either you or the caller would affect the other.
Adding explicit mutable defaults, you end up with:
from copy import deepcopy

class Attributes:
    def __init__(self, arg1=[], arg2={}, arg3=set(), arg4=MyMutable(), arg5=OtherMutable()):
        self.arg1 = deepcopy(arg1)
        self.arg2 = deepcopy(arg2)
        self.arg3 = deepcopy(arg3)
        self.arg4 = deepcopy(arg4)
        self.arg5 = deepcopy(arg5)

    # attribute methods like getters and setters

Option 2: Let dataclasses do your work for you
As an alternative to hand-writing all of Attributes, I'd suggest making it a dataclass, which means you don't need to repeat the names, and allows you to define default_factorys for each field to generate default values on demand. That would allow you to write a simpler Attributes (with far less name repetition) matching what I wrote above like so:
from dataclasses import dataclass, field

@dataclass
class Attributes:
    arg1: list = field(default_factory=list)
    arg2: dict = field(default_factory=dict)
    arg3: set = field(default_factory=set)
    arg4: MyMutable = field(default_factory=MyMutable)
    arg5: OtherMutable = field(default_factory=OtherMutable)

    # attribute methods like getters and setters

and it will generate __init__ (as well as __repr__ and __eq__ for good measure; you can turn them off, or other features on, by parameterizing the @dataclass decorator) for you, including automatically calling your default_factory to initialize the field if and only if the caller did not provide the parameter.
Note: Unlike the other solution, this doesn't ensure caller-provided arguments are copied, so the risk of aliasing would remain. You could always define a __post_init__ to copy any fields you think this is likely to be a problem for.
Side-note: For my example, I just annotated the types as list, dict, and set; to annotate properly, you'd usually the typing classes (List, Dict, Set) and annotate with the types the containers are expected to hold, e.g. arg1: List[int] = field(default_factory=list) if arg1 is expected to be a list of ints.
Preferred solution (especially if the child must not have defaults, and the parent class should): dataclasses everywhere
In your example, Attributes() fails for lack of arguments, while Functionality() does not (substituting defaults),
dataclasses still cover that case adequately. You'd define both parent and child as dataclasses, but not provide defaults for the fields on the parent:
from dataclasses import dataclass, field

@dataclass
class Attributes:
    arg1: list
    arg2: dict
    arg3: set
    arg4: MyMutable
    arg5: OtherMutable

    # Optionally define __post_init__ to modify arguments, perform other work

    # attribute methods like getters and setters

@dataclass
class Functionality(Attributes):
    arg1: list = field(default_factory=list)
    arg2: dict = field(default_factory=dict)
    arg3: set = field(default_factory=set)
    arg4: MyMutable = field(default_factory=MyMutable)
    arg5: OtherMutable = field(default_factory=OtherMutable)

    # Optionally define __post_init__ to modify arguments, perform other work

    # Methods that give functionality to the class

Since no defaults are set on Attributes, direct use of Attributes will require you all arguments to be provided. But dataclasses are helpful again here; the fields of a child class of a dataclass are:

All of the fields of the parent(s)
Plus all of the fields of the child
When a given field is defined in both, the child's definition wins

So we can provide default_factorys solely on the child (and get defaulting behavior), but not on the parent (so it never defaults).


HaxeFlixel 2 player game: make input code cleaner

Parametrizing the keys seems like the correct solution to me. The subclassing approach leads to code duplication and inflexibility. However, you should not do that by adding parameters to update() - in fact, you can't, because the function signature of an overriden method has to match. You would get a compiler error:

Field update overloads parent class with different or incomplete type
Different number of function arguments

Since it's 4 parameters that are closely related to each other, you might want to bundle them in a structure. By using the FlxG.keys.anyPressed() API, which takes an array of keys, we could in theory also allow multiple keys per input:
package;

import flixel.FlxG;
import flixel.FlxSprite;
import flixel.util.FlxColor;
import flixel.input.keyboard.FlxKey;

class Player extends FlxSprite
{
    var keys:PlayerKeys;

    public function new(x:Float, y:Float, keys:PlayerKeys)
    {
        super(x, y);
        makeGraphic(20, 100, FlxColor.WHITE);
    }

    override public function update(elapsed:Float):Void
    {
        if (FlxG.keys.anyPressed(keys.up)) { /* move up */ }
        if (FlxG.keys.anyPressed(keys.down)) { /* move down */ }
        if (FlxG.keys.anyPressed(keys.left)) { /* move left */ }
        if (FlxG.keys.anyPressed(keys.right)) { /* move right */ }

        super.update(elapsed);
    }
}

typedef PlayerKeys = {
    up:Array<FlxKey>,
    down:Array<FlxKey>,
    left:Array<FlxKey>,
    right:Array<FlxKey>
}

And to construct the player instances:
player1 = new Player(x, y, {up: [UP], down: [DOWN], left: [LEFT], right: [RIGHT]});
player2 = new Player(x, y, {up: [W], down: [S], left: [A], right: [D]});

There's two other issues with your code:

You update() your players manually in PlayState - Flixel already does that when you call super.update(), since you've add()ed the players to the state. This means the players end up being updated twice per frame.
You manually added variables for WindowWidth and WindowHeight, which are already available globally via FlxG.width and FlxG.height.


Project Euler 35: Circular primes below 1 million

Trial division repeatedly can get very expensive, and is not scalable in terms of computation time. Especially when you are running your rotation check during the process.

I would suggest getting a list together, then filtering that out. That way it is more efficient, and also when you rotate a number you just check if it is in the list, rather than rechecking it for primality slowly. Lookup tables are usually a good recommendation for these things, as the rotated elements overlap in spots. (such as 79 & 97, having to check if they are prime twice. It gets worse for longer numbers!)

To get all primes below 1,000,000 you can implement the Sieve of Eratosthenes to quickly get the list of primes.

from math import sqrt

def sieve(n):
    primes = [True] * (n+1)
    primes[0] = primes[1] = False

    for x in range(4,n+1,2):
        primes[x] = False

    for x in range(3,int(sqrt(n))+1,2):
        if(primes[x]):
            for y in range(x*x,n+1,x):
                primes[y] = False

    return primes

Now you just go through the returned list, and for each True entry, you can check if it's rotatable.

And here is a simpler way to right a rotation. This one shifts left.

def rotate(n):
    n=str(n)
    return n[1:]+n[:1]

And with that rotation, and the sieve available to us, we now just rotate the number, and check if it is True in the sieve! Return false if any rotation of n is False, else return True if we can't find any non-primes.

def isRotatable(n, primes):
    for x in range(2,n):
        n = rotate(n)
        if not primes[int(n)]:
            return False
    return True

Now for a main method to just go through and print the results for us! I'm using main because I'm not sure what else to name it.

def main(n):
    primes = sieve(n)
    for x in range(2, len(primes)):
        if(isRotatable(x,primes)):
            print(x)

Altogether these pieces should work rather quickly. The longest part I found was it actually outputting to the interpreter, possibly writing to a file may be quicker.


janos already pointed out some important issues. I'm just going to add a few

Separate concerns

A ShoppingList is a shopping list, nothing more. It could be simply a wrapper around a List with maybe some additional convenience functions. It shouldn't be responsible for creating items from user input, much less asking the user for that input. Therefore, most of the code in method addItem() belongs to another class.

Explicitly declare menu options

You are using magic numbers to identify your menu options. Wait, I just said menu option. This is a very important entity in your program, yet it doesn't appear explicitly anywhere, only implicitly in your println()s and ifs. Let's make an enum for it. This will also allow us to get rid of the magic numbers.

enum MenuOption {
    ADD_ITEM("Add an item to the list."),
    DISPLAY_ITEMS("Display list and total number of items."),
    EXIT("Exit.");

    private final String message;

    private MenuOption(String message){
        this.message = message;
    }

    public String getMessage(){
        return message;
    }
}

ShoppingList myList = new ShoppingList();
Scanner scanner = new Scanner(System.in);
MenuOption selectedOption = null;

while(selectedOption != MenuOption.EXIT){

    selectedOption = askUserOption(scanner);

    switch(selectedOption){
        case ADD_ITEM:
            myList.addItem();
            break;
        case DISPLAY_ITEMS:
            myList.displayItem();
            break;
    }
}

private MenuOption askUserOption(Scanner scanner){
    System.out.println("");
    System.out.println("----- Shopping List------");
    for(int i=0; i<MenuOption.values().length; i++){
        MenuOption option = MenuOption.values()[i];
        System.out.println("(" + i + ") " + option.getMessage());
    }

    int numericInput = scanner.nextInt();
    // TODO check for invalid inputs
    return MenuOption.values()[numericInput];
}

Wrap user prompting

Instead of writing System.out.println() at every point where you need to comunicate to your user, it might be a good idea to write a class for this purpose. For example:

class UserPrompter {
    public void prompt(String message){
        System.out.println(message);
    }
}

This has at least two benefits:

It makes the intent of your code more clear. You are not just printing to stdout (maybe for debugging purposes) - you are actually sending a message to the user of your application.
It makes it easier to change the means of communication in the future. At one time you may want to display the messages on a web page instead of printing to stdout.

This last piece of advise, however, will add additional indirection that may not be needed. You may omit it if you feel that you'll be able to refactor your code at any time and just replace the println()s with something else.


If A was not included in the observed range, you wouldn't need the if (A == sqrtA * sqrtA) part, right? So, let's use that: instead of checking the range {A,A+1,...,B}, check the range {A-1,A,...,B}. Since you're working with integers, the two are the same:

        int sqrtA = (int)Math.Sqrt(A-1);
        int sqrtB = (int)Math.Sqrt(B);
        count = sqrtB - sqrtA;

A minor detail: when returning a predefined constant, I prefer writing the constant itself, not a variable initialized to that value:

        if (A < 0 && B < 0) return 0;

It seems more readable to me.

Also, I would replace two main if-s with if (B < 0 || B < A) return 0. This gives the same result, but in a cleaner way.

So, my version would be:

public static int CountPerfectSquares(long A, long B)
{
    // Return zero if there are obviously no perfect squares
    if (B < 0 || B < A) return 0;

    // Reset the lower bound if required
    if (A <= 0) A = 1;

    // Find the number of perfect squares between A & B (INCLUSIVE)
    return (int)Math.Sqrt(B) - (int)Math.Sqrt(A-1);  // Now giving the correct count, even when the lower bound value is a whole square (for exp. CountPerfectSquares(1, 25))
}


I think your solution still has some potential but you don't need an Enum for the #getCoinToss method because you don't have any advantage over using an Integer. Not using simple integers might even lead to your code getting more complex than it should, as you would have to implement some kind of way to convert the Integer to an Enum constant. This would be possible could affect the time complexity of your code even tho it would not be heavily noticable.

Binary

For handling the binary values I would not use an integer but instead a byte for obvious reasons:

The values of the two integral types are integers in the following ranges:

For byte, from -128 to 127
For int from -2147483648 to 2147483647

As you only need zero and one for representing binary data I would suggest using the "smaller" data type.

#generateValue Return Value

For this method, I would stick with an Integer as this method is public and might be used by other methods later on and an int is the most common data type. If you use a byte as the return value here you might have to cast the return value of this method when using it because most other methods don't use bytes as their arithmetic differs.

Still, you could use an Enum here which would have the advantage of the user not being able to create for example if-Statements that can't be true:

if (RandomDieValueGenerator.generateValue() == 7)

This problem would be solved if you provide an Enum for this return value because then, the user could only check if the return value of this method is one of the six defined possible enum constants.

Putting it all together

public class RandomDieValueGenerator {

    enum DieValue {
        ONE, TWO, THREE, FOUR, FIVE, SIX
    }

    public static DieValue generateValue() {
        int firstCoinToss = RandomDieValueGenerator.getCoinToss();
        int secondCoinToss = RandomDieValueGenerator.getCoinToss();

        if (firstCoinToss * secondCoinToss == 1) {
            return RandomDieValueGenerator.generateValue();
        }

        String binaryRepresentation = String.valueOf(firstCoinToss) + secondCoinToss + RandomDieValueGenerator.getCoinToss();
        return DieValue.values()[Integer.parseInt(binaryRepresentation, 2)];
    }

    private static byte getCoinToss() {
        return (byte) Math.toIntExact(Math.round(Math.random()));
    }
}


Nice implementation. Few suggestions to make the method groupByMean more compact using Java Streams:

Calculate the average:
public static double getAverage(int[] arr) {
  int sum = 0;
  for (int num : arr) {
      sum += num;
  }
  return ((double) sum) / arr.length;
}

To:
public static double getAverage(int[] arr) {
  return Arrays.stream(nums).average().getAsDouble();
}

Group by average:
if (!map.containsKey(average)) {
    List<Integer> indices = new ArrayList<>();
    indices.add(i);
    map.put(average, indices);
} else {
    map.get(average).add(i);
}

To:
map.computeIfAbsent(average, v -> new ArrayList<>()).add(i);

Convert list to array:
for (int k = 0; k < indices.size(); k++) {
    result[row][k] = indices.get(k);
}

To:
result[row] = indices.stream().mapToInt(index->index).toArray();

Convert map's values to a matrix:
int[][] result = new int[map.size()][];
int row = 0;
for (List<Integer> indices : map.values()) {
    result[row] = new int[indices.size()];
    for (int k = 0; k < indices.size(); k++) {
        result[row][k] = indices.get(k);
    }
    row++;
}
return result;

To:
return map.values().stream()
          .map(v -> v.stream().mapToInt(index->index).toArray())
          .toArray(int[][]::new);

Time/Space Complexity
In terms of complexity there are no relevant differences between your solution and the one using Streams. The time complexity is still \$O(n*m)\$ where \$n\$ is the number of arrays and \$m\$ is the size of the longest array. Basically, for each array we need to calculate the average.
To check which approach is faster you need to benchmark the solutions.
Final code
public static void main(String[] args) {
    int[][] arr = {{ 1, 2, 3 }, { 2, 3, 4 }, { 2, 4, 0 }};
    Arrays.stream(groupByMean(arr)).map(Arrays::toString)
        .forEach(System.out::println);
}

public static int[][] groupByMean(int[][] arr) {
    Map<Double, List<Integer>> map = new HashMap<>();
    for (int i=0 ; i<arr.length; i++) {
        double average = Arrays.stream(arr[i]).average().getAsDouble();
        map.computeIfAbsent(average, v -> new ArrayList<>()).add(i);
    }
    return map.values().stream()
      .map(v -> v.stream().mapToInt(index->index).toArray())
      .toArray(int[][]::new);
}


For what it is worth, using strlen is much more efficient than using strtok.  I did some tests (omitting the file access) using strlen, strchr, strtok, strstr, strpbrk and strcspn:

It surprised me that to execute this neat looking thing:

s = strchr(s, '\n');
if (s) {
    *s = '\0';
}

takes nearly 50% longer than this ugly looking sucker:

size_t len = strlen(s);
if (len && (s[len-1] == '\n')) {
    s[len-1] = '\0';
}

and the beautiful

strtok(s, "\n\r");

and

strsep(&s, "\n\r");

are 10 to 20 times slower.  The latter two do of course look for \r as well as \n. But even adding \r, the strlen approach is still quicker than the strchr and still quicker then strtok and strsep by 10 to 20 times:

size_t len = strlen(s);
if (len && ((s[len-1] == '\n') || (s[len-1] == '\r'))) {
    s[len-1] = '\0';
}

Note that I wasn't exhaustive with string variations.  In fact I didn't even break a sweat.  And of course this is all quite irrelevant as the stdio call will dominate in your target code :-)

Note also from the comments below that if the first character of the search string (s in the examples above) is one of the characters in the pattern string, strtok does nothing (thanks to @chux).


Avoid string building jQuery selectors. If your exampleData variable might contain special characters, or possibly contains user input, you've opened yourself to selector injection.

For example, if exampleData has a value of:

'"],body,[a="'

The computed selector becomes:

[data-example=""],body,[a=""]

which might cause unexpected behavior.

More typically, the selector will just fail outright, and your page or app will not work as expected.

Although jQuery calls itself the "write less, do more" library, this is a case where you'll need to write a bit more.

Instead of string building a single selector, use .filter():

$('[data-example]').filter(function () {
  return $(this).data('example') === exampleData;
});


Supporting different orientation in viewcontrollers

What about implementing CoreViewController class which by default support
landscape for iPad and portrait for iPhone.
All your VCs inherit from it.
As a result VC1,VC2 and VC3 will have it by default and in VC4 override rotation methods to add support for landscape mode?


Assigning values from a numerical array to an associative array

This has been answered here: https://stackoverflow.com/a/3000342/561731

array_combine

In your case:

$this->userdata = array_combine(['company','tx_trouserextend_contactperson',...], $data);

Can also just have anarray of $keys to match to your data and then use array_combine


You should provide a compiling code. I'll assume that n and m are int, but you should have added their declaration.

You should use explicit names for variables. n is a line count, so call it line_count. m is column_count.
You should check the return values of scanf to be sure you handle gracefully EOF and bad input.
You print "Error, number of colums/ligns < 1. \n" every time, so the user can't know if it's the lines or the columns or both that are < 1.
The english word is "lines", not "ligns".
Your checks are too complicated and redundants. The entire if/else block can be replaced by this:

while(*line_count < 1)
{
    printf("Error, number of lines < 1. \n");
    scanf("%d", line_count);
}

while(*column_count < 1)
{
    printf("Error, number of colums < 1. \n");
    scanf("%d", column_count);
}

printf("Number of lines : %x, Number of columns : %x \n", *line_count, *column_count);


Simple CSS minifier for twig, with basic caching

The very obvious thing is that str_replace.

Here, there are 2 things to change:

Completely remove this line.
All that replace can be made into the following regular expression: @(?:\s{2,}|[\r\n\t])+@
This should be the very first regular expression.
Since all the other rules handle whitespace, one only needs to normalize it. The rest of the replacements will dictate if it needs to be replaced or not.
If the whitespace is simply removed, it will lead to removing needed whitespace.
Here's an example CSS:

#services  img{
    max-width: 100%;
}

#slide .carousel-caption {
display: none
}

With the replacement as an empty string, you would remove the double-space in #services  img. Normalizing it to a single space will return #services img instead of minifying into #servicesimg.

With this said, and a bug fixed, the code will look like the following:

    $twig->addFilter(new Twig_SimpleFilter('minify_css', function($css, $cache = true){
        $path = $_SERVER['DOCUMENT_ROOT'] . '/cache/minify_css/';
        $min_length = 1024;

        if(!is_dir($path))
        {
            mkdir($path, 0755, true);
        }
        $length = strlen($css);
        $result = '';

        if($cache && $length > $min_length && @is_file($file = $path . ($hash = md5($css)) . '.css' ))
        {
            $result = file_get_contents($file);
        }
        else if($length >= 9)
        {
            $result = preg_replace(
                array(
                    '@(?:\s{2,}|[\r\n\t])+@', // normalize whitespace
                    '@/\*[^*]*\*+([^/][^*]*\*+)*\/@', // /*abc*/ ->
                    '@([\-;\{]\w*)\s*:\s*@', //a : b -> a:b
                    '@\s*;\s*\}\s*@', //a:b ; } -> a:b}
                    '@\s*\{\s*@', // a { b:c} -> a{b:c}
                    '@\s*!important\s*@i', // a:b !important } -> a:b!important}
                    '@([,;}!:]|^)\s*0+\s*px@i', // a: 0px -> a:0
                    '@([,;:!.>~\+=\[\{\}\(]|^)[\s\r\n]+@', // a, b -> a,b
                    '@[\s\r\n]+([,;!>~\+=\]\{\}\)]|$)@', // a ,b -> a,b
                    '@([,:\( ])\s*#([\da-f])\2([\da-f])\3([\da-f])\4@i' // a: #FF00CC -> a:#F0C
                ),
                array(
                    ' ',
                    '',
                    '$1:',
                    '}',
                    '{',
                    '!important',
                    '${1}0',
                    '$1',
                    '$1',
                    '$1#$2$3$4'
                ),
                $css
            );

            if($cache && $length > $min_length)
            {
                file_put_contents($file, $result);
            }
        }
        return $result;
    }), array('is_safe' => array('html', 'css', 'js'))
);


NSDictionary * dictionary = nil;
NSError * returnError = nil;
NSString * errorCode = nil;
NSString * errorText = nil;

This is superfluous and unnecessary.  It's more than fine to just declare them.  They're nil by default.

NSDictionary *dictionary;
NSError *returnError;
NSString *errorCode;
NSString *errorText;

You should use modern syntax for your mutable dictionaries.

Rather than [someDictionary setValue:someValue forKey:someKey];, you can and should simply do:

someDictionary[someKey] = someValue;

And the same can be done for accessing the variable.  Rather than NSString *foo = [someDictionary objectForKey:someKey];, you can and should simply do:

NSString *foo = someDictionary[someKey];

Most Objective-C programmers I know (and certainly myself included) don't particularly like foo == nil or foo != nil.  We can instead use:

if (foo) // foo != nil

And

if (!foo) // foo == nil

I don't know what exactly createApiUrlFromEndpoint: does for you, as it's not included in the review.  But I'd argue, strictly speaking, that this method (the one posted for review) should probably take an NSURL for the endpoint argument and createApiUrlFromEndpoint: should be a public method.  If for no other reason, it could save multiple calls to createApiUrlFromEndpoint: if a user wants to use the same URL multiple times with a different params dictionary.

Moreover, as the method is called "create API URL", it should return an NSURL object, not an NSString object.

if([data length] >= 1)

I personally thing >= and <= are ugly and only use them when there's no alternative (or the alternative is even uglier).  In this case, length is an unsigned integer, so if([data length] > 0) is exactly the same... except less ugly in my opinion.

Your method is called makeRequestToEndPoint:values:onCompletion:

I'm going to argue that values: should be changed to params: since that's what you're naming the the variably internally.

I'm also going to argue that onCompletion: should be changed to completionHandler: or completion: so that it matches every other existing Apple method which takes a completion block as an argument.

dictionary = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];

You've got an error object.  You call a method that could have an error, but you don't care at all about the possible error that could happen within this method?  You should send &returnError rather than nil as the last argument, and immediately follow this call with:

if (error) {
    responseHandler(dictionary,returnError);
    return;
}

There's no point in continuing to execute code in the method if all the other code relies on the dictionary being initialized correctly, AND if the dictionary wasn't initialized correctly AND we're going to return some sort of an error, we should at least care about the one that goes with this method and will give a decent description of what problem occurred.

To add to the previous point, this is all happening within a completion block which sends as an argument an NSError object.  So the absolute first thing we should do before we try to initialize the dictionary is check this error object, and just as before, if it exists, call responseHanlder(nil,error); and return out of the method.

As it stands, other than the points I made above, the code seems decent enough.  For completeness however, you might implement a way of accomplishing this within the same class with the delegate-protocol pattern, rather than completion blocks.

To do this, you'd need to create a protocol, add a delegate property (which conforms to the protocol and is a weak property), and add a instance method version of this class method--the primary difference being that the instance method doesn't take a completion block argument, and instead of executing a completion block, it calls the delegate methods.

Unlike Ravi D's answer, however, the delegate methods defined in your protocol need more arguments so they can send more detail.

You could create a single method that's called regardless of whether or not there's an error:

@required - (void)fooBarObject:(FooBarObject *)fooBarObject
            didCompleteRequest:(NSDictionary *)results
                         error:(NSError *)error;

Where the first part of the method is sending a self argument (similar to tableView:cellForRowAtIndexPath:, etc), the second argument is the results dictionary (though would be nil in the case of an error) and the third argument is the error (and would be nil when there's not an error.  These leaves it up to the delegate to handle checking whether or not there was an error in this method.

Alternatively, you can require two methods, one for success and one for failure.  You're checking that in your methods, and the delegate doesn't have to do the check--simply has to implement a method for each scenario:

@required - (void)fooBarObject:(FooBarObject *)fooBarObject
            didCompleteRequest:(NSDictionary *)results;

@required - (void)fooBarObject:(FooBarObject *)fooBarObject
                requestDidFail:(NSError *)error;


Random number generator based on a hash of the time

It looks like you're relying on running this on a system where the granularity of the time() function is smaller than the amount of time it takes to execute baseRandom(), do what you want with the results, and come back to call baseRandom() again.  If not, you'll get more repeating numbers than you should.  You're also relying on the result of the hash() function to be sufficiently pseudorandom given the input you're feeding to it.

Detecting an obvious pattern depends on how you look for it.  I think Knuth gave an example of a RNG that looked OK when you plotted pairs of numbers on an x-y plane, but if you took three numbers in a row as x-y-z coordinates, and look at the resulting cube from the right direction, you can clearly see a finite number of planes where all the outcomes lie.  In other words, just because you tried a couple of things and didn't see a pattern doesn't mean a non-random pattern isn't there.

There are fifteen tests for randomness listed here, if you're interested: http://csrc.nist.gov/groups/ST/toolkit/rng/stats_tests.html


Find the longest ascending subarray from a given array

Josay provided a lot of good feedback, so I'll try to focus on something I think is very important.

There's no need to save the current subsequence

For your solution, you manage two lists, both of which are rewritten and cleared multiple times. Instead of doing this, we can just save where the largest subsequence starts, and how long it is. This can be stored in two integers.

When looping, we also keep track of where the current subsequence started, and how long it is. Once it is broken, we simply compare the length to the previous maximum length, and update accordingly. I also added a check to handle sequences which are fully ascending (e.g. {1, 2, 3, 4, 5}).

public static int[] getLongestAscending(int[] a) {
    int maxLength = 0;
    int maxStart = 0;
    int length = 1;
    int start = 0;
    boolean fullAscension = true;
    for (int i = 1; i < a.length; i++) {
        if (a[i]-1 == a[i-1]) {
            length++;
        } else {
            fullAscension = false;
            if (length > maxLength) {
                maxLength = length;
                maxStart = start;
            }
            length = 1;
            start = i;
        }
    }
    if (fullAscension) {
        return a;
    }
    if (length > maxLength) {
        maxLength = length;
        maxStart = start;
    }       int[] ret = new int[maxLength];
    System.arraycopy(a, maxStart, ret, 0, maxLength);
    return ret;
}

According to me, this is clearer, and saves all information needed. It also has the advantage of returning data on the same format as the input, and it is also quite a bit faster. From some benchmarks it seems to be about 20-30 times faster.


See if you can figure this bit out.

Is this meant to be a Programming Puzzle?

You don't call append until after you finish calling reverse; reverse is recursive; so all the append calls will be called after all the reverse calls: and that explains why reverse will eventually terminate i.e. why the list will eventually be empty.

From a code-review point of view:

I fear that a recursive implementation might exceed your finite maximum stack size if the list is long.
You're deleting and creating new Node objects; you might instead be able to do it in a way that reuses existing Node instances.

Also, it should be spelled "sentinel".


Your iterator is missing a few important details:

You should provide the pre- and post-increment operators (++it and it++). Currently, you only have the pre-increment version.

It might also be good to provide the -> operator, since some people prefer the it->something syntax over the (*it).something one.

The comparison and dereference operators should be const. Remember Const Correctness.

The copy constructor is just performing a memberwise copy of the underlying data, so you don't need to provide one and can let the compiler default it.

The Standard Library containers always provide two flavors of iterators, the iterator type, pointing to mutable data, and the const_iterator type, pointing to immutable data. It is easy to adapt your class to support both by providing a conversion operator and inheriting from std::iterator (see the following example).

Decide which course of action should be taken when incrementing and dereferencing an invalid iterator. E.g.: list.end()++;. Should it trigger an assertion? Throw an exception? Do nothing as it is now? I would at least assert to help the debugging process. You might find exceptions more appropriate in your context.

The above points applied to your code:
#include <cassert>      // assert
#include <cstddef>      // ptrdiff_t
#include <iterator>     // iterator
#include <type_traits>  // remove_cv
#include <utility>      // swap

template
<
    class Type,
    class UnqualifiedType = std::remove_cv_t<Type>
>
class ForwardIterator
    : public std::iterator<std::forward_iterator_tag,
                           UnqualifiedType,
                           std::ptrdiff_t,
                           Type*,
                           Type&>
{
    node<UnqualifiedType>* itr;

    explicit ForwardIterator(node<UnqualifiedType>* nd)
        : itr(nd)
    {
    }

public:

    ForwardIterator()   // Default construct gives end.
        : itr(nullptr)
    {
    }

    void swap(ForwardIterator& other) noexcept
    {
        using std::swap;
        swap(itr, other.iter);
    }

    ForwardIterator& operator++ () // Pre-increment
    {
        assert(itr != nullptr && "Out-of-bounds iterator increment!");
        itr = itr->next;
        return *this;
    }

    ForwardIterator operator++ (int) // Post-increment
    {
        assert(itr != nullptr && "Out-of-bounds iterator increment!");
        ForwardIterator tmp(*this);
        itr = itr->next;
        return tmp;
    }

    // two-way comparison: v.begin() == v.cbegin() and vice versa
    template<class OtherType>
    bool operator == (const ForwardIterator<OtherType>& rhs) const
    {
        return itr == rhs.itr;
    }

    template<class OtherType>
    bool operator != (const ForwardIterator<OtherType>& rhs) const
    {
        return itr != rhs.itr;
    }

    Type& operator* () const
    {
        assert(itr != nullptr && "Invalid iterator dereference!");
        return itr->data;
    }

    Type& operator-> () const
    {
        assert(itr != nullptr && "Invalid iterator dereference!");
        return itr->data;
    }

    // One way conversion: iterator -> const_iterator
    operator ForwardIterator<const Type>() const
    {
        return ForwardIterator<const Type>(itr);
    }
};

// `iterator` and `const_iterator` used by your class:
typedef ForwardIterator<T> iterator;
typedef ForwardIterator<const T> const_iterator;

Note: In the example, I've assumed that the end of your list or an invalid iterator are marked by a null pointer. You'll need to change that if you are using some other method, such as a dummy sentry node.


Since (I assume) there should only be a single cookie fragment called cookie_law you should use find instead of filter. filter will go through the whole array even if the result is the first element.
As it stands I think that it is bad for a filter method to modify the underlying data.
Also the number of parenthesis in the line
.map(c => JSON.parse(atob(decodeURIComponent(c.pop())))).pop()

is pretty scary. I would pull at least some of that out into another method.
update
In my code I usually split out my logic with a method to get any cookie, that way I can reuse it for other cookies. The logic also ends up being simpler.
function getCookieLawSettings() {
    return decodeCookie(getCookie('cookie_law'));
}

function getCookie(na,e) {
    var cookie = document.cookie.split(';')
            .map(c => c.trim().split('='))
            .filter(c => c[0] === name);
    return cookie ? cookie[1] : undefined;
}

function decodeCookie(data) {
    return JSON.parse(atob(decodeURIComponent(data)));
}

function encodeCookie(data) {
    return btoa(encodeURIComponent(JSON.stringify)));
}


For one, it is not an abstract repository, but a generic repository. Never mind. As mentioned in a comment, generic repositories are hardly ever helpful and I would never use them. But apart from that, there's a couple of things I can say about this code:

TryGet should be absolutely safe (that's what the "Try" prefix conveys), so use FirstOrDefault() and only return an entity if exactly one is fetched.
I would not return a List, but an IEnumerable, so you retain deferred execution.
If the repository is only internally used, e.g. to supply data for services, I would return IQueryable, so you can compose queries from different repositories, do projections, includes and everything you can do with IQueryable and not with IEnumerable.
As said in another comment, it is not necessary to return anything from Add and Update, because you always modify a reference type.
I would prefer method names like MarkForDelete, because that's what actually happens.


Sum of multiples of 3 or 5 below 1000 in Scala

In the Scala solution as in the Erlang solution, the accumulator is pointless.  For max = 1000, you don't necessarily have to be concerned about tail recursion, and you could just write it without an accumulator:

def sumMultiplesRecursive(from: Int, to: Int): Int = {
    if (from >= to) {
        0
    } else if (from % 3 == 0 || from % 5 == 0) {
        from + sumMultiplesRecursive(from + 1, to)
    } else {
        sumMultiplesRecursive(from + 1, to)
    }
}

Note that the sum_multiple_recursive name, with underscores, does not follow the Scala naming convention.  It is not so helpful to mention that it works recursively, but it would also be useful to describe what you mean by "multiples".

The from and to parameters, together, could constitute a Range.  If you are going to use a Range, then you might as well take advantage of its capabilities:

def sumMultiplesOf3Or5(range: Range): Int = {
    range.filter(n => n % 3 == 0 || n % 5 == 0).sum
}

val max = 1000;
println(s"The sum of all the multiples of 3 or 5 below ${max}: " + sumMultiplesOf3Or5(1 until max));


If the size of your input array can be large, you can get a speed-up by preallocating the capacity of your HashMap:

Map<Integer, Integer> numbersMap = new HashMap<Integer, Integer>(numbers.length * 2);

As the algorithm runs, data will be added to the HashMap.  When number of entries exceeds the capacity * load_factor, the hashmap's capacity is doubled, and the elements are re-binned for the larger capacity.  This capacity doubling and rebinning takes time.  It doesn't happen often, \$O(\log N)\$ times, but it can be eliminated by starting with a hashmap of sufficient capacity.

The load_factor defaults to 0.75, so an initial capacity larger than numbers.length * 4/3 is required.  numbers.length * 2 is a simple expression that satisfies that requirement.


I'm not sure what kind of error your getting but here is a very simple collision test:

#include <cmath>
#include <iostream>

class float3 {
        public:
                float x,y,z;
};

class float4 {
        public:
                float a,b,c,d;
                float norm() const{
                        return sqrt(a*a+b*b+c*c);
                }
};

typedef float4 plane;

class sphere {
        public:
                float3 position;
                float radius;
};

float project( const float3 & spherePos, const plane & p){
        return std::abs( spherePos.x*p.a + spherePos.y*p.b + spherePos.z*p.c + p.d );
}

bool const collision( const sphere & s, const plane & p){
        return project(s.position,p)/p.norm() < s.radius;
}

int main( int argc, char * argv[]){

        plane p = {0.0,-1.0,0.0, 2.0 };
        sphere s = { {0.0,1.5,0.0}, 1.0 };

        if ( collision(s,p) )
                std::cout << "Collision detected" << std::endl;

}

The advantage here is that you don't need a normalized plane. The line that bothers me is this:

return abs<float>(dot(p.normal, s_origin) - p_distance) < s.radius;

Just write your solution such that it can handle un-normalized planes. If you're working with normalized planes (which may be what is contained in "p.normal"?) I believe you need :

return abs<float>(dot(p.normal, s_origin) + p_distance) < s.radius;

See the wolfram page on this topic - it is straight forward. It is not clear how you have implemented BoundingPlane - but if you are getting errors, that would be the first place to look.


Project Euler #1 - Multiples of 3 and 5 - First Program

Here's what I would change:

I'd use a for loop instead of a while loop here: for (int currentNumber = 999; currentNumber > 0; currentNumber--). This keeps all loop-related things grouped together. Loop bodies can be skipped or broken out of, so if code that must be executed every cycle is put at the end of a loop body it's easily broken when the loop body grows more complex and someone adds a continue or break in there.
Actually, there is no need to count down - the result will be the same either way. Counting up is often a little easier to understand: for (int currentNumber = 0; currentNumber < 1000; currentNumber++). Note that using < here means you don't need to decrement currentNumber by one before the loop starts.
You can write a += b instead of a = a + b (the same goes for various other operators).
else { if { .. } } can be simplified to else if { ... }.
Though in this case, a single if statement is sufficient: if (currentNumber % 3 == 0 || currentNumber % 5 == 0) { ... }. The 'or' operator (||) short-circuits if the first expression is true, so if a number can be divided by 3 it won't also try to divide it by 5.
C# naming conventions typically write class, method and namespace names in PascalCase.

Regarding your questions:

Static things belong to a class, non-static things belong to instances of that class. Classes are to instances what blueprints are to actual buildings. Trying to access a non-static (instance) members from a static context is like trying to open a door on a blueprint. The blueprint doesn't contain any real doors, only actual buildings do.
Programs need a place to start executing, and in C# the starting point is a static Main method. Putting everything in there is fine for a small program like this.
Identifier names in C# cannot start with a number, so 3_5_multiples isn't a valid name. I'd probably use EulerProblem1 or something like that here.
Namespaces are useful for organizing larger programs (namespaces to classes are a bit like folders to files). The root namespace of a project is usually the name of that project itself, and child namespaces often correspond to folders.

EDIT: Part of the fun on Project Euler is coming up with more efficient solutions. Can you find a way to solve this without checking every number below 1000?


Why do you check the time with (hours - 12 < 0). This involves two operations, one subtraction and one compare. You could simply use (hours < 12).

Also you rely that in the method set24hrTime(int newTime) the time is never > 23 for your code to work. Why don't you check this?

Also what about the value 0 for your hours? This must be displayed as 12 AM. At the moment you return 0 in this case where it must be 12.

Also for the value 12 of the hours you return 0 as value for the 12hrTime which is wrong.

To sum up I would suggest the following code:

public Clock {
    private int time = 0;
    public int get24hrTime() {
        return time;
    }
    public int set24hrTime(int newTime) {
        if (newTime > 23 || newTime < 0) {
            throw new IllegalArgumentException();
        }
        this.time = newTime;
    }
    public int get12hrTime(){
        if (time == 0) {
            return 12; // Special case 0
        } else if (time <= 12) {
            return time;
        } else {
            return time - 12;
        }
    }
    public String get12hrPostfix() {
        if (time < 12) {
            return "AM";
        } else {
            return "PM";
        }
    }
}


Follow PEP8

A is a bad variable name, use say matrix.
You should remove the space in-front of the function argument.
You should put spaces after ,.
You don't need the () surrounding sorted.
You could add some space around your division.

You can use // rather than / to make your code Python 2 and Python 3 compatable.
You don't need to use pop, normal indexing will work too.

def find_median(matrix):
    """Returns the median value from given matrix"""
    for i in range(1, len(matrix)):
        matrix[0].extend(matrix[i])
    return sorted(matrix[0])[len(matrix[0]) // 2]

Your code doesn't work as the challenge asks, if you add print(matrix) before return you'll see:

[[1, 3, 5, 2, 6, 9, 3, 6, 9], [2, 6, 9], [3, 6, 9]]


Play audio files when buttons are clicked in Simon Says

I recommend removing the inline onclick event handlers from your HTML document for a cleaner separation of markup and logic / JavaScript similarly to how you separate markup and style / CSS.

You can then add all event handlers with a few lines of code as follows:

document.querySelectorAll('.pushPad').forEach(pad => {
  let audio = pad.querySelector('audio');
  pad.addEventListener('click', event => audio.play());
});

A better design would probably have the data-pad attributes on the colored buttons and not on hidden <audio> elements, introduce a mapping between pad and audio source and leverage the web audio API instead. Using <svg> shapes instead of heavily styled <div>s for the UI might further simplify your markup.


Screen recorder producing huge AVI files

takeScreenshot()

Based on the .NET Naming Guidelines methods should be named using PascalCase casing takeScreenshot() => TakeScreenshot()
You are enclosing the usage of the Bitmap inside a using statement which is the way to go but calling Dispose() on that Bitmap is superfluous because that is what a using statement is doing.
If you have two using statements without any code between you can stack them which saves one level of indentation like so (already removed the Dispose())

using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
using (Graphics g = Graphics.FromImage(bitmap))
{
    //Add screen to bitmap:
    g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);

    //Create and save screenshot:
    string name = path + "//screenshot-" + fileCount + ".jpeg";
    bitmap.Save(name, ImageFormat.Jpeg);
    inputImageSequence.Add(name);
    fileCount++;
}

Comments should explain why something is done in the way it is done. Let the code itself tell what is done by using meaningful named things. In this way your comments won't lie like e.g //Create and save screenshot: which isn't what that code does. Saving yes but no creating of a screenshot is taking place.

Creating the video

Try to be consistent. Here you create a Bitmap and call Dispose() instead of using a using statement. In addition, sometime you use var and sometimes you use the concrete type although the type is seen at first glance.
If you are using the as operator you should always add a null check for that object because an as operator won't throw an exception but the resulting object may be null which will trigger an exception somewhere else.

Implementing these points will look like this:

Rectangle bounds = Screen.FromControl(this).Bounds;
var width = bounds.Width;
var height = bounds.Height;

var framRate = 5;

using (var vFWriter = new VideoFileWriter())
{
    vFWriter.Open(outputPath+"//video.avi", width, height, framRate, VideoCodec.Raw);

    foreach (var imageLocation in inputImageSequence)
    {
        using(var imageFrame = (Bitmap)System.Drawing.Image.FromFile(imageLocation))
        {
            vFWriter.WriteVideoFrame(imageFrame);
        }
    }
    vFWriter.Close();
}
DeletePath(path);

My guess about the big file size is that you are using the VideoCodec.Raw. Try to change it to some other codec and see if this helps.


Ghostscript check, sends e-mail if one occurs

Looks pretty good, just some minor details:

if res == nil -> if !res
DRY the sending of the email by creating a new method: send_email(to, subject, body)
Subjective: I'd not include a blank lines when there is a change of indentation level (between class and attr_accesor)


Elegant way to add a value to a member variable inside a vector

You could use a range-based for loop and push_back( Pressure(i,i) ).

#include <iostream>
#include <vector>

class Pressure {
public:
    Pressure(int date, int time) : m_date(date), m_time(time) {

    }

    int GetDate() const {
        return m_date;
    }

    int GetTime() const {
        return m_time;
    }

    void AddTime(int val) {
        m_time += val;
    }
private:
    int m_date;
    int m_time;
};

int main() {
    std::vector<Pressure> p;

    // populate the vector with values.
    p.reserve(10); // you can reserve space if you know the size ahead of time to prevent extra reallocations, but it isnt necessary for a vector this small.
    for(int i = 0; i < 10; ++i) {
        p.push_back( Pressure(i,i) );
    }

    for(Pressure& pressure : p) {
        // add offset
        pressure.AddTime(20000);

        // display data
        std::cout << pressure.GetDate() << " " << pressure.GetTime() << "\n";
    }

    return 0;
}


Looks OK.

Though I have to ask why you're using map, when you're not really mapping the array to a new array. Using reduce would be more semantically correct, but in this case even just replacing map with forEach would also be more accurate. (The difference is literally only skin-deep; there's zero change in overall functionality.)

I might ask why an undefined value should throw an exception, though. It'll work fine without it, and I might want to group objects based on whether or not they have a certain property or not. Without the exception, I'd be able to get back an object with some of the elements grouped by the key "undefined"

And if I were super nit-picky, I'd say you should always using braces even for one-line "block" like your throw line.

I'm betting, though, that a lot of the time, you'll want to group by a simple, named key, in which case it'd be much easier to pass in a string, rather than a function. A custom function is still very useful, though, so it'd be nice to support both.

I might do:

function groupBy(array, keyOrIterator) {
  var iterator, key;

  // use the function passed in, or create one
  if(typeof key !== 'function') {
    key = String(keyOrIterator);
    iterator = function (item) { return item[key]; };
  } else {
    iterator = keyOrIterator;
  }

  return array.reduce(function (memo, item) {
    var key = iterator(item);
    memo[key] = memo[key] || [];
    memo[key].push(item);
    return memo;
  }, {});
}

Lastly: Libraries like underscore.js and it's "doppelgänger" lo-dash has this and many other helpful functions, ready for you to use. I'm only mentioning it because if you found yourself needed a groupBy function, you'll probably find yourself needing other similar functions, and libraries like those provide that in spades.


Upper section of a vertical single-page website

HTML validation

Always include a doctype declaration.  These days, HTML 5 is recommended, so the document should start with <!DOCTYPE html>.

The
 is unclosed.  That would likely explain your vertical alignment issues.

The <meta charset="utf-8"> declaration should occur as early as possible, preferably immediately after the opening  tag, because the charset affects how all text in the document is interpreted.  It would be better not to make the browser re-parse the <title>.

The  tag must have an alt attribute.  The omission of the alt attribute is unacceptable here, especially since the image contains text.  It is odd that the logo has a height attribute but no width.

HTML semantics

The
 inside the
 is not appropriate, since it is there for styling.  I would go with a width rule in CSS, using em as the measurement unit so that it scales with the font size.

Writing class="nav" in every navigation link, though harmless, seems excessive.  These elements could be selected in CSS using nav > a instead.

It's unclear which of the  links, if any, takes you back to the "home" page.

CSS

The * selector is excessive.  If you want to set a font for the page, a body rule should suffice.

In #PageHeader, you set a background-color.  It would be a good idea to also set the color at the same time.  A comment saying /* white text on orange */ would be nice.  You should specify color: white on the links too, in such a way that applies even to visited links.

When you float each nav link to the right, the visual order ends up backwards relative to the DOM order.  I would rather float the entire .  It would be a good idea to specify a margin-left on the nav so that it will not overlap the logo if the page is too narrow.

body {
  font-family: Open Sans;
  margin: 0px
}

#PageHeader {
  background-color: rgb(236, 100, 62);
  color: white;
  height: 615px;
}
/* logo and nav look aligned on the original file :c */
#logo {
  position: relative;
  margin-left: 40px;
  top: 30px;
}

nav {
  float: right;
  margin-left: 200px;
}

nav > a {
  text-decoration: none;
  font-size: 12px;
  font-weight: bold;
  text-transform: uppercase;
  margin-right: 40px;
  color: white;
}

nav > a:hover {
  border-width: 0px 0px 3px 0px;
  border-style: solid;
}

#heading {
  color: white;
  text-align: center;
  line-height: 1.2;
  margin-top: 150px;
}

#heading h1 {
  font-size: 60px;
  margin-bottom: 30px;
  margin-left: auto;
  margin-right: auto;
  width: 15em;
}

    <title>Empreendi na Rede</title>
    <meta charset="utf-8">
    <meta name="author" content="Luciano Infanti">

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,800" rel="stylesheet">

        Solucoes
        Metodologia
        Sobre nos
        Depoimentos
        Clientes
        Contato

A consultoria empresarial acaba de ser redefinida

Aliquam et placerat lacus. Donec pharetra nibh a placerat tincidunt.

  Integer viverra nisl dolor, in viverra enim sollicitudin nec.


I think, performance wise, you won't get much better than the if-then-else construct. Since isAssignableFrom is not a direct lookup, but a rather complex task, but your runtime types are actually limited, it may be helpful to build a cache around the result. So, if you found a type match, keep that in a direct lookup cache to avoid walking the if-then.

To help with code-maintenance, I would refactor the comparisions into seperate stateless comparator classes, each will implement one function, the getValue method.

The list of comparators will be initialized at some early point in the lifecycle of your application and put in a list. The method getValue will be reduced to a for loop over the comparator-list.

Adding another type is now reduced to changing a comparator class. This makes it very obvious, what you have changed even in changelogs, since the class is mentioned in the committed-files-list.

To help maintenance even more, you could introduce either a search of your classpath for the comparator interface or introduce an annotation to mark the implementations for automatic building of the list.

This will give you an almost self-maintaining code for the given task. Whenever you need a new type, you just add it with the right interface/annotation and it will magically be seen on the next run.

This would be your main entry point.

public class ValueGetter {

    private static List<TypeConverter> converter;

    static {
        // might require synchronize
        converter = new ArrayList<>(1);
        converter.add(new FloatConverter());
        // ... add more or build using reflection or whatever
    }

    public Object getValue(final Class<?> type, final int index, final ResultSet resultSet) throws SQLException {
        Object value;

        for (TypeConverter c : converter) {
            value = c.getValue(type, resultSet, index);
            if (value != TypeConverter.NOTTYPE) {
                return value;
            }
        }

        throw new IllegalArgumentException("Cannot convert to requested type");
    }
}

This is the interface mentioned.

public interface TypeConverter {

    public static final String NOTTYPE = "not of this type";

    Object getValue(Class<?> type, ResultSet resultSet, int index) throws SQLException;
}

This is taking the float if-else

public class FloatConverter implements TypeConverter {
    @Override
    public Object getValue(Class<?> type, ResultSet resultSet, int index) throws SQLException {
        if (Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) {
            return resultSet.getFloat(index);
        }

        return NOTTYPE;
    }
}


Improve Parallel Cache with Reactive Extensions & Unity Interception

Personally i believe that there is no need for the reactive framework in this scenario.
To handle the multithreaded nature of your problem i would first make sure that your RequestCache (Icache) uses the ConcurrentDictionary> and exposrts the method GetOrAdd

With this your code will look like this:

/// <summary>
/// Intercepts the calls and tries to retrieve from the cache
/// </summary>
class CacheCallHandler : ICallHandler
{

    [Dependency]
    public ICache RequestCache { get; set; }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        return InvokeAsync.Result;
    }

    public Task<IMethodReturn> InvokeAsync(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        IMethodReturn mesg = null;

        string cacheKey = CacheKeyGenerator.GetCacheKey(input);

        //create the task to retrieve the data
        var task = RequestCache.GetOrAdd(
               cacheKey,
               key => new Task.Factory.StartNew(() => getNext()(input, getNext))
               );

        return task;
    }

    /// <summary>
    /// Should always be the first to execute on the boundary
    /// </summary>
    public int Order
    {
        get { return 1; }
        set { ; }
    }
}

The asynchronous version offers the option of to blocking the calling thread when invoking it.


I don’t do programming challenges, so my review will be more from the point of view of actually writing decent C++ rather than the programming challenge mindset (which, in my humble opinion, encourages terrible coding practices). Nevertheless, if it’s performance you want, I can give you some tips on how to get some huge speed increases.
So let’s dive in.
#include <bits/stdc++.h>

I’ve heard this is standard practice in programming challenge circles. Nevertheless, it is terrible practice in real life. Instead, look at all the standard library components you use, and include the headers for them. In your case, you use cin/cout, vectors, strings, pairs, and the sort function, so you’ll need their headers. Including only those headers should speed up compilation measurably, but I don’t know if compilation time is counted in total time, so I don’t know how much that will help.
using namespace std;

Never do this, even in a programming challenge. It’s just a terrible habit that will eventually bite you in the ass. Just put std:: where needed. Just get used to it.
int main(int argc, char *argv[]) {

Since you don’t actually read the command line, you can just use the simpler form of main().
Now you’ve packed your entire program into main(). That’s okay for this very trivial program, but you should really get in the habit of writing better code. Isn’t that what programming challenges are for, after all?
Break the program into logical steps, and put each major step into its own function. It costs nothing; even the most basic level of optimization will eliminate all the overhead (and anything it doesn’t isn’t worth eliminating).
The first step is to read the number of pairs in the data set… so it should be a function  called read_dataset_size(), or something like that. It could look something like this:
auto read_dataset_size() -> int;

Or, even better, take the input stream as a parameter:
auto read_dataset_size(std::istream&) -> int;

Why would you do that? Because it makes the function easier to test. You should always program with testing in mind, even for off-the-cuff code like this. Because if something doesn’t work—and we all make stupid mistakes—you want to be able to do tests to figure out what the problem is. With the function written like above, you can read the input from a file, or even directly from memory, and see whether you get the expected result.
So, refactored that way, the read_dataset_size() function looks like this:
auto read_dataset_size(std::istream& in) -> int
{
    int t;  in >> t;

    return t;
}

(This is just your code exactly as you’ve written it, except I replaced cin with in. And of course, added the return statement.)
Now, you should never write two statements on a single line. Space costs nothing, but being able to read code clearly is the difference between having silly hidden bugs or not. So:
auto read_dataset_size(std::istream& in) -> int
{
    int t;
    in >> t;

    return t;
}

Even better would be to give clear names to the variables:
auto read_dataset_size(std::istream& in) -> int
{
    int size;
    in >> size;

    return size;
}

Normally you’d do error checking to make sure you actually read a proper number and all… but okay, I get this is just challenge code. So we’ll skip the error checking.
That’ll do for this bit.
Your next function should be something like read_data_pairs() or something. It should look something like this:
auto read_data_pairs(std::istream&, int) -> std::vector<std::pair<int, std::string>>;

And with your code refactored into it:
auto read_data_pairs(std::istream& in, int size) -> std::vector<std::pair<int, std::string>>
{
    std::vector< std::pair <int,std::string> > median;

    int num; std::string name;
    for(int i=0;i<size;i++) {
        in>>name; in>>num;
        median.push_back( std::make_pair(num,name));
    }

    return median;
}

(Note this is exactly your code with the std::s added, cin replaced with in, and t replaced with size, and of course the return statement added.)
Alright, now let’s talk performance.
Here’s the problem: vector automatically resizes to accommodate more data. When it does, it has to allocate a new chunk of memory (usually twice the size of the existing capacity), and then copy all the old data into the new memory. If there are 1,000 pairs in the vector, then the vector would have to allocate space for 2,000 pairs, and then do 1,000 copies (technically, moves). In modern C++, that all happens very quickly… but it’s still not free; there’s still a cost. And if you’ve got millions of pairs….
Even worse, it will probably happen many, many times as you read in the data. Your vector will start empty, and then have to allocate space for a couple elements. You’ll read in a couple elements, then run out of space again… so the vector will have to allocate a new block of memory, and copy everything over. Now you’ll read in a few more elements… but soon run out of space again. So the vector will have to reallocate and copy again. And it will have to do it over and over and over. And as the number of elements becomes huge, all that allocating and copying will add up quickly.
Here’s the key to fixing that problem. You already know the size of the input data. So you can just pre-allocate all the space you need, and avoid the need for all that reallocation and copying. The technically correct way would be to do this:
auto read_data_pairs(std::istream& in, int size) -> std::vector<std::pair<int, std::string>>
{
    std::vector< std::pair <int,std::string> > median;  // median probably
                                                        // isn't a great name
                                                        // for this variable,
                                                        // because it isn't
                                                        // the median... it's
                                                        // all the input data
                                                        //
                                                        // maybe call it
                                                        // "pairs" instead?

    median.reserve(size); // this is the magical line that will probably fix
                          // all your performance problems

    int num;
    std::string name;
    for(int i=0; i < size; ++i)
    {
        in >> name;
        in >> num;

        median.push_back( std::make_pair(num,name));
    }

    return median;
}

That one line alone will probably fix your timeout errors.
But we can do even better.
Although we’re reserving all the memory we’re going to need, we’re still pushing elements on to the vector. Now it is going be very quick… but, again, still not free.
So instead of just reserving space and then pushing elements in to the vector over and over… why not create the elements right away, and then read the data directly into them? No extra copies needed.
This is technically not good practice in general… but it is a valid hack for efficiency. And efficiency is what you’re gunning for.
So:
auto read_data_pairs(std::istream& in, int size) -> std::vector<std::pair<int, std::string>>
{
    std::vector<std::pair<int,std::string>> median;

    median.resize(size);    // note: reSIZE, not reSERVE
                            // this will fill the entire vector with the
                            // right number of pairs in a single shot

    // note: no more need for temporaries to read input!
    // we'll be reading *directly* into the proper place

    // note: we can use the much safer range-for loop now
    for (auto&& element : median)
    {
        in >> element.first;
        in >> element.second;
    }

    return median;
}

That’s about as fast as that can be, I think.
The sorting is just a call to std::sort()… not much we can do to improve that, or speed that up.
Now, the way the output is printed is a bit weird. Why do you do median[t/2].second and then median[t/2+1].first? Are you sure that’s correct? Have you tested it with more data than what is shown? (Seriously, TEST YOUR CODE!!! That’s the biggest thing that separates the shitty coders from the good ones. You should test your code with multiple data sets, including edge cases likely to cause problems (like a 1-element data set, for example).)
I have a hunch you have a bug, but can’t be sure because you haven’t given the actual program requirements. So I’m just going to assume your code isn’t broken (but I think it is!).
Now, the output could be slightly faster. Instead of:
cout << median[t/2].second << " " << median[t/2+1].first << endl;

You could do:
std::cout << median[t / 2].second << ' ' << median[(t / 2) + 1].first << '\n';

There are two things I changed (other than the spacing to make it more readable, and adding the std::):

The space is now a single character, rather than a string. In theory, this should be much faster, because a single character is a single character… while a string requires reading multiple characters with a loop and a conditional (to search for the NUL). (In reality, the compiler probably optimizes this for you anyway.)
Don’t use std::endl. std::endl prints a newline… and then flushes the stream, which is expensive. The stream is going to be flushed automatically anyway, so there’s no sense paying for it multiple times.

There’s one final trick I can think of that might gain you a bit more speed: std::ios::sync_with_stdio(false);. This is a high-level trick, but with a cost: if you do this, you cannot use any of the C stdio library. That means no printf(), no fopen(), none of that. What’s going on is that, by default, the C++ I/O streams will synchronize with the C stdio streams. This is a handy convenience that allows you to mix std::cout and printf(). BUT! That comes with a heavy cost. It slows down std::cin and std::cout a LOT. If you never use any C stdio stuff, then you can turn that synchronization off, and get a huge performance boost. It might make a difference for you, or it might not. Either way, just stick std::ios::sync_with_stdio(false); right after the beginning of main().
Okay, in summary, I think the reason you’re getting timeouts is all due to the way you’re reading the input. By not pre-allocating the vector, it is forced to constantly re-allocate and copy (move) all of its contents, over and over and over. Just be pre-allocating the vector with reserve(), you will spare yourself all that wastage by doing one single allocation, and avoiding all the copying (moving) entirely. Even better, you can just size the vector one time up front, and then read the data directly into its elements, so now you don’t even need to read into temporaries then copy into the vector.
Adding std::ios::sync_with_stdio(false); may help, too.
But most importantly: TEST YOUR CODE!!! I think you have a bug. You say your code works, so I assume you know what you’re doing… but I’m still skeptical. TEST YOUR CODE!!! See for yourself whether it really works the way you think it does. You just need simple tests, like this (using the Catch2 test framework):
TEST_CASE("dataset size is read correctly")
{
    auto const test_data = R"(
3
1 Alice
2 Bob
3 Carol
)";

    auto iss = std::istringstream{test_data};

    CHECK(read_dataset_size(iss) == 3);
}

TEST_CASE("simple data is read correctly")
{
    auto const test_data = R"(
3
1 Alice
2 Bob
3 Carol
)";

    auto iss = std::istringstream{test_data};

    // just assume this works and throw the result away, because it is tested
    // in the other test case
    [[maybe_unusued]] auto const data_size = read_dataset_size(iss);

    auto const data = read_data_pairs(iss, 3);

    CHECK(data.size() == 3);

    CHECK(data.at(0) == "Alice");
    CHECK(data.at(1) == "Bob");
    CHECK(data.at(2) == "Carol");
}

Then you just need a couple more tests to make sure sorting produces the right result, and that you print the right output for the median. After that, you could add more tests with different test data to test different potential problems. Get in the habit of testing your code. You may even find benefits with this very program….


How can I make this XML gallery snippet prettier?

There's a lot of duplication to get src, name, and so on. Simply use $.map:

var properties = $.map(["src", "name", "date", "desc"], function(id) {
  return xml.getElementsByTagName(id)[d].childNodes[0].nodeValue;
}

You can then use properties[0]. Not sure how I could return an object with the correct keys as simply as this. Maybe something like

var properties = {}
$.each(["src", "name", "date", "desc"], function(i, name) {
  properties[name] = xml.getElementsByTagName(name)[d].childNodes[0].nodeValue;
}

Don't forget any var
Create img using this less error-prone technique:

var img = $('<img>').attr({'alt': properties["name"], 'src': properties["src"]});


Range class to represent limited values, like HP, Stamina and so on

Problematic
Fill and Deplete are public, but don't call UpdateSlider, whereas Increment/Decrement do.

SetMax should reject values < 0 (0 could be allowed, for value forced to 0)

Design Style
There is a function in the Unity Mathf static class that does bounds checking Mathf.Clamp

C# has properties, while you can have the pair GetX/SetX they are preferred.

public int Value {
    get { return val; }
    set { val = Mathf.Clamp( value, 0, Max );
        UpdateSlider(); } }
public int Max {
    get { return max; }
    set { if ( value < 0 ) throw new ArgumentOutOfRangeException ("Max");
        max = value; } }

Consider
Increment and Decrement could be replaced by overriding + and -, as += and -= will use such overloads.


Expanding the region of interest of an image

The secret to performance is to choose the appropriate data structures which lay out the memory as raw arrays of bytes (or uint8_t values). This is done by creating cython typed memoryviews from numpy arrays or images loaded through PIL. This applies to the border list as well; that is, I create an array of (x, y) coordinates rather than a list of python tuples (which is slow, not contiguous in memory, and requires conversions to access the data from python to C or vice versa. Below is the preliminary code that I have so far, hope this helps.

from libc.stdint cimport *
from libc.string cimport *
cimport libc.math as c_math
import numpy as np
from PIL import Image

cpdef uint8_t[:, :, :] load_image(str image_path):
    cdef uint8_t[:, :, :] image_data
    image = Image.open(image_path).convert("RGBA")
    image_np = np.array(image)
    image_np.setflags(write=1)
    image_data = image_np
    return image_data

cpdef save_image(uint8_t[:, :, :] image_data, str image_path):
    image = Image.fromarray(np.array(image_data)).convert("RGBA")
    image.save(image_path)

cpdef border_enhance(uint8_t[:, :, :] image, uint8_t[:, :, :] mask):
    cdef:
        uint8_t[:, :, :] out
        uint8_t[:] color
        uint8_t[:, :] roi
        uint32_t[:, :] border
        size_t i, j, k
        size_t w = image.shape[0]
        size_t h = image.shape[1]
        size_t num_border
        size_t num_not_roi = 0
        float avg[4]
        size_t avg_count
        size_t x, y
        size_t sx, sy
        int a, b

    roi = np.zeros((w, h), dtype=np.uint8)
    border = np.zeros((w * h, 2), dtype=np.uint32)#assumes no product overflow
    out = image[:, :, :]

    #define ROI from mask; only white pixels are part of the mask?
    for i in range(w):
        for j in range(h):
            color = mask[i, j]
            if color[0] == 255 and color[1] == 255 and color[2] == 255 and color[3] == 255:
                roi[i, j] = True
            else:
                roi[i, j] = False
                num_not_roi += 1

    while num_not_roi:

        #Create border
        k = 0
        for i in range(w):
            for j in range(h):
                if not roi[i, j]:
                    #assumes edges wrap over
                    if roi[i-1, j] or roi[i+1, j] or roi[i, j-1] or roi[i, j+1]:
                        border[k, 0] = i
                        border[k, 1] = j
                        k += 1

        for i in range(k):
            x = border[i, 0]
            y = border[i, 1]
            avg_count = 0
            avg = [0, 0, 0, 0]
            for a in range(-1, 2):
                for b in range(-1, 2):
                    sx = x+a
                    sy = y+b
                    if roi[sx, sy]:
                        #print(np.array(image[sx, sy]))
                        avg[0] += image[sx, sy, 0]
                        avg[1] += image[sx, sy, 1]
                        avg[2] += image[sx, sy, 2]
                        avg[3] += image[sx, sy, 3]
                        avg_count += 1
            for a in range(4):
                avg[a] /= avg_count
                out[x, y, a] = <uint8_t>c_math.round(avg[a])

        for i in range(k):
            x = border[i, 0]
            y = border[i, 1]
            roi[x, y] = True
            num_not_roi -= 1
            #dprint(num_not_roi)

    save_image(out, "./images/out.png")

cdef:
    uint8_t[:, :, :] image
    uint8_t[:, :, :] mask
    size_t count

image = load_image("./images/image.png")
mask = load_image("./images/mask.png")
border_enhance(image, mask)

That being said, the results do not seem particularly correct. The intermediate border step generates the correct pixel results, but the final result is wrong. Here is my output for the out.png after the call to the border_enhance function: