DM::OJ Slot Machines challenge in Python 3

Code organisation, separation of concerns and tests

The code is a single monolithic piece of code. It could be a good idea to reorganise things a bit: to make it clearer, to make it easier to test, to make it easier to maintain, etc.

The first major improvement could be write a function with a clear input (money, m1, m2, m3) and a clear output solving the issue we care about: computing the number of turns.
The logic handling the input/output is separated from the logic performing the computation - seel also https://en.wikipedia.org/wiki/Separation_of_concerns .

Then, this function could be used with inputs from the user but we could also feed it hardcoded values. This can be used to write tests to ensure that the function behaves properly (at least on the example provided by dmoj).

(In the code provided below, I've a simple assert statement to write the tests but it could be a good chance to read about unit test frameworks and start to use them).

Then, you can add any number of tests easily.

Now that we have unit-tests to prevent us from breaking things too badly, we can start tweaking the code.

Finally, you could use if __name__ == "__main__": to separate the definitions in your code from the code actually using these definitions. It makes your code easier to reuse via the import mechanism.

Style

Python has a Style Guide called PEP 8. It is followed (more or less stricly) by the Python community. It is highly recommended to read it and try to stick to it when relevant. In your case, you have superfluous parenthesis, indentations of 2 spaces instead of 4, superfluous whitespaces.

At this stage, we have:

def get_number_of_games(money, m1, m2, m3):
    """Return the number of games <to be continued>."""
    turns = 0
    while money != 0:
        #machine 1
        money -= 1
        m1 += 1
        if m1 == 35:
            money += 30
            m1 = 0
        turns += 1

        #machine 2
        money -= 1
        m2 += 1
        if m2 == 100:
            money += 60
            m2 = 0
        turns += 1

        #machine 3
        money -= 1
        m3 += 1
        if m3 == 10:
            money += 9
            m3 = 0
        turns += 1
    return turns

def interactive_main():
    money = int(input())
    m1 = int(input())
    m2 = int(input())
    m3 = int(input())
    print('Martha plays {} times before going broke.'.format(get_number_of_games(money, m1, m2, m3)))

def unit_test():
    """Run unit-tests."""
    assert get_number_of_games(48, 3, 10, 4) == 66
    print("OK")

if __name__ == "__main__":
    unit_test()

Magic numbers

The code is full of magic numbers, making the logic hard to understand.
We could store these values into constant with a meaningful name.

Even better, we could store these into appropriate data structures. For a simple solutions, we could decide to use namedtuples.

from collections import namedtuple

Machine = namedtuple('Machine', ['winning_freq', 'profit'])

MACHINE1 = Machine(35, 30)
MACHINE2 = Machine(100, 60)
MACHINE3 = Machine(10, 9)

def get_number_of_games(money, m1, m2, m3):
    """Return the number of games <to be continued>."""
    turns = 0
    while money != 0:
        money -= 1
        m1 += 1
        if m1 == MACHINE1.winning_freq:
            money += MACHINE1.profit
            m1 = 0
        turns += 1

        #machine 2
        money -= 1
        m2 += 1
        if m2 == MACHINE2.winning_freq:
            money += MACHINE2.profit
            m2 = 0
        turns += 1

        #machine 3
        money -= 1
        m3 += 1
        if m3 == MACHINE3.winning_freq:
            money += MACHINE3.profit
            m3 = 0
        turns += 1
    return turns

Un-handled situations (also known as bugs)

The code is not very robust. A few situations can lead it astray.

Let's take a simple example: we have 1 quarter and the machines haven't been used. This can be written as:

print(get_number_of_games(1, 0, 0, 0))

When we run this, we are stuck into a infinite loop. I'll let you investigate the reason why.

Another example - which could be considered invalid but is definitly worth fixing because of how simple it is: we have a lot of money and the machines have been used a lot. For instance, we have:

print(get_number_of_games(1000, 36, 101, 11))

Assuming we fix the previous issue: how many turns do we play ? How many times have we won ?

As we fix behaviors, you can add corresponding unit-tests to be sure you don't fall into the same issue later on.

Going further

The code relies on duplicated logic to handle the different machines. A better solution could be to handle them via the same logic. We could imagine having a list of machines.

Also, we could imagine having the numbers of turns played on a given machine stored along with the other information in a Machine class. Then, the get_number_of_games functions could take as inputs an amount of money and a list of properly defined Machines.

Take-away for Python and non-Python code

Make your code testable
Make your code tested and correct
Improve it while keeping properties 1 and 2.


Does the instance() method need to be synchronized?

Theoretically, yes: because unique_ptr isn't thread-safe: therefore you should not call get while another thread is calling reset.

It may be safe in practice.

Alternatively you don't need all the functionality of a unique_ptr.
Instead you could implement its functionality using a dumb pointer, which you can reason about and/or access using the STL atomic functions.

  Is there a better way to handle violated workflow from the instance() method than throwing an exception?

You could return a pointer instead of a reference, and return a null pointer instead of throwing an exception: and expect the caller to check for null before dereferencing the pointer.

Another possibility may be the Null Object pattern: if there's no Config instance then return a reference to an empty Config instance, or a Config instance initialized with suitable default values.

  What are the dangers of call-back from under the lock?

In general the danger of callback from under a lock is 'deadly embrace' a.k.a. 'deadlock'; for example:

Thread 1:

// get the lock
lock_guard<mutex> lock(foo_mutex);
// get the config
config.init("foo", [](string loc){ cout << "I don't care"; });

Thread 2:

config.init("foo", [](string loc){
    lock_guard<mutex> lock(foo_mutex);
    cout << "I don't care";
});

Imagine the following sequence:

Thread 2 enters config and acquires config's lock
Thread 1 acquires the the foo_mutex
Thread 1 blocks on the config mutex (owned by thread 2)
Thread 2 enters the callback
Thread 2 callback blocks on the foo_mutex (owned by thread 1)

It's safe to acquire multiple locks if you always acquire them in the same sequence.
With a callback it's difficult for the author of the Config class to predict what locks might be held before and/or during the callback.
This is a hidden problem for low-level library classes: for example if Logger uses Config in its implementation, Logger and Config each have their own mutex, and a callback from Config tries to invoke a Logger method.

Another problem with callback from under a lock is that you don't know how long the callback is going to take. If the callback takes a long time to execute, then the lock will be held for a long time.

  OK, so callback is now gone.

Perhaps you can keep the callback provided you unlock before calling it:

void Config::init(std::string loc, DupInitCB err_cb) {
  bool succeeded;

  { // scope of lock_guard
    std::lock_guard<std::mutex> lock(init_mutex);
    if (cfg != nullptr) {
      succeeded = false;
    } else {
      cfg.reset(new Config(loc));
      succeeded = true;
    };
  } // lock_guard is released here

  // error callback after releasing the lock`enter code here`
  if (!succeeded)
    err_cb(loc);
};

Or the code within the artificial { ... } scope above could be a private method which returns bool, called from init, and named something like locked_init.


ChunkerTransformStream, a transform stream to take arbitrary chunk sizes and make them consistent

First of all, your code looks great. It brought me to study the internal workings of Node's stream API.

The piece that you're concerned with, and rightfully so, is:

buffer = Buffer.concat([buffer, chunk]);

That's the way to do it. There are no other ways to do what you want to do without using bufferjs, which likely handles things the same way, or less efficiently.

Now, there is one optimization you can make here. By adding the totalLength parameter of Buffer.concat Buffer.concat(list, [totalLength]) you can improve efficiency by avoiding an additional loop in the function, which would need to check the new length of the new buffer.

    Name         Description                                       Required?    Type
    list         List of Buffer objects to concat                  Required     array
    totalLength  Total length of the buffers when concatenated.    Optional     number

  If totalLength is not provided, it is read from the buffers in the
  list. However, this adds an additional loop to the function, so it is
  faster to provide the length explicitly. - See more at:
  http://www.w3resource.com/node.js/nodejs-buffer.php#sthash.qISHPlCO.dpuf

Not sure if this will help or not, but other than that, I don't see any possible optimizations.


Returning a string representation of the number of albums and songs available

Text manipulation like that is always a pain. I like to extract functions for things like this, though.

private static final String simplePlural (int count, String noun) {
    if (count == 1) {
        return "1 " + noun;
    }
    return count + " " + noun + "s";
}

With that function, your code becomes:

public String toAlbumSongCount() {
    return simplePlural(albumCount(), "album")
       + ", " + simplePlural(songCount(), "song");
}

I know there's no StringBuilder in there, but the performance benefit for something that's seldom used, will be negligible, and this is more readable.

Note that the code above adds a space after the comma, which your code is missing.


Rvalue copy and and assignment for secure array class

This code does not function.

Let's take a look at your move constructor:

SecBlock(SecBlock&& t)
{
    std::swap(*this, t);
}

This caused a stack overflow on my system. Why? Imagine if the swap function was implemented like this:

template <typename T>
void swap (T &t1, T &t2)
{
    T temp = std::move (t1) ;
    t1 = std::move (t2) ;
    t2 = std::move (temp) ;
}

In fact, this is how it is implemented by Visual Studio 2012. The first line T temp = std::move (t1) ;, calls your move constructor. This causes you to recursively call your move constructor until your program inevitably crashes.

Another problem is that before the swap, m_size and m_ptr for *this will be uninitialized. So even if you fixed your move constructor, you will be transferring uninitialized data to t. Assuming you're destructor does some clean-up, this could lead to undefined behavior.

All in all, both member-functions are a mess.
Check out the rule of 5 for more help.


To clearly state our problem/task: We want to compare 2 checksums, one supplied as a text being the hexadecimal representation, and the other being an array of the "raw" bytes.

2 forms exist: a hexadecimal representation and raw bytes. To compare them, we need the same representation. So 2 possible paths:

1. Convert the second to hex representation

Let's see your proposed solution. If we want to handle leading/trailing spaces, and if the text input may contain lowercased and uppercased hex digits, your solution is as simple as it can be.

A variation may be to convert the text to lowercased, and then we can simply compare strings without strings.EqualFold(). The lowercase conversion can be done by calling strings.ToLower() or since we already have the input as []byte, by bytes.ToLower():

checkSum = bytes.ToLower(bytes.TrimSpace(checkSum))
argHash := makeHash(flag.Arg(0))
if fmt.Sprintf("%x", argHash) == string(checkSum) {
    // They match
} else {
    // They don't match
}

2. Convert the first to raw bytes

Compare slices ([]byte)

We may choose to convert the text checksum back to a []byte which holds the raw bytes of the checksum (NOT the bytes of the UTF-8 encoded hex representation).

We can parse the hex representation simply with hex.DecodeString(). Or even better: since we have the text checksum as a []byte, we can use hex.Decode() which takes input as a []byte.

As an extra gain, we don't even have to care about lower or upper case: hex.Decode() handles that for us.

And we can convert [16]byte to []byte by simply slicing it. Once we have 2 []byte, we can use bytes.Equal() to compare them (in Go slices are not comparable unlike arrays).

checkSum = bytes.TrimSpace(checkSum)
dst := make([]byte, 16)
if _, err := hex.Decode(dst, checkSum); err != nil {
    // Invalid input, not hex string or not 16 bytes!
} else {
    argHash := makeHash(flag.Arg(0))
    if bytes.Equal(argHash[:], dst) {
        // They match
    } else {
        // They don't match
    }
}

Compare arrays ([16]byte)

As a variation of the previous solution, we will use arrays to do the comparison as arrays are comparable.

Since makeHash() already returns an array [16]byte, we only need to get the raw bytes of the text checksum into an array. The simplest and fastest is to create an array [16]byte, and pass such a slice to hex.Decode() that shares its backing array with our new array. We can obtain such a slice by simply slicing the array:

checkSum = bytes.TrimSpace(checkSum)
dst := [16]byte{}
if _, err := hex.Decode(dst[:], checkSum); err != nil {
    // Invalid input, not hex string or not 16 bytes!
} else {
    if makeHash(flag.Arg(0)) == dst) {
        // They match
    } else {
        // They don't match
    }
}

Compare manually (byte-by-byte)

We can also do the comparison manually, it's relatively easy and straightforward.

But first to do it manually, let's create a simple helper function which tells if a hex digit (the text representation) equals to the raw data:

func match(hex, raw byte) bool {
    if raw < 10 {
        return hex-'0' == raw
    }
    return hex-'a'+10 == raw || hex-'A'+10 == raw
}

And with this the solution:

checkSum = bytes.TrimSpace(checkSum)
argHash := makeHash(flag.Arg(0))
if len(checkSum) != 2*len(argHash) {
    // Quick check: length differ, they don't match!
} else {
    equal := true
    for i, v := range argHash {
        if !match(checkSum[i*2], v >> 4) || !match(checkSum[i*2+1], v & 0x0f) {
            equal = false
            break
        }
    }
    // Now the variable "equal" tells if they are equal
}


The point where the parameters stop and the function-body begins isn't easy to see.
Either indent more, or better consider changing to what c2-wiki calls form 6.

You are allocating way too much when passing arguments.
Using std::wstring_view instead of std::wstring const& lets you avoid that overhead and reduces indirection, which is also a win.

Also, you potentially re-allocate after copying the source when widening to the target-length.

static std::wstring fillWString(
    std::wstring_view source,
    size_t target,
    wchar_t fillChar = L' ',
    std::wstring_view startFill = {},
    std::wstring_view endFill = {}
) {
    if (target <= source.size())
        return source;

    std::wstring result;
    result.reserve(target);
    result += source;
    target -= source.size();

    if (startFill.size() > target)
        return result;
    result += startFill;
    target -= source.size();

    if (endFill.size() > target) {
        result.append(target, fillChar);
        return result;
    }
    result.append(target - endFill.size(), fillChar);
    result += endFill;
    return result;
}


Evaluating an expression with integers, +, and *, as well as -, /

@tim has covered a bunch of what I was going to add, but here are some additional points:

You should anticipate having whitespace in the input. A "simple" replace-all would suffice:

equation = equation.replaceAll("\\s+", "");

Your solution of converting - to +- is novel, and effective, but it really should have a comment on it explaining that you are going to re-split the String and parse the new - as part of the integer, rather than as an operator. Leaving it as it is required some detective work on how it functions.

Bug: Your system will fail on things like: 1 + 2 * -3  (ignoring the whitespace).

Your inner workings of the * and / is a bit messy, though. A logical progression for your challenge would be to add, say, a % operator.... which would require a complicated change.

Operators of equal precedence should be handled together. treating * specially when compared to / makes it awkward because you have to test all combinations inside the * breakdown....

I would suggest using a smarter split expression, one that splits on the gaps between the operators and the values...:

String[] parts = operand.split("(?=[/*])|(?<=[/*])");

With the above regex, you will get for example:

1/2*773 -> [1, /, 2, *, 773]

The way the regex works is that it looks for two things (the regex is in two parts - using "lookaround" expressions)....

(?=[/*]) - A positive zero-width look-ahead - This says: find any gap between two characters where the next character is a / or *.
(?<=[/*]) - A positive zero-width look-behind - This says: *find any gap between two characters where the previous character was a / or *.

Put them together with an or condition, it says: split the input on the gaps before and after / or *.
Now, you can just initialize the result to index-1, and then loop through the rest.... :

double result = Double.parseDouble(parts[0]);

for (int i = 1; i < parts.length; i += 2) {
    String op = parts[i];
    double val = Double.parseDouble(parts[i+1]);
    switch (op) {
        case "*" :
            result *= val;
            break;
        case "/" :
            result /= val;
            break;
    }
}
return result;


This code looks reasonably clean and seems to accomplish what it's intended to do.
Some minor nitpicks can still be improved here and there:

You're not consistent in visibility modifier ordering between class declaration and member declarations. It should either be public final class or final private static int timeout.
Most Java conventions that I've seen default to the public static final ordering.
handler and logo are currently package-private. It's very unusual for that visibility to be necessary and I think setting these to private if at all possible would be better. (I'm not recommending protected, because the class can not be extended.)
static final members are usually named in SNAKE_CAPS (also known as shout-case).
the id companylogo might be better off named companyLogo to follow camel case conventions.
myanimation doesn't tell us anything about the animation. A better name would be splashScreenAnimation or logoAnimation


FizzBuzz implementation using the ternary operator

even if it involves telling me that starting with Ideone is not the best choice for whatever reasons.

As a beginner, starting with Ideone is not the best choice IMO. For a number of reasons:

It is not a good practice to use import xxx.xxx.*. Only import the things that you actually need. In this case, you don't even need to import anything (because the things that you need are part of the java.lang package.
In IdeOne the filename is "Main.java" and there is no way to change that, which means that you will not learn that a public class in a file must have the same name as the file itself. I.e. the public class SomeClass must go in a file named SomeClass.java.
In IdeOne you are not able to declare a package name. A package name is mainly used to identify projects and the author of the code and so on. They are usually your domain-name backwards. For example, as I own zomis.net my package names are net.zomis.someproject. If you don't own a domain, well... make one up for now. com.jamal could work for you. Either way, usage of the "default"-package (i.e. not declaring a package at all) is discouraged.
In IdeOne there is no direct feedback for compiler errors. You have to click "Run" on your code to make sure that it has no compiler errors. In all modern Java IDEs you automatically get such feedback whenever you have finished writing a line of code (sometimes you have to hit Ctrl+S to save though before it will show the errors properly). This may not feel important at first, but once you get used to it you will really miss the feature in other IDEs.

As for the code itself, it isn't that bad. It is good that you removed IdeOne's throws Exception declaration.

Greg has already covered the aspects of the conditional operator, so there is only one thing I can possibly comment about, but this is just a personal opinion more than anything else and feel free to completely ignore this comment.

for (int i = 1; i <= 100; ++i) {

In Java, it is more common in such for-loops to use i++ rather than ++i. Although this has no effect whatsoever in this case, and I'm sure you're aware of the differences between i++ and ++i from your C++ (or is it ++C?) experience.

When using ++i or i++ alone (i.e. without an assignment to another variable), there is a myth that there is a performance difference in C++ and C, while apparently that is not the case.

In Java, it is also exactly the same (the same applies for C#, if you're wondering).

Of course, using i++ or ++i always matters when adding another assignment. If i = 1:

a = i++ will make a == 1
a = ++i will make a == 2
i == 2 after the statement in both cases


I like this opportunity for a code review because I hopefully can share some good programming techniques that I didn't have a chance to learn until I actually got out of school and into the industry. I can edit to explain anything further.

Your variable infixExpression can be defined as final:

private final String infixExpression;

This isn't necessary but is good practice as it's a good idea to maximize the immutability of your classes. Anything variable which is only modified when declared, or in a constructor, may be final.
The convertInfixExpression method should also be public. I know this is for an assignment, but that should not stop you from thinking about using it outside the main method. Alternatively, you could do away with the constructor altogether, and just make this method static. That way, you would use it by calling

PostfixConverter.convertInfixExpression("my infix expression");

This is possible by changing your current convertInfixExpression method signature to

public static String convertInfixExpression(String infixExpression)

I don't know what library ArrayStack came from, but I can assume how it works. That being said, you don't parametize it which is a big no no, and causes yourself some extra work later. This should be

Stack<String> operatorStack = new ArrayStack<String>();

In Java, appending to a String is typically a bad idea. If you have an object you know you'll be appending too, use a StringBuilder:

StringBuilder converted = new StringBuilder();

Concerning the first while loop in the method, I don't like the looks of it from a glance. There's way too many nested while, if, and else statements. We'll see if we can simplify some of that. To start, let's look at the highest level of what's going on:

If token is a '(' push to stack
If token is a ')' do complicated stuff
If token is an Operator do complicated stuff
Otherwise append the token to the result

So the hint here is that you want to move all that complicated stuff to separate methods. Your code benefits from this by being much easier to read and reason about.
There's almost never a reason to use the new keyword next to String in Java.

operatorStack.push(token);

not

operatorStack.push(new String(token));

The first complicated block (fixed formatting):

while(operatorStack.top().equals("(") != true) {
    converted = converted + " " + operatorStack.pop();
}
if(operatorStack.top().equals("(")) {
    operatorStack.pop();
}

I guess this isn't too complicated, but I don't like seeing nested while statements... This is how I would write it:

while(!operatorStack.top().equals("(")) {
    converted.append(" ").append(operatorStack.pop());
}
operatorStack.pop();

I'll highlight the differences:

There's no reason to ever compare anything to true or false in an if statement.
Used append from the StringBuilder. Check out the Oracle tutorial on this class to find out why.
There's no reason for the if statement. We already know the a ( is on the top of the stack, otherwise the previous loop wouldn't have ended.

Regarding the second complicated bit, I would write it like so:

else if (isOperator(token)){
    if(operatorStack.isEmpty()) {
        operatorStack.push(token);
    }
    else {
        if(ICP(token) < ISP(operatorStack.top())) {
            converted.append(" ").append(operatorStack.pop());
            operatorStack.push(token);
        }
        else {
            operatorStack.push(token);
        }
    }
}

Pretty much the same comments as above, but notice you don't need to cast to a String because you've now parametized your stack. Too be honest, though I'm still not entirely sure of the purpose of the logic here, but mainly because I have no idea what ICP and ISP mean!
Use descriptive and conventional method names. If ICP and ISP return a value, they should start with get. I know they're return the precedence of operators, but the S and C is still unclear to me. That being said, you can simplify all of this by using some Map constants. For example,

private static final Map<String, Integer> S_PRECEDENCE;
static {
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("+", 2);
    map.put("-", 2);
    map.put("*", 4);
    ....
    S_PRECEDENCE = Collections.unmodifiableMap(map);
}

And then you can change the ISP method to something like

public int ISP(String token) {
    return S_PRECEDENCE.contains(token) ? S_PRECEDENCE.get(token) : 0;
}

I'll note that S_PRECEDENCE is a bad name and should be expanded with whatever S means.
Along the same lines, you can make a Set of your operators, and simply check if that collection contains the token.


Extract integers from a string that is split at given positions

Walking across the list of positions from the right cuts off suffixes, requiring you to keep traversing and copying the corresponding prefixes over. If you cut off prefixes instead, you only need to traverse once.

import Data.List
import Data.Tuple

splitAts :: [Int] -> [a] -> ([[a]], [a])
splitAts is xs = swap $ mapAccumL go xs (zipWith (-) is (0:is)) where
  go :: [a] -> Int -> ([a], [a])
  go xs i = swap $ splitAt i xs

This piece of code is, incidentally, the epitome of order confusion and what wouldn't happen if there was a way to bundle API updates with automatic patchers to old code.


The code is understandable, but it can be simplified.

Instead of:

public function unset_session()
{
    if (isset($this->session))
    {
        $this->session =  null;
    }
}

You can simply:

public function unset_session()
{
    $this->session =  null;
}

Instead of:

public function get_session()
{
    if (isset($this->session))
    {
        return $this->session;
    }
    else
    {
        return false;
    }
}

You can simply:

public function get_session()
{
    return $this->session;
}

(if you don't mind that it returns a falsy value (null) instead of a real false)

Instead of:

public function is_logged_in()
{
    if (isset($this->session))
    {
        return true;
    }
    else
    {
        return false;
    }
}

You can simply:

public function is_logged_in()
{
    return isset($this->session);
}

Instead of:

public function get_error($key)
{
    if (isset($this->error[$key]))
    {
        return $this->error[$key];
    }
    else
    {
        return false;
    }
}

As of PHP 5.3, using the short ternary operator, you can simply:

public function get_error($key)
{
    return $this->error[$key] ?: false;
}


Python calculate arrangements of sequence

Notes

I'd expect arrangements to return the unique permutations of sequence, not just how many there are.
If it returns a number, it should be an integer.
You could use collections.Counter instead of counting the integers again and again.
You're right, it would be nice to have itertools.unique_permutations. In the meantime, I often come back to this SO answer.

Possible refactoring

from math import factorial
from functools import reduce
from collections import Counter
from operator import mul

def count_unique_permutations(sequence):
    count_permutations = factorial(len(sequence))
    repetitions = (factorial(v) for v in Counter(sequence).values())
    return count_permutations // reduce(mul, repetitions)


Returning status codes from business layer

Status codes have long gone the way of the Dodo --- made extinct by exceptions, actually.

The problem with a status code is that it can be ignored. An exception cannot. Consider these two examples.

Status Codes as Return Values

First, the "merchant repository" implementing CRUD operations for merchants:

public enum MerchantStatusCode
{
    OK = 0,
    Created = 1,
    Updated = 2,
    Deleted = 3,
    MerchantAlreadyExists = 4,
    MerchantDoesNotExist = 5
}

public class MerchantRepository
{

    public MerchantStatusCode Create(Merchant model)
    {

        if (MerchantExists(model))
            return MerchantStatusCode.MerchantAlreadyExists;

        // Save to DB

        return MerchantStatusCode.Created;
    }
}

Now, the C# code to create a merchant and ignore error handling:

var merchantRepository = new MerchantRepository();

// Create a merchant. I'm not really sure what could go wrong, and if
// something should go wrong, I'm not really sure if it's a problem.
merchantRepository.Create(merchant);

The MerchantRepository.Create method returns a status code that our programmer promptly ignores. By looking at these lines of code, there is no indication that you should do any error handling before subsequent lines of code are executed.

Status Codes as Output Parameters

Let's also say an output parameter is used:

public class MerchantRepository
{
    public void Create(Merchant model, out MerchantStatusCode statusCode)
    {

        if (MerchantExists(model))
        {
            statusCode = MerchantStatusCode.MerchantAlreadyExists;
            return;
        }

        // Save to DB

        statusCode = MerchantStatusCode.Created;
    }
}

And the code to ignore the status code:

var merchantRepository = new MerchantRepository();
MerchantStatusCode code;

// Create a merchant. Sure I could check the "status" but, meh. If
// something fails it must not be THAT important. After all, good
// programmers are lazy, right?
merchantRepository.Create(merchant, out code);

While this exhibits more of a code smell, an error code doesn't halt program execution.

Now, let's tweak this to throw an exception:

Using Exceptions

public class MerchantRepository
{
    public void Create(Merchant model)
    {
        if (MerchantExists(model))
            throw new RecordExistsException();

        // Save to DB
    }
}

public class RecordExistsException : Exception
{
    ...
}

And the C# code to use this in the same manner as the previous example where the programmer blissfully ignores problems:

var merchantRepository = new MerchantRepository();

try
{
    merchantRepository.Create(merchant);
}
catch Exception
{
    // I realize this method throws exceptions when it fails to create
    // a merchant, but I am a complete idiot as a programmer, and
    // failure as a human being, so I'm going to blindly swallow any
    // possible errors, then move to another team or job and let you
    // try tracking down this production problem for 6 months while
    // the company bleeds customers and your boss screams at you so
    // hard he spits his bagel and coffee all over your face.
    //
    // But, hey. At least I didn't write "TODO: Error handling"!
}

Both examples work the same when the code is executed and a duplicate merchant is created, but there is one glaring difference here: The empty try-catch block. Empty try-catch blocks go beyond "code smells" to "steaming piles of rotting flesh that have been baking in the sun all afternoon." I get an ulcer every time I see this.

Now, if we tweak example #2 to be the exact same code as example #1:

var merchantRepository = new MerchantRepository();

// Even though I don't handle an exception, at least the next
// line of code won't execute if something goes terribly wrong.
// I'm not an idiot. I just HAVE to create a merchant here, and
// failure to do so is a hard stop.
merchantRepository.Create(merchant);

No subsequent lines of code will get executed, and the programmer does not have to guard against this condition unless they want to.

The lesson here: For the love of God do not blindly trap exceptions and do nothing, unless you document this behavior in comments and provide a really really really really really really really really really really really really really good reason for doing so.

Regarding your particular approach, there are a couple things that you should be doing instead:

Error Handling Best Practices Regarding Database Operations

Prior to creating a merchant, check the database to ensure the merchant doesn't already exist. This is basic data validation, and should be handled in its own layer.
When creating a merchant, if a merchant happens to exist, throw an exception which will force you, as a programmer, to handle this "exceptional situation" (hence the term Exception).

When a database operation is invoked, it needs to assume that all data is valid, and then throw an exception if anything goes wrong. Things should never be wrong in the first place, and the data access layer has no way of remedying this problem, so throwing an exception halts any further operation. Failing to create a merchant is a catastrophic, unresolvable issue requiring the immediate cessation of logic.

If attempting to create a duplicate merchant is something you can handle, then your Controller needs to trap this exception and handle it.

An interesting blog post about error codes and exceptions:

Error codes or Exceptions? Why is Reliable Software so Hard?

There can be a case for either, but I generally lean towards exceptions because they halt application execution, which is what you want most times.


Okay, I am not sure exactly in what limits your exercise is, but I'll answer to what I think is good web standard. (I've been a web developer for ~4 years)

Don't use the align attribute. HTML is supposed to be a markup language. Use CSS to control the appearance of your html elements. In this case something like h1 { text-align: center; } should do just fine.
Don't use the
 tags for other things than actual line-breaks (that is, to break text). I would remove all
 tags, since you don't need them in this exercise. Elements like ul, li and p are by default block elements, which flows vertically. If you need more space between elements, use margin/padding instead. However, img is not a block element by default, so you can either wrap it in a div or make it a block element using CSS like img { display: block; }.
Do not put a ul inside a p tag. Close the p tag and then add another p tag after the ul instead.
Fine detail: insert line breaks in text to increase readability. A typical practice is to keep lines less than 80 characters.

Btw, you do know that there are validator tools for HTML, right?

EDIT: Full code, in a better way: (Note that I chose to preserve one br tag. Maybe it can be an exercise to figure out why)

<!DOCTYPE HTML>

        <title>BLA| Welcome </title>

Meet Jack

He is Jack. He is an odd little boy that just got an empty box for his
               birthday. He may look happy but is a little
               disappointed. Now he will have to put a little things in the box.

               Jack would really like...

Roller blades

Magic tricks

Anything Pokemon

A motorized Lego set

You can get all this (and more) at an online toy store. Two very popular
               ones are toysrus.com and
               eToys.


Log and Count the exception in a Single method

Is there any more cleaner way of doing the same thing? Meaning right now I am counting the exceptions in a method and then printing out the exceptions in the next line inside the catch block.
  Is it possible to do the both of the things in the same addException method?

It depends. You could configure the logger and add a new a appender. Then your logger serves two appenders: The (probably) println and the counting.
Otherwise, you could add the log call inside the addException method (could be renamed to handleException(...) then).

  And if the flag is true to terminate the program, then terminate the program with the proper logging as well.

I highly suggest to avoid boolean flag arguments. If you have a public api, this suggestion is a must. Look at java for a lot of bad examples.
Use two methods:

private static void addException(String cause) {
  ...
}

private static void addExceptionAndTerminate(String cause) {
  addException(...);
  System.exit(1);
}

(And I do not see the point of adding the exception if you terminate anyway, but it could be for some multithreading things.)

  What could be the best way to re write addException method do this?

I would change the method signature from String, Boolean to Exception and put all exceptions inside a synchronized list.
Only if I want to get some statistics, I would start to parse them. Which makes the live easier for everyone who is using this.
At the moment, the functionality depends on the format of the string. If you or someone else, does not use the correct format, it does not work.
therefore, you sould document this at least in the javadoc. And the correct formatting is a pain, noone will like to write like this.
And I am not sure if the implementation for concurrent map access is correct.

If you just allow an exception object, noone has to care about formatting, the synchronization is a lot easier (just add to the list) and you have all the freedom in some other method how to count, parse
and do whatever you want with this exceptions.


The call can apparently fail if the matrix supplied is larger than the internal buffer in the function. Yet there is no indication that this was the case. matrix_transpose should return an error code indicating the result of the operation.
float buffer[MATRIX_TRANSPOSE_BUFFER_SIZE]; lives on the stack of the function. The stack is usually limited to a few MB (I think default in Visual Studio is 1MB, on Linux it's typically around 8MB but depends on the setup). Not sure how big the matrices will get but this might get you into trouble. Consider using either a static buffer (not thread safe) or allocate the buffer via malloc on the heap.
Instead of *(matrix + current_row * columns + current_column) you can also write matrix[current_row * columns + current_column] which is a bit easier on the eyes (imho).
It is accepted practice that loop counters can be single letter variables. In conjunction with the fact that you operate on a 2 dimensional array you could consider renaming current_row into y and current_column into x. Shortens the code somewhat and doesn't loose much meaning. Using x and y to identify positions in a 2D structure is common practice.
When you transpose a matrix which is not square then the calling code will not be directly exposed to the fact that rows and columns are now transposed. You should pass rows and columns "by reference" (int *) and swap them before you return from the function. Otherwise the calling could needs to do that every time it calls the transpose function and the programmer is bound to forget it at one point.


Python recursive function that receives list of strings, and returns a nested list of anagrams

I think a much simpler approach would be beneficial to you here, as well as if you were to utilize a dictionary to hold the results as you go along. The below code does not make use of recursion though, so if you were trying to learn about recursion in python then this would not help. But if you're just trying to learn what a simple and pythonic function to solve this problem would look like then I think this will help you. Notably it is much less code, easier to reason about, and does not make use of global variables.
def sort_anagrams2(list_of_strings):
    result = {}

    for string in list_of_strings:
        sorted_string = "".join(sorted(string))

        if sorted_string in result:
            result[sorted_string].append(string)
        else:
            result[sorted_string] = [string]

    return list(result.values())


Only focusing on the code in question (not on OWIN)

Using region outside of methods is discussed controversially but using region's inside a method is clearly a code smell. It indicates that a method is too big or worse that a method has too many responsibilities.

Instead of adding "Request" to the List and using the string "Request"  in the switch you should declare a const holding "Request" and which you should add to the List and use it in the switch to reduce the possibility of spelling errors.

Using a switch for a single case should be better changed to a simple if statement.

You should use braces {} for single statements if's too. This will make your code less error prone.

Variables should be declared as near as possible to their usage. So changing

var request = context.Request;
var response = context.Response;
var path = request.Path.Value.TrimStart('/');
if (!_knownRequests.Contains(path))
    return;

response.StatusCode = 200;

to

var request = context.Request;
var path = request.Path.Value.TrimStart('/');
if (!_knownRequests.Contains(path))
{
    return;
}

var response = context.Response;
response.StatusCode = 200;

would be better.

Using the var keyword should be only done when the type of the right hand side of the declaration is obvious.
This is only true for the last usage here:

var request = context.Request;
var response = context.Response;
var path = request.Path.Value.TrimStart('/');

so better change it to

IOwinRequest request = context.Request;
IOwinResponse response = context.Response;
var path = request.Path.Value.TrimStart('/');

but using the request does not add to much value here,because it is only used once, so you could just change it to

IOwinResponse response = context.Response;
var path = context.Request.Path.Value.TrimStart('/');


Two icon animations — one on the left, one on the right

Make a function with one parameter, depending on the direction (right or left), copy a block of code and replace the key word there.


Select member for comparison in sort or search

This might be a bit nitpicky, but Asc and Desc aren't that good of names for classes. Granted, they are in your detail namespace, so it should be fine, but why not just write out the names Ascending and Descending?

I do find Asc more ambiguous than Desc, because I see "desc" as shorthand for "descending" more often.

Both Desc and Asc are structs, which means that your public: is redundant. You probably want to make them classes, as it seems you want to hide the fn member variable.

Why restrict the sort-by function to being by member variables? You could easily let it work for any callable object:

template <class F>
class Asc {
    F fn;
public:
    Asc(F fn) : fn(std::move(fn)) {}

    template <typename Lhs, typename Rhs>
    bool operator()(Lhs&& a, Rhs&& b) {
        // by separating the types like this, we gain a little bit
        // of generality. Not that it matters if we are using it
        // with std::sort only. However, really what the overall
        // utility is doing is defining a comparator, so you might
        // want to keep it more general
        return fn(std::forward<Lhs>(a)) < fn(std::forward<Rhs>(b));
    }
};

I know that, at this point, this removes the ability to use member functions at all, but we can use std::invoke to remedy that:

    template <typename Lhs, typename Rhs>
    bool operator()(Lhs&& a, Rhs&& b) {
        return std::invoke(fn, std::forward<Lhs>(a)) < std::invoke(fn, std::forward<Rhs>(b));
    }

Although std::invoke does require C++17. If you don't want to require C++17, this Stack Overflow question discusses how to get the behavior of std::invoke in C++11. In particular, you can use std::ref:

    template <typename Lhs, typename Rhs>
    bool operator()(Lhs&& a, Rhs&& b) {
        return std::ref(fn)(std::forward<Lhs>(a)) < std::ref(fn)(std::forward<Rhs>(b));
    }

Although you may want to wrap the std::ref(callable)(args...) into a utility function to make the code more self-documenting

There's also a small problem, where if the field we are sorting by is a pointer, you can have undefined behavior. Comparing pointers with operator< is only allowed if the pointers are from the same array. So it would be better to use std::less:

    template <typename Lhs, typename Rhs>
    bool operator()(Lhs&& a, Rhs&& b) {
        return std::less<>()(std::ref(fn)(std::forward<Lhs>(a)), std::ref(fn)(std::forward<Rhs>(b)));
    }

But if you don't have C++14, you'd have to write something like this instead:

    template <typename T>
    bool operator()(T const& a, T const& b) {
        auto cmp = std::less<
            std::decay_t<decltype(std::ref(fn)(a))>
        >();
        return cmp(std::ref(fn)(a), std::ref(fn)(b));
    }

Also, we can actually combine both Asc and Desc. Currently, the only difference is that you call operator< with the arguments in the other order.

Instead, what we can do is take a comparator in our class:

template <class F, class Compare = std::less<>>
class SortBy {
    F fn;
    Compare cmp;
public:
    SortBy(F fn, Compare cmp = {})
        : fn(std::move(fn))
        , cmp(std::move(cmp))
    {}

    template <typename Lhs, typename Rhs>
    bool operator()(Lhs&& a, Rhs&& b) {
        return cmp(
            std::invoke(fn, std::forward<Lhs>(a)),
            std::invoke(fn, std::forward<Rhs>(b))
        );
    }
};

Then, you can reduce your ascending and descending functions down to a single function:

template<typename F, typename Compare = std::less<>>
SortBy<F, Compare> sort_by(F fn, Compare cmp = {}) {
    // by using uniform initialization, we don't have to repeat the
    // type of SortBy<...>
    return { std::move(fn), std::move(cmp) };
}

If the user wanted to sort descending, they'd have to use sort_by(..., std::greater<>). That does require that an operator> is defined for their type, but they can always define their own comparator that defines a greater-than by using operator<

Orthogonally, splitting the Lhs and Rhs arguments for the operator() makes our SortBy a transparent comparator, so we should indicate this by adding a is_transparent typedef:

template <class F, class Compare = std::less<>>
class SortBy {
    F fn;
    Compare cmp;
public:
    using is_transparent = void;

    SortBy(F fn, Compare cmp = {})
        : fn(std::move(fn))
        , cmp(std::move(cmp))
    {}

    template <typename Lhs, typename Rhs>
    bool operator()(Lhs&& a, Rhs&& b) {
        return cmp(
            std::invoke(fn, std::forward<Lhs>(a)),
            std::invoke(fn, std::forward<Rhs>(b))
        );
    }
};


Instead of using ids #r, let's include in the element the attribute data-something to differentiate the elements that must have the behavior setted by the function. Using a div, for instance:

We won't need the ids with #r anymore. Considering that you already have the elements #h* we just need to put the id number inside data-something of the corresponding element, so that the function can use it:

$("div[data-something]").hoverIntent(function() {
    var idNumber = $(this).data("something");
    $('#h' + idNumber).toggleClass('vis');
});

Now, you just need to use the data-something attribute.


Solution 1:

If all of your grp* inherits of the same object (say Control), what you can do is:

private List<Control> _groups = new List<Control>();

.ctor()
{
   // Populate _groups
   _groups.Add(grpPeriod);
   _groups.Add(grpPrintOptions);
   _groups.Add(grpInvoiceInformation);
   _groups.Add(grpHND);
   _groups.Add(grpArchiveDocument);
   _groups.Add(grpBalanceControlList);
}

Now you method becomes:

private void dlgOptionsForm_Load(object sender, System.EventArgs e)
{
    if (_hideAccountingOption)
    {
        Adjust(grpAccountingOption);
    }
    if (_hidePeriod)
    {
        Adjust(grpPeriod);
    }

    if (_hidePrintOptions)
    {
        Adjust(grpPrintOptions);
    }

    ....
}

private void Adjust(Control control)
{
    control.Visible = false;
    this.Height -= control.Height;
    chkPrint.Checked = false;

    foreach (var item in _groups)
    {
        if(control != item)
            item.Top -= (control.Height + 8);
    }
}

EDIT

Solution 2:

Dictionary<Func<bool>, Control> _groups= new Dictionary<Func<bool>, Control>();

.ctor()
{
   // Populate _groups
   _groups.Add(() => _hidePeriod, grpPeriod);
   _groups.Add(() => _hideInvoiceInformation, grpInvoiceInformation);
   _groups.Add(() => /* your bool variable */, /* the associated control */);
   // ...
}

private void dlgOptionsForm_Load(object sender, System.EventArgs e)
{
    foreach (var item in _groups)
    {
        if (item.Key()) // Evaluate the boolean variable
            Adjust(item.Value);
    }
}

private void Adjust(Control control)
{
    control.Visible = false;
    this.Height -= control.Height;
    chkPrint.Checked = false;

    foreach (var item in _groups)
    {
        if(control != item)
            item.Top -= (control.Height + 8);
    }
}


Generate XKCD passwords from single Bash line

shuf: Is it truly random?

No. According to the GNU documentation,

  By default these commands use an internal pseudo-random generator initialized by a small amount of entropy, but can be directed to use an external source with the --random-source=file option.

For password generation you'll want to use --random-source=/dev/random.

gsed 's/.*/\u&/'

I've not seen this before. Nice trick, but it can be done in pure bash. The catch is that bash case modification is part of parameter expansion, so you have to store each word in a variable, and you'll need a loop. If you're not completely committed to having a one-liner then this is something which could be pulled out as an auxiliary function, and you might even find it useful elsewhere.

tr -d '\n' | awk '{print $1}'

awk seems a bit heavyweight given that the only reason for calling it is to append a newline. I'd replace with

tr -d '\n'; echo

In order to speed things up at the cost* of a small reduction in entropy, you could try to rewrite so that you only call shuf once, getting 128 words, and then split them into fours.

* (There's room for debate as to whether it's a cost or a benefit when you see whether using /dev/random slows things down while it tries to refill its entropy pool).


If your output is really what you desire, you are working way too hard for this.
In your original solution you work from the back, and sum all the needed elements in each step to generate the new sum. This is inefficient. Working from the back, you can reuse the sum from the previous step and just add the current element on top of it.
def parts_sums_from_the_back(ls):
    nls = []
    sum_ = 0
    for element in reversed(ls):
        sum_ += element
        nls.insert(0, sum_)
    return nls

You can also work from the front. Then you start with the sum over all elements, and subtract the elements as you go along:
def parts_sums_from_the_front(ls):
    nls = [sum(ls)]
    for i in range(len(ls)-1):
        nls.append(nls[i]-ls[i])
    return nls

Sidenote: As you can see, sum is already taken in Python, so you should not use it to name your own variables.
Also, since what you are doing is not uncommon it even has a special name: cumulative sum. Just think about it for a second how your code can be expressed in terms of a cumulative sum. In the meantime, let me introduce you to NumPy. NumPy is a specialized library for numeric computations, and as such also has a implementation of a cumulative sum.
import numpy as np

def parts_sums_np(ls):
    return np.cumsum(ls[::-1]).tolist()[::-1]

Spoiler: As you can see, your result is cumsum of the reversed list, reversed again.
Addendum: Since I'm usually working with Python in a scientific context I'm quick to use NumPy for quite a lof of tasks. Fortunately there are experienced people like Maarten Fabré who know a thing or two about Python. He gave the following implementation in a comment below which only uses tools from Python's standard library:
from itertools import accumulate

def parts_sums_itertools(ls):
    return list(accumulate(reversed(ls)))[::-1]

itertools.accumulate is a very handy function to express all kind of cumulative computations. If used on a sequence with no further arguments it computes the cumsum, but it can also be used to implement other algorithms like cumulative multiplication.

I tested all of them with this little snippet:
ls = [1, 4, 6, 4]
nsl = [15, 14, 10, 4]
print("parts_sums", parts_sums(ls) == nsl)
print("from_the_back", parts_sums_from_the_back(ls) == nsl)
print("from_the_front", parts_sums_from_the_front(ls) == nsl)
print("numpy", parts_sums_np(ls) == nsl)
print("itertools", parts_sums_itertools(ls) == nls)

which happily prints
parts_sums True
from_the_back True
from_the_front True
numpy True
itertools True

Where parts_sums is your original implementation.

Timing
I also performed some preliminary timing. With the input given in your question the results are as follows:

parts_sums: 5µs
from_the_back: 1.6µs
from_the_front: 2µs
numpy: 13µs
itertools: 1.15µs

As you can see itertools takes the leadworking from the back is the most efficient approach since it doesn't make it necessary to look at all elements of the list beforehand. NumPy performs actually quite poorly here. This is likely due to the overhead from going from Python to the C backend of NumPy and back again.
I repeated the timing for an input with 1000 elements. The results are as follows:

parts_sums: 185ms
from_the_back: 690µs
from_the_front: 285µs
numpy: 170µs
itertools: 63.1µs

As you can see, all the repeated summing makes your original implementation scale really badly. Also, from_the_front and from_the_back have switched places. This is likely because .insert(0, ...) is more expensive than .append(...). You can work against this dynamic array growing since you know exactly how large the array will be at the end. If you accomodate for this (see code below), the time goes down from over 600µs to around 270µs. At this point you also see that NumPy starts to play its strengths. NumPy might get stronger here, but itertools still dominates the comparison by a considerable margin.
def parts_sums_from_the_back_pre(ls):
    nls = [None, ]*len(ls)
    sum_ = 0
    for i, element in enumerate(reversed(ls)):
        sum_ += element
        nls[-(i+1)] = sum_
    return nls

Appendix: Further timing
I performed some extended timings to generate a visual presentation how the function runtimes scale with the list length.

As expected, the original implementation scales very badly with the size of the input. This becomes even more obvious if you look at the plot with linear axis scale on the left (click for full resolution).
While creating the test routine I also came to the conclusion that NumPy loses against itertools because it has to convert the data from Python to NumPy's own format. If you repeat the test above using input already in NumPy's own format, NumPy steals the lead from the itertools implementation.


Data transformation involving dictionaries and lists

TL;DR: Scroll to the end for the provided code with suggested improvements

Suggestions

1. Standalone cartesian_product helper function outside scope of combinations

A preferable solution would be to simply use itertools.product as most Python-savvy readers will be familiar with it - and it is well-documented for those that aren’t. However, since you explicitly mention it...

If you still don't want to use itertools.product:

While it does improve clarity to construct a hierarchy of scopes that expose things only when necessary, in this case, I believe that making cartesian_product a nested function inside combinations serves only to confuse the purpose of combinations. It is better to define cartesian_product above, making the code below cleaner and easier to understand. Now someone reading your code will first see cartesian_product’s definition and understand its relatively simple purpose. Then, inside ParametricMapping.combinations, readers are already familiar with cartesian_product, and their train of thought isn’t derailed by trying to understand a nested function.

2. flatten helper function

This helper function should be used thusly:

for term in cartesian_product(*pools):
    results.append(flatten(term))

This may seem silly as flattening is a simple operation, but in this example there are a few fairly tricky list/dict comprehensions nearby. Therefore, it may help to replace that piece with a simple flatten call to clean up some confusion and to emphasize that this is  a straight-forward operation - A fact that could be lost on some readers of the code in its current state. My point here is that stacking lots of loops and comprehensions on top of each other (especially without documentation/comments) can quickly get messy and confusing.

3. Consolidate some code

If you took both of the above suggestions, a nice opportunity to consolidate some code has presented itself. After the above changes, the section that was originally

results = []
for term in cartesian_product(*pools):
    results.append([pp for p in term for pp in p])

should now be

results = []
for term in itertools.product(*pools):
    results.append(flatten(term))

This block can be expressed clearly and concisely with the following list comprehension:

results = [flatten(term) for term in itertools.product(*pools)]

Note that because of the separation of functionality into helper functions, the purpose of this list comprehension is abundantly clear. It creates results, which is a list containing the flattened outputs of product.

4. Check for empty mappings at top of combinations

Instead of the if/else at the end of combinations that checks for len(tmp) == 0, make the first two lines of combinations the following:

if self.mappings == [{}]:
    return [{}]

The else clause at the bottom of combinations is no longer necessary, and you can simply return tmp. This is cleaner because it handles the case where mappings is empty immediately, which means those cases bypass all the code that was being executed before when len(tmp) was evaluated at the end of combinations. This also allows readers to make the assumption that mappings is non-empty when they get into the actual work being done by combinations, which is just one less thing to worry about. Alternatively, a more concise option would be to replace

if len(tmp) == 0:
    return [{}]
else:
    return tmp

with

return tmp or [{}]

This works because if mappings is empty, the value of tmp will be an empty list, which will evaluate to False, returning the value following the or. This more concise version may come at the cost of decreased readability.

5. Define labels and pools using helper methods or non-init fields

Remove the first two code lines from combinations, and move them to either helper methods, or additional fields that are processed post-initialization. I recommend doing this to further clarify the work actually being done by combinations and to clean up the code overall. These both have the added benefit of exposing labels and pools as additional attributes of the dataclass that can be accessed outside of combinations.

See the ParametricMapping1 class defined in the section below for an implementation using helper methods, and see the alternative ParametricMapping2 class defined below it for an implementation using non-init fields.

TL;DR

In the end, if all suggestions are followed, the code should include the below declaration of flatten, along with one of the two following blocks (ParametricMapping1, or ParametricMapping2):

def flatten(l):
    return [item for sublist in l for item in sublist]

With either ...

@dataclass
class ParametricMapping1:
    mappings: List[Mapping[Tuple[str], Sequence[float]]] = field(default_factory=lambda: [{}])

    def _labels(self) -> List[Tuple[str]]:
        return flatten(self.mappings)

    def _pools(self) -> List[List[Sequence[float]]]:
        return [list(map(tuple, zip(*arg.values()))) for arg in self.mappings]

    @property
    def combinations(self) -> List[Mapping[Tuple[str], float]]:
        if self.mappings == [{}]:
            return [{}]

        pool_values = [flatten(term) for term in itertools.product(*self._pools())]
        return [dict(zip(self._labels(), v)) for v in pool_values]

Or ...

@dataclass
class ParametricMapping2:
    mappings: List[Mapping[Tuple[str], Sequence[float]]] = field(default_factory=lambda: [{}])
    labels: List[Tuple[str]] = field(init=False, repr=False)
    pools: List[List[Sequence[float]]] = field(init=False, repr=False)

    def __post_init__(self):
        self.labels = flatten(self.mappings)
        self.pools = [list(map(tuple, zip(*arg.values()))) for arg in self.mappings]

    @property
    def combinations(self) -> List[Mapping[Tuple[str], float]]:
        pool_values = [flatten(term) for term in itertools.product(*self.pools)]
        return [dict(zip(self.labels, v)) for v in pool_values] or [{}]

Edit (2019-01-09 - 1530):

The definitions of _labels and self.labels in the above two code blocks, respectively, have been simplified per @MathiasEttinger's excellent suggestion. See revision history for their original definitions.


Determine how many bits are in a floating point value

You should do the output in main(), not in countbits().  Functions should have only one primary purpose, according to the Single Responsibility Principle (SRP).  In this case, countbits() should just perform the calculations and return the result.  Thus, its return type should now be of type int.

Inside of countbits(), you could just loop while k is not 0 instead of looping 32 times.  Once all the bits in k shift away and k becomes 0, there's no point in continuing.  This will also give you a result of 0 right away if the input is 0; calculating this will be a waste of time.

int main(void) {
    int input;

    // get the input...

    int count = countbits(input);

    printf("%d has %d bits set\n", input, count);
}

int countbits(int k) {
    int count = 0;

    while (k != 0) {
        // perform calculations...
    }

    return count;
}

Some notes about this and other things:

main() should have a void parameter since it isn't taking any command line arguments.
The first (unformatted) output in main() should use puts() instead of printf().
count doesn't need to be declared and then assigned to 0.  Just initialize it to 0.
j should be initialized inside the for loop statement (if you have C99).  If you don't, then declare it right before the loop.  Variables should be used as close in scope as possible.


Exception itself actually inherits from a class called BaseException so:

class BaseException(Exception):

Seems backwards.


This is how I would do it. First, we need a function to convert a UTC string to a DateTime since one doesn't already exist, as you already found out. The function that you found looks a bit complicated to me. I did a search for ".net utc to local time", and I found this: https://stackoverflow.com/questions/179940/convert-utc-gmt-time-to-local-time

Don't forget that .NET code, such as C#, can be translated easily into PowerShell. This is what I came up with, based on the top-rated answer:

function UtcToDateTime($dateStr)
{
    $date = [DateTime]::Parse($dateStr)
    [DateTime]::SpecifyKind($date, [DateTimeKind]::Utc)
}

The result is returned in the last line of that function because SpecifyKind returns a result.

Now we can use that function to transform our UTC date strings into DateTime objects:

$utcTimes = gc C:\Scripts\UTC.txt

$dates = $utcTimes | % { UtcToDateTime $_ }

The % is short for foreach. In English: "for each date in $dates, convert it to a DateTime using our function."

Since you want a two-column output, an easy way to do that is to make a custom objects with two the desired two fields:

$results = $dates |
    % { [pscustomobject]@{UTCTime = $_.ToString(); LocalTime = $_.ToLocalTime().ToString() } }

The @{...} is a hash table. So what that code says is that for each date, convert it to a hash table, and then convert that hash table into a pscustomobject. (That's just an easy way to make custom objects.)

And now we return our results:

$results

Which looks like the following (note that days and months are switched in my country):

UTCTime                  LocalTime
-------                  ---------
19/04/2015 4:10:03 AM    19/04/2015 2:10:03 PM
19/03/2015 9:10:03 AM    19/03/2015 7:10:03 PM

Here's the full script:

function UtcToDateTime($dateStr)
{
    $date = [DateTime]::Parse($dateStr)
    [DateTime]::SpecifyKind($date, [DateTimeKind]::Utc)
}

$utcTimes = gc C:\Scripts\UTC.txt

$dates = $utcTimes | % { UtcToDateTime $_ }

$results = $dates |
    % { [pscustomobject]@{UTCTime = $_.ToString(); LocalTime = $_.ToLocalTime().ToString() } }

$results


Refactor Coffee Script to fire on page load instead of change

This is borderline Code Review material, since the code doesn't work as intended. It's not the same thing as "broken", because it does run, but what you're asking for is more or less a new feature.

(I'm also a little unsure of what you're asking, though I think I got it right. This isn't prose review, but you've got some run-on sentences in your question that are nigh impossible to read. Edit: That's been improved now)

Still, I'll give it shot regardless.

First, when you use jQuery, remember to store things you'll use more than once - don't call $(...) again and again for the same selectors.

Second, store a clone of the facilities list element. Not the HTML string. You can just have an element in memory without having to to display it on the page. No need to reduce it a string, and parsing it every time you need something.

Third, I'd use a more precise identifier for the optgroups than the region name. It works, but I'd prefer using an integer ID or something. Unfortunately, grouped_collection_select doesn't have an option to do that (you'd have to write your own version), so I'll skip that here.

I'd extract a function to do the options-setting

$ -> # on DOM ready

  # Grab the elements we'll need
  facilitySelect = $ "#call_transfer_from_id"
  regionSelect = $ "#call_region_id"

  # Make an in-memory clone of the facilities.
  # We'll use this as out "master list"
  facilitiesCopy = facilitySelect.clone()

  # A simple helper function to set the facility select's option
  # to match those in a named optgroup (again, we're cloing elments)
  setFacilityOptionsForSelectedRegion = ->
    region = regionSelect.val()
    options = facilitiesCopy.find("optgroup[label='#{region}'] option").clone()
    facilitySelect.empty().append options

  # Call the function on region change
  regionSelect.on "change", setFacilityOptionsForSelectedRegion

  # and also just call it now that the page has loaded
  setFacilityOptionsForSelectedRegion()

I think that should work.

Edit: Here's a demo


Project Euler Problem 6: sum of squares and square of sums

This would be good practice for list comprehension, especially since sum() is a builtin function.

sequence = range(1, 11)
sum_of_squares = sum([i**2 for i in sequence])
square_of_sum = sum(sequence)**2
print(square_of_sum - sum_of_squares) # 2640

For even more fanciness, you can use this expression for the sum_of_squares:

sum_of_squares = sum(i**2 for i in sequence) # No square brackets

This sums over a generator expression instead of creating a new list, saving memory, especially if the sequence is something ridiculous like range(1, 1000000001).


Find all possible sumation numbers to a specified sum

Rather than go through a line-by-line critique of your program, let me just say:

It is way too long and too complicated
You are getting hung up on all the adds and removes.  This problem is much easier to solve if you never add or remove anything. Treat sequences as immutable data structures.

You should be able to do this in about four lines of code in your method body, and some little helper methods.  Here's an example:

using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
    static IEnumerable<T> Singleton<T>(T t)
    {
        yield return t;
    }
    static IEnumerable<IEnumerable<int>> AllSums(int n, int min = 1)
    {
        for (int i = min; i <= n / 2; ++i)
            foreach(var seq in AllSums(n - i, i))
                yield return Singleton(i).Concat(seq);
        yield return Singleton(n);
    }
    public static void Main()
    {
        foreach(var result in AllSums(7))
            Console.WriteLine(string.Join(",", result));
    }
}

The key here is to make a clear specification for the AllSums method.  It takes positive integers n and min and returns a sequence of sequences that all have the following properties:

They sum to n
The smallest number in the sequence is not smaller than min
The sequence is non-decreasing

Once you have a method that has these properties, the recursion becomes much easier to reason about.

Go through this implementation very carefully and annotate each line of code with its meaning and purpose in the algorithm.

For another application of this general principle of generating a sequence of data structures that all have a sum property, see my series of articles which begins here:

https://blogs.msdn.microsoft.com/ericlippert/2010/04/19/every-binary-tree-there-is/


Secret Santa pair allocator in JavaScript

This is not a review of the coding style and syntax, but of the algorithm used.

Permutations and randomised rule based selection.

A random search for a set of permutations is never a good method, especially if the set of previous results reduce the size of the set of valid permutations for the next set.

Random solution guessing

Your problem is finding one of a set of solutions. There are only a finite set of possible solutions.

Your code uses a random guess method.

Each iteration you randomly guess a possible combination then test its validity. Because the set of valid solutions gets smaller each year, your code needs to make more guesses as the number of valid solutions gets smaller but the set you are guessing in remains the same size.

This method also has been limited (to 50) and thus you could always have a chance of not finding a solution. For the first year there is a relatively small chance of not finding a solution, but this grows quickly. In three years you will need to (on average) run the code 5 times to find a solution.

Also the limit you must surely have seen is that after 4 years there are no more possible solutions, as everyone has given to everyone. This should be obvious from the code as well, but it still tries to guess a solution where there is none.

There is no need for the code to throw an error. The solutions are known and fixed, so there is no need to guess.

Systematic solution computation.

To do this effectively you need to know the set of all valid solutions. Once you have that set you just randomly select one. There is no need to search for valid solutions as you are only selecting from known valid values.

Pre-computation of the set of valid solutions has a limit, as the possible number of solutions quickly grows with the complexity of a solution. For 6 people there are 80 solutions that are valid, for 10 people that is approaching a million. For 20 people you need to start applying some serious optimisation and storage compression to use this method.

Abstraction

If you compute them systematically and hold them as an abstracted data set, e.g. each person is a letter A,B,C,D,E,F that identifies them both as an entry in the data struc and a position in the abstracted data, e.g. "A" is 1st person in a solution string and the first person in the people array. A solution for a particular year is a string e.g. "CDEFAB" which means person A gives to C, person B gives to D, C to E and so on.

If you ignore the previous year the possible solutions are only 80.

Computing permutations.

For your data the following is all valid solutions.

var allValidSolutions = "DCFEBA,DCFEAB,DCEFBA,DCEFAB,ECFADB,ECFABD,ECFBDA,ECFBAD,ECAFDB,ECAFBD,ECBFDA,ECBFAD,FCEADB,FCEABD,FCEBDA,FCEBAD,FCAEDB,FCAEBD,FCBEDA,FCBEAD,CDFEBA,CDFEAB,CDEFBA,CDEFAB,EDFACB,EDFABC,EDFBCA,EDFBAC,EDAFCB,EDAFBC,EDBFCA,EDBFAC,FDEACB,FDEABC,FDEBCA,FDEBAC,FDAECB,FDAEBC,FDBECA,FDBEAC,CEFADB,CEFABD,CEFBDA,CEFBAD,CEAFDB,CEAFBD,CEBFDA,CEBFAD,DEFACB,DEFABC,DEFBCA,DEFBAC,DEAFCB,DEAFBC,DEBFCA,DEBFAC,FEBADC,FEBACD,FEABDC,FEABCD,CFEADB,CFEABD,CFEBDA,CFEBAD,CFAEDB,CFAEBD,CFBEDA,CFBEAD,DFEACB,DFEABC,DFEBCA,DFEBAC,DFAECB,DFAEBC,DFBECA,DFBEAC,EFBADC,EFBACD,EFABDC,EFABCD".split(",");

This was created with the following code. Note this is a brute force method. You should do some research into optimal methods if you need to include more than a dozen people.

function permutations2Of(chars) {
    var i,j;
    const count = chars.length;
    const sets = [];
    for (i = 0; i < count; i ++) {
        for (j = 0; j < count; j ++) {
            if (j !== i) { sets.push(chars[j] + chars[i]) }
        }
    }
    return sets;
}
function isSetValid(set, ofSet) {
    var i = 0;
    while (i < ofSet.length) {
        if (set.indexOf(ofSet[i ++]) === -1) { return false }
    }
    return true;
}
function findUnique(arr, ofSet, result = [], index = 0, current = "") {
    var i;
    const testSet = index === arr.length - 1;
    for (i = 0;  i < arr[index].length; i ++)  {
        const aSet = current + arr[index][i];
        if (testSet) {
            if (isSetValid(aSet, ofSet)) { result.push(aSet) }
        } else {
            result = findUnique(arr, ofSet, result, index + 1, aSet);
        }
    }
    return result;
}
const AB = permutations2Of("CDEF");
const CD = permutations2Of("ABEF");
const EF = permutations2Of("ABCD");
const combos = findUnique([AB, CD, EF], "ABCDEF");

This is based on the smallest unit being a couple (e.g. AB is the first and second person, and they can give only to persons "CDEF")

It calculates all the possible permutations for each couple and then calculates all the possible permutations for all couples.

The  function findUnique uses recursion to create all possible solutions and then calls the function isValidSet to test if the solution should be kept.

The set of solutions should only be calculated once; once computed it can be retrieved from a data store and filtered when there is a need for extra rules to be applied - e.g. last years results.

Random solution without the guesswork.

Now it is very easy to find the first years arrangement.

var secretSantas = combos[Math.random() * combos.length | 0];

And convert to your data:

const baseCode = "A".charCodeAt(0);
secretSantas.split("").forEach((id, index) => {
    const personIndex = id.charCodeAt(0) - baseCode;
    people[index].current = people[personIndex];
});

Additional rules.

The above does not consider the previous year's gifts, but that can be stored as the abstracted string e.g. "DEFGAB". As there are only 4 people for each person to give to there are only 4 years before you are forced to repeat. If you limit the repeat only to 4 years then after the 3rd year everyone will know who is giving to who (if anybody bothered to keep track that is).

So the better rule is to just not repeat two years. You can't give to the person you gave to last year.

Then you can use a filter on the combos array to eliminate any invalid combination due to previous years results.

const lastYearsCombo = "CDEFAB".split("");
const comboFiltered = combos.filter(combo => {
     for (var i = 0; i < lastYearsCombo.length; i++) {
         if (combo[i] === lastYearsCombo[i]) { return false }
     }
     return true;
});

comboFiltered will only have 17 possible combinations as the rest have been eliminated due to the previous year. The random selection is still the same.

var secretSantas = comboFiltered[Math.random() * comboFiltered.length | 0];


The difference in the two branches of that if statement is just the Farwell so only this generation is what should happen inisde the if.
the name of the variable i is not choosen very well if you later on need a comment to describe what it should represent.
The GenerateMessage() method is doing more than its name implies. It is generating and outputting the message. This is also violating the single responsibility principle which means that each method should have only one responsibility. So let the method return a string which then can be used in the Main().
you shouldn't create each time a new Random but reuse an existing.
if the range out of which the random numbers should be generated starts at 0 you should use the overloaded Next() method which only takes the exlusive upper bound as a parameter.
by using a List<string> the multiple string variables won't be needed and you can take advantage of the string.Join() method

private static Random random = new Random();
private static string GenerateMessage()
{
    IList<string> subMessages = new List<string>(4);
    subMessages.Add(Greetings[random.Next(Greetings.Length)]);
    subMessages.Add(Compliments[random.Next(Compliments.Length)]);
    subMessages.Add(Garments[random.Next(Garments.Length)]);

    int chance = random.Next(1, 11);
    if (chance < 3)
    {
        subMessages.Add(Farewells[new Random().Next(Farewells.Length)]);
    }

    return string.Join(" ", subMessages);
}

Edit based on the comment

  Why do you have a 4 in the parentheses in this line: IList<string> subMessages = new List<string>(4); I removed the 4 to see if the code would still work and it did...

The 4 is pretty bad code style if another programmer needs to ask. Thats what a magic number is which I should have extracted to a meaningful constant like so

private static readonly int maxMessages = 4;

and then used it like so

IList<string> subMessages = new List<string>(maxMessages);

now you know what it is, but you are still missing what is for. That is shown if you take a look at the documentation for this overloaded constructor of the List<T> you will see that this is the initial capacity of the List<T> which is explained more in the Remarks section.

  The capacity of a List is the number of elements that the List can hold. As elements are added to a List, the capacity is automatically increased as required by reallocating the internal array.

And the reason why I used it is shown here

  If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List.


A few things to consider;

Is it worth abstracting the collection into the lights and locks arrays? The data format is effectively identical, and I think separating them makes the collection as a whole harder to iterate over.

To follow up from the first point, I try to avoid for loops in JavaScript because there's so many efficient and readable alternatives for working with arrays. If we were to rewrite your data structure to be the following:

{
    "switches": [{
        "name": "light-one",
        "pin": 3, // definitely store integers as ints and not wrapped in quotes!
        "command":"gpioDo",
        "actions": {
            "on": 1,
            "off": 0
        }
    }, {
        // ...
    }]
}

We can then rewrite your first example to be the following:

var state = lib.map(function(switch) {
    return {
        pin: switch.pin,
        val: 0
    };
});

This removes the index variables completely, and in my opinion makes the code more readable. In the case of not rewriting the data structure you could just iterate over the lights and locks arrays with a map function, then concat them together.

In the same way we can iterate over this when you want to set the values.

var updateVal = function(pinID, valID) {
    state.forEach(function(s) {
        s.pin === pinID && (s.val = valID);
    });
};

The function expression is just a personal preference, but I like it as it forces you to declare a function before using it.

I'm also not sure if the actions key needs to be like it is; perhaps you need it for other entities that have other actions, but I would probably replace it with a boolean active (to represent on and off), for simplicity.

Hope this helps. :)


The TryParse or TryGetValue pattern is often used in the .NET Class Library and is a good approach. In order to fully comply with it, you should always return the type's default value default(T) for the output parameter when the parsing fails. For reference types this is always null:

public static bool TryParse(string expression, out OrderExpression orderExpression) {
    if (_parser.ExpressionIsValid(expression)) {
        orderExpression = new OrderExpression { Rules = _parser.Parse(expression) };
        return true;
    } else {
        orderExpression = null;
        return false;
    }
}

An out parameter must be assigned before leaving the method anyway. You'll get a compiler error otherwise.

Also, in C#, the C# type aliases are usually preferred over the .NET type names. I.e.: use string instead of System.String, bool instead of System.Boolean, int instead of System.Int32 and so on. (Personally, I prefer to use the .NET type name when accessing static members: Int32.TryPare(...).)

When calling a method, the return value can be ignored in C#, but here, it seems logical to react differently, depending on the outcome of the parsing:

if(OrderExpression.TryParse(expression, out orderExpression)) {
    // Use orderExpression.
} else {
    // Handle the error case.
}

A comment regarding the logic: Order expressions usually have to be executed in a specific order, however, a HashSet<T> is unordered. Return a List<OrderExpression> instead. Also, the setter can be private.

public List<OrderRule> Rules { get; private set; }

UPDATE

Since C# 6.0 you can declare getter-only auto-properties. You can set them in the constructor or in a property initializer.

To set the Rules property I declare a constructor. It can be private to force a client to use the static TryParse factory method.

public class OrderExpression
{
    private OrderExpression(List<OrderRule> rules)
    {
        Rules = rules;
    }

    public List<OrderRule> Rules { get; }

    public static bool TryParse(string expression, out OrderExpression orderExpression)
    {
        if (_parser.ExpressionIsValid(expression)) {
            orderExpression = new OrderExpression(_parser.Parse(expression));
            return true;
        } else {
            orderExpression = null;
            return false;
        }
    }
}

Since C# 7.0 you can declare the out-parameter in-line

string expression = "+name;-age;-city";
if (OrderExpression.TryParse(expression, out var orderExpression)) {
    //TODO: use orderExpression.
} else {
    //TODO: handle pare error.
}


Calculate the sum of the square of two biggest numbers out of three

One of the ways of obtaining concision is by “astracting” a repeated operation to define a new function. For instance in this case you could use the square function previously defined in that chapter.

But if you look at the expression (square a) you will discover that it is longer then (* a a), even it is, in some sense, more readable (has a minor number of symbols, so it is simpler to understand).

But having a function to abstract an operation could have other benefits that an immediate reduction in the count of the characters. Consider that in your example you are comparing two numbers to find the larger between them: in other words, you are looking for their maximum.

So, let's define  a new maximum operator:

(define (max a b)
  (if (> a b) a b)

Then, having the functions square and max you can now combine them, like, for instance, in:

(define (sum-of-larger-two a b c)
  (if (> a b)
      (+ (square a)
         (square (max b c)))
      (+ (square b)
         (square (max a c)))))

Or you can rearrange the operations in this way:

(define (sum-of-larger-two a b c)
  (+ (square (max a b))
     (square (if (= (max a b) a)
                 (max b c)
                 (max a c)))))

Note that we are reducing the number of conditions to check in the function sum-of-larger-two (in addition to reducing the number of lines and symbols), and so we are simplifying it, improving both its readability as well as its maintainability.


Breaking a chess coordinate string into 2D coordinates

Give your code some breathing room. I.e. ) { |a, b| instead of ){|a, b|. And there's no need to put everything on one line. The way your block works right now, it'd be better to store the result of pwn.split in a variable, instead of calling split twice. (There's also no need to abbrevate "pawn" as "pwn".)
That being said, strings support array-like access, so you don't need the split at all.
Judging from your code, pawns is an array. Transforming an n-element array to a new n-element array is called "mapping". You're using inject which is also known as reduce (and fold in many other languages; see comments) - an operation most often used to take an n-element array and reduce it to a single value. So step 1: Use map instead of inject.
I'd probably use a regex to pull the string apart. It'll double as a way to check the coordinate strings for validity (e.g. so no "z9" coordinates will slip through).
It's a little low-level, but we can use the fact that "a" is 97 in ASCII. So to get the number for a letter, we can say letter.ord - 96.

You get something like this:

def safe_pawns(squares)
  squares.map do |square|
    [$1.ord - 96, $2.to_i] if square.downcase =~ /^([a-h])([1-8])$/
  end.compact
end

Alternatively, if you're sure that all the input coordinates are valid, lowercase strings already, you don't need the regex or the downcasing:

def safe_pawns(squares)
  squares.map { |square| [square[0].ord - 96, square[1].to_i] }
end

As tokland points out in the comments, we can avoid the hardcoded 96 (which isn't very self-explanatory) and instead get the letter-to-number translation by saying:

square[0].ord - 'a'.ord + 1


Jumping in after the horse has bolted with a very minor different approach (using Any rather than Count and null).

IEnumerable<string> GetSmallFileNames(Directory directory, string fileName, string filter)
{
   var smallFileNames = new List<string>();

   if (directory.Exists)
   {
       smallFileNames = directory.GetFiles(filter).Select(i => i.FullName);
   }

   return smallFileNames.Any() ? smallFileNames : DivideIntoFiles(fileName);
}

Then used such as

IEnumerable<string> smallFileNames = GetSmallFileNames(directory, fileName, "*.csv");


Spotify Bestbefore Coding Challenge in Python

I just went over the last version of your code you posted on freenode's #python, and there are two major errors in it:

You never check if month or day are 0, and your month > 12 check gets overwritten by the later if clauses. With those fixed, it passes.

Same issues are already in the code above, but I did not check if it has others as well.

the flag variable approach is very error prone and hard that way - it would be better to return False right away if you determine that, not tag it along with the chance that it might get flipped back erroneously.


Enumerate directories to a given search depth

Since the class has only static and constant members, you should make the entire class static.  It eliminates the unnecessary empty instance constructor the framework automatically generates.  (see code analysis rules CA1052 and CA1053).

You should also generally use the type aliases provided (i.e., string instead of String, bool instead of Boolean, etc. - see StyleCop rule SA1121).

Additionally, I would change the recursion in EnumerateDirectoriesInDepth so it does not have to recurse another step when the depth is zero.

private static IEnumerable<string> EnumerateDirectoriesInDepth(string startDirectory, int depth)
{
    var directories = Directory.EnumerateDirectories(startDirectory, "*.*", SearchOption.TopDirectoryOnly);

    if (depth == TopDirectoryOnly || !directories.Any())
    {
        return directories;
    }


Checking that a string matches one regex and doesn't match another

Per PEP-8, you can ("Acceptable options in this situation include, but are not limited to...") further indent the second line of the condition:

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

The difference is that indentation in the continuation lines is purely stylistic, whereas indentation of the next code block has semantic meaning. In your case:

if (not re.search(regexp, summary)
        and not re.search(regexp2, summary)):
    return False

Note I have moved the and per the same guidance.


Prettify this code - combine items in a list

You can shorten this and get lazy evalution using yield:

private static IEnumerable<Span> CombineAdjacentSpans(this IEnumerable<Span> spans)
{
    Span current = null;
    foreach (var span in spans.OrderBy(s => s.Start)) {
        if (current == null) { current == span; }
        // I made this handle overlaps, but if you don't care about those
        // you can change the comparison to just ==
        else if (span.Start <= current.End && span.End > current.End) {
            // current.End = span.End
            // it's probably better to make a new span rather than modifying the
            // current one here since that way this method doesn't modify elements
            // in the original list. If span is a struct, then modification would be
            // fine but we'd have to rely on a bool rather than checking against null
            current = new Span { Start = current.Start, End = span.End };
        } else {
            yield return current;
            current = span;
        }
    }

    if (current != null) { yield return current; }
}

This way, something like mySpans.CombineAdjacentSpans().Take(3) will only do the work of combining the first 3 spans (although OrderBy will still have to look at all elements in the input sequence).

In response to Chris's comment, if you really want the last if statement inside the loop here's one way I can think of to do it:

private static IEnumerable<Span> CombineAdjacentSpans(this IEnumerable<Span> spans)
{
    Span current = null;
    // could also use Enumerable.Repeat() instead of new[] { ... }
    foreach (var span in spans.OrderBy(s => s.Start).Concat(new[] { default(Span) })) {
        if (current == null) { current == span; }
        // I made this handle overlaps, but if you don't care about those
        // you can change the comparison to just ==
        else if (span.Start <= current.End && span.End > current.End) {
            // current.End = span.End
            // it's probably better to make a new span rather than modifying the
            // current one here since that way this method doesn't modify elements
            // in the original list. If span is a struct, then modification would be
            // fine but we'd have to rely on a bool rather than checking against null
            current = new Span { Start = current.Start, End = span.End };
        } else {
            yield return current;
            current = span;
        }
    }
}


The function generate_primes() shouldn’t print the list it generated.  The caller should print the returned value, if desired.

Calling generate_primes(2) will unexpectedly return [2, 3], as will generate_primes(1) or generate_primes(-500).

The increment_2 flag is awkward.  When True, increment by 2 seems ok, but when False the increment is ... what?  0?  1?

Instead of an increment_2 flag, you could use an increment amount, starting with 2 ...

increment = 2

... and then toggle that value between 2 & 4:

num += increment

# Alternate step size between 2 and 4
increment = 6 - increment

No more if ... else ..., reducing the complexity of the function slightly.

Stretch goal:

After generate_primes(200), if a call is made to generate_primes(500), you will recalculate all of the primes beneath 200.  Perhaps there is a way to cache the computed values for future generate calls?


As far as performance goes, there isn't much you can improve without doing manual optimization tricks. Such things are already implemented in the library functions though.

The main issue I see here is that you copy data into the destination before you know if the string actually contains a termination character. By doing so, you save a bit of time as you can copy and search at the same time. But you also end up copying data before the input has been verified.

What's best in your case, I don't know. It depends on how reliable your input is. If you have already verified it previously, then your copy+check in one might be the best choice. If it's some raw data from a serial bus (UART etc), it might be wisest to verify the data before you copy. I will show a version that does the verification first, it will be safer although possibly slightly slower than what you currently have.

General code review:

Style/best practices

Pointer parameters to data that isn't modified should be const qualified.
Using a plain int for error handling isn't ideal. You actually have several possible errors here: missing search string, missing terminator, potential buffer overflow. Even if your program doesn't need to know what went wrong, it might ease debugging and it costs you nothing extra to add.
The while loop could have been replaced with a for loop, for better readability:

for(size_t i=0; i<desLen-1; i++)
{
  if(temp[i]==termChar)
  {
    break;
  }
  dst[i]=temp[i];
}

Performance

The length of the search key could be determined at compile-time.
Consider dropping the terminating character parameter if what2find[0] could be said to always contain it.
Some micro-optimizations with C99 restrict are possible. I'll show an example below.

Here is a different version which contains more detailed error handling and checks for termination before copy:

#include <string.h>
#include <stdbool.h>

typedef enum
{
  STRFIND_OK,
  STRFIND_KEY_NOT_FOUND,
  STRFIND_TERMINATOR_NOT_FOUND,
  STRFIND_BUFFER_OVERFLOW,
} strfind_result_t;

strfind_result_t strfind_cpy (const char* str,
                              size_t      key_size,
                              const char  key[key_size],
                              char        terminator,
                              size_t      dst_size,
                              char        dst [dst_size])
{
  char* start = strstr(str, key);
  if(start == NULL)
  {
    return STRFIND_KEY_NOT_FOUND;
  }

  start += key_size-1;
  char* end = strchr(start, terminator);
  if(end == NULL)
  {
    return STRFIND_TERMINATOR_NOT_FOUND;
  }

  size_t length = (size_t)(end-start);
  if(length+1 > dst_size)
  {
    return STRFIND_BUFFER_OVERFLOW;
  }

  memcpy(dst, start, length);
  dst[length] = '\0';

  return STRFIND_OK;
}

C99 pointer-to-VLA are used to ensure data size integrity of the buffers. If the verification of data isn't needed, strchr could be replaced with a for loop like the one demonstrated above.

memcpy is the fastest possible copy. It will be faster than copy character-by-character, since the library implementation will work on 32 bit chunks that your ARM likes better than copying individual bytes. So my code might actually be faster (or it may be slower), you'll have to benchmark it.

Further micro-optimization is possible with C99 restrict:

strfind_result_t strfind_cpy (const char* restrict  str,
                              size_t                key_size,
                              const char* restrict  key,
                              char                  terminator,
                              size_t                dst_size,
                              char* restrict        dst);

This tells the compiler that none of the pointers passed point at the same buffer. This may improve performance ever so slightly, depending on how your compiler handles pointer aliasing internally. Check the disassembled code to see if restrict gave any benefits.

Example of use:

#include <stdio.h>

int main (void)
{
  const char data[] = "blablabla$GPTXT->SOME CODES HERE<-\r\n$GPRMCblablabla";
  char buf[50];
  strfind_result_t result;

  result = strfind_cpy(data,
                       sizeof "$GPTXT",
                       "$GPTXT",
                       '$',
                       sizeof buf,
                       buf);

  if(result == STRFIND_OK)
  {
    puts(buf);
  }
}


Game of Life rules in 14 lines of Python

For docstrings, if you're following the Sphinx documentation format (which it looks like you are), you can specify an explicit :return: field to document what exactly it is your function is returning. PEP-0257 has various other conventions for docstrings like leaving a blank line between the summary line and the rest of the docstring, if you're really interested.

In terms of functional programming, you could use some of Python's functional programming functions, e.g the builtins filter and map and also any functions from the functools module. Also, since you are already not mutating any of the variables in your program (as you wouldn't do when programming in a functional manner), you can use frozenset()s in place of where you're currently using sets, as frozen sets are explicitly immutable.

Here is an attempt at "functionifying" the step function. Since Python 3, you can put type hints in the signature of functions, and since Python 3.5 you can also use the typing module to define types in a formal way, which can allow for better static type-checking if you're using a typing-aware IDE. Since you're wanting to program in a functional way, I'm guessing this would be of more interest than usual.

from functools import reduce
from typing import Tuple, Set

Cell = Tuple[int, int]
Universe = Set[Cell]  # or even FrozenSet[Cell]

...

def step(universe: Universe) -> Universe:
    """ Evaluate the next step in the Game of Life.

    :param universe: set of live cells in the universe. A live cell is the tuple (x,y)
    :return: the new universe after a single step in the game of life.
    """
    survivors = filter(lambda cell: is_survivor(universe, *cell), universe)
    neighbours = reduce(set.union, map(lambda cell: get_neighbours(*cell), universe))
    dead_neighbours = filter(lambda cell: cell not in universe, neighbours)
    births = filter(lambda cell: is_born(universe, *cell), dead_neighbours)
    return frozenset(survivors) | frozenset(births)

To be honest though, functional programming does not seem idiomatic in Python, even though it can be done; I would say your current code is pretty clear and idiomatic as is, using set comprehensions and such.