When an object has different representations... what's the OO pattern?

I would use an abstract class instead of, or in addition to, an interface. You have quite a bit of repetition that could be removed by doing so. The only problem then would be that you would have to use protected instead of private properties and methods, at least for those that you need to share between the abstract class and inheriting class, but I don't think that should make too much of a difference. Remember: You can't create an instance of an abstract class, so you have to use some other "initiator" and call that in each constructor.

abstract class AbstractTransport {

    protected
        /** @var \Guzzle\Service\Client */
        $client,

        /** @var \Swift_Mailer */
        $mailer,

        /** @var Converter\MessageConverterInterface */
        $converter
    ;

    protected function initClient( Client $client, MessageConverterInterface $converter ) {
        $this->client = $client;
        $this->converter = $converter;
    }

    protected function initMailer( Swift_Mailer $mailer, MessageConverterInterface $converter ) {
        $this->mailer = $mailer;
        $this->converter = $converter;
    }

    public function executeTransport( AbstractMessage $message, array &$fails = array() ) {
        $representation = $this->converter->convert( $message );
    }
}

You might also want to be careful with referencing. It can sometimes be hard to determine where a variable was changed if you don't know that it was assigned by reference somewhere. This is entirely your choice, just a suggestion. I would, however, like to point out that if this parameter is referenced, then setting a default value to it is kind of pointless. If the parameter has not been set, then that value can't be used and should therefore not be used at all to avoid the overhead.

I've never heard of, nor could find a library design pattern, so I can't be sure. As for the name of the pattern you are using? I honestly don't know. But it doesn't matter. Functional code is much better than any code that adheres to a design pattern just for the sake of doing so. Many times I see programmers attempting to force their code into a design pattern, and some times its not even the right pattern. Design patterns are not necessary at this stage. Code for functionality. Once you are comfortable with OOP, then you can start worrying about design patterns and how and when to apply them.

Now, as to whether this is good OOP or not; It appears to be fine, however, this code is incomplete, so it is hard to tell. The concepts seem fine, but the implementation is unsure. You are using encapsulation, inheritance, and a sort of polymorphism. Those are some of the main points of OOP, and you seem to grasp them fairly well, though you could probably stand to look into polymorphism a bit more. You are also using interfaces and dependency injection. These are also important concepts. A couple more points that might help is to ensure you are following the Single Responsibility Principle (can't be sure) and the "Don't Repeat Yourself" (DRY) principle. As I pointed out above, you could use some help with DRY.

Finally, your code samples could have easily been reduced to a single interface and class with a note that the other related classes only differed in the commented area. The other classes, except that last, are redundant, whereas that last is unnecessary in this context. If you would have submitted complete classes, this would not be the case. The second interface was slightly relevant, but was also unnecessary.

I hope this helps!

EDIT

Example implementation of above code:

class RestTransport extends AbstractTransport {
    public function __construct( $client, $converter ) {
        $this->initClient( $client, $converter );
    }
}

Per comment, here's how to do it with separate classes for each type:

//only worth it if both client and mailer implementations share more than this
abstract class AbstractTransport implements TransportInterface {
    public function executeTransport( AbstractMessage $message, array &$fails = array() ) {
        $representation = $this->converter->convert( $message );
    }
}

class Client extends AbstractTransport {
    public function __construct( Client $client, MessageConverterInterface $converter ) {
        $this->client = $client;
        $this->converter = $converter;
    }

    public function executeTransport( AbstractMessage $message, array &$fails = array() ) {
        parent::executeTransport( $message, $fails );

        /*
        assuming there will be shared aspects unique to clients
        you can use polymorphism to further extend method
        same in the mailer
        otherwise it is unnecessary to redefine here
        */
    }
}

class RestTransport extends Client {
    public function executeTransport( AbstractMessage $message, array &$fails = array() ) {
        parent::executeTransport( $message, $fails );

        /* ... */
    }
}

And you'd do pretty much the same thing with the mailer, and any of its classes. The problem with this implementation is that the parent classes, in this case "Client", can be instantiated, and by itself it doesn't do anything. This is why I was originally suggesting the abstract class.


Retrieving MAC addresses based on PCI interface connections and SQL queries

public static string returnMAC()

The C# coding conventions state that functions should be UpperCamelCase. Additionally that function name is not optimal, returnMAC, return it from where? More appropriate would be GetMAC or RetrieveMAC.

You should add XML documentation to this method.

ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select MACAddress, PNPDeviceID FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND PNPDEVICEID IS NOT NULL");

This could benefit from using a literal/verbatim string:

ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"
SELECT
    MACAddress,
    PNPDeviceID
FROM
    Win32_NetworkAdapter
WHERE
    MACAddress IS NOT NULL AND
    PNPDEVICEID IS NOT NULL");

ManagementObjectCollection mObject = searcher.Get();

foreach (ManagementObject obj in mObject)

Both variable names are not great. You should avoid naming something obj if it is not an Object. Also you have the variable mObject which is a ManagementObjectCollection but can easily be confused to be a ManagementObject. Despite not being a great alternative either, collection and item might be better...though, only slightly.

ManagementObjectCollection collection = searcher.Get();

foreach (ManagementObject item in collection)

string pnp = obj["PNPDeviceID"].ToString();

Again, I would have rather named this variable pnpId or deviceId.

string pnp = obj["PNPDeviceID"].ToString();
if (pnp.Contains("PCI\\"))
{
    string mac = obj["MACAddress"].ToString();
    mac = mac.Replace(":", string.Empty);
    return mac;
}

This whole block can be shortened without losing much readability:

    if (item["PNPDeviceID"].ToString().Contains("PCI\\"))
    {
        return item["MACAddress"].ToString().Replace(":", string.Empty);
    }

Though, it seems a little bit messy at first sight, I think it's within an acceptable level.

return "Nothing happened...";

A more appropriate return value would be "" or "No PCI device found.".

Of course, the most appropriate action would be to throw an exception, as that should not happen during normal operation.


Print the number of unique pairs Stored in a HashSet

Clearly, janos solution is the simplest, but it'd probably break for the input

a b
a  b

Moreover, it circumvents the learning effect (I guess, it's about learning to write a class with equals and hashCode).

As often, Lombok makes it trivial:

@EqualsAndHashCode
public static class Pair {
    private final String first, second;
}

hashCode

The inefficiency was most probably caused by

@Override public int hashCode() {
    return first.hashCode();
}

which is correct, but leads to many collisions due to ignoring second. Something like

    return first.hashCode() + 123456789 * second.hashCode();

would solve it (the multiplier should be odd, anything else doesn't matter much).

equals

  return (first.equals(otherPair.first) && second.equals(otherPair.second))
            || (first.equals(otherPair.second) && second.equals(otherPair.first));

This contradicts the part

  implies (a,b) is not same as (b,a).

If it ever worked, then only because of the asymmetry in hashCode.

Why?

Two equals objects must have the same hashCode, otherwise the HashSet doesn't work properly (as the hash determines the index where the lookup starts). Violating this rule is a serious bug with which you may spend many funny debugging days.

This time, it helped you. After

set.put(new Pair("a", "b"));

the query

set.contains(new Pair("b", "a"));

erroneously returns false, although according to equals, the pair is there. However, it doesn't get found due to the non-equal hashCode. Analogously, after

set.put(new Pair("b", "a"));

you managed to contradict

  set is an abstract data type that can store certain values, without any particular order, and no repeated values.

Note that this is not guaranteed to happen as the hashes may coincide and only a part of them gets used.


Generating all unlabeled trees with up to n nodes

1. Review

In Python, a docstring goes after the function or class introduction. So instead of:

""" return copy of graph with newNode node appended to toNode node """
def leaf_copy(graph, newNode, toNode):

write something like:

def leaf_copy(graph, newNode, toNode):
    """Return a copy of graph with newNode appended to toNode."""

There are several advantages of doing it this way. Docstrings are available via the help function in the interactive interpreter:

>>> help(leaf_copy)
Help on function leaf_copy in module __main__:

leaf_copy(graph, newNode, toNode)
    Return a copy of graph with newNode appended to toNode.

Also, some integrated development environments (for example, PyCharm) can read and interpret docstrings to provide context-sensitive help or to generate reference documentation. And the built-in doctest module can automatically run examples in docstrings.
The trivial graph with one node and no edges is generated like this:

g = nx.Graph()
g.add_node(1)

but networkx has the function trivial_graph which does something similar.
The specification of genNextTreeList is:

""" get all n+1 node cases out of all n node cases in prevTreeList """

but this only the case if prevTreeList is the result of iterating genNextTreeList starting with an empty list. A more accurate specification would be something like this:

def genNextTreeList(prevTreeList):
    """Return a list of the graphs that can be constructed by attaching a
    new node to any of the nodes in any of the graphs in prevTreeList,
    except that if prevTreeList is None or the empty list, in which
    case a list containing the trivial graph is returned.

    """

It says in the Zen of Python,

  Special cases aren't special enough to break the rules.

so I would drop the special case. It is easy enough for the caller to pass the list containing the trivial graph, if that's what's wanted.

Also, it should be clear now that genNextTreeList does not only operate on trees. So a better name and specification would be something like this:

def augmented_graphs(graphs):
    """Return a list of the graphs that can be constructed by attaching a
    new node to any of the nodes in any of the graphs in the argument.

    """

Instead of having a flag isomorphic to determine whether the new graph has been found to be a duplicate, use Python's for ... else: ... statement, or the any or all functions.
There's no need to use networkx.algorithms.isomorphism.GraphMatcher: you could just call networkx.algorithms.isomorphism.is_isomorphic directly.
genNextTreeList has a two-step construction of the result: first, construct a list nextTreeList of augmented graphs, and second, eliminate duplicates. These could be combined into a single step by testing each new graph for isomorphism as soon as you construct it, like this:

from networkx.algorithms.isomorphism import is_isomorphic

def augmented_graphs(graphs):
    """Return a list of the graphs that can be constructed by attaching a
    new node to any of the nodes in any of the graphs in the argument.

    """
    result = []
    for old_graph in graphs:
        new_node = max(old_graph.nodes()) + 1
        for node in old_graph.nodes():
            new_graph = leaf_copy(old_graph, new_node, node)
            if not any(is_isomorphic(new_graph, g) for g in result):
                result.append(new_graph)
    return result

The top-level code does two things: it generates the free trees with up to N nodes, and it plots them. This would be better split into two functions each of which does a single thing, for example:

from networkx.generators.classic import trivial_graph

def free_trees(n):
    """Return list of free trees with up to n vertices."""
    result = trees = [trivial_graph()]
    for i in range(n - 1):
        trees = augmented_graphs(trees)
        result.extend(trees)
    return result

2. Alternative approach

A look at the NetworkX manual finds networkx.generators.nonisomorphic_trees.nonisomorphic_trees which implements the algorithm of

Robert Alan Wrights, Bruce Richmond, Andrew Odlyzko and Brendan D. Mckay (1986). “Constant time generation of free trees”. SIAM J. Comput. 15:2, pp. 540–548.

This generates the 19,320 free trees on 16 nodes (see A000055) in just over a second:

>>> from networkx.generators.nonisomorphic_trees import nonisomorphic_trees
>>> from timeit import timeit
>>> timeit(lambda:list(nonisomorphic_trees(16)), number=1)
1.0307372510433197

Here are 100 of these trees:


It depends on your intent. Your code should use idioms to match what its actually trying to do.

void foo(boolean cake) {
    if (!cake)
        return;

    // TODO some work.
}

Indicates that !cake is a precondition and as such is insignificant to what the function is doing.

void bar(boolean cake) {
    if (cake)
        //TODO some work.
}

Indicates that cake is an important part of what the function is doing.


There are several Comments that are unnecessary. You should get rid of them, since your code explains a few of those Comments.

Most C# coding standards suggest that you always use braces for if statements, so instead of this:

 if (BitConverter.IsLittleEndian)//Check for Endianess
        Array.Reverse(tempSize);//Reverse if necessary

you would format it like this:

if (BitConverter.IsLittleEndian)
{
    Array.Reverse(tempSize);
}


Prime numbers less than a given number N

The challenge states

  Print out the prime numbers less than a given number N

but you are iterating

for (int i = 2; i <= limit; i++)

The ending condition should be i < limit.

You need to check some edge cases:

limit == 0 here you would get an exception at sb.deleteCharAt(sb.length() - 1);
limit == 1 here you would get an exception at sb.deleteCharAt(sb.length() - 1);
limit == 2 using the ending condition mentioned above you would get an exception at  at sb.deleteCharAt(sb.length() - 1); too

If you start the loop (in main)  at 3 and increment i by 2 this will be faster and you wouldn't need if (n % 2 == 0)
Using braces {} for single if statements and loop bodies will make your code less errorprone.
importing the whole java.io namespace is to much. Restrict the imports to the classes you need.
the StringBuilder.append() method returns a StringBuilder object. So instead of calling sb.append(i + ",") you should call sb.append(i).append(",")

Refactoring

The while loop

while ((line = buffer.readLine()) != null) {
    StringBuilder sb = new StringBuilder();
    line = line.trim();
    limit = Integer.valueOf(line);
    if (limit > 2) {
         sb.append(2).append(",");
    }
    for (int i = 3; i < limit; i += 2){
        if (isPrime(i)){
            sb.append(i).append(",");
        }
    }
    if (sb.length() > 0) {
        sb.deleteCharAt(sb.length() - 1);
    }
    System.out.println(sb);
}

and the isPrime() method

private static boolean isPrime(int n) {
    for (int i = 3; i*i <= n; i += 2) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

in this way isPrime() would return true for each int n < 3 but this is for this case perfectly fine, because this is a private method which is only called in this specific szenario given strong borders.


As long as the real implementation that is being mocked here is also unit tested. And the mock is configured to match the expected behavior of the real implementation. You should be fine.
However you gotta remember to change all mock configuration when expectations of the real implementation change. This should not happen often for a library (BC break) but it is much more common in applications.
You are also depending on a specific implementation and if in future the tested object is changed to use different approach/calling other methods of other classes etc, your tests will have to change.
But anyway there is something your test does not test. It does not check that the correct json is returned by the endpoint. And it does not test what happens when exception is thrown. Although the latter should probably be a separate test.
One note for the route, I'm not sure whether save method throwing an exception should be considered a client error (400). It is not client's fault that your db failed.


You are searching for a number with more than 500 divisors in the range 0 to 10000. But we are not sure whether a number less than 10000 will be the required number. So, instead of searching a number in a range, we can search for that number which satisfies the condition the in the set of positive real numbers.

num=1
tnum=0 #representing triangular number
nof=0
while nof<501:
      nof=2 #to include 1 and the number itself
      tnum+=num
      num+=1
      for i in range (2,int((tnum/2))+1):
          if tnum%i==0:
             nof+=1
      print (tnum," : ",nof) #printing the triangular number and its number of divisors
print ("Required number is ", tnum)

This code will also take a good amount of time to get you result.


Try to avoid using Select. I have fixed that for you.

This line: Range(Cells(4, i + 2), Cells(Cells(Rows.Count, i + 2).End(xlUp).Row, i + 2)).Address(ReferenceStyle:=xlR1C1)

may require you to add Sheets("SheetName") separated by dot . before Range to specify the sheet you want the data to refer to.

Also added Columns.Autofit at the end to automatically resize column widths upon completion

Sub UniqueOverheads()

    Worksheets.Add(after:=Worksheets(4)).Name = "Overheads"

    With Sheets(Sheets.Count).Range("B3")
        .Value = "Overheads Code"
        .Interior.ColorIndex = 37
        .Interior.Pattern = xlSolid
        .Font.Bold = True
    End With
    With Sheets(Sheets.Count).Cells.Font
        .Name = "Lucida Sans"
        .Size = 10
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ColorIndex = xlAutomatic
    End With

    Dim names As Variant
    names = Array("OverheadsList", "OverheadsActuals", "OApr", "OMay", "OJun", "OJul", "OAug", "OSep", _
                  "OOct", "ONov", "ODec", "OJan", "OFeb", "OMar")

    For i = LBound(names) To UBound(names)
         ActiveWorkbook.names.Add Name:=names(i), RefersToR1C1:="=" & _
         ActiveSheet.Name & "!" & _
         Range(Cells(4, i + 2), Cells(Cells(Rows.Count, i + 2).End(xlUp).Row, i + 2)).Address(ReferenceStyle:=xlR1C1)
    Next i
    Columns.AutoFit
End Sub


Your answer should also be a template struct. It contains first and last element of type big_int but in the bubble _sort function it is constructed with template argument type T.

template<class T>
struct answer {
    std::size_t count;
    T first_element;
    T last_element;
};

But actually maybe the structure Is redundant because first And last element can Always easily be accessed inside the sorted container. Or it could at least contain just references to those elements instead of their copies in case the template argument T is something more complex then long long.

auto count = bubble_sort(v);
auto & first = v[0];
auto & last = v[v.size - 1];

Further instead of accepting vector<T>, you could accept two iterators of template argument type as Is common with many standard functions and allows to work not only for any type of container but also for just a range within a container.

template<class Iterator>
std::size_t bubble_sort(Iterator from, Iterator to);

// ...

auto count = bubble_sort(v.begin(), v.end());


Faster track to recognizing patterns in looping through nested sequences

I would write the loop like this:

for i, j, move in list_of_moves:
    assert(0 <= i < 3 and 0 <= j < 3 and move in 'XO')
    board[j][i] = move

or maybe:

VALID_MOVES = 'XO'
for i, j, move in list_of_moves:
    assert(0 <= j < len(board) and 0 <= i < len(board[j]) and move in VALID_MOVES)
    board[j][i] = move

depending on how general I needed the implementation to be.

Something that you might find helpful would be to step through your code in the Python debugger. Look at each line as it is executed and check that it makes sense. For example:

>>> board = [[''] * 3 for _ in range(3)]
>>> moves = [(1,1,'X'), (0,0,'O')]
>>> import pdb
>>> pdb.run("insertMoves(board, moves)")
> <string>(1)<module>()
(Pdb) step
--Call--
> cr32933.py(1)insertMoves()
-> def insertMoves(board, list_of_moves):
(Pdb) step
> cr32933.py(2)insertMoves()
-> for move in list_of_moves:
(Pdb) step
> cr32933.py(3)insertMoves()
-> for i in range(0, 3):
(Pdb) print move
(1, 1, 'X')
(Pdb) step
> cr32933.py(4)insertMoves()
-> if move[0] == i:
(Pdb) print i
0
(Pdb) step
> cr32933.py(3)insertMoves()
-> for i in range(0, 3):
(Pdb) step
> cr32933.py(4)insertMoves()
-> if move[0] == i:
(Pdb) print i
1

At about this point (if not earlier) you should be saying to yourself, "why did I have to go round the loop in order to discover that move[0] has the value 1?"


Exercise for playing wordgames with user input

1. Proper indentation
Please have a look at a style guide. One important topic of style guides is how to "correctly" indent your code:
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;

public class WordGames {

    public static void main(String[] args) throws FileNotFoundException {
        getSelection();
        File file = new File("DICTIONARY.txt");
        if (file.isFile() == true) {
        }
        else {
            System.out.println("File doesn't exist.  Exiting.");
            System.exit(0);
        }

        subStringProblem();
        pointsProblem();
    }

    static String getSelection() {
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Welcome to the Word Games program menu.");
        System.out.println("Select from one of the following options.");
        System.out.println("1. Substring problem.");
        System.out.println("2. Points problem.");
        System.out.println("3. Exit.");
        System.out.println("Enter your selections: ");

        if (!keyboardInput.hasNextInt()) {

           System.out.println("Invalid option.  Try again.");
           getSelection();

        } else if (keyboardInput.hasNextInt(1)) {
            subStringProblem();
            getSelection();

        } else if (keyboardInput.hasNextInt(2)) {
            pointsProblem();
            getSelection();

        } else if (keyboardInput.hasNextInt(3)) {
            System.out.println("Good Bye!");
            System.exit(0);
        }
        return null;
    }

    static String subStringProblem() {
        System.out.println("Substring problem.");
        System.out.println("Enter a Substring:");
        return null;
    }

    static String pointsProblem() {
        System.out.println("Points problem.");
        return null;
    }
}

2. Empty if
if (file.isFile() == true) {
}
else {
    System.out.println("File doesn't exist.  Exiting.");
    System.exit(0);
}

This is not necessary. Just use
if (file.isFile()) {
}
else {
    System.out.println("File doesn't exist.  Exiting.");
    System.exit(0);
}

Without an == the if will automatically check if the value is true.
Even better:
if(!file.isFile()) {
    System.out.println("File doesn't exist.  Exiting.");
    System.exit(0);
}

Empty if-statements should be avoided.
3.Input validation
In getSelection(), your program doesn't crash when the user enters a letter instead of a number. That is good. But your program does crash, when the user enters a number not equal to 1, 2 or 3. This problem can be avoided like this:
int sel = 0;
try{
    sel = keyboardInput.nextInt();
} catch (InputMismatchException e){
    keyboardInput.next();
    System.out.println("Invalid option. Try again.");
    getSelection();
}

if (sel == 1) {
    subStringProblem();
    getSelection();
}
else if (sel == 2) {
    pointsProblem();
    getSelection();
}
else if (sel == 3) {
    System.out.println("Good Bye!");
    System.exit(0);
}
else {
    System.out.println("Invalid option. Try again.");
    getSelection();
}

If you are not familiar with try-catch yet, I suggest reading the documentation.
4.Unnecessary returns
If you don't want to return something in your methods, you can use void as return type instead of String.
For example:
static String subStringProblem() {
    System.out.println("Substring problem.");
    System.out.println("Enter a Substring:");
    return null;
}

should be replaced with
static void subStringProblem() {
    System.out.println("Substring problem.");
    System.out.println("Enter a Substring:");
}

5. Access modifiers
It is considered good practice to always add Access modifiers to your methods. Instead of
static void getSelection() {

it should be
private static void getSelection() {

6. throws
The throws-keyword in the main-method is not necessary.
Code
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.util.InputMismatchException;

public class WordGames {

    public static void main(String[] args) {
        getSelection();
        File file = new File("DICTIONARY.txt");
        if(!file.isFile()) {
            System.out.println("File doesn't exist. Exiting.");
            System.exit(0);
        }
        subStringProblem();
        pointsProblem();
    }

    private static void getSelection() {
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Welcome to the Word Games program menu.");
        System.out.println("Select from one of the following options.");
        System.out.println("1. Substring problem.");
        System.out.println("2. Points problem.");
        System.out.println("3. Exit.");
        System.out.println("Enter your selections: ");

        int sel = 0;
        try{
            sel = keyboardInput.nextInt();
        } catch (InputMismatchException e){
            keyboardInput.next();
            System.out.println("Invalid option. Try again.");
            getSelection();
        }

        if (sel == 1) {
            subStringProblem();
            getSelection();
        }
        else if (sel == 2) {
            pointsProblem();
            getSelection();
        }
        else if (sel == 3) {
            System.out.println("Good Bye!");
            System.exit(0);
        }
        else {
            System.out.println("Invalid option. Try again.");
            getSelection();
        }
    }

    private static void subStringProblem() {
        System.out.println("Substring problem.");
        System.out.println("Enter a Substring:");
    }

    private static void pointsProblem() {
        System.out.println("Points problem.");
    }
}


Your conversion from celcius is not correct, since 0°F is not 0°C. Something like \$F = \frac{9}{5} C + 32\$ should work for the conversion.


How to make a int not be used twice when it randomly generates them?

There are basically two different ways of doing this efficiently:

Put the questions in a list
Shuffle the list
Loop through the list and show the questions

or:

Put the questions in a list
Pick a question to show by random
Remove that question from the list
Repeat until the list is empty


Translate strings from an XML attribute into corresponding constants in my module

Well, that's more or less of a personal preference. I'd just adapt any of those to fit my existing code.

For the sake of example, I'd also consider the below example:

self.types = frozenset(v for v in (getattr(objects_module, enum_name, None) for enum_name in
                                   element.attrib.get('object-types', '').split()) if v)

That's just how PyCharm suggested it. But as I said, is more or less a mater of preference. If you want, from what you showed, I'd go with the first one.

You might also consider the following:

split_element = element.attrib.get('object-types', '').split()

self.types = frozenset(v for v in (getattr(objects_module, enum_name, None) for enum_name in split_element) if v)

Which is exactly as your last solution. I've just created an extra variable which will hold the split() part. Now that that respects the PEP8 requirement about the length of a line, I like it.


It certainly seems like you're working too hard here. Some long methods, a lot of to_i and to_s (and back to_i) and so on. A line like this:

ret_val << a.to_i.to_s[start..3*(i+1)+(rem-1)].to_i.to_s

is, well, horrifying. Sorry.

Quick review

As ckuhn203 pointed out in the comments, this might be worth monkey patching into Integer. But if you choose not to, instantiating an object for it is a bit much. The entire thing is state-less, so it could just as well be a class method or module function.
You make heavy use of the ret_val name. Besides being unnecessarily shortened, it's also completely opaque. Ok, it's the return value, but what is it? It's sort of like naming a method method - it doesn't really explain much.
You make a lot of use of unless some_string.empty?. A simpler solution would be to (conditionally) push strings to an array, and then call join at the end. No need for "manual" string concatenation.
And, as mentioned, there's a lot of number-to-string-to-number stuff going, a lot of slicing and dicing, and tricky loops with complex ranges like start..3*(i+1)+(rem-1). As a rule of thumb, you very, very rarely need to do index arithmetic in Ruby, so if you find yourself doing that, take a step back and reconsider.

In terms of readability, I pretty much just gave up, to be honest. I mean, I get the gist of what your code is doing in one place or another, but I just don't want to read through it in detail and make heads and tails of all the slicing and looping.

It doesn't have to be this way, though. While it's tempting to approach this as slicing up a string, what we're dealing with is just a number, so a little arithmetic works too; you basically want to work with the remainders of dividing by 1000, 100, and 10.

Alternative approach

Your friends for this task are Numeric#divmod and multiple assignments (aka array destructuring). For instance, to split the input number into "thousands-chunks":

chunks = []
while number > 0
  number, chunk = number.divmod(1000)
  chunks << chunk
end

or, if you want to be a little obtuse about it:

chunks = []
number, chunks[chunks.count] = number.divmod(1000) while number > 0

That basically replaces your chunks_of_thousand method. Note that the chunks array is "backwards", e.g. if number = 1_123_456_089 you'll get:

[89, 456, 123, 1]

Now that we've got chunks to work on, we can again use divmod to our advantage. However, it'd be nice to reorganize those lookup tables a little. I'd do something like this, combining the first 20 numbers into one hash (or just an array)

ZERO_TO_TWENTY = {
  0 => nil,
  1 => "one",
  # ... snip ...
  19 => "nineteen"
}.freeze

The TENS can remain as-is for now (although it's recommended to call freeze on objects that are declared as constants), and the NUMBER_SCALE we'll change later.

Now, to convert each 0-999 chunk to English, we can do this (it's not super pretty though - I've included some further alternatives later on):

strings = chunks.map do |number|
  string = []

  # get the hundreds
  hundreds, remainder = number.divmod(100)
  string << "#{ZERO_TO_TWENTY[hundreds]} hundred" if hundreds > 0

  # get the tens and units (with a special case for numbers below 20)
  tens, units = remainder < 20 ? [nil, remainder] : remainder.divmod(10)
  string << [ TENS[tens], ZERO_TO_TWENTY[units] ].compact.join("-")

  string.join(" ")
end

Yes, I have hard-coded the string "hundred" in there, which is less than ideal. I wouldn't take much to move it to a constant of course. However, there's no sense in sticking it in the NUMBER_SCALE hash like your current code does, but where it doesn't belong.

Now, to match those strings to their "scale", we have Array#zip. Note, however, that for this to work, we have to redefine your NUMBER_SCALE a bit:

NUMBER_SCALE = [
  nil,
  "thousand",
  "million",
  "billion",
  "trillion"
].freeze

After that, we can do this bit of chaining magic:

strings.zip(NUMBER_SCALE).reverse.flatten.compact.join(" ")

which'll give us the result. E.g.:

in_english(1_123_456_089)
#=> "one billion one hundred twenty-three million four hundred fifty-six thousand eighty-nine"

All together now

All we need is the input checks from your code and we've got:

# constants declared as above

def in_english(number)
  number = number.to_i

  raise RangeError if number < 0 or number > 999_999_999_999
  return "zero" if number.zero?

  chunks = []
  number, chunks[chunks.count] = number.divmod(1000) while number > 0

  strings = chunks.map do |number|
    string = []
    hundreds, remainder = number.divmod(100)
    string << "#{ZERO_TO_TWENTY[hundreds]} hundred" if hundreds > 0

    tens, units = remainder < 20 ? [nil, remainder] : remainder.divmod(10)
    string << [ TENS[tens], ZERO_TO_TWENTY[units] ].compact.join("-")

    string.join(" ")
  end

  strings.zip(NUMBER_SCALE).reverse.flatten.compact.join(" ")
end

It's not brilliant, but I'd say it's at least better. If nothing else, there's just a lot less code there.

You'll note I've just made a single method here, not a class. You can package it however you want of course (e.g., as ckuhn203 suggested, as a monkey patch on integer) - but I'll leave that as an exercise to the reader. If you make a class, it'd of course be beneficial to break the various parts of the logic into separate (private) methods.

Also of note is that I'm raising a RangeError, as that's the most appropriate error to use when a numeric value is, well, out of range. It would be very nice to append a custom error message to that error while you're at it, to let the user know what the range actually is.

And I'm using zero? instead of == 0, as that's more idiomatic.

I'm a little on the fence about the number.to_i line. I think I'd prefer to assume that a number has been passed in, and if not then it's the user's problem (since the code will just raise a NoMethodError at some point). Garbage In, Garbage Out, basically. I've left it in to match your current code, but I would probably leave it out otherwise.

You can try it here if you'd like.

Further alternatives

Here's a different approach, using a recursive lambda

def in_english(number)
  number = number.to_i
  raise RangeError if number < 0 or number > 999_999_999_999
  return "zero" if number.zero?

  convert = -> (number) do
    case
    when number.zero?
      nil

    when number < 20
      ZERO_TO_TWENTY[number]

    when number < 100
      tens, units = number.divmod(10)
      [ TENS[tens], convert[units] ].compact.join("-")

    when number < 1000
      hundreds, number = number.divmod(100)
      [ "#{ZERO_TO_TWENTY[hundreds]} hundred", convert[number] ].compact.join(" ")

    else
      chunks = []
      number, chunks[chunks.count] = number.divmod(1000) while number > 0
      chunks.map(&convert).zip(NUMBER_SCALE).reverse.flatten.compact.join(" ")
    end
  end

  convert[number]
end

I like this a little better myself. The lambda could of course be a (private) method instead, which would make sense in a class. The only thing that's keeping this from simply being a single, recursive method is the "zero" vs nil return values.

You could handle that with just an extra method argument, however. It might in fact be useful to the user - not just as a hack to make the code work. It'd let someone pass in, say, "none" instead of zero which could be nice is some situations.

Doing so, we get a single, recursive method:

def in_english(number, zero_string = "zero")
  number = number.to_i
  raise RangeError if number < 0 or number > 999_999_999_999

  case
  when number.zero?
    zero_string

  when number < 20
    ZERO_TO_TWENTY[number]

  when number < 100
    tens, units = number.divmod(10)
    [ TENS[tens], in_english(units, nil) ].compact.join("-")

  when number < 1000
    hundreds, number = number.divmod(100)
    [ "#{ZERO_TO_TWENTY[hundreds]} hundred", in_english(number, nil) ].compact.join(" ")

  else
    chunks = []
    number, chunks[chunks.count] = number.divmod(1000) while number > 0
    chunks.map { |n| in_english(n, nil) }.zip(NUMBER_SCALE).reverse.flatten.compact.join(" ")
  end
end

It's still quite long for a Ruby method, but I like it all the same.


Getting count value for matched document

A few things that meet my eye:
Value Casing
You run item.lower() for each item in the keyword list when you iterate over the records. You could ensure the lower-case of all items in your keyword-list before getting to the records, then that step would be away.
Naming
count2 should be total, count1 should be matched, collection1 needs a better name. Names are vital in allowing other programmers to understand your code.
Nitpicks

You may get better performance by formatting the string before entering the loop over the keyword-list
The keyword list contains duplicate items
Remove Code you do not need instead of commenting it out. Version Control has got your back :)
keyword_list could be keywords...
printing is not really a valid return from a method.


Fetching a post from the database based on a query parameter

There are two things that jump out at me:

You assume $_GET['post'] exists.

If someone just goes to post.php without specifying a parameter, $_GET['post'] is not set -- and any attempt to read it would trigger a notice like "Undefined index: post". Checking the length won't make that notice go away; even the act of getting the length starts with the assumption that your parameter exists.

You really ought to put that variable into a known state before you make any assumptions about it. It might be as simple as, say:

$requestedID = isset($_GET['post']) ? $_GET['post'] : null;

You don't even need the strlen check; null and '' aren't numeric, so they'd both fail the is_numeric check.

(Course, the bigger issue is that you have error reporting set to ignore notices. You should generally be developing with error reporting turned all the way up, even if you turn it back down for production.)
You repeat the same error-case code three times.  If you ever want to change how you handle nonexistent or unspecified post IDs, you have to change the code in three places.

That could be fixed by changing the flow a bit.

$requestedID = isset($_GET["post"]) ? $_GET['post'] : null;
$row = null;

if (is_numeric($requestedID)) {
  if ($stmt = $mysqli->prepare("SELECT * FROM posts WHERE id =?")) {
    $stmt->bind_param('s', $requestedID);
    $stmt->execute();
    $result = $stmt->get_result();

    # oh...this too.  $result can be false if something went wrong.
    if ($result && $result->num_rows > 0) {
      $row = $result->fetch_assoc();
    }
  }
}

// $row is only set (and truthy!) if you succeeded
if ($row) {
  // logic for the content
}
else {
  header("Location: index.php");
  // exit(); not necessary if this is the last line of the script
}


In get_raw_bytes you should use with to close the file.
Without using a with or .close the file is not guaranteed to close and so can cause problems depending on how nice Python is feeling on being to you.

Don't leave bugs to change.
The code is fairly good, but get_debiased_bytes is doing three things at once.

Converting bytes (\$2^8\$) to crumbs (\$2^2\$).

for byte in raw_bytes:
    for k in range(0, 8, 2):
        bit1 = byte >> k & 1
        bit2 = byte >> k + 1 & 1

Debiasing the crumbs to bits.

if bit1 != bit2:
    debiased_byte = debiased_byte << 1 | bit1

Joining bits to bytes.

debiased_byte = debiased_byte << 1 | bit1
bit_counter += 1
if bit_counter == 8:
    arr_debiased_bytes.append(debiased_byte)
    debiased_byte = 0
    bit_counter = 0

Bundling all this together is making your code harder to read.
When extracting the above functions I would use generator functions.
This has a couple of benefits:

In Python the iterator pattern has a lot of sugar.
By using a generator we have more options on how to deal with the length.
We can truncate the size on the input, or only take length amount of items from the sequence after it's been made.

I'm not a fan of using byte >> k to get the bits / crumb.

Since bit operators are not commonly used their order of precedence can be confusing.
This doesn't help when you're mixing both bitwise and integer operators.

By using this you're adding a requirement for naming k when there is no need.
You can extract the nibble in a readable form by using byte & 0b11.
The code to debiase the crumbs is smart, but not exactly readable.

We know only two of the four states can yield data.
And so just hard coding the values can allow people to just read the code and figure it out faster.

By using the 0b prefix this can make the code really quite simple.
The code for building the bytes is ok. It's fairly easy to read.
The code for building the bytes can silently swallow data.

I personally would not be a fan of this. Instead I would yield the byte regardless.
There are two forms this can take, padding the bits on the left or right.

def bytes_to_crumbs(bytes):
    for byte in bytes:
        for _ in range(4):
            yield byte & 0b11
            byte >>= 2

def debiase_crumbs(crumbs):
    for crumb in crumbs:
        if crumb == 0b10:
            yield 1
        elif crumb == 0b01:
            yield 0

def bits_to_bytes(bits):
    """Just discard."""
    try:
        while True:
            byte = next(bits)
            for _ in range(7):
                byte <<= 1
                byte |= next(bits)
            yield byte
    except StopIteration:
        pass

def bits_to_bytes(bits):
    """Pad to the right - 1111000."""
    try:
        while True:
            byte = next(bits)
            for _ in range(7):
                byte <<= 1
                byte |= next(bits, 0)
            yield byte
    except StopIteration:
        pass

def bits_to_bytes(bits):
    """Pad to the left - 00001111."""
    try:
        while True:
            byte = next(bits)
            for _ in range(7):
                try:
                    bit = next(bits)
                except StopIteration:
                    yield byte
                    return
                byte <<= 1
                byte |= bit
    except StopIteration:
        pass

def get_debiased_bytes(length):
    with open('/dev/hwrng', 'rb') as f:
        _bytes = f.read(length)
    return bytes(bits_to_bytes(debiase_crumbs(bytes_to_crumbs(_bytes))))


Update user country based on IPv4 decimal address

You process data Row By Agonizing Row instead of a single Update statement.

There's no need for temp tables, variables and a loop, simply write a single SELECT and use this in an UPDATE FROM. This should return the correct country ids:

    SELECT u.id, c.Id
    FROM [dbo].[UserSignatures] AS u
    JOIN dbo.IpLookups AS lo
    ON CONVERT(BIGINT, PARSENAME(u.ClientIp, 1)) * POWER(256, 0)
     + CONVERT(BIGINT, PARSENAME(u.ClientIp, 2)) * POWER(256, 1)
     + CONVERT(BIGINT, PARSENAME(u.ClientIp, 3)) * POWER(256, 2)
     + CONVERT(BIGINT, PARSENAME(u.ClientIp, 4)) * POWER(256, 3)
       BETWEEN lo.[FROM] AND lo.[TO]
    JOIN [dbo].[Countries] AS c
    ON c.Code = lo.CountryIsoCode
    WHERE u.CountryId IS NULL


RXJS queue up multiple http requests and send when x conditions happens

//Maintain Queue of http Observable
const quequeHTTP = [];

//Dummy Http Request
getData(){
   return this.http.get('./api');
}

addInQueuqe(observable:Observable<any>){
     quequeHTTP.push(observable);
}

//Dummy addition 4 request
addInQueuqe(this.getData());
addInQueuqe(this.getData());
addInQueuqe(this.getData());
addInQueuqe(this.getData());

eventWhenXHappen(){
  Observable.forkJoin(quequeHTTP).subscribe((resArr)=>{
     console.log('When all request succesfully executed ');
},(err)=>{
  console.log('When error occur');
})

}


Before answering the question I have a few convention suggestions for you:

Use static instead f abstract when creating static classes.
By the look of your code I assume that your classes are not mean to be used for creating new instances but using abstract to achieve this is ill advised since you can walk around the restriction by creating a class which inherits from this class. Instead use the static keyword to create your static class:

public static class MyStaticClass
{
    //static members here
}

The method total days could be refactored as a property just with a getter method like this:

public int TotalDays => EndDay - StartDay;

You could also use the Linq method Zip() to join the input lines into the record object

With Zip() you can turn this

var rentalList = new List<RentalRecord>();

for (var i = 0; i < recordCount; i++)
{
    rentalList.Add(new RentalRecord(startDays[i], endDays[i]));
}

return rentalList;

into this:

return startDays.Zip(endDays, (startDay, endDay)
    => new RentalRecord(startDay, endDay));

Now for your question:
I suggest validating the content of the file instead of letting it fail without having code explaining why it fail and then throw your own custom exception when the validation method fails. I'd refactor your Load method like this:

public static List<RentalRecord> Load(string path)
{
    int recordCount;
    int[] startDays;
    int[] endDays;
    using (var reader = new StreamReader(path))
    {
        if(!int.TryParse(out recordCount))
        {
            throw new MyInvalidCustomException("Record line is not in the
            correct format);
        }
        startDays = ConvertStringToIntArray(reader.ReadLine());
        endDays = ConvertStringToIntArray(reader.ReadLine());
        if(startDays.Length != endDays.Length)
        {
            throw new MyInvalidCustomException("not all records have
            matching start and end days");
        }
    }

    return startDays.Zip(endDays, (startDay, endDay)
    => new RentalRecord(startDay, endDay));
}

This gives you a more specific exception control so you can troubleshoot the errors better.


This implementation is fine. It's easy to read and it works well.

A minor optimization could be to use an auxiliary dictionary to track the keys seen so far, in order to avoid an extra iteration to create the final result. But I don't think this is really important.

seen = {}
common_outliers = {}
for outlier in outliers:
    for idx, feature in outlier.items():
        if idx not in seen:
            seen[idx] = [feature]
        else:
            seen[idx].append(feature)
            common_outliers[idx] = seen[idx]
print(common_outliers)


Yes, the execution time amounts to O(n^3) because of the nested loops. A brute force approach cannot be healed; you need to change the algorithm.

A given denominator Q produces exactly phi(Q) rational numbers, so the problem boils down to calculating $$ \sum \phi (k) $$

There are many approaches for doing that. For the small numbers (according to constraints, less than 10000) I'd recommend a straightforward use of multiplicative property. A precomputed table of primes may also help.


UIButton subclass with animated 'shimmer' effect

Okay, so sometimes posting a question is the best way to figure out an  answer yourself .

I was looking for an alternative to having the gradient colors evenly spaced (my hack was to repeat the colors e.g. "blue blue red blue blue") and found the locations property on CAGradientLayer which is also animatable.

Animating this property feels like a much better approach because with the position not changing I can remove the wrapper layer.

Then, with without the wrapper layer I realized that I could override layerClass so the buttons backing layer is a gradient layer, which will also resize as needed when the view frame changes so that I don't even need to override layoutSubviews.

The only thing that feels a little strange is the forced requirement for for gradient colors to have three colors (otherwise I'd need to figure some formula to derive values for locations).

Edit: I've updated answer so instead of directly setting the colors, I've exposed gradientTint and gradientHighlight properties that are used to set the gradients colors array.

I've created a protocol that captures the properties used to define the shimmer effect, and also provide a default implementation of the animation.

It wasn't a requirement from my original question, but moving this code out of a specific subclass makes this snippet of code reusable (and maintainable) across other subclasses (e.g. UIView, UILabel).

protocol ShimmerEffect {
    var animationDuration: TimeInterval { set get }
    var animationDelay: TimeInterval {set get }

    var gradientTint: UIColor { set get }
    var gradientHighlight: UIColor { set get }

    //// Expects value between 0.0—1.0 that represents
    //// the ratio of the gradient highlight to the full
    //// width of the gradient.
    var gradientHighlightRatio: Double { set get }

    //// The layer that the gradient will be applied to
    var gradientLayer: CAGradientLayer { get }
}

Default implementation:

extension ShimmerEffect {

    /// Configures, and adds the animation to the gradientLayer
    func addShimmerAnimation() {

        // `gradientHighlightRatio` represents how wide the highlight
        // should be compared to the entire width of the gradient and
        // is used to calculate the positions of the 3 gradient colors.
        // If the highlight is 20% width of the gradient, then the
        // 'start locations' would be [-0.2, -0.1, 0.0] and the
        // 'end locations' would be [1.0, 1.1, 1.2]
        let startLocations = [NSNumber(value: -gradientHighlightRatio), NSNumber(value: -gradientHighlightRatio/2), 0.0]
        let endLocations = [1, NSNumber(value: 1+(gradientHighlightRatio/2)), NSNumber(value: 1+gradientHighlightRatio)]
        let gradientColors = [gradientTint.cgColor, gradientHighlight.cgColor, gradientTint.cgColor]

        // If the gradient highlight ratio is wide, then it can
        // 'bleed' over into the visible space of the view, which
        // looks particularly bad if there is a pause between the
        // animation repeating.
        // Shifting the start and end points of the gradient by the
        // size of the highlight prevents this.
        gradientLayer.startPoint = CGPoint(x: -gradientHighlightRatio, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1+gradientHighlightRatio, y: 0.5)
        gradientLayer.locations = startLocations
        gradientLayer.colors = gradientColors

        let animationKeyPath = "locations"

        let shimmerAnimation = CABasicAnimation(keyPath: animationKeyPath)
        shimmerAnimation.fromValue = startLocations
        shimmerAnimation.toValue = endLocations
        shimmerAnimation.duration = animationDuration
        shimmerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

        let animationGroup = CAAnimationGroup()
        animationGroup.duration = animationDuration + animationDelay
        animationGroup.repeatCount = .infinity
        animationGroup.animations = [shimmerAnimation]

        // removes animation with same key (if exists) then adds
        // the new animation
        gradientLayer.removeAnimation(forKey: animationKeyPath)
        gradientLayer.add(animationGroup, forKey: animationKeyPath)
    }
}

In the UIButton subclass I've added property observers to each of the properties that calls addShimmerAnimation() with any property change.

I also considered just supplying default values and requiring addShimmerAnimation() to be called manually once properties were configured. Another route was not having any public properties exposed and instead passing everything in through an initializer, but that would remove the possibility of these classes being used in a storyboard (which is an option I like to leave open) and having properties exposed through tagging  the properties with IBInspectable.

class ShimmerButton: UIButton, ShimmerEffect {

    override static var layerClass: AnyClass {
        return CAGradientLayer.self
    }

    var gradientLayer: CAGradientLayer {
        return layer as! CAGradientLayer
    }

    var animationDuration: TimeInterval = 3 {
        didSet { addShimmerAnimation() }
    }
    var animationDelay: TimeInterval = 1.5 {
        didSet { addShimmerAnimation() }
    }

    var gradientHighlightRatio: Double = 0.3 {
        didSet { addShimmerAnimation() }
    }

    var gradientTint: UIColor = .black {
        didSet { addShimmerAnimation() }
    }

    var gradientHighlight: UIColor = .white {
        didSet { addShimmerAnimation() }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        gradientLayer.mask = titleLabel?.layer
        addShimmerAnimation()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        gradientLayer.mask = titleLabel?.layer
        addShimmerAnimation()
    }
}

Example usage:

let shimmer = ShimmerButton()
shimmer.setTitle("Find new skills", for: .normal)
shimmer.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: UIFontWeightHeavy)
shimmer.gradientTint = darkBlue
shimmer.gradientHighlight = lightBlue
shimmer.sizeToFit()

What I like about this approach is that the complexity is moved out of the subclass making it super easy to duplicate over other views.

What frustrates me is that UIView, UILabel and UIButton only have minor differences. I wish there was a way for the computed properties to be extracted into a common place.

Example of ShimmerButton and ShimmerView (a UIView subclass) being used together:


You are giving very short names and commneting next to them the meaning

const nbloci = 100         # length of the genome
const N = 100              # Number individuals in the population
const nbgenerations = 100  # number of generations
const mu = 1/10^5          # mutation rate
const s = 0.01             # effect of a given mutation on fitness

It would be better to give long and self-explanatory names without comments:

const genome_length = 100
const population_size = 100
const no_generations = 100
const mutation_rate = 1/10^5
const s = 0.01                # effect of a given mutation on fitness # Too criptic for  me to understand

Many beginners think:

  If I write many many many comments everywhere in my code, it will for sure become better!

But this is not True, you should remove all the meaningless comments such as:

# Settings
# Packages
# Type and Functions

  Maybe using functions will slow down my code very much?

No, the opposite, code inside functions runs much faster.

But you should

  Avoid writing overly-specific types

(Reference is again the link above).

for l = I.Genome

Readibility counts, avoid using names like l and I because it is easy to mistake one for the other.

mutpos = mutposs

same as above.

  Is there a way to improve the calcfitness step, maybe by coding
  true/false instead of 1/1-s?

No, fitness must be a number, if you use a true/false value for the fitness then you are not searching genetically but randomly.


Misleading

Why would You something like this:

typedef unsigned int u32;
typedef int i32;

That's quite misleading. On 64bit machines it's probably not going to be 32 bit wide. Standard uint32_t, int32_t types would be the way to go, if You really need fixed sized integers. Also, typedefing primitive types like that just sucks and kills readability.

Also, You're using unsigned int for storing size. Why not just size_t?

Readability

Typedefing structs as well kills a bit of readability.

What's char *s;? Start? String? Digging through Your code doesn't make it clearer, especially when You have something like this:

void Buffer_clear(Buffer *buff) {
  buff->ins_ptr = buff->s;
  *(buff->ins_ptr) = '\0';
}

What does this mean: if (*Buffer_content(buff) == '\0')? Something like if (Buffer_isEmpty(buff)) would be waaaaay clearer.

Why would You mix casing in function names? void write_fizzbuzz_transformation(), but const char *Buffer_content(), etc.

Also, decide how do You form Your function names. noun_verb, verb_noun, or whatever. Now it's... quite inconsistent. Again, write_fizzbuzz_transformation(), but Buffer_*().

Generic rant

assert() is not intended to be used for production code. It's used only for debugging purposes and only when NDEBUG is defined. Why wouldn't You have proper logger for errors like... not enough space and... wrong input? In fact, You have no control of wrong inputs because none of those are sanitized properly. For example imagine user of Your buffer library does something stupid like Buffer_clear(NULL), Buffer_content(NULL), etc.

In production code You have potential buffer overrun here:

void Buffer_append_str(Buffer *buff, char* s) {
  u32 needed_sz = strlen(s);
  assert(Buffer_has_space(buff, needed_sz));
  strcpy(buff->ins_ptr, s);
  buff->ins_ptr += needed_sz;
}

As I said before, assert() is used only for debugging purposes. You should use strncpy() or check buffer size explicitly. Same applies to void Buffer_append_i32(Buffer *buff, i32 n).

Also, it would be nice if You'd provide proper error codes or 0 on success on Your buffer operations.

Functionality

You could shorten the following and make it safer using snprintf():

u32 needed_sz = 0;
if (n < 1) ++needed_sz;
while (n) {
  n /= 10;
  ++needed_sz;
}
assert(Buffer_has_space(buff, needed_sz));
sprintf(buff->ins_ptr, "%d", original);

You have #define BUFF_SZ 9, but accepting unsigned integers, which are... by Your typedefs --- 32 bit long. So, anything over 99 999 999 goes to abyss...

Warnings

./fizz.c:45:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
void main() {
     ^


Using Python to model a single elimination tournament

You have two lines marked as "doesn't scale".

The initial team list can be obtained from your database table of available teams (select of team details).

The other "problem line", is

 if gameid in [8,12,14]:  ##this is a manual decision tree, doesn't scale at all

But that's easily avoided by noticing that the games in a round are always half the previous round, and the initial round is half the number of teams!

In other words, you can do something like (if you include the initial round):

def NewRoundIds( teams_in_tournament ):
    round_ids = []
    game_id = 0
    games_in_next_round = len(teams_in_tournament)/2 #need to count the number of teams_in_tournament list
    while games_in_next_round > 0:
        round_ids += [game_id]
        game_id += games_in_next_round
        games_in_next_round /= 2
    return round_ids

new_round_game_ids = NewRoundIds( teamlist )
...
if gameid in new_round_game_ids:
    # etc

== edit ==

This puts it well outside the brief of the site, but it was interesting. The following I think does what you want, generate_tournament(16). It could do with a bit of tidying up, and it's the sort of thing that will certainly benefit from docstrings and doctests, which I shall leave as a exercise.

import math

def tournament_round( no_of_teams , matchlist ):
    new_matches = []
    for team_or_match in matchlist:
        if type(team_or_match) == type([]):
            new_matches += [ tournament_round( no_of_teams, team_or_match ) ]
        else:
            new_matches += [ [ team_or_match, no_of_teams + 1 - team_or_match ] ]
    return new_matches

def flatten_list( matches ):
    teamlist = []
    for team_or_match in matches:
        if type(team_or_match) == type([]):
            teamlist += flatten_list( team_or_match )
        else:
            teamlist += [team_or_match]
    return teamlist

def generate_tournament( num ):
    num_rounds = math.log( num, 2 )
    if num_rounds != math.trunc( num_rounds ):
        raise ValueError( "Number of teams must be a power of 2" )
    teams = 1
    result = [1]
    while teams != num:
        teams *= 2
        result = tournament_round( teams, result )
    return flatten_list( result )


Speeding up and fixing phone numbers from CSVs with Regex

Use a compiled regular expression.

Since you are looking for the pattern anywhere within a string, use re.search() instead of re.match().  Actually, the behaviour is not exactly the same.  .search() will return the leftmost match, whereas .match() using your original pattern will return the rightmost match, since the initial .* is greedy.  The backtracking that is necessary to accomplish a rightmost match would be a source of inefficiency.

By using .search(), which performs a search not anchored to the start of the subject string, you can also eliminate the capturing parentheses and use .group(0) instead.

You can also shorten the regex by using \d (match any digit) and {n} (match the previous element n times).  Since your two regular expressions differ by only one character, combine them, using a [ -] character class to cover both cases.

In the canonicalization step, you want to eliminate all non-digits, so just do that instead.

regex = re.compile(r'\+?[2-9]?\d?\d?-?\(?\d{3}\)?[ -]?\d{3}-?\d{4})')
…

match = regex.search(s1)
if match:
    canonical_phone = re.sub(r'\D', '', match.group(0))
    if canonical_phone not in seen:
        seen.add(canonical_phone)
        output.append(canonical_phone)


Same function, variable parameters and types with lambda

A couple of things I notice, and they are both around the if statements

I would flip the if statements around so that they are checking the positive test.  I would also put the disp on the right side of the ==.  You can eliminate the else statement, all it really does is clutters up the code.

if (System.Windows.Threading.Dispatcher.CurrentDispatcher == disp)
{
    f(arg);
    return;
}

disp.Invoke(f, arg);


If you really, really want to catch an unchecked exception that might be thrown when using a database, you can catch DataAccessException which is the higher exception on Spring's data translation exception hierarchy.

For correct method names, there no such thing on Spring, just use a name which can clearly describe what your method does, your current names are pretty good too. One more note, use the Service layer to aggregate data or do complicated business logic, and place simple logics on the domain, to avoid the Anemic Domain Model

You can find more info here about the last statement around Spring


How can I make placing JButtons from an array more elegant?

In order to find a more elegant solution, we first need to identify the problems; only then can we solve them:

Magic Numbers
One of the confusing things about this snippet is that we constantly (pun intended) come across magic values such as 15 and 749. What if the map gets bigger in the future, or the dimensions of the buttons change? Solution: Define constants.
Note: I used the Java naming convention for constants, which is SHOUTY_CASE, although I dislike it, because unified coding standards when sharing code trump personal preferences.

private static final int NUMBER_OF_BUTTONS = 2501;
private static final int BUTTON_SIDE = 15;

Unnecessary use of array
Why are you copying every button into your grid before adding them to the mapFrame? If you aren't accessing them from the array later on, you can get rid of all the access-by-index complexity.

JButton button = new JButton();
button.setBounds(x, y, BUTTON_SIDE, BUTTON_SIDE);
mapFrame.add(button);

Function doing too many things
The empty lines that you have used to split your code into sections is a code smell: it indicates that your function is doing too many different things, and therefore needs to be divided into several functions, each doing one thing. To quote Robert C. Martin, author of Clean Code: A Handbook of Agile Software Craftsmanship:

  Functions should do one thing. They should do it well. They should do it only.

Using complex syntax for simple things
Code like the following two examples from your code snippet

x = x + 15;
y = y + 15;

can be shortened by using the combined += operator.

Refactored

private static final int NUMBER_OF_BUTTONS = 2501;
private static final int BUTTON_SIDE = 15;
private JFrame mapFrame = new JFrame();

public void createAndShowMap() {
    mapFrame.setBounds(40, 0, 750, 773);
    addButtons();
    mapFrame.setVisible(true);
}

private void addButtons() {
    int leftOffset = 0;
    int topOffset = 0;
    for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {
        if (isBeyondEndOfLine(leftOffset)) {
            leftOffset = 0;
            topOffset += BUTTON_SIDE;
        }
        addButtonAt(leftOffset, topOffset);
        leftOffset += BUTTON_SIDE;
    }
}

private boolean isBeyondEndOfLine(int x) {
    return x >= mapFrame.getBounds().width;
}

private void addButtonAt(int x, int y) {
    JButton button = new JButton();
    button.setBounds(x, y, BUTTON_SIDE, BUTTON_SIDE);
    mapFrame.add(button);
}


Suppress console output from React in Jest testing output but not in browser output

Hope this helps someone else:
jest --silent

http://facebook.github.io/jest/docs/en/cli.html#silent


How to find the next sequence of integers?

There is a lot of repetition in your code, which makes it unnecessarily long, difficult to read, difficult to maintain, and error-prone. And in fact you have an apparent copy-paste error, can you spot it?
if a[-1]<39:
    ...
elif a[-2]<38:
    ...
elif a[-3]<38:
    ...
elif a[-4]<37:
    ...

The outer if/elif chain is to find the rightmost position in the list which can be increased, and that can be done with a loop:
for i in range(len(a)):
    if a[-1-i] < 39 - i:
       ...

The inner repeated assignments can be replaced by a loop as well. Then your function would look like this:
def next_row(a):
    for i in range(len(a)):
        if a[-1-i] < 39 - i:
            a[-1-i] += 1
            for j in range(0, i):
                a[-1-j] = a[-1-i] + i - j
            return a

Here i and j are positions from the end of the array as in your code, other choices are possible.
The new function is shorter, more general (it works with lists of arbitrary lists, not only lists of length 7), and can easily be generalized to arbitrary upper bounds (just replace the constant 39 by a function parameter).
If the intention is to enumerate all 7-element subsets of the first 39 integers then you can also use existing functions from the itertools module, in this case itertools.combinations():
import itertools

rows = itertools.combinations(range(1, 40), 7)

This creates an iterator which you can access one-by-one:
next_row = next(rows)
print(next_row)
# (1, 2, 3, 4, 5, 6, 7)

next_row = next(rows)
print(next_row)
# (1, 2, 3, 4, 5, 6, 8)

...

or enumerate:
for row in rows:
    print(row)

As a general remark, I suggest to check your code against the PEP8 coding style, for example at PEP8 online. It will report mainly missing whitespace around operators, and wrong indentation.


Collecting a list of documents from a factory for an AngularJS controller

In addition to what Blindman said, I would recommend avoiding using this in nested scopes , which is always confusing and error prone, by assigning documents to a local variable. i.e.

this.$onInit = function() {
  const id = $route.current.params.someId;
  let documents =this.documents = [];
  ...
  response.documents.forEach((object) => {
    documents.push(object);


A menu option that receives input from users and then performs actions

Technical

Your naming conventions are inconsistent - you mix PascalCase with alllowercase (don't know if that convention has it's own name). In Java types (like classes and interfaces) are PascalCase and method and variable names are camelCase.
Declare variables where they are used and not all at the top of the function.
Movie1 one is not a good name for a variable. The variable name should express the meaning of it. In this case it should be movieExists.
FindMovie won't compile due to the first line in the function (there is no movie type in your source code and nothing actually references a movie type except that one line of code). It should be removed (Movieobject is never used)
There is no need to prefix the variable name with the type of the variable it just adds clutter and no real value. So ArrayMovie should be movies as that's what the collection represents (a collection of movies).
If you use ArrayList instead of arrays you get automatic resizing when adding new movies and a whole bunch of nice utility functions like contains which reduce a lot of code clutter and does not impose the limitation of fixed sized arrays.
AddMovie requires the caller to pass in the index in the array where the movie should be stored. This is bad as it requires the caller to keep information about the structure of the list. It should just add a new movie to the end of a list (see previous point about ArrayList).
You can reduce nesting by breaking early when hitting the negative condition, for example:

bool movieExists = FindMovie(Movie, ArrayMovie);
if (movieExists)
{
    return;
}

System.out.println("Do you want to add this movie to the collection? Please select 1 for Yes or 2 for No");
bool userAction = console.nextInt();
if (userAction != 1)
{
    return;
}

// add the movie

Design

It seems like you had the right idea at some point about having a movie class (although it should be named Movie) encapsulating the properties of a movie like name, rating and reviews. Right now you seem to pass them around as 3 independent lists and the only connection is that the index in each list refers to the same movie. This is easy to get out of sync and you always have to pass around 3 lists - not to mention what happens when you want to add a 4th or 5th property.

AddMovie should just accept an ArrayList<Movie> as input to which you can add a new movie after you have gathered all the user input.


Interpret English as Math and Perform Operations

How should I be naming variables? Operation and numInString good names?

Great question, Python has an extensive but approachable style guide call PEP8. Specifically local variables should be lowercase, Global Constants should be UPPERCASE, and Global variables should be avoided.

  Should I print the result of a function operator?

In order to use it later you should return the value:

Instead of: print(multAns) do return multAns

  Should I be storing the numbers in a global list, numInString, instead of passing them to operator functions?

No, pass the numbers to the operator and save the returned result

result = oper(a=1, b=3)

instead of

a = 1
b = 3
oper()

  Should I print errors like this?:

print('NO OPERATION GIVEN')

No, raise errors when you come to this sort of situation.

ValueError("Cannot match an operator to \"{}\"".format(inputstring))

  Is it ok to assume all numbers will be int?

It would be better to handle the case of decimal number, especially if you want to be able to do true division (which was in your code)

My revision with plenty of comments, incorporating my above suggestions

import re
from decimal import Decimal

Dictionary mapping search words to operator function

operations = {
    '<a> (times|multiplied by) <b>':
        lambda a, b: a * b,
    '<a> divided by <b>':
        lambda a, b: a / b,
    '(add|sum)? <a> (and|plus) <b>':
        lambda a, b: a + b,
    'subtract <a> and <b>':
        lambda a, b: a - b,
    '<a> (minus|take) <b>':
        lambda a, b: a - b,
    '<a> squared':
        lambda a: a**2,
    '<a> cubed':
        lambda a: a**3,
    '<a> raised to the power <b>':
        lambda a, b: a**b,
    }

think of lambda as "make_function"

def plus(a, b):
    return a + b

is the same as

plus = lambda a, b: a + b

also you can use the actual operator:
    eg. * instead of operator.mul
        + instead of add

Match any number eg. 8, 8.8, -3.14 https://stackoverflow.com/questions/15814592/how-do-i-include-negative-decimal-numbers-in-this-regular-expression this is defined as a Global Constant

NUM_RE = "-?\d+(\.\d+)?"

Match that number and give it a name that can be
access later via m.groupdict()

def named_number_regex(name):
    return "(?P<{name}>{num})".format(name=name, num=NUM_RE)

variable_names = ['a', 'b']
for name in variable_names:
    # replace all of the name placeholders with
    # the actual regex for matching a named number
    #     eg. "<a>" ---> "(?P<a>-?\d+(\.\d+)?)"
    # placeholder were used just to make the above patterns easier to read
    old = '<{}>'.format(name)
    new = named_number_regex(name)
    operations = {k.replace(old, new): v for k, v in operations.items()}

# allow for varying amount of whitespace
operations = {'\s*' + k.replace(' ', '\s*'): v for k, v in operations.items()}

Now the patterns look like this:

#
# \s*(?P<a>-?\d+(\.\d+)?)\s*squared
#
# let's break it down:
#
# \s*                                 ignore leading whitespace
#    (?P<a>-?\d+(\.\d+)?)             match any number, name it 'a'
#                        \s*          ignore other whitespace
#                           squared   only match if you find " squared"

Function to take a string and and recursively simplify it until we either get a number or encounter an error.

def simplify(inputstring):
    print(inputstring) # see what is going on internally

    # if you get down to a single number return its value
    if re.fullmatch(NUM_RE, inputstring) is not None:
        return Decimal(inputstring)

    for matcher, oper in operations.items():
        # iterate over all key: value pairs in the dict "operations" eg:
        #    matcher = '(?P<a>\d+) (times|multiplied by) (?P<b>\d+)'
        #    oper = lambda a, b: operator.mul(a, b)
        m = re.match(matcher, inputstring)
        if m is None:
            continue

        # dict of named matches eg {'a': '4', 'b': '8'}
        numbers = m.groupdict()

        # convert text eg. '4' strings into integers eg. 4
        # this is like your [int(d) for d in re.findall(r'-?\d+', inputs)]
        # Decimal handles ints and floats, with floating point rounding errors
        numbers = {k:Decimal(v) for k, v in numbers.items()}

        # now numbers = {'a': 4, 'b': 8}

        # get the result of the matched operation
        # Note: ** means call function with keyword args from a dict
        #     eg. oper(a=4, b=8)
        result = oper(**numbers)

        # substitute the result of oper with the matched string
        # Note we can lose precision here when casting Decimal to str
        simplified = re.sub(matcher, str(result), inputstring)

        # now simplify it further if possible
        # this is call recursion, it will continue to simplify until we get down to just a number
        print('= ', sep='', end='')
        return simplify(simplified)

    raise ValueError("Cannot match an operator to \"{}\"".format(inputstring))

Test Cases

def test_a_few_cases():
    print("\nSimple Addition:")
    result = simplify("4 plus 8")

    print("\nDemonstrate the recursion:")
    result = simplify("2 squared squared squared squared")

    print("\nMore elaborate:")
    result2 = simplify("2 plus 1.11 times -7 raised to the power 6")

    print("\nDemonstrate an Error:")
    result = simplify("2 squared squared squared squard")

def main():
    print("\nYour input:")
    yourresult = simplify(input(">").lower())

if __name__ == '__main__':
    test_a_few_cases()
    main()


I would definitely remove the database access from the Category partial view and move it to the Controller (you can add it to the view model or have a separate action for returning them which is even more clean).

Views are supposed to be dumb layouts and not perform any business logic. Removing the database context shouldn't affect the compilation of the views.

Small refactoring suggestion for the Controller:

    public ActionResult Category(int? id)
    {
        var pid = id ?? 1;  //if requested id is null, set is as 1

        var category = db.Categories.Find(pid);

        if (category == null)  //if category does not exist, return Error
            return View("Error");

        var model = category.Products.ToList(); //return list of projects in requested category

        return View(model);
    }

Don't call find twice will save an extra database access which is important and code style wise I would use the ?? operator as you see above.

What the View("Error") is doing? Do you have an error view or is it just raising an exception? In both cases I would be more specific.

I would also make the view strongly typed as it will prevent errors and give you IntelliSense.


I'd rewrite the first part like this:

if(empty($_GET['key']) or !strcmp($_GET['key'], 'home')){
    $page = 'section';
    $id = 1; // integer not string
}elseif(!strcmp($_GET['key'], 'blahblah')){
    $page = 'blahblah';
    $id = 2; // integer not string
} // ...
include ('header.php');
include ("{$page}.php");
include ('footer.php');

Switch for strings is not always the best idea. You might want case insensitive compare and that's the strcasecmp realm.
If $_GET['key'] is missing, you will get a notice with the switch while empty() is safe.
$id seems to be an integer 1 so why make it a string '1'?
Why concatenate like this $page.'.php' when you can have php do it for you "{$page}.php"?

As of the second part, things are not too great:

Why concatenate on echo like this echo 'string'.'string' when echo is a language construct and allows this echo 'string', 'string' which skips the concatenation?
Why use $num_results == 0 when you can just use !$num_results?
Why not escape arguments in MySQL Query (let's just say you have an $id integer and might get away with it here) when SQL injections are so nasty :)

PS: AND YOU need to work on your formatting A LOT... like very much!


if(role!=Qt::EditRole||
         index.row()<0||
         index.row()>=this->m_ueJsonData.isArray()?this->m_ueJsonData.array().size():this->m_ueJsonData.isObject()?this->m_ueJsonData.object().size():0||
         index.column()<0||
         index.column()>=this->m_ueJsonData.isArray()?this->m_ueJsonData.array().size():this->m_ueJsonData.isObject()?this->m_ueJsonData.object().size()>0?this->m_ueJsonData.object().size():0:0)
{

Stop. Regardless of what you're doing here, you should not be doing so many things in one condition. This looks like you need to write a new function instead.

Talking about functions, they'd greatly improve the readability and maintainability of your code. Now you got everything in one big bool. Your while could use it's own function. The data changing, inserting and replacing could probably use a wrapper as well. If you give those functions meaningful names, the readability will increase big time!

Imagine the following:

  You haven't touched this code in 6 months. Now you want to add a feature. To add this feature, you try to understand how this code works and why you wrote it like this. Since it has been a while, you can't rely on your memory. How long would it take you to grasp the workings of this function?

Exactly. Way longer than necessary. Now imagine you share this code. Like you did here. How long does it take someone not familiar with your program to figure it out? Way longer than necessary.

For the sake of your future self, improve the readability of the code by splitting things up.


The code implementing the core algorithm is very cumbersome. This is partly due to shoehorning the line entry/exit times into the first/last stations as evidenced by some internal stations in your tests having unusable exit times. But the code duplication doesn't help either.

  Note: The diagram shows the transition time belonging to the station being transitioned from. Your code uses the transition time from the station on the other line. I'm going with the diagram as it seems cleaner to me.

Store the current stations into local variables to avoid having to read .get(0) and .get(i) many times. Also, when you name variables identically except for 1 and 2 (unavoidable in this method), don't hide the numbers in the middle of the names. Finally, since all these time-based local variables are for line X and track minimum times, drop Line and Min from their names.

public static int assemblyLineShortestTime(List<Station> line1, List<Station> line2) {
    return assemblyLineShortestTime(line1.iterator(), line2.iterator());
}

private static int assemblyLineShortestTime(Iterator<Station> line1, Iterator<Station> line2) {
    Station station1 = line1.next();
    Station station2 = line2.next();
    int prev1 = station1.getStationTime() + station1.getTransitionToTime();
    int prev2 = station2.getStationTime() + station2.getTransitionToTime();
    while (line1.hasNext()) {
        station1 = line1.next();
        station2 = line2.next();
        int curr1 = station1.getStationTime() + Math.min(prev1, prev2 + station2.getTransitionToTime());
        int curr2 = station2.getStationTime() + Math.min(prev2, prev1 + station1.getTransitionToTime());

        prev1 = curr1;
        prev2 = curr2;
    }
    return Math.min(prev1 + station1.getTransitionFromTime(), prev2 + station2.getTransitionFromTime());
}

While the code duplication seems much worse with those temporary variables, the logic is more apparent to me. The real problem is that there's no logic inside Station. If you add the line number to Station and added some helper methods, you could clean up that code a bit.

private static int assemblyLineShortestTime(Iterator<Station> line1, Iterator<Station> line2) {
    Station station1 = line1.next();
    Station station2 = line2.next();
    int prev1 = station1.start();
    int prev2 = station2.start();
    while (line1.hasNext()) {
        station1 = line1.next();
        station2 = line2.next();
        int curr1 = station1.proceed(prev1, prev2);
        int curr2 = station2.proceed(prev2, prev1);
        prev1 = curr1;
        prev2 = curr2;
    }
    return Math.min(prev1 + station1.exit(), prev2 + station2.exit());
}

class Station {
    public int start() {
        return stationTime + transitionToTime;
    }

    public int proceed(thisLineTime, otherLineTime) {
        // The transitionToTime here is not the correct one,
        // but this demonstrates the technique
        return stationTime + Math.min(thisLineTime, otherLineTime + transitionToTime);
    }

    public int exit() {
        return transitionFromTime;
    }
}

These small refactorings improve the readability only a little, but they don't alter it significantly. The real gains will require expanding the model and moving away from a single, static method.

Starting Over

If you're going to model the stations with classes to solve this, go all in and model the lines and entry/exit times properly to avoid confusion.

class Station
    int runTime - time to process this station
    int switchTime - time to switch lines

class Line
    List<Station> stations
    int entryTime - time to enter this line
    int exitTime - time to exit this line

Next model the location along the lines.

class Location
    Line line - which line are we on
    Station station - which station did we just go through
    int totalTime - elapsed time to reach this location

This design will allow moving the bulk of the algorithm into the model. You may not even need to model the lines themselves if you store the next stations in each station.

class Station
    int runTime - time to process this station
    Station next - next station on the same line
    Station otherNext - next station on the other line
    int switchTime - time to switch lines


is the current implementation 'safe'?

Absolutely not. The fact that you had to ask this question indicates that you do not understand enough about threading to build your own mechanisms like this. You need to have a deep and thorough understanding of the memory model to build these mechanisms. That is why you should always rely on the mechanisms provided for you in the framework, that were written by experts..

Why is it unsafe? Consider the following scenario. We have two threads, A and B. _Value is null and _Loaded is false.

We're on thread A.
The memory location of _Value is loaded into the processor cache for the CPU that thread A is affinitized to. It is null.
We switch to thread B.
Thread B reads _Loaded as false, takes the lock, checks _Loaded again, calls create, assigns _Value and _Loaded and leaves the lock.
We switch back to thread A.
_Loaded is now true, so thread A returns _Value from the processor cache, which is null.

Thread A is not required to invalidate the cache because thread A never takes a lock.!

Now, I made an argument here from processor caches. This is the wrong argument to make in general. Rather, what you must do when trying to build a new threading mechanism like this is to not reason about any specific processor architecture, but rather to reason about the abstract memory model of the C# language.  C# permits reads and writes to move forwards and backwards in time in multithreaded programs.  Any time travel that is not explicitly forbidden by the C# specification must be considered to be possible.  Your task is to then write code that is correct for any possible combination of movements of reads and writes in time regardless of whether they are really possible on a specific processor or not.

Note that in particular the C# specification does not require that all threads observe a consistent set of write and read re-orderings. It is perfectly legal and possible for two threads to disagree on how a read was re-ordered with respect to a write.

If writing correct programs in a world where all reads and writes can be moved around in time sounds hard, that's because it is. I am not competent to do this work, and I do not attempt to. I leave it to experts.

  are there any important performance considerations vs the original one?

Only you can answer that question.  Answer performance questions by gathering real-world empirical data.

However, I can say a few things about this problem in general.

The first is: double-checked locking is intended to avoid the cost of the lock. Let's examine the assumptions underlying that intention.  The assumption is that the cost of taking the lock is too high on the uncontended path.  Is that assumption warranted? What is the cost of taking an uncontended lock? Did you measure it? Did you compare it against the cost of the lock-avoiding check?  (Since the lock-avoiding check code is wrong, testing it for performance is not actually meaningful since we can always write faster code if we don't care about correctness, but still, we need to know whether this intervention is an improvement.)  And most importantly, is the cost of taking an uncontended lock relevant to the consumer of this code?  Because they are the stakeholder whose opinions are relevant; what do they say about the cost of an uncontended lock?

Let's suppose that the cost of an uncontended lock is relevant. Then surely the cost of a contended lock is enormously relevant.  You've built a mechanism that potentially contends a lot of threads!  What are the alternatives that you considered here?  For example, you could avoid the lock altogether by deciding that it is OK for the create function to be called on multiple threads -- perhaps we know that it is cheap and idempotent.  Those threads can then race to their heart's content to initialize the field, and we can use an interlocked exchange to ensure that we get a consistent value. That avoids the cost of the lock altogether, but it creates a different kind of cost, and puts a requirement on the caller to pass an idempotent creator.

Let's consider other aspects of your solution with respect to performance. You allocate the lock object regardless of whether you ever take the lock, and you keep it forever.  What's the burden on the garbage collector? What is the impact on collection pressure? These things are all deeply relevant to performance.  Again, remember, the assumption here is that we are so worried about the couple of nanoseconds it takes to enter and leave an uncontended lock that we're willing to write a double checked lock.  If those nanoseconds are relevant then surely the milliseconds it takes to do an extra collection are incredibly relevant!

  is there anything else I'm missing that I should be concerned about in a high traffic application?

I don't know how to answer that question.


Building query params which append to URL in a browser

Your main question

I have trouble understanding it, because:

minor reason:
(unless I'm missing something obvious) whatever way you encode the array parts, the resulting query string is quite valid in both cases;
so the only possible criterion for choosing a method rather than the other one would be to find which one is faster... and this sounds a bit overkill!
major reason:
you initially referred to the PHP http_build_query() function, so I'd expect you work the same, i.e. for a given key: [val_1, val_2]:

you're currently returning key=val_1,val_2
while it should be key=val_1&key=val_2

To match the latter case, I'd suggest something like this:

const output = Object.entries(params).map(
  (pair) => {
    let [key, val] = pair;
    // normalize val to always an array
    val = (val instanceof Array) ? val : [val];
    // encode key only once
    key = encodeURIComponent(key);
    // then make a different query string for each val member
    return val.map(
      (member) => `${key}=${encodeURIComponent(member)}`
    ).join('&');
  }
).join('&');

Your complementary question

To implement null or undefined, first you have to decide how they must be managed: they might be simply omitted, or included with no value (its often useful to have query params where only its presence/absence is meaningful for the underlying application).

Anyway you may simply add any of these capabilities; instead of

    return val.map(
      (member) => `${key}=${encodeURIComponent(member)}`
    ).join('&');

you can include null/undefined params simply with:

return val.map(
  (member) => (member ? `${key}=${encodeURIComponent(member)}` : `${key}`)
).join('&');

(NOTE: it's up to you to enhance this with more precise tests if desired, in order to keep 0 as key=0, or '' as key=)

or you can omit them with a slightly different method:

return val.reduce(
  (result, member) => {
    if (member) {
      result.push(`${key}=${encodeURIComponent(member)}`);
    }
    return result;
  },
  []
).join('&');


Simplify your components functions:

def fxcomponent(x, angle):
    return x * math.cos(math.radians(angle))

def fycomponent(y, angle):
    return y * math.sin(math.radians(angle))

Instead of using number.lower() in every IF statement, convert it once putting number = number.lower() after get the value from input.'
Focusing on readability and maintainability you should extract the copy+paste code of calculating x and y and create a generic function that encapsulates that. So, your code will look like this:

def calculate_fcomponent(component):
    print ('Please tell me the %c and the angle:' % (component))
    value, angle = [int(x) for x in input('>').split()]
    result = fxcomponent(value, angle) if component == 'x' else fycomponent(value, angle)
    print ('The %c component of %d at %d° is: %d' % (component, value, angle, result))
    print()

def run():
    print('Welcome to my Python vector components calculator!')
    print()

    prompt = ('Please select what you wish to find:'
              '\n-type x for x-component'
              '\n-type y for y-component'
              '\n-type quit to end program')

    flag = True

    while flag:
        cmd = input(prompt + '\n>')
        cmd = cmd.lower()

        if cmd == 'quit':
            flag = False

        elif cmd in ('x', 'y'):
            calculate_fcomponent(cmd)

        else:
            print ('Invalid command; try again!')

if __name__ == "__main__":
    run()


There are indeed some things lacking to call this C#5 code: your delegates are not necessary.

The first two are easy: remove the delegate, make the event return EventHandler instead, call the event with Started(this, EventArgs.Empty) and change the method signature accordingly. This results in this:

public event EventHandler Started;

if (Started != null)
{
    Started(this, EventArgs.Empty);
}

public static void WorkerStartedWork(object sender, EventArgs e)
{
    Console.WriteLine("Universe notices worker starting work");
}

The same thing goes for Progressing.

The Completed event is more difficult but only because you made it so. In your Completed event you have 2 consumers at this point. All you have to do is change the signature to EventHandler, change the calling to

if(Completed != null)
{
    Completed(this, EventArgs.Empty);
}

And change all handlers to

public async void WorkCompleted(object sender, EventArgs e) { }

Now it will call every consumer and you don't have to mess around by looking at the invocation list anymore

Don't use the universe statically. Combined with events, that is just bound to cause memory problems. Instead I would make it an instance just like Worker and Boss and then connect its handlers to peter.

By making these changes to the WorkCompleted handlers you'll notice that you can't use Task anymore as a return type. That's true, events are forced to adhere to their void X(object, T) where T : EventArgs definition. Because of this, events are the only place where it is allowed to use async void.

This will cause your events to become fire-and-forget but there are ways around that as well if you don't want this.

Lastly: you now don't have your program spitting out grades. You used to do this in your invocationlist iteration but that was the wrong place for multiple reasons (abuse of events, single responsibility, etc).

I would suggest making a service that allows you to pass in a grade and have it spit out the output.

Combining all these remarks brings me to this:

public class Worker
{
   public event EventHandler Started;
   public event EventHandler Progressing;
   public event EventHandler Completed;

   public void DoWork()
   {
        Console.WriteLine("Worker: work started");
        if (Started != null)
        {
            Started(this, EventArgs.Empty);
        }

        Console.WriteLine("Worker: work progressing");
        if (Progressing != null)
        {
            Progressing(this, EventArgs.Empty);
        }

        Console.WriteLine("Worker: work completed");
        if(Completed != null)
        {
            Completed(this, EventArgs.Empty);
        }
   }
}

public class Boss
{
   public async void WorkCompleted(object sender, EventArgs e)
   {
       await Task.Delay(TimeSpan.FromSeconds(3));
       Console.WriteLine("Better...");
       Grader.Grade(5);
   }
}

public static class Grader
{
    public static void Grade(int grade)
    {
        Console.WriteLine("Worker grade = {0}", grade);
    }
}

public class Universe
{
   public void WorkerStartedWork(object sender, EventArgs e)
   {
       Console.WriteLine("Universe notices worker starting work");
   }

   public async void WorkerCompletedWork(object sender, EventArgs e)
   {
       await Task.Delay(TimeSpan.FromSeconds(10));
       Console.WriteLine("Universe pleased with worker's work");
       Grader.Grade(7);
   }

    private static void Main()
    {
        var universe = new Universe();
        var peter = new Worker();
        var boss = new Boss();
        peter.Completed += boss.WorkCompleted;
        peter.Started += universe.WorkerStartedWork;
        peter.Completed += universe.WorkerCompletedWork;
        peter.DoWork();

        Console.WriteLine("Main: worker completed work");
        Console.ReadLine();
    }
}

I toyed around with events as well some time ago so you might be interested in taking a look at my proof of concept: https://github.com/Vannevelj/VariousSmallProjects/tree/master/KeyConcepts/KeyConcepts/Events


Assumptions I made:

The 3 object will have 3 arrays, just as the 67 object will have 67 arrays
The "combined" array can be computed on demand
Each call to pickNumbers for a certain object will always have the same parameters

Firstly for your objects, I think they belong in a namespace and also a way to define which numbers you want to be in the game:

var Game = {}
Game.NUMBERS = [3, 5];

Next instantiate all the classes:

for (var i = Game.NUMBERS.length; i --) {
  Game[Game.NUMBERS[i]] = new GameNumber(Game.NUMBERS[i]);
}

Let's define what your class would look like:

var GameNumber = function(number) {
  this.number = number;
  this.arrays = [];
  for (var i = number; i --) {
    this.arrays.push([])
  }
}
GameNumber.prototype.combined = function() {
  Array.prototype.concat.apply([], this.arrays)
}
GameNumber.prototype.pick = function(arrayLength, sum, max, min) {
  for (var i = this.number; i --) {
    pickNumbers(this.arrays[i], arrayLength, sum, max, min);
  }
}

Cool, so now you can create your objects in a sufficiently general way and call pick or combined on any of them.

Game[3].pick(5, 40, 20, 1);
Game[3].combined() // Output: [...]

As for the pickNumbers function, I didn't look at the logic too heavily, I'm sure that's working how you want it to. The variable names I would simplify to array, arrayLength, sum, max, min for readability. You may also want to attach it to the Game object so you have less globals (ie Game.pickNumbers = function(...)). I'd also try and abstract the html from it so as to separate logic from presentation.

Note: I haven't tested this code, it's only to give you an idea of how to structure it.