Scraping lunar/solar eclipse data with BeautifulSoup

Regarding the Eclipse class:

Using "eclipse" in names is redundant. Beware though, that date and type are would not be good names since they both usually have a different meaning. A common pattern (but also unsatisfying) is to add an underscore after the name as in type_ to use special words as a variable or parameter name.
In languages like Java I would probably make the properties private, but doing so in Python is much more of a maintainability trade-off as you've probably noticed. Avoiding the @property methods and naming the properties the same as the constructor parameters simplifies the code quite a bit.
This class is only a container, with no logic and only a little bit of string formatting. The argument could be made that the code would be a fair bit simpler if it was replaced with a dict.
You don't actually use any of the get_eclipse_ methods.

Regarding the main file:

Many of the names, like eclipse_info, info_to_clean and data are vague, and don't encapsulate what they contain. In some cases you'll find that this is because they are rather arbitrary middle steps between two more cleanly defined things, in which case their processing might be improved by splitting differently, or that they really can be named more clearly in context. For example, the eclipse_data passed as data to write_data_to_file is actually a list of strings, or more accurately a list of Eclipses rather than an arbitrary binary blob.
In generate_date_and_type you can merge several lines into one:

eclipse_date, eclipse_type = info_to_split.strip().split("—")

Rather than writing the results to a file, consider simply printing them. This makes your tool easier (and faster) to interact with using other shell tools, and it's still trivial to write the results directly to a file using a redirect.

General:

This code could benefit from type hinting. This will also often emphasize names which should be changed.
If I were working on this I might use an IDE to squish the entire program into a single function and see if there are any obvious classes or methods which show themselves. When building a larger system there is a lot of value to splitting and abstracting, but now that you have a working program it looks possible to squeeze the whole thing into about 20 comprehensible lines.


The end-of-list patterns can be combined into one:

zip4 (b:bs) (c:cs) (d:ds) (e:es) = (b,c,d,e) : zip4' bs cs ds es
zip4 _ _ _ _ = []

There's no need for a separate zip4' helper.

This definition is correct, but it's unnecessarily complex. List functions like this are usually defined in terms of more general list functions like map, rather than by explicit recursion. The actual definition of zip4 is:

zip4 = zipWith4 (,,,)

Doing recursion exercises like reimplementing standard list functions can teach you the bad habit of using recursion even when you don't need it. Good Haskell code does almost all list manipulation with high-order functions or list comprehensions. It's better practice to use them than reimplement them.


A small extension to the reCaptcha library

The $error field should be private (Why use getters and setters?). Currently users of the Captcha class can modify the value of the $error field directly which. It's not a good idea to allow them to do this.
What's the point of returning with false in the check function when the response is not valid while if it's valid the function does not return with true?
The render and check functions seems somehow temporarily coupled. See: Clean Code (by Robert C. Martin), G31: Hidden Temporal Couplings

References:

Effective Java Second Edition, Item 38: Check parameters for validity (I know that this is a Java book but this chapter applicable to PHP too.)
Function/method argument validation standards


Using encryption/hashing to create a secure login

Encryption isn't Hashing
encryptedPass = hashPass(pW)

You're not encrypting the password, you're hashing it.
For passwords you should not be hashing them with the SHA2 family. Instead, use bcrypt.
Sanitize input
From my limited knowledge of Python, it doesn't appear you're sanitizing your input on some functions, for example userExists() and the first query in newUser(). Instead, you're using simple string formatting to substitute values directly.
You should be passing the variables as arguments to execute() every time.


Assign values to a matrix based on the location of non-zero elements in another matrix

First, let's go through the code:

You have two calls to size() in the beginning of your code, where the dimension is specified. It's better to make a single call to size, and save the two variables.
This won't improve performance much, but will make it possible to reuse the two dimensions:

[rows, cols] = size(A);

You are using i and j as names for the iterators. In general, using those names are discouraged. It is not a problem when working with only real numbers, but once you
start working with complex numbers this could be a problem. As an example, consider the following code, where we're adding complex numbers:

x = 1 + i;      % Complex number, Real(x) = 1, Imag(x) = 1
for i = 1:10
   x = x + i
end

In this case, x will be 11 + i, instead of 10 + 11*i. Similarly, you might get code that doesn't behave as expected, if you forget to intialize i to a variable. For instance,
if you think you have written i = true, i = false, i = 0 or something similar, neither of the two statements will give an error: i == true, i == false. This might be hard to debug
since you don't get any error messages.

You have a growing loop inside your code. A row will be added to B for each iteration of the outer loop. This is very slow, and MATLAB actually warns you about this:

  The Variable A appears to change size on every loop iteration

You should always preallocate memory. In this case, the size of the B matrix is known:

B = zeros(size(A));
% or
B = zeros(rows, cols);

You loop through all columns and use if A(i,j) == 1 to check if there are any non-zero elements. In the following code you use find to find the index of that element. A better
way to do this is:

for ii = 1:rows
    idx = find(A(ii,:) == 1, 1);
    if ~isempty(idx)
       B(ii,:) = A(ii,:) * idx;
    end
end

This way, you can save one loop, and only loop through each element once.

You should use proper indentation. This can easily be achieved in Matlab. Press Ctrl+a followed by Ctrl+i, and Matlab will do the
indentation for you.

The better way to do this:

A better way to do this, that's both simpler and faster is:

% Find the column index of the first element in each "slice".
[~, idx] = max(A,[],2);

% Multiply the column index with each row of the initial matrix
bsxfun(@times, A, idx);

[M, idx] = max(A, [], dim) returns the value and index of the largest element along one dimension. It will only give one index per row or column (dependent on which dimension you choose).
We can now multiply the vector of indices by the elements in A. For this, we use bsxfun.


Fast alternative for String.split by whitespace

Bug #1

You have an off-by-one error here:

  if(index1 < n - 1)
  {
    result.add(text.substring(index1));
  }

The consequence of this is that "a b c" will be split to ["a", "b"], poor "c" is left out.

Bug #2

I would expect the same output for these calls:

fastSplitWS("");
fastSplitWS("   ");

But that's not the case. The first returns an empty list, the second a list with a single empty string in it.
This behavior is also inconsistent with String.split.

This is caused by this:

if(!y)

One way to fix:

if(!y && i > 0)

Another way is to initialize y to true.
(Notice that with this variable name,
it's hard to understand the logical meaning of this.)

Readability

@TopinFrassi was too kind.
I find this code extremely hard to read,
mostly due to the poor naming throughout.
The unconventional indenting and brace placement don't help.

Performance

It's worth nothing the trade-offs of using .charAt and .toCharArray.
Take a look at those links, of the implementations in OpenJDK 8:

toCharArray does an arraycopy, using double the space
charAt does a boundary check on the index parameter

Which one is more efficient? I've no idea...

Improvement ideas

The indentation levels can be reduced here:

  if(text != null)
  {
    final int n = text.length();
    if(n > 0)
    {

The first one can be reduced using an early return:

if(text == null) return result;
final int n = text.length();
if(n > 0)
{

The second can be reduced by eliminating the if(n > 0) completely,
as the loop logic takes care of the n == 0 case automatically.

Suggested implementation

Applying the above suggestions and bugfixes, the implementation becomes:

private List<String> fastSplitWS(final String text) {
    if (text == null) {
        throw new IllegalArgumentException("the text to split should not be null");
    }

    final List<String> result = new ArrayList<String>();

    final int len = text.length();
    int tokenStart = 0;
    boolean prevCharIsSeparator = true;  // "preceding char is separator" flag

    char[] chars = text.toCharArray();

    for (int pos = 0; pos < len; ++pos) {
        char c = chars[pos];

        if (c == '\t' || c == ' ') {
            if (!prevCharIsSeparator) {
                result.add(text.substring(tokenStart, pos));
                prevCharIsSeparator = true;
            }
            tokenStart = pos + 1;
        } else {
            prevCharIsSeparator = false;
        }
    }

    if (tokenStart < len) {
        result.add(text.substring(tokenStart));
    }

    return result;
}


You probably want to forward your parameters:

   *result = f(*first, params...);

Try:

   *result = f(*first, std::forward<Params>(params)...);

To go along with forwardign you probably want two versions of trans() on that takes values by reference/value one that takes r-value references:

// Normal parameters.
trans(InputIterator first, InputIterator last, OutputIterator result,
      Function f, Params const&... params)

// R-Value parameters.
trans(InputIterator first, InputIterator last, OutputIterator result,
      Function f, Params&&... params)

Going to main transform function.

I am not sure you in realty want to pass a function and arguments. That's the whole point of the lambda. So you can wrap the function call and its parameters into a function.

threaded_transform(4, values.cbegin(), values.cend(), results.begin(), sum, 10);

// Or would you prefer:

threaded_transform(4, values.cbegin(), values.cend(), results.begin(),
    [](int other){ return add(other, 10);}
);

//Or even
threaded_transform(4, values.cbegin(), values.cend(), results.begin(),
    [](int other){ return 10 + other;}
);

If you do this you should write details about your iterator requirements.

The requirements for std::transform()

template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryFunction>
OutputIterator transform(InputIterator1 first1, InputIterator1 last1,
                         InputIterator2 first2, OutputIterator result,
                         BinaryFunction binary_op);

Where:
   InputIterator must be a model of Input Iterator.
   OutputIterator must be a model of Output Iterator.

In your threaded implementation you have a more stringent requirement for the output iterator. I believe it needs to be random access iterator.

    OutputIterator must be a model of Random Access Iterator.

See: http://www.sgi.com/tech/stl/RandomAccessIterator.html


Generate all possible permutations from a string with character repetitions

My solution below uses a custom radix counter and then maps the value to each character in a given String. I have used BigInteger as you will hit problems with ints once your String gets to about 10 characters long, and the same problem with longs once your String gets to around 16 characters.

I have wrapped it all in one class so you can see it in action, but given the Counter class is completely independent, you should have that in it's own file.

package permutationgenerator;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Iterator;

public class StringPermutationGenerator implements Iterable<String> {
    private final String word;

    public StringPermutationGenerator(String word) {
        this.word = word;
    }

    @Override
    public Iterator<String> iterator() {
        return new StringIterator(word);
    }

    private class StringIterator implements Iterator<String> {
        private final char[] alphabet;
        private final Counter counter;
        private final BigInteger max;
        private BigInteger count;

        private StringIterator(String word) {
            alphabet = word.toCharArray();
            counter = new Counter(alphabet.length, alphabet.length);
            max = BigInteger.valueOf(alphabet.length).pow(alphabet.length);
            count = BigInteger.ZERO;
        }

        @Override
        public boolean hasNext() {
            return count.compareTo(max) < 0;
        }

        @Override
        public String next() {
            StringBuilder sb = new StringBuilder();
            for (int i : counter.getCounter()) {
                sb.append(alphabet[i]);
            }
            counter.increment();
            count = count.add(BigInteger.ONE);
            return sb.toString();
        }

    }

    private class Counter {
        private final int radix;
        private final int length;
        private final int[] counter;

        public Counter(int radix, int length) {
            this.radix = radix;
            this.length = length;
            counter = new int[length];
        }

        public int[] getCounter() {
            return counter;
        }

        public void increment() {
            for (int index = length - 1; ; index--) {
                if (index == -1) {
                    resetCounter();
                    return;
                }
                if (counter[index] < radix - 1) {
                    counter[index]++;
                    return;
                }
                counter[index] = 0;
            }
        }

        private void resetCounter() {
            Arrays.fill(counter, 0);
        }
    }
}

Usage is as such:

for (String s : new StringPermutationGenerator("ferrari")) {
    System.out.println(s);
}


That example looks like a very simple "chain of command" implementation.
Looks fine to me, nothing unusual (though YYMV depending on the code-base).

You'll see things like this as an alternative to long blocks of procedural code, often when there's a bunch of distinct actions to perform that have no relation to one another. It's a nice way to clean up and cut up large classes to keep things "SRP"'d.


Remove the magic numbers for the constrained values and give them constants instead:

private static final double MAX_VAL = 10;
private static final double MIN_VAL = -10;

These constants should also be printed in the exception statement instead of hard-coding the values.  Otherwise, if you just change the constants, the code will give inaccurate results.

Regarding the class name, consider renaming it to something like Constrained2DPoint.  Points can also have a 'z' if they're used in 3D space, so the name Point may be ambiguous in either case.


Decoding assembly instructions in a Game Boy disassembler

I have some ideas about how you might be able to improve your program.

Avoid problems

Rather than trying to deal with the problem for every instruction, one approach is avoiding it entirely.  One way to do that is to simply append a number of bytes to the end of the vector.  If the maximum bytes for an instruction is \$n\$, then append \$n-1\$ bytes to the end and stop when you've advanced into the padded area.

Check before advancing

One could also pass the number of remaining bytes to the disassemble function.  However, the mechanism I'd suggest would be to pass a range, e.g.:

int diassembleOne(std::vector<char>::iterator& it, std::vector<char>::iterator& end) {
    //  figure out number of bytes for this opcode
    if (std::distance(it, end) > opbytes) {
        it = end;
        // throw or return 0
    }
    // disassemble the instruction thoroughly
    std::advance(it, opbytes);
    return opbytes;
}

Use const iterators

If all the code is doing is disassembling, then it shouldn't alter the underlying vector.  For that reason, I'd recommend passing a std::vector<char>::const_iterator &.

Use classes

I'd suggest using an Opcode class like this:

class Opcode {
    char code;
    short int bytes;
    std::string_view name;
    bool operator==(char opcode) const { return code == opcode; }
    int decode(std::vector<char>::const_iterator& it, std::ostream& out=std::cout) const {
        out << name;
        ++it;
        for (int i{bytes-1}; i; --i) {
            out << static_cast<unsigned>(*it++);
        }
        out << '\n';
        return bytes;
    }
};

constexpr std::array<Opcode,2> instructions {
    { 0x10, 2, "STOP $" },
    { 0x76, 2, "HALT " },
};

Pass a pair of iterators to the dissemble function

As mentioned before, you can pass a pair of iterators to the disassemble function.  Using that plus the class above:

int disassembleOne(std::vector<char>::const_iterator& it, std::vector<char>::const_iterator& end){
    auto op{std::find(instructions.begin(), instructions.end(), *it)};
    if (op == instructions.end()) {
        std::cout << "Instruction not found\n";
        it = end;
        return 0; // instruction not found or off the end of the passed array
    }
    if (std::distance(it, end) < op->bytes) {
        std::cout << "Not enough bytes left to decode " << op->name << '\n';
        it = end;
        return 0; // instruction not found or off the end of the passed array
    }
    return op->decode(it);
}

Now main becomes very simple:

int main(){
    const std::vector<char> char_vect = {0x76, 0x10, 0x20, 0x10}; // Fill vector of char
    auto end{char_vect.cend()};

    for (auto it{char_vect.cbegin()}; it != end; disassembleOne(it, end)) {
    }
}

Another way to do this would be to put more of the processing in the Opcode itself -- it would make sense that each opcode would know how to decode itself.

Be clear about caller expectations

This code, as with the original code, expects that the it being passed is a valid iterator that is not the end.  It is good to document that in comments in the code.


Getting lines from a file

You can use simple list comprehension to get all the lines from a file.

words = [word for word in open("dictionary.txt", "r")]

However, this does not ensure the file will be closed. To be safe, I would do this:

with open("dictionary.txt", "r") as file:
    words = [word for word in file]

The with ensures the file will be closed once you're done working with the file.

Globals

With a small program like this, globals can be quite helpful since you don't have to pass word_to_guess through functions. However, as you begin to develop more complicated programs, you should be mindful and careful about your globals "leaking" into other parts of your programs, should you be using multiple files.

Random choices

Instead of generating a random number between the min and max of the list, use random.choice(...) to chose a random word from the dictionary. And if you're worried about the beginning of the alphabet, you can create a buffer variable and splice the list so the beginning of the alphabet is removed.

# The first 11 words will be removed from the list #
buffer = 11
word_to_guess = random.choice(words[buffer:])

check_index_and_replace

Instead of casting replace on each index, you can use an if statement to make sure the letter is equal to the letter in word_to_guess, and in the same position. If it is, then assign that letter to the position in the list.

from typing import List

def check_and_replace(letter: str) -> List[str]:
    """
    For each character in the word, if that character
    is equal to the passed letter, then the position in
    user_guesses is changed to that letter.
    """
    for idx, char in enumerate(word_to_guess):
        if char == letter:
            user_guesses[idx] = letter
    return user_guesses

Type Hints

These help yourself and other people looking at your code understand what types of variables are being passed and returned to/from functions. As above, the function accepts a str for letter, and returns a list of strings.

lettersleft

If you have a function that only has one line, most of the time you can delete the function and put that line where the function is called. And since this function utilizes a built-in function to count the occurrences of # in the list, this function doesn't need to be written.

The main body

Instead of keeping track for each try, use a for loop and only run as many times as the user inputed. If the user enters 4, the loop only runs four times.

When I first played this game, it was impossible to win. I could guess the word, but the game wouldn't end. A quick fix is to check if the number of letters left is 0. If it is, display a game won message and exit the program. If it isn't, print how many are left and go through the loop again.

All in all, your program would look something like this:

import random
from typing import List

with open("dictionary.txt", "r") as file:
    words = [word for word in file]
buffer = 11
word_to_guess = random.choice(words[buffer:])
user_guesses = ['#' for _ in word_to_guess]

def check_and_replace(letter: str) -> List[str]:
    """
    For each character in the word, if that character
    is equal to the passed letter, then the position in
    user_guesses is changed to that letter.
    """
    for idx, char in enumerate(word_to_guess):
        if char == letter:
            user_guesses[idx] = letter
    return user_guesses

def main():
    tries = int(input('How many tries you want? '))
    for _ in range(tries):
        letter = input('Try a letter ')
        print(check_and_replace(letter))
        letters_left = user_guesses.count("#")
        if letters_left == 0:
            print("You guessed the word!")
            quit()
        else:
            print(letters_left, "letters remaining!")
    print("The word was", word_to_guess)

if __name__ == '__main__':
    main()


Use findAll() instead of each(). findAll() is a filter function which can be used on a Collection/Iterable or Map. It filters the result on satisfying the condition provided by the Closure parameter.

Here, you can filter String which has the desired text or does not match with the supplied regex. Using findAll is better than each because it returns the filtered collection as a result as compared to each which returns the Collection itself.

def regex = "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.+"

def headErrors = errorMessages.findAll {
    it.contains('Invoice does not foot Reported') || !(it ==~ regex)
}

assert headErrors ==  [
    'Line : 1 Invoice does not foot Reported',
    'cl_id is a required field',
    'File Error : The file does not contain delimiters',
    'lf_name is a required field'
]


Extraction of value from a dict-tree, given a path of arbitrary length

Recursive Approach Review

In this method you are performing too many look-ups.

First, you are looking up the 0th value of p two or three times.  List indexing does take time, so it may be faster to store p[0] in a local variable, to avoid repeatedly indexing into the list.

Second, you are  performing a dictionary looking ups two or three times.  While dictionary look-ups are fast, ideally \$O(1)\$ in time, they do take time.  p[0] in d is a dictionary lookup without retrieving the looked up value; d[p[0]] is a dictionary lookup that retrieves the value.

The first and second if statements do effectively the same things.  They check p[0] in d, and if true, they retrieve d[p[0]].  We can extract this common functionality, perform it once, and then, depending on len(p), perform the recursion.  Additionally, we'll use dict.get(p[0], None) to perform a single dictionary lookup, using the value from a single list index operation:

def get_val_from_path_1(d, p):
    d = d.get(p[0], None)
    if d is not None and len(p) > 1:
        return get_val_from_path_1(d, p[1:])
    return d

Note: I used d is not None, instead of simply testing if d is "truthy", so that if a subkey is requested of a "falsy" value (0, False, ""), the dictionary lookup will happen in the recursive call, and an exception will be raised similar to the original code.

EDIT: As mentioned by RootTwo in the comments, it is "safer" to use a sentinel object, in case None is an actual value contained in the JSON object.  Although if None values are contained in the JSON object, it is ambiguous as to whether the key does not exist, or exists with the value None:

def get_val_from_path_1(d, p):
    sentinel = object()
    d = d.get(p[0], sentinel)
    if d == sentinel:
        return None
    if len(p) > 1:
        return get_val_from_path_1(d, p[1:])
    return d

Iterative Approach Review

This code begins with tmp = d, which is odd as d is never used in the remainder of the code.  The temporary variable can be removed.

Similar to the Recursive Approach, you are using a double dictionary lookup.  s in tmp followed by tmp[s].  Again, using tmp.get(s, None) would perform the dictionary lookup once, and return None if the key was not present.

def get_val_from_path_2(d, p):
    for s in p:
        d = d.get(s, None)
        if d is None:
            break
    return d

EDIT: A sentinel can be used here as well, with the same ambiguity disclaimer:

def get_val_from_path_2(d, p):
    sentinel = object()
    for s in p:
        d = d.get(s, sentinel)
        if d is sentinel:
            return None
    return d

Which approach is better?

EDIT: Clarifications added at based on comments by Konrad.

Gloweye attempts to make the case that "recursive is the way to go".  I disagree.

First off, Python does not do tail call optimization.  If it did, it would close the performance gap with the iterative approach, but with the current recursive implementation, the iterative method would still win.

In each recursive call, the p[1:] is being passed to the p argument.  This is building a brand-new list, and copying the elements to the new list.  With n items in the original list, n-1 elements are copied the first time, n-2 are copied the second, n-3 the third, and so on, making this an \$O(n^2)\$ time algorithm.

Gloweye's approach is a constant factor worse, since *args[1:] in addition to constructing the list slice must "splat" the items into the argument list, which then gets unsplatted back to args tuple in the next call.  I should stress it is not that much worse; it is still only \$O(n^2)\$.

Both Gloweye's and the current recursive approach, passing p[1:] as the argument in the recursive call, can be corrected from \$O(n^2)\$ to \$O(n)\$ by replacing the list slicing with an iterator.  Since the recursive argument has changed from a list to an iterator, a second function would be needed to implement this change.

If tail call optimization was present, and the list was not being repeatedly sliced and recreated each step, such as by using an iterator to walk down the list of keys, then things would be better (as in \$O(n)\$).  Tail call optimization works by updating the arguments for the next call, and jumping to the top of the function, which turns the recursion into a simple loop.

So why not just use a loop?

One last optimization is to stop checking for the existence of the keys (or even a None default or sentinel value); these checks slow the loop down.  Instead, unconditionally lookup and retrieve the values.  Rely on Python's blazingly fast exception handling to efficiently recover from non-existent keys.

Also, use meaningful variable names.  d and p are far too obscure.

Finally, use """docstrings""" to document how to use the function.

def get_val_from_path(json_object, key_path):
    """
    Retrieve a value from a JSON object, using a key list to
    navigate through the JSON object tree.

    Parameters:
       json_object (JSON): An object return from json.loads()
       key_path (Iterable[str]): A list of keys forming the key path.

    Returns:
       The value found at the given key path, or `None` if
       any of the keys in the path is not found.
    """

    try:
        for key in key_path:
            json_object = json_object[key]

        return json_object

    except KeyError:
        return None

Optionally, use Gloweye's *args method signature for slightly friendlier calls, without the [] noise.

def get_val_from_path(json_object, *key_path):
    ...

get_val_from_path(d, "b", "2", "bb")  # --> "b2"


In this program there is a single remote server which performs miscellaneous work. Because there is only one server, it seems like a singleton pattern could fit well.

Let us see the definition from Wikipedia:

  In software engineering, the singleton pattern is a design pattern
  that restricts the Instantiation of a class to one object. This is
  useful when exactly one object is needed to coordinate actions across
  the system. The concept is sometimes generalized to systems that
  operate more efficiently when only one object exists, or that restrict
  the instantiation to a certain number of objects. The term comes from
  the mathematical concept of a singleton.

So basically you are on the right track but what can't a simple private final object accomplish what the singleton can ?

Furthermore, which disadvantages has using a singleton ?

Quoting from here

  Singletons are essentially static classes, relying on one or more static methods and properties. All things static present real, tangible problems when you try to do Unit Testing because they represent dead ends in your code that cannot be mocked or stubbed. As a result, when you test a class that relies on a Singleton (or any other static method or class) you are not only testing that class but also the static method or class.

and here

  It is because of this specific design choice that the pattern introduces several potential long-term problems:

  Inability to use abstract or interface classes;
  Inability to subclass;
  High coupling across the application (difficult to modify);
  Difficult to test (can't fake/mock in unit tests);
  Difficult to parallelize in the case of mutable state (requires extensive locking);

  and so on.

  None of these symptoms are actually endemic to single instances, just the Singleton pattern.

  What can you do instead? Simply don't use the Singleton pattern.

So basically this boils down, if you really need to use it then use it, but make sure you understand the possible pitfalls and possible upcoming problems.

That being said, let me review some of your code.

public class Configuration {
    public static final int COMPUTE_REMOTE_PORT = 8900;
    public static final String COMPUTE_REMOTE_ID = "COMPUTE_REMOTE_ID";
    public static final String COMPUTE_REMOTE_HOST = "localhost";
}

What will happen if the port or the remote host needs to be changed ? You will need to recompile this class because all members are static and can't be changed. How about testability of the server /client code ?

Using this setup also restricts the server to be on the same computer than the client(s).

Based on how you have implemented the ComputeService and the ComputeInterface I would like to suggest that you add another method to the ComputeTask interface returning if the task really has been processed. Right now if the ComputeService can't connect to the server the returned ComputeTask object doesn't tell the client that it hadn't been processed.

The private static boolean connected() method doesn't throw a RemoteException and therefor either the isConnected() method of the ComputeInterface shouldn't have a throws RemoteException or better, let the connected() really throw that exception.

Right now if this method returns false the client doesn't know what the problem is.

In addition, I would name the connected() method just isConnectedToServer() or something along this line. But nevertheless this method is doing to much because it is doing a registry lookup so to say it is connecting to the server, but is read like a simple "property getter" .

I would change isConnected() method like so

@Override
public synchronized boolean isConnected() throws RemoteException{
    if (computeServer == null)
    {
        return false;
    }
    return computeServer.isConnected();
}

Then I would replace the connected() method by a, to the ComputeInterface added, boolean connect() method which does exactly what the name implies like so

@Override
public synchronized boolean connect() throws RemoteException{
    if (computeServer == null) {
        try{
            Registry reg = LocateRegistry.getRegistry(Configuration.COMPUTE_REMOTE_HOST, Configuration.COMPUTE_REMOTE_PORT);
            computeServer = (ComputeInterface) reg.lookup(Configuration.COMPUTE_REMOTE_ID);
            System.out.println("New Connection to Compute Server");
        }
        catch (RemoteException | NotBoundException e){
            System.err.print(e);
            computeServer = null;
            throw e;
        }
    }
    return true;
}

and if you want to add some kind of authentication, I would add a boolean connect(someparameters) method to the ComputeInterface which then is called instead of just returning true.

The most recent question for me is if you really should use RMI for this application. RMI has some disadvantages like

it is using blocking IO
if you want to use callbacks, you will likely come into trouble if a router or firewall is set up
and some more

IMHO a much better alternative would be SIMON ( Simple Invocation of Methods Over Network), which is actively developed and maintained. I use this myself for a multi-server/multi-client system and don't regret its use.


Programming Challenge from Kattis: Watchdog

Your solution is right, but unfortunately the time limit enforces a certain optimization. The key of this is where it says:

  If several such point print point with lowest x, if several points with equal x, print point with lowest y

In your case, you just append all possible candidate and then you have a very complicated way to find the lowest. First of all, this complicated way could have been reduced to sorting and returning first element.

If we think a bit further on how does itertools.product work, it will first iterate over x and then over y. This means that the first candidate we find, is the one with lowest x and lowest y of those x. This means 2 things: you don´t even need that sort, the answer will always be the first candidate.

Now if the answer is always the first candidate, why are we keeping all candidates? And why are we still calculating other possible candidates when we already have the answer? Keeping this in mind, the solution to your time limit is simple adding a break after the possibles.append((x, y)) line. This will make us stop processing when we find the answer, and will save enough time for the time limit.

This means all the elif len(possibles)>1: part is unnecessary, making it shorter and cleaner. Another simple optimization is changing hatch_list to a set instead of a list so that the if (x, y) not in hatch_list: takes less than O(n). Its a small change that only requires changing list() to set() and append to add.

There might be more optimization to make but the one of the break is the key to the problem and the expected optimization to make to be able to not have time limit.


I feel that sometimes inlining some values makes things a little more readable. But in terms of overall compactness, this isn't that much better. Here is what I would probably write

Map value = (Map)methodOutOfMyControl();
Set<String> strings = new HashSet<String>();
for (Map.Entry<Object, LinkedHashSet<String>> set : value.entrySet()) {
    strings.addAll(set.getValue());
}


Functionality for automatic retry after exception

public static <T> Optional<T> autoRetry(@NonNull final DoWork<T> task, @NonNull final Optional<Predicate<T>> predicate) {

No predicate, please. Call it something like acceptResult or resultRejector... you know what I mean.

Thread.sleep(retry * StaticData.NETWORK_CALL_WAIT);

This doesn't do what you write, as the first time retry=0.

  I take care to not retry after InterruptedException & UnknownHostException.

The latter may be retryable as it may be a temporary network or DNS problem. But it's your choice.

final String regId = autoRetry(new DoWork<String>() {...

I'm too lazy to copy it in my Eclipse and without it, it's unreadable as I have no idea where the expressions ends. What about a private final DoWork<String> regIdDoWork = ... or alike?

Optional.<Predicate<Boolean>>absent()).orNull(); //No need of predicate hence send absent

How nicer would the world be if there was no Optional? :D Just null.

Note that even if you like Optional, you should probably use it for as return types only. This is the place where it may prevent bugs and where it doesn't add so much verbosity.


Selecting folders based on last modified date

Do not put all imports on the same line and use snake_case rather than camelCase for variable names.
Read PEP8, the official Python style guide to make your code look like Python code.

Use functions for better reusability. Instead of using hardcoded values like your folder path or archive date, use parameters. You will more easily be able to test various values in the interactive interpreter.
This also means using the if __name__ == '__main__' construct.

return values instead of printing them in the function. Again, better reusability.
For starter you can build a list and return it.

when using datetime objects, you can compare them directly. It is cleaner and probably faster than comparing their string representation. Building dates is also as simple as using the right constructor.

you don't need to move to the desired directory before listing its content. os.listdir can take the absolute path and work from that.

Revised code
import os
import datetime

def filter_by_date(src_folder, archive_date):
    relevant_folders = []
    for name in os.listdir(src_folder):
        full_name = os.path.join(src_folder, name)
        if os.path.isdir(full_name):
            if datetime.fromtimestamp(os.path.getmtime(full_name)) > archive_date:
                 relevant_folders.append(name)
    return relevant_folders

if __name__ == '__main__':
    print filter_by_date("C:\Users\Test\Desktop\Folder", datetime.datetime(2016, 11, 10))

Is a first aproach. But using append in a for loop is deemed unPythonic, better use a generator or a list-comprehension here:
import os
import datetime

def filter_by_date(src_folder, archive_date):
    os.chdir(src_folder)
    return [
        name for name in os.listdir('.')
        if os.path.isdir(name)
        and datetime.fromtimestamp(os.path.getmtime(name)) > archive_date
    ]

if __name__ == '__main__':
    print filter_by_date("C:\Users\Test\Desktop\Folder", datetime.datetime(2016, 11, 10))


Extend API of complex source-code parsing CPAN module

Now all these statements contain strings with prefix PPI::

I know this is true of all things in PPI itself, and its a very popular convention.

But I suspect there are cases where things may enter the Document without actually being =~ /^PPI::/.

Also, it seems to me that what you're optimising for is a less frequent usecase than you should be optimising for:

$x->isa("PPI::Whatever")

Should be more heavily used in real code than

"PPI::Whatever" eq $x->class

Either way, you can do better than

 "Whatever" eq $x->name

You could do

 $x->is_named('Whatever');

But that's still gross because "you're not using @ISA".

 $x->is("Whatever")

This could work, but now you're in a bind:

What happens if $x does not subclass whatever class the is method was added on?

These are all, IME, big annoying problems that your desired approach simply makes more complicated to paper over a minor detail.

Which is especially silly when

$x->isa("PPI::Whatever")

Will work, on everything, both PPI and not.

That doesn't mean a "name" attribute wouldn't be useful, but it needs to be said that you should not be proposing to use it as the prime deciding mechanism, and should probably only be for diagnostics.

Given all of the above, a functional API is going to be much more to your liking.

use PPI::Naming qw( is_named is_an );
# not ISA aware
if ( is_named( $object, 'Whatever' ) ) {
         ....
}
# ISA aware
if ( is_an( $object, 'Whatever' ) ) {

}

is_named would be straight forward:

sub is_named {
  my ( $object, $name ) = @_;

  return undef unless defined blessed( $object );

  # This allows somebody to specify "=Whatever" and have it mean
  # "Whatever.pm" instead of "PPI::Whatever"
  if ( $name =~ /^=(.*$)/ ) {
     return $object->class eq "$1";
  }
  return $object->class eq 'PPI::' . $name;
}

is_an would be a little more complicated.

use MRO::Compat;
use Scalar::Util qw( blessed );
sub is_an {
  my ( $object, $name ) = @_;

  my $class = blessed($object);
  return undef unless defined $class;

  # This allows somebody to specify "=Whatever" and have it mean
  # "Whatever.pm" instead of "PPI::Whatever"
  if ( $name =~ /^=(.*$)/ ) {
    return $object->isa("$1");
  }
  for my $parent ( mro::get_linear_isa($class) ){
    return 1 if $parent eq "PPI::" . $name;
  }
}

The biggest benefit of this approach is there's almost no room for error. There's no chance that one of your objects could be missing the magic methods you require.

Related Reading

MRO::Compat
Scalar::Util


Like it was mentioned in the comments, it's difficult for us to tell you how to get your code faster witbout more information about the runtime context of your code. But based on what you have shown in code, I would do these modifications:

import numpy as nm
import pytesseract
import cv2
import ctypes
from PIL import ImageGrab

def im_to_string():

    # Path of tesseract executable
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
    while(True):

        # ImageGrab-To capture the screen image in a loop.
        # Bbox used to capture a specific area.
        cap = ImageGrab.grab(bbox=(687, 224, 1104, 240))

        # Converted the image to monochrome for it to be easily
        # read by the OCR and obtained the output String.
        tes_str = pytesseract.image_to_string(
                cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
                lang ='eng')
        check_word(tes_str)

words_dictionary = ['orange', 'marshmellow']
scrambled_words_dictionary = set(sorted(current_word) for current_word in words_dictionary)

def check_word(tes_str):
    if sorted(tes_str) in scrambled_words_dictionary:
        print(tes_str)

im_to_string()

This is based ont the assumption that the word dictionary doesn't change between screen grabs.

Here's some of the modifications I made to your code:

I defined the word dictionary outside of check_word() so that it doesn't need to be recreated each time to invoke that function
I created a set with the words scrambled because a set is optimized to check for membership. You are also only cheking against the scrambled words
I also changed the name of the dictionary variable because a dictionary has a specific meaning in Python and that could be slightly confusing for someone reading your code

If it's not what you were looking for, give us more precisions.


Custom array like implementation with components x, y, z

I suggest you to use a solution that relies on properties notion. This is simpler and more efficient to implement. Here is what you can do:

class CustomArrayLike:

    def __init__(self):
       self._x = None
       self._y = None
       self._z = None

    @property
    def x(self):
       return self._x

    @x.setter
    def x(self, value):
       self._x = value

    @property
    def y(self):
       return self._y

    @y.setter
    def y(self, value):
       self._y = value

    @property
    def z(self):
       return self._z

    @x.setter
    def z(self, value):
       self._z = value

    def __repr__(self):
       return repr([self._x, self._y, self._z])

if __name__ == '__main__':
   a = CustomArrayLike()
   a.x = 1.2
   a.y = 2.3
   a.z = 3.4
   print(a.x, a.y, a.z)
   print(a)


Creating a human-readable list from the values of a map

A stream-based approach is still feasible, by materializing your state names into a List first.

By using a List, you can retrieve all the names except the last using List.subList(int, int) (this may be empty, for a single-entry Map), and then retrieving the last (or the only, for a single-entry Map) directly using a simple List.get(int). Afterwards, you just need to handle for an empty Map or String values.

public static String getHumanReadableStates(Map<String, String> stateMap) {
    List<String> names = new ArrayList<>(stateMap.values());
    if (names.isEmpty()) {
        return "";
    }
    String exceptLastPlusBlank = Stream.concat(
            names.subList(0, names.size() - 1).stream(), Stream.of(""))
            .collect(Collectors.joining(", "));
    return Stream.of(exceptLastPlusBlank, names.get(names.size() - 1))
            .filter(v -> !v.isEmpty())
            .collect(Collectors.joining(LocaleUtil.getBundleValue("theWordAnd") + " "));
}

Stream.of("") is introduced to append the final comma.


Show byte representation of generic type

I am not aware of any safe method in the standard library to do this, so we need some unsafe code.

In your code, you have two unsafe blocks. However, the first one is unnecessary: you can use as to perform the cast, but you need two consecutive casts, because we can't cast from &T to *mut u8 directly. Actually, you should use *const u8 here instead, since you don't actually mutate the referent. So, instead of mem::transmute, you can write:

let array = &element as *const T as *const u8;

If you really need a *mut u8, then you'd need to define element as mut and write &mut element instead of &element.

However, I would do this differently. I'd write a function to turn a &T into a slice of bytes (&[u8]), which would encapsulate the only unsafe operation of the program. Then, we can use a simple for loop on that slice to print each byte.

use std::mem;
use std::slice;

fn bytes_of<T>(value: &T) -> &[u8] {
    unsafe {
        slice::from_raw_parts(
            value as *const T as *const u8, mem::size_of::<T>())
    }
}

fn show_as_bytes<T>(element: T) {
    for b in bytes_of(&element) {
        print!("{:X}", b);
    }
}

fn main() {
    show_as_bytes(-1i64);
}

Note that the bytes_of function plays a very important role that would be lost if it was inlined (by hand): the lifetime of the returned byte slice is tied to the lifetime of the input parameter. It's as if it was written thus:

fn bytes_of<'a, T>(value: &'a T) -> &'a [u8] {
    // ...
}

If the function's body was inlined, the slice returned by slice::from_raw_parts would be unconstrained, and the compiler wouldn't be able to report an error if the slice accidentally outlived the data it references, causing subtle memory errors at runtime.

Bonus: Here's how I would format your original code (note the changes to whitespace and the removal of parentheses).

use std::mem::size_of;

fn show_byte<T>(element: T) {
    let array: *mut u8 = unsafe { mem::transmute(&element) };
    for i in 0..mem::size_of::<T>() {
         let current = (array as usize + i) as *mut u8;
         print!("{:X}", unsafe { *current });
    }
}

fn main() {
    show_byte(-1i64);
}


Swift: extract string with regex and range

Simplify the code

The guard statement and the following if let can be combined into a single statement:

let key = "Signature"
let signatures = iconURL.matches(for: "\(key)[^&]+")
if let firstSignature = signatures.first,
    let range = firstSignature.range(of: "\(key)=") {
    let signature = String(firstSignature[range.upperBound...])
    print(signature)
}

Improve the regex pattern

Your method is fragile because the key "Signature" may occur in the host part of the URL. Here is an example where it fails:

let iconURL = "http://Signature.com/?a=b&Signature=sig&c=d"

As mentioned in the comments, you can use a positive look-behind which includes the "=" character:

let key = "Signature"
let signatures = iconURL.matches(for: "(?<=\(key)=)[^&]+")
if let signature = signatures.first {
    print(signature)
}

However, this would still fail for

let iconURL = "http://foo.com/Signature=bar?a=b&Signature=sig&c=d"

because the "=" character is valid in the path part of an URL.

You also must ensure that the key does not contain any characters which have a special meaning in a regex pattern.

And now for something completely different

The Foundation framework has a dedicated URLComponents type to parse URLs into their parts. It does exactly what you need here:

let iconURL = "http://Signature.com/Signature=foo?a=b&Signature=2BI%2BauSvy&c=d"
let key = "Signature"

if let urlComponents = URLComponents(string: iconURL),
    let queryItems = urlComponents.queryItems {
    for queryItem in queryItems where queryItem.name == key {
        if let value = queryItem.value {
            print(value) // 2BI+auSvy
        }
    }
}

In addition, the value is already percent-decoded.


About LotteryGeneratorService

The goal of the method generateRandomInt is to generate a random integer:

private static int generateRandomInt(){
    Random random = new Random();
    return random.nextInt(N);
}

This method creates each time it is called a new Random object, which is inefficient. It is better to create the Random object just once, and reuse it each time a new random integer is needed.

This does raise a new concern: this class would benefit from being thread-safe (as it is called by Spring @Controller methods). While Random is thread-safe, it may perform poorly when used concurrently, and it would be preferable to use ThreadLocalRandom in this case:

  When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.

As such, consider refactoring this method to:

private static int generateRandomInt() {
    return ThreadLocalRandom.current().nextInt(N);
}

which makes it perform well concurrently and doesn't create unnecessary objects over and over.

I suggest adding documentation to this method so that it's clearer the range of the random integers returned. Currently, it returns random integers between 0 and N-1 included.

The second method is generateNRandom which generates x distinct random integers. First of all, its name is a bit misleading with regard to the parameters: it generates N random integers, but takes x as input. The current implementation can be improved a lot:

It generates a random integer between 0 (included) and N (excluded), but then it disregards 0 if it was generated. This could be solved by using the right bounds when fetching the random integer in the first place. For example, if you want to generate a random integer starting from 1 instead of 0, you can modify the generateRandomInt method to have ThreadLocalRandom.current().nextInt(1, N) instead.
It loops until x distinct numbers have been generated. This works well when there's a large pool of possible numbers, because more often than not, you'll pick a number that hasn't been generated yet. But when this pool starts to decrease, the time it takes to find one that hasn't been generated will increase dramatically. Consider you have a range of possible numbers from 0 to 10, and you want 10 distinct numbers; by the time you have got 9 of them, you'll have 1/10 chance of getting the 10th one, when this could be deduced automatically, since there's only one possibility remaining anyway.

There's a better approach that doesn't involve "fetch or try again". Since you have a range of N integers, and you want x distinct in it, you can shuffle that range once, and then take the first x elements. They are guaranteed to be distinct, since the source elements were distinct, and they were only shuffled; and you are guaranteed to have x of them. So you could have:

public Set<Integer> generateNRandom(int x) {
    List<Integer> list = new ArrayList<>(x);
    for (int i = 0; i < N; i++) {
        list.add(i);
    }
    Collections.shuffle(list);
    return new HashSet<>(list.subList(0, x));
}

This runs in linear-time, always. (Note that list could only be created once per N, so the creation of that list could be done outside of the method as well.). Also note that with such an implementation, you don't even need the generateNRandom method anymore.

About Controller

This is a Spring Controller, as noted by the RequestMapping annotation. In this case, you shouldn't create instances of LotteryGeneratorService yourself with

lotteryGeneratorService = new LotteryGeneratorService();

Let Spring inject that for you. Annotate LotteryGeneratorService with @Component (or @Service) and autowire it inside the controller with

@Autowired
private LotteryGeneratorService lotteryGeneratorService;

This makes the controller testable, by possibly injecting a mock service.

About LotteryTest

You do not need to set your variables to null:

@After
public void tearDown() {
    lotteryGeneratorService = null;
}

This doesn't help garbage collection, and clutters the code a bit. You should just get rid of that.

Also, since the method returns a Set, the test testNumbersAreUnique is not needed: it cannot contain duplicates, by definition of a set, so the test would be useless.


How do I make this C# code more efficient, in terms of FPS and time complexity?

I think your code is already quite good. My guess is that the calls to DetectHaarCascade are the majority of the time. Can you run a profiler on it? The Equatec profiler is free. As for the lower loop you could preallocate your colors (although I assume they're structs). Also, I don't see where possibleROI_eyes changes, so do you really need to draw that every time through the loop? Or is it drawing at the cursor position?


Ruby metaprogramming - declaring "properties" on a class

Rather than access the possibly uninitialized @permissions instance variable inside my_property, use your wrapper method permissions and put the initialization logic in there. Also use Hash.new to save you the ||= statements. Also, the name list should be a Set, IMHO:

def permissions
  @permissions ||= Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = Set.new }}
end

That way you can simply call

permissions[permission][level].add

without bothering if the intermediate hashes and sets have been initialized

Some other thoughts:

The second half of your my_property method is only about updating the access methods. This should be a separate method.
You don't use @perm_methods at all, you can remove it.
Use map(&:to_sym) (or even better, don't create the temporary string array in the first place, it's not shorter!).
Don't use to_sym on the first argument to define_method, it shouldn't be necessary.
The min_level part can be improved in style and efficiency. You have at least two options here to get all the affected levels:

Use array slicing: access_levels[access_levels.index(level)..-1]
Use drop_while: access_levels.drop_while { |level| level != min_level }

After cleaning this up a bit, I came around with the following (untested) code:

require 'set'

class ResourceBase
  class << self
    def my_property(name, access)
      access_levels = [ :all, :owner, :admin ]
      puts "#{name}: #{access}"

      access.each do |perm, min_level|
        access_levels.drop_while { |level| level != min_level }.each do |level|
          permissions[perm][level].add name
        end
      end
      update_permission_methods
    end

    def update_permission_methods
      permissions.each do |name, perm|
        define_method("#{name}able_properties") { |level| perm[level] }
      end
    end

    def permissions
      @permissions ||= Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = Set.new }}
    end
  end
end

class Resource < ResourceBase
  # Levels range: all < owner < admin
  # Higher levels imply lower ones (i.e. admin always have owner access)
  my_property :id, :read => :admin #, :write => :none
  my_property :name, :read => :all, :write => :owner
  my_property :pin, :read => :owner, :write => :owner
end

resource = Resource.new
puts "Readable: " + resource.readable_properties(:admin).to_s
puts "Writeable: " + resource.writeable_properties(:admin).to_s


Procedural generation of a general matrix representing a tile map

You don't need to create a second m x n matrix to track where you've set. Since you're only interested in the index of the last one placed in each column you can use an one dimensional n-length array to track the row of the last one added and then use that directly when indexing the matrix.
Similarly, it also lets you randomly choose columns that still have space to add ones directly (that is, the nber of ones added is less than the length of the column) using np.less, np.where, and np.random.choice instead of picking a column, checking if it contains all ones, and resampling if it does. That's almost always a bad approach, especially when you start to have more columns full than not. If there are 5 full columns and 1 non-full one you have to keep sampling until you randomly select the one non-full column with only 1/6th odds which is going to be slow.
Combining all that you can write everything you need in about 8 lines with a 6-7x speed up
def matrix_generator(m, n):
    matrix = np.zeros((m,n), dtype="int")
    ones = np.zeros(n, dtype="int")

    while np.any(np.less(ones, m)):
        i = np.random.choice(np.where(np.less(ones, m))[0])

        matrix[ones[i],i] = 1
        ones[i] += 1

        yield matrix


Clojure function composition: logging results of an action performed by a "pure" function

Let the side effects happen and return nil
The way you have your fight function has the potential to throw an exception when you try to use it. Notice how you start with two opening parentheses, (( -- this should stick out like a sore thumb to any Lisper, and it's especially rare in Clojure. Keep in mind that because Clojure is a Lisp, it attempts to call the first thing in any S-expression as a function. In this case, (swap! characters battleturn :player target) is the first thing in the single S-expression that constitutes the body of the fight function. That means that whatever that expression evaluates to, Clojure will try to call it as a function, using whatever follows (in this case, (swap! characters battleturn target :player)) as an argument. You don't really want that, though. You just want the side effects from using swap! twice, once for :player target and once for target :player, and then you don't care what it returns. There are a handful of special forms in Clojure that have what's called "implicit do syntax," which means you can have more than one S-expression in the body. defn is one of those forms, so all you have to do to avoid throwing an exception is take out a set of parentheses:
(defn fight [target]
  (swap! characters battleturn :player target)
  (swap! characters battleturn target :player))

Incidentally, this will also greatly simplify the way your battleturn function is structured, because you don't have to worry about returning thechars at the end of every conditional branch. You're working with a mutable collection (the atom characters), so the key thing to remember is that it doesn't matter what you're returning. This is backwards from the way things usually work in Clojure with its functional programming paradigm, but that's the whole point -- your program is utilizing a more object-oriented style, so it's all about mutating values rather than returning something. In this case, you're mutating things like the characters' HP.
Maybe each character should be an atom (also, destructuring)
On that note, I think it would make more sense to represent each character as its own, separate atom, since the character itself is what you are modifying. Maybe try something like this:
(def player     (atom {:name "Fred" :hp 100 :att 5 :dex 10 :alive? true :last-swing 0}))
(def creature-1 (atom {:name "Badman" :hp 99 :att 4 :dex 7 :alive? true :last-swing 0}))

(By the way, this is just a nitpicky thing, but the idiomatic thing to do in Clojure is to hyphenate multi-word symbol names, e.g. battle-turn instead of battleturn, etc.)
Then adjust your functions so that they are referring to the player and the creature directly by their symbols, rather than reaching into characters to get them. This also means you can take thechars out of your battleturn function entirely, which simplifies things:
(defn battle-turn [attacker defender]
  (let [{:keys [att dex]}   @attacker
        {:keys [hp alive?]} @defender
        result              (attack att dex hp)
        last-swing          (- hp result)]
    ...

I'll pause here and point out that I shortened your let statement in a couple of ways:

You no longer need to bind attacker and defender to (a thechars) and (d thechars), since we got rid of the characters collection altogether and we're just passing in the atoms for each character to the function explicitly. Notice that we now have to dereference attacker and defender using @, as they are atoms.

I used destructuring to simplify the process of grabbing fields from attacker and defender. Basically what we're saying is "bind the values for :att and :dex from @attacker to att and dex", and the same for :hp and :alive? from @defender.

Prefer cond over nested ifs
Another key point is that it's generally better to use a cond statement than nested if statements when you have several branches of conditional logic like you have here. It can really make your code easier to read if you structure it right. Consider this:
(defn battle-turn [attacker defender]
  (let [{:keys [att dex]}   @attacker
        {:keys [hp alive?]} @defender
        result              (attack att dex hp)
        last-swing          (- hp result)]
    (cond
      (not alive?)
      (printf "%s is already dead!\n" (:name @defender))

      (<= result 0)
      (do
        (printf "%s died!\n" (:name @defender))
        (swap! defender assoc :alive? false))

      :else
      (do
        (log-fight (:name @attacker) (:name @defender) last-swing hp)
        (swap! defender assoc :hp result)
        (swap! attacker assoc :last-swing last-swing)))))

The cond statement here makes it clearer that there are only 3 possible outcomes, and in what order they are considered.
printf/format is awesome
You may have noticed that I replaced your use of (println (str ...)) with (printf ...). printf is just a shortcut for (print (format ..., so we're really talking about str vs. format. To be fair, there's nothing wrong with using str, and in fact, it's often shorter than its format equivalent, particularly when you're not dropping a whole lot of things into the string. But I still prefer format, because I think it's a lot more readable, and when you use printf, it's often shorter than the equivalent (print (str ... expression. I don't think there's an "idiomatic" preference of one vs. the other, but I just thought I'd throw that out there for your consideration. Consider:
(println (str aname " hits " dname " for " aswing ". " dname " has " dhp " hp left."))

vs.
(printf "%s hits %s for %d. %s has %d left.\n" aname dname aswing dname dhp)


Most of your code looks good
The one improvement is do not overwrite the initial settings, instead extend from defaults and the options provided. Use $.extend for this

 popup.settings = $.extend(defaults, options);

Also store the reference of this into a variable so that it will be used inside event handlers and anonymous callbacks.

var Popup = function() {
    var popup = this,
        new_id = "div" + Date.now(),
        defaults = {
            id: new_id,
            container: "body",
            height: 200,
            width: 200,
            text: "
 created with \"id\" = " + new_id,
            x: 100,
            y: 100,
            position: "absolute",
            bgcolor: "red"
        };

    popup.create = function(options) {
        popup.settings = $.extend(defaults, options);
        var html = "
" +
            popup.settings.text +
            "
";
        $(popup.settings.container).append(html);
        popup.update();
    };

    popup.update = function(options) {
        popup.settings = $.extend(defaults, options);
        $("#" + popup.settings.id).css({
            "height": popup.settings.height + "px",
            "width": popup.settings.width + "px",
            "position": popup.settings.position,
            "top": popup.settings.y,
            "left": popup.settings.x,
            "background-color": popup.settings.bgcolor
        });
    };
};

var pop = new Popup(); // new popup is declared

pop.create({
    bgcolor: "green"
}); // popup appears green instead of read

pop.update({
    bgcolor: "blue"
}); // popup changes to blue


I'm assuming you're only wanting a review of the approach rather than the implementation. Otherwise, you would have placed the entire implementation in the question (which is required by Code Review if you wanted that reviewed).

Doing parameter checks on runtime is

A performance cost
Noise in the code
Development overhead

If you want to ensure type safety while not sacrificing runtime performance, code readability, or precious developer time (and hair), it is best to move this responsibility off the runtime and to somewhere else. This is either at authoring time, compile time, or both. Your options are either:

To use a type hinting and linter setup, like JSDoc and ESLint. This is the least invasive way to enforce safety while still be able to write in vanilla JS.
Use a type-safe language, like TypeScript or Flow. You'll have to change how your code is written, but type-safety is built-in. You can also write code in TS, compile it to JS, and always be sure that JS is type-safe (and not care about the consuming end).

In either case, there are tools, plugins and editor add-ons that allow you to get immediate feedback on incorrect types (in-editor warnings) and fail the build if the types aren't adhered correctly. An added benefit is that the code is self-documenting, especially if you take the JSDoc route.


Steve is absolutely right that adding a buffered layer between the Data input/output streams and the File input/output streams, will make things work a whole lot better. I would also suggest changing to use a try-with-resources system, which will also close, and otherwise manage the files in a better way:

try (DataInputStream dis1 = new DataInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
     DataInputStream dis2 = new DataInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
     DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile))); ) {

    //initialise block2 at right position
    dis2.skipBytes((int) blockSize);

    ... do other work ...

}

Now, your input/output is buffered, and it's closed cleanly, and there are no leaks. The input/output is also buffered, leading to fewer IO's, and more efficient processing.

This will likely make a huge difference in performance, but, I suspect that using NIO (ByteBuffer) operations (especially with memory-mapped IO) will be faster again. Consider using FileChannel operations that reduce the amount of memory copies that are made of the data in the file.

UPDATE:

I have taken some time to run some tests and use some strategies that I am familiar with from high-performance systems. As I suspected, a FilChannel with Memory-mapped IO is far faster.

On my computer, a file with 400,000 int values takes about 15 seconds to sort using your system. When I used Buffered IO, it took 1.5 seconds (10 times faster).

I then rewrote the system using a couple of tricks:

use small sorts for blocks of 32 integers.
then use merging for larger, and larger blocks.
use memory mapped IO to do the file accesses

The result was a sort in 0.096 seconds, or 150 times faster than your code.

Now, this code is not exactly simple, so, be warned that it is a little obscure.

The first thing I did though, was create a class to abstract away the low-level IO:

private static final class FastFile implements AutoCloseable {
    private final Path path;
    private final FileChannel channel;
    private final long size;
    private MappedByteBuffer buffer = null;
    private long mapPosition = -1;

    public FastFile(final Path folder, final long size) throws IOException {
        this.size = size;
        this.path = Files.createTempFile(folder, "tmpdata", ".dat");
        this.channel = FileChannel.open(path, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.READ);
        // Create the file with the right size.
        channel.write(ByteBuffer.allocate(1), size - 1);
        resetFile();
    }

    @Override
    public void close() throws Exception {
        channel.force(true);
        channel.close();
        buffer = null;
    }

    private final void relocate(final long filepos) throws IOException {
        if (filepos >= size) {
            throw new IllegalArgumentException("Illegal file position " + filepos + " in file of size " + size);
        }
        final long mappos = filepos >>> MAPPEDSHIFT;
        if (mappos != mapPosition) {
            final long pos = mappos << MAPPEDSHIFT;
            final long len = Math.min(size - pos, MAPPEDSIZE);
            buffer = channel.map(MapMode.READ_WRITE, pos, len);
            buffer.load();
            System.out.println("Move to position " + pos + " and length " + len);
            mapPosition = mappos;
        }
    }

    public void resetFile() throws IOException {
        relocate(0);
    }

    public int getInt(final long intPosition) throws IOException {
        final long filepos = intPosition << 2;
        final int offset = (int)(filepos & MAPPEDMASK);
        relocate(filepos);
        return buffer.getInt(offset);
    }

    public void putInt(final long intPosition, final int intValue) throws IOException {
        final long filepos = intPosition << 2;
        final int offset = (int)(filepos & MAPPEDMASK);
        relocate(filepos);
        buffer.putInt(offset, intValue);
    }

    public void rename(String targetName) throws IOException {
        Files.move(path, Paths.get(targetName));
    }

    public void delete() throws IOException {
        Files.delete(path);
    }

}

The above class can take a file, and read/write ints at any particular place. It first creates the file, and sets it to be the right size.

It is read/write and random-access. It can write an int at any position. The expensive part of the operation is relocating the buffer, but, that will happen seldom.

Using that file class, I have the following sort code:

private static void mergeSortSmart(String sourceName, String targetName) throws IOException {
    long start = System.currentTimeMillis();
    Path source = Paths.get(sourceName);
    final long size = Files.size(source);
    final long intvals = size >>> 2; // number of actual integer values (4 bytes per int).

    Path target = Paths.get(targetName).toAbsolutePath();
    if (Files.exists(target)) {
        Files.delete(target);
    }
    Path tdir = target.getParent();
    FastFile filea = new FastFile(tdir, size);
    FastFile fileb = new FastFile(tdir, size);

    int blockSize = 32;

    // copy the source data to a fast file, but do 32-size block int sorts
    // before merge-sorting.
    copyAndMicroSort(source, size, filea, blockSize);

    // then do iterative merge sorts.
    for (long bs = blockSize; bs < size; bs *= 2) {
        mergeFast(filea, fileb, intvals, bs);
        FastFile tmp = filea;
        filea = fileb;
        fileb = tmp;
    }
    // rename the sorted file.
    filea.rename(targetName);
    // delete the temp file.
    fileb.delete();
    System.out.printf("Sorted in %.3fs%n", (System.currentTimeMillis() - start)/ 1000.0);
}

The copyAndMicroSort is simple:

private static void copyAndMicroSort(Path source, long size, FastFile filea, final int batchSize) throws IOException {
    try (DataInputStream di = new DataInputStream(new BufferedInputStream(new FileInputStream(source.toFile())))) {
        long pos = 0;
        int cnt = 0;
        long vcount = 0;
        int[] data = new int[batchSize];
        while (pos < size) {
            if (cnt == data.length) {
                appendSortedInts(data, cnt, filea, vcount);
                vcount += cnt;
                cnt = 0;
            }
            data[cnt++] = di.readInt();
            pos += 4; // size of int;
        }
        appendSortedInts(data, cnt, filea, vcount);
    }

}

private static void appendSortedInts(final int[] data, final int cnt, final FastFile filea,
        final long vcount) throws IOException {
    Arrays.sort(data, 0, cnt);
    for (int i = 0; i < cnt; i++) {
        filea.putInt(vcount + i, data[i]);
    }
}

And the individual merge sorts are:

private static void mergeFast(final FastFile infile, final FastFile outfile, final long intCount, final long bs) throws IOException {
    long apos = 0;
    long bpos = bs;
    long outpos = 0;

    while (apos < intCount) {
        long alimit = Math.min(bpos, intCount);
        long blimit = Math.min(alimit + bs, intCount);
        while (apos < alimit && bpos < blimit) {
            int aval = infile.getInt(apos);
            int bval = infile.getInt(bpos);
            if (aval <= bval) {
                outfile.putInt(outpos++, aval);
                apos++;
            } else {
                outfile.putInt(outpos++, bval);
                bpos++;
            }
        }
        while (apos < alimit) {
            outfile.putInt(outpos++, infile.getInt(apos++));
        }
        while (bpos < blimit) {
            outfile.putInt(outpos++, infile.getInt(bpos++));
        }
        apos += bs;
        bpos += bs;
    }

}


Comparing multiple arguments and returns the smallest argument

You can use something called Varargs that was introduced in java 5.

It is used in method declarations to declare arguments as an array.

public void myMethod(double... doubleArray) {
}

public void callMyMethod() {
    myMethod(1.2, 4, 2, 1); // all those are put into a double[]
}

You can adapt this to your program by doing the following:

public static double smallest(double... vals) {
    // must pass at least 1 argument. You could also return Double.NaN or something
    if(vals.length == 0) throw new IllegalArgumentException("smallest must be passed at least 1 value.");
    // start with the first value as the smallest
    double smallest = vals[0];
    for(int i=1;i<vals.length;i++) {
        // see if this ones smaller than our stored smallest
        if(vals[i] < smallest) {
            smallest = val[i];
        }
    }
    return smallest;
}

You can then call this with as many double values as you like.


Java function that blocks until a specific file is deleted

This is an interesting concept. I would link it in with, say, a pid file, and have the program terminate itself when the pid file is deleted.... and also delete it's own pid if it terminates early. I think that's why you have your end() method....
General

public class BlockOnRunFile {
    private File watchedFile;
    private Path path;
    private WatchService watcher;

The above variables should all be final too. Also, there's an uncomfortable mix of the "old" File-based system, and the "new" Path based one. I recommend that you use Path, and stick to it.
Simplifications
This code is.... ugly.

path = FileSystems.getDefault().getPath(
        runFilePath.substring(0, runFilePath.lastIndexOf(FileSystems
                .getDefault().getSeparator())));
watchedFile = new File(runFilePath);
watchedFile.createNewFile();

It can be simplified a lot:
Path watchedFile = Paths.get(runFilePath).toAbsolutePath();
Path runDir = watchedFile.getParent();
Files.deleteIfExists(watchedFile);
Files.createFile(watchedFile);

Note, there is no actual File instance in there, all just paths.... Also, there is no Watcher in there. There is no need to create the Watcher in the constructor, it is only used in the block() method, so use it there.
In your block() method, the try/catch is good, but I would add a finally:
} finally {
    Files.deleteIfExists(watchedFile);
}

The Watcher should be added as a resource to the top of that try.... and it auto-closes that way...
Also, about simplification, this code should be 1 line:

WatchKey key;
key = path.register(watcher, StandardWatchEventKinds.ENTRY_DELETE);

like:
WatchKey key = runDir.register(watcher, StandardWatchEventKinds.ENTRY_DELETE);

Then, your code body, the guts, is a little more complicated than necessary, and has a bug....
The first thing is that the inner try/catch is unnecessary, and buggy. You cannot close() the watcher and then try to reset the key, and wait for more. That will just fail. The code will simply terminate the loop, yet you have a continue statement. It's unintuitive. I would simply remove the try/catch entirely.
The second bug is in the "OVERFLOW" code. Your code tests for if the file does not exist, but it should only continue if it does exist.
Finally, why do you have the take() commented out... and use a Thread.sleep()? The take() is a blocking operation, and will 'sleep' until there is an event ready. Use the logic in the take(), and trust it...
Oh, and your handling of InterruptedException is not good.....
Finally, you go to a lot of effort to make sure that every event in the directory is 'handled', but, there is no need to handle the events. All we need to do is to make sure our sentry file is still there. If it is gone, then we die. We don't care about any other files.... this essentially removes the need for the Overflow and other conditions....
Suggestions
With the 'finally' block, the above fixes, and a little bit of "return" instead of "break", your code becomes:
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class BlockOnRunFile {
    private final Path watchedFile;

    public BlockOnRunFile(String runFilePath) throws IOException {
        watchedFile = Paths.get(runFilePath).toAbsolutePath();
        Files.deleteIfExists(watchedFile);
        // create entire directory tree, if possible, to create our watch file
        // in.
        Files.createDirectories(watchedFile.getParent());
        Files.createFile(watchedFile);

    }

    public void end() throws IOException {
        Files.deleteIfExists(watchedFile);
    }

    public void block() {
        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
            final WatchKey key = watchedFile.getParent().register(watcher,
                    StandardWatchEventKinds.ENTRY_DELETE);

            // stall until the game is supposed to end
            // reset key to allow new events to be detected
            while (key.reset()) {

                // wait for a file to be deleted (or an overflow....)
                if (key != watcher.take()) {
                    throw new IllegalStateException(
                            "Only our key is registered, only it should be taken");
                }

                // now, we know something has changed in the directory, all we
                // care about though, is if our file exists.
                if (!Files.exists(watchedFile)) {
                    return;
                }

            }
        } catch (IOException e1) {
            Common.log.logMessage(e1, LogLevel.ERROR);
        } catch (InterruptedException e) {
            // propogate an interrupt... we can't handle it here.....
            // just let the file be removed, and we die....
            Thread.currentThread().interrupt();
            Common.log.logMessage(e, LogLevel.WARN);
        } finally {
            try {
                Files.deleteIfExists(watchedFile);
            } catch (IOException e) {
                // unable to delete the sentry file.....
                Common.log.logMessage(e, LogLevel.WARN);
            }
        }
    }
}


There is not a huge amount of code to review here, just a few things:

You have a method NewPrime which I assume provides a prime number between the two bounds provided. Yet you do not use it and call priemgen.newKey directly in calce. You should either get rid of the wrapper method or use it consistently.
Braces are used inconsistently:

else
    value2 %= value1;

Should be same as the if block:

else
{
    value2 %= value1;
}

The naming conventions are inconsistent. Standard naming convention for C# for methods and fields is PascalCase and local variables and parameters are camelCase:

calce -> CalculateE
newKey on priemgen should be NewKey
priemgen - I assume it's a field so should be PrimGenerator
lowerbound -> lowerBound
upperbound -> upperBound
GCD -> Gcd

If priemgen is what it sounds like then the name for nextKey should be NextPrime.
What does priemgen.newKey return if there is no prime within the given bounds?


Here's some points. I commented directly in the code.

(function () {
    'use strict';

    //Why do you use `database` instead of `mongo` or `mongodb`.
    //It can become confusing later in the code when you are using `db`.
    //It will be hard to tell the diffence between database and db.
    var database = require('mongodb');
    var util = require('util');

    var constants = require('../constants');

    var dbhelper = {
        //`me` Will it be you all the time ?
        //You should think a more meaningful name such as `logedInUserId`
        updateLastSeenDate: function (me) {
            //Do you really want to connect and close the database everything you want to update a field ?
            //You should consider keeping the connection alive and share it across the whole process.
            database.connect(constants.variables.connection, function (err, db) {
                if (err) {
                    db.close();
                    throw err;
                }
                var bsonID = database.BSONPure.ObjectID(me);
                var collection = db.collection('users');

                //nesting calls to async function is affecting readability, testability and maintability.
                //You should consider using workflow library such as async
                collection.findOne({
                    _id: bsonID
                }, function (err, result) {
                    if (result) {
                        result.lastLoginDate = Date.now();

                        //Here's another nested call
                        collection.update({
                            _id: bsonID
                        }, result, function (err, u) {
                            //Using async you could handle errors in only one place.
                            if (err) {
                                db.close();
                                throw err;
                            }
                            util.log('Update complete: updateLastSeenDate');
                            db.close();
                        });
                    }
                });
            });
        }
    };

    module.exports = dbhelper;
}());

I would use async https://github.com/caolan/async#waterfall, change a few variable names and share the connection. Since node.js in single threaded you can open only one connection and share it to all your modules.


Storing a ByteBuffer into a Cassandra database

I cannot see anything wrong with the way you are using it. The example is a little contrived (given that you are not actually using cassandra), and the only things I can see that look odd are a direct result of that.

Bottom line is that it appears to be a fine piece of code (which is perhaps why there have been no reviews so far).

As for some nit-picky things:

I don't like that you are hard-coding the size of the buffer (on the write-side): int size = 2 + 8 + 4 + attributeValue.length is 'ugly'.

I tend to do th 'overkill' approach and use a buffer that is always too big. I find memory is cheap for the occasional buffer (even up to a couple of megs of memory...). I then make the buffer a thread-local so that I am not always creating new buffers. In your example it is trivial because it is all in the main method.... but for a 'real' program you may want to reconsider. If you know your data will always be less than, say 4K, I would instead do the following on the write side:

// a 'smaprt' implementation will make the buffer a ThreadLocal,
// and will also make it grow, if needed.
ByteBuffer bbuf = ByteBuffer.allocate(4096);
bbuf.order(ByteOrder.BIG_ENDIAN);

Then, your code should reset the buffer before using it:

bbuf.clear(); // position to 0, limit to capacity
bbuf.putShort(employeeId);
bbuf.putLong(lastModifiedDate);
bbuf.putInt(attributeValue.length);
bbuf.put(attributeValue);

Now, instead of doing a rewind(), do a flip()

bbuf.flip(); // limit to position, position to 0
byte[] bytesToStore = new byte[bbuf.limit()];
bbuf.get(bytesToStore);

The advantage of the above is that you do not need to manually track the size of your data, and you do not need to keep allocating new ByteBuffers each time,


Some notes:

Those counter classes are probably overkill, keep it simple.
Ruby is an OOP language, but it's not necessary to create a bunch of classes  for simple scripts like this.
Idiomatic: if not x -> if !x
Idiomatic: { ... } for one-line blocks, do/end for multi-line.

I'd write:

fail("Usage: #{0} PATH (lines|words|find REGEXP)") unless ARGV.size >= 2
path, mode, optional_regexp = ARGV

open(path) do |fd|
  case mode
  when "lines"
    puts(fd.lines.count)
  when "words"
    puts(fd.lines.map { |line| line.split.size }.reduce(0, :+))
  when "find"
    if optional_regexp
      fd.lines.each { |line| puts(line) if line.match(optional_regexp) }
    else
      fail("mode find requires a REGEXP argument")
    end
  else
    fail("Unknown mode: #{mode}")
  end
end


spring has the concept of paging and they do something like this:

public Page findAll(Pageable pageable);

where the Page interface has the following methods (trimmed):

getTotalElements()
getTotalPages()
isFirst()
isLast()
nextPageable()
previousPageable()

it also extends the iterable interface so you can loop like this:

Library library = new Library();
Pageable pageRequest = ...
Page<T> page;
do {
  page = library.getData(pageRequest);
  for (T t: page) {
    log.debug("T is {}", t);
  }
  pageRequest = page.nextPageable();
} while( !page.isLast() );

the most notable difference is that the page being requested is not stored as a state in the client library. by storing the state you make it harder to use the same instance from multiple places in the code.

see http://docs.spring.io/spring-data/rest/docs/1.1.x/reference/html/paging-chapter.html


Give a try to shutil and subprocess.

To copy all the files:
http://docs.python.org/2/library/shutil.html#shutil.copyfile

import shutil
shutil.copy(src_file, destination_file)

To make the system calls:
http://docs.python.org/2/library/subprocess.html#subprocess.check_call

import subprocess
subprocess.check_call('ls -al', shell=True)


The design of Place.canUse(Animal) suggests that places use animals.
But in reality it's the other way around.
The question is not if land can use a whale,
but if a whale can "use" land.
I suggest to invert the design to Animal.canUse(Place) (or possibly even canInhabit).

If performance is important,
then you can add in Animal one method for each Place type,
for example canUseLand, canUseOcean.
After all, do you seriously need to consider future expansion of place types?
It's the animal kingdom that's likely to grow.
And the canUseX methods only need to be implemented in higher level classes,
the vast majority will be happy to inherit.


Line spacing is important for readability. leave two spaces before your functions and don't have so many after. be sure to also be consistent about whitespace around operators.
word.lower() does not change the case of word but rather returns a string that is the lowercase equivalent of word.
The following can be simplified using the modulo operator

charvalue = ord(i) +key
if ( charvalue > 122):
    charvalue = ord('a') + (charvalue -123)
    encryptedstring += chr(charvalue)

else:
    encryptedstring += chr(charvalue)

becomes

charvalue = ((ord(i) - ord('a')) + key) % 26 + ord('a')

Your cipherencrypt() function does not currently support negative keys (see #2), but if it did, cipherdecrypt() could be written as:

def cipherdecrypt(word, key):
    return cipherencrypt(word, -key)

In python it is recomendend to do this kind of replacement with a comprehesnion:

def cipherencrypt(word, key):
    return "".join(
        chr(((ord(i) - ord('a')) + key) % 26 + ord('a'))
        for i in word.lower()
    )

Your cipher does not currently support space or any non latin character. If passed a non latin character, like space, your program will not be able to decrypt it. consider expanding your range to all printable characters or adding a special case for space.


You do have to be careful when calling methods from the constructor though. See the answer to the same question here.
But as long as you don't call overridable methods (and don't pass a reference to this) there is no problem.

The biggest issue I have with your method is the naming. By convention a method starting with getXXX() implies that it actually returns that XXX. If you would rename your method to something like initFromExcelData() for example it would be a lot clearer what the method does.

I personally would also do the assignments for first and last name inside this method. Especially if these are the only things you want to do with the excel. That way you can make the map local to that init method.


First Python program: pick and display alien characteristics

Good job on your first Python program!

You used a Dictionary to store all the alien classes. There are many other alternatives to do the same task. The most common one for this kind of problem is Python Classes (https://www.w3schools.com/python/python_classes.asp).

You could simply create a class called myArmy and then create your soldiers as objects.

#Create a class called myArmy
class myArmy:

  #Use the __init__() function to assign values for name, color...
  def __init__(self, name, color, size, speed, damage):

    self.name = name
    self.color = color
    self.size = size
    self.speed = speed
    self.damage = damage

#Create your soldiers (Referred to as "Objects" here. The __init__() function is called automatically every time the class is being used to create a new object.
rogue = myArmy('rogue', 'green', 'small', 'fast', 'small')
warrior = myArmy('warrior', 'green', 'medium', 'average', 'heavy')
hunter = myArmy('hunter', 'dark green', 'average', 'average', 'average')

#Access Rogue information for example
print(rogue.name, rogue.color, rogue.size, rogue.speed, rogue.damage)

Next step should be to give them attack/defense values and attack speed, and let the user make them battle each other!


Congratulations, you just came up with a prime sieve! And indeed, it's faster than always considering all the multiples of 2 of 3. But why do you stop at multiples of 2 and 3? What about 5? And 7? But why stop somewhere?

Let's be more ambitious. What about skipping all the multiples of all the primes encountered so far? This is called the sieve of Eratosthenes. It uses more memory (if you double the maximum number you're interested in, you need twice the memory), but it will be faster and will tell you if any number below your maximum number is prime.

If you want more improvements, note that other prime sieves exist: both the sieve of Sundaram and the sieve of Atkin improve over the sieve of Eratosthenes. And of course, if you're interested in raw speed, use numpy or even a language like C.


Better way of calculating Project Euler #2 (Fibonacci sequence)

No iteration is required to calculate this result.

Every third Fibonacci number is even.  The Fibonacci numbers can be expressed in closed form as:

Fib(n) = 1/sqrt(5) * (phi^n - psi'^n)

where

phi = (1 + sqrt(5) / 2)

and

psi = (1 - sqrt(5) / 2)

F(n) is even when n is a multiple of 3.

Therefore the sum of even fibonacci numbers is equal to the sum of two geometric series, and can be calculated directly and exactly.

P.S. A little experimentation shows that

sum(i=0..n) Fib(3*i) = (Fib(3*n + 2) - 1) / 2

e.g.

2 + 8 + 34 = 44 = (89 - 1) / 2


You can do it with a more reduced code, taking advantage of the PHP count_chars() function:

function ra_count_chars($str) {
    foreach (count_chars(str_replace(' ', '', $str), 1) as $char => $count) {
        $result[chr($char)] = $count;
    }
    return $result;
}

This method has pros and cons:

pro: the characters are alphabetically sorted in $result
pro or con (depends on your need): upper- and lower-case are counted separately

In the other hand, as noticed by @insertusernamehere, this doesn't work for multibyte characters.

Last point: due to the above limitation, you might choose to omit not only spaces but also any character other than A-Z and a-z.
To achieve it merely change str_replace(' ', '', $str) into preg_replace('/[^A-za-z]/', '', $str).


Validity checks for a user signup process

This is only a partial review.

I would declare your constants outside of your functions, as they are constant.
Also, the constants you did declare outside of your functions should be chained.
Finally, you should never call a function more than once. If you are truly using functional-programming then you should do the following:

const required = joi.string().required(),
      loginSchema = joi
  .object({
    appname: required,
    email: required,
    password: required,
  })
  .required();

because a given function must return the same output for the same input.

Rewrite

'use strict';

const bcrypt = require('bcrypt'),
      boom = require('boom'),
      joi = require('joi'),
      flatten = require('lodash/flatten'),
      pick = require('lodash/pick');

const models = require('../../models'),
      { AccessToken, App, User } = models;

const debug = require('debug')('microauth:test');

const userFields = [
    'device',
    'email',
    'firstname',
    'language',
    'lastname',
    'phone',
    'uid',
  ],
      roleFields = ['name', 'description'],
      permissionFields = ['name', 'object', 'action'];

const required = joi.string().required(),
      loginSchema = joi
  .object({
    appname: required,
    email: required,
    password: required,
  })
  .required();

async function run(req, res, next) {
  const { appname, email, password } = await joi.attempt(req.body, loginSchema);

  const app = await getApp(appname);
  (!app) && (throw boom.badRequest(`Invalid app name: ${appname}.`);)

  (app.isInactive()) && (throw boom.badRequest('App is not active.');)

  const { isAuthorized, user } = await authorize({ email, password });
  (!user) && (throw boom.notFound('User not found.');)

  debug(`User ${user.get('email')} is authorised? ${isAuthorized}`);
  (!isAuthorized) && (throw boom.unauthorized('Invalid email or password.');)

  const { result } = await isUserBelongsToApp(user, app.get('name'));
  (!result) && (throw boom.badRequest(`User is not authorised to access app.`);)

  return successResponse(email, app.get('secret'), res);
}

async function getApp(name) {
  return await App.findOne({ name });
}

async function authorize({ email, password }) {
  const user = await User.findOne(
    { email, status: 'active' },
    { withRelated: ['apps', 'roles.permissions'] }
  );

  let isAuthorized = false;
  if (user) {
    isAuthorized = await bcrypt.compare(password, user.get('password'));
  }
  return { isAuthorized, user };
}

async function isUserBelongsToApp(user, appname) {
  let result = false;
  let app = null;
  app = user.related('apps').findWhere({ name: appname });
  if (app) {
    result = true;
  }
  return { result, app };
}

async function successResponse(email, secret, res) {

  let user = await User.findOne(
    {
      email: email,
    },
    {
      withRelated: ['roles.permissions'],
    }
  );
  user = user.toJSON();
  const result = Object.assign({}, { ...user });
  result.roles = [];
  result.permissions = [];

  if (user.roles) {
    result.roles = user.roles.map(role => pick(role, roleFields));
    result.permissions = user.roles.map(role => {
      return role.permissions.map(permission =>
        pick(permission, permissionFields)
      );
    });
  }
  result.permissions = flatten(result.permissions);
  const { token, expiration } = new AccessToken(secret).create(result);
  res.json({ token, expiration });
}

module.exports = run;


My approach on nested properties that bind to XAML

To me it looks fine. If you can or will not modify the model objects (Product) by letting them implement INotifyPropertyChanged then this approach is the price to pay for using XAML. In larger projects, it can be a little annoying to seemingly write the same thing twice, but you on the other hand have a true separation of concerns, and your solution is an implementation of the MVVM-pattern.
To me ProductVM is an OK name, I always name my view objects that way.

Instead of using string literals in the call to NotifyPropertyChanged you can use nameof(<property name>):
               NotifyPropertyChanged(nameof(Name));

this will make it easier to maintain, if the property name changes.

   Another approach is to define `NotifyPropertyChanged` as:

  private void NotifyPropertyChanged([CallerMemberName] string name = "")
  {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  }

then you don't need to provide the property name in the call:
    public String Name
    {
        get { return _p.Name; }
        set
        {
            _p.Name = value;
            NotifyPropertyChanged();
        }
    }

CallerMemberName requires a reference to System.Runtime.CompilerServices.