Maintainable and Adaptable FizzBuzz implementation

You could make some sort of struct or class that stores the text printout and the number i should be divisible by. Then you just need to create as many instances of the class as you need and loop through them.

One other approach is to have a hashtable and store the keys in an array that you loop through. You can use whichever one you feel makes the most sense but the first method should technically use up less memory because you only store the text once for each condition. I might be wrong though, I don't really use Java.

Example (Not tested and not written by a Java developer):

class Condition {
    String printout;
    int div;
}

Condition[] conditions = { {"Fizz", 3}, {"Buzz", 5} };
int loops = 100;

public static void main() {
   for(int i = 0; i < loops; i++) {
       String printOut = "";
       for(int j = 0; j < conditions.length; i++) {
           if(i % conditions[j] == 0) {
              printOut += conditions[j].printout;
           }
       }
       if(printOut == "") {
          System.out.println(Integer.toString(i));
       } else {
          System.out.println(printOut);
       }
   }
}

Then if you want to you could wrap it in a function and call it with the conditions array and number of loops as parameters.

You can also shorten your divisible to:

public static boolean divisible(int a, int b) {
   return ((a % b) == 0);
}

But I think that you don't really need that function because you can just use the % operator and your code would be cleaner and quicker to understand. Just for future consideration.

Hope this answers your question.


DFS on a binary tree: marking nodes as visited

I don't need to mark the nodes as visited, when I traverse binary tree, right?

Well, is your code working even though you are not doing this right now? Then yes, you don't need it.

See also this question for a theoretical discussion about marking nodes as visited, and this question for a practical reason to mark nodes (it's not needed for a simple search, but it is needed when looking for paths).

Naming

Even though you are not that interested, it is important. It makes your code more readable, which helps reviewers review your code. If you don't really care about your code, why should we?

In this case, it's not really that bad (there aren't all that many variables), but I wouldn't even know what res was short for (rest? Like the rest of the nodes?); even nodes would be better.

Formatting

Just like naming, correct formatting makes code easier to read and thus easier to maintain and review. Again, your code is very short, so it's not all that bad, but your spacing is off and you should use curly braces even for one-line statements.

Printing

Your code isn't really testable or practical as it doesn't return a result, but just prints something. You should return true (or the node) or false instead if your using it as a search, and return a string/list/etc if your using it to traverse the tree and collect the content of the nodes.


Looks great.  Don't forget to define lower-bound and upper-bound as car and cdr respectively.


First of all, maybe you should give the user a way to configure the selector - this gives most applications the chance to go for an id selector, others might want to have a more global or unobstrusive approach - so they can just use a data-selector.

Your object oriented approach is not following the standard principles for jquery plugins - from what I see there you are using jquery so why not use their plugin techniques then. As the jquery docs have a huge documentation of that, here is just a small example:

$.fn.tabs= function() {
    this.css( "color", "green" );
};

$( "a" ).tabs(); // Makes all the links green.

See http://learn.jquery.com/plugins/basic-plugin-creation/ for a better explanation. This also makes possible what I showed above - let the user decide what selector to use.

For this simple tabs script I don't see any other considerations when it comes to performance.


I believe I can help with these things:

Obliterate macros
Obliterate raw arrays

Macros can be replaced with std::integer_sequence (C++14), and raw arrays can be replaced with std::array (C++11).

#include <array>
#include <utility>

template <typename T, T... Is>
constexpr auto gen_primes_helper(std::integer_sequence<T, Is...>) {
    return std::array<T, sizeof...(Is)>{{getPrime(Is)...}};
}

// T: integer type
// N: number of elements
// return: std::array<T,N>
template <typename T, T N>
constexpr auto gen_primes() {
    return gen_primes_helper(std::make_integer_sequence<T,N>());
}

constexpr auto primes = gen_primes<int,1024>();

However, we have a problem: Compilers currently implement std::make_integer_sequence in O(N) complexity.

GCC limits N to 900, unless you add the -ftemplate-depth= compiler option. See this bug.

Clang limits N to a pathetic 256, but also provides the same -ftemplate-depth= option.

To solve the problem, std::make_integer_sequence can be implemented in O(log(N)). I have done this as follows:

#include <array>
#include <utility>

namespace logseq {

// alias for std::integer_sequence, for brevity
template <typename T, T... Is>
using intseq_t = std::integer_sequence<T, Is...>;

template <typename A, typename B>
struct concat;

// A: intseq_t
// B: intseq_t
// return: typename intseq_t
//
// Example:
//   concat_t< intseq_t<int,0,1,2>, intseq_t<int,0,1,2,3> >
//     => intseq_t<int,0,1,2,3,4,5,6>
template <typename A, typename B>
using concat_t = typename concat<A,B>::type;

template <typename T, T... As, T... Bs>
struct concat<intseq_t<T, As...>, intseq_t<T, Bs...>> {
    using type = intseq_t<T, As..., (sizeof...(As) + Bs)...>;
};

template <typename T, T N, typename = void>
struct logseq;

// T: integer type
// N: number of elements
// return: typename std::make_integer_sequence<T,N>
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66059
template <typename T, T N>
using logseq_t = typename logseq<T,N>::type;

template <typename T, T N, typename>
struct logseq {
    using type = concat_t<logseq_t<T,N/2>,logseq_t<T,N-N/2>>;
};

template <typename T, T N>
struct logseq<T,N,typename std::enable_if<N==0>::type> {
    using type = intseq_t<T>;
};

template <typename T, T N>
struct logseq<T,N,typename std::enable_if<N==1>::type> {
    using type = intseq_t<int,0>;
};

} // namespace logseq

template <typename T, T... Is>
constexpr auto gen_primes_helper(std::integer_sequence<T, Is...>) {
    return std::array<T, sizeof...(Is)>{{getPrime(Is)...}};
}

// T: integer type
// N: number of elements
// return: std::array<T,N>
template <typename T, T N>
constexpr auto gen_primes() {
    using logseq::logseq_t;
    return gen_primes_helper(logseq_t<T,N>());
}

constexpr auto primes = gen_primes<int,1024>();

Namespace logseq provides a metafunction logseq_t that returns a typename std::integer_sequence<T, 0, /* ... */, N-1>. It is a drop-in replacement for std::make_integer_sequence, which returns the same type.

logseq_t allows for infinite (read: really freaking big) values of N.


LinkedList?

    List<AverageResult> averages = new LinkedList<>();

If there is a reason why this should be a LinkedList rather than an ArrayList, you should comment it.  An ArrayList will normally use less memory if it fits exactly and allows easy random access.  So is often preferable for containers that are built all at once as this one seems to be.

That's not to say that it is wrong to use a LinkedList here.  It's to say that I don't see any reason in this segment of code to use a LinkedList.  With more context, that might make perfect sense.  So there should be a comment here letting us know that you thought about it and the basis for your decision.

Be careful

    Set<Integer> questionIDSet = responses.get(0).getAnswerMap().keySet();

This assumes that the first response has an answerMap with answers to all the possible questions.  But that is a contract that you will actively have to work to maintain.  It may be true now, but a future change could easily make it not true.  Consider instead

    Set<Integer> questionIDSet = responses.get(0).getQuestionIDs();

Yes, this means defining a new method on responses.

or even better something like

    Set<Integer> questionIDSet = sample.getQuestionIDs();
    List<Response> responses = sample.getResponses();

So you can pass one sample object rather than a container of responses.

Yes, this requires an entire new class.

Keep it simple

        for(Iterator<Response> iter = responsesCopy.iterator(); iter.hasNext();) {
            Response actualResponse = iter.next();
            if(filterMatch(actualResponse,filters)) {
                if(isNumber(actualResponse, questionID)) {
                    sum += Double.valueOf(actualResponse.getAnswerMap().get(questionID));
                    count += 1;
                }
            }else {
                iter.remove();
            }
        }

So you create a copy of the responses so that you can iterate over them and remove those that do not match the filters.  If they do match and are numeric, you calculate the sum and count.  That's fine, but it seems more complicated than necessary.  You never use responseCopy after this section.  So why do you have to remove the entries that don't match?  Why not just

        for (Response actualResponse : responses) {
            if (filterMatch(actualResponse, filters)) {
                if (isNumber(actualResponse, questionID)) {
                    sum += Double.valueOf(actualResponse.getAnswerMap().get(questionID));
                    count++;
                }
            }
        }

That will return the same sum and count values.  But it doesn't require making a copy of responses or modifying the iterator. Or consider

        for (Response actualResponse : responses) {
            Map<Integer, String> answers = actualResponse.getAnswerMap();
            if (filterMatch(answers, filters)) {
                String answer = answers.get(questionID);
                if (isNumber(answer)) {
                    sum += Double.valueOf(answer);
                    count++;
                }
            }
        }

Rather than passing the response to filterMatch and isNumber, this narrows down to the information that they actually want.  This makes isNumber general purpose.

Yes, this requires changes to the other methods.

The ++ is more idiomatic than += 1.

Declare at the smallest scope that covers

        Double average = null;
        if(count != 0) {
            average = sum/count;

Consider

        if (count > 0) {
            Double average = sum / count;

Now if the count is not greater than 0, we don't even bother allocating a place to store the average.  We only do that if we're going to calculate it.  Since we don't use average outside the if, this changes no functionality.

As a functional matter, there wouldn't seem to be a difference between not equal and greater than.  But I find it to be more readable.  This makes it clear that negative values would not be handled.  The original just implicitly assumes that there will never be negative values.  But I had to think about that.  Now I don't.  If we counted something, we calculate the average and return it as a result.

Right after writing the code is when you know the most about it.  It's the best time to make the intentions of the code clear.  Because when you look at it in six months, you won't necessarily remember all the clever things you did today.  So make the code clear or comment why you can't.

And it will really help if someone else is the next person to edit the code.  Since that person never did know all the decisions you made while developing the code.


A simple Q and A quiz that reinforces Ruby learning

Store related data in a Hash

Also, looping like you've done is very uncommon in Ruby. You'll see Array#each (or Hash#each in this case) much more common than storing an index in a var while iterating through indexes.

@success_msg = 'Good job. Next question..'
@incorrect_msg = 'Incorrect. Next question..'
{
  "What is the command for a 'for' loop?" => 'for',
  'What is another name for a method?' => 'function',
  'What are the three types of loops that I know of?' => 'while, for, and until'
}.each do |q, a|
  puts q
  puts(gets.chomp.downcase == a ? @success_msg : @incorrect_msg)
end
puts 'All done.'

Also, I'd try to make this multiple choice or something if you're really trying to use it, theres no way your response is going to match those answers exactly. Perhaps you could look for certain terms in the response, but parsing English for semantic meaning isn't very easy hehe.


Generating a bytearray by choosing an exclusive set of parameters

Simplest would be to separate parsing of the bytes, words and dwords to their own respective method, this would simplify the main logic a lot

def pack_message2(DeviceID, Offset, dataLength=None,
                Byte0=None, Byte1=None, Byte2=None, Byte3=None,
                Word0=None, Word1=None, DWord0=None):

    Offset_low, Offset_high = parse_offset(Offset)

    if dataLength is not None and not 1 <= dataLength <= 4:
        raise ValueError('dataLength should be between 1 and 4')

    result = parse_dword(DWord0)
    if result == ():
#         print('no dwords')
        result = tuple(parse_words(Word0, Word1))
        if result == ():
#             print('no words')
            result = parse_bytes(Byte0, Byte1, Byte2, Byte3)

    if dataLength is None:
        dataLength = len(result)

    result = pad_tuple_to(result, 4, 0) # if result should be padded with 0's'
#     print(result, dataLength)
    return bytearray([DeviceID, dataLength, Offset_low, Offset_high, *result])

Even if you wouldn't know what the implementation of each of these methods were, the code would be clear in what happens

offset

parsing the offset is pretty straightforward

def parse_offset(Offset):
    if Offset >= 2**16:
        raise ValueError('Offset should be less than 2**16')
    return (Offset & 0x00FF), ((Offset & 0xFF00) >> 8)

Data

Instead of manually chaining the splitting the words in bytes, you can use that generator expression. This will also allow you to easily parse triple words or even quads without letting the code explode

def parse_dword(dword):
#     print('dword:', dword)
    if dword is None:
        return ()
    if not 0 <= dword <= 2**32:
        raise ValueError('dword should be between 0 and 2**32')
    return tuple((dword & 0xFF * (2**(8*i))) >> (8 * i) for i in range(4))

def parse_words(*words):
#     print('words: ', words)
    for word in words:
        if word is None:
#             yield from (0, 0)
            break
        if not 0 <= word  <= 2**16:
            raise ValueError('word should be between 0 and 2**32')
        yield from ((word & 0xFF * 2 ** (8*i)) >> (8 * i) for i in range(2))

from itertools import takewhile
def parse_bytes(*bytes_):
#     print('bytes: ', bytes_)
    return tuple(takewhile(lambda x: x is not None, bytes_))

These methods can be further generalized, but I'll leave that open as an exercise

padding the result

the simplest (but not purest) way to pad a tuple

def pad_tuple_to(tup, to, default=None):
    return tup + tuple(default for _ in range(to - len(tup)))

generalization

I was intrigued by the generalization, so I tried it myself

def generalized_parse_word(size, words):
#     print('words: ', words)
    if words is None:
        return 'empty'
    for word in words:
#         print('word: ', word)
        if word is None:
#             yield from (0, 0)
            break
        if not 0 <= word  <= 2 ** (8 * size):
            raise ValueError('word with %i should be between 0 and %i' % (size, 2 **(8*size)))
        yield from ((word & 0xFF << (8*i)) >> (8 * i) for i in range(size))

def pack_message3(DeviceID, Offset, dataLength=None,
                Byte0=None, Byte1=None, Byte2=None, Byte3=None,
                Word0=None, Word1=None, DWord0=None):

    Offset_low, Offset_high = parse_offset(Offset)

    if dataLength is not None and not 1 <= dataLength <= 4:
        raise ValueError('dataLength should be between 1 and 4')

    data = (
        (4, (DWord0,)),
        (2, (Word0, Word1)),
        (1, (Byte0, Byte1, Byte2, Byte3)),
    )

    for size, words in data:
        result = tuple(generalized_parse_word(size, words))
        if result != ():
            break

    if dataLength is None:
        dataLength = len(result)

    result = pad_tuple_to(result, 4, 0) # if result should be padded with 0's'
#     print(result, dataLength)
    return bytearray([DeviceID, dataLength, Offset_low, Offset_high, *result])

arguments

Instead of manually naming the different bytes or words, I would accept a collection as argument, something like this:

def pack_message4(DeviceID, Offset, dataLength=None,
                dwords=None, words=None, bytes_=None):
    ...
    data = ((4, dwords), (2, words), (1, bytes))
    ...

testing

inputs = [
    {'Word0': 0x1122, 'Word1': 0x3344},
    {'DWord0': 0x11223344},
    {'Byte0':34, 'Byte1':17, 'Byte2':68, 'Byte3': 51},
]
for i in inputs:
    ans0 = packMessage(DeviceID=3, Offset=220, **i)
    ans1 = pack_message3(DeviceID=3, Offset=220, **i)
    print(ans0 == ans1, ans0, ans1)

True bytearray(b'\x03\x04\xdc\x00"\x11D3') bytearray(b'\x03\x04\xdc\x00"\x11D3')
True bytearray(b'\x03\x04\xdc\x00D3"\x11') bytearray(b'\x03\x04\xdc\x00D3"\x11')
False bytearray(b'\x03\x03\xdc\x00"\x11D3') bytearray(b'\x03\x04\xdc\x00"\x11D3')

Could it be your method to calculate the dataLength in the case of Bytes is off by 1


Create a pump object from either one of pump model number or pump product id

You could make your code "more dynamic" by creating a whitelist of "actionable keys" and the associated method name to be called, but that seems like unnecessary convolution.

Your current method is direct and literal and probably makes sense to those on your development team.  I only have a few minor suggestions, but overall you should keep your basic structure.

It is not clear where $pump and $pumpFactory come from in your posted method, so I cannot offer advice on those variables.  I also don't know what processes are actioned by the subsequent method calls, nor do I know the value type (boolean?, array?, string?, etc) or value of the return.  A DocBlock would be a wise choice.

class AssemblyFactory
{
    /**
     * Generates assembly data based on model number or product id.
     *
     * @param array $params An array of pump details expected
     *                      to contain model number or product id.
     *
     * @throws InvalidArgumentException if $params does not contain a
     *         model number or product id.
     *
     * @return string Pump assembly name
     */
    public function makeAssembly(array $params)
    {
        if (array_key_exists('modelNumber', $params)) {
            return $pumpFactory->fromModelNumber($params['modelNumber']);
        }
        if (array_key_exists('productId', $params)) {
            return $pumpFactory->fromProductId($params['productId']);
        }
        throw new \InvalidArgumentException("FAIL");
    }
}

When seemingly simple code doesn't feel clear enough (or if you really love documentation blocks), then use DocBlocks to explain your script and avoid misinterpretation or lost time in the future.

PSR-5: PHPDoc

Here's an example that is relevant to your code: https://docs.phpdoc.org/references/phpdoc/tags/throws.html

Beyond your provided code, I feel that you should determine which lookup method is more efficient within your application (If this is a database lookup, is one column a Primary Key and another one not?).  Make the more efficient process the default one.

Alternatively, if you have two separate collections of data containing redundant data, consider merging the data storage so that only one lookup is necessary.


Check for pixel spacing between two folder images

The simplest improvement that you can do right now is to avoid recomputing the same reference image over and over for each case of an item: just store load_series(item).GetSpacing() before looping over each case.

You can also use writer.writerows and feed it a list or a generator instead of writer.writerow. This should optimize disk writes a bit, even though reading images should be the task that take up the most resources here.

Proposed improvements:

import csv
import SimpleITK as sitk

def load_series(path):
    reader = sitk.ImageSeriesReader()
    dicom_names = reader.GetGDCMSeriesFileNames(path)
    reader.SetFileNames(dicom_names)
    return reader.Execute()

def generate_equal_spacing(matches, progress_bar=None):
    items = matches.keys()
    if progress_bar is not None:
        items = progress_bar(items)

    for item in items:
        reference_spacing = load_series(item).GetSpacing()
        for case in matches[item]:
            if load_series(case).GetSpacing() == reference_spacing:
                yield (item, case)
                break

def main(matches, output_filename='BenignTest.csv'):
    with open(output_filename, 'w') as f:
        writer = csv.writer(f)
        writer.writerows(generate_equal_spacing(matches, ProgressBar()))

if __name__ == '__main__':
    main({
        '/mnt/sdd1/DSB2017/stage1/0030a160d58723ff36d73f41b170ec21': [
            '/mnt/sde1/Cancer/128443/01-02-1999-LSS-59120/2-0OPAGELSPLUSD3602.512060.00.11.5-98506',
            '/mnt/sde1/Cancer/213485/01-02-1999-ACRIN-13247/3-0OPAGELSPLUSLUNG3502.51204026.71.5-85097',
            '/mnt/sde1/Cancer/206342/01-02-1999-ACRIN-68321/3-0OPAGELSPLUSLUNG3702.51205033.31.5-72233',
            '/mnt/sde1/Cancer/200209/01-02-2000-CRIN-10216/3-1OPAGELSPLUSLUNG4002.51204026.71.5-42354',
        ],
        ...
    })


Is this a sensible form iteration pattern for a web form with an unknown number of fields?

is this iteration pattern safe?

Safe for what? Safe for a database? We can't tell you that! There's no code for your database entry function. What you have here is perfectly safe, but that's excluding any type of insert into a database. To safely protect yourself from SQL injection and other types of security exploits, use prepared queries, validate (sanitize only if needed) incoming data (which includes the username and $_POST['project']!), and encode any output.

Without your database function, it's difficult to critique your code. There's not too much that be be done wrong in the snippet provided.


For just a few items, the difference is small. If you have many items you should definitely use a switch.

This question might help: https://stackoverflow.com/questions/29566229/go-switch-string-efficiency


I see a number of things that might help you improve your code.

Arrange functions from simple to compound

Within your source code files, try to arrange your functions such that simpler functions, such as checkCrossing precede compound functions such as analyzeNewValue that call other simple functions.  Doing so allows you to avoid having to write function declarations that would otherwise be required.

Use const where practical

The checkCrossing function is passed a pointer to an ekgDataModel and the function does not alter that structure.  This should be made explicit by declaring the parameter const as in:

int checkCrossing(const struct ekgDataModel* ekgData) {

Carefully consider your data

The checkCrossing routine is looking for zero-crossings and uses this expression:

if (ekgData->newValue * ekgData->previousValue < 0) { /* ... */ }

However, consider the possibility that one of the samples is exactly 0.  For example, a sequence might be -0.15, 0.0, +0.20.  For (-0.15, 0.0) the expression is false and for (0.0, +0.20) the expression is again false.  The effect is that the function has just missed an obvious zero-crossing. An alternative approach would be to use the signbit macro:

if (signbit(ekgData->newValue) != signbit(ekgData->previousValue)) { /* ... */ }

I'd rewrite the function using stdbool.h as a bool function:

bool isZeroCrossing(float prev, float curr) {
    return (bool)signbit(curr) != (bool)signbit(prev);
}

Prefer >= to == to prevent "runaway data"

In the checkIfFrequencyValid function, the program currently does this:

if (ekgData->amountOfData == MAX_AMOUNT_OF_DATA
    && (ekgData->frequency < MIN_FREQUENCY_ALLOWED
            || ekgData->frequency > MAX_FREQUENCY_ALLOWED)) {
     /* stuff */
     ekgData->amountOfData = 0;
}

There is a potential problem here in that the analyzeNewValue function only increments amountOfData, so if it ever gets to MAX_AMOUNT_OF_DATA and the frequency is within range, subsequent readings will increase amountOfData beyond MAX_AMOUNT_OF_DATA which would make for a difficult-to-debug error.  Instead, use the >= operator for the first clause to make sure that you don't have "runaway data" problems.

Use better names

Function names such as displayWrongFrequencyMessage and initEKGData are good because they give a very good idea of what the functions are doing just by the name.  However functions like checkCrossing and checkIfFrequencyValid are not so good.  In one case, essentially a boolean value is returned indicating that a zero crossing has occurred, but in the other, nothing is returned at all.  Better for boolean functions is to name them to suggest what the return value might mean.  For example isZeroCrossing would return true if it detected a zero crossing.  Very clear and doesn't require much further explanation.

Check return values of standard functions

Many standard functions, including scanf can fail and return values that can help in detecting those failures.  To write robust software, you should get into the habit of checking the return values and dealing intelligently with the potential failures.

Avoid scanf if you can

There are so many well known problems with scanf that you're usually better off avoiding it.  The usual approach is to read in user input into a string and then parse from there, in this case using something like atof().

Think carefully about signed versus unsigned

Would it ever be possible that amountOfData or frequency would be negative numbers?  If so, what would that mean?  Better would be to declare them both as unsigned so that all possible values have an interpretable meaning.

Prefer pass-by-value for simple data

Generally, unless there is a need to modify the underlying variable, it's better to pass a value rather than a pointer.  For instance, this function:

void displayWrongFrequencyMessage(int *frequency) {

Could instead be written like this:

void displayWrongFrequencyMessage(int frequency) {

That way there's no way that the function could alter the original frequency variable and it's likely to be efficiently passed in a register.

Write code for humans to read it

The runElectrocardiography function is not bad, but it's not easy to understand.  I'd recommend doing something like this instead:

void runElectrocardiography() {
    unsigned dataCount = 0;  // number of data points so far
    unsigned crossingCount = 0; // number of zero-crossings
    float curr; // the most recent EKG voltage value
    float prev = 0; // the previous EKG voltage value

    for (curr = getNewValue(); curr != END_VALUE; curr = getNewValue()) {
        if (isWithinValidRange(curr)) {
            ++dataCount;
            if (isZeroCrossing(prev, curr)) {
                ++crossingCount;
            }
            if (!isFrequencyValid(dataCount, crossingCount)) {
                displayWrongFrequencyMessage(crossingCount);
                dataCount = 0;
                crossingCount = 0;
            }
            prev = curr;
        }
    }
}

Note that the ekgDataModel structure is no longer needed or used.


Calculate Work Week Hours by Shift (stored as dict)

I would improve the way you calculate total hours - you don't actually need to keep track of how much hours per day of a week you can work and do the calculations in one go on the "schedule" object with the sum() built-in function:

def _calc_workhours(sched=_DEFAULT_SCHEDULE):
    """Returns total work hours from a schedule."""
    return sum(_calc_shift_hours(shift)
               for shifts in sched.values() if shifts
               for shift in shifts)

Note that, to define the "scope" of a function more clearly and set the clear boundaries, it returns work hours instead of printing it and executing an os.system() call (which I consider a side effect). Then, to print the result, edit the main block of the program and replace:

_calc_workhours(schedule)

with:

total_hours = _calc_workhours(schedule)
os.system('cls||clear')
print("Total Weekly Hours: %s" % total_hours)

Other ideas:

use argparse module instead of reading from sys.argv directly - it will be cleaner overall, you would have a simple and clear way to define a "--help" mode for your command-line program. Would be easier to set the default value for the schedule
instead of parsing the schedule with literal_eval() from the command-line consider accepting a JSON file with your schedule object which you would load with json.load()
in any case, reading and parsing the schedule should also be extracted into a separate function
we can also refactor _calc_shift_hours() a bit and instead of accepting the shift list, accept two arguments, shift_start and shift_end, a bit more explicit and cleaner:

def _calc_shift_hours(shift_start, shift_end):
    """Returns a number of hours per shift."""
    tdelta = datetime.strptime(shift_end, _TIME_FORMAT) - datetime.strptime(shift_start, _TIME_FORMAT)
    # ...

def _calc_workhours(sched=_DEFAULT_SCHEDULE):
    """Returns total work hours from a schedule."""
    return sum(_calc_shift_hours(shift_start, shift_end)
               for shifts in sched.values() if shifts
               for shift_start, shift_end in shifts)

print() function vs print statement, .values() vs itervalues() for Python 3 compatibility
missing docstrings (I've added them in the snippets above - they still can/should be more detailed)
the way you set the default schedule at the moment can be improved so that, if a default schedule is used, you know about it, something like:

try:
    dictarg = literal_eval(sys.argv[1])
    if isinstance(dictarg, dict):
        schedule = dictarg
    else:
        print("Invalid schedule object provided. Using the default schedule.")
        schedule = _DEFAULT_SCHEDULE
except IndexError:
    print("No schedule provided. Using the default schedule.")
    schedule = _DEFAULT_SCHEDULE

if literal_eval() cannot evaluate a string - there will be ValueError thrown - currently it is not handled properly. This again, can be beautifully solved by argparse, or/and if you switch to having schedule in JSON


Loading information about a competition every time the page is loaded

Is this slowing down your app by a significant amount? If not, I wouldn't worry about it.

Other than that I would consider removing the custom error handling, and rather pass it on to some other more general error handler at the end of your middleware stack (just call next(err)), and maybe make the Not Found error a 404 status code.


I've just installed KTurtle for Windows, and ran your code. I never thought a turtle could be so frantic! KTurtle is ..entertaining to see in action! I've played with LogoWriter back in high school, an eternity ago; this is very similar (although I was somehow expecting a 16-color, 320x240 resolution.. the shock it was!).

  Save often.

  KTurtle works on Windows, but it sometimes crashes when you click to run your script. Save often; save every time you want to run it, and it's workable. Also whatever you do, don't undock the code pane, it seems impossible to dock it back into the IDE afterwards (and restarting the IDE won't help). If you have access to KTurtle on Ubuntu, by all means don't bother with Windows (assuming it's more stable on Ubuntu).

So I ran it again, at a slower speed.. first thing I'm noticing is that you're missing a clear at the beginning of the script (/program?), so that successive executions start off an empty canvas.

Your algorithm is drawing the 4 boards clockwise, starting top-left. Each board is made of 2 horizontal and 2 vertical lines, which means if you skip drawing the larger/bolder lines in the center, the canvas looks like this:

Your algorithm takes good care of not drawing the same line twice and gets the job done, but there's no separation of concerns whatsoever - as was mentioned in @Sjlver's answer, you need abstractions; teaching a kid how to get things done is nice, teaching the kid how to think in terms of abstractions is even nicer. I would go by @Sjlver's recommendation and create a command responsible for drawing a single square (learn square), and use a repeat loop to keep the code DRY:

learn square $x, $y, $size {
    go $x, $y
    repeat 4 {
        edge $size, 90
    }
}

learn edge $size $angle {
    forward $size
    turnright $angle
}

Notice the square command is only responsible for drawing 4 edges at the specified coordinates - the edge command is responsible for drawing a single line and turning the turtle in the specified direction. It is not responsible for knowing whether or not the pen is up or down.

I like that you're using penup and pendown instead of the shorthand pu and pd - you've used the easier-to-read ones and that's good.

So, now you have a command that can draw a square; now you need one that draws 9 of them to draw a board:

learn board $x, $y {
    for $w = 0 to 2 {
        for $h = 0 to 2 {
            square $x + $w * $boxSize, $y + $h * $boxSize, $boxSize
        }
    }
}

And now you can have code like this:

$boardSize = 150
$boxSize = $boardSize/3

# number of boards to draw in each direction:
$boards = 2

clear
pendown
penwidth 1

for $x = 0 to $boards-1 {
    for $y = 0 to $boards-1 {
        board $x * $boardSize, $y * $boardSize
    }
}

It's slower than your code, and it's not as efficient (pretty much every line get drawn more than once), but thinking in abstractions, in terms of functions that do only one thing, is more important than getting a script to do what you need it to do.

This is the result:

Now you want have a black border around each board, right? The code to do that is pretty much already written!

penwidth 5
for $x = 0 to $boards - 1 {
    for $y = 0 to $boards - 1 {
        square $x * $boardSize, $y * $boardSize, $boardSize
    }
}

Now this leaves the "script" part doing 3 things: declaring global-scope variables, drawing the boards, and drawing the outlines. Here's the final script, with the result:

learn square $x, $y, $size {
    go $x, $y
    repeat 4 {
        edge $size, 90
    }
}

learn edge $size, $angle {
    turnright $angle
    forward $size
}

learn board $x, $y {
    for $w = 0 to 2 {
        for $h = 0 to 2 {
            square $x+$w*$boxSize, $y+$h*$boxSize, $boxSize
        }
    }
}

learn drawBoards {
    for $x = 0 to $boards-1 {
        for $y = 0 to $boards-1 {
            board $x*$boardSize, $y*$boardSize
        }
    }
}

learn drawOutlines {
    for $x = 0 to $boards-1 {
        for $y = 0 to $boards-1 {
            square $x*$boardSize, $y*$boardSize, $boardSize
        }
    }
}

$boardSize = 150
$boxSize = $boardSize/3
$boards = 2

clear
pendown

penwidth 1
drawBoards

penwidth 5
drawOutlines

The "script" part is now only in charge of controlling the high-level stuff; the lower-level actual looping and drawing is abstracted away into commands with meaningful names, that start with a verb, and as a bonus, the turtle ends up right in the middle!


Using DataView is pretty much the same thing. Probably slower though. But it allows you to see that you only have to worry about endianness when dealing with values using more than one byte, like you do when storing width and height using 4 unsigned bytes each.

// Getting pixels as a byte (uint8) array
var imageData = ctx.getImageData(0, 0, can.width, can.height);
var pixels8BitsRGBA = imageData.data;

var i;
var pixelsAs32Bits = new Uint32Array(pixels8BitsRGBA.length + 8); // +8 bytes for the two leading UInt32
var pixelsARGB = new DataView(pixelsAs32Bits.buffer);

// Reverting bytes from RGBA to ARGB
pixelsARGB.setUint32(0, can.width, true); // little endian
pixelsARGB.setUint32(4, can.height, true);  // little endian
for(i = 0; i < pixels8BitsRGBA.length ; i += 4) {
    pixelsARGB.setUint8(i + 8, pixels8BitsRGBA[i + 3]);
    pixelsARGB.setUint8(i + 9, pixels8BitsRGBA[i]);
    pixelsARGB.setUint8(i + 10, pixels8BitsRGBA[i + 1]);
    pixelsARGB.setUint8(i + 11, pixels8BitsRGBA[i + 2]);
}

console.log(pixelsAs32Bits);


import time
import os
import sys

#class for parsing settings.ini
class parseIni(object):

Python style guide recommends names like ParseIni

    def __init__(self, fileStream):

Python style guide recommends argument like file_stream.

        self.lines = fileStream.readlines()

You don't use the lines again, so why are you storing them on the object. There is not a whole lot of point in calling deadlines, because you can actually just pass the file object in the for loop for the same effect

    self.options = []
        for line in self.lines:
            if "=" not in line:
                continue

I suggest almost always avoiding continue. As it is continue does nothing, replacing with pass will have the same effect. The whole if can be simplified by inverting the condition

            else:
                self.options.append(tuple(line.replace("\n", "").split("=")))

For clearing out excess whitespace, I recommend using line.strip(). I'd also suggest having options be a dictionary. Then you could do

 key, value = line.strip().split('=')
 self.options[key] = value

It'll make lookup more efficient and is a bit simpler

    def getValueOf(self, option):

Awkward and longish name. I'd have this be __getitem__, and then you can access it with the [] operator

        for op, value in self.options:
                if op==option:
                    return value

This is the for-if anti-pattern. Whenever you find yourself writing an if which should only be true for one instance of the surrounding loop, you should look for a better solution.

Also, what happens if the option is missing? You should probably raise an exception.

#Tries to open the settings file, if unsuccessful then exit program
settingsFileStream = None

No point in doing this.

try:
    settingsFileStream = open("settings.ini")
except IOError:
    print("ERROR: SETTINGS FILE NOT FOUND.", file=sys.stderr)
    raw_input("Press <ENTER> to exit....")
    sys.exit(0)

You should probably print the exception itself. As it is you are throwing away potentially useful error information.

#Initialize parser
settings = parseIni(settingsFileStream)

#Precondition: settings file was opened successfully
#Assigning values to required variables
timeDelayInMins = eval(settings.getValueOf("timeDelay")) #For user information

Using eval is a bad idea. It'll try to evaluate any valid python you pass to it which could allow an external file to cause your application to do bad things. You also can't be sure what kind of data you got back. Instead pass the incoming string to int or float to safely convert.

timeDelay = timeDelayInMins * 60 #Converting to seconds, for time.sleep() method
sourcePath = settings.getValueOf("sourcePath")
destinationPath = settings.getValueOf("destinationPath")

#Runs the game
os.system("Minecraft.exe")

#Prints out Welcome message
print()
print("|--------------------------------------------------------|")
print("|WELCOME TO MINECRAFT AUTO BACKUP UTILITY!               |")
print("|--------------------------------------------------------|")
print("|REFER TO THE settings.ini FILE TO EDIT SETTINGS FOR THIS|")
print("|PROGRAM. e.g. TIME DELAY FOR AUTO BACKUP, PATHS etc     |")
print("|--------------------------------------------------------|")
print("|TIME DELAY FOR AUTO BACKUP IS {:0.2f} MIN(S)        |".format(timeDelayInMins))
print("|--------------------------------------------------------|")
print()

#Variable to keep tract of backups done per session
backupsDone = 0

#mainLoop runs forever, backups "saves" folder every after ever timeDelay mins
while True:
    time.sleep(timeDelay)
    os.system('robocopy "{}" "{}" /e'.format(sourcePath, destinationPath))

Python has function for copying files. Consider using that instead of calling to another program.

    backupsDone += 1
    print
    print
    print("|---------------------------------|")
    print("|{} BACKUP(S) DONE THIS SESSION.  |".format(backupsDone))
    print("|---------------------------------|")

It would also be a good idea to move all this logic into a main() function.


SSE instruction to check if byte array is zeroes C#

This code is broken

When unrolling you add all the Vector16b.

From github.com/mono:

[Acceleration (AccelMode.SSE2)]
public static unsafe Vector16b operator + (Vector16b va, Vector16b vb)
{
    Vector16b res = new Vector16b ();
    byte *a = &va.v0;
    byte *b = &vb.v0;
    byte *c = &res.v0;
    for (int i = 0; i < 16; ++i)
        *c++ = (byte)(*a++ + *b++);
    return res;
}

So the vectors are added index to index, and then truncated back to byte. A sequence of adds can then end up as 0, fx:

16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 16 = 256

256 in binary is 0b100000000 and when you truncate that to byte you get 0b00000000.

You need to ensure that each individual Vector16b is equal to zero or use | instead of +.


Use alphabetical order for imports

import bpy
import os
import shutil
import time


Coded a Go Script that Sends proxy requests to backend servers

I'm looking for it to be peer reviewed with no holds barred critism of
my code. Why? to learn new ways of improving my coding techniques and
making it much more efficient. Judas Is Back

The evaluation criteria for a code review:
Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable. Code should be useful and have real value.

I tried to read your code. I found it to be an unreadable, sprawling, blob of code. Sorry!
The first step is to give the code some structure. For example,

On the Criteria To Be Used in Decomposing Systems into Modules, D.L.
Parnas, Carnegie-Mellon University, Communications of the ACM, December
1972, Volume 15, Number 12.

Parnas quotes Gouthier and Pont:

A well-defined segmentation of the project effort ensures system
modularity. Each task forms a separate, distinct program module. At
implementation time each module and its inputs and outputs are
well-defined, there is no confusion in the intended interface with
other system modules. At checkout time the in- tegrity of the module
is tested independently; there are few sche- duling problems in
synchronizing the completion of several tasks before checkout can
begin. Finally, the system is maintained in modular fashion; system
errors and deficiencies can be traced to specific system modules, thus
limiting the scope of detailed error searching.

After spending ten minutes on basic cleanup, this is what I have:
Playground: https://play.golang.org/p/tsPqSe0urdv
The main function summarizes the program.
func main() {
    // the servers
    serverConns := servers()
    // the proxies
    fanoutConn := proxies(serverConns)
    // the client
    client(fanoutConn)
}

The server and servers functions encapsulate the server related processing, promoting information hiding. I did a lot of basic cleanup.
// the server
func server(id int, conn frames) {
    defer close(conn)

    server := fmt.Sprint("server ", id, ": ")
    resps := []string{"banana", "apple", "guava"}

    for frame := range conn {
        time.Sleep(time.Duration(50+rand.Intn(500)) * time.Millisecond)

        resp := server + resps[rand.Intn(len(resps))]

        select {
        case <-frame.Done():
        case frame.resp <- resp:
        }
    }
}

// the servers
func servers() []frames {
    const totalServers = 10
    serverConns := make([]frames, totalServers)
    for id := range serverConns {
        conn := make(frames)
        serverConns[id] = conn
        go server(id, conn)
    }
    return serverConns
}

There is more cleanup to be done on these and other functions.
As the code gets more readable, we move closer to other code review goals like correctness and maintainability.
proxy.go:
package main

import (
    "context"
    "fmt"
    "math/rand"
    "time"
)

type frame struct {
    context.Context
    resp chan<- string
}

type frames chan frame

// the server
func server(id int, conn frames) {
    defer close(conn)

    server := fmt.Sprint("server ", id, ": ")
    resps := []string{"banana", "apple", "guava"}

    for frame := range conn {
        time.Sleep(time.Duration(50+rand.Intn(500)) * time.Millisecond)

        resp := server + resps[rand.Intn(len(resps))]

        select {
        case <-frame.Done():
        case frame.resp <- resp:
        }
    }
}

// the servers
func servers() []frames {
    const totalServers = 10
    serverConns := make([]frames, totalServers)
    for id := range serverConns {
        conn := make(frames)
        serverConns[id] = conn
        go server(id, conn)
    }
    return serverConns
}

// the proxy
func proxy(conns []frames, fanoutConn frames) {
    for p := range fanoutConn {
        ctx, cancel := context.WithCancel(p.Context)
        firstResp := make(chan string)
        for _, serverConn := range conns {
            serverConn := serverConn
            fwdframe := frame{
                Context: ctx,
                resp:    firstResp,
            }
            go func() {
                serverConn <- fwdframe
            }()
        }
        response := <-firstResp
        cancel()
        p.resp <- response
    }
}

// the proxies
func proxies(serverConns []frames) frames {
    connIDs := rand.Perm(len(serverConns))[:len(serverConns)/2]
    var conns []frames = make([]frames, 0, len(connIDs))
    for _, connID := range connIDs {
        fmt.Println("selected server:", connID)
        conns = append(conns, serverConns[connID])
    }
    fanoutConn := make(frames)
    go proxy(conns, fanoutConn)
    return fanoutConn
}

// the client
func client(fanoutConn frames) {
    for {
        resp := make(chan string)
        p := frame{
            Context: context.Background(),
            resp:    resp,
        }
        fanoutConn <- p
        fmt.Println(<-resp)
    }
}

func main() {
    // the servers
    serverConns := servers()
    // the proxies
    fanoutConn := proxies(serverConns)
    // the client
    client(fanoutConn)
}


Finding the difference between two different arrays using JS and FP

I am concerned that you really haven't defined "difference" here and that perhaps your code does not perform the way you expect.

You example is quite simple in that you would expect [4, 6].  But what if you had arrays like:

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

What do you expect to be returned?  Currently, your function would return [4, 4, 6], but is that what you expect, or would each instance of a repeated value need to be treated differently (i.e. return would be [1, 2, 3, 4, 4, 5, 6])?

Have you considered flipping your array values into object keys (if type conversion is not a concern) or using Array.sort() on input arrays in combination with fromIndex parameter to Array.indexOf() to minimize array iteration caused by Array.indexOf()? This may not be a concern if you don't expect to be diffing large arrays.

Do you really want to support the find()() syntax for this? I don't really see much value in nesting your function calls in this manner vs. just using:

let find = (arr1, arr2) => {
    // function logic
}

You are not ever returning the intermediate function for possible use elsewhere, so I don't follow the need for this approach.

I agree with the comment from @GregBurghardt around not unneccesarily wrapping native array functions.

I don't like the function being called find.  Perhaps something more descriptive to what is actually happening here like arrayDiff(). You are not finding here at all.

To me this whole thing would be clearer/simpler like this:

let arrayDiff = (arr1, arr2) => {
    return arr1.filter( elem => arr2.indexOf(elem) < 0 )
       .concat(
            arr2.filter( elem => arr1.indexOf(elem) < 0 )
       );
};

Note, this obviously does not address some of the questions I asked about uniqueness of array values or optimization of the filter operations.


Python script to convert hierarchical JSON to LaTeX itemize

Unless you specifically want a tab of 2 spaces in the resulting LaTeX, you can use '\t' to get the actual tab character.

TAB = '\t'

When working with strings with one or more backslashes, you can declare them as 'raw' strings by prefixing them with an r, which allows you to write backslash characters without having to escape them.

BEGIN = r'\begin{itemize}'
ITEM = r'\item {0}\hfill{{}}{1}'
END = r'\end{itemize}'

You can use the magic method iter() to get iterators, for example:

stack = [iter(data['items'])]

or

stack.append(iter(current['items']))

This is more idiomatic than calling the __iter__() method directly. In addition, there is a next() magic method as well which you can use to get the next item from an iterator.

current = next(iterator)

If you are using Python 3.4 or higher, I'd recommend checking out the pathlib module for manipulating file paths over os.path, but in this case using os.path does the job and is probably sufficient.


My first RSpec test - Rock Paper Scissors

let(:answers_snippet) { /valid answers/ }

it "fails when invalid" do
  game = RockPaperScissors.new(0)
  game.result.should match(answers_snippet)
end

When I read this spec code, I see that result should match valid answers, but from the spec name I see, that we test for invalid answers. Your specs code should be easy readable and I recommend to name constants correctly:

let(:invalid_answers_pattern) { /invalid answer/ }

Your specs are small and independent and if one spec will fail, it is enough to read this spec's code to understand how to reproduce problem. Specs are fine. But I would removed duplication in the last 4 specs, I think it won't hurt specs readability:

test_round_result(your_choice, opponent_choice, expected_result) do
  RockPaperScissors.any_instance.stub(:random_choice).and_return(opponent_choice)

  game = RockPaperScissors.new(your_choice)
  game.result.should == expected_result
end

it "should tie when rock vs rock" do
  test_round_result( 'rock', 'rock', 'tie!' )
end

#...

Also I found that you do too much logic in the initializer of your game class:

def initialize(choice)
    @choice = choice

    if is_valid_choice?
      @result = play
    else
      @result = instructions
    end
end

Class initializer should accept parameters and make sure your class instance is in the consistent state (is_valid_choice? in your case). You can write your class initializer this way:

def initialize(choice)
    raise ArgumentError, instructions unless valid_choice?(choice)
    @choice = choice
end

Or even accepted choice in the play method because choice is a parameter for the round of the game, not for the whole game and leave initializer empty for now. When you will start doing BDD, you will likely star making design decisions like this.
With this refactoring your tests will be a little bit cleaner, something like this:

let(:game) { RockPaperScissors.new() }

test_round_result(your_choice, opponent_choice, expected_result) do
  game.stub(:random_choice).and_return(opponent_choice)
  game.play(your_choice).should == expected_result
end


bool inputCheck(){
    if(!std::cin.fail())
        return false;

    std::cout << "Invalid input!" << std::endl;
    return true;
}

Carefully name your functions with a meaningful name.  inputCheck doesn't really tell anyone what to expect as a result.

Prefer to distinguish language constructs with spaces.

You can use the contextual boolean conversion operator to check the if the stream has failed rather than explicitly calling !std::cin.fail().

Prefer to avoid std::endl.  Be aware of what the manipulator std::endl actually does.  Stream '\n' as it explicitly states your intent, correctly outputs the end-of-line character, and is shorter to type.

bool isInvalidInput() {
    if (std::cin) {
        return false;
    }
    std::cout << "Invalid input!\n";
    return true;
}

bool numCheck(int i, char name){
    if(i < 0){ /* ... */ }
    if(name == 'm' && i > 3){ /* ... */ }
    if(name == 'n' && i > 12){ /* ... */ }
    return false;
}

Specify const for immutable variables.  const self-documents that a variable should not change values in the current scope and any accidental modification to the value is detected at compile time rather than run time.

Prefer enumerations to represent sets of related named constants.

Avoid magic constants as they are difficult to understand and may be overlooked.  Prefer symbolic constants to give values contextual meaning.

bool check(int x, char y){
    bool result = inputCheck() || numCheck(x, y);
    std::cin.clear();
    std::cin.ignore();
    return result;
}

Do you really want to ignore the remaining buffer on success?

unsigned int ackermann(unsigned int m, unsigned int n){
    if(m == 0)
        return n+1;
    if(n == 0)
        return ackermann(m-1,1);
    return ackermann(m-1,ackermann(m,n-1));
}

The Ackermann–Péter function should be tail-call optimized by any decent compiler, so you won't find much improvement with the recursive approach.  If you really care for performance, calculate Ackerman values in constant time using the formula's for \$A(m,n)\$.

$$
A(0,n) = n + 1\\
A(1,n) = n + 2\\
A(2,n) = 2n + 3\\
A(3,n) = 2^{(n+3)} - 3\\
A(4,0) = 13\\
A(4,1) = A(5,0) = 65533
$$

Contractually enforce your preconditions by testing them in the function that requires them.

namespace impl {
    unsigned Ackermann(unsigned m, unsigned n) {
        // calculate A(m,n)
    }
    void check_overflow_bounds(unsigned m, unsigned n) {
        if (m > 3 || n > 12) {
            throw std::out_of_bounds("");
        }
    }
}
unsigned Ackermann(unsigned m, unsigned n) {
    impl::check_overflow_bounds(m, n);
    return impl::Ackermann(m, n);
}

If your return type is an unsigned int, will Ackermann values overflow if \$m < 4\$ and \$n = 13\$?  Are there Ackermann values that don't overflow when \$m = 4\$ or \$m = 5\$?  Consider what actually is computable and throw an overflow exception for values that are not computable.


Sourcing data format from multiple different structures

Don't abuse inner lists

This:

self.name = ' '.join([data.get('name').get(key) for key in ['first_name', 'last_name']])

should be

self.name = ' '.join(data.get('name', {}}.get(key) for key in ('first_name', 'last_name'))

Note the following:

Generators don't need to go in a list if they're just being passed to a function (join) that needs an iterable
Give an empty dictionary as the default for the first get so that the second get doesn't explode
Use a tuple instead of the last list because the data are immutable

Use set logic

This:

return all(key in data for key in ('name', 'workEmail'))

is effectively asking "are both 'name' and 'workEmail' in data?" There's a better way to ask this - with a set.

needed = {'name', 'workEmail'}
return needed.issubset(set(data))

If data can be stored as a set once outside of this function, it will increase efficiency.

Read more here: https://docs.python.org/3/tutorial/datastructures.html#sets

Don't needlessly materialize generators

This:

# Instantiate Person from data
persons = [Person(data) for data in [dict_a, dict_b]]

# Store persons that fit the database model
persons = [PersonModel(**person.__dict__) for person in persons]

makes a generator, saves it to a list in memory, consumes that list, makes a second generator, and stores that generator in a second list in memory. Instead:

persons = [PersonModel(**Person(data).__dict__)
           for data in (dict_a, dict_b)]

Again, the last inner list should be a tuple.

Parsing heuristics

It's not useful to write separate parsing classes for formats A and B in this case, because they aren't declared by the API so have no meaning. Write a translation routine for every member you extract from the JSON. Do a series of attempts against known paths in the data to get the members out.


Docstrings: You should include a docstring at the beginning of every method, class, and module you write. This will allow documentation to identify what your program is supposed to do.
Constants Naming: Any constants that you have in your program (eg. cube) should be in UPPERCASE, like so: CUBE.
Main Guard: Any code that isn't inside a method/class should be inside an if __name__ == '__main__' guard. This will prevent this code from being executed if you decide to import this module from other programs. This StackOverflow answer provides more insight and explanation.
Unnecessary if/else with returns: It is unnecessary to have an else after an if, if you return something in the if. Simply put the else return statement outside the if statement. This return will be run if the if evaluates to be False, which removes the necessity for the else statement.
Reserved Names: You shouldn't use reserved names for variable names, such as iter and slice, to avoid confusion.
Variable/Parameter Naming: You have a parameter named iter which you use as the number of times you iterate over the cube. It took a bit to identify this, as I see iter as an iterator, not the number of times you iterate. Renaming it  iterations makes it clearer about what that parameter is supposed to be.

Updated Code

"""
Module Docstring
A description of your program goes here
"""

def updated_trajectory_component(row):
    """
    Updated the trajectory component of the passed row

    :param row: Row to be updated

    """
    num = 1
    return row[0] + sum([num / i for i in row[1:]])

def updated_distance_component(row):
    """
    Updated the distance component of the passed row

    :param row: Row to be updated

    """
    return [i - row[0] for i in row[1:]]

def iterate_row(row):
    """
    Iterates over the passed row

    :param row: Row to be iterated

    """
    dist = updated_distance_component(row)
    return [updated_trajectory_component(row)] + dist

def iterate_slice(_slice):
    """
    Iterates over the rows in the passed slice

    :param _slice: Slice to be iterated over

    """
    return [iterate_row(i) for i in _slice]

def iterate_cube(cube):
    """
    Iterates over the slices in the passed cube

    :param cube: Cube to be iterated over

    """
    return [iterate_slice(i) for i in cube]

def num_iterator(cube, iterations):
    """
    Recursive iterator, iterates over the cube `iterations` times

    :param cube: Cube to iterate
    :param iterations: Number of times to iterate
    """
    print(cube)
    if iterations == 1:
        return iterate_cube(cube)
    return num_iterator(iterate_cube(cube), iterations - 1)

if __name__ == '__main__':
    CUBE = [
        [
            [0, 0.1, 1],
            [0, 1, 0.1],
            [0, 1, 1]
        ],
        [
            [0, 0.1, 1],
            [0, -1, 1],
            [0, -1, 0.1]
        ],
        [
            [0, -1, -1],
            [0, 0.1, -1],
            [0, -1, 0.1]
        ]
    ]

    #Sample Cases
    num_iterator(CUBE, 5)
    num_iterator(CUBE, 2)
    num_iterator(CUBE, 7)
    num_iterator(CUBE, 4)


Use Python to determine the repeating pattern in a string

I see that there already is an accepted answer, before I got around to writing this answer. That is a little discouraging for me as a reviewer, but I've written a code alternative and have some thoughts regarding your code.

Code review

Document your code – To guess what your code is doing by simply reading it is not very easy. It could very well have a few comments on what it tries to achieve.
Better variable names – In general try to use variable names describing the content. Names like x, a, exp (which I would read as expression?), and so on, are not very informative.
Regex are generally expensive – In general regex, whilst being a fantastic too, are somewhat overused. Do note that it takes time to build the patterns and match the patterns, especially compared to simple string matches.

Some new(?) constructs

I'm not sure if you know these already, but there are a few new constructs I would like to show you:

String repeat – Strings can be multiplied (aka duplicated) using the multiplication operator.

text = "abc"
print text * 3     # Will output "abcabcabc"

divmod with multiple outputs – divmod(a, b) will divide a by b and return the divisor and the rest. This can be stored directly into a tuple like in the following:

div, rest = divmod(13, 5)   # Giving div == 2, rest = 3

Slice and dice strings – As of Python 2.3 one can slice strings. The most common variants indicates how many characters you want from start like text[:3] or if you want the rest of the text like text[3:]. This can be very useful...
A slightly fancier print varant – Using .format in combination with print can produce nicer output rather easily:

print 'i: {}, sub: {}, div: {}, mod: {}'.format(i, source[:i], div, rest)

This would output on the same line, something like:

i: 4, sub: abcd, div: 2, mod: 3

else-block after for?! – This will make sense later on, but if a for loop completes normally, it'll not enter the optional else:-block. In other words, if you break out of a for loop Python won't enter the else block. This can be used to verify that the for loop actually found/did something, and provide an alternative if it didn't.

for i in range(5):
    print i
   if i == 3:
      break
else:
   print "Nothing larger than 3..."

Code alternative

I haven't commented too much on your chosen algorithm, as I find it a little confusing, so I thought what is he trying to achieve and what is an alternative approach. I then came up with these demands for the code:

You're looking for the maximum repeated substring completely filling out the original string. This means:

The candidate substring length, must then divide the original string length without any leftover (or rest characters)
The candidate substring can't be more than half the length of the original string, as it then can't be duplicated
The first (and shortest) candidate substring will always give the most repeats, if it matches the other criteria

So one way to write this out is like this:

def repeatedSubstring(source):
  """Look for the shortest substring which when repeated equals
     the source string, without any left over characters.
  """
  length = len(source)
  print '\nOriginal text: {}. Length: {}'.format(source, length)

  # Check candidate strings
  for i in range(1, length/2+1):
    repeat_count, leftovers = divmod(length, i)
    # print 'i: {}, sub: {}, div: {}, mod: {}'.format(i, source[:i], repeat_count, leftovers)
    # print 'repeated: {}'.format(source[:i]*repeat_count)

    # Check for no leftovers characters, and equality when repeated
    if (leftovers == 0) and (source == source[:i]*repeat_count):
      print 'Found repeated substring: {}, count: {}'.format(source[:i], repeat_count)
      break
  else:
    print "Couldn't find any repeated substring"

repeatedSubstring("abcdeabcde")
repeatedSubstring("abcdeabcdef")
repeatedSubstring("aaaaa")

I've commented out some debug print statements, and left it a little more verbose than the original code.

If you want, you can easily replace the remaining print statements with return div and return 1. A stripped down version would then look like:

def repeatedSubstringCount(source):
  """Look for the shortest substring which when repeated equals
     the source string, without any left over characters.
     Return the maximum repeat count, 1 if none found.
  """
  length = len(source)

  # Check candidate strings
  for i in range(1, length/2+1):
    repeat_count, leftovers = divmod(length, i)

    # Check for no leftovers characters, and equality when repeated
    if (leftovers == 0) and (source == source[:i]*repeat_count):
      return repeat_count

  return 1

I still left a few comments in there, so that it possible to have some idea on what is happening. I've also changed the name to "repeatedSubstringCount" to indicate both what the function does, but also what it returns.


Compare two Excel sheets by Cell Content

This answer assumes that all Names in the data are unique. There is no
  provision in this example to handle duplicate Names except to issue a
  note in the debug output.

This answer will involve Dictionaries. Please review this website for complete information on how and why they are an efficient way to store unique data. The short answer is that you can create a large dictionary by looking at a unique "key", which is a string that uniquely represents some data that you want to track. In your case, you've asserted that all of the Names are unique. Dictionaries exist for speedy access to any single entry -- no looping through 200k entries to find the one you want. Use your unique key string and you have near-instant access to the data associated with that key.

For your situation, my example builds two Dictionaries, one for each set of data. The keys are the Names. The values associated with each key (Name) is the row number on which each Name is used. The row numbers will play a major role later on.

As with the other Code Review for your previous version of code, I'll reiterate:

Identify your function parameters ByRef or ByVal
Declare your variables as close to their first use as possible.

As an example:

Dim arr1 As Variant
Dim arr2 As Variant
arr1 = BuildDataArrays(ws1, startRow:=2)
arr2 = BuildDataArrays(ws2, startRow:=2)

You'll see that there is a call to a BuildDataArrays function. That brings me to

Functional Isolation. When your routine starts getting very long, that is the perfect time to begin breaking parts of the logic out into separate functions/subs. This is especially useful if you have repetitive logic where only the variable is different. This is the case for BuildDataArrays.

Give this function a worksheet and optionally the starting row or column and it determines the range of available data, returning a memory-based array. Breaking out code into separate routines is very helpful because it makes your main logic easier to follow.

Private Function BuildDataArrays(ByRef ws As Worksheet, _
                                 Optional ByVal startRow As Long = 1, _
                                 Optional ByVal startCol As Long = 1) As Variant
    '--- assumes all rows and columns are valid data
    Dim lastRow As Long
    Dim lastCol As Long
    Dim dataArea As Range
    Dim data As Variant
    With ws
        lastRow = .Cells(.Rows.Count, startRow).End(xlUp).row
        lastCol = .Cells(startCol, .Columns.Count).End(xlToLeft).Column
        Set dataArea = .Cells(startRow, startCol).Resize(lastRow - startRow + 1, _
                                                         lastCol - startCol + 1)
        data = dataArea
    End With
    BuildDataArrays = data
End Function

Use Dictionaries to collect your data. As with the previous point, this is a perfect opportunity to isolate the logic in a separate function.

The BuildDataDictionary function will accept your memory-based array and use the selected column of data as a unique key (currently defaulted to column "I").

Private Function BuildDataDictionary(ByRef data As Variant, _
                                     Optional ByVal keyColumn As Long = 8) As Dictionary
    Dim row As Long
    Dim name As String
    Dim names As Dictionary
    Set names = New Dictionary
    For row = LBound(data, 1) To UBound(data, 1)
        name = Trim$(data(row, keyColumn))
        If Len(name) > 0 Then
            If Not names.Exists(name) Then
                '--- add the new name to the dictionary and save the row number
                names.Add name, row
            Else
                '--- if you get here, it means that the Name is NOT unique
                '    and you'll have to change your logic, or change the name
                Debug.Print "ERROR: Duplicate name detected on " & _
                            " on row " & row & ": '" & name & "'"
            End If
        End If
    Next row
    Set BuildDataDictionary = names
End Function

Next we'll build the resulting report data. According to your description, the report will consist of all data rows (each with a unique Name), with any differences noted in the data itself. In your original post, you are assuming that the larger of the two row counts for the sheets will be your output array. This isn't true.

Consider that, by definition, all of the data from Sheet1 is unique (because each row's Name is unique). That means if you have 10 rows of data on Sheet1, your output data will have at least ten rows. It's possible that your data on Sheet2 also has ten rows of data, and only one of those rows repeats a Name on Sheet1. So your resulting report of data will have 19 rows.

Dim totalRows As Long
totalRows = ws1Names.Count

'--- now add on the number of unique rows from the other sheet
Dim name As Variant
For Each name In ws2Names
    If Not ws1Names.Exists(name) Then
        '--- name is unique
        totalRows = totalRows + 1
    Else
        '--- name is not unique
    End If
Next name
Debug.Print "There are " & totalRows & " unique Names between the sheets"

'--- now build a correctly sized output array
'    ASSUMES both arrays have the same number of columns!!
Dim reportData As Variant
ReDim reportData(1 To totalRows, 1 To UBound(arr1, 2))

Now that we're about to generate the report data, we have to consider how to make note of any errors encountered. For this I'm using a Collection, which is a simple way to generate a running list of items. In this case, for each difference I'm adding a string that notes the row and column of each difference in the data arrays. I can use this later on to highlight the difference cells.

'--- and create an object to list which cells are different
Dim diffCells As Collection
Set diffCells = New Collection

After that, we simply move the data over to the report array, making note of any differences.

'--- we know that all Names are unique in sheet1, so move the all that
'    data from sheet1 into the report array
Dim row As Long
Dim col As Long
Dim ws1row As Long
Dim ws2row As Long
row = 1
For Each name In ws1Names
    If ws2Names.Exists(name) Then
        '--- this row will have a difference because the Names match!
        '    so get the rows for each sheet that match the name
        ws1row = ws1Names(name)
        ws2row = ws2Names(name)
        For col = 1 To UBound(reportData, 2)
            If arr1(ws1row, col) = arr2(ws2row, col) Then
                reportData(row, col) = arr1(ws1row, col)
            Else
                '--- note the different values in the cell and add the
                '    row and column to the difference list
                reportData(row, col) = arr1(ws1row, col) & " <> " & _
                                       arr2(ws2row, col)
                diffCells.Add CLng(row) & "," & CLng(col)
            End If
        Next col
    Else
        '--- this is a unique row, so a straight copy of all columns
        For col = 1 To UBound(reportData, 2)
            reportData(row, col) = arr1(row, col)
        Next col
    End If
    row = row + 1
Next name

'--- the remaining data are the unique rows that exist in sheet2
'    the "row" variable count is continued in this loop
For Each name In ws2Names
    If Not ws1Names.Exists(name) Then
        '--- this is a unique row, so a straight copy of all columns
        ws2row = ws2Names(name)
        For col = 1 To UBound(reportData, 2)
            reportData(row, col) = arr2(ws2row, col)
        Next col
        row = row + 1
    End If
Next name

The final step is to output the report data. In my example, I am not creating a new workbook, but only creating a new worksheet. You can un-comment some code lines there to change it back for your purposes.

If diffCells.Count > 0 Then
    Dim report As Workbook
    Dim reportWS As Worksheet
    'Set report = Workbooks.Add           'un-comment to report to a new workbook
    'Set reportWS = report.ActiveSheet    'un-comment to report to a new workbook
    Set reportWS = ThisWorkbook.Sheets.Add   'comment to report to a new workbook

    '--- copy the resulting report to the worksheet
    Dim reportArea As Range
    Set reportArea = reportWS.Range("A1").Resize(UBound(reportData, 1), UBound(reportData, 2))
    With reportArea
        .Value = reportData
        .Columns("A:B").ColumnWidth = 25

        '--- now highlight the cells that are different
        Dim rowcol As Variant
        Dim parts() As String
        For Each rowcol In diffCells
            parts = Split(rowcol, ",")
            With .Cells(CLng(parts(0)), CLng(parts(1)))
                .Font.Bold = True
                .Font.ColorIndex = 3
            End With
        Next rowcol
    End With
    Debug.Print "Report Generated secs " & Timer - tm
End If

Here is the whole code module in one block:

Option Explicit

Sub test1()
    Compare2WorkSheets Sheet1, Sheet2
End Sub

Sub Compare2WorkSheets(ByRef ws1 As Worksheet, ByRef ws2 As Worksheet)
    Dim tm As Double
    tm = Timer

    'Application.ScreenUpdating = False
    'Application.Calculation = xlCalculationManual
    'Application.EnableEvents = False

    '--- establish the data in the arrays, skip the header row
    Dim arr1 As Variant
    Dim arr2 As Variant
    arr1 = BuildDataArrays(ws1, startRow:=2)
    arr2 = BuildDataArrays(ws2, startRow:=2)

    '--- buidl a dictionary of Names for each worksheet
    Dim ws1Names As Dictionary
    Dim ws2Names As Dictionary
    Set ws1Names = BuildDataDictionary(arr1)
    Set ws2Names = BuildDataDictionary(arr2)

    '--- we don't know how many rows the report will be, so compare
    '    names between the two sheets to find out. it's basically
    '    the sum of the number of unique names between the sheets
    Dim totalRows As Long
    totalRows = ws1Names.Count

    '--- now add on the number of unique rows from the other sheet
    Dim name As Variant
    For Each name In ws2Names
        If Not ws1Names.Exists(name) Then
            '--- name is unique
            totalRows = totalRows + 1
        Else
            '--- name is not unique
        End If
    Next name
    Debug.Print "There are " & totalRows & " unique Names between the sheets"

    '--- now build a correctly sized output array
    '    ASSUMES both arrays have the same number of columns!!
    Dim reportData As Variant
    ReDim reportData(1 To totalRows, 1 To UBound(arr1, 2))

    '--- and create an object to list which cells are different
    Dim diffCells As Collection
    Set diffCells = New Collection

    '--- we know that all Names are unique in sheet1, so move the all that
    '    data from sheet1 into the report array
    Dim row As Long
    Dim col As Long
    Dim ws1row As Long
    Dim ws2row As Long
    row = 1
    For Each name In ws1Names
        If ws2Names.Exists(name) Then
            '--- this row will have a difference because the Names match!
            '    so get the rows for each sheet that match the name
            ws1row = ws1Names(name)
            ws2row = ws2Names(name)
            For col = 1 To UBound(reportData, 2)
                If arr1(ws1row, col) = arr2(ws2row, col) Then
                    reportData(row, col) = arr1(ws1row, col)
                Else
                    '--- note the different values in the cell and add the
                    '    row and column to the difference list
                    reportData(row, col) = arr1(ws1row, col) & " <> " & _
                                           arr2(ws2row, col)
                    diffCells.Add CLng(row) & "," & CLng(col)
                End If
            Next col
        Else
            '--- this is a unique row, so a straight copy of all columns
            For col = 1 To UBound(reportData, 2)
                reportData(row, col) = arr1(row, col)
            Next col
        End If
        row = row + 1
    Next name

    '--- the remaining data are the unique rows that exist in sheet2
    '    the "row" variable count is continued in this loop
    For Each name In ws2Names
        If Not ws1Names.Exists(name) Then
            '--- this is a unique row, so a straight copy of all columns
            ws2row = ws2Names(name)
            For col = 1 To UBound(reportData, 2)
                reportData(row, col) = arr2(ws2row, col)
            Next col
            row = row + 1
        End If
    Next name

    Debug.Print " Calc secs " & Timer - tm
    If diffCells.Count > 0 Then
        Dim report As Workbook
        Dim reportWS As Worksheet
        'Set report = Workbooks.Add           'un-comment to report to a new workbook
        'Set reportWS = report.ActiveSheet    'un-comment to report to a new workbook
        Set reportWS = ThisWorkbook.Sheets.Add   'comment to report to a new workbook

        '--- copy the resulting report to the worksheet
        Dim reportArea As Range
        Set reportArea = reportWS.Range("A1").Resize(UBound(reportData, 1), UBound(reportData, 2))
        With reportArea
            .Value = reportData
            .Columns("A:B").ColumnWidth = 25

            '--- now highlight the cells that are different
            Dim rowcol As Variant
            Dim parts() As String
            For Each rowcol In diffCells
                parts = Split(rowcol, ",")
                With .Cells(CLng(parts(0)), CLng(parts(1)))
                    .Font.Bold = True
                    .Font.ColorIndex = 3
                End With
            Next rowcol
        End With
        Debug.Print "Report Generated secs " & Timer - tm
    End If
    'Application.ScreenUpdating = True
    'Application.Calculation = xlCalculationAutomatic
    'Application.EnableEvents = True

    If diffCells.Count > 0 Then
        Debug.Print diffCells.Count & " cells contain different data!"
    Else
        Debug.Print "No differences found between the sheets."
    End If
End Sub

Private Function BuildDataArrays(ByRef ws As Worksheet, _
                                 Optional ByVal startRow As Long = 1, _
                                 Optional ByVal startCol As Long = 1) As Variant
    '--- assumes all rows and columns are valid data
    Dim lastRow As Long
    Dim lastCol As Long
    Dim dataArea As Range
    Dim data As Variant
    With ws
        lastRow = .Cells(.Rows.Count, startRow).End(xlUp).row
        lastCol = .Cells(startCol, .Columns.Count).End(xlToLeft).Column
        Set dataArea = .Cells(startRow, startCol).Resize(lastRow - startRow + 1, _
                                                         lastCol - startCol + 1)
        data = dataArea
    End With
    BuildDataArrays = data
End Function

Private Function BuildDataDictionary(ByRef data As Variant, _
                                     Optional ByVal keyColumn As Long = 8) As Dictionary
    Dim row As Long
    Dim name As String
    Dim names As Dictionary
    Set names = New Dictionary
    For row = LBound(data, 1) To UBound(data, 1)
        name = Trim$(data(row, keyColumn))
        If Len(name) > 0 Then
            If Not names.Exists(name) Then
                '--- add the new name to the dictionary and save the row number
                names.Add name, row
            Else
                '--- if you get here, it means that the Name is NOT unique
                '    and you'll have to change your logic, or change the name
                Debug.Print "ERROR: Duplicate name detected on " & _
                            " on row " & row & ": '" & name & "'"
            End If
        End If
    Next row
    Set BuildDataDictionary = names
End Function

  EDIT: added an example on how to call the routine from a button click

It seems that you're adding an ActiveX command button to your worksheet. In this case, the CommandButton1_Click() method will be executed in the Sheet1 module. Take the code above with the Compare2WorkSheets routine and paste it into a regular code module. Then, in your sheet1 module, fix up your button-click code like this:

Option Explicit

Private Sub CommandButton1_Click()
    Dim myWorkbook1 As Workbook
    Dim myWorkbook2 As Workbook

    '--- if Sheet1 is contained in the workbook where the code is running, use this
    Set myWorkbook1 = ThisWorkbook

    '--- if Sheet1 is in a different -- but already open -- workbook, use this
    Set myWorkbook1 = Workbooks("the-already-open-workbook-filename.xlsx")

    '--- if Sheet1 is in a different -- but unopened -- workbook, use this
    Set myWorkbook1 = Workbooks.Open("the-workbook-filename-to-open.xlsx")

    '--- you can make the same decisions for setting myWorkbook2
    Set myWorkbook2 = Workbooks.Open("C:\Temp\testreport1.xlsx")

    Compare2WorkSheets myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1")

    myWorkbook1.Close
    myWorkbook2.Close
End Sub


Python program to get all non unique elements in an array

One thing to keep in mind is your variable checked_list, which serves almost no purpose in the function, as you could do without the else block.

The simplest thing I can think of would be just to shorten the function down to one list comprehension, instead of appending to two lists.

Revised code:

def checkio(original_list: list) -> list:
    return [x for x in original_list if original_list.count(x) > 1]

When running this function, these are the outputs:

checkio([1, 2, 3, 1, 3])  # Returns [1, 3, 1, 3]
checkio([1, 2, 3, 4, 5])  # Returns []
checkio([5, 5, 5, 5, 5])  # Returns [5,5,5,5,5]
checkio([10, 9, 10, 10, 9, 8])  # Returns [10, 9, 10, 10, 9]


Securing access to PHP services from Javascript Ajax calls

I consider myself a security nazi, and you're asking security-related questions, so I'm going to do something I don't normally do and be pretty blunt here.  Please don't take it personally.

You've completely missed the mark on security.  Not to say that your solution is "insecure" (you haven't given us enough information to really decide that), but simply because, from a security perspective, most of what you are doing just doesn't make sense.  Your code more-or-less looks like you threw together as many security-related functions as you could and called it secure.  Granted, these things aren't making things less-secure, but it also isn't making you more-secure.  I'm a firm believer that code that doesn't actually do anything should be thrown away.  That is the case with most of your code here.

I think the problem you have is that you've missed out on the big picture: what is your code actually trying to accomplish?  The answer, as near as I can tell, is to make sure that only the original viewer of a page can access the API calls related to that page.  In other words, you are trying to identify users via a secret.  In that context, here's the thing:

Don't use the remote address.  The client's IP address can change for any number of reasons, completely breaking your system.  This can happen as easily as someone opening your website on their phone with their home WIFI connection, and then stepping outside and switching to internet via their mobile carrier.  When that happens their IP changes and suddenly your javascript refuses all subsequent requests.  A system that breaks when the user moves 50 feet is definitely a problem.  Moreover, this is not a perfect security step anyway.  It is quite common for multiple users to share the same IP address, sometimes in contexts in which session stealing is most relevant (i.e. public wifi).  This means that identifying users by IP Address causes UI problems, and is also not secure.  Lose/Lose.
bin2hex is not the best choice.  If you want to encode random bytes as a string (which is perfectly normal: strings, especially ASCII, move back and forth from server-to-client easily), then don't use bin2hex.  For a given number of bytes, a hexadecimal string will be longer than an equivalent ASCII string.  Instead store your random string as an ASCII string using only numbers and letters.  You'll get shorter strings with the same amount of entropy.  Granted, this is really just a nitpick: this won't impact your security either way.  In essence, you are trying to generate a random string, and are doing that by taking random bytes and converting it to hex.  It's better to just generate a random string, IMO.
Neither crypt nor md5 are doing anything for you at all.  Again, focus on the big-picture goal here.  You are (as near as I can tell) trying to generate a random string to act as a "secret" to later identify users.  Encrypting things doesn't make them more random, and neither does hashing.  It's especially pointless to hash an encrypted string.  Encryption preserves data, while hashing destroys it.  The fact that you would follow up one with the other suggests that you don't really understand what you are doing.
Checking for the value both in the cookie and post data doesn't make your app more secure: it just gives you more code to maintain on both the front-end and back-end.  Moreover, it violates Kerckhoff's principle, which states that the only thing that should be a secret in any secure system is the actual secret (in this case, your key).  You're effectively trying to rely on an extra security step to keep out attackers, but that security step is already public (because it is present in your front-end javascript code).  As a result, it is pointless.  Just let the value come up in the cookie that you already set.

So what should you do?  I would suggest one of two things:

Best bet: authenticate users in this API call in exactly the same way that you authenticated them for the initial page load.  The only reason you can't do that is if:
Your system is anonymous and people are not authenticated at all.  In this case though, you don't need to do anything fancy at all: just use PHP's built in session system.  Its entire purpose is to securely identify users from one page-view to another, and everything you have here is basically a poor-man's session system.  You don't have to worry about errors in implementation if you use one that has been around and vetted for many years and by countless websites.  Don't reinvent the wheel, especially when it comes to security.

Also, standard things apply:

Make sure to flag your cookies as HTTP-only
Make sure to configure your cookies to only be transmitted over HTTPS.
This won't protect against session stealing, but then again neither will your solution.  That topic is a completely different discussion.

Forgot to say

If you don't want to use PHP sessions, then things can still be substantially simplified.  To reiterate the big picture goal, all you really want is a unique (and unguessable) key that lets you identify visitors from page-view to page-view.  You don't need crypt, md5, or salting to make that happen.  All you need is, literally, a long random string.  A 32 character string made from just numbers and letters (upper+lower case) gives you almost 200 bits of entropy, and is very easy to generate.  As long as your random string generator has no weaknesses, no one is going to guess such a string.  This becomes your session ID.  Store it in a cookie, and get it out of the cookie when it comes back up.  No need to encrypt or hash it: those don't increase your security at all.  So in the end your code basically just looks like:

$sessionId = randomString(32);
setCookie('qnrwp_ajax_cookie', $sessionId);
set_transient('qnrwp_ajax_temp_salt_'.$sessionId, 60 * MINUTE_IN_SECONDS);

Then:

$ajaxTrans = get_transient('qnrwp_ajax_temp_salt_'.$_COOKIE['qnrwp_ajax_cookie']);
if (!$ajaxTrans) wp_die();
// Also make sure and check session expiration

Also, you don't want to just die.  You should return some sort of API error that your front-end AJAX call can turn into a more user friendly "Your session has expired" error message.  Don't forget to check the session expiration.


Increase performance of a spate of 2x2 matrix multiplication

Leave matmul in
You can test the speed of matmul versus do-loops versus dot_product for any size arrays via the program found in this SO question. You can test this with any compiler and optimization you want, but the results are that any matrix of size < 50 (probably more, but I didn't test it higher than that), the three methods are identical in execution time.

Identity matrix initialization
This can be done with vector assignment and a simple loop

Tfu(i)%elements(:,:) = cmplx(0d0, 0d0)
do k=1,2
   Tfu(i)%elements(k,k) = cmplx(1d0,0d0)
end do

While Fortran defaults the imaginary component to zero when the 2nd argument is not present (e.g., cmplx(1d0)), it is probably better to be more clear by including it. Note that this won't change the run time, but it will make the declaration more compact.

Time variable in call to Z_gate
AFAIK, when there is math to be done in subroutine calls, Fortran will make a temporary copy of that variable. While it isn't much space for a double precision variable, you should still declare a new variable t_temp=t / dble(2 * CP_seq) and use that in place of your function call, especially since the math is done twice in subsequent calls to Z_gate.

It might also be worth declaring a new variable outside the j-loop

cp_seq_inv = 1d0/dble(cp_seq)

and making use of it as

t_temp = t * 0.5 * cp_seq_inv

As multiplication is faster than division, computing the inverse once (or at least once per call to this subprogram) should shave off some time.

Looping over k
Another thing to consider is that you have do loop increments at your disposal. That is to say, you can write your do k=1,CP_seq loop as

do k=1,CP_seq,2
! odd step
   Tfu(i)%elements = matmul(Tfu(i)%elements, Tud(i)%elements)
   Tfd(i)%elements = matmul(Tfd(i)%elements, Tdu(i)%elements)
! even step
   Tfu(i)%elements = matmul(Tfu(i)%elements, Tdu(i)%elements)
   Tfd(i)%elements = matmul(Tfd(i)%elements, Tud(i)%elements)
end do

Rather than wasting any time testing the two cases, do both in order and increment k by 2.


Ternary operation in Java - isn't this abuse?

I think it's important to note that nested ternary operators can be formatted to look good:

String name = isConditionA ? "first"
            : isConditionB ? "second"
            : isConditionC ? "third"
                           : "fourth";

This isn't the most readable option in your case, because you have longer method calls, but I think it's better when the conditions are kept short and meaningful.


Idiomatic use of computed properties in Polymer 2

Any specific comments on my use of computed?

I understand it's an annoying thing to have to repeat the dependencies for computed function but that's how Polymer can infer when that property has to be refreshed. If you had to use only the function name then it had to analyze your JavaScript code and it's an definitely a complex/slow task (it can't simply execute it to keep track of what you're reading because code may have side effects and/or multiple execution paths). The easiest workaround is to have you explicitly name the dependencies. Notably View.js does it for you.

Think positive: at least you do not have to add observers to all the dependencies and to manually invalidate the computed property...

  Any generic comments on this component?

Few things you can improve. First of all a non primitive default value shouldn't be an immediate value but a function. That value instance is shared across all instances of your component. Imagine you have two instances of <people-template> and in one of them you push() a new item in people. That new item is added to all the default instances! You should simply rewrite is as:

people: {
    type: Array,
    value: function () {
        return [
            { id: 1, name: "John Doe" },
            { id: 2, name: "Mary Havenstein" },
            { id: 3, name: "Janie van Staffelen" }
        ];
    }
}

There are, of course, cases when this shared value behavior is what you need (for example to implement a custom iron-meta-like component).

You set a new value for the property using this.set(), it's perfectly allowed but in this simple case you may also just use:

this.selectedPerson = event.composedPath()[0].item;

Of course you may decide to mark selectedPerson as read-only, in this case keep this.set() in-place.

I find that getting the model using composedPath()[0] is little bit fragile. dom-repeat template lets you use an easier syntax (see also Data binding helper elements):

this.selectedPerson = event.model.item;

Note that item is the name of the item used in the dom-repeat template, in your case you specified another name with as="person" then you need to use it:

this.selectedPerson = event.model.person;

I find person != null much more clear than return !!person if person is not supposed to be a boolean value.

In general I'd suggest to use a prefix for your custom components and to drop -template. Reasoning: they're all templates then you repeat the obvious and using a prefix you highly reduce possible collisions with 3rd party components.

You have a computed property hasSelectedPerson you use to hide a paragraph. Few things might be optimized here:

dom-if template does not need a boolean property, any falsy value will do the job then simply if="[[selectedPerson]]" is sufficient.
dom-if to hide a single element without any complex logic (for example lists) is an overkill and a (small) performance hit. You can use the hidden attribute (eventually complimented by a specific *[hidden] CSS rule when there isn't browser support) to achieve the same result: <p hidden$="[[selectedPerson]]">...</p>.


Adding, subtracting, and multiplying a vector by a scalar

No.

If this would be production code, you would be better off by

  (define (sub-vect v1 v2) (add-vect v1 (scale-vect v2 -1)))

However, this is not what the exercise asks for, as everything should be written "in terms of constructors and selectors".


Is my Python tkinter application properly structured?

Don't create more than one instance of Tk

You should only ever create exactly one instance of Tk. If you need to make more windows, useToplevel`.

You aren't using inheritance properly

This code is wrong:

class MainApplication(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        ...
        # Creating main page widgets
        frame = tk.Frame(root, bg="#34495e")
        ...
        lb = tk.Label(frame, ...)

First, you inherit from tk.Frame. This is good, in that when done properly you can treat MainApplication as if it were a standalone widget. However, the first thing you do after creating this frame is to create another frame as a child of root. That makes no sense since the object is itself already a frame. It completely negates any advantage of inheriting from tk.Frame.

The proper way to do this is to not create the "main page widgets" frame. Just remove that, and then put all widgets created by MainApplication inside self. The basic structure should look like this:

class MainApplication(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs):

        lb = tk.Label(self, ...)
        ...
            button_main = tk.Button(self, ...)
        ...
        button = tk.Button(self, ...)
        ...

if __name__ == "__main__":
    root = tk.Tk()
    app = MainApplication(root)
    # app is a frame, so add it to root. Since it's the
    # only widget in root, pack is the simplest method
    # to add it to the root window
    app.pack(fill="both", expand=True)

With that, everything in MainApplication is encapsulated inside the MainApplication frame, Nothing is leaking out into other widgets.

Don't inherit from Frame if it's not a frame

Your ChampionWindow inherits from Frame, but I can't see any reason to do so based on the way you coded it. You never use an instance of ChampionsWindow anywhere so there's no point in inheriting from anything.

Since the only purpose of ChampionWindow appears to be to hold a static method which creates a new window, I recommend inheriting from Toplevel and moving all code from the static method into a normal method called from __init__.

Don't remove control from the user

This is more of a personal preference, but I don't see any reason to remove the user's ability to resize the window with root.resizable(False, False). Usually, when I see that, it's a sign you didn't take the time to make your UI responsive. That seems to be the case here - the UI doesn't respond properly to resizing. Instead of just removing that ability, I recommend doing a few things to make the UI respond properly to resizing.


two or more render/redirect in the same method

Some notes:

Keep your controllers lean, this is too much code for an action.
The photo upload should be done as a part of the object's save chain (after validation), so create a before_save callback in the User model that returns false if the upload fails.
You set r (cryptic name) but don't use it anywhere? does the upload raise an exception on error?

At the end the controller should look extremely simple, something like:

def update
  @user = current_user

  if @user.update_attributes(params[:user])
    render action: 'edit'
  else
    redirect_to photo_path, flash: {alert: t(:text_photo_edit_failed)}
  end
end

Any additional logic should be in User. Models are easy to test in isolation, controllers on the other hand have a lot of state to worry about.


I'm going to copy and paste snippets from your other reviews that you havne't implemented as well as my own review:

  shortened names like out or d don't really have any benefit over
  slightly longer, clearer ones

You still use the exact name "out" in your code:

String out = "";

  stick with code style guides

Java in particular has common naming standards. You should use lowerCamelCase for class & method variables such as:

String UserInput

You may even notice StackExchange has given it different highlighting. Normally UpperCamelCase is used for classes.

while (count < ...

I'd suggest using a for-each loop here instead since you never use the 'count' variable

WhatToDo

I really don't like this name. I missed it at the top and it really surprised me when I first saw it used. "WhatToDo" Is not a good name.

"test" is also a really bad name. There are lots of information available online & on this site about variable namings. As a general rule, try to look at the name by itself and see if it's at all descriptive.

I don't see the point in declaring the variable "test". Just pass a boolean true/false directly to the method.