React component to list TV shows from a JSON result

A few things to change. Move the api request to componentDidMount because componentWillMount is considered legacy now. Rename the method thats making the api request to be more declarative which is to be more descriptive of whats its doing. Move the list of ids into the method thats making the api request. All of those changes + the changes to the api request from your question here https://stackoverflow.com/questions/39473302/show-result-from-parallel-ajax-request-in-react-component/39486654#39486654 would look like this:

import React, { Component } from "react";
import List from "./List";

class ListManager extends Component {
  constructor(props) {
    super(props);

    this.state = {
      listData: []
    };

    this.getListData = this.getListData.bind(this);
  }

  componentDidMount() {
    this.getListData();
  }

  getListData() {
    const ids = [1, 2, 3, 4, 5];

    let listData = [];

    ids.forEach(id =>
      fetch("http://api.tvmaze.com/shows/" + id)
        .then(resp => resp.json())
        .then(show => {
          listData.push(show);
        })
    );

    this.setState({
      listData: listData.sort((a, b) => a.runtime - b.runtime)
    });
  }

  render() {
    return (

{this.props.title}

        <List data={this.state.listData} />

    );
  }
}

export default ListManager;


Baby Step Giant Step Discrete Log Solver

The most expensive operation you're performing is calculating a^(rk) every iteration. Since you are doing this in a loop and increasing the exponent by a constant amount each iteration (k), you can replace the exponentiation with a multiplication. This makes your concurrent task function look like this:

        go func(receiver chan int64, rGiven, k int64) {
            r := rGiven
            ark := pow(a, big.NewInt(r*k))
            ak := pow(a, big.NewInt(k))
            // fmt.Println("Currently at", rGiven, "\nRemaining:", sub(m, rk), "\n")
            for ; r < rGiven+increment+1; r++ {
                current := mod(mul(b, modInverse(ark, m)), m)
                currentString := current.String()
                val, inMap := store[currentString]
                if inMap {
                    receiver <- (val + r*k)
                }
                ark.Mul(ark, ak) // a^(rk) * a^(k) = a^((r+1)k)
            }
            receiver <- -1
        }(receiver, r, k)

To test this out, I commented out all the prints (they slow things down a lot) and made a test file named main_test.go containing:

package main

import (
    "math/big"
    "runtime"
    "testing"
)

func BenchmarkBabyGiant(b *testing.B) {
    processors = runtime.NumCPU()
    runtime.GOMAXPROCS(processors)

    b.ResetTimer()
    b.ReportAllocs()

    for i := 0; i < b.N; i++ {
        a := big.NewInt(7)
        b := big.NewInt(24190)
        m := big.NewInt(65537)

        babyGiant(a, b, m)
    }
}

Running this with go test ./ -bench=. before and after shows:

Before:
BenchmarkBabyGiant-8          50     663145338 ns/op    812469942 B/op    213165 allocs/op

After:
BenchmarkBabyGiant-8         100     335030538 ns/op    425100448 B/op     85983 allocs/op

This shows that this technique causes it to finish in just over half the time of the original. Using ReportAllocs also shows that this function is rather memory allocation heavy, so you could likely squeeze out another 10-30% by reusing big.Int instances instead of allocating a new one for every operation, and using something other than a string map for the lookup table (a sorted list that you binary search using sort.Search will likely be significantly faster and will avoid the overhead of converting to a base 10 string).


In general I think this code looks excellent.  You have made good use of comprehensions.  I have two suggestions:

More Comprehensions:

This:

def _get_tank_names(tanks=None, data=None):
    names = list()
    for n in tanks:
        for tank_dict in data:
            if tank_dict['Tank'] == str(n):
                names.append(tank_dict['Product'])
                break
return names

Can be expressed as:

def _get_tank_names(tanks=None, data=None):
    tanks = {str(n) for n in tanks}
    return {t['Product'] for t in data if t['Tank'] in tanks}

This converts tanks to a set while performing the str() conversion, to clean things up a bit.  Then the result can be generated in a single statement.

Gathering like elements

So this entire section:

# Create new row template
tank_names = _get_tank_names(tanks=tanks, data=d1)
row_template = {key: None for key in (tank_names + [primary_key])}

# New rows from row template
d4 = []
for row in d3:
    # update new row with available keys
    new_row = {key: row.get(key) for key in row_template}

    # update new row with matching values
    for key in new_row:
        if key in row.values():
            new_row[key] = row[data_key]

    # remove keys with None value
    new_row = {k: v for k, v in new_row.items() if v is not None}
    d4.append(new_row)

# Merge all rows based on Time key
merged = {}
for row in d4:
    if row[primary_key] in merged:
        merged[row[primary_key]].update(row)
    else:
        merged[row[primary_key]] = row

return [value for value in merged.values()]

Can be reduced down to:

merged = {}
for row in d3:
    merged.setdefault(row['Time'], {'Time': row['Time']}) \
        [row['Product']] = row['Volume']

return [v for k, v in sorted(merged.items())]

The cornerstone here is using dict.setdefault to accumulate the records that match the timestamp.

So how does the setdefault work?

We create an empty dict, the keys to which will be the timestamps we will be accumulating data for.

merged = {}

Loop through the data, a row at a time:

for row in d3:

Look up the element in our dict corresponding to the timestamp for this row:

merged.setdefault(row['Time'], {})

This is most of the magic, it will populate merged[this rows timestamp] with an empty dict if one is not already there, and then return the dict, so that we can put something in it.  An empty dict would often be sufficient, but in this case you also need the timestamp in the final dict, so we can extend the statement to be:

merged.setdefault(row['Time'], {'Time': row['Time']})

This will return a dict with the timestamp already populated, the first time we see that timestamp.  In subsequent loops when we see the timestamp, it will return the dict that was built the previous time we saw the timestamp.

To finish the dict creation code we set the Product and Volume data into the dict with:

merged.setdefault(row['Time'], {'Time': row['Time']}) \
    [row['Product']] = row['Volume']

Lastly, return the list of dicts we built, sorted by the timestamp with:

return [v for k, v in sorted(merged.items())]

Ain't Python fun? :-)


Prefer four-space indentation instead of a mix of four and two
queueurls should be queue_urls
else / pass is redundant and can be deleted
It's not a great idea to use a single, statically-named temporary file for your playback. Instead, use tempfile to generate you a random one-off temporary filename. It's possible that the inefficiency you see is actually some kind of contention around your single filename.
while queueurls != [] is better-stated as while len(queue_urls) > 0.
while vcs.is_playing is a polling loop that's probably going to saturate your CPU. At the least, add a sleep(0.1) to the inside of your loop to release your thread from the OS scheduler. Better yet would be a blocking call to your audio library, though I don't know whether that's possible. Based on the documentation, you could wait until an after finalizer hook is called.


If the goal is "general purpose" I would be inclined to start from a much simpler premise, allowing users (i.e. developers) to build GUIs with the features that they need. Using object-oriented techniques you could subclass the tkinter widgets and extend them as needed. For example:

import tkinter as tk
from tkinter import messagebox

class ValidEntry(tk.Entry):

    def __init__(self, *args, validator=lambda text: True, **kwargs):
        super().__init__(*args, **kwargs)
        self.validator = validator

    def get(self):
        text = super().get()
        if not self.validator(text):
            raise ValueError('Invalid input')
        return text

This is now a reusable component; it can be dropped in wherever a regular tk.Entry is required (indeed the default validator allows it to be a direct replacement if validation isn't actually needed). The next step up is then:

class ValidatorFrame(tk.Frame):

    INSTRUCTION_FONT = '20px'

    def __init__(self, root, *args, button_text='Validate', instructions=None,
                 validator=lambda text: True, **kwargs):
        super().__init__(root, *args, **kwargs)
        if instructions is None:
            instructions = validator.__doc__
        self.instructions = tk.Label(
            root,
            font=INSTRUCTION_FONT,
            justify=tk.LEFT,
            text=instructions
        )
        self.instructions.pack(expand=1, fill=tk.X)
        self.user_input = ValidEntry(root, validator=validator)
        self.user_input.pack(expand=1, fill=tk.X)
        self.validate = tk.Button(root, command=self.validate, text=button_text)
        self.validate.pack()

    def validate(self):
        try:
            text = self.user_input.get()
        except ValueError:
            messagebox.showerror(
                "Input NOT valid.",
                "Please try again and enter a valid input."
            )
        else:
            messagebox.showinfo(
                "Input valid.",
                "Congratulations, you entered valid input."
            )

Again, this is a component that can be easily used elsewhere. One final step outward:

class TestGui(tk.Tk):

    TITLE_FONT = '25px'

    def __init__(self, *args, title=None, validator=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.title_label = tk.Label(self, font=self.TITLE_FONT, text=title)
        self.title_label.pack(expand=1, fill=tk.X)
        self.frame = ValidatorFrame(self, validator=validator)
        self.frame.pack(expand=1, fill=tk.X)
        if title is None:
            title = validator.__name__.replace('_', ' ').capitalize()
        self.wm_title(title)

By building up from basic components, you give yourself and your users a lot more flexibility. You can now launch this (using the validator you've already written) as simply as:

if __name__ == '__main__':
    app = TestGui(validator=is_valid_salutation)
    app.mainloop()

It's slightly more code, but a lot more flexible. One thing I haven't put much thought into is where the text would go once valid...

A few other things to note:

import tkinter as tk saves you repeating a few extra characters all over the place;
You tend to end up with a lot of keyword arguments to widgets, so I keep them in alphabetical order; and
Factoring out the styling information makes it easier to reuse, too.


Dice rolling simulator, any ideas on implementing any features?

I normally would agree with Graipher here, however with your code I think there's a simpler and more readable solution.

The first number doesn't have to be larger than the second.

This is an artificial limitation that can be fixed by sorting the inputted values.
Not allowing the same value to be selected is an artificial limitation. random.randint includes both bounds, meaning random.randint(n, n) is valid input.
You can bundle the first two try statements together to simplify the code.

This makes the code DRY as the two loops are logically doing two different things.

Whilst longer it keeps the functionality to change the lower bound if you enter it incorrectly, without having to kill the process.

import random

while True:
    try:
        min_, max_ = sorted([
            int(input("Please enter one of the bounds: "))
            int(input("Please enter the other bound: "))
        ])
        break
    except ValueError:
        print("Invalid input")

while True:
    try:
        amount = int(input("How many times do you want to roll the dice: "))
        break
    except ValueError:
        print("Invalid input")

for _ in range(amount):
    print(random.randint(min_, max_))

Note: You can move both the while try loops into a function, and pass a lambda, however I don't think that's as readable.

min_, max_ = while_try(lambda: sorted([
    int(input("Please enter one of the bounds: "))
    int(input("Please enter the other bound: "))
]))


You shouldn't use i and j as variables in MATLAB, as they are used to denote the imaginary unit (sqrt(-1)).
In fact, the official MATLAB documentation warns you about it. It's better to use 1i or 1j for the imaginary unit.
The documentation says the performance is better, but that's not really true. The main problem however is that using those variable names
can result in some stange behavior. As i is not undefined, you don't get the usual Undefined function or variable 'x'.

For instance, assume you intended to write i = true, but forgot it. Now, try out:

if i == true
   disp('What happens here?')
end

This should normally result in "What happens here?" being displayed on the screen, but since i = sqrt(-1), which is neither true nor false, you get nothing. You won't get anything for this either:

if i == false
   disp('What happens here?')
end

Similarly, this will result in an infinite loop:

while i < 10
    i = i * 2;
end

So, change i and j to ii and jj (this is common for users on SO at least), or some other variable names.

Now, what about the loops and ifs?

You are right, this should definitely be vectorized. Althoug the performance of loops have been drastically improved after the new exectuion engine
was included, vectorization is still fastest in most cases.

First off, you should know that boolean values can be treated as numeric values. They can be subtracted, added, etc. Furthermore, any non-zero real number is considered to be true, while a zero is considered to be false. Also, if a == true is the same as just if a, and if a == false is the same as just if ~a (~ means not in this case), or if a ~= 0.

If you had only the first part about where result is defined only be the values of A, then this could be done quite simply:

results = (A > 0.75)  % or `results = (A > 0.75)

The part with A < 0.25 is irrelevant there, since those elements are already zero.

x | y means x == true and/or y == true. So, it's enough that one of the conditions are true. If you do x & y, then both x and y must be true.

Since you include the part with B, you must add a term, the above line is not enough. First note that the part with B is only relevant if the two conditions

A < 0.75

and

A > 0.25

are both false. We can disregard the A < 0.75 part, since those elements are already set to 1.

In plain text: The elements in result shall be 1 if either A > 0.75 or A > 0.25 and B == 1. Since the last part has an and in there, we must use &.

So, the loops and ifs can simply be rewritten as:

result = ((A > 0.75) | (A > 0.25 & B))

It's a matter of preference, but you might want to do ... & B == true alternatively ... & B == 1 for clarity. It's common to ignore the true part, but it is a bit clearer to include it.

Example:

A =

   0.568800   0.162200   0.165600   0.689200
   0.469400   0.794300   0.602000   0.748200
   0.011900   0.311200   0.263000   0.450500
   0.337100   0.528500   0.654100   0.083800

B =
   1   0   1   0
   0   0   1   1
   0   1   1   0
   0   0   1   1

res =
   1   0   0   0
   0   1   1   1
   0   1   1   0
   0   0   1   0


Simple File Manager with recursion in C#

I don't think I would make this class static, unless it's going to be used extensively throughout the program. If not you can build up a large list of files, that may hang around in memory for no use, unless you remember to call ClearFiles(). Instead you could make a static method that could return an initialized object like:

public static FileManager Create(string directoryPath)
{
  FileManager fm = new FileManager();
  fm.AddFiles(directoryPath);
  return fm;
}

If you have a need for it, then make this instance as static somewhere in the application.

public static string GetPath(string filename)
{
  var File = Files.Find(x => x.Name == filename);
  return File.Path;
}

It returns only a first match of possible more matches, which will be in a directory high in the hierarchy, but what if you actually seek a path to a file in a subdirectory?

I think I would return a list/array/IEnumerable instead and let the client filter as needed.

Besides that, file names are case insensitive, so you should do:

Files.Find(x => string.Equals(x.Name, filename, StringComparison.CurrentCultureIgnoreCase));

public static void AddFiles(string directory)
{
  foreach (string file in Directory.GetFiles(directory))
  {
    Files.Add(new File() { Name = Path.GetFileName(file), Path = directory });
  }
  foreach (string subdirectory in Directory.GetDirectories(directory))
  {
    AddFiles(subdirectory);
  }
}

Nice recursive method. As an alternative you could consider to use DirectoryInfo instead - it can handle the recursive search for you:

  DirectoryInfo directory = new DirectoryInfo(directoryPath);
  Files.AddRange(
    directory
    .GetFiles("*.*", SearchOption.AllDirectories)
    .Select(fi => new File { Name = fi.Name, Path = fi.DirectoryName }));

There is no way to iterate through all the found File objects because the Files static member is private. I would consider to provide a public IEnumerable of some kind.

All in all, my implementation would look something like:

  public struct File
  {
    public string Name;
    public string Path;

    public override string ToString()
    {
      return $"{Name} => {Path}";
    }
  }

  public class FileManager : IEnumerable<File>
  {
    private List<File> Files = new List<File>();

    public void AddFiles(string directoryPath)
    {
      DirectoryInfo directory = new DirectoryInfo(directoryPath);
      Files.AddRange(
        directory
        .GetFiles("*.*", SearchOption.AllDirectories)
        .Select(fi => new File { Name = fi.Name, Path = fi.DirectoryName }));
    }

    public IEnumerable<string> GetPaths(string filename)
    {
      return Files
        .Where(x => string.Equals(x.Name, filename, StringComparison.CurrentCultureIgnoreCase))
        .Select(f => f.Path);
    }

    public void Clear()
    {
      Files.Clear();
    }

    public IEnumerator<File> GetEnumerator()
    {
      return Files.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }

    public static FileManager Create(string directoryPath)
    {
      FileManager fm = new FileManager();
      fm.AddFiles(directoryPath);
      return fm;
    }
  }


String appending function (location-independent)

This is more of a string-inserting function than a string-appending function, and should be renamed as such.

When calling realloc(…), the string could very well move to a different memory location.  The caller of strapp() has no way of knowing where the new string is, though.  Furthermore, if the string got moved, and the caller continues to use the string as if were still at source_offset, then that's a memory-use-after-free bug.

There are two possible remedies:

/**
 * s points to the address of the old and new string.
 */
string_insert(char **s, int insertion_pt, const char *to_insert)

or

/**
 * Returns the location of the new string, which may or may not be at
 * the original s.  Callers must assume that the string at s may be
 * invalid after this call.
 */
char *string_insert(char *s, int insertion_pt, const char *to_insert)


Multiple null Checks or try/catch NullPointerException

The problem with catching NullPointerException is “which one did you catch?”  A null can be returned from getGrandParent(), and using that return value without checking will cause the exception.  OR a bug in getGrandParent() might cause an exception while trying to find the parent’s parent, and you are obscuring the bug by assuming the NullPointerException results from a properly returned null value.

You can use Optional to properly capture the null and not call subsequent function.

Optional<Boolean> isRequired = Optional.ofNullable(context)
                          .map(Context::getGrandParent)
                          .map(GrandParent::getParent)
                          .map(Parent::getChild)
                          .map(Child::isRequired);

if (!isRequired.isPresent()) {
    LOG.error("Unable to determine if processing is required.");
} else if (isRequired.get()) {
    // continue with business logic
}

The Context::, GrandParent::, Parent::, Child:: class types are, of course, WAG's.  You'll need to supply the corrent types based on the type returned by the previous stage.

Alternately, you could use .getOrElse(Boolean.FALSE) at the end of the .map() chain.


Sort ObservableCollection after added new item

Your code unnecessarily sorts the whole collection on each insert (which is likely going to be O(n log n)). It also produces two events for each insert (one for Add and one for Move), which also isn't necessary.

What I would do:

Find the index where the inserted item belongs.
Insert the item at that index.

A simple implementation for that could look like this:

public static void AddSorted<T>(this IList<T> list, T item, IComparer<T> comparer = null)
{
    if (comparer == null)
        comparer = Comparer<T>.Default;

    int i = 0;
    while (i < list.Count && comparer.Compare(list[i], item) < 0)
        i++;

    list.Insert(i, item);
}

This could be made faster by using binary search to find the index. Though the total complexity is still going to be O(n), even with binary search, because Insert is O(n) (it has to move all items after the inserted item).

This means that using binary search would help the most if you're often inserting items at or near the end of the collection.

Other notes about your code:

public void UpdateSource(ObservableCollection<SomeType> source, SomeType newItem)

I don't think Update is the right name here, this is not a general update, something like AddToSource would be better.

source.OrderBy(_=>_.SomeProperty)

_ as a parameter name of a lambda is commonly used when you don't care about the value of that parameter. If you do care about it (like here), use something like x, or, even better, a meaningful name.


Check string having unique character or not without additional data structure

1. Function name seems to be misleading. It returns true if no repeating character is found, so I find isNonRepeatedUsingArray to be more appropriate.

2. Basic input checks - when I began trying your function, I set up a few tests (included in the final code) and some of them crashed. Your code should handle at least basic input values such as null, empty string, string with spaces.

public static boolean isNonRepeatedUsingArray(String inputStr) {
    if(inputStr == null || inputStr.isEmpty())
        return false;

    String s = inputStr.replaceAll(" ", "").toUpperCase();

    // other character stripping may be put here

3. Checking for duplicates - The algorithm itself can be improved by thinking in terms of set. I am not very familiar with Java language and I have used HashMap data structure, but the bottom idea is the following:

if current element is already in the set, it is a duplicate. Else add it to the set.

This solution also has the advantage that avoids hardcoding the number of allowed characters (26).

    Map<Character, Boolean> charDict = new HashMap<Character, Boolean>();
    for (int i = 0; i < s.length(); i++) {
        Character c = s.charAt(i);
        if (charDict.containsKey(c))
            return false;

        charDict.put(c, true);
    }

HashMap operations have a complexity of O(1), so function's overall complexity is O(n), where n is string length.

[edit]
Based on Bobby's correct observation, a HashSet is a better choice (elements only, no key and values):

    HashSet<Character> charSet = new HashSet<Character>();
    for (int i = 0; i < s.length(); i++) {
        Character c = s.charAt(i);
        if (charSet.contains(c))
            return false;

        charSet.add(c);
    }

4. Tests - it is a good habit to accompany a function with a test suite. It is particularly efficient when the code changes much (regressive testing) and helps to cover scenarios that are usually missed when developing (developers have a tendency to think in terms of making it work, not making it fail).

private static void printTestResult(String s) {
    boolean testRes = isNonRepeatedUsingArray(s);
    System.out.println("Repeating result for " + s + " is " + testRes);
}

public static void main(String []args){
    printTestResult("a");
    printTestResult("abcde");
    printTestResult("some random text");
    printTestResult("repeating");
    printTestResult(null);
}

The final code

import java.util.*;

public class HelloWorld{

    public static boolean isNonRepeatedUsingArray(String inputStr) {
        if(inputStr == null || inputStr.isEmpty())
            return false;

        String s = inputStr.replaceAll(" ", "").toUpperCase();

        Map<Character, Boolean> charDict = new HashMap<Character, Boolean>();
        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            if (charDict.containsKey(c))
                return false;

            charDict.put(c, true);
        }

        return true;
    }

    private static void printTestResult(String s) {
        boolean testRes = isNonRepeatedUsingArray(s);
        System.out.println("Repeating result for " + s + " is " + testRes);
    }

    public static void main(String []args){
        printTestResult("a");
        printTestResult("abcde");
        printTestResult("some random text");
        printTestResult("repeating");
        printTestResult(null);
    }
}


Static Methods for Dealing with Conversions from and to UTC

Using the String constant LOCAL_TIME_ZONE_STRING_REPRESENTATION, any user who wishes to compile the code can specify which time zone they want the code to run in, rather than it try to use Window's local time zone.

I think this is not the right way to provide flexibility. Lets say you sell your application to three different customers that want three different LOCAL_TIME_ZONE, then you'll have to compile the application three times. Do yourself the favor and place this as a setting in a configuration file or database. And what if the application is to be used world wide by a global customer? Do you plan to use the same time zone in all their offices?

    public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)
    {
        return TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE).ToUniversalTime();
    }

I don't think this is working correctly:

A DateTime object can either represent a local time which is always regarded as  local according to the system settings or a UTC time if created with kind = DateTimeKind.Utc - seen from the DateTime api.

Let say LOCAL_TIME_ZONE_STRING_REPRESENTATION = "GMT Standard Time"; and the system time zone = "Romance Standard Time" (+01.00).

Because TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE) converts from local time (Romance Standard Time), it converts

DateTime inputDate = new DateTime(2019, 3, 1, 15, 30, 0);

to

01-03-2019 14:30:00

and the call to ToUniversalTime() converts it further to:

01-03-2019 13:30:00

because this too anticipate the DateTime object to be in local time, which is "Romance Standard Time" and not "GMT Standard Time".

But if you - as you write in the explanation to the method - expect the input date time object to be in LOCAL_TIME_ZONE, no change should occur, because GMT = UTC.

To do it correctly I'll suggest this approach if the input DateTime object is still expected to be in LOCAL_TIME_ZONE:

public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)
{
  return TimeZoneInfo.ConvertTimeToUtc(dateAndTime, LOCAL_TIME_ZONE);
}

That said, if I were you, I would reconsider the whole setup thoroughly before using it in a larger scale. Dates, Times and globalization in general is rather complicated, so do yourself the favor to read and test a lot before taking a concept into use that is not just relying on the system. A place to start reading could be here.


Copy arbitrary number of bits at arbitrary offset from buffer to another buffer

I don't know how you could make it shorter or less complicated, hopefully someone else will provide you a few insights on that. I can comment on a few minor points that you might be interested in changing:

BITMASKU8 should preferably be a function. Such a short function would certainly to be inlined by the compiler, producing the same results as the macro you currently have. If you can't afford the chance of overhead, or your compiler is not capable of inlining, then you should at least #undef the macro name at the end of the file to clear the namespace.
In offset_bitcpy(), I see that you've nicely marked the variables that are initialized only once with const, this is a good practice, even for small functions/blocks, you never know how big they might grow in the future, after a few refactorings. But you did forget to mark std::uint8_t shift as const too, since it is never modified after being set.
Decide how you are going to handle invalid inputs. The only thing that can break your code is an ill-formed input in copy_lowbits_off(), such as a null pointer or a zero count. Decide which course of action should be taken in such cases. Just doing nothing is hardly a good choice. At least assert to facilitate debugging, or throw and exception if the caller should be responsible for handling the error.
Overall, I find your code too tightly packed. Blank lines before each comment inside copy_lowbits_off() would visually separate stuff in a more natural way, IMHO.


SimpleTwo obj = new SimpleTwo();

is unnecessary because all your properties and methods of SimpleTwo are static, therefore creating an instance of SimpleTwo does nothing unless you have something in it that's not static. I would also guess that lines with code like obj.age give you a compiler warning because you should be using SimpleTwo.age since age is a static member.

I would also change the names of the classes and the methods to something more meaningful. firstMethod doesn't describe what it is for and technically it is the second method in your class


Implementation of Javascript Classes and Inheritance

I read your code several times, and I could only find few observations:

jQuery has extend as well, the idea of it is sound, you could consider working with arguments and allow for n objects like jQuery does
I am not sure that always overriding the constructor is a good idea in extend
In the same vein, your approach does not allow for custom constructors that take parameters, whereas most OO classes have those ( new Customer( "Bob" ) to give a silly example)
From a lint perspective:

You declare var key thrice in extend, you only need to declare it once, preferably on top
for loop blocks do not need semicolons
You should really look into .hasOwnProperty(), I am pretty sure your code can cause subtle bugs by smushing everything together


PHP OOP - Does this database reading class make sense?

Why don't you split the "constructor" part and the "get the values" part?

Code :

class Database {

    protected $dbh;                 // Database handle connection

    public function __construct( $dbh) {
        $this->dbh          = $dbh;
    }

    public function getResults($columns,$table)
    {
        $resultSet = array();

        $read_database = $this->dbh->query('SELECT ' . implode(',' , $columns) . ' FROM ' . $table);
        while ($row = $read_database->fetch()) {
            foreach($columns as $column) {
                $resultSet[$column] = $row[$column];
            }
        }
        return $resultSet;
    }
}

Usage :

$db = new Database($dbh);
$db->getResults($columns, $table);


Global

You're hard coding the URL to your Mongo instance; it might be better to load it from a settings file. You're also not performing any authentication, though we'll assume that you have your firewalls properly set up, I guess. Some people prefer opening a new connection per request, up to you I guess. I would say that global variables suck, but if you don't think your program will expand beyond a single script, then it could be OK.

Static views

You could combine all of the static views fairly simply; have one view that captures everything matching <filename:re:.*\.(.+)> (or whatever the correct regexp would be), and then have a dictionary mapping from extensions to directories:

STATIC_DIRS = {
    "jpg": "static/images",
    "gif": "static/images",
    ... # etc
}

That said, I don't see the advantage of being able to do /foo.jpg over /static/images/foo.jpg. Also, you could always eliminate the entire set of views and just serve your static content straight from the Nginx/Apache instance that is reverse proxying your application.

Do Upload

I would strongly suggest you look into reading the file in chunks; as it is, your server would be trivial to DOS.

It might create nicer code if you reversed your if condition, so the code looked more like

@bottle.route('/upload', method='POST')
def do_upload():
    data = request.files.data
    if not data:
        return bottle.redirect("/")

    raw = data.file.read()  # This is dangerous for big files
    file_name = data.filename
    try:
        newfile_id = fs.put(raw, filename=file_name)
    except:
        return "error inserting new file"
    print(newfile_id)
    return bottle.redirect('/')

This is known as a guard statement, and they are very nice.

Avoid using try: ... except: ... without specifying the type of the exception you wish to catch. In this case, it's particularly bad as you are not even logging the error; someone could come along, shoot a bullet through the hard drive of the machine you were running this on, and your service wouldn't note that anything of interest had happened. I'd suggest that when a request fails, you return a non-200 status code; at the moment, your bullet ridden hard drive will not cause a single non-200 status code.

Download

If the file exists in Mongo, but not in the FS, currently you say document id not found for id. However, due to the except statement which doesn't specify exception types, your code also says that no matter what else goes wrong (recall the hard drive with a gun wound). I'd find out what class of errors come under the file not found category, and then treat them differently to others.

Currently, if the user looks up a file that doesn't exist, you return None, which I think bottle will complain about. It'd probably be better to add a guard clause along the lines of

if not file_id:
    # I don't know the bottle api for returning a particular status code, but something like this
    return bottle.abort(404)
... # otherwise serve the file

You don't handle the case that someone gives you a file you don't know the mimetype for, I'd recommend checking before you try and set the header.

General

It's best to include a guard at the bottom of the file so that you can import the file without starting the webserver. I'd modify the last few lines to read

if __name__ == '__main__':
    bottle.debug(True)
    bottle.run(host='localhost', port=8080)


I think this is one of those rare case where with hits its limits and you should be better served with a try: ... finally.
You can open the first file, and wraps the rest of the operations into a
try:
    # rest of the operations
finally:
    f.close()

Then, each time the fileName need to change, you f.close() and f = open(...) again. This way, you only close the file when you won't use it anymore.
As for the rest of the code:

use 4 spaces per indentation level
use snake_case for variable and functions names
use unpacking to extract and give a meaningful name to the 2 components of the items in your list
create pattern as a global variable as there is no added value to compile it each time you call createFileName
you can avoid copying d when you slice it if you use iter

Proposed improvements
import sys
import re

PATTERN = re.compile("[a-zA-Z]+")

def create_file_name(string, index, number_of_words, suffix):
    matches = [x.lower() for x in re.findall(PATTERN, string)]
    return '{:02}{}.{}'.format(index, '_'.join(matches[:number_of_words]), suffix)

if __name__ == "__main__":
    d = [("aaa", True), ("bbb x yyy aa" False), ("ccc aa", False), ("ddd bbb", True), ("eee ddd", False), ("fff x a b" True)] # this list of tuples is just for illustration, it will be usually much bigger.

    iterator = iter(d)
    file_index = 0
    name, _ = next(iterator)
    filename = create_file_name(name, file_index, 3, 'txt')
    f = open(filename, 'a')
    try:
        f.write(name + '\n')
        for name, new_file in iterator:
            if new_file:
                file_index += 1
                filename = create_file_name(name, file_index, 3, 'txt')
                f.close()
                f = open(filename, 'a')
            f.write(name + '\n')
    finally:
        f.close()


I would get rid of variables found and stop, and just return true on match, false after the body (which means there was no match). The reason is that you keep checking in the loop conditional their value; that's unnecessary computation.

Edit Actually, it would be even better if you returned the index of the found element instead of just a boolean value indicating whether the element is in the input array. In case there is no match, return a value that cannot be a valid array index, for example, -1.


Use C++ headers instead of C headers. Change #include <stdlib.h> to #include <cstdlib>. You could actually remove this header altogether because you really should not be calling exit() in this program.
Avoid using namespace std;. You are polluting the global namespace and increasing the probability of naming clashes. If you put using namespace std; into a header, you pollute the global namespace of every user that uses your header. Putting it into a CPP file is not as bad as putting it into a header, but the same dangers exist. See this link for more information.
Avoid using global variables when they are not necessary. You want to limit the scope of your variables as much as possible. This program can be rewritten to use no global variable at all.
Use appropriate function names. mainmenu() should be either main_menu() or MainMenu(), writetofile() should be either write_to_file() or WriteToFile(), etc.
Get rid of the unnecessary recursion. Recursion is very nice an clean in some situations. Unfortunately, it's very ugly in this situation. This program can be rewritten to use no recursion at all.
Learn about RAII. It is one of the most important aspects of the C++ language. In your writetofile function, you manually call writefile.close();. You do not have to do this. The std::ofstream will automatically clean up its own resources once it goes out of scope. This is one of the reasons why limiting the scope of your variables is important.
Learn about std::numeric_limits. While cin.ignore(10000,'\n'); should work in most cases, std::cin.ignore(std::numeric_limits <std::streamsize>::max(), '\n'); will work in more cases.

Now with that out of the way, let's see how we can rewrite this program.

Headers

#include <fstream>
#include <iostream>
#include <limits> // for std::numeric_limits
#include <string>

Create a function to get user input

We want to get rid of the ugly recursion that we have going on. One thing we can do is create a helper function that can read user input for various values. This is a function template. It can return ints, std::strings, and other variable types. If bad input is given to this function, then it asks the user to try again.

template <typename T>
T get_input(const std::string &strQuery)
{
    std::cout << strQuery << "\n> ";
    T out = T();

    while (!(std::cin >> out)) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits <std::streamsize>::max(), '\n');
        std::cout << "Error!" "\n";
        std::cout << strQuery << "\n> ";
    }

    return out;
}

Rewrite the mainmenu() function

First we will rename mainmenu() to main_menu(). Second we will use our new get_input() function. Notice that in C++, two string literals next to each other (such as "[1] Login" "\n") are automatically concatenated into one string literal by the compiler. Even if the string literals are on separate lines, as long as there are no semicolons or anything else between them, then the compiler will concatenate them. Using this strategy make your main_menu() class easier to read. Notice that we only need two switch cases. All other cases result in nothing being done.

void main_menu()
{
    int choice = get_input <int>(
        "Hello, Would you like to log in or register?" "\n"
        "[1] Login" "\n"
        "[2] Register" "\n"
        "[3] Exit");

    switch (choice)
    {
    case 1:
        login();
        break;
    case 2:
        register_user();
        break;
    }
}

Rewrite the login() function

This is a very small change. I add a newline to it.

void login()
{
    std::cout << "You are being logged in!" "\n";
}

Rewrite the registerme() function: Part 1

First, let's give it a better name. Let's rename this function to register_user(). This function does 3 things. It:

Gets a username.
Gets a password.
Saves the password to a file.

To make this function more readable, we will create 3 helper functions to perform each of these tasks.

Get the username

We will create a helper function that will get the username. We will use get_input() to avoid all of the ugly recursion that you have.

std::string get_username()
{
    std::string username = get_input <std::string>("Please enter a username.");
    std::cout << "Username: \"" << username << "\"\n";

    while (get_input <int>("Confirm? [0|1]") != 1) {
        username = get_input <std::string>("Please enter a username.");
        std::cout << "Username: \"" << username << "\"\n";
    }

    return username;
}

Get the password

We just have to make sure the passwords match. Once again, the get_input() function makes this clean.

std::string get_password()
{
    std::string password1 = get_input <std::string> ("Please enter your password.");
    std::string password2 = get_input <std::string> ("Please re-enter your password.");

    while (password1 != password2) {
        std::cout << "Error! Passwords do not match." "\n";
        password1 = get_input <std::string>("Please enter your password.");
        password2 = get_input <std::string>("Please re-enter your password.");
    }

    return password1;
}

Save the username and password

Now we need a function that can save the username and password. This one is pretty similar to your writetofile() function, except it is easier to read. It does require passing both the username and the password though.

void save_user(const std::string &username, const std::string &password)
{
    std::string filename = username + ".txt";
    std::ofstream file(filename);
    file << password << "\n";
}

Rewrite the registerme() function: Part 2

Now with those 3 helper functions implemented, we can write the new registerme() function (which we renamed register_user()). This turns your complicated function into a simple function that is easy to read.

void register_user()
{
    std::string username = get_username();
    std::string password = get_password();
    save_user(username, password);
}

Rewrite the main() function

Your main() function stays pretty much the same. Just call main_menu() instead of mainmenu() since we renamed the function.

All of it together

#include <fstream>
#include <iostream>
#include <limits>
#include <string>

template <typename T>
T get_input(const std::string &strQuery);

std::string get_username();
std::string get_password();
void save_user(const std::string &username, const std::string &password);

void login();
void register_user();
void main_menu();

int main()
{
    main_menu();
}

template <typename T>
T get_input(const std::string &strQuery)
{
    std::cout << strQuery << "\n> ";
    T out = T();

    while (!(std::cin >> out)) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits <std::streamsize>::max(), '\n');
        std::cout << "Error!" "\n";
        std::cout << strQuery << "\n> ";
    }

    return out;
}

std::string get_password()
{
    std::string password1 = get_input <std::string> ("Please enter your password.");
    std::string password2 = get_input <std::string> ("Please re-enter your password.");

    while (password1 != password2) {
        std::cout << "Error! Passwords do not match." "\n";
        password1 = get_input <std::string>("Please enter your password.");
        password2 = get_input <std::string>("Please re-enter your password.");
    }

    return password1;
}

std::string get_username()
{
    std::string username = get_input <std::string>("Please enter a username.");
    std::cout << "Username: \"" << username << "\"\n";

    while (get_input <int>("Confirm? [0|1]") != 1) {
        username = get_input <std::string>("Please enter a username.");
        std::cout << "Username: \"" << username << "\"\n";
    }

    return username;
}

void login()
{
    std::cout << "You are being logged in!" "\n";
}

void main_menu()
{
    int choice = get_input <int>(
        "Hello, Would you like to log in or register?" "\n"
        "[1] Login" "\n"
        "[2] Register" "\n"
        "[3] Exit");

    switch (choice)
    {
    case 1:
        login();
        break;
    case 2:
        register_user();
        break;
    }
}

void register_user()
{
    std::string username = get_username();
    std::string password = get_password();
    save_user(username, password);
}

void save_user(const std::string &username, const std::string &password)
{
    std::string filename = username + ".txt";
    std::ofstream file(filename);
    file << password << "\n";
}


On the whole this is nicely done for an application made during your first week of C programming. The functions are generally reasonably-sized, the code is comprehensible and the design decisions are understandable given the size and purpose of the application.
My remarks mostly center around improving the design to support new features and avoid bugs. The merit of many of my points may be negligible if you're never planning on adding to the application beyond what you have, but if you'd like to add (for example) even fairly unassuming improvements like an AI opponent or arbitrary board sizes, the current design would be pushed beyond its narrow limits.
Avoid globals
Your core state variables
int player = 1, choice;
int places[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

should all be scoped to main at minimum. The problem with the existing design is that all functions operating on these global variables are non-idempotent. This means they are unsafe in a multithreaded environment and modify state outside of themselves which makes the application difficult to reason about and may lead to bugs.
The parameterless functions in your original code creates an illusion of simplicity. But in reality these functions are quite unsafe and would inhibit a larger application significantly.
Encapsulate related data
int player = 1, choice;
int places[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

Are loose variables that are conceptually attributes of the same entity and as such should be grouped in a TicTacToePosition structure along with a set of functions that operate on this structure. This makes it easier to understand the purpose and relationship between these pieces of data. Taken out of context, a variable name like places has non-obvious purpose, but as a struct member, position.places or ttt_state.squares is a bit clearer.
Separate UI from game logic
If you want to generalize and expand on your code, you'll need to detach user interaction from game logic. Doing so makes the code maintainable and expandable through looser coupling.
There are many subtle manifestations of the strong UI-game logic coupling throughout the app, like:
int markBoard(char mark){
    for (int i = 1; i < 10; ++i) {
        //       ^
        if (choice == i && places[i]-48 == i) {
            //                      ^^^
            places[i] = mark;
            return 0;
        }
    }
    return 1;
}

In the above code, the 1-indexing seems to be a convenience measure to avoid having to normalize 1-indexed user input to internal logic. But this convenience leads to an awkward board design for the programmer and a confusing magic 'o' character at the 0-th index.
Additionally, -48 is a conversion between external UI and internal game logic that markBoard shouldn't be responsible for. The correct name for this function is convertFromUserInputCharAndMarkBoard, which is overburdened. Normalize/sanitize user input outside of the tic tac toe board logic. This lets you keep the interface user-centric while supporting an intuitive internal representation for the programmer.
switchPlayers does more than switch players: it also takes user input. Those are two distinct things that should be separate.
checkForWin does win checking but also does IO, a side effect. Better to just return the result and let the caller handle the IO. In fact, checkForWin is called twice in the main function, once to check for a win and the second time to display the winning player after clearing the screen.
UX
I recommend spelling out the input format more precisely and using X wins! or O wins! instead of You won!.
Instead of Player 1 and Player 2, using X and O throughout removes ambiguity and lets you avoid a layer of indirection by having to display/explain Player 1 (X) - Player 2 (O) which asks the user to mentally translate between multiple terms for the players.
Bad input into scanf spams the console and there are no error messages or handling to speak of. scanf isn't the right tool here; use fgets to pull the line in as a string and parse the number out of it.
I'm not really crazy about system("clear"). It feels invasive. If you're committed to this sort of interface, I'd go all in with curses. Or just keep it simple and keep printing without clearing.
Avoid convoluted logic
In checkForWin, the draw logic is somewhat hard to follow:
//Check for draw
for (int j = 1; j < 10; ++j) {
    if (places[j] - 48 != j)
        draw++;
}
if (draw == 9){
    printf("\t  Draw!\n");
    return 1;
}

Once again, the -48 is an artifact of user input conversion that really doesn't belong in the game engine. Instead of a player variable and this manual draw check logic, most two-player board games use a single number, ply, which counts the turn. A draw check then becomes ply >= length of board assuming is_won is called first, figuring out whose turn it is becomes ply % 2 and switching sides is ply++.
Ply can be used to avoid pointless win checks if not enough moves have been played. In tic tac toe, it seems like a minor optimization but it can speed up an AI that's running win checks thousands of times per turn, and it's a single extra line of code.
Consider breaking commented code out into functions
The checkForWin function has 4 distinct parts to it: checking horizontals, verticals, diagonals and draws. Each could be a separate function instead of delimiting the areas with comments. Otherwise, some of these loops could be merged and the logic simplified (it's debatable which is best).
Code style

Keep your braces consistent: void switchPlayers(){ should be void switchPlayers() {.

Use #include <stdbool.h>:
  if (draw == 9){
      printf("\t  Draw!\n");
      return 1;
  }

could then be
  if (draw == 9){
      printf("\t  Draw!\n");
      return true;
  }

which is easier for the programmer to understand.

Possible rewrite
While I'd prefer to use a bitboard and bitmasks to check win patterns, I think it's most instructive to keep the array format to avoid too radical of a departure from your design.
Feel free to accuse this code of being prematurely future-proof or anticipating adding AI and other features. Fair enough--it is more code. While I've gone somewhat deep into generalizing board sizes and so forth, you can cherry-pick the techniques that make sense for you and take the rest with a grain of salt.
Future steps might be adding a GUI, generalizing the board sizes with malloc or a FAM, adding an AI, adding a variant or network play.
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

struct TicTacToePosition {
    uint8_t ply;
    uint8_t board_len;
    uint8_t side_len;
    char board[3][3];
};

struct TicTacToePosition ttt_init() {
    struct TicTacToePosition ttt_pos = {};
    ttt_pos.board_len = sizeof ttt_pos.board;
    ttt_pos.side_len = sizeof ttt_pos.board[0];
    return ttt_pos;
}

char ttt_current_player(const struct TicTacToePosition *pos) {
    return pos->ply % 2 ? 'O' : 'X';
}

char ttt_last_player(const struct TicTacToePosition *pos) {
    return pos->ply % 2 ? 'X' : 'O';
}

bool ttt_is_board_full(const struct TicTacToePosition *pos) {
    return pos->ply >= pos->board_len;
}

bool ttt_legal_move(const struct TicTacToePosition *pos, int row, int col) {
    return row >= 0 && row < pos->side_len &&
           col >= 0 && col < pos->side_len && !pos->board[row][col];
}

bool ttt_try_move(struct TicTacToePosition *pos, int row, int col) {
    if (!ttt_legal_move(pos, row, col)) {
        return false;
    }

    pos->board[row][col] = ttt_current_player(pos);
    pos->ply++;
    return true;
}

bool ttt_line_win(const unsigned int len, const char *arr) {
    for (int i = 1; i < len; i++) {
        if (!arr[0] || !arr[i] || arr[0] != arr[i]) {
            return false;
        }
    }

    return true;
}

bool ttt_is_won(const struct TicTacToePosition *pos) {
    if (pos->ply < 5) return false;

    const uint8_t len = pos->side_len;
    char left_diag[len];
    char right_diag[len];

    for (int i = 0; i < len; i++) {
        char column[len];
        left_diag[i] = pos->board[i][i];
        right_diag[i] = pos->board[i][len-i-1];

        for (int j = 0; j < len; j++) {
            column[j] = pos->board[j][i];
        }

        if (ttt_line_win(len, pos->board[i]) || ttt_line_win(len, column)) {
            return true;
        }
    }

    return ttt_line_win(len, left_diag) || ttt_line_win(len, right_diag);
}

char ttt_fmt_square(const struct TicTacToePosition *pos, int i, int j) {
    return pos->board[i][j] ? pos->board[i][j] : i * pos->side_len + j + '1';
}

void ttt_print_board(const struct TicTacToePosition *pos) {
    puts("");

    for (int i = 0; i < pos->side_len; i++) {
        for (int j = 0; j < pos->side_len - 1; j++) {
            printf("   |");
        }

        printf("\n %c ", ttt_fmt_square(pos, i, 0));

        for (int j = 1; j < pos->side_len; j++) {
            printf("| %c ", ttt_fmt_square(pos, i, j));
        }

        if (i < pos->side_len - 1) {
            printf("\n___");

            for (int j = 1; j < pos->side_len; j++) {
                printf("|___");
            }
        }

        puts("");
    }

    for (int i = 0; i < pos->side_len - 1; i++) {
        printf("   |");
    }

    puts("\n");
}

int ttt_get_num(const char *failure_prompt) {
    for (;;) {
        int result;
        char buf[128];
        fgets(buf, sizeof buf, stdin);

        if (sscanf(buf, "%d", &result)) {
            return result;
        }

        printf("%s", failure_prompt);
    }
}

void ttt_get_move(struct TicTacToePosition *ttt_pos) {
    for (;;) {
        printf("Choose a square for %c's move: ",
               ttt_current_player(ttt_pos));
        int move = ttt_get_num("Invalid input. Try again: ") - 1;
        int row = move / ttt_pos->side_len;
        int col = move % ttt_pos->side_len;

        if (ttt_try_move(ttt_pos, row, col)) {
            break;
        }

        puts("Invalid move. Pick an empty square between 1 and 9.");
    }
}

void ttt_play_game() {
    for (struct TicTacToePosition ttt_pos = ttt_init();;) {
        ttt_print_board(&ttt_pos);
        ttt_get_move(&ttt_pos);

        if (ttt_is_won(&ttt_pos)) {
            ttt_print_board(&ttt_pos);
            printf("%c won!\n", ttt_last_player(&ttt_pos));
            break;
        }
        else if (ttt_is_board_full(&ttt_pos)) {
            ttt_print_board(&ttt_pos);
            puts("The game is a draw");
            break;
        }
    }
}

int main() {
    ttt_play_game();
    return 0;
}


Establishing parameters for a sales report, with default boolean and date values

You could reduce branching and improve readability by requiring the default for to_b to be explicitly stated.  (It seems a bit excessive to have a default for the default, don't you think?)

The branching is not my primary concern, though.  The constructor seems to have a very copy-and-paste pattern.  Metaprogramming could help here, I think.  It would be nice to write…

class Report
  include ActiveModel::Model
  include ParamAccessors

  date_param_accessor(:start_date) { |today| today - 7.days }
  date_param_accessor :end_date
  bool_param_accessor :show_sales, true
  bool_param_accessor :show_daily_active_users, false
  bool_param_accessor :show_registered_cc, false
  bool_param_accessor :show_all_time_registered_cc, false
  bool_param_accessor :show_users, false

  def initialize(params)
    @params = params
  end

  def sales
     …
  end
end

This mixin could make that possible:

module ParamAccessors
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def date_param_accessor(name, default=nil)
      attr_writer(name)
      define_method(name) do
        if instance_variable_defined?("@#{name}")
          instance_variable_get("@#{name}")
        else
          @params.fetch(name, default) or
          (yield Time.zone.today if block_given?) or
          return Time.zone.today
        end
      end
    end

    def bool_param_accessor(name, default)
      attr_writer(name)
      define_method(name) do
        if instance_variable_defined?("@#{name}")
          instance_variable_get("@#{name}")
        else
          @params.fetch(name, default)
        end
      end
    end
  end
end

This assumes that the object is transient, such that the constructor and the start_date/end_date methods will be called on the same day.


DOM
The outer HTML conversion is probably unecessary. You can manipulate DOM nodes directly. The appending could look something like this.
// note that the HTML representation is irrelevant; we go straight to the DOM
document.getElementById('input-groups').appendChild(ageCol)

JS
addInputGroup() seems to be a misleading name, as the function creates a new DOM element; it doesn't do anything with it. createInputGroup() would be more appropriate I think.
You can use const instead of let here. This provides some nice guarantees about consistency, and makes these guarantees immediately visible to the reader.
return(ageCol.outerHTML); is more commonly written as return ageCol.outerHTML;


Properly mark up multiple person using schema.org microdata

Microdata / Schema.org

Your use of Microdata and the Schema.org vocabulary is fine.

To specify multiple directors, you have to provide multiple director properties, which your loop seems to achieve:

…
…
…

To specify a URL value, you have to use a suitable link element (with href or src attribute), like a, link, img etc. So your use of the a element achieves this.

I prefer using http Schema.org URIs (reasons why), but using https is fine, too.

HTML

Is this h3 really the heading for a section of content? If yes, your markup is fine. But then you might want to add a textual delimiter (like ,) to separate the conductor names.

If the section should just specify the conductors, and there is no other content under its scope, the h3 should just be something like "Conducted by", with the list of conductors under its scope:

Conducted by

…

…

…

Headings should not be used for content just because this content is important. h1-h6 don’t represent important content, they represent "headings for their sections". There is typically no case where you should have a heading without any content in its section.


Best practice to initialize instance variables for a POJO when values are null

Multiple facets to this answer:

First, direct responses to the given approaches

1.

Initializing fields with a value, only to reinitialize them in a constructor is not useful - skimming the class, which will be done in time, would lead to confusion. When initializing values with defaults, it would be better to modify them using setters.
The empty String may, however, not be a good default. A Constructor is supposed to instantiate an Object in a way that it can be used - however, a user without a user id appears relatively useless.

2.

This approach is better, but the concepts are not cleanly understood.
First off, Clean Code does not argue against ternaries in general. Ternary operations can be very useful, if utilized correctly. The way you use them here is not a good way to use a ternary. This however is

private static <T> T valueOrDefault(T value, T default) {
  return value != null
    ? value
    : default;
}

This is a ternary which is instantly understandable, as it is entirely alone, and formatted in a way that it makes understanding easier.
This is also a suggestion to use here, as declaring this method within the User class allows for the following constructor:

public User(AuthUser authUser, Set<String> roles) {
  this.userId = valueOrDefault(authUser.getUserId(), "");
  // omitted
}

While this is very readable in both constructor and utility method, it is also technically overengineered here, as the use of generics is not necessary in this case, it merely removes the need to declare two extremely similar functions.

3.

Do not use Optional like this. Optional has a very specific and limited use, which is as a return type on specific methods and function calls.
Also, while this is one way to remove a redundant get-call, this also adds a rather large amount of unnecessary overhead, plus it is much less readable than the second approach.
This reduced readability and increased overhead in comprehension and execution remains even if the formatting in improved for readability.

4.

This is the most acceptable approach in general, however this is only true if the necessary dependencies are already present on the classpath. Adding commons-lang for null-checks only is, while technically adhering to the KISS principle, too much cost for effect.

Second: Considerations

Is this an Object or a data structure? Right now, it is technically speaking both, which is inherently problematic. See here for some explanations, the mentioned book would help you more though.

Considering the construction approach: the constructor seems to copy fields from object a, which is also a kind of user, and append a Set of Strings to the object. So it is neither a copy constructor nor a plain constructor. This is in so far confusing that, when described from a more distanced view,
the User is instantiated by passing a User and Roles. The Passed User is not present in the User Object, but some fields of it are.
If you find this sentence confusing: people who read your code will most likely think along these lines. At least, I do, as I always try to simplify as much as possible.

As this kind of construction CAN be confusing, it may be useful to create a Mapper or Converter accepting AuthUser and Set<String> and returning User. This would separate the data structure from the logic, and it would allow more validation logic to happen without bloating the user object.

This would also allow the user to be a @Value-class, meaning no setters and all fields final, which makes this object almost immutable and easy to share - almost as the Set still can be modified.

Third: the null-problem

Is null really the same as the empty String in case of id, name and email? And, are "no roles" the same as null?
null in java is, despite the dreaded NullPointerException, a very useful value, and replacing it with "I don't want to do null check"-defaults is rarely a good idea.

It would actually be better practice to not modify the values at all and take them at face value, as that allows you to determine if there was an error during authentication or data binding (as data binding errors often lead to empty strings, while authentication errors fail to instantiate objects correctly).

Try to incorporate null-values into your application as valid values - for example as validation values, or as markers for errors.

Also, for good measure, never allow or return null where Collections, Maps, arrays or other similar objects are expected, as effectively no one expects these to be null.


I think there is a mistake, this line is defined twice (line 28):

self.check_box2.stateChanged.connect(self.onStateChange)

Therefore the event onStateChange is triggered twice when you check check_box2, which is logical.

I think you did a copy paste and the last should be check_box3. But your naming conventions are not intuitive, give your objects some more meaningful names, otherwise how are you going to tell the difference from your code.

If what you want is mutually exclusive checkboxes the implementation could be more straightforward. Personally I prefer to use radio buttons like in plain HTML because this is more intuitive (it is immediately obvious that only one answer is allowed).

First approach: a generic method that loops on the checkboxes in your form and unchecks all of them except the sender. Then you can simplify code and get rid of if/elif

Second approach: use QT built-in features. You could wrap your checkboxes in a QButtonGroup container.

  A rectangular box before the text label appears when a QCheckBox
  object is added to the parent window. Just as QRadioButton, it is also
  a selectable button. Its common use is in a scenario when the user is
  asked to choose one or more of the available options.

  Unlike Radio buttons, check boxes are not mutually exclusive by
  default. In order to restrict the choice to one of the available
  items, the check boxes must be added to QButtonGroup.

and:

  As mentioned earlier, checkBox buttons can be made mutually exclusive
  by adding them in the QButtonGroup object.

self.bg = QButtonGroup()
self.bg.addButton(self.b1,1)
self.bg.addButton(self.b2,2)

  QButtonGroup object, provides abstract container for buttons and
  doesn’t have a visual representation. It emits buttonCliked() signal
  and sends Button object’s reference to the slot function btngroup().

Source: PyQt - QCheckBox Widget


Rot and polyalphabetic ciphers in Python 2.7

rotInt, letters, length are defined in class. Use it.

Instead of for loop use map.

def rot(self, string, letters=None, rotInt=None):
    if letters is None:
        letters = self.letters
    length = len(letters)
    if rotInt is None:
        rotInt = self.rotInt
    return ''.join(map(lambda letter: letter in letters and letters[(letters.index(letter) + rotInt) % length] or letter, string))

and or

It's like bool ? a : b in C / C++. It's equivalent to:

if bool:
    return a
else:
    return b


Return the product of the pythagorean triplet if a+b+c == 1000

Don't use std::pow(n, 2) to square an integer - not only is it slower than n*n, it's much less accurate (so you'd want to add 0.5 before assigning to c, to round to nearest).

Instead of computing c as the hypotenuse of triangle (a,b,c), it's simpler to take c as 1000-a-b, then check if that makes a right-triangle:
        c = 1000 - a - b;
        if (a*a + b*b == c*c) {
            return a*b*c;
        }

Look, no <cmath>!

We can reduce the limits of our search, by noting that a can't be as much as 500 (because a < b and a+b < 1000):
for (a = 1;  a < 500;  ++a) {
    for (b = a+1;  b < 1000-a;  ++b) {
        c = 1000 - a - b;

Keep your types consistent.  You seem to be aware that int is only guaranteed to be able to hold values up to 32,767, so that's obviously the wrong choice for c and for the result.  But it's also the wrong choice for a and b, because expressions such as a*b can overflow (500*500 = 250,000), so that computing the return value could be Undefined Behaviour.  The best approach is to use one of the fixed-size types defined in <cstdint> for all three quantities - I recommend std::uint_fast32_t for this.

Make sure you return a value even if no match was found.  At present, we just run off the end of the function (and get a compiler warning, so we have no excuse for missing that).  We can safely return zero to indicate "no match", as that could never be the result of a successful search.

Modified code
#include <iostream>
#include <cstdint>

std::uint_fast32_t pythagoreanTriplet()
{
    for (std::uint_fast32_t a = 1;  a < 500;  ++a) {
        for (auto b = a+1;  b < 1000-a;  ++b) {
            auto c = 1000 - a - b;
            if (a*a + b*b == c*c) {
                return a*b*c;
            }
        }
    }
    return 0;                   // not found
}

int main()
{
    std::cout << pythagoreanTriplet() << std::endl;
}

Exercise
Instead of hard-coding the target sum 1000, pass it as a parameter to your function.


Your code is very clear and nicely written. Also, using a TreeMap to take advantage of ordered keys is great insight.

Overall, I practically only have good comments about the code:

Throwing an IllegalArgumentException in case of a negative or greater than 3000 number is a great way to document the fact those values are not allowed.
The recursive method toRomen handles all the case correctly. You made a small typo in the name of the method: it should be toRoman instead of toRomen.
Coding against the NavigableMap interface and hiding the TreeMap concrete instantiation inside a method is a nice thing to do.
Using a cache might indeed be a good idea: it helps to ensure that the same roman numerals are not converted each time and, since we're only interested in 3000 numbers at maximum, this map won't become gigantic and consume a lot of memory.

I still have a couple of suggestions:

You are currently handling the number 0 in a special early return inside getRomanNumeral with:

if (number == 0) {
    return "";
}

This isn't strictly needed. You have done that because toRomen doesn't handle 0 as input. Handling 0 could be done inside toRomen instead. Consider the following:

private static String toRoman(int num) {
    if (num == 0) {
        return "";
    }
    int floorNum = NUMBER_TO_ROMAN.floorKey(num);
    return NUMBER_TO_ROMAN.get(floorNum) + toRoman(num - floorNum);
}

Now the method toRoman has a clear-cut base case: when the number given is 0, we return an empty String. This also takes care of the recursive call with num - floorNum when both are equal: we will fall under this case and return the empty String.
With the above change, getRomanNumeral now becomes:

public String getRomanNumeral() {
    String result = CACHE.get(number);
    if (result != null) {
        return result;
    }
    result = toRomen(number);
    CACHE.put(number, result);
    return result;
}

We could use methods introduced in Java 8 to make this shorter. Mainly, we're interested in the computeIfAbsent(key, mappingFunction) method here. This method will return the currently mapped value to the given key, or invoke the given mapping function if there are no mapping. Therefore, we can simply have here:

public String getRomanNumeral() {
    return CACHE.computeIfAbsent(number, RomanNumeral::toRoman);
}

When the cache already contains the value for number, it will be returned directly. Otherwise, the method toRoman will be invoked by giving it the number as parameter, the cache will be updated with the value returned by the function and this value will be returned.


This:

maybeStringToMaybeDouble x = do
      y <- x
      maybeRead y

Could be:

maybeStringToMaybeDouble x = x >>= maybeRead

Similarly,

safeHead m = do
    x <- m
    listToMaybe x

Could be

safeHead m = m >>= listToMaybe

Or we could remove these functions entirely and just write

rpn xs = foldM foldingOp [] (words xs) >>= listToMaybe >>= maybeRead

It seems strange that we're importing Network.CGI.Protocol for maybeRead. I would suggest using readMaybe from Text.Read instead.

There's a chance to use isJust here:

matches' :: Regex -> String -> Bool
matches' r x
   | matchRegex r x == Nothing = False
   | otherwise                 = True

matches' :: Regex -> String -> Bool
matches' r x = isJust $ matchRegex r x

We can do away with six functions by rewriting foldingOp like this:

foldingOp :: [String] -> String -> Maybe [String]
foldingOp acc s
   | isNumber s = Just (s : acc)
   | s == "+"   = performOp Add acc
   | s == "-"   = performOp Subtract acc
   | s == "*"   = performOp Multiply acc
   | otherwise  = Nothing

And we can simplify further by removing the Operator type:

foldingOp :: [String] -> String -> Maybe [String]
foldingOp acc s
   | isNumber s = Just (s : acc)
   | s == "+"   = performOp (+) acc
   | s == "-"   = performOp (-) acc
   | s == "*"   = performOp (*) acc
   | otherwise  = Nothing

performOp :: (Double -> Double -> Double) -> [String] -> Maybe [String]
performOp o (x:y:zs) = Just $ doOp o x y : zs
performOp _ _        = Nothing

doOp :: (Double -> Double -> Double) -> String -> String -> String
doOp op a b = show $ (read b :: Double) `op` (read a :: Double)


Pretty print with unit and physical suffix

Use better variable naming, with proper vocabulary.  In particular, "significand" is the term to use instead of nx.
You multiplied some intermediate result by 3 to obtain e.  Then you immediately do idx = int(e/3) + …, which represents wasted work.  More importantly, clarity suffers.  I suggest replacing e with power_of_1000 = int(math.floor(math.log10(x) // 3)), whose intent is much clearer.
You can take advantage of the fact that negative indexes count backwards from the end of a list.
There should be a Space in front of each prefix for consistency with the '*10^%d ' format.

import math

def eng_format(x, unit=''):
    # U+03BC is Greek lowercase mu
    UNITS = [' ', ' k', ' M', ' G'] + \
            ([None] * 10) + \
            [' f', ' p', ' n', u' \u03bc', ' m']

    power_of_1000 = int(math.floor(math.log10(x) // 3))
    exponent = 3 * power_of_1000
    prefix = UNITS[power_of_1000]
    if prefix is None:
        prefix = '*10^%d ' % exponent

    significand = x * 10**(-exponent)
    return '%.2f%s%s' % (significand, prefix, unit)


Construct a numpy array by repeating a 1 dimensional array sliced at different indices

Enter pandas.cut. It returns the bin in which each event lies. You can even pass the labels directly. This way you can reduce it to a Python loop over the people:
import pandas as pd
import numpy as np

age_bins = range(59, 70)   # one more than the probabilities
death_prob = [0.005925, 0.006656, 0.007474, 0.008387, 0.009405, 0.010539, 0.0118,
              0.013201, 0.014756, 0.016477]

policy_holders = {'John' : 65, 'Mike': 67, 'Alan': 71}

values = {name: pd.cut(range(age, age + 101), age_bins, labels=death_prob)
          for name, age in policy_holders.items()}

out = pd.DataFrame(values, dtype=np.float64).fillna(1)
print(out)

#          John      Mike  Alan
# 0    0.010539  0.013201   1.0
# 1    0.011800  0.014756   1.0
# 2    0.013201  0.016477   1.0
# 3    0.014756  1.000000   1.0
# 4    0.016477  1.000000   1.0
# ..        ...       ...   ...
# 96   1.000000  1.000000   1.0
# 97   1.000000  1.000000   1.0
# 98   1.000000  1.000000   1.0
# 99   1.000000  1.000000   1.0
# 100  1.000000  1.000000   1.0
#
# [101 rows x 3 columns]

Note that the hin edges need to be one larger than the labels, because technically, this is interpreted as (59, 60], (60, 61], ..., i.e. including the right edge.


Coding conventions

It is more customary to put one space character before and after a binary operator. So instead of a=1, you should write a = 1.
int low=0,high,n,i,a[100]; This is not easy to read, so instead, declare each variable on its own row:

    int low = 0;
    int high;
    .
    .
    .

Implementation

new_array[100] This substantially limits your implementation. Of course, in C, you can always overflow it, but it may rewrite relevant data or terminate your program altogether in case your process references a memory location it may not.
mid=(low+high)/2; This is a minor nitpick, yet some people suggest writing mid = low + (high - low) / 2. That may avoid overflowing low + high in some (super rare) cases.

General comments

Otherwise, your implementation looks reasonable as you don't write an if hell some novices tend to.

Summa summarum

After mainly correcting the style issues, you may come out with something like this:

#include<stdio.h>
#include<stdlib.h>

void merge(int* a, int low, int mid, int high)
{
    int i = low;
    int j = mid + 1;
    int k = 0;
    int m;

    int* new_array = malloc(sizeof(int) * (high - low + 1));

    while (i <= mid && j <= high)
    {
        if (a[i] < a[j])
        {
            new_array[k++] = a[i++];
        }
        else
        {
            new_array[k++] = a[j++];
        }
    }

    while (i <= mid)
    {
        new_array[k++] = a[i++];
    }

    while (j <= high)
    {
        new_array[k++] = a[j++];
    }

    for (m = low, k = 0; m <= high; m++, k++)
    {
        a[m] = new_array[k];
    }

    free(new_array);
}

void my_mergesort(int a[], int low, int high)
{
    int mid;

    if (low < high)
    {
        mid= low + (high - low) / 2;
        my_mergesort(a, low, mid);
        my_mergesort(a, mid + 1, high);
        merge(a, low, mid, high);
    }
}

int main()
{
    int high;
    int n;
    int i;
    int a[100];

    printf("Enter the lenght of array\n");
    scanf("%d",&n);
    high = n;

    printf("Enter the array that you want to sort\n");

    for(i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }

    my_mergesort(a, 0, n - 1);

    printf("The sorted array is \n");

    for (i = 0; i < n; i++)
    {
        printf("%d ",a[i]);
    }

    puts("\n");
    return 0;
}

Hope that helps.


When it comes to multidimensional vectors I usually suggest two approaches.
1. vector/array (C++11 and later)
This only works, when the inner dimensions are fixed and only the outer is runtime dynamic. In the end it comes down to something like this:
std::vector<std::array<T, N>> field;

In your case a Vector3d would either derive from std::array<double, 3> or contain one.
2. simple vector
This approach simply creates a one dimensional vector with X * Y size.
The element (x, y) can then be addressed with vec[y * X + x]. This works also with the older C++ standard. Although I think this solution might not work in your setup.
Bonus
I just want to highlight @Yakk's comment. Your Vector3d could look like this:
class Vector3d
{
public:
    // stuff
    // ...
private:
    double components_[3];
};

This way the memory would also be contigous.


Finding the longest word without these characters

The code is not bad as it stands, but I think there are some things that could be improved.

Think of the user

The input file name and unwanted letters are all hardcoded at the moment.  It would be nice if the user could specify one or both of these parameters on the command line.

Add error handling

There is almost no error checking or handling.  It's not hard to add, and it makes the program much more robust.  Here's how the start of main might look:

int main(int argc, char *argv[]) {
    if (argc != 2) {
        puts("Usage: longword filename");
        return 0;
    }
    FILE* fp;
    fp = fopen(argv[1], "rb");

    if (!fp) {
        perror("couldn't open words file");
        return 3;
    }
    size_t length = 5000000;
    char *buffer = malloc(length);
    if (buffer == NULL) {
        perror("couldn't allocate memory");
        return 2;
    }
    length = fread(buffer, 1, length, fp);
    if (ferror(fp)) {
        perror("couldn't read file");
        free(buffer);
        return 1;
    }
    // rest of program here
    free(buffer);
}

Consider using standard library functions

At a very small performance penalty (as measured on my machine), one could write a very clean version using only standard functions:

char *longest = NULL;
int longestlen = 0;
char *word = strtok(buffer, "\n");
while (word) {
    const int len = strlen(word);
    if (len > longestlen) {
        if (strpbrk(word, "gkmqvwxzio") == NULL) {
            longestlen = strlen(word);
            longest = word;
        }
    }
    word = strtok(NULL, "\n");
}
printf("%s\n", longest);

That is the way I'd probably write it unless there were some compelling reason that's not fast enough.

Use functions

Your is_legal function is not bad, but I'd also write a get_word_len function to fetch the length of the next word in the buffer.

static inline int get_word_len(const char *buff, const char *end) {
    int len = 0;
    for ( ; *buff != '\n' && buff < end; ++buff, ++len)
    {}
    return len;
}

Use const where practical

The is_legal function doesn't alter the passed string, so that parameter should be const.

Think carefully about the problem

The current code might print the word followed by \n, but if the words doesn't happen to be the first in the file, it will also print the \n from the previous word.  It's not necessarily wrong, but it's not consistent.

Use bool for boolean values

The implmentation of bool is in <stdbool.h> and should be used as the return type of is_legal.

Use only the required headers

In this program neither <stddef.h> nor <unistd.h> appear to be needed; I'd recommend omitting them and only including headers that are actually needed.

Consider using pointers

There may not be a performance difference in this case, but for problems like these, the use of pointers seems more natural to me.  For example:

const char *end = buffer + length;
const char *longest = buffer;
int longestlen = 0;

for (const char *curr=buffer; curr < end;  ) {
    const int wordlen = get_word_len(curr, end);
    if (wordlen > longestlen) {
        if (is_good_word(curr, wordlen)) {
            longestlen = wordlen;
            longest = curr;
        }
    }
    curr += wordlen + 1;
}
printf("%.*s\n", longestlen, longest);

Here, is_good_word is like your is_legal function:

static inline bool is_good_word(const char *curr, int wordlen) {
  static const char* bad = "gkmqvwxzio";
  for ( ; wordlen; --wordlen) {
      char ch = tolower(*curr++);
      for (const char *badptr = bad; *badptr; ++badptr) {
          if (ch == *badptr) {
              return false;
          }
      }
  }
  return true;
}

Don't leak memory

The program allocates but does not free the buffer space.  Yes, the operating system will clean up after you, but a free costs very little and allows for better memory leak checking with tools like valgrind.


Certainly found the alternative (2nd version) immediately understandable.  Not so with the first (both simplified below).  The 2nd maps directly to the stated requirement "exits early and returns false if any call fails".  This alone gives it a strong preference.

int success = 1;
....
success = success && func1();
success = success && func2();
success = success && func3();
....

versus

if (!func1()) {
  return 0;
}
if (!func2()) {
  return 0;
}
if (!func3()) {
  return 0;
}
....

Minor: Why isn't the first success = success && func1(); vs. int success = func1();.  Just to maintain symmetry?

Why use int instead of bool?  Portability?  If C99 or later available as the minimum standard, better to use bool.

The success approach may have merit in select circumstances yet do not see that called for here.  I would opt for the if () style as it matches the scant coding requirements.


Small implementation of a singly-linked list in C89

init_list

should really initialize the list. Otherwise you are forcing the caller to make an non-obvious memset.

void init_list(linked_list * list) {
    list->head = 0;
    list->size = 0;
}

is much more clean.
add_last

is not a particularly good name. Traditionally this operation is called append or push_back.

The function can be streamlined. First, assert your invariant fully (that is either head == 0 and size == 0 or head != 0 and size > 0) and immediately.

Second, once the invariant is deemed correct, allocate the node (you need to do it anyway). It is a good idea to delegate node allocation to a function.

Finally, find the tail (it is also a good candidate to factor out into a function), and attach the node. For example,

void append (linked_list * list, int32_t item)
{
    assert(list_is_good(list));
    linked_list_node * node = create_list_node(item);
    linked_list_node * tail = find_list_tail(list);
    if (tail == NULL) {
        list->head = node;
    } else {
        tail->next = node;
    }
    list->size += 1;
}

malloc may fail

Test the results of malloc. There is not much you can do once it fails, but it is good form anyway.


Validation/error handling of user input values

I question your use of exceptions to catch the invalid input. Exceptions are supposed to be used for exceptional situations. Validating user input is part of the normal functionality of the program, not an exceptional situation. It's on the lazy side to use exceptions here; you're basically treating it as a goto.

When you do use exceptions, you should probably create a new class that's derived from one of the standard exception classes, and throw/catch that instead of the one from <stdexcept>.

I also think that when you fail, you should inform the user of that, reset the input stream, and give them another chance, rather than just exiting.

Also, sure this is just a toy, but in a real program you should separate the business logic of your program from the input and output. You might want to plug the business logic into adapters that get input from a different place and/or send the output to a different place.


I’ll start with a meta comment:

Python (and production code) emphasis readability. There are several parts of your code which are quick difficult to read, or work out what they’re for (more details below). In production code, we don’t just want speed and reliability – we also want code that somebody else can debug in a year, who’s never seen it before. Try to write something that’s easy to follow.

Then a few style comments:

I prefer to list module imports (after grouping them per PEP 8’s recommendations) in alphabetical order. If you have a long list of module imports, this makes it much easier to quickly see whether a module has been imported, or find duplicate imports.
Quoting PEP 8 on line length:

  Limit all lines to a maximum of 79 characters.

The line which defines ret is 126 characters long, which means I can't see it without scrolling off the screen. Ick.

More general comments:

Add comments and docstrings. I don’t know what any of this code does, and even if I work it out, I don’t know why you wrote it that way. For example, what does the ping function return, and why are you passing all those flags to the ping utility?
Use better variable names. A few examples:

I expect a variable named host_list to be a list, but it’s actually a dict.
In production code, I steer clear of single-character variable names like p. Fine in small scripts, but it’s a pain to grep for later.
I’d change the name of the ping function so it can be discussed unambiguously from the command-line ping utility.

I wouldn’t accept these variable names in “production code”.
Not everything is encapsulated in a function. The ping function provides a nice wrapper around the ping utility, but checking the list of hosts is handled at the main level. Wrap this in a function that takes a list of hosts, and returns a list of alive/dead. That makes it easier to reuse this code later.

Then wrap the testing of this particular list of hosts in a main() function, and use the if __name__ == '__main__': main() construction. More portable.
You assume the list of host names is correct. If I drop in something that clearly isn’t a hostname (for example, '127.0.0.1 notahostname' into the hosts tuple), I get a non-zero return code from the subprocess call, but it’s not because that host is dead – it’s because it’s nonsensical.

I would consider storing the return code from each host: this is a much more useful indicator of what’s happened. Alternatively, you could check that hostnames are valid before you pass them in – this Stack Overflow answer looks like it might be useful.
There seems to be duplication of data in host_list and host_stat. I’m really not sure what the point of having both of these dictionaries is. Why not just start with empty lists in host_stat?
That list comprehension is too complicated. Not only is it too long (86 chars), but it’s not immediately obvious what it does. Break it down across multiple lines (remember, Python emphasises readability).
Using /dev/null to throw away the output from subprocess is platform-specific. It’s better to use os.devnull, which should work on non-Unix systems. (from How to hide output of subprocess in Python 2.7)

Four woolier comments:

Are the keys and values of host_stat the right way round? Once you have a dict of host availability data, I’d imagine you’re going to go through the list of hosts one-at-a-time and check if they’re available. For that, surely having the keys be the hostnames makes more sense (but that’s just me).
Why is hosts a tuple? I'd make it a list instead. Also, break it across multiple lines (see below).
I don’t see the value of multiprocessing here. Perhaps if you’re doing it for lots of hostnames, but otherwise I wouldn’t bother.
What do you need logging for? The only thing that might be useful is the return code from ping, but since you’re throwing that away, I’m not sure what you think you’d like to log.

With those comments in mind, here's how I'd rewrite your script:

import os
import subprocess

def ping_return_code(hostname):
    """Use the ping utility to attempt to reach the host. We send 5 packets
    ('-c 5') and wait 3 milliseconds ('-W 3') for a response. The function
    returns the return code from the ping utility.
    """
    ret_code = subprocess.call(['ping', '-c', '5', '-W', '3', hostname],
                               stdout=open(os.devnull, 'w'),
                               stderr=open(os.devnull, 'w'))
    return ret_code

def verify_hosts(host_list):
    """For each hostname in the list, attempt to reach it using ping. Returns a
    dict in which the keys are the hostnames, and the values are the return
    codes from ping. Assumes that the hostnames are valid.
    """
    return_codes = dict()
    for hostname in host_list:
        return_codes[hostname] = ping_return_code(hostname)

    return return_codes

def main():
    hosts_to_test = [
        '127.0.0.1',
        'google.com',
        '127.0.0.2',
        '10.1.1.1'
    ]
    print verify_hosts(hosts_to_test)

if __name__ == '__main__':
    main()


Components should hold information, that is / can be different from one instance to another; in your example hardcoded ExitData values with conjunction of creating new instances on each get call make it little different to just using a global field. Frankly I am not sure if Exit should even be a system as such.

Your systems should be getting components in packs (grouped by entity) from common pool (instead of creating it each for it self), and then depending on the kind of components there are in said pack, do something with them or not.

I don't understand what your entities list is supposed to do, you don't use it. Also you put values by value, but retrieve by index, which smells like a bug.

I think your problem is that you chose a bad testing case. Something more appropriate would be:

Make Position (with x and y fields) and Velocity (with xvel and yvel) components.
Make Velocity System, which in update loop for entities with Position and Velocity components does x += xvel; y += yvel;
Make 'Render' System, which simply prints Position values.
Add entities, which all have Position component, optionally have Velocity component, and the starting values of the components is different.

This way you would test against systems interacting on components from same pool, systems choosing to work against component set that matches criteria, grouping components by their entity.

--

By saying Your systems should be getting components in packs (grouped by entity) from common pool (instead of creating it each for it self) I meant to say there is no composition relation between systems and components. Your systems should not have components directly attached to it.

Here is minimal example of ECS with the position, velocity and 'rendering' components. It is not optimized, lacks encapsulation, manager misses few methods (at the very least deleteEntity), but I hope it captures the spirit in least lines of code possible.

public class Component {

    public final static int POS = 1 << 0,
                            VEL = 1 << 1,
                            RENDER = 1 << 2;

    public static class Velocity {
        float velx, vely;
    }

    public static class Position {
        float x, y;
    }

    public static class Rendering {
        String name; // for sake of having at least one field inside.
    }
}

--

public class Systems {

    public static class Velocity {
        public void update(EntityManager manager) {
            int required_components = Component.POS | Component.VEL;
            for (int i = 0; i < manager.size; i++) {
                if ((manager.flag[i] & required_components) == required_components){
                    manager.pos[i].x += manager.vel[i].velx;
                    manager.pos[i].y += manager.vel[i].vely;
                }
            }
        }
    }

    public static class Render {
        public void update(EntityManager manager) {
            int required_components = Component.POS | Component.RENDER;
            for (int i = 0; i < manager.size; i++) {
                if ((manager.flag[i] & required_components) == required_components) {
                    System.out.println(String.format("%s: (%f x, %f y)", manager.rendering[i].name, manager.pos[i].y, manager.pos[i].y));
                }
            }
        }
    }

}

--

public class EntityManager {
    public int flag[];
    public Component.Position pos[];
    public Component.Velocity vel[];
    public Component.Rendering rendering[];
    public final int size;

    public EntityManager(int size) {
        this.size = size;
        pos = new Component.Position[size];
        vel = new Component.Velocity[size];
        rendering = new Component.Rendering[size];
        flag = new int[size];
    }

    public int createEntity(int flag) {
        for (int i = 0; i < size; i++){
            if (this.flag[i] == 0) {
                this.flag[i] = flag;
                if ((flag & Component.POS) > 0) pos[i] = new Component.Position();
                if ((flag & Component.VEL) > 0) vel[i] = new Component.Velocity();
                if ((flag & Component.RENDER) > 0) rendering[i] = new Component.Rendering();
                return i;
            }
        }
        return -1;
    }
}

--

public class GameContainer {

    public static void main(String[] args) {
        new GameContainer();
    }

    EntityManager manager;
    Systems.Render renderingSystem;
    Systems.Velocity velocitySystem;

    GameContainer() {
        manager = new EntityManager(5);
        renderingSystem = new Systems.Render();
        velocitySystem = new Systems.Velocity();

        int id = manager.createEntity(Component.POS | Component.VEL | Component.RENDER);
        if (id > -1) {
            manager.pos[id].x = 10;
            manager.pos[id].y = 10;
            manager.vel[id].velx = 1;
            manager.vel[id].vely = 1;
            manager.rendering[id].name = "player";
        }

        id = manager.createEntity(Component.POS | Component.RENDER);
        if (id > -1) {
            manager.pos[id].x = 0;
            manager.pos[id].y = 0;
            manager.rendering[id].name = "tree";
        }
        startGameLoop();
    }

    void startGameLoop() {
        while(true) {
            velocitySystem.update(manager);
            renderingSystem.update(manager);
        }
    }

}


Avoid using object to hold int, bool, double application setting values

As you say, returning an object isn't ideal. This is a relatively straightforward use case for generics:

public abstract class ModelSetting<T>
{
    public T Value { get; set; }
    public abstract string ToString();

    public ModelSetting(T value)
    {
        Value = value;
    }
}

Then implementing classes can use:

public class DoubleSetting : ModelSetting<double>
{
    //...The rest of the class
}

This:

public abstract string ToString();

Is bad. ToString is already defined on Object, so by declaring an abstract version here, you're not overriding, you're hiding. This is far less frequently done, and for good reason- it breaks our basic expectations of polymorphism. You should only do it with good reason, and you don't have one here. Just get rid of the ToString redeclaration, it gives you nothing.

You require a value in your constructor, but then let Value be set publicly. This doesn't really make much sense- somebody could just pass default(T) to the constructor, making the constructor meaningless. You're giving two different ways to set the value, for no particular reason. It's not a big deal, but is needlessly confusing.

Consider whether you actually need to be able to change Value for an existing ModelSetting instance. If so, remove the constructor. If not (and this is probably better!), make the property private set. This makes the value immutable, which makes it much easier to reason about the class. For example, if I hold an instance, I know I can pass that instance to whoever I want without having to worry about them changing the value without me expecting it.

return (bool)Value ? "1" : "0";

Shouldn't this be the BoolSetting version, rather than the IntSetting one? At least you can take comfort that this bug is a demonstration of one of the advantages of the strong-typedness that you get from the generic approach!