It's not clear where this PrepareDataForBitTemplate(PropertyInfo) method is located. Is it code-behind? Whatever it is, if the goal is to bind a ComboBox with some enum values, I would much rather keep it standard - meaning the DataContext of the ComboBox is the ViewModel of the containing Window or UserControl:

public IEnumerable<SomeEnumType> ViewModelEnumValues
{
    get { return Enum.GetValues(typeof(SomeEnumType)).Cast<SomeEnumType>(); }
}

private SomeEnumType _selectedEnumValue;
public SomeEnumType SelectedEnumValue
{
    get { return _selectedEnumValue; }
    set { _selectedEnumValue = value; NotifyPropertyChanged(() => SelectedEnumValue); }
}

Before I move on to the corresponding XAML markup, a few observations:

The ViewModel implementation derives from some ViewModelBase abstract class which implements INotifyPropertyChanged and allows its derivatives to specify a property name in a strongly-typed way. I see your setter calls some OnPropertyChanged() method, but not how that method is able to notify the View that a specific property was changed.
The name Enum refers to a specific language construct. Calling something "Enum" when that something is not an enum is rather confusing.
I don't see why you're not using an actual enum when the values you're trying to load are basically "Yes" and "No".
EnumItemObject is an awful name, for several reasons:

It's not an object, it's a class - an object is an instance of a class.
It's not an enum item, it's essentially a ViewModel that exposes two properties - an int and a string.
It's not immediately apparent how this class relates to any type of enum.

Now, given that your ViewModel exposes the above SelectedEnumValue and ViewModelEnumValues properties (both bad/stub names), with a ValueConverter the XAML for the ComboBox would be as simple as this:

<ComboBox ItemSource="{Binding ViewModelEnumValues}"
          SelectedItem="{Binding SelectedEnumValue, Mode=TwoWay}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Border Style="{StaticResource ListItemBorder}"> <!-- just some border -->
                <StackPanel>
                    <Image Source="{Binding Value, Converter={StaticResource EnumValueIconConverter}}" />
                    <Label Content="{Binding Value, Converter={StaticResource EnumValueNameConverter}}" />
                </StackPanel>
            </Border>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

And the converters would look like this:

using resx = Project.Properties.Resources;

public class EnumValueToStringConverter : ConverterBase
{
    public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        SomeEnumType result;
        return Enum.TryParse(value.ToString(), out result)
                   ? resx.ResourceManager.GetString(promoType + "Caption")
                   : string.Empty;
    }
}

public class EnumValueToIconConverter : ConverterBase
{
    public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var result = string.Empty;
        var typedValue = value As SomeEnumType;
        if (typedValue != null)
        {
            switch(typedValue)
            {
                case SomeEnumType.EnumValue1:
                    result = "images/image-for-value1.png";
                    break;
                case SomeEnumType.EnumValue2:
                    result = "images/image-for-value2.png";
                    break;
            }
        }

        return new BitmapImage(new Uri("/project.namespace;component/" + result, UriKind.Relative));
    }
}

Of course this is overkill if all you want is the enum names in your dropdown list - but I tend to define a DataTemplate for just about everything (and I think I have a tendency to abuse converters, too).

If all you need is to display an enum value directly in the UI, then this will suffice:

public IEnumerable<string> ViewModelEnumNames
{
    get { return Enum.GetNames(typeof(SomeEnumType)).ToList(); }
}

private string _selectedEnumName;
public string SelectedEnumName
{
    get { return _selectedEnumName; }
    set { _selectedEnumName = value; NotifyPropertyChanged(() => SelectedEnumName); }
}

<ComboBox ItemSource="{Binding ViewModelEnumNames}"
          SelectedItem="{Binding SelectedEnumName, Mode=TwoWay}">


Building tree from edges puzzle with performance requirement

Would rather make this a comment, but I need 50 reputation for that, so:
It became quite an answer apparently.

I find given code quite confusing. From what I am picking up, it does excessive searching/iteration where it is not necessary. I'd propose to make a refactoring, creating a class representing your tree. Then you can cleanely implement your requirements. E.g.:

public class Node {

    private final int id;
    private final List<Node> children;

    public Node(final int id) {
        this.id = id;
        this.children = new ArrayList<>();
    }

    public void addChild(final Node child) {
        children.add(child);
    }
}

Now you can add some methods directly expressing your requirements:

    public int graphValue() {
        return nodeValue() + children.stream().collect(summingInt(Node::graphValue));
    }

    public int nodeValue() {
        return 1 + children.size() + children.stream().collect(summingInt(Node::nodeValue));
    }

When creating your tree, you could use something like a HashMap so you can retrieve an already existing node by id in constant time. Perhaps you might need more optimizations.

Some other comments:

Try to avoid using the Stack class: see Stack JavaDoc
Close the scanner as soon as possible; it is also AutoCloseable, so you can use try-with-resources: see try-with-resources documentation
Prefer !list.isEmpty() over list.size() > 0, it is more idiomatic and potentially more efficient. Some implementations might traverse all elements to calculate the size, but as soon as there is an element it is of course not empty.
You created a Tuple class, which is a generic thing. But the implementation is not generic. I'd give it a more specific and telling name. (or possibly make it truly generic)
The amount of +'s in values[currentNode.parent] += ++values[currentNode.id] + 1 is too damn high :D


The second one is definitely better. In the first one, it's really hard to see that the div is actually inside the if.

Personally, I would build the string completely in PHP, and then echo it, instead of switching in and out of the HTML context. This will avoid the opening and closing PHP tags being littered around your code:

$html = "";
if ($this->product->getType() == Product_Types::BOOK) {
    $html += "<div>" . $this->product->getAuthor() . "</div>";
}
echo $html;


Opinions on my Command pattern design - is it extensible?

I think you've added an unnecessary layer of abstraction here.

To me, populateCommandList looks completely unnecessary.  You are converting a list of commands in one format (character string) into another format (an array of Command objects).  Then, presumably, executeCommands just executes all of those command objects in order.  This wastes time and memory by creating a bunch of unnecessary objects.

Why not just have executeCommands take the string directly, and execute the appropriate command for each character that it encounters?

In other words, I would have something like this in executeCommands:

   for(int i=0; i<cmds.length(); i++){
       char cmd = cmds.charAt(i);
         switch(cmd){
            case 'F':
                robot.move(FORWARD,1);
                break;
            case 'R':
                robot.turn(RIGHT);
                break;
            case 'L':
                robot.turn(LEFT);
                break;
        }
   }

Either way looks equally extensible to me.  Either way you will have a switch statement somewhere that defines what commands are possible, and that is what you have to change in order to add a new command.


Find the most common number in an array of numbers

For small arrays as input your script's performance is very good. Let me show you a different approach which might especially improve readability and might also increase performance for larger inputs and multiple runs.

.reduce()

Instead of iterating through the elements manually, I've used Array.prototype.reduce():

  The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

The function has two steps now which both use reduce():

Reduce the input into an object that holds each number and its count as key/value-pairs.
Reduce this object to find the key with the highest value.

function findMode(numbers) {
    let counted = numbers.reduce((acc, curr) => {
        if (curr in acc) {
            acc[curr]++;
        } else {
            acc[curr] = 1;
        }

        return acc;
    }, {});

    let mode = Object.keys(counted).reduce((a, b) => counted[a] > counted[b] ? a : b);

    return mode;
}

Performance

In the comments we had a lot of discussion about performance about this and other solutions.

One requested improvement was to calculate the mode directly in the first reduce call. It could look like this:

function findModeAlternative(numbers) {
    let max = 0;
    let mode = null;
    let counted = numbers.reduce((acc, curr) => {
        if (curr in acc) {
            acc[curr]++;
        } else {
            acc[curr] = 1;
        }

        if (max < acc[curr]) {
            max = acc[curr];
            mode = curr;
        }

        return acc;
    }, {});

    return mode;
}

Unfortunately it didn't improve performance in Chrome and Firefox.

Then Blindman67 suggested the naive approach with this solution:

function findCommon(arr) {
    var max = 1,
        m = [],
        val = arr[0],
        i, x;

    for(i = 0; i < arr.length; i ++) {
        x = arr[i]
        if (m[x]) {
            ++m[x] > max && (max = m[i], val = x);
        } else {
            m[x] = 1;
        }
    } return val;
}

Which will increase performance significantly in Firefox, but performs about the same in Chrome. Keep in mind, that functions like reduce, map etc. come with some overhead.

Finally the approach using map in Gerrit0's answer also increases the performance drastically opposed to the original.

Test

I've created a test, so you can check the performance of each variant yourself. The test uses two different arrays with ca. 500 elements each and runs every function 100000 times:

test array A is kind of mixed
test array B contains mostly one number with a few exceptions

These are the results from Chrome 61 on macOS:

array A "findMode": 1000ms
array B "findMode": 950ms
array A "findModeAlternative": 1200 ms
array B "findModeAlternative": 1100 ms
array A "findCommon": 930 ms
array B "findCommon": 960 ms
array A "mostCommonNumber": 1700 ms
array B "mostCommonNumber": 1300 ms
array A "searchMostCommonNumber": 12697 ms
array B "searchMostCommonNumber": 13400 ms

Try it yourself

Of course you can tweak the test and try different inputs etc.

The functions's name

As this is called mode in statistics, you could use a shorter function name like findMode()

Unfortunately this doesn't improve performance. This is just a personal preference

I only included the ES6 version of the script in this answer. I didn't add the check whether the array is an array and not empty, as this will be added when compiling from TypeScript to JavaScript


Scoping

All the static fields of your class can be made into local variables. This gives them a smaller scope. Always give variables the smallest possible scope.
When you do this you'll notice userString and al are already defined as a local variable.
al should be declared as a List<String>, in fact you'll see that the code works fine with the List returned by Arrays.asList().

Naming

Use meaningful names instead of abbreviations for names : al, sc, even temp don't convey anything.

Algorithm

Testing whether the first letter of a String is a vowel shouldn't require you to uppercase the entire String. You shouldn't even be making a second String (tester).
It's easier to make a String of all vowels (upper and lower case) and use indexOf() on that string with the character you want to test.

The while(true) loop is bogus too. I had to look for the exit condition. Make it explicit.

You remember to close the Scanner, but do it in a finally block, so a possible Exception doesn't bypass the closing. For extra points use a try-with-resources structure (see my refactored example).

Wait, remember I said the code would work fine with the result of Arrays.asList()? It will, but you don't even need a list to loop over an array. Just use an advanced for loop.

for (String temp : userString.split("\\s")) {
    ...
}

latinString should be a StringBuilder, as it's mostly used to build the resulting String.

Use helper methods to explain what you're doing or to extract repeated code.

Here's my refactored version :

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) { // try with resource will ensure the Scanner gets closed.
        String userString = getUserInput(scanner);
        while (!userString.isEmpty()) {
            System.out.println(buildLatinString(userString));
            userString = getUserInput(scanner);
        }
    }
}

private static String buildLatinString(String userString) {
    StringBuilder latinString = new StringBuilder();
    for (String word : userString.split("\\s")) {
        latinizeWord(latinString, word);
    }
    return latinString.toString();
}

private static void latinizeWord(StringBuilder latinString, String word) {
    if (startsWithVowel(word)) {
        latinString.append(word).append("ay ");
    } else {
        latinString.append(word.substring(1)).append(word.charAt(0)).append("ay ");
    }
}

private static String getUserInput(Scanner scanner) {
    System.out.print("Enter a string to be converted into Pig Latin. To stop, enter a blank input: ");
    return scanner.nextLine();
}

private static boolean startsWithVowel(String word) {
    return "AEIOUaeiou".indexOf(word.charAt(0)) != -1;
}


Should I put python3 argparse filetype objects in a contextlib stack?

I've expanded on your example, and explored some alternatives.

Observations:

your def argparse shadowed the module; I changed its name.
using FileType to process the argparse input results in unclosed file warnings.  It opens the files, but does not close them.  So for multiple files, it is not right tool.
simpler just runs the FileInput without a context.  FileInput handles stdin itself.  It does not close stdin when done.  It closes other files, even when processing is interrupted.
main with the context, closes stdin.
I wrote a process_arguments with a break to test whether files are closed. FileInput properly closes the files, with or without the context.
FileInput also can read sys.argv, so you don't actually need argparse in this simple case.  See simplest.

The script:

import argparse
import contextlib
import fileinput
import sys

files = set()

def filetype():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', nargs='*',type=argparse.FileType('r'))
    args = parser.parse_args()
    print(args)
    # gives ResourceWarning: unclosed file

def simpler():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', nargs='*')
    args = parser.parse_args()
    input = fileinput.FileInput(
        files=args.input)
    process_arguments(input)

def simplest():
    # uses sys.argv[1:]
    process_arguments(fileinput.input())

def main():
    with contextlib.ExitStack() as stack:
        input = myparse(stack)
        process_arguments(input)

def myparse(stack):
    # change name so as to not shadow the module
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', default=[sys.stdin], nargs='+')
    d_args = vars(parser.parse_args())
    print('d_args',d_args)
    if d_args['input'] != [sys.stdin]:
        input = stack.enter_context(fileinput.FileInput(
            files=d_args['input']))
    else:
        input = stack.enter_context(sys.stdin)
    return input

def process_arguments(input):
    try:
        print(input, input._files)
    except AttributeError as e:
        # error if input is not a FileInput
        print(e)
        return
    for l in input:
        print(input.filename(), input.fileno(), input.lineno(), input.filelineno())
        if not input.isstdin():
            files.add(input._file)
        if input.lineno()>15:
            break

if __name__=="__main__":
    # simplest()
    simpler()
    # main()
    if files:
        print([(f.name, f.closed) for f in files])
    print('is stdin closed?', sys.stdin.closed)

This function is a simpler example (without fileinput) of processing a list of files with a proper context.  I learned about this use of stdin.fileno() from another argparse bug issue, http://bugs.python.org/issue14156.

def other():
    # example with simple 'with open...'
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', nargs='*', default=[sys.stdin])
    args = parser.parse_args()
    for file in args.input:
        if file is sys.stdin:
            # open(fileno) does not close the underlying file
            file = file.fileno()
        with open(file) as f:
            lines = f.readlines()
            print(f.name, f.fileno(), len(lines))


This would probably be better on DBA
You can use a CTE
An index on fork_id should help

with cte as
( SELECT ROW_NUMBER() OVER (PARTITION BY [fork_id] ORDER BY ID DESC) AS RowNumber
  FROM [tableName]
)
delete from cte
WHERE RowNumber > 1

Optimize

select * from cte
WHERE RowNumber > 1

If that is fast it is volume thing and you could delete in batches


Instead of three nested for loops, you can use itertools to enumerate combinations. Also, I would personally prefer to keep a count in a dictionary, as opposed to storing the same numbers over and over.

import itertools

cube_counts = {}

for i, j, k in itertools.combinations(range(1, 500), 3):
    cube = i**3 + j**3 + k**3
    cube_counts[cube] = cube_counts.get(cube, 0) + 1

print(min([cube for cube, count in cube_counts.items() if count >= 12]))


Regarding the API:

consider using std::string const & arguments instead of char const*. They are less error prone.
your configuration uses a std::ifstream input that is only used in the constructor; the file should not be a member of the configuration.
the code to read the configuration from a stream should (probably) be put into an std::istream& operator>>(std::istream&, configuration&);. This would:

integrate well with existing APIs on streams
abstract away the concrete type of the stream (your configuration would be able to read a string in memory - using a std::istringstream just as easily as a file on the disk)
separate concerns
allow you to test the configuration class in separation

Consider this public API instead:

class configuration final
{
public:
    using storage_type = std::map<std::string,std::string>;

    /// \b instantiate from set of values (that can be empty)
    explicit configuration(storage_type values = {}) noexcept;

    ///. \note default destructor is enough to have - so don't declare it here

    /// \return a const reference instead of an object
    ///
    /// we are not modifying the class so we can be const and noexcept
    const std::string&
    get_value(const std::string& key) const noexcept
    {
        using namespace std::string_literals;
        try
        {
            return values.at(key);
        }
        catch(std::out_of_bounds const&)
        {
            static const auto empty = ""_s;
            return empty;
        }
    }

private:
    storage_type data_;
};

Regarding the implementation (general notes):

try
{
    file.open(std::string(path), std::ios::in);

consider instantiating a file with a file name (opening directly from the construction instead of explicitly calling open)

if (file.is_open())

this is bad: the file could be open, but the stream could be in an invalid state; when you want to check on a stream's state for reading, simply rely on it's boolean conversion (use if(file) instead).
this could be a simple assignment: values.insert_or_assign(key, value);: values[key] = value;
logging messages in case of errors is very very bad:

it adds a dependency to a logging module (every time you want to reuse the class somewhere else, you will also have to add the logging dependencies)
it does too much: when you want to reuse the code you will want to do that for reading a configuration, not for logging. Logging should not be in here at all.
it gives you no possibility for checking for an error in client code, unless your logging framework has extra functionality to give you the last of it's error messages and you want to parse those (and all of a sudden you are solving the x-y problem)
you should either catch the errors here (like you already do) and throw a higher abstraction exception instead, or simply remove the try-catch block and allow client code to catch exceptions - or not. One of the best features of exceptions is that you can choose not to handle anything at the current level and you have to write no explicit code for that.

Final reading code for this:

std::istream& operator>>(std::istream& in, configuration& c)
{
    auto storage = storage_type{};
    auto line = std::string{};
    while(getline(in, line))
    {
        if(line.empty())
            continue;
        auto split = line.find_first_of("#=");
        if (split == std::string::npos)
            throw std::runtime_error{ "bad data format" };

        // strip comment
        if(line[split] == '#')
            line = line.substr(0, split);
        ...
    }

    c = configuration{ std::move(storage) };
    return in;
}

Edit: here's some client code, that is possible due to the separation of the parsing and the construction:

#include <sstream>
#include <fstream>

// test code
std::istringstream test_input{ R"(
# Program configuration

network.port=30000 # The port the server uses
network.ip=127.0.0.1 # The IP the server uses)"};

auto c1 = configuration{};
assert(test_input >> c1);

// useful code:
std::ifstream in{ "file.cnf" };
auto c2 = configuration{};
if!(in >> c2)
    std::cerr << "Error reading file.cnf\n";


How to attach click to header child without reusing the code?

Without knowing what your elements are or the html around them, i would say just combine the id's into one selector and use $(this).find in the click function. Example:

$("#id1, #id2, #id3").find(':header').click(function(){
 $(this).find('p').slideToggle('slow')l
});


Selecting three stylesheets in a specific order

I have a sneaking suspicion that this might should do an IN clause and then handle the sorting in code, but if you want to keep it in SQL, you can do:

SELECT *
  FROM Stylesheets
  WHERE
    ID IN (14, 1, 5)
  ORDER BY ID = 14, ID = 1, ID = 5;

Don't use backticks when you don't have to by the way. They're extra typing, and they pretty much kill portability (for no reason -- you'll eventually have to kill portability for some reason or other).

Also, I'm not a fan of ALL_CAPS identifiers. They blend in too closely with keywords which tend to be all caps ("ID IN" looks pretty odd for example).

Perhaps your actual use of this is different, but if 14, 1, and 5 are actually hard coded, that's a bit fragile. It would be better to assign them to some kind of constant and then use that in the query. Or, if you wanted to go a step farther, you could even assign them some kind of code in addition to an int primary key ('reset', 'layout', 'colors'), then not only are they less likely to change (what if they get inserted in a different order next time? suddenly all your IDs are wrong), they're also easier to remember, and the values of your constants will have more meaning.


Shuffling sections of an ordered list based on tuple values

Both branches of the if statement have the line:

temp.append(i)

This duplication could be avoided.
The variable temp could have a better name, for example group or current_group.
i[1] is evaluated twice.
The variable name i is normally used for an index, but in this case it is an element of the list, so it could have a better name.
These lines appear twice:

random.shuffle(temp)
new_pieces_needed +=  temp

This duplication could be avoided by postponing the shuffles until the groups have been found, like this:

# Group pieces_needed according to their frequency.
groups = []
current_freq = object()
for piece in pieces_needed:
    freq = piece[1]
    if freq != current_freq:
        groups.append([])
        current_freq = freq
    groups[-1].append(piece)

# Randomly shuffle each group.
for group in groups:
    random.shuffle(group)

# Concatenate the shuffled groups.
new_pieces_needed = [piece for group in groups for piece in group]

There is something arbitrary about the use of "pieces" and "frequency" and piece[1]. The same general algorithm would work for any kind of data, not just pieces. So I think the code would be clearer if we generalized it like this, taking an arbitrary iterable and an optional key function:

def shuffle_groups(iterable, key=None):
    """Group the iterable (using the key function if supplied), randomly
    shuffle each group, and return the concatenation of the shuffled
    groups.

    """

and then we can shuffle the pieces by passing operator.itemgetter(1) for the key argument:

from operator import itemgetter
new_pieces_needed = shuffle_groups(pieces_needed, key=itemgetter(1))

The grouping logic can be delegated to itertools.groupby and the concatenation to itertools.chain:

from itertools import chain, groupby
from random import shuffle

def shuffle_groups(iterable, key=None):
    """Group the iterable (using the key function if supplied), randomly
    shuffle each group, and return the concatenation of the shuffled
    groups.

    """
    groups = [list(group) for _, group in groupby(iterable, key)]
    for group in groups:
        shuffle(group)
    return list(chain(*groups))


An implementation of parallel workers in Ruby

Where not to lock
I'm not sure why you decided to lock on @exit_state and @idle_state, as they don't seem to have any potential to cause any race condition (except for maybe when the manager calls thread.shut_down, and even then - all that would happen is that you will 'lose' a round of one second - hardly catastrophic).

Where to lock
When you want to concurrently work on a queue - you should synchronize your work with the queue (in this case @queue.empty? and @queue.pop), which you don't do...

How to lock
You should also note the @queue.pop is implicitly @queue.pop(false) which means that if the queue is empty, it will block until a new message arrives, which is probably not what you want, since you can't be sure that it is not empty (between while @queue.empty? to job = @queue.pop another worker might have 'hijacked' your message).

Since Queue is thread-safe, you could write your worker like this:

class Worker

  def initialize(queue)
    @thread = Thread.new { poll(queue) }
  end

  def poll(queue)
    until done?
      begin
        queue.pop(true).call
      rescue ThreadError
        # queue was empty
        sleep 1
      end
    end
    exit 0
  end

  def done?
    @done
  end

  def shut_down
    @done = true
  end
end


When there're comments in the code that tell what it does, it usually indicates that the following piece of code should be a separate function with a meaningful name. I'd create a separate function that the positions of the words to be modified (and it something like get_indices_to_modify) and a separate function that checks if a word already has a label.
You can make your code more readable the tuples from the indices list:

for modification_range, label in indices looks better than

for ind in indices: # Do something with ind[0] and ind[1]
You can also use the += operator in this line: input_sentence[n] += ind[1]
The names n and i are kind of confusing in your code. i normally stands for a counter while n stands for the number of elements. For instance, I'd change n and i in the first line of your polarize function to idx and word (when i is not the counter, the thing gets pretty confusing).
Assuming that it's python 2, you can save some space by using xrange instead of range. It can a have a serious impact if the window_length gets really big.
What is the point of creating the outputsentence variable just to return it? Why not return the input_sentence directly?
The polarize function actually changes the input_sentence. Your documentation doesn't say anything about it. This could lead to unexpected results for the users of your code. You should either make a copy and not change the input, or document the fact the input is changed explicitly.
Instead of printing the return value of the function to the standard output (and checking that it's correct by looking at it), I'd recommend to write unit-tests. This way, you would be able to check that code remains correct after your change it automatically (moreover, it's quite easy to overlook something when you just look at the output with your eyes).


You've got a class with only two classmethods and one staticmethod. One classmethod does not use the class argument, the other one refers to a static method. Hence none of the class' methods use either the class or one of its instances. Thus, you do not require a class at all:

def encode_basic(usr, pwd):
    token = base64_encode(f"{usr}:{pwd}")
    return f'Basic {token}'

def encode_bearer(token):
    return f'Bearer {token}'

def base64_encode(token):
    return b64encode(token.encode('ascii')).decode('ascii')

Also consider adding docstrings to the functions, that explain how they are supposed to be used. Without knowlege of your program's context it is hard to tell, why the strings are being formatted in the respective ways and why one string needs ASCII encoding.


A function that reverses a string of characters

Naming

The mix of Spanish and English is disconcerting: cad vs. s.  The use of cadenita for the reversed string also seems odd, since the reversed string is the same length as the original.  svol is even weirder, as s appears to be short for "string" (English) and vol, I'm guessing, is short for "volvió" (Spanish).  Keep in mind that the function's name, reverse, is English.  (Personally, I recommend using English everywhere.)

i is conventionally used as an iteration dummy variable rather than as a length parameter.  If you mean length, then call the parameter len or length.  Using size_t instead of int would also be a good hint to its purpose.

Function declaration

Does reverse() operate on NUL-terminated strings or on a byte array of a specified length?  You should make up your mind, since bugs tend to occur when the two conventions get mixed up.  If the function takes a length, then it shouldn't look for '\0'.  Alternatively, if looks for '\0', then it shouldn't accept a length parameter.

Since allocating memory is an annoyance in C, I would consider it idiomatic for the reverse() function to operate on the string in place rather than making a copy.  If the caller wants to keep the original string intact, then make it the caller's responsibility to duplicate the string first.

It is conventional to place main() last, so that you don't need to make forward declarations of the functions that it calls.

Input

I don't recommend reading a character at a time using getchar().  Character-at-a-time I/O is less efficient.  More importantly, using a more appropriate function to read an entire line can simplify your code.  Using getline(), for example, makes your intentions clearer, and it avoids the possibility of a buffer overflow.

#include <stdio.h>

char *reverse(char *s, size_t len) {
    for (int i = 0, j = len - 1; i < j; i++, j--) {
        char swap = s[i];
        s[i] = s[j];
        s[j] = swap;
    }
    return s;
}

int main() {
    char *line = NULL;
    size_t linecap = 0;
    ssize_t linelen;
    while ((linelen = getline(&line, &linecap, stdin)) > 0) {
        if (line[linelen - 1] == '\n') {
            line[--linelen] = '\0';
        }
        puts(reverse(line, linelen));
    }
}


np.random.choice takes an additional argument specifying how many elements should be chosen. You can also use the built-in module string to save having to spell out the alphabet:

import numpy as np
import string

ALPHABET = np.array(list(string.ascii_lowercase + ' '))

def generate_guess(sentence):
    return np.random.choice(ALPHABET, size=len(sentence))

I also made the alphabet a constant to avoid having to build it again and again.

Your code was not faster because you did not take advantage of the vector-wise operations of numpy. Neither your starting array, the alphabet, nor your output array were actual numpy arrays.


This second version doesn't have to pull in extra packages…

Data.Bifunctor is part of base since 4.8.0.0, so I'm not sure where you get the "extra packages" from. Yes, Data.Bifunctor was originally in the bifunctors package, but it was transferred into base in 2015.

However, compared to the extras version, your variant is easy to read, as the [x | res] … [x | not res] slightly obfuscates the result. I'd probably bind map fst, but that's personal preference.

  and doesn't create intermediate lists

It generates a lot of intermediate lists. I haven't checked yet, but as [x|res]++as depends on res cannot get simplified to x:as or as at compile time by rules, so it might create a thunk […]++as. In the end, you have \$\mathcal O(n) \$ additional \$\mathcal O(1)\$-sized lists.

Since this is a hidden implementation detail, I don't really like Neil's solution too much. Something along

partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM f [] = return ([], [])
partitionM f (x:xs) = do
    res <- f x
    (as,bs) <- partitionM f xs
    return $ if res then (x : as,     bs)
                    else (    as, x : bs)

would at least support the optimizer and get rid of those intermediate lists, but is even more verbose. Your variant uses an additional list, sure, but it's easier to read and to understand IMHO.


Usage of Decorator pattern in baking program

You missed a somewhat crucial point in the pattern: the decorator must present the exact same interface as the decorated object.

In other words, any IBake decorator should also implement the IBake interface, so that it's possible to decorate a cake with both cream and cherries!

Here's your CreamDecorator, fixed:

class CreamDecorator : IBake
    {
        public static readonly decimal ExtraCharge = 50;
        private readonly IBake _decorated;

        public CreamDecorator(IBake decorated)
        {
            _decorated = decorated;
        }

        public string Name
        {
            get
            {
                var name = _decorated.Name;
                return name + " +Cream";
            }
        }

        public double Price
        {
            get
            {
                var price = _decorated.Price;
                return price + ExtraCharge;
            }
        }
    }

The idea is that you call the decorated code, and then decorate the result before returning it.

Also since we're talking about money, double is a bad choice of a type for Price. IBake should look like this:

public interface IBake
{
    string Name { get; }
    decimal Price { get; }
}

As for the wrong price being output, there's your bug:

public string GetCakeCost()
{
    return "Normal cake is:" + m_Price + "and Tax is: " + (this.m_Price * 0.08f);
}

The base class doesn't know whether it's decorated or not, and shouldn't make that assumption, it's just another implementation of the IBake interface:

public static readonly decimal TaxRate = 0.08;

public string GetCakeCost()
{
    return string.Format("Price: {0:C2}\nTax: {1:C2}\nTotal: {2:C2}", Price, Price * TaxRate, Price * (1 + TaxRate));
}

Now that looks cleaner, but it's also flawed: Cost is a bad/confusing term, should be Price, SellingPrice, or TotalPrice - Cost could refer to what the bakery is paying to produce the cake, and would be used to calculate profits and gross margins. The tax rate shouldn't be hard-coded into a method that returns a string either.

Another problem is that the decorator would need to override the Price property for the base class to return the correct figure, and that's not how decorators work.

One solution could be to include a TaxAmount member in the IBake interface, and a separate member to return a string representation of the cake's price, which I'd call PriceDetails:

public interface IBake
{
    string Name { get; }
    decimal Price { get; }
    decimal TaxAmount { get; }
    string PriceDetails { get; }
}

The base cake could do it like this:

public decimal TaxAmount
{
    get { return TaxRate * Price; }
}

public string PriceDetails
{
    get { return return string.Format("{0}\nPrice: {1:C2}\nTax: {2:C2}\nTotal: {3:C2}", Name, Price, TaxAmount, Price + TaxAmount); }
}

And then the decorators have nothing to change about these two, so they just call the decorated code:

public static readonly decimal ExtraCharge = 50;

public decimal TaxAmount
{
    get { return _decorated.TaxAmount; }
}

public string PriceDetails
{
    get { return _decorated.PriceDetails; } // add an "Extra" in the detail line?
}

At the end of the day, what you want to ensure is that the client code is always calling into the decorated instance - that's why it's important for decorators to present the same interface as the decorated type, and for all members to be accessed by the client code via that interface.

Here's what your client code could look like in a production application:

public class CakeOrderLine
{
    private readonly IBake _cake;
    public CakeOrderLine(IBake cake)
    {
        _cake = cake;
    }

    public override string ToString()
    {
        return _cake.PriceDetails;
    }
}

An "order line" is injected with an IBake instance, but has no clue how/if it's decorated, it treats all implementations of IBake equally.

Your console client could do this:

var cake = new BakeBase();
var cherryCake = new CherryDecorator(cake);
var creamCherryCake = new CreamDecorator(cherryCake);

And then this:

Console.Write("{0:C2}\n", cake.PriceDetails);
Console.Write("{0:C2}\n", cherryCake.PriceDetails);
Console.Write("{0:C2}\n", creamCherryCake.PriceDetails);

Should output something like this, assuming Price is implemented as above:

Cake Base
Price: $200.00
Tax: $16.00
Total: $216.00

Cake Base +Cherry
Price: $250.00
Tax: $20.00
Total: $270.00

Cake Base +Cherry +Cream
Price: $350.00
Tax: $28.00
Total: $378.00

I'm not a UML-ist, I think this fairly represents the concept:

See the full code here.


Have you tried something like this (?):

MemoryStream memoryStream = new MemoryStream(MessageBody.SelectMany(mb => mb.Value).ToArray());


Couple of points:

Utilize Dependency Injection for your constructor to loosely couple it's dependencies.
In OOP, functions are not used that often, but methods. user_logged_in() should reside in some sort of User authentication handler (Single Responsibility Principle). Where you could do something like $usrAuthService->isLoggedIn().
Give your classes meaningful names. Generic and Conn are really bad names. What is a "Generic" class? What is "Conn"? Connection? Connection of what? In a month when you come back to visit your code, you will not understand at a glance what is happening.
A constructor's primary purpose is to initialize the object.

$user->username doesn't work because your class properties are private.

You must realize that there are many different design patterns out there that programmers may adapt for their systems. User systems that have entity classes like User are more domain oriented (DDD).


Random timestamp within last 3 relative years

As Darren H has said in the comments, just generate a random number between 0 and nanoseconds in three years, and subtract from time.Now():

const threeYears = 3 * 365 * 24 * time.Hour

func main() {
    rand.Seed(time.Now().UnixNano())
    d := time.Duration(rand.Int63n(int64(threeYears)))
    fmt.Println(time.Now().Add(-d))
}


The CPU load doesn't look so bad. On my 2011 MBP the linked example runs easily at 60fps, taking between 0.4 and 0.85ms (of the 16.6ms available for that framerate) to run the animation frame callback. No sweat.

As for code style; it's generally pretty clear and easy to follow, though I would suggest  name-spacing your state variables and methods instead of using global variables. This is generally considered better practice, it's safer, can in theory improve performance and make the code easier to read. For example, you could do something like:

FlyingBalls = {
    colors: [...],
    dots: [],
    maxDots: [],
    init: function initDots(canvasId) { this.canvas = ... }
    create: function createDots() { ... },
    update: function updateDots() { ... }
}

Or use a constructor like:

function FlyingBalls(canvasId) {
    var canvas,
        ctx,
        ...;

    function createDots() { ... }

    function updateDots() { ... }

    // init code here
    canvas = document.getElementById(canvasId);
    ...
}


Some notes:

Use 2-space indentation.
Move all the logic to the model.
DB deletes can also fail.
No need for self.
If you use object instead of object_id as argument, code is usually more declarative.
In case of error, you are performing a double render.

I'd write:

class LikesController < ApplicationController
  def create
    post = Post.find(params[:post_id])

    if current_user.toggle_like(post)
      render(json: {status: "success", likes: post.likes.count})
    else
      render(json: {status: "error"}, status: :unprocessable_entity)
    end
  end
end

class User < ActiveRecord::Model
  # Toggle like for post. Returns boolean with the status of the operation.
  def toggle_like(post)
    likes_for_post = likes.where(post_id: post.id)

    if likes_for_post.exists?
      likes_for_post.destroy_all.all?(&:destroyed?)
    else
      likes.new(post: post).save
    end
  end
end


Rotate an array to the right by a given number of steps

In place solution

Jon Bentley "Programming Pearls" (1986) has this task as one of problems.

The recommended solution, instead of either:

doing K 1-element rotations, using 1 temporary variable, with O(K N) time, which is slow
using K-element temporary array, with O(N) time, which is wasteful... but only if there is requirement of doing it in place (and not returning copy, i.e. new N-element array)

is the Aha! solution of using reversals, with the following pseudocode

reverse(A, 0, K-1);
reverse(A, K, A.length()-1);
reverse(A, 0, A.length()-1);

assuming that reverse(A, I, J) operation reverses elements of array A from I-th element to J-th element, inclusive, that is, if $$A=\{a_0,a_1,...,a_i,a_{i+1}...,a_j,a_{j+1}...,a_{N-1}\}$$ then $$\text{reverse}(A, i,j)=\{a_0,a_1,...,a_j,...,a_{i+1},a_i,a_{j+1},...,a_{N-1}\}$$

  For example, given array A = [3, 8, 9, 7, 6] and K = 3,
  the function should return [9, 7, 6, 3, 8].

Steps, corrected for the account of different meaning for K, namely whether it is number of elements to move from left to right ("Programming Pearls"), or from right to left (an example):

[3, 8,| 9, 7, 6] - original array
[8, 3,| 9, 7, 6] - reversed first part
[8, 3,| 6, 7, 9] - also reversed second part
[9, 7, 6,| 3, 8] - the solution

The idea by @forsvarir, namely:

  You're currently rotating the array by 1 over and over again. Instead, think about where each element will end up at the end of N rotations. It's end position should be something like (startPos + numberOfRotations) modulus array size.

is another possible algorithm for an in-place rotation in "Programming Pearls". It can be written in an elegant way, but coming up with correct implementation is a bit more tricky. Though it does twice less operations than the reverse based one, each operation is more complex; also it doesn't play well when N is large enough that swap must be used (nowadays probably not a problem).

Return copy solution

If you are returning a copy, you don't need a temporary K-element array. The solution is to create a result by copying appropriate parts.

In pseudocode (and in programming languages where you can do whole (sub)array copy) it would look like this:

Anew = allocate(N)
Anew[0:K-1] = A[N-K-1:N-1]
Anew[K:N-1] = A[0:N-K-1]

Here I assume that K means number of elements from the end to move to beginning, and that A[0:K-1] means array slice (a(1:K) in Fortran).

Note: I have not checked this solution - beware off-by-one errors here.


Extract thoughput value from JMeter log file

You are using here four different tools: grep, tail, awk and cut to do the following:

select lines
get the last one
print a given field of that one
extract the integer part of that field

This is clear and it works. However, using four processes is a bit of overkill, since all of these can be performed one-handedly via awk:

awk '/meter.reporters.Summariser: summary/ {rec=$12} END{printf "%d\n", rec}' file

/meter.reporters.Summariser: summary/ {rec=$12}
When reading from the file, /pattern/ will match those lines containing the "pattern". If this happens, the action within {} is performed. In this case, it consists in storing the 12th field.
But wait, weren't we looking for the last line in which this occurs? Yes, and this is exactly what we are doing by overwriting rec every time the pattern happens: last time it is written, it will store the definitive result.
END{printf "%d\n", rec}
Once all lines have been processed, red will have the desired value on the form 3.4/s. We just want the 3 to appear, so we could do some string triming similar to the one you did with cut. However, we can also use awk's printf() to use Format-Control Letters to just print the integer part of it. This will also print 0 if rec is empty:

$ awk 'BEGIN {printf "%s\n", "3.4/s"}'
3.4/s
$ awk 'BEGIN {printf "%d\n", "3.4/s"}'
3
$ awk 'BEGIN {printf "%d\n", ""}'
0

Of course, you could also add the threshold logic in the script.


Nested stream to check the truth condition at first instance

If you don't need the Car, you can also flatMap to have the features and then distinct them before searching.

cars.stream()
  .flatMap(car -> car.getAmounts().stream())
  .map(Feature::getType)
  .distinct() // As spotted by @Pimgd in the comments this is useless
  .anyMatch(lookForTypes::contains);

But if you want to improve the readability of your code you should better consider to move a part of this "logic" into your objects :

cars.stream()
  .anyMatch(car -> car.hasAtLeastOneFeature(lookForTypes);

// ...

Car {
  boolean hasAtLeastOneFeature(List<Integer> features) {
    // Note that I renamed getAmounts to getFeatures
    return getFeatures().stream()
      .anyMatch(feature -> features.contains(feature.getType());
  }
}


You should definitely check out how properties can make your code shorter, by adding some standard setter/getter

@interface Watch: NSObject

@property int hours;
@property int minutes;
-(void) printTime;

@end

@implementation Watch

-(void) printTime
{
    NSLog(@"Time is %i:%i", _hours, _minutes);
}

@end

Also the naming convention of a getter is the property name

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

    @autoreleasepool
    {
        Watch *myWatch = [[Watch alloc]init];
        [myWatch setHours: 5];
        [myWatch setMinutes: 30];

        int hours = [myWatch hours]; //standard getter
        int minutes = [myWatch minutes];
        [myWatch printTime];
    }
    return 0;
}

naming conventions are important in Cocoa, as higher level technologies as Key-Value-Observing depends on them.


My approach is to keep the XxxxxDbContext class as lightweight as possible:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    new ModelCreator().Execute(modelBuilder);
}

The ModelCreator class looks like this:

internal class ModelCreator
{
    public void Execute(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        modelBuilder.Configurations.Add(new FirmConfiguration());
        // etc.
    }
}

Then each table has its own EntityTypeConfiguration<TEntityType>:

internal class FirmConfiguration : EntityTypeConfiguration<Firm>
{
    public FirmConfiguration()
    {
        HasKey(x => new { x.Id });

        Property(t => t.Name).HasMaxLength(30).IsRequired();
        Property(t => t.Address).HasMaxLength(120).IsRequired();
        Property(t => t.PostalCode).HasMaxLength(4).IsRequired();
        Property(t => t.City).HasMaxLength(30).IsRequired();
        Property(t => t.Responsible).HasMaxLength(30).IsRequired();
        Property(t => t.Email).HasMaxLength(40).IsRequired();
        Property(t => t.Phone).HasMaxLength(14);
    }
}


Scroll to the top of an element when document is loaded

Three concerns:

Error if there is not element called 'foo'
I have no idea what that boolean in the function is for.  Passing booleans at parameters is  very bad.  I have no idea what happens if I were to pass it false or any other value. Not scroll into view? I know that it is for topAlign but why not leave it out.
you can't use the onload event again without messing it up.


Generate random string to match the goal string with minimum iteration and control statements

Find my suggestions below.

goalString = input()

Let the user know what to do, input accepts a string as an argument:
goalString = input('Type a string:')

alphanum = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#&()–[{}]:;‘,'?/*1234567890'''

If you need all printable characters you can use string.printable:
import string

alphabet = string.printable
# alphabet contains: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Or choose a combination of other constants in the string module.

Generating a random string
def getRandomString():
    randomString = ''
    for i in range(stringLen):
        randomString = randomString + alphanum[random.randrange(alphaLen)]

    return randomString

Avoid using globals passing the length as an argument
String concatenation can be done more efficiently with join
Use random.choices to avoid the for-loop
PEP 8: function names should be lowercase, with words separated by underscores. Variable names follow the same convention as function names.

def generate_random_string(n):
    alphabet = string.printable
    return ''.join(random.choices(alphabet, k=n))

The function to match the string creates many strings using concatenation. It can be done more efficiently by using a list of booleans (as @rperezsoto suggested).
def get_matching_string(s):
    n = len(s)
    matches = [False] * n
    i = 0
    while not all(matches):
        matches = [matches[i] or s[i] == c for i, c in enumerate(generate_random_string(n))]
        i += 1
    return i

The key part is to use the operator or that "remembers" positive matches.

I want this to be combined together into a single generateString()
function with minimum iteration statements

I would suggest keeping two separate functions as in your first solution. The code will be easier to test and reuse. Additionally, you can extract the logic to request the input and print the result from the function getMatchString with a main function:
def main():
    s = input('Type a string:')
    print(get_matching_string(s))

if __name__ == "__main__":
    main()


Normally, I'd start of modelling promise chains following the "happy path". Following that, you will almost always find your logic (therefore your promise chain) in a straight line. Any fail condition in the chain should be broken by returning a rejected promise, which then skips to the nearest fail callback (which might redeem it) or catch if nothing caught it midway.

For rejections, it's also advised to reject with an error object because 1) it makes sense to, 2) error-handling mechanisms will almost always expect an error object not a string, and 3) works well with async-await, which uses the try-catch mechanism, where catch expects an error object. Lastly, you can key off of the error object's data to know what status code to return. This versus having multiple ends within the chain.

Avoid hoisting variables to outer scopes unless needed. I'm referring to q and p. It's only used in the callback that does return client.query(q, p).execute();. It makes sense to put it in the callback because it's only used there, and there's no unnecessary operation if ever that callback is never reached.

Also, exitChain() does not work the way you think it works.

function getUserByID(req, res) {
  const id = req.query.id
  req.checkQuery('id', 'ID is not a number').isInt()

  req.getValidationResult().then(vRes => {

    // Do next async operation or fail depending on condition
    return vRes.isEmpty() ? pg.connect(postgresConfig) : Promise.reject(new Error('...'))

  }).then(client => {

    return client.query('select * from users where user_id=$1', [id]).execute()

  }).then(result => {

    result.client.done();
    return res.status(200).send(res.json(result.rows))

  }).catch(error => {

    // If anything fails, it all ends up here. The 400 could be replaced
    // depending on the error object data.
    res.status(400).send('Error: ' + error.message)

  })
}


For a basic program like this, everything is more or less okay. Here are some nits:

game_status_check() should only do checking. Put the print("Game over !") in your main function.

def game_status_check():
    return len(player_card) == 0 or len(computer_card) == 0

This also removes the need for you to do:

while not game_status_check():
    ...
    game_status_check()

What happens if a player doesn't remove a card that was in their set of player cards, and then enters an answer that's not y or n? Your end_game() function has a handler for that, but doesn't prompt the user again for input. Suggestion:

def end_game():
    answer = input("Do you want to restart the game [y or n] ?: ")
    while answer != "y" and answer != "n":
        answer = input("Do you want to restart the game [y or n] ?: ")
    if answer == "y":
        main()
    else:
        print("Thank you for playing ! ")
        exit()

This change is optional and is purely my opinion to make the output look better.

def printout_cards():
    print("######################################\n")
    print("Player card: {}".format(" ".join(player_card)))
    print("\n######################################\n")
    print("Computer card: {}".format(" ".join(computer_card)))

I would suggest not naming a function random_choice() for readability. It can easily be confused with random.choice().


Powershell script that updates Active Directory user information

I agree with what @veefu suggests, and would like to build off that. To start with, you have different columns in your CSV as to what Set-ADUser is expecting. To work around this I would suggest creating a property map hashtable.

$PropMap = @{
    EmployeeNumber='EmployeeNumber'
    Department='Department'
    Title='Title'
    office='Office'
    Address='StreetAddress'
    City='City'
    State='State'
    PostalCode='PostalCode'
    Company='Company'
    telephone='OfficePhone'
    cell='Mobile'
    Fax='Fax'
    custom1='ExtensionAttribute1'
    custom2='ExtensionAttribute2'
    custom3='ExtensionAttribute3'
    custom4='ExtensionAttribute4'
}

Then you want to find out what the valid parameters for Set-ADUser are to determine if a given column should be applied as a parameter, or be fed to the -Replace parameter.

#Find the valid parameters for the Set-ADUser cmdlet (only strings, to avoid complex objects and switches, and no common parameters)
$ValidParams = Get-Command Set-ADUser -ShowCommandInfo |% ParameterSets |% Parameters |?{$_.ParameterType.FullName -match 'String' -and $_.Name -notin [System.Management.Automation.PSCmdlet]::CommonParameters} |Select -Expand Name -Unique

Then you import the CSV and loop through the users. For each user you find what properties they have filled in on the spreadsheet, see if it is a parameter for the Set-ADUser cmdlet, and build a hashtable to splat to the cmdlet.

#Import the list of users and updates
$Users = Import-Csv C:\Scripts\Employees.csv

#Loop through users
ForEach($User in $Users){
    #Set an empty hashtable for what this user needs to have updated
    $UserParams = @{}
    #Find the properties for this user that have values
    $UserProps = $User.PSObject.Properties.Name |?{![string]::IsNullOrWhiteSpace($User.$_)}
    #If it has a parameter in Set-ADUser add it to $UserParams
    $UserProps |?{($ParamName=If($_ -in $PropMap.Keys){$PropMap[$_]}Else{$_}) -in $ValidParams} |%{$UserParams.Add($ParamName,$User.$_)}
    #If it doesn't have a valid parameter build a hashtable for the -Replace parameter, and add that to $UserParams
    $UserProps |?{($ParamName=If($_ -in $PropMap.Keys){$PropMap[$_]}Else{$_}) -notin $ValidParams} |% -Begin {$ToReplace = $_} -Process {$ToReplace.Add($ParamName,$User.$_)} -End {$UserParams.Add('Replace',$ToReplace)}

Here I added a little Try/Catch to let you know if it failed to find or update any of the users, and if it failed to find them, or failed to update them, and gives the error. I used the shortened -ea instead of -ErrorAction out of habit.

    #Try to find the user, and apply the updates
    Try{
        Get-AdUser -Filter "EmployeeID -eq '$($user.EmployeeID)'" -SearchBase "ou=Logins,dc=domain,dc=com" -ea Stop | Set-ADUser @UserParams -ea Stop
    }Catch{
        #If the Get-ADUser or Set-ADUser cmdlets failed throw a warning with the user's EmployeeID for investigation

        #Determine if it was Get-ADUser or Set-ADUser that failed, to see if we couldn't find the user or couldn't update the user
        $WarningMessage = If($_.InvocationInfo.MyCommand -eq 'Get-ADUser'){'find'}else{'update'}
        Write-Warning "Unable to $WarningMessage user with EmployeeID (actual error follows): $($User.EmployeeID)"
        Write-Warning "$_`n"
    }
}


F# Djikstras shortest path implementation

Matthew Podwysocki wrote a nice functional solution for this on his blog a few years ago:

module Map =
  let transposeCombine m =
    (m, m) ||> Map.fold (fun acc k1 m' ->
      (acc, m') ||> Map.fold (fun acc' k2 v ->
        acc'
        |> Map.add k2 (Map.add k1 v (defaultArg (acc' |> Map.tryFind k2) Map.empty))
    ))

type City =
    | Boise   | LosAngeles | NewYork | Seattle
    | StLouis | Phoenix    | Boston  | Chicago
    | Denver

let distanceBetweenCities =
  Map.ofList
    [
        (Boise, Map.ofList [(Seattle, 496);(Denver, 830);(Chicago, 1702)]);
        (Seattle, Map.ofList [(LosAngeles, 1141);(Denver, 1321)]);
        (LosAngeles, Map.ofList [(Denver, 1022);(Phoenix, 371)]);
        (Phoenix, Map.ofList [(Denver, 809);(StLouis, 1504)]);
        (Denver, Map.ofList [(StLouis, 588);(Chicago, 1009)]);
        (Chicago, Map.ofList [(NewYork, 811);(Boston, 986)]);
        (StLouis, Map.ofList [(Chicago, 300)]);
        (Boston, Map.ofList [(StLouis, 986)]);
        (NewYork, Map.ofList [(Boston, 211)])
    ]
    |> Map.transposeCombine

let shortestPathBetween startCity endCity =
  let rec searchForShortestPath currentCity distanceSoFar citiesVisitedSoFar accMap =
    let visitDestinations m =
      (m, distanceBetweenCities.[currentCity])
        ||> Map.fold
          (fun acc city distance ->
             searchForShortestPath city (distance + distanceSoFar) (citiesVisitedSoFar @ [city]) acc)

    match Map.tryFind currentCity accMap with
    | None -> accMap |> Map.add currentCity (distanceSoFar, citiesVisitedSoFar) |> visitDestinations
    | Some x ->
        let (shortestKnownPath, _) = x
        if distanceSoFar < shortestKnownPath then
          accMap |> Map.add currentCity (distanceSoFar, citiesVisitedSoFar) |> visitDestinations
        else accMap

  let shortestPaths = searchForShortestPath startCity 0 [] Map.empty
  shortestPaths.[endCity]

Usage:

shortestPathBetween LosAngeles NewYork //(2721, [Denver; StLouis; Chicago; NewYork])


count all array[index] == index occurrences

Now let's see if I understand your problem: Given a sorted list of unique numbers you want to find all instances where list[i] == i (the important part is the unique).

This means each number in the list is at least 1 larger than the previous number.
Assume that list[k] == x < k. Because the numbers are strictly increasing it must be that list[k-1] <= x-1 < k-1, list[k-2] <= x-2 < k-2, ... list[k-l] <= x-l < k-l. So if you have an index where the value is smaller than the index then this must also be the case for all previous indices.
Assume that list[k] == x > k. Because the numbers are strictly increasing it must be that list[k+1] >= x+1 > k+1, list[k+2] >= x+2 > k+2, ... list[k+l] >= x+l > k+l. So if you have an index where the value is larger than the index then this must also be the case for all following indices.

The conclusion from these points is that a list with the given properties can be divided into three parts

Start 0 <= s < ms with list[s] < s
Middle ms <= m < me with list[m] == m
End me <= e < n with list[e] > e

Your problem is to find the middle part. The number of items where list[i] == i is then me - ms.

This can be solved by finding the largest index for which list[k] < k and the smallest index for which list[k] > k (or the smallest and largest indices for which list[k] == k - depends on how you want to write the search criteria).

Using two binary searches should yield the desired results which will guarantee a worst case complexity of O(log(n))

Update: Your original implementation is effectively a binary search which will find both end and start point of the middle sequence so you implementation is O(log(n))


Encapsulation of client side logic in web page

Update: To answer your specific questions (which I just now realized I completely neglected):

The this/that stuff is one way of doing "context resolution" (you used the word "callback", but that's when you pass a function to another function). There are other ways, such as Function.bind/jQuery.proxy, but in your case assigning a local that variable is a valid and customary way of doing it.
Sure, you can have the constructor do nothing except declare and assign instance variables. But there are no written or unwritten rules regarding a construtor's responsibilities, so it's up to you what it should do. As you say the init method ends up being public, which isn't terribly useful - in fact, init is only useful once in the object's lifetime, so it should probably be in the constructor. And if it's in the constructor, you don't need to assign instance variables; they work fine as local variables and closures. And if they're closures, you don't need the this/that either...

... and so you don't actually need a "class" anymore, which is how I arrived at the code below.

It depends on your specific needs, but with the example you give, it seems like overkill to have a "class" (constructor + prototype) to handle that bit of logic. You can make do with:

$(function () { // shorthand for $(document).ready(...)
  var postNrCtrl   = $("#postnr"),
      postStedCtrl = $("#poststed");

  postNrCtrl.on("change", function () {
    var postnr = jQuery.trim(this.value);

    // if the field is empty, clear the postStedCtrl and stop
    if( !postnr ) {
      postStedCtrl.val("");
      return;
    }

    // Return if the value isn't 4 digits (i.e.
    // if it isn't a valid Norwegian postal code)
    if( !/^\d{4}$/.test(postnr) ) {
      // perhaps you want to alert the user here before returning
      return;
    }

    // Make an explicit JSONP request to get around same-origin policy
    // jQuery takes care of encoding the params and adding the callback param
    $.ajax({
      type:     "GET",
      dataType: "jsonp",
      url:      "http://fraktguide.bring.no/fraktguide/api/postalCode.json",
      data: {
        country: "no",
        pnr:     postnr
      }
    }).done(function (data) {
      if( data && data.valid ) {       // check the response a little
        postStedCtrl.val(data.result); // postStedCtrl is available via closure
      }
    });
  });
});

Here's a demo

On a more general note: For things like controller-logic, I find "classes" too cumbersome. You only need 1 instance of a controller, so coding a prototype and construtor only to instantiate it once, seems like overkill in a language like JavaScript that has object literals and closures.


Algorithm
Your algorithm is a bit flawed. One might think that it was that easy, but with your current approach one of three things can happen:

The result has exactly one solution (A traditional Sudoku)
The result has many solutions (Not seen as a traditional Sudoku, as there's no way to logically deduce one solution)
The result has no solutions (Yes, although unlikely, this is a possible outcome of your current approach)

A different approach to generating Sudokus is to fill the entire grid first with a valid and completed Sudoku puzzle, and then (pseudocode following):

Remove a number
Check if the current puzzle is solvable using a Sudoku solving algorithm

If it is solvable, continue
If it is not solvable, put the number you just removed back and either try removing another number, or stop.

By using this different approach your result Sudoku is guaranteed to be solvable and have only one solution.
Making it object-oriented
Your main method is doing many many things, I would recommend changing your main method to do only this:
private static final int DEFAULT_SIZE = 9;
public static void main(String[] args) {
    Sudoku sudoku = new Sudoku(DEFAULT_SIZE, DEFAULT_SIZE);
    sudoku.generate(Difficulty.HARD); // Using @Jeroen's lovely enum!
    sudoku.output();
}

With this structure of your main method, you can see that I'm expecting you to create a Sudoku class. You will hopefully see that you will have many benefits by having a specific Sudoku class. By having a Sudoku class, it will be much easier to expand your code, read your code, modify specific parts of your code, and create a world of new amazing Sudoku-ness.
Example of an unsolvable puzzle
For the sake of simplicity, consider a 4x4 puzzle divided into 2x2 boxes:

  12 34
  -----
a|00 03
b|02 04
 |
c|10 00
d|40 00

This puzzle does not break any Sudoku rules in it's current state, however, it is not possible to create a finished Sudoku puzzle from this state!
If you don't believe me, I ask: Which number should be in the top-left corner?

It cannot be a 1, as there is a 1 on position c1.
It can't be a 2 as there's a 2 in the same box on position b2.
It can't be a 3 as there's a 3 on a4.
It also can't be a 4 as there's a 4 on d1.

There is no valid number we can put in the top-left corner, and therefore it is unsolvable!


Type that returns a result based on some logic

The problem is the Initialise method.

'Initialise', 'Init', 'PostConstruct', ... are always a code smell. All these methods perform actions/checks on an object after it has been created.
But most of the time, these actions/checks need to happen before, or while an objects is created.

Refactor the code by using a factory-method or builder where you put the 'initialise' code in the method/class, instead of in the object itself.

Then you can write an easy test on this object creation or validation method/class.

I would rewrite to something like this:

enum Reason{
    ZERO,ONE,OK
}

class MyFilterCreator
{
    public MyFilter create(int value)
    {
        if(shouldFilter(value) == Reason.OK){
            return new MyFilter(value);
        }else{
            return null;
        }
    }

    // write a test for this method
    public Reason shouldFilter(int _state)
    {
        if (_state == 0)
        {
            return Reason.ZERO;
        }
        else if(_state == 1)
        {
            return Reason.ONE;
        }
        else
        {
            return Reason.OK;
        }
    }
}

But to answer your question: No, do not check on messages, but on statuses.


For the first part of your code, it could be refactored into the following for readability and "better" practice:

update: function(req, res) {

  // I usually recommend one var per variable to explicitly say "this is a variable"
  // as well as not fumble with commas. Commas have a lot of uses in JS. I'd
  // like to avoid confusion.

  // Arrays can be indented this way to make it look like a list. Additionally,
  // this is a "constant", so let's make it appear like so. And let's pull it up
  // the scope, away from the action, because it does no action.
  var FORBIDDEN_FIELDS = [
    'telerivetId',
    'telerivetProjectId',
    'votoId',
    'votoApiKey',
    'campaign',
    'country'
  ];

  var slug = req.body.slug;

  // Highly suggest you not modify objects you don't own, especially ones
  // generated by the system. That's because something else might be need them.
  //
  // Instead of stripping, why not create one that doesn't include forbidden
  var surveyDiff = Object.keys(req.body.diff).reduce(function(carry, key){
    if(!~FORBIDDEN_FIELDS.indexOf(key)) carry[key] = surveyDiff[key];
    return carry;
  }, {});

  // We can coerce a value to a boolean, and get rid of "> 1"
  // As a colleague would say "What is 1? Is that arbitrary? What does it mean?"
  var hasDiff = !!Object.keys(surveyDiff).length;

  return hasDiff ? update(slug, diff) : res.json({ success: false });

}

As for the second part, callbacks look fine. Though there is a way to prevent "callback hell" and that is to break away the callbacks as named functions, and let the operation refer to them by name. Something like

// Something like this:

function asyncRoutine(){
  db.findSomething({...}, function(err, data){
    db.findAnotherSomething({...}, function(err, data2){
      // data
    });
  });
}

// into something like this:

function asyncRoutine(){
  db.findSomething({...}, handleDbFind);
}

function handleDbFind(err, data){
  db.findAnotherSomething({...}, handleAnotherDbFind);
}

function handleAnotherDbFind(err, data){
  // done!
}

However, you lose the advantage of scopes (visibility of outer variables in nested callbacks). It also makes the code rather long, since you're splitting them up.


It seems to me that you don't need the self invoking function and the anonymous function:

inter = window.setInterval( scroll, 50);

should do


Implementation of String object as an exercise

Some information up front:

Object.defineProperty is an Ecmascript 5 feature, and is not available in older browsers (IE < 9).
There is likely a cleaner way of doing all of this.

This is a basic skeleton:

function MyString(primitive) {
    var length = 0, a;   // private internal variable to track length, and our iterator

    // the loop below basically ensures that this string object is immutable.
    for(a in primitive){
        (function(char){
            Object.defineProperty(this, length++, {
                get:function(){return char;}
            });
        }).call(this,primitive[a]);
    }

    // we can "get" the length, but we can't "set" it.
    Object.defineProperty(this, "length", {
        get:function(){return length;}
    });

    return this;
}

// defining methods on the prototype of an object allows us to share the same instance
// of the method without recreating it for each instance of the object.
// (reduced memory footprint)
MyString.prototype.toString = function(){
    return [].join.call(this, '');
    // since our object is "array-like", we can use array methods on it.
}

MyString.prototype.charAt = function(index){
    return this[index];
}


JavaScript canvas animation slowing down and hogging memory

There is no need to recalculate the linearDistEachFrame during each update. You may want to precompute 2 * Math.PI as well.


Transformation rules

Especially useful if there are many fields and each needs a unique rule.

const dateToUTCString = d => new Date(d).toUTCString();

const DataTransformer = {
  createdDate: dateToUTCString,
  expirationDate: dateToUTCString,
};

// [...]

for (const [key, calue] of Object.entries(product)) {
  const transform = DataTransformer[key];
  formData.append(key, transform ? transform(value) : value);
}


Ideally you won't want to change the strDisplay, so we should probably take it out of the parameter list and make it a constant inside the method and then just return in each of the 3 circumstances.

var display = "Unknown";

try
{
    if (cType.IsEnum)
    {
        object cResult = cExpression.Compile().DynamicInvoke(cHtml.ViewData.Model);

        if (cResult != null)
        {
            return Enum.ToObject(cType, cResult).ToString();
        }
    }
}
catch (Exception cExc)
{
    return cExc.ToString();
}

return display;

this seems weird to me that we are using the variable (whatever you choose to name it)  only once, I would probably in this circumstance (since we aren't allowing it to be changed)  just return the string Unknown like this

try
{
    if (cType.IsEnum)
    {
        object cResult = cExpression.Compile().DynamicInvoke(cHtml.ViewData.Model);

        if (cResult != null)
        {
            return Enum.ToObject(cType, cResult).ToString();
        }
    }
}
catch (Exception cExc)
{
    return cExc.ToString();
}

return "Unknown";


I'm not sure of any implementation that can actually trim this down (it's doomed to be at least 3 levels of loops), but here's an alternative approach in doing it which I think is much readable.

We group them by year first by going through each country, create an array for each year, and pushing them into the array. Then, we extract the key-value pairs and convert them into an array of objects containing key and value.

var yearsToCountries = self.dataByGroup.reduce(function(dataByYear, group){
  group.values.forEach(function(year){

    // If the country appears just once, then we can do this:
    (dataByYear[year] = dataByYear[year] || []).push(group.key);

    // If the country can appear more than once, we guard the push:
    dataByYear[year] = dataByYear[year] || [];
    if(!~dataByYear[year].indexOf(group.key)) dataByYear.push(group.key);

  });
  return dataByYear;
}, {});

// {
//   1990: ['US', 'Italy', ...],
//   1989: ['US', 'France', ...],
//   ...
// }

var dataByYears = Object.keys(yearsToCountries).map(function(year){
  return { key: year, values: yearsToCountries[year]};
});

// [
//   {key: '1990', values: ['US', 'Italy', ...]},
//   {key: '1989', values: ['US', 'France', ...]},
//   ...
// ]


Check if a site is indexed by google and stores status in Database

First of all, changing between double and single quotes is going to make such a trivial difference, you would probably need to measure to microsecond precision to see any performance impact. Use quote styles that make your code most readable in whatever context you are forming strings.

The main thing you can do to speed things up is to parallelize the requests against Google and then batch your update queries for each batch of requests.

Using curl_multi may be a good approach. I actually have a simple REST library that leverages curl_multi that you are free to use if you find it helpful - https://github.com/mikecbrant/php-rest-client

Obviously, making requests in parallel will consume more memory and CPU on your server, so you might need to play around with number of concurrent requests to get your desired compromise of run time vs. resource utilization.

You also need to make sure you have an index on your Name field in the DB.

Don't use root user in MySQL, and especially don't leave root user with empty password.


Precognitive waiting - waiting for something to finish, before it starts

You have an interesting problem to solve. Your solution would be helped a lot with a small extension to the SourceAndFileName class. Consider the following version of it:

private static class SourceAndFileName
{
    private final DetectorMessageSource m_source;
    private final String m_fileName;

    private final ReentrantLock lock = new ReentrantLock();
    private final Condition arrived = lock.condition();
    private URL aviURL = null;

    public SourceAndFileName( DetectorMessageSource source, String fileName )
    {
        m_source = source;
        m_fileName = fileName;
    }

    public void setURL(URL url) {
        lock.lock();
        try {
            if (aviURL == null) {
                aviURL = url;
            }
            arrived.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public URL getURL(long timeout) {
        long now = System.currentTimeMillis();
        final long delayto = now + timeout;
        lock.lock();
        try {
            while (aviURL == null && now < delayto) {
                arrived.await(delayto - now, TimeUnit.MILLISECONDS);
                now = System.currentTimeMillis();
            }
            return aviURL
        } finally {
            lock.unlock();
        }

    }

    .... the rest is the same.....
}

OK, so, with the above class, you can get (with a timed delay, if you want) the URL, and you can set it too. This encapsulates the logic for the process well... but, the problem is that you need to have one, and only one instance of this for each source/fileName. This is solved with a single ConcurrentMap... (using the same key/value instances).

private ConcurrentMap<SourceAndFileName, SourceAndFileName> m_map = Maps.newConcurrentMap();

private SourceAndFileName getKey(DetectorMessageSource messageSource, String fileName)
{
    // be optimistic, and assume we are the first in....
    SourceAndFileName key = new SourceAndFileName(messageSource, fileName);
    SourceAndFileName current = m_map.putIfAbsent(key,key);
    if (current != null) {
        // we were wrong, and not the first in, so use the key from the previous one.
        return current;
    }
    return key;
}

@Override
public void messageReceived( MessageSource messageSource, UrlAviMessage message )
{
    // be optimistic, and assume we are first in....
    SourceAndFileName key = getKey((DetectorMessageSource)messageSource, message.getFileName());

    // set the location, which will trigger the get to return, if necessary...
    key.setURL(message.getLocation());

}

@Override
public InputStream waitForAvi( DetectorMessageSource messageSource, String aviFileName ) throws InterruptedException
{
    // be optimistic, and assume we are first in....
    SourceAndFileName key = getKey((DetectorMessageSource)messageSource, message.getFileName());

    URL url = key.get( 5000 ); // 5 second delay....

    // TODO download the avi to a temp local folder so we can add connect and read timeouts on the connection

    return url.openStream();
}

A more general code review is also in order...

The m_... type prefixing of variables is not useful in modern IDE's where it is normally color-coded where variables are from....
Java style guidelines put the { opening brace on the same line as the block condition (while/if/etc.).
your hashCode/equals methods on the key class would benefit from early-return statements instead of carrying the result variable.


You didn't write a docstring (which you should have done) or explain your function (which you should also have done), but it looks like n is supposed to be the same as the length of s.  If so, why should n have to be specified?

Your function has some unintuitive behaviour:

>>> matrix = nDimensionalArray(3, [1,2,3])
>>> matrix
[[[0], [0]], [[0], [0]], [[0], [0]]]
>>> matrix[0][0][0] = 1
>>> matrix
[[[1], [1]], [[1], [1]], [[1], [1]]]

Changing one element changes everything!  I assume that that is unintentional.  If it is intentional, then it needs to be clearly documented.


SSMTP configuration in Ubuntu 18.04 with Bash in my own system (one user)

First, I recommend set -eu early in the script to abort on errors and to make any use of unset variables be an error.

Second, If HOSTNAME is unset, we probably want to fallback to running the hostname command.  There seems little point in assigning it to a variable we use only once:

# (simplified to show only the relevant part)
cat <<EOF
    hostname=${HOSTNAME:-$(hostname)}
EOF

Then we can delete the line myHostName="$HOSTNAME", as it's no longer used.

Third, the other thing missing is umask 077 to ensure that the file isn't created readable by anyone else (important, as it contains cleartext credentials).

When reading email address, it shouldn't be necessary to hide it using read -s - only the password ought to be a secret.

When reading the password, there's no need to mention that confirmation is not required, as we wouldn't normally expect it here: we use confirmation when creating a password (so the user doesn't accidentally lock herself out of her account by a simple invisible typing error).  Here, we're entering an existing password, and any error can be corrected just by re-running the script.

Edited script

Applying my suggestions, we get:

#!/bin/bash

set -eu

umask 077  # Ensure others can't read the file

read -p "Please paste your Gmail proxy email address: " \
     gmail_proxy_email_address
read -sp "Please paste your Gmail proxy email password:" \
     gmail_proxy_email_password && echo

cat <<-EOF > /etc/ssmtp/ssmtp.conf
    root=${gmail_proxy_email_address}
    AuthUser=${gmail_proxy_email_address}
    AuthPass=${gmail_proxy_email_password}
    hostname=${HOSTNAME:-$(hostname)}
    mailhub=smtp.gmail.com:587
    rewriteDomain=gmail.com
    FromLineOverride=YES
    UseTLS=YES
    UseSTARTTLS=YES
EOF


This is the kind of function that benefits from unit tests.  I wrote a few simple tests in C++ with GoogleTest:

extern "C" {
    void quick_sort(int arr[],int pivot_, int right_);
}

#include <gtest/gtest.h>

#include <algorithm>
#include <iterator>
#include <numeric>

TEST(quick_sort, empty)
{
    int a[1] = {};
    quick_sort(a, 0, 0-1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, one_element)
{
    int a[] = { 0 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, two_same)
{
    int a[] = { 0, 0 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, two_asc)
{
    int a[] = { 0, 1 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, two_desc)
{
    int a[] = { 1, 0 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, three_123)
{
    int a[] = { 1, 2, 3 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, three_231)
{
    int a[] = { 2, 3, 1 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, three_312)
{
    int a[] = { 3, 1, 2 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, four)
{
    int a[] = { 3, 1, 2, 0 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, large)
{
    int a[100];
    std::iota(std::rbegin(a), std::rend(a), -50);
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

The first thing this highlighted was the unusual calling convention - right_ is an inclusive bound, but without any guidance, most C coders would expect an exclusive bound.

(In passing, I'll also point out that pivot_ isn't very meaningful to most callers - I think that left would be a better choice of name there.)

The second thing we see (diagnosed by running under Valgrind) is undefined behaviour when we run off the end of the array here:

    while(arr[i] < arr[pivot]) i++;

That needs to be fixed before this code is ready.


I assume the class this method resides in represents a person's full name (and title).

Two remarks before suggesting major refactorings:

You are using a getter getTitle and direct access to $this->title: stick for one. Usually I prefer to use getters within the class as well (as usual they contain some logic beside returning). Your other variables don't have getters at all. Also, getting a value just for checking for its existence is bad practice. Introduce some existence method for this (e.g. hasTitle).
Don't store information serialized during runtime ($middlenames). As you obviously need the middle names as an array, store them accordingly.

Now looking at your class, it has two responsibilities: (1) representing a name, and (2) formating a name. Moving the name formatting into a separate class decouples representation and formating. It allows you to have different means to format at name at the same time and when you want to change the formatting you don't have to touch the name class at all. This is how such a formatter might look like (untested):

class NameFormater {
    private $seperator;
    private $includeTitle;
    private $includeMiddleNames;

    public function __construct($seperator, $includeTitle, $includeMiddleNames) {
        // argument validation here
        $this->seperator = $seperator;
        $this->includeTitle = $includeTitle;
        $this->includeMiddleName = $includeMiddleName;
    }

    public function format(Name $name) {
        $nameParts = array();

        if ($this->includeTitle && $name->hasTitle()) {
            $nameParts[] = $name->getTitle();
        }
        if ($name->hasForName()) {
            $nameParts[] = $name->getForName();
        }
        if ($this->includeMiddleNames && $name->hasMiddleNames()) {
            $nameParts = array_merge($nameParts, $name->getMiddleNames());
        }
        if ($name->hasLastName()) {
            $nameParts[] = $name->getLastName;
        }

        return implode($this->seperator, $nameParts);
    }
}

Now this method could be refined further. E.g. we first could allow $nameParts to contain null values if the respective part was not set and filter them before implodeing. This would make it more challenging to read though and I prefer a bit more verbosity over compactness. The current version is trivial to follow and understand. This is due to no complex nesting or logic and names that speak for themselves (e.g. hasTitle) - and in my opinion this is the most important point in programming :)


Ranges

You use

var hecsHelp = [
{from:0,     to:53345, percentage:4},
{from:53344, to:59421, percentage:4},
{from:59422, to:65497, percentage:4.5},
{from:65498, to:68939, percentage:5.0},
{from:68940, to:74105, percentage:5.5},
{from:74106, to:80527, percentage:6.0},
{from:80258, to:84481, percentage:6.5},
{from:84482, to:92970, percentage:7.0},
{from:99070, to:99069, percentage:7.5},
{from:99070, to:Infinity, percentage:8.0},
];

to define ranges with different percentages. A few things to say about this :

it does not respect the DRY principle : this makes things easier to get wrong (and I believe that either the first or the second range is indeed wrong as it does not follow the same pattern where range[n].to + 1 == range[n+1].from)
it does not define what happens when the number you want to handle happens to be between range[n].to and range[n+1].from which can happen if you are handling non-integers values.

I think things would be easier if you were to define it like :

var hecsHelp = [
{from:0,     percentage:4},
{from:53344, percentage:4}, # By the way, is this line useful ?
{from:59422, percentage:4.5},
{from:65498, percentage:5.0},
{from:68940, percentage:5.5},
{from:74106, percentage:6.0},
{from:80258, percentage:6.5},
{from:84482, percentage:7.0},
{from:99070, percentage:7.5}, # This one seems pretty weird too.
{from:99070, percentage:8.0},
];

Then, iterating backward (or forward if you define your array as the reverse of what I have written), everything should be easier to maintain.


Python has what you want built into the standard library: see the multiprocessing module, and in particular the map method of the Pool class.

So you can implement what you want in one line, perhaps like this:

from multiprocessing import Pool

def parallelize(analysis, filenames, processes):
    '''
    Call `analysis` for each file in the sequence `filenames`, using
    up to `processes` parallel processes. Wait for them all to complete
    and then return a list of results.
    '''
    return Pool(processes).map(analysis, filenames, chunksize = 1)


Running multiple games concurrently with node.js

First I would suggest separating your game server from your static server. You wouldn't want your static server clogging up your game server process. The advantage is that you can easily spawn more processes if you want, across different ports, or even across different machines. And if one goes down, it's just that one, not everything.

So that means the following should be written separately:

Your static server (express)
Your room list server
Game server (which stores the game state)

Static server will be a standalone thing. Room list will share data with the game server. All your room listing server does is just get the active rooms from some DB. The game server will hold the game states across rooms. Creating a room would mean storing it's id to the DB for the server listing.

I also consider using UUIDs instead of counting. Create the id when a game object is created. This ensures that a game object will have a unique id upon creation, without relying on outer logic to supply it one.


Use extension methods
I find you did well by implementing the EverySecondElementIterator as a separate class. However, I also think it would be better to turn it into an extension of IEnumerable<T> and use MoveNext instead of the internal Node.
Otherwise if someone suddenly comes up with the idea to skip every third element, you would need to modify the original SimpleList by creating another private class class and another property. We usually try to avoid modifying code that is tested and is working well. This would also violate the open/closed principle.
It's much safer and extendable to create a new and independent extension that you also can resue with any IEnumerable<T> and skip every-second-element of any collection.
Let the SimpleList be closed for modifications by not implementing anything as specific as that enumerator. It is already opend for extension by implementing the IEnumerable<T> interface. Make use of it.


Simple calculation program in assembly MASM

I have some suggestions that may help you improve your code.

Fix formatting

There seem to be varying numbers of leading spaces on each line, impeding easy reading.  Typically labels and directives start in column 1 and instructions start in column 9 (one tabstop) and are all aligned there.  Many, including me, additionally align comments as well.

Make comments more useful

Comments like this are useful because they explain why we're doing something.

MOV     DX,AX    ; tO PRINT WE FIRST MOVE DATA IN DX REGISTER

Although it would be easier to read if it wasn't in ALL CAPS.  Other comments are not useful because they explain something obvious from the instruction:

 MAIN    PROC    FAR          ;MAIN PROGRAM STARTS HERE.
    ;  other code
    MOV     DS,AX      ;INITIALIZING THE DS REGISTER.

Eliminate "magic numbers"

There are a few numbers in the code, such as 30H and 2 that have a specific meaning in their particular context.  By using named constants such as ASCII_ZERO or PRINT_CHAR, the program becomes easier to read and maintain.

Think carefully about the problem

As mentioned in a comment, if you're really calculating (Z-Z)+(X-Y) then you can simply ignore Z because (Z-Z) is always going to be zero.  Next, the description says X-Y but the code says Y-X.  It's usually essential to clearly understand the problem at hand before beginning to write the code.

Prefer registers to memory

Register use is typically much faster than memory use.  For that reason, I'd recommend eliminating memory use that isn't needed.  In particular, RES1 and RES2 could easily be eliminated by either chaining operations or storing temporary values in a register.  By "chaining operations" I mean that (Z-Z)+(Y-X) is equivalent to Z-Z+Y-X (or simply Y-X) so one could simply evaluate the expression from left to right.

Use the appropriate OS service

The INT 21h, AH=02h is the "Write character to standard output" service, so it's only going to print a single character.  That's fine if you're only ever going to have a single digit non-negative result, but that doesn't seem assured here.  Better would be to create a function that converts the numeric result in AX to a string in memory and then use a function such as INT 21h, AH=40h, "Write to file or device" for output.

Set all appropriate registers for use by the OS services

The program exits with a call to the DOS "Terminate with error code" function (INT 21h, AH=4Ch) but fails to actually set the error code in AL.


Display a Text() with a foreground color based on a condition

There is a shorter and faster way, using ternary operators.
You could use
Text("Home").foregroundColor(self.viewRouter.currentView == "home" ? Color.blue: Color.black)

instead  of
{ () -> Text in
  if self.viewRouter.currentView == "home" {
    return Text("Home").foregroundColor(Color.blue)
  } else {
    return Text("Home")
  }
}()

However, with the advent of macOS Mojave 10.14 two years ago, users had an option to enable dark mode. So, unless you've explicitly disabled dark mode in your app, Color.black will blend in with the rest of your app bar. To prevent this, check for dark mode with UserDefaults.standard.object(forKey: "AppleInterfaceStyle"). If the user is using light mode, UserDefaults.standard.object(forKey: "AppleInterfaceStyle") will be nil, and if it's dark mode, it will be "Dark"
Text("Home").foregroundColor(self.viewRouter.currentView == "home" ? Color.blue: UserDefaults.standard.object(forKey: "AppleInterfaceStyle") == nil ? Color.black: Color.white)

As @BenLeggiero has suggested, this is a much shorter way to do the above:
Text("Home").foregroundColor(viewRouter.currentView == "home" ? .blue : .primary)


Better QOpenGLWidget by delaying GL code to initializeGL with lambda functions

Small nitpicks:

The default value of the parameter QWidget* parent of the constructor is 0. This should be replaced with nullptr.

Either OpenGLWidget or SomeWidget would need to inherit from QOpenGLFunctions to get access to the OpenGL functions used in the example.

The implementation as-is is absolutely not thread-safe. This might not be a concern if your application is guaranteed to be single threaded, but more often than not, applications using advanced graphics end up using multiple threads.

Since the context() member function is publicly accessible, it might be appropriate to make delayForInit adhere to the same level of accessibility.

While delayForInit isn't the worst name, it doesn't really convey what it's doing. deferGLCall or withGLContext might be more fitting.

Design
It's simplicity of usage is great. However, you have no way of enforcing that it will be used at all possible call sites (where appropriate).Another possibility that comes to mind would be to use the State pattern to provide access to the OpenGL functions in form of a member, with 2 states: One that records the OpenGL calls and one that simply forwards them. The call to initializeGL then switches state from recording to forwarding, executing the recorded calls.Though also not foolproof, but which is harder to forget: "I have to use OpenGL calls in a lambda passed to this function." or "I have to use this member to get access to the OpenGL functions (as they aren't provided directly by default anyways)."?
Example (rough outline, as I currently have no Qt install at hand):
class GLState {
protected:
    QOpenGLWidget& widget;
public:
    explicit GLState(QOpenGLWidget& w) : widget(w) {}
    virtual ~GLState() {}

    // define gl functions as needed
    void glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) = 0;
    void glClear(GLbitfield mask) = 0;
    // ...
};

class ForwardingGLState : public GLState, public QOpenGLFunctions {
    Q_OBJECT // not sure if needed, but probably is
public:
    ForwardingGLState(QOpenGLWidget& w) : GLState(w), QOpenGLFunctions(w.context()) {}

    // gl calls implemented by QOpenGLFunctions, nothing to do here
};

class RecordingGLState : public GLState {
    std::vector<std::function<void()>> records;
public:
    RecordingGLState(QOpenGLWidget& w) : GLState(w), records() {}

    // either do execution of recorded calls during destructor (might
    // be tricky with exceptions) or implement another virtual function
    // in GLState
    virtual ~RecordingGLState() {
        if(widget.context() == nullptr) return;

        widget.makeCurrent();
        for(auto& record : records) {
            record();
        }
        widget.doneCurrent();
    }

    // record gl calls
    // might be able to simplify lambda implementation
    void glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) {
        records.push_back([&]() {
            widget.context()->functions()->glClearColor(red, green, blue, alpha);
        });
    }

    void glClear(GLbitfield mask) {
        records.push_back([&]() {
            widget.context()->functions()->glClear(mask);
        });
    }
};

Usage in OpenGLWidget:
class OpenGLWidget : public QOpenGLWidget {
    Q_OBJECT
protected:
    std::unique_ptr<GLState> gl;

public:
    OpenGLWidget(QWidget *parent = nullptr) : QOpenGLWidget(parent), gl(std::make_unique<RecordingGLState>(*this)) {}

protected:
    virtual void initializeGL() override {
        // if not (ab-)using the destructor, execute recorded calls here
        gl = std::make_unique<ForwardingGLState>(*this);
    }
};

class SomeWidget : public OpenGLWidget {
    Q_OBJECT
public:
    SomeWidget(QWidget *parent = nullptr) : OpenGLWidget(parent) {
        gl->glClearColor(0.f, 0.f, 0.f, 0.f);
        gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }
};

Yes, it's a lot of boiler plate code inside the GLStates, but after that its mostly done (though some of it could probably be replaced with macros if it gets too bad). Plus side: you can't really get the final usage wrong!