I can't see a good use for this, but nonetheless:

Since you treat tabInfo as a list, why not have it be an array, this way you don't need tabInfoKey and you can use push instead. Arrays are objects too.
Don't use console.log for production code
tab is a terrible name, go for either the Spartan o or object
info is an unfortunate name, perhaps value ?
tabInfo is also meh, perhaps objectMap ?
you should have a constructor for this!

Something like this incorporates my feedback:

function ObjectMap() {
  this.entries = [];
}

ObjectMap.prototype.get = function( object ) {
  for( var i = 0 , length = this.entries.length ; i < length ; i++ ){
    if( this.entries[i].object === object ){
      return this.entries[i].value;
    }
  }
}

ObjectMap.prototype.set = function( object, value ) {
  //If we can find it, update it
  for( var i = 0 , length = this.entries.length ; i < length ; i++ ){
    if( this.entries[i].object === object ){
      this.entries[i].value = value;
      return;
    }
  }
  //Otherwise, generate an entry
  this.entries.push( { object : object , value : value } );
}

ObjectMap.prototype.remove = function( object ) {
  for( var i = 0 , length = this.entries.length ; i < length ; i++ ){
    if( this.entries[i].object === object ){
      this.entries.splice( i , 1 );
      return;
    }
  }
}

You can then

o = new ObjectMap();
o.set( o , "123" );
o.get( o ); //Gives "123"
o.remove( o );
o.get( o ); //Gives nothing

Furthermore you should consider whether you want to allow function chaining, right now none of these functions return anything and it seems a shame.


Validating ISBN-10s, with or without dashes in C++11

When you're comparing against 8 different patterns, and then simply removing - for 7 of those validations, why not just remove - initially, and then validate against the only remaining pattern.
Another thing to note is, in the patterns, at the end; you have a character set: [\d|\X]. This actually will match one of:

a digit
literal |
literal X characters (you don't need \X though).

This should instead be:
\d{9}[\dX]

A general outline of how the code should work:

Remove all - from given string
Check if length of string is exactly \$ 10 \$
Validate against the pattern rewritten above
Check if last character is X
Validate individual digit sum and divisibility.


Assuming that your lists are sorted and this is something that comes out of problem description and the part where you need to find something in 99% of that kind of questions you want to use binary search. So basically all your code could be written like this:

from bisect import bisect_left

def binary_search(a, x):
    pos = bisect_left(a, x)
    return pos if pos != len(a) and a[pos] == x else -1

def two_sum(a, b, target):
    result = []
    for num in a:
        index = binary_search(b, target-num)
        if index != -1:
            result.append((num, b[index]))
    return result

Now if you want to save some memory, you might want to make two_sum a generator, which will make it look like this:

def two_sum(a, b, target):
    result = []
    for num in a:
        index = binary_search(b, target-num)
        if index != -1:
            yield num, b[index]

I cannot really call my answer a review to your code because I completely overwrote a solution for this. But as I mentioned in the beginning whenever a problem says something about sorted lists and searching on it, most likely you will use bsearch in your solution.


Is this code with global variables good practice?

Your doubt is correct, don't use global variables.

(Note: For this post, I mean variable in its true meaning, i.e. objects that may change.)

I can't say for sure which technique is the correct one without seeing your code, but normally you want to pass the variable as a parameter to whichever entity needs it:

void foo(Input input)
{
    input.doSomething();
}

int main()
{
    Input input;
    input.doSomething();

    foo(input);
}

Or, restrict it to a class as a member variable.

Update: Class examples

You can do it one or both of these ways:

class Person {
    std::string name_;
public:
    explicit Person(std::string const& name) : name_(name) {}
    void set_name(std::string const& name) { name_ = name; }
}

void foo()
{
    Person p("Bob Loblaw");

    p.set_name("Slartibartfast");
}

There are two key downsides to using global variables:

1. They can be changed everywhere.

You generally want to enlist the compiler's aid in finding bugs and errors for you. If you allow yourself to modify a variable from all over your code, it is very hard for your compiler and yourself to track down an error. Consider the following scenario:

Input input; // global

void foo()
{
    Input inputt;
    input = someThingWeird;
}

This code will compile. If you're really unlucky, it will even work for a while. If you don't have a global, the code won't compile and the bug will be easy to find.

2. They increase coupling (and reduce testability).

By reading from a global variable, your entity (i.e. function, class, whatever) depends on that global variable. If some day you want to use something else, you'll have to do a lot of refactoring. What's more important, if you change an aspect of the global variable, you will need to update all parts of the code that uses it. This is a great opportunity for suble bugs to infiltrate your code and make your life miserable. A typical example is that you modify one part of your code, and a completely different part will break.

Using globals also makes your code hard to unit test, because it depends on the global variable.


I haven't examined the actual functionality, but this is based on my comment about moving this.toString to a prototype method (which is, I feel, the main improvement) and then I've done a few micro optimisations (but nothing that is going to make any real noticeable difference). Other than that I performed a bit of personal styling, there was nothing particularly wrong with what you had.

Javascript

/*jslint maxerr: 50, indent: 4, browser: true, nomen: true */
/*global Float32Array */

(function () {
    "use strict";

    /* Circular buffer used to add values in blocks of constant size */

    function IndexOutOfBounds(maxIndex, requestedIndex, method) {
        this.maxIndex = maxIndex;
        this.requestedIndex = requestedIndex;
        this.method = method;
    }

    IndexOutOfBounds.prototype.toString = function () {
        return "Invalid index in method ['" + this.method + "']\nRequested index    : " + this.requestedIndex + "\nValid _buffer index : [0.." + this.maxIndex + "]";
    };

    function ImproperBlockLength(ringBlockLength, givenBlockLength) {
        this.ringBlockLength = ringBlockLength;
        this.givenBlockLength = givenBlockLength;
    }

    ImproperBlockLength.prototype.toString = function () {
        return "Block length mismatch.\nRequeste block length : " + this.givenBlockLength + "\nValid block length    : " + this.ringBlockLength;
    };

    function Ring(length, blockLength) {
        this.length = length;
        this._maxIndex = length - 1;
        this._start = 0;
        this._buffer = new Float32Array(length);

        /* blockLength should always be a factor of size.
         * An exception is thrown if it's not;
         */
        this._blockLength = 0;
        if (blockLength) {
            if (length % blockLength !== 0) {
                throw "Block length must be a factor of length.";
            }

            this._blockLength = blockLength;
        }
    }

    Ring.prototype.checkBounds = function (requested, callerName) {
        var maxIndex = this._maxIndex;

        if (requested < 0 || requested > maxIndex) {
            throw new IndexOutOfBounds(maxIndex, requested, callerName);
        }
    };

    Ring.prototype.relativeIndex = function (index) {
        return (this._start + index) % this.length;
    };

    /* Should not be used when there is a set _blockLength */
    Ring.prototype.push = function (element) {
        var start = this._start,
            newStart = start + 1;

        this._buffer[start] = element;
        this._start = 0;
        if (newStart <= this._maxIndex) {
            this._start = newStart;
        }
    };

    Ring.prototype.get = function (index) {
        this.checkBounds(index, 'get');

        return this._buffer[this.relativeIndex(index)];
    };

    Ring.prototype.set = function (index, value) {
        this.checkBounds(index, 'set');
        this._buffer[this.relativeIndex(index)] = value;

    };

    Ring.prototype.concat = function (arr) {
        var alen = arr.length,
            blen = this._blockLength,
            start;

        if (alen !== blen) {
            throw new ImproperBlockLength(blen, alen);
        }

        start = this._start;
        this._buffer.set(arr, start);
        this._start = (start + alen) % this.length;

    };

    Ring.prototype.map = function (callback) {
        var relativeIndex,
            length = this.length,
            i = 0;

        while (i < length) {
            relativeIndex = this.relativeIndex(i);
            this._buffer[relativeIndex] = callback(this._buffer[relativeIndex], i, length);
            i += 1;
        }
    };
}());

One other thing to consider is, because you will only be using newer browsers that support Float32Array then you could also define properties using Object.defineProperty

Update: Here is a refactoring using Object.defineProperty, I did it kind of quick so there are no guarantees that I did it correctly, it is more to give you a starter, hope it helps.

Javascript

/*jslint maxerr: 50, indent: 4, browser: true, nomen: true, bitwise: true */
/*global console, Float32Array */

(function () {
    "use strict";

    var Ring = (function () {
        /* Circular buffer used to add values in blocks of constant size */

        var minIndex = 0,
            maxIndex = 4294967294;

        function clamp(number, min, max) {
            return Math.min(Math.max(number, min), max);
        }

        function IndexOutOfBounds(maxIndex, requestedIndex, method) {
            Object.defineProperties(this, {
                "maxIndex": {
                    value: maxIndex
                },

                "requestedIndex": {
                    value: requestedIndex
                },

                "method": {
                    value: method
                }
            });
        }

        Object.defineProperty(IndexOutOfBounds.prototype, "toString", {
            get: function () {
                return "Invalid index in method ['" + this.method + "']\nRequested index    : " + this.requestedIndex + "\nValid _buffer index : [0.." + this.maxIndex + "]";
            }
        });

        function ImproperBlockLength(ringBlockLength, givenBlockLength) {
            Object.defineProperties(this, {
                "ringBlockLength": {
                    value: ringBlockLength
                },

                "givenBlockLength": {
                    value: givenBlockLength
                }
            });
        }

        Object.defineProperty(ImproperBlockLength.prototype, "toString", {
            get: function () {
                return "Block length mismatch.\nRequeste block length : " + this.givenBlockLength + "\nValid block length    : " + this.ringBlockLength;
            }
        });

        function Ring(length, blockLength) {
            length = clamp(length, minIndex, maxIndex + 1) >>> 0;

            /* blockLength should always be a factor of size.
             * An exception is thrown if it's not;
             */
            blockLength = clamp(blockLength, minIndex, maxIndex + 1) >>> 0;
            if (length % blockLength !== 0) {
                throw "Block length must be a factor of length.";
            }

            var privateStart = 0,
                privateBuffer = new Float32Array(length);

            Object.defineProperties(this, {
                "length": {
                    get: function () {
                        return length;
                    },

                    set: function (newLength) {
                        length = clamp(newLength, minIndex, maxIndex + 1) >>> 0;
                    }
                },

                "_start": {
                    get: function () {
                        return privateStart;
                    },

                    set: function (start) {
                        privateStart = clamp(start, minIndex, maxIndex) >>> 0;
                    }
                },

                "_buffer": {
                    get: function () {
                        return privateBuffer;
                    },

                    set: function (buffer) {
                        privateBuffer = buffer;
                    }
                },

                "_blockLength": {
                    value: blockLength
                }
            });
        }

        Object.defineProperties(Ring.prototype, {
            "_maxIndex": {
                value: function () {
                    return clamp(this.length - 1, minIndex, maxIndex) >>> 0;
                }
            },

            "checkBounds": {
                value: function (requested, callerName) {
                    var maxIndex = this._maxIndex;

                    if (requested < 0 || requested > maxIndex) {
                        throw new IndexOutOfBounds(maxIndex, requested, callerName);
                    }

                    return maxIndex;
                }
            },

            "relativeIndex": {
                value: function (index) {
                    return (this._start + index) % this.length;
                }
            },

            /* Should not be used when there is a set _blockLength */
            "push": {
                value: function (element) {
                    var start = this._start,
                        newStart = start + 1;

                    this.buffer = element;
                    if (newStart > this._maxIndex) {
                        this._start = 0;
                    } else {
                        this._start = newStart;
                    }
                }
            },

            "get": {
                value: function (index) {
                    this.checkBounds(index, 'get');

                    return this._buffer[this.relativeIndex(index)];
                }
            },

            "set": {
                value: function (index, value) {
                    this.checkBounds(index, 'set');
                    this._buffer[this.relativeIndex(index)] = value;
                }
            },

            "concat": {
                value: function (arr) {
                    var alen = arr.length,
                        blen = this._blockLength,
                        start;

                    if (alen !== blen) {
                        throw new ImproperBlockLength(blen, alen);
                    }

                    start = this._start;
                    this._buffer.set(arr, start);
                    this._start = (start + alen) % this.length;
                }
            },

            "map": {
                value: function (callback) {
                    var relativeIndex,
                        length = this.length,
                        i = 0;

                    while (i < length) {
                        relativeIndex = this.relativeIndex(i);
                        this._buffer[relativeIndex] = callback(this._buffer[relativeIndex], i, length);
                        i += 1;
                    }
                }
            }
        });

        return Ring;
    }());

    var ring = new Ring(10, 1);

    console.log({
        0: ring,
        1: ring.length
    });
}());

On jsfiddle


Is there anything incorrect about this layout, semantically or otherwise?

In HTML5 h1 elements can be treated as relative to their semantic container, so it is not bad practice to have an h1 as the main page header text and further h1's for each section, aside, article, etc.

As you've mentioned you would naturally style this with something like section h1 { ... }.  I'd recommend making this more general and not depending on .panel-ws because you may want to hang it off main and aside instead to allow for different header text styling in each?

I found a similar question on stackoverflow which you might want to check out too...

https://stackoverflow.com/questions/7405282/how-to-properly-use-h1-in-html5

For the webpage name and slogan, you could group h1 and h2 elements inside a parent hgroup to ensure that html readers don't parse the slogan as an implicit second level of content.


Do not use using namespace std.
In the constructor and push(), it looks like you're calling new on a function.  It should be node.
Prefer nullptr to NULL and 0 for the node pointers if you're using C++11.  Otherwise, you should choose either NULL or 0 for node pointers and keep it consistent.
You don't need this-> everywhere as the code already has the current object in scope.
It's needless to call pop() in the destructor.  For one thing, pop() returns a value.  You should just be using delete.

Instead, have head point to the first element, loop through the stack (stopping when NULL is hit) and call delete on each node.  With this, you won't need to delete head at the end.
pop() and getTopElement() might be best as void.  Here, a 0 is returned if the list is empty.  Sure, no errors happening there.  But then the calling code will take it as an element 0, never knowing whether or not the stack is empty.  If you make them void, you can simply return if the stack is empty.  As for retrieving an element, that's why you have getTopElement().  Once you get the value with getTopElement(), call pop() after that.

Regarding checking for an empty stack, you could make a public empty() function for calling code.  The two functions above should still check for an empty stack, but containers like this usually utilizes such a function.  This could go in the header:

bool empty() const { return num_elements == 0; }

You could make your class more useful by using templates.  This will allow you to populate the stack with any type instead of just ints.


Refactor IQueryable and IEnumerable that share the same condition

You can use IQueryable<T> everywhere, because you can convert to it from IEnumerable<T> by using AsQueryable():

public static IQueryable<PAYTRACK_PARTNER> WhereInPayer(
    this IQueryable<PAYTRACK_PARTNER> query, int payerId)
{
    var result = query.Where(q => q.payer_id == payerId);
    return result;
}

public static IEnumerable<PAYTRACK_PARTNER> WhereInPayer(
     this IEnumerable<PAYTRACK_PARTNER> query, int payerId)
{
     return query.AsQueryable().WhereInPayer(payerId);
}

Also, names in ALL_CAPS are not commonly used in C#, you should adopt c# naming conventions.


How to clean the indexes, and ideally not create an additional array

Here is a review of the solution.

^ is xor in Python. It is not for computation of exponentials.

When running code outside a method / class, it is a good practice to put the code inside a main guard. See here for more explanation.
 if __name__ == "__main__":
    ...

When you are providing quick answers on a forum, the guard might not always be necessary. However, if you are writing reusable code for yourself, it is better to adopt the practice.

By convention, _ is used to represent a don't-care variable, which won't be used after its value is assigned, e.g. v = [[] for _ in range(4)]. It is undesirable to refer to it in an expression like answer[_].

The output is a pure text file. It is unnecessary to open it in binary mode (b). The original question does not suggest an append mode (a) either.

The q-1 index would no longer work if q is changed to a different group of values. Therefore, it is better to use enumerate in this case:
for i, q in enumerate(RANGE_Q):
   ...
   export[i, 0] = q
   ...

A better approach is to use zip:
for q, output_row in zip(RANGE_Q, output_arr):
    ...
    output_row[0] = q
    ...

The assignments to the output numpy array can be improved, as shown in my solution below.

Here is my solution.
import numpy as np

if __name__ == "__main__":
    # Define constants
    RANGE_Q = range(1, 11)               # Range of q values
    POLY_DEG = 4                         # Degree of polynomial
    OUTPUT_PATH = "/tmp/latest_foo.csv"  # Output csv path

    # Compute roots
    roots_arr = np.array([np.roots([1, 3*q*q, 4*q, np.sqrt(q), q]) for q in RANGE_Q])

    # Construct output array and assign values
    output_arr = np.empty(shape=(len(RANGE_Q), POLY_DEG * 2 + 1))
    output_arr[:, 0] = RANGE_Q
    output_arr[:, 1::2] = roots_arr.real
    output_arr[:, 2::2] = roots_arr.imag

    # Save results to output file
    np.savetxt(OUTPUT_PATH, output_arr, fmt="%.4g", delimiter=',')


Using the wildcard when importing packages

First, let's acknowledge that this is a subjective question.  However, in my opinion, it is constructive enough to be on topic for this site.

I would treat the standard Java library differently than your own packages or third-party packages.  Everyone recognizes classes from the standard Java library, such as BufferedReader, PrintWriter, and IOException.  There is therefore no value in importing those individually; it just clutters the code.  Everyone who has worked with Java will know that those classes belong to the java.io package, unambiguously.  Anyone who writes classes whose names conflict with those well known classes will be soundly beaten up, so name conflicts with java. classes just don't happen in practice.

With third-party libraries, it makes sense to import more specifically.  Programmers encountering those classes could use some help to figure out which packages they belong to.  Name clashes could happen.  That said, star imports for third-party libraries would be a judgement call.  I would suggest importing individual classes up to some number of classes (around 4) per package; beyond that, a star import might be sensible.  I would try to avoid star-importing more than one such package, though, to mitigate against the documentation-searching and name clash concerns.  (If you feel the urge to star-import multiple packages, your class is probably doing too much anyway and should be split up.)

With code that you have written yourself for the same or a closely related project, go ahead and star-import related packages, judiciously.  If you're working with the source code, you'll be familiar with the related code in neighbouring packages anyway.  If it fails to compile because of a name clash, you can fix it yourself.


Method for adding error messages to a dictionary given a key

Consider narrowing accepted types

This might not be possible based on the context of your code, but if it is: arguments sharing one of many different types hinders and complicates testability and maintainability. There are many different solutions to this that will help this situation; one is accepting variadic arguments - i.e.

def add_error(error_dict, key, *errs):

This is still easily invocable without needing to wrap a single error in a list.

Use x not in instead of not x in

i.e.

if key not in error_dict

Lose your loop

and also lose your empty-list assignment, instead doing

error_dict.setdefault(key, []).extend(err)

If you use the variadic suggestion above, your entire function becomes that one line.

Immutable or not?

Currently you do two things - alter a dictionary and return it - when you should only pick one. Either make a copy of the dict and return an altered version, or modify the dict and don't return anything.


LINQ to Entities query of tests for my classes, with many subqueries

I bet the database does not have the indexes to process this combination of conditions, especially with a contains on a name column. You will get table scans. Break off the || (o.Author.SchoolId == CurrentUser.SchoolId... part to return a new list of AuthorIds and you can add the CurrentUser.Id so the db.Tests where condition is just using the primary key.

The idea here is to preprocess your contains to be lists of ints to make the indexes happy.


How can I avoid repeated code using lambdas?

You should be able to wrap up your loops in a single method that takes a Func<T> and then do something like this:

public static T1 Do<T1,T2,T3>(Type retryOnExceptionType, Func<T2,T3,T1> action, T2 param1,
                              T3 param2, TimeSpan retryInterval, int retryCount)
{
    var del = new Func<T1>(() => action(param1, param2));
    return DoLoops<T1>(del, retryOnExceptionType, retryInterval, retryCount);
}

public static T Do<T>(Type retryOnExceptionType, Func<T> action,TimeSpan retryInterval,
                      int retryCount)
{
    return DoLoops<T>(action, retryOnExceptionType, retryInterval, retryCount);
}

private static T DoLoops<T>(Func<T> func, Type retryOnExceptionType,
                            TimeSpan retryInterval, int retryCount)
{
    if (retryInterval == default(TimeSpan))
        retryInterval = TimeSpan.FromSeconds(1);

    var exceptions = new List<Exception>();

    for (int retry = 0; retry < retryCount; retry++)
    {
        try
        {
            return func();
        }
        catch (Exception ex)
        {
            if (!retryOnExceptionType.IsInstanceOfType(ex))
                throw;

            exceptions.Add(ex);
            Thread.Sleep(retryInterval);
        }
    }

    throw new AggregateException(exceptions);
}

The key is in wrapping up your Func<T2, T3, T1> call in a separate Func<T1>, which allows you to pass a parameterless delegate to DoLoops regardless of how many type parameters the original delegate has, since that's the only difference between the original methods.

Even simpler, you can do away with DoLoops and just keep the for loop in the public static T Do<T> overload and Do<T1, T2, T3> can just pass the parameterless delegate it creates into that method:

public static T1 Do<T1,T2,T3>(Type retryOnExceptionType, Func<T2,T3,T1> action, T2 param1,
                              T3 param2, TimeSpan retryInterval, int retryCount)
{
    return Do<T1>(retryOnExceptionType, () => action(param1, param2),
                  retryInterval, retryCount);
}

public static T Do<T>(Type retryOnExceptionType, Func<T> action, TimeSpan retryInterval,
                      int retryCount)
{
    if (retryInterval == default(TimeSpan))
        retryInterval = TimeSpan.FromSeconds(1);

    var exceptions = new List<Exception>();

    for (int retry = 0; retry < retryCount; retry++)
    {
        try
        {
            return action();
        }
        catch (Exception ex)
        {
            if (!retryOnExceptionType.IsInstanceOfType(ex))
                throw;

            exceptions.Add(ex);
            Thread.Sleep(retryInterval);
        }
    }

    throw new AggregateException(exceptions);
}


Feedback on generator functions and class composition in Python 3

Code Organization
Your code organization seems non-existent.  You have:

imports
code
function definition
code
class definitions
main-guarded code

Code should be organized in a more consistent structure, like:

imports
class definitions
function definitions
main-guarded code

The point of using a main-guard is to prevent code from running if the file is imported into another file.  Here, you have two separate code blocks which are unconditionally executed.  This limits code reuse.  For example, imagine someone could use CWLogs for their own task, but doesn't need ESWriter.  They try from your_file import CWLogs, and find their program exits after displaying a cryptic error message about a how to execute a program they are not actually running, due to a missing environment variable they don't actually use.
sys.exit()
Don't call this.  It terminates the Python interpreter.
Any debugging you may have hoped to do when the program finishes will be impossible, because the entire Python environment imploded.  It is impossible to safely import your file using try: import your_file except ImportError: because Python execution terminates during the import, meaning the program trying to import it unconditionally terminated.  If you try to use unittest to test your program, or Sphinx to generate documentation for your program, or any number of other common things, you can't, because your file has unconditionally terminated the Python interpreter.
Don't call it.
Instead:
if __name__ == '__main__':
    if {'GROUP_NAME', 'ES_HOST'} <= os.environ.keys():
        main()
    else:
        usage()

No need for usage() to call sys.exit().  After usage() is called, and returns normally, execution reaches the end of the file, which if this is the main program file, will naturally end the program.  Of course, if this is not the main program file, the main guard would have not run either method, the execution would reach the end of the file completing the importation of the file as a module in another program.
Stop Writing Classes
See "Stop Writing Classes" for a PyCon talk by Jack Diederich.
A class with no instance data members probably shouldn't be a class.  Neither ESWriter nor CWLogs have any instance data members.
A class with no constructor and only one public method to call shouldn't be a class.  Neither ESWriter nor CWLogs have a constructor.  Both have a single public method, called immediately after constructing a class instance, so the instance is not even saved.
These should not be classes.
Private name mangling
Private name mangling is used to prevent private member name collisions when a class is derived from another class, typically when the base class and the derive class are under control of different entities.  For instance, if you derive your own class from a tkinter.Frame, and you create a _validate method in your class, you could cause the base class to stop functioning properly if it had its own _validate method that was just abruptly changed on it.  So, the base class would use __validate, the leading double underscore would trigger name "mangling", and replace the name with _Frame__validate, so collisions are less likely.
There appears to be no reason for your usage of a double underscore prefix in your method names; a single underscore would be more idiomatic.
Type Hints
Your type hints are wrong.
For instance, the following is clearly returning a str, not None:
    def __transform(self, event: dict) -> None:
        ...
        return "\n".join( ... )

Since __transformer is yielding the results of __transform, it is not returning None either, but should be declared as:
from typing import Generator

...

    def __transformer(self, events: object) -> Generator[str, None, None]:
        ...

Or simply:
from typing import Iterator

...

    def __transformer(self, events: object) -> Iterator[str]:
        ...

And events: object is virtually meaningless, since everything in Python is an object.  Either use a proper type for it, or don't bother with a type hint at all.
Generator Expressions
As yedpodtrziko noted,
def __generate_events(self) -> None:
    stream_names = [stream["logStreamName"] for stream in self.__generate_streams()]

    for stream_name in stream_names:
        ...

builds up a temporary list, only to immediately iterate through it.  They made a fairly large change in the code to avoid the temporary list.  There is a much smaller change that can be made:
def __generate_events(self) -> None:
    stream_names = (stream["logStreamName"] for stream in self.__generate_streams())

    for stream_name in stream_names:
        ...

Because it may be hard to see the change, I'll amplify it: the [...] got changed to (...).  This means instead of stream_names being realized as an in-memory list, it becomes a generator expression, which will produce the values one at a time when asked.
It doesn't make much of a difference here, but if stream_names was being passed to a function, instead of being used locally, the change proposed by yedpodtrziko would require reworking code much further away to accept the stream_obj and extracting the stream names inside that function.


Review

findMinimum means to me that you find the minimum value in an array of items. Since your function returns the index instead, call it indexOfMinimum.
Prefer the use of const over let if you only assign a variable once: let minIndex = findMinimum(toSort); -> const minIndex = findMinimum(toSort);.
Use arrow notation to write more compact functions: function (item, index) -> (item, index) =>.
Your documentation seems like wasted space. If you document a public function (which is a good thing), put in some effort to write a clear description of the function, not just the name of the method copied.
Use whitespace to write more idiomatic javascript:

let minIndex=0; ->  let minIndex = 0;
if(item < arr[minIndex]) -> if (item < arr[minIndex])

Rewritten:

function selectionSort(toSort, sorted=[]) {
    if (!toSort.length) {
        return sorted;
    }
    const minIndex = indexOfMinimum(toSort);
    sorted.push(...toSort.splice(minIndex, 1))
    return selectionSort(toSort, sorted);
}

function indexOfMinimum(arr) {
    let minIndex = 0;
    arr.forEach((item, index) => {
        if (item < arr[minIndex]) {
            minIndex = index;
        }
    })
    return minIndex;
}


NumPy works best if you represent all your data as uniform arrays. Then you can vectorize your operations: that is, arrange for each operation to run uniformly on all the elements of an array. This allows NumPy to delegate the operations to fast branchless native code.

Assuming these considerations applies to your case, then what you need here is to convert your input to NumPy arrays:

>>> start = np.array((0, 0, 0))
>>> end = np.array((10, 10, 10))
>>> r = 3

and then construct an array of points along the line:

>>> start + np.linspace(0, 1, r)[..., np.newaxis] * (end - start)
array([[ 0.,  0.,  0.],
       [ 5.,  5.,  5.],
       [10., 10., 10.]])


"Remember me" functionality for a website

Performance

As your code is executed on every request, it's best to optimize it. First of all, you perform two queries when one would be enough. You could join your getSalt and getCookieID method to a getSaltAndCookie method which returns both values in an array.

It's not all that clear, but how I understand it, you do not use a session for login check at all. It would be better to add code that handles the normal session checking, and only use the cookie based authentication if no session is set, and then set a session (so All the times but not the first would become Only the first time, and you would not have any queries on subsequent requests).

Security

If UserID is user controller, you have a second order SQL injection in storeCookie. Either way, I would use prepared statements for all variable content just to make sure.

Even if there isn't an injection at the time, I could imagine that you will extend your code in the future. For example, currently, there can only ever be one login cookie, so I'm assuming you only allow one user. But this might change in the future, in which case $cookie_name will not be the static string GETIN, but some kind of identifier send via cookie. These changes would not be made in getSalt and getCookieID, so it would be very easy to forget to secure the queries.

The documentation of uniqid says: Warning: This function does not create random nor unpredictable strings. This function must not be used for security purposes, this is because it's based on the time it is created. It's not so bad because your salt is actually random, but still. If you are afraid of collisions for the token, you could generate a truly random string and prefix it with the username.

Misc

If you store this: 7 * 24 * 60 * 60 in a named variable, it would be immediately obvious that it is 7 days.
use more spaces, eg around . to increase readability.
all your SQL keywords should be all uppercase to increase readability (eg values -> VALUES, and all the keywords in the insert queries).


Updating only certain fields on a database row

I think it is.

What you are asking for is known as UPSERT - a portmanteau of UPDATE and INSERT. Some databases support UPSERT intrinsically, but some don't. A quick search for "MySQL UPSERT" suggests that MySQL does not support an UPSERT keyword or the concept directly. However, as you discovered, the ON DUPLICATE KEY construct will simulate it.

That seems the best way to do it in MySQL. (In SQL Server you would probably use MERGE.)


I'm not sure whether it's correct:

If show_hash uses cdecl calling conventions you should preserve registers like %bl, and read the input parameter values from the stack into esi and edi.
(see section "3.2.3 Parameter Passing" of the Application Binary Interface: parameters are conveniently passed in the rdi and rsi registers)
I don't understand the syntax of mov 1b(%rax),%al: is it reading from the lookup array defined at label 1:? On re-reading, I think it is; however that will only work if the most-significant bytes of rax and rdx are all zero; perhaps you should initialize them as you did using xor %eax,%eax
(apparently xor %eax,%eax will clear the whole of %rax)
You're using stosw which writes two bytes (two ASCII characters) a time; but %ah contains  a value from %bl, and %bl wasn't previously initialized? I think that statement should have been mov %dl,%ah not mov %bl,%ah; or perhaps you could have done mov 1b(%rdx),%ah directly.
The function ends with mov %cl,(%rdi) to null-terminate the string; that is clever but could use a comment (it took me a bit to figure out). Most of the assembly questions either have good comments, or answer which say that they should have good comments.


Starting an activity after 1000ms from a splash screen with Runnable and Handler().postDelayed

I don't like name startTheTransitionAfterTheSplashScreen. Too long, you are already in SplashScreen. Maybe startTransition or startTransitionafter1second.

Using handler is fine, but what if user manages to change orientation during that 1 second? Activity gets destroyed and recreated. Now you have 2 active handlers and I expect ActivityJustAfterSplashScreen will be called 2 times.

I suggest keeping reference to handler so that you can cancel in onDestroy - handler.removeCallbacksAndMessages(null).


Readability in creation of a long output string

How about something like this:

def read_config(bus, sensor):
    tpl = '''Status of DS1621 at address {sensor}:
    \tConversion is {done}
    \t{have_th} measured {th} degrees Celsius or more
    \t{have_tl} measured below {tl} degrees Celsius
    \tNon-volatile memory is {busy}'''

    print tpl.format(sensor=sensor,
                     done='done' if Conf & DONE else 'in process',
                     have_th='HAVE' if Conf & TH_BIT else 'have NOT',
                     th=TH,
                     have_tl='HAVE' if Conf & TL_BIT else 'have NOT',
                     tl=TL,
                     busy='BUSY' if Conf & NVB else 'not busy',
                     )

This is PEP8 compliant, and I think more readable.

Also, I think there's nothing wrong with this kind of use:

'something' if condition else 'otherthing'


Styling navigationController per viewController

extension UIViewController   create  a navigation bar Method call anywhere  from ViewController  in your project.navigation bar will appear   and  add more parameter  color or other relevant change you want to achieved .

for example

    import UIKit

    extension UIViewController {

        func setupNavigationBar(title: String) {
            // back button without title
            //self.navigationController?.navigationBar.topItem?.title = ""

            //back button color
            //self.navigationController?.navigationBar.tintColor = UIColor.white

            //set titile
             self.navigationItem.title =  title

            //set text color & font size
            //self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.init(red: 251/255, green: 251/255, blue: 251/255, alpha: 1) , NSFontAttributeName:UIFont.systemFont(ofSize: 19)]

            //set background color without gradian effect
            //self.navigationController?.navigationBar.barTintColor = UIColor.init(red: 134/255, green: 145/255, blue: 152/255, alpha: 1)

            //show right button
            let rightButton = UIBarButtonItem(image: #imageLiteral(resourceName: "Menu"), style: .plain, target: self, action: #selector(menu))

            //right Bar Button Item tint color
            //self.navigationItem.rightBarButtonItem?.tintColor = UIColor.init(red: 219/255, green: 219/255, blue: 219/255, alpha: 1)

            //show the Menu button item
            self.navigationItem.rightBarButtonItem = rightButton

            //show bar button item tint color
            //self.navigationItem.rightBarButtonItem?.tintColor = UIColor.init(red: 219/255, green: 219/255, blue: 219/255, alpha: 1)

        }

        func menu(){
            print("showSlideOutMane fire ")
        }

    }


Slicing and dicing images for Google Play

Use target- and pattern-specific variables:

$(ldpi_dir)/btn_%.png : GEOMETRY := 24x
$(mdpi_dir)/btn_%.png : GEOMETRY := 36x
$(hdpi_dir)/btn_%.png : GEOMETRY := 72x

and similar definitions for launcher_%.png

Then you can combine all the individual recopies into a single one:

$(ldpi_dir)/%.png $(mdpi_dir)/%.png $(hdpi_dir)/%.png) :
    convert -geometry $(GEOMETRY) $< $@
    identify $@


However, I am not sure if this is good practice, or if it should be avoided.

While I don't think it is bad practice, it could be simplified. One technique to simplify it is using event delegation.

For example, the array of tab options could be added to a JavaScript array:

$tab_options = array('home', 'profile', 'news', 'api');
echo 'var tab_options = '.json_encode($tab_options).';';

Then add a click handler to the document and check if the id attribute corresponds to one of those tab options.

$(document).click(function(clickEvent) {
    var targetId = clickEvent.target.id;
    if (tab_options.indexOf(targetId) > -1) {

In that code Array.indexOf() is used but one could also use Array.contains() though it isn't supported by as many (mostly older) browsers (e.g. IE).

Then to get the equivalent of ucwords(), a solution like from this answer can be used:

var properCaseOption = targetId.replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
window.top.document.title = properCaseOption;

With this approach, the JavaScript code is not duplicated once for each tab option. Perhaps it may not be a big issue because that code could easily be updated with the PHP code, it would yield a larger HTML/JS page size.

See a demonstration of this in this playground example but note that the AJAX requests won't yield the pages as expected so the code to update the containers has been commented out. However I made a phpfiddle that has the response from the AJAX request utilized.


Simple shared pointer implementation in a single threaded environment (revised)

Unless this is just for learning, always remember that adding yet another smart-pointer will seriously hinder interaction with anyone expecting a different one.

The Design:

The maker-function is mandatory:

Cannot use a different allocator.
Cannot generally be used to allow sharing across DLL boundaries, as DLLs (in contrast to SOs) don't do symbol unification.
Cannot be used with already-allocated resources, or those needing different deallocation.

Your shared-pointers must always point to the full object. Interior pointers are not allowed, nor are base-pointers.
You don't allow for weak pointers at all.
As an aside, the overhead of using atomic reference-counts is small enough that the standard library eschews the complication of adding single-threaded shared-pointers. Consider whether that's really the part you should save on.

The Implementation:

Using in-class-initializers allows you to simplify the ctors.
You could use aggregate-initialization with Pair, no need for a custom ctor.
Explicitly testing for self-assignment is a bad idea, as it pessimises the common case. Anyway, it's completely useless in a ctor!
You should know that -> binds stronger than anything but scope-resolution ::. If you need to, there are many places to look up the operator precedence rules.
Your move-assignment-operator leaks the assignee's state. Fix it by just doing an unconditional swap instead.


I'd say you're on the right track with you idea to extract a method.

While I can't fully replicate your code and its context, I think something like this should work:

task countries: setup do |task_name|
  rows = rows_from_file("system/#{task_name.to_s}", 2)
  process_rows(task_name, rows) do |row|
    { alpha2: row[0], name: row[1] }
  end
end

# ...

def import_rows(task_name, rows, &block)
  klass = task_name.to_s.classify
  bar = RakeProgressbar.new(rows.length)
  info "» Importing #{task_name.to_s.humanize}"
  rows.each do |row|
    attrs = block.call(row)
    klass.new(attrs).save!
    bar.inc
  end
  bar.finished
end

But it's going pretty far in its assumptions - it's basing a lot off of the task name alone.

A somewhat less fragile approach might be this where the correct class is explicitly passed to the helper method and the file name isn't guessed from the task name

task countries: setup do
  rows = rows_from_file("system/countries", 2)
  process_rows(Country, rows) do |row|
    { alpha2: row[0], name: row[1] }
  end
end

# ...

def import_rows(klass, rows, &block)
  bar = RakeProgressbar.new(rows.length)
  info "» Importing #{klass.to_s.pluralize.humanize}"
  rows.each do |row|
    attrs = block.call(row)
    klass.new(attrs).save!
    bar.inc
  end
  bar.finished
end


Singly linked list implementation in python 3

You are missing several important things for this code:

Type Annotations

Python 3.7 supports type annotations. Especially for a container class like this, you should fully use them.

Initializer parameters

Python containers generally all provide builder methods or class initializer functions that take other containers and use their contents. Consider:

dict(iterable,**kwarg)
list(iterable)
set(iterable)
str(object=b'', encoding='utf-8', errors='strict')
tuple(iterable)

If you're writing a Python container, you need to conform to expectations. I expect to be able to initialize the container when I create it.

Protocols & Magic methods

Python has a well-established set of protocols for implementing containers. You just have to decide what kind of container you're writing.

I would suggest that a singly-linked list is an Iterable, a Sequence, a MutableSequence and possibly a Set type.


Use UriBuilder and set Port to -1

Uri oldUri = new Uri("http://myhost:443/Home/Index");
UriBuilder builder = new UriBuilder(oldUri);
builder.Port = -1;
Uri newUri = builder.Uri;

In case you want to remove the port part only when it is default, e.g. 80 for http and 443 for https, use snippet below (credit goes to Chris for the idea)

static Uri RemovePortIfDefault(Uri uri) {
    if (uri.IsDefaultPort && uri.Port != -1) {
        UriBuilder builder = new UriBuilder(uri);
        builder.Port = -1;
        return builder.Uri;
    }
    else return uri;
}

  If the Port property is set to a value of -1, this indicates that the default port value for the protocol scheme will be used to connect to the host.

See: UriBuilder.Port Property


Rotating color table object (for easy and consistent labeling)

Minor nitpicks:

None of you keywords are reserved words (especially if it starts with an underscore!) so encasing them in single-quotes is superfluous.

ColorTable.tableSize is an example of the smurf-naming convention (see item 21). Drop the second instance of table to become ColorTable.size

For setIndex you return two different datatypes: index on success, and false for failure. Since index is an arguements known to external code, what purpose does this serve? For consistency, you should return true/false for pass/fail if you have to. If you have to, how about a single point-of-return? You'd have to introduce a variable, and two more LOCs, but... single point-of-return!

But why not throw an exception? The existing mixed-type return suggests that calling code doesn't use the return value in any meaningful way.


Let's look at your solution function by function. First, start/0:

start() ->
    {ok, ListenSocket} = gen_tcp:listen(8211,[binary,{packet,4},{active, once}]),
    spawn(fun() -> accepter(ListenSocket) end),
    sleep().

First, port 8211 is hard-coded. You might instead want to export both a start/0 and a start/1, the latter taking a port number argument, with start/0 calling start/1 with 8211 as the default. You don't need {packet,4} unless your Erlang client is also using that option, or your non-Erlang client precedes each packet with a 4-byte integer in network order that indicates the packet length. You probably also want to use the {reuseaddr,true} option so that you can stop the application and quickly start it again on the same port. With all these changes, we wind up with this:

start() ->
    start(8211).
start(Port) ->
    {ok, ListenSocket} = gen_tcp:listen(Port, [binary,{active,once},{reuseaddr,true}]),
    spawn(fun() -> acceptor(ListenSocket) end),
    sleep().

(Note that technically you don't need the sleep/0 call, but I'm sure you put it there to make the program easier to work with interactively from an Erlang shell, so I'm leaving it.)

Next, we have sleep/0:

sleep() ->
    receive
        cancel -> void
    end.

I would return ok here, since that's extremely common in Erlang. Using the atom void is not.

Next, we have acceptor/1:

acceptor(ListenSocket) ->
    {ok, Socket} = gen_tcp:accept(ListenSocket),
    spawn(fun() -> acceptor(ListenSocket) end),
    Proc = spawn(fun() -> worker(Socket) end),
    gen_tcp:controlling_process(Socket, Proc).

The big problem here is the spawning of the worker process, and then handing control of the accepted socket over to it. There are two problems with this:

The accepted socket inherits {active,once} from the listen socket. But what happens if a message arrives after the worker is spawned but before control of the socket is given to it? The message is queued to the controlling process, which is the acceptor process, not the new worker process. The worker process misses that message, and since the acceptor never checks it, the message just gets lost.
Once the acceptor accepts a connection, it spawns a new acceptor. This is good. But it then spawns a worker, gives it the control of the socket, and then dies. This is pointless. Since the acceptor spawns a new acceptor, it can just continue and call worker/1 itself, and that way it can avoid the problem of changing the socket's controlling process, which means it won't miss any messages.

We can fix these problems by revising acceptor/1 like this:

acceptor(ListenSocket) ->
    {ok, Socket} = gen_tcp:accept(ListenSocket),
    spawn(fun() -> acceptor(ListenSocket) end),
    worker(Socket).

And finally, we have the original worker/1 function:

worker(Socket) ->
    receive
        {tcp, Socket, Data} ->
            io:format("Received ~p", [Data]),
            inet:setopts(Socket, [{active,once}]),
            worker(Socket);
        {tcp_closed, Socket} ->
            io:format("Socket ~p closed", [Socket])
    end.

This function looks just right, no changes needed.


Simple function that execute an instruction every X time until Y condition is accomplished

Usually it's a bad idea to put to sleep whole thread. I'd recommend use Java Timer or kotlin's wrapper for it.

Here is an example:

fixedRateTimer("default", false, 0L, 1000){
    println("Hello!")
    if (theEndIsNear) cancel()
}


Building tree structure based on flat objects

You could use the AddRange combined with the Except method inside of Build:

public static List<ArchiveTreeEntry> Build(List<ArchiveDefinition> entries)
{
    List<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

    if (entries != null && entries.Count > 0)
    {
        List<ArchiveDefinition> rootEntries = GetRootEntries(entries);

        entries = rootArchiveTreeEntried.AddRange(rootEntries.Select(definition=> new ArchiveTreeEntry(definition)).Except(entries);

        foreach (ArchiveTreeEntry parent in rootArchiveTreeEntries)
        {
            FillChildren(parent, entries);
        }
    }
    return rootArchiveTreeEntries;
}

You have made the public method static, which in this case is probably fine but it does make it harder to unit test dependencies. I envisage the class being consumed, like this:

in app

var builder = new ArchiveBuilder();
builder.Build(entities);

That said, the private methods are fine as static methods because the are an implementation detail.
The private methods can return/accept IEnumerable<> instead of List<>
From there, you could then re-write the method above to be:

public static List<ArchiveTreeEntry> Build(List<ArchiveDefinition> entries)
{
    List<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

    if (entries != null && entries.Count > 0)
    {
        entries = rootArchiveTreeEntried.AddRange(GetRootEntries(entries).Select(entry => new ArchiveTreeEntry(definition)).Except(entries);

        foreach (ArchiveTreeEntry parent in rootArchiveTreeEntries)
        {
            FillChildren(parent, entries);
        }
    }
    return rootArchiveTreeEntries;
}

So here is the completely re-written class:

public class ArchiveBuilder
{
    public IEnumerable<ArchiveTreeEntry> Build(IEnumerable<ArchiveDefinition> entries)
    {
        IEnumerable<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

        if (entries != null && entries.Count > 0)
        {
            entries = rootArchiveTreeEntried.AddRange(GetRootEntries(entries).Select(entry => new ArchiveTreeEntry(definition)).Except(entries);

            foreach (ArchiveTreeEntry parent in rootArchiveTreeEntries)
            {
                FillChildren(parent, entries);
            }
        }
        return rootArchiveTreeEntries;
    }

    private static void FillChildren(ArchiveTreeEntry parent,
                                 IEnumerable<ArchiveDefinition> entries)
    {
        if (entries.Count > 0)
        {
            IEnumerable<ArchiveDefinition> children = GetChildren(entries, parent.Id);

            if (children.Count > 0)
            {
                RemoveChildren(entries, parent.Id);

                foreach (ArchiveDefinition child in children)
                {
                    ArchiveTreeEntry treeEntryChild = new ArchiveTreeEntry(child);
                    parent.AddChild(treeEntryChild);
                    FillChildren(treeEntryChild, entries);
                }
            }
        }
    }

    private static IEnumerable<ArchiveDefinition> GetRootEntries(IEnumerable<ArchiveDefinition> entries)
    {
        return entries.FindAll(e => e.TypeOfArchive == ArchiveType.Archive);
    }

    private static IEnumerable<ArchiveDefinition> GetChildren(IEnumerable<ArchiveDefinition> entries, string parentID)
    {
        return entries.FindAll(e => e.ParentId == parentID);
    }

    private static void RemoveChildren(IEnumerable<ArchiveDefinition> entries, string parentID)
    {
        entries.RemoveAll(e => e.ParentId == parentID);
    }
}

NB: I haven't compiled the class or tested it, so it might not work out the box.


You are repeatedly extracting the smallest remaining numbers.

A data structure that is optimized for such operations is a priority queue, which is typically implemented using a heap.  A heap could be constructed in O(N log N) time, after which you would do N delete-min operations, each of which takes O(log N) time.  The total time to solve this challenge would be O(N log N).

Alternatively, you can sort the numbers in descending order (which takes O(N log N)), then repeatedly pop the smallest numbers off the end of the list (N times O(1)).

So, using a heapq would reduce the running time to O(N log N), and a simple sort would be a more efficient O(N log N).

In fact, after you perform the sort, you will see that it's just a simple counting exercise:

def cuts(sticks):
    sticks = list(reversed(sorted(sticks)))
    i = len(sticks)
    while i:
        # Avoid printing results in your algorithm; yield is more elegant.
        yield i
        shortest = sticks[i - 1]
        while i and sticks[i - 1] == shortest:
            i -= 1

raw_input()    # Discard first line, containing N
for result in cuts(int(s) for s in raw_input().split()):
    print(result)

Here's an implementation of the same idea, but using itertools.groupby to avoid keeping track of array indexes:

from itertools import groupby

def cuts(sticks):
    sticks = list(sticks)
    sticks_remaining = len(sticks)
    stick_counts_by_len = groupby(sorted(sticks))
    while sticks_remaining:
        yield sticks_remaining
        number_of_shortest_sticks = len(list(next(stick_counts_by_len)[1]))
        sticks_remaining -= number_of_shortest_sticks


Bot that selects web reviews based on spreadsheet entries

I will only comment on the "getting rid of the repeating ifs part".  A way to avoid writing the same condition in different places is to move the check entirely into a separate piece of code.  Some may refer to this as "state pattern".  Below is an example:

class StateExample(object):

    class State(object):

        def __init__(self, example):
            self.example = example

        def __str__(self):
            return self.__class__.__name__

    class Cities(State):

        def query_limits(self):
            self.example.do_one_thing(self)

    class Reviews(State):

        def query_limits(self):
            self.example.do_something_else(self)

    def __init__(self):
        self.state_factories = {
            'cities': self.Cities,
            'reviews': self.Reviews
        }

    def do_one_thing(self, state):
        print 'doing one thing with %s' % state

    def do_something_else(self, state):
        print 'doing something else with %s' % state

    def interact(self, city_or_review):
        self.state = self.state_factories[city_or_review](self)

    def interact_more(self):
        self.state.query_limits()

And an example usage, to illustrate the usage:

>>> example = StateExample()
>>> example.interact('cities')
>>> example.interact_more()
doing one thing with Cities
>>> example.interact('reviews')
>>> example.interact_more()
doing something else with Reviews
>>>

You may or may not need all of the machinery here.  The important part is to notice how this would be equivalent to testing repeatedly for the same condition inside interact and interact_more, which in the example above happens only once.

You can read more about this technique here: https://en.wikipedia.org/wiki/State_pattern

As an aside: it is not necessary to use classes and objects to achieve the same goal, but I want to keep this answer short.


Bank account model implementation in Django

In general this seems fine, easy to read, you seem to be following PEP8, that's excellent.

At first look, this repeated logic in balance and debt jumps in the eye:

@property
def balance(self):
    # ...
    while current_date <= today:
        result -= sum(x.total for x in self.cashing_set.on_date(current_date))
        result -= sum(x.total for x in self.outcome_transfers.on_date(current_date))
        result += sum(x.total for x in self.deposit_set.on_date(current_date))
        result += sum(x.total for x in self.income_transfers.on_date(current_date))
        # ...

@property
def debt(self):
    # ...
    while current_date <= today:
        result += sum(x.total for x in self.cashing_set.on_date(current_date))
        result += sum(x.total for x in self.outcome_transfers.on_date(current_date))
        result -= sum(x.total for x in self.deposit_set.on_date(current_date))
        result -= sum(x.total for x in self.income_transfers.on_date(current_date))
        # ...

My immediate reaction is to extract those summations to a helper method, for example:

def sum_total_transfers(self):
    result = 0
    result -= sum(x.total for x in self.cashing_set.on_date(current_date))
    result -= sum(x.total for x in self.outcome_transfers.on_date(current_date))
    result += sum(x.total for x in self.deposit_set.on_date(current_date))
    result += sum(x.total for x in self.income_transfers.on_date(current_date))
    return result

So that the above methods can reuse that with less duplication:

@property
def balance(self):
    # ...
    while current_date <= today:
        result += self.sum_total_transfers()
        # ...

@property
def debt(self):
    # ...
    while current_date <= today:
        result -= self.sum_total_transfers()
        # ...

On closer look, these assert lines don't look good:

@property
def balance(self):
    assert self.method == self.DEBET
    # ...

@property
def debt(self):
    assert self.method == self.CREDIT
    # ...

These assertions force the callers to check the value of self.method before using these properties,
or to organize the code in a way that ensures that .debt will only be called when self.method == self.CREDIT, otherwise the program would crash.
It would be better to avoid such unwritten rules.

For example, it might be better to have one public property that applies the correct calculation based on the method:

@property
def balance(self):
    if self.method == self.DEBET:
        return self._credit_balance
    return self._debt_balance

@property
def _credit_balance(self):
    assert self.method == self.DEBET
    # ...

@property
def _debt_balance(self):
    assert self.method == self.CREDIT
    # ...

Lastly, "debt" is misspelled in self.DEBET.


Method that remove duplicates from a list of words in Java

General advice

Prefer to declare variables by interfaces and not implementations. You don't need to specify that you use and return an ArrayList, specifying List is enough. So the first lines would be:

public static List<String> removeDuplicates(List<String> input) {
    List<String> array = new ArrayList<String>();
    Set<String> noDups = new TreeSet<String>();

Complexity

Javadoc for TreeSet says:

  This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

Since you are performing a log(n) operation \$n\$ times, this becomes n * log(n).

Unnecessary edge cases

This is your main code:

for(int i = 0; i < input.size(); i++){
        noDups.add(input.get(i));
}

Now let's take a look at your special cases:

if(input.isEmpty()){
    return array;
}

We can see that this would be handled correctly by your main code.

Your other special case:

if(input.size() == 1){
    array.add(input.get(0));
    return array;
}

This too would be handled correctly by your main code.

Shortened code

With the above advice this would shorten your code to:

public static List<String> removeDuplicates(List<String> input) {
    List<String> array = new ArrayList<String>();
    Set<String> noDups = new TreeSet<String>();
    for(int i = 0; i < input.size(); i++){
        noDups.add(input.get(i));
    }
    return new ArrayList<String>(noDups);
}

There is however one more thing we can do, and that is to use a specific constructor of TreeSet:

public static List<String> removeDuplicates(List<String> input) {
    return new ArrayList<String>(new TreeSet<String>(input));
}


There are many things that you do well here. Overall the code is fine.
I have some points that you should seriously consider and some things that you should think about. In the end, this is your code and I don't know everything that you know about it's purpose, usage and further plans.
Seriously consider

Android provides a lovely way to handle String Resources. I suggest you make use of that. Not only is it very handy to keep all your strings stored in .xml-files but it is also impossible to internationalize your messages if you hardcode string values within your code.

As AsyncResult seems to be a good, flexible, generic (generic as in both Java-generics and English generic) utility class, it wouldn't hurt to put getters as public and the fields as private final

Think about

What if the server provides both an error message and more detailed information as a response? I suggest that you create a constructor for your AsyncResult which accepts both T response and String errorMessage. You can then use constructor chaining in your class. Constructor chaining is a good way to reduce code duplication in constructors.

I find the naming of DefaultServerCallTask to be a bit misleading, the usage of the word Default together with the keyword abstract on the same class doesn't make sense to me. If it really is Default, then why is it abstract? (Although I understand your reasons for having it this way, I question the naming of the class).

Your AbstractServerCallTask extends AsyncTask<Void, Void, AsyncResult<Result>>. It is functional and I understand that you can specify data to be sent to the server by calling a constructor and storing it in a field, or creating an inner anonymous class which you actually do when you call new DefaultServerCallTask<LoginResponse>(){ ... }.execute();.
I think that you should consider allowing change of the first Void generics, which is the Param class. If you would allow changing that, then you can pass arguments to your execute method, which can be passed on to callServerMethod instead of having to get variables from outside into your new DefaultServerCallTask<LoginResponse>(){...

It is OK to have a AsyncResult<T> class, but will you have any use for the generics in that class outside your server calls? Your server calls only makes use of AsyncResult<Result>. As hinted by rolfl in his comment, a user currently can't use a AsyncResult<String> along with your classes for server calls.

I want to leave you with something positive though: Overall, your code is fine. So for your question "Is it good at all?" I have to say "yes".


This won't compile:

void generator(char tree, char water, char land);
// ...
generator("T", "~", ".");

Because generator takes 3 chars, and you're giving it const char* instead.

Of course that's easy to fix, just make the params chars:

generator('T', '~', '.');

It would be better if the generator generated, instead of printing.
It's to preserve the single responsibility principle.
Like this:

char generator(char tree, char water, char land)
{
    const char tileList[] = {tree, water, land};
    int tileIndex = rand() % 3;
    return tileList[tileIndex];
}

int main()
{
    srand(time(NULL));

    while(true)
    {
        std::cout << generator('T', '~', '.') << " ";
    }
}

Of course the loop will never end... Are you ok with that?

Taking 3 chars as possible tiles doesn't seem too flexible. How about making it work with arbitrary number of tiles? Something like this:

char generator(const char * tiles, int len)
{
    int index = rand() % len;
    return tiles[index];
}

int main()
{
    srand(time(NULL));

    const char * tiles = "T~.";
    int len = strlen(tiles);

    while(true)
    {
        std::cout << generator(tiles, len) << " ";
    }
}


Style

It won't hurt you and makes your code less error prone, if you would use braces {} also for single if statements.

Commented code (// if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);) should be removed completely. You should instead use a code versioning system like svn or git.

Update based on the comments below
It is not about a comment but about commented out code which is just dead code. What value has dead code ? Does it make your live code more readable or does it make your live code easier to understand ? No, it is quite the opposite.

Asume the following

public static void SetProperty(string propertyName, object content)
{
    //if (System.ComponentModel.DesignerProperties.IsInDesignTool)
    //    return;

    //if (content == null)
        RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);

    isoSettings[propertyName] = content;
    isoSettings.Save();
}

this is quite hard to read and understatnd by Mr.Maintainer.

This instead

public static void SetProperty(string propertyName, object content)
{
    RemoveProperty(propertyName);

    isoSettings[propertyName] = content;
    isoSettings.Save();
}

is much better to understand.

If you check something into svn/git you always should add a descriptive message to the commit.

SetProperty() method

if (content == null)
        RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);

    isoSettings[propertyName] = content;
    isoSettings.Save();

this does not make sense to me. If content==null you first remove the property, and then you add it. Next time passing null you just do the same.

You should consider returning after you have removed the property. There is no need to save the setting.

SetProperty() returning setted value

This is in my opinion a bad idea for a method which seems to be like a property setter. A property setter should only set a properties value.


Decorator to pass instance and class to method

I'd recommend not using value.__class__. This is as it's not guaranteed to return the type.

  type(x) is typically the same as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__class__).

Take:

class A:
    __class__ = 'something'

print(A.__class__)   # <class 'type'>
print(A().__class__) # 'something'
print(type(A()))     # <class '__main__.A'>

I also think just using type would be cleaner, and easier to understand.

def save_unique(self, *args, **kwargs):
    cls = type(self)


Fluttering
            if previousState == 0:
                if ticks_diff(ticks_ms(), clock) >= 0:

This is called a soft debounce. It may or may not be adequate. My usual recommendation is to do hard debounce instead (or maybe in addition) via a first-order RC lowpass filter followed by hysteresis in a Schmitt trigger. If none of that makes sense to you, then that's a question for https://electronics.stackexchange.com/ .
Truthiness
I would sooner write
if state:

rather than
if state == 1:

snake_case
Per PEP8, previousState should be previous_state.


os.chdir('../../Desktop')

Halt. Stop right there. This assumes the script is located at some specific location. Desktop happens to be always in the same place, but this assumes the script to be in a place relative to Desktop. On what OS do you intent to run this? If it's Linux-only, you could replace it by:

os.chdir('~/Desktop')

Now it will work regardless of where the script is located. Of-course, you just made the problem worse for non-Linux systems.

Even better would be to ask where the user wants to drop his files, possibly by using arguments (take a look at argparse).

But why don't you simply drop it instead? A map named Wallpapers will simply be created in the current directory. This would be obvious and expected behaviour.

for images in section:
    imageLink = images.find_all('a')
    for a in imageLink:
        imageUrl = a.get('href')
        linkList.append(imageUrl)
        print('Image found at... ' + imageUrl)

This isn't your bottleneck (not by a long shot), but that second for reeks of bad time complexity for something simple as telling the user where the images are.

One of the major time-consumers appears to be the downloading itself.

I ran cProfile against your code to find the bottleneck(s):

python3 -m cProfile -s tottime CR_133564.py

This automatically sorts the output on the total time taken per function, highest first. Don't forget to import cProfile. Let's take a look at everything with a total time higher than 0.5 seconds:

         8989953 function calls (8984594 primitive calls) in 108.880 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    20393   59.314    0.003   59.314    0.003 {method 'read' of '_ssl._SSLSocket' objects}
      183   28.853    0.158   28.853    0.158 {method 'do_handshake' of '_ssl._SSLSocket' objects}
      183    9.689    0.053    9.689    0.053 {method 'connect' of '_socket.socket' objects}
      183    1.547    0.008    1.548    0.008 {built-in method _socket.getaddrinfo}
      183    1.005    0.005    1.005    0.005 {method 'load_verify_locations' of '_ssl._SSLContext' objects}
    78129    0.621    0.000    3.383    0.000 parser.py:301(parse_starttag)
   585660    0.580    0.000    0.580    0.000 {method 'match' of '_sre.SRE_Pattern' objects}
       93    0.549    0.006    5.750    0.062 parser.py:134(goahead)

That's responsible for 102.2 seconds out of the 108.9 it takes. If you want to optimize, do it here. The rest is peanuts.

Do you notice anything? You're wasting half a minute on handshakes. That's almost 30 seconds you could be doing something useful instead. Unless you find a trick to carry all files over one handshake, there's not much you can do about it. It also takes almost 60 seconds simply to read (AKA: download) the data. That's only slightly more than I'd expect with my internet connection, so there's not much you can do about that either.


Using jQuery string replacements to make labels bold

I think yes, the ugliest I think is the follow:

// Define one regexp with all the piece you need and save
// the match with ()
var re = /(Employee|SSN|DOB|Start Date\/Time|End Date\/Time):/g

// Then change the replace as follow
var replaced = $("#myContents").html().replace(re, '<b>$1:</b>');

$("#myContents").html(replaced);

Of course you can compose your regexp as chunks as follow:

var terms = [];

...
terms.push("Employee");
...
terms.push("End Date\/Time");

...

var re = new RegExp("("+terms.join("|")+"):", 'g');

...


You write

from termcolor import colored

but then ignore that and write non-portable escape sequences directly in the strings:

  print("\033[1;34m"+"....", "\033[0;30m")

Doesn't that defeat the point of termcolor, which is supposed to adapt to the connected terminal?


Writing a hiveserver2 query result to CSV with Python using pyhs2

Speed improvements

Using a for loop to build a list is quite slow, when Python has 'list comprehensions'. They're for loop like expressions that build lists. So your col could be changed from this:

for key in cur.getSchema():
    col.append(key['columnName'])

to this:

col = [key['columnName'] for key in cur.getSchema()]

As far as I can tell, your header is actually pointless. You're making it just a single item list that then gets iterated over to write to your file. This seems to be the same as just mywriter.writerows(col).

Your use of zip is confusing. zip is used to join two or more lists when iterating. It's not normally used for a single list like you have, and doesn't really do much for you unless I'm missing something. It's a redundant drain on your time.

Other notes

You use context managers (with x as y) for the connection which is great, but you should do the same for your csv_out.

with open('data.csv', 'wb') as csv_out:

It's extra safety for your file the same way you have with the connections.

I'd also recommending refactoring your code into discrete functions rather than just one long script. It's better for readability and debugging purposes. Plus it makes it easier to change or reuse this code later.


Make things easier on yourself by separating concerns. E.g., each line encodes a position in its amount of leading whitespace followed by an identifier. Parse this representation into a more manipulable form in a single function invocation, don't thread it through your algorithm logic which shouldn't care about serialized representation.

type SerializedGraph = String -- Aliases for pedagogical clarity
type Indentation = Int
type Symbol = String

parse :: SerializedGraph -> [(Indentation, Symbol)]
parse = map (first length . span (== ' ')) . lines
    where first :: (a -> b) -> (a, c) -> (b, c)
          first f (a, c) = (f a, c)

Now consider intermediate representations that can get you closer to your goal. Remember that it's easy to construct a map from an association list with fromList, so let's make that our end goal. Write out the types for a roadmap from where we are to where we want to be.

    [(Indentation, Symbol)] -- [(Hint, Key)]
==> ???
==> [(Symbol, [Symbol])] -- [(Key, [Value])]

If that final representation has only unique keys, then a reasonable intermediary would be one that hasn't had values which share a key accumulated yet. I.e., [(Symbol, Symbol)] -- [(Key, Value)].

associate :: [(Int, String)] -> [(String, String)]
associate []          = []
associate ((i, s):ss) = [(s, t) | (j, t) <- descendants, j == i + 1]
                     ++ associate descendants
                     ++ associate siblings
    where (descendants, siblings) = span ((> i) . fst) ss

Now all that's left to do is create a Map. We could accumulate values on our own, but really that's what fromListWith is for.

toMap :: [(String, String)] -> Map String [String]
toMap = fromListWith (++) . map (second (:[]))
    where second f (a, b) = (a, f b)

All that's left is composing these functions together.

readGraph :: String -> Map String [String]
readGraph = toMap . associate . parse


Firefox profile specs to speed up web scraping

Regardless of if these settings are correct, or if you could get by without a webbrowser, this is not a very good way to set all these values. At the very least extract the key, value pairs to a dictionary, which you ideally read from a config file.

import webdriver

SETTINGS = {'browser.download.animateNotifications': False,
            ...}

def create_driver():
    firefox_profile = webdriver.FirefoxProfile()
    for key, value in SETTINGS.items():
        firefox_profile.set_preference(key, value)
    driver = webdriver.Firefox(firefox_profile = firefox_profile)
    return driver


I only have some comments about the shell scripting elements.

This is a very archaic (and silly) way of testing flags:

    [test "x$enable_yaml" != "xno"],

You can write simpler as:

    [test "$enable_yaml" != no],

This can be simplified:

    if test "${with_yamlroot}" != ""; then

To just:

    if test "${with_yamlroot}"; then

I also find it odd to use sometimes $this_style and sometimes ${that_style}.
I prefer less typing (especially the shift key for }),
so the first, simpler style.
The only time I use braces is when appending some text directly after the variable would break the script, for example in situations like this:

authtype=...  # something
# broken, not using the $authtype variable
#modpath=/usr/libexec/apache2/mod_$authtype_dbd.so
# good
modpath=/usr/libexec/apache2/mod_${authtype}_dbd.so


Why is read7 declared inline? You should only do this when it's needed as an optimization. (And it's particularly confusing when the function contains a static variable.)

It's not necessary for is to be static. It should really be an argument to read7, so it can work on any istream. (In real code, buffer should also be a parameter to readN, but for this toy problem it's reasonable to have it static.)

Bug: what happens if the input contains null characters?

You could avoid the queue by using a string as the queue. You can simply append the result of each read7 to it until you have enough characters, then remove and return the first n.


For such a simple use case, I would drop the abc module in favor of NotImplementedError:

class BaseAlgorithm:
    """This is the base on which all other algorithms are to be built."""

    # Unless explicitly stated otherwise, algorithms are in development
    STATUS = Status.in_development

    def encrypt(self, word):
        """Encrypt the word using an internal algorithm."""
        raise NotImplementedError

    def decrypt(self, word):
        """Decrypt the word using an internal algorithm.

        If this is not overloaded, it is assumed that
        encrypting and decrypting are the same operation.
        """
        return self.encrypt(word)

Using such base, only encrypt is explicitly required to be overloaded. I also extracted the status from a method to a class constant as this is the kind of information that does not depend of any state about this class. It also allows to focus on the algorithm first and only change the status when it is ready. Lastly, I also expanded the docstrings a bit so they are more explicit; you may want to explain, in the class docstring, what a user is expected to do when inheriting from BaseAlgorithm.

As for RotateAlg:

you could name it Rotate as the Alg part is already implied from the base BaseAlgorithm class;
you could incorporate the rotate function directly in the rotate method as there shouldn't be much use for a function on their own;
you could handle the rotate_left logic better by using this information directly as a parameter to rotate.

This would become something along the lines of:

class Rotate(BaseAlgorithm):
    """Takes a rotation amount  which it uses to encrypt or decrypt
    all words pass into it"""
    def __init__(self, offset):
        try:
            self.offset = int(offset)
        except ValueError:
            raise ValueError("the offset must be an integer") from None

    def encrypt(self, word):
        """Encrypts by rotating the word"""
        return self.rotate(word, rotate_left=False)

    def decrypt(self, word):
        """Decrypts by rotating the word back"""
        return self.rotate(word, rotate_left=True)

    def rotate(self, word, rotate_left=False):
        """Rotates the word to the chosen direction"""
        offset = -self.offset if rotate_left else self.offset
        offset %= len(word)
        return word[offset:] + word[:offset]

And, unless you specify otherwise with:

class Rotate(BaseAlgorithm):
    STATUS = Status.under_testing
    ...

then Rotate.STATUS will still be Status.in_development.


Something like :

xgc.toGregorianCalendar().toZonedDateTime().toLocalDateTime() ?

If you don't want to just rip off the zone information, but instead get the local time at UTC :

ZonedDateTime utcZoned = xgc.toGregorianCalendar().toZonedDateTime().withZoneSameInstant(ZoneId.of("UTC"));
LocalDateTime ldt = utcZoned.toLocalDateTime();

This answer is from the guy who has written the java.time specifications and implemented them btw : https://stackoverflow.com/questions/29767084/convert-between-localdate-and-xmlgregoriancalendar


Is this C++ naive primality test done right?

Is there such a thing as a prime real number?

If not then the function signature should use integer (preferably unsigned as there are no negative primes).

Then you should be able to use % rather than fmod() which I would suspect is a tad faster but, more importantly, easier to read.

Since you have already checked for all even primes:

for (int i = 3; i < sqrt(value); i+=2) {
                            //   ^^^^  No need to increment by 1;
                            //         All evens already checked already so inc by 2
                            //         So just check 3/5/7/9 etc

Here is a link to cool but not obvious optimization (That allows you to avoid checking all multiples of 3 as well as 2): https://codereview.stackexchange.com/a/7342/507


I would like to point some opportunities here. As you are refactoring your old code, I suggest:

try to avoid the use of literal string inside methods. Instead, use const variables or Resources (I do prefer Resources);
create your variables where you need them. Move your using to the nearest point of interest;
try to use string.Equals, it will be faster;
get your DbCommand directly from your connection, you have a method to do this;
try to use a Factory Pattern in this class, so in the future, if you need to change your database, you won't have to search for all your SqlConnection objects, you'll just need to change your Factory creator;
don't forget your XML comments

I made an example just to show those points. Sorry for the simplicity, but it's more difficult without knowing all your solution, but here is the idea:

using System;
using System.Configuration;
using System.Data;
using System.Data.Common;

namespace ClassLibrary1
{
    public class Class1
    {
        public const string shopStr = "shop";
        public const string shopDbConn = "Shop.DbConnection";
        public const string factoryDb = "System.Data.SqlClient";

        private static DbProviderFactory factory = DbProviderFactories.GetFactory(factoryDb);

        /// <summary>
        /// Get data from the database.
        /// </summary>
        /// <param name="sql">SQL command to retrieve data.</param>
        /// <param name="connString">Connection string for the database.</param>
        /// <returns><c>IDataReader</c> with the first result set, or <c>null</c> if no result was found.</returns>
        public static IDataReader GetRS(string sql, string connString)
        {
            IDataReader result = null;

            using (DbConnection conn = factory.CreateConnection())
            {
                if (string.Equals(connString, shopStr, StringComparison.OrdinalIgnoreCase))
                    conn.ConnectionString = ConfigurationManager.ConnectionStrings[shopDbConn].ConnectionString;
                else
                    conn.ConnectionString = connString;

                using (DbCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;

                    using (DbDataAdapter adapter = factory.CreateDataAdapter())
                    {
                        DataTable tbl = new DataTable(); // don't dispose it
                        adapter.Fill(tbl);
                        if (tbl.Rows.Count > 0) result = tbl.CreateDataReader();
                    }
                }
            }

            return result;
        }
    }
}


Bugs

var us, them, red = {
        rotation: gameInfo.red_rot,
        x: gameInfo.red_x,
        y: gameInfo.red_y,
        alive: gameInfo.blue_alive
    },
    blue = {
        rotation: gameInfo.blue_rot,
        x: gameInfo.blue_x,
        y: gameInfo.blue_y,
        alive: gameInfo.blue_alive
    };

Red and blue are using the same alive variable.

Also...

if (distanceFromSun < 30) {
    actions.push("hyperspace");
    console.log("Command Module is Hyperspacing.")
}
if (gameInfo[botVars["color"] + "_alive"]) {

I don't think dead ships are supposed to hyperspace.

Licensing

When you use code from StackExchange, like from this answer to the PPCG challenge, you should at the very least add a comment referencing the original source.

Duplication

Without looking at the code in detail, I spot this bit of duplication:

var rotation, x, y, opponentAlive;
if (botVars.color == "red") {
    rotation = gameInfo.red_rot;
    x = gameInfo.red_x;
    y = gameInfo.red_y;
    opponentAlive = gameInfo.blue_alive;
} else if (botVars.color == "blue") {
    rotation = gameInfo.blue_rot;
    x = gameInfo.blue_x;
    y = gameInfo.blue_y;
    opponentAlive = gameInfo.red_alive;
}

if (gameInfo[botVars["color"] + "_alive"]) {

You should pick one style and stick with it. I think you could get rid of a lot of the duplication by using the second style:

var rotation, x, y, opponentAlive;
rotation = gameInfo[botVars.color + "_rot"];
x = gameInfo[botVars.color + "_x"];
y = gameInfo[botVars.color + "_y"];

Leaves us with the opponentAlive variable, though.

For that, I'd just go with a function getOppositeColor:

function getOppositeColor(ownColor){
    return ownColor === "blue" ? "red" : "blue";
}

And then we can get opponentAlive via

opponentAlive = gameInfo[getOppositeColor(botVars.color) + "_alive"];

Other weird things in your code are that you explicitly declare a distance function... and then you don't use it. You make objects for red and blue, but you don't use them and then extract values from gameInfo a second time...

You should get the variables once. Then use them. Make a single flow like that.

var actions = [];
var us, them, red = {
        rotation: gameInfo.red_rot,
        x: gameInfo.red_x,
        y: gameInfo.red_y,
        alive: gameInfo.red_alive
    },
    blue = {
        rotation: gameInfo.blue_rot,
        x: gameInfo.blue_x,
        y: gameInfo.blue_y,
        alive: gameInfo.blue_alive
    };
if (botVars.color == "red") {
    us = red;
    them = blue;
} else if (botVars.color == "blue") {
    us = blue;
    them = red;
}

This part, in that regard, is perfectly fine.

var rotation, x, y, opponentAlive;
if (botVars.color == "red") {
    rotation = gameInfo.red_rot;
    x = gameInfo.red_x;
    y = gameInfo.red_y;
    opponentAlive = gameInfo.blue_alive;
} else if (botVars.color == "blue") {
    rotation = gameInfo.blue_rot;
    x = gameInfo.blue_x;
    y = gameInfo.blue_y;
    opponentAlive = gameInfo.red_alive;
}

This entire part can go. It's not needed. You already have all of these variables as us.rotation, us.x, us.y, and them.alive.

    if (rotationToOpponent > 90 && rotationToOpponent < 270) {
        actions.push("turn right");
    } else {
        actions.push("turn left");
    };

Also, you don't need a semicolon to end this if-statement here.


As mentioned in the original comment you leak on assignment:

Unique_Ptr<int>   a = new int(1);
Unique_Ptr<int>   b;

a = b;  // You leak the original a pointer.

Looking at the assignment operator:

Unique_Ptr& operator = (Unique_Ptr&& ob) noexcept {
    if (this != &ob) {
        m_ptr = ob.m_ptr;     // Here you overwrite the current value.
                              // and thus leak its original value.
        ob.m_ptr = nullptr;
    }
    return *this;
}

As mentioned in the comments the standard way of implementing move semantics is:

Unique_Ptr(Unique_Ptr&& ob) noexcept
    : m_ptr(nullptr)
{
    swap(ob);
}
Unique_Ptr& operator = (Unique_Ptr&& ob) noexcept
{
    swap(ob);
    return *this;
}

This has a couple of benefits. Calling the destructor is not required. You are moving the actual data to the other object. Thus means the destructor of the other object will correctly handle destruction.

This also potentially allows for re-use. If the ob is in some other context and you the object could be re-used this can help in optimizations. If it can not be-reused it will correctly be deleted.

You remove the pesimizing check for self assignment.

You don't have a conversion too bool.

if (a) {
    // A is holding a value you can do stuff with it.
}

// Now you can do
if (a.get()) {
    // A is holding a value you can do stuff with it.
}
// But its not as neat. And the context changes.

This is simply fixed with:

// Note the explicit (added in C++11) to replace the safe-bool idiom
explicit operator bool() {
    return m_ptr;
}

Can you guarantee that the destructor of type T does not throw?

void reset(T* ptr = nullptr) noexcept;

I think not. I agree it should be but that is not something you can guarantee and thus your code should not guarantee that it does not. So this should probably be:

void reset(T* ptr = nullptr);

You can probably do some meta-programming to determine if the destructor is noexcept but I don't have that in my head.

Don't mark your destructor as noexcept.

~Unique_Ptr() noexcept; // this is not needed.
                        // Destructors are automatically noexcept

Your destructor is automatically noexcept unless specific conditions are met so the compiler will work it out correctly for you.


The problem with any sort of timer in which each "tick" is a measurement from the previous "tick" is that in software, these "ticks" are not guaranteed to be exact.  This means that if your first tick is off by a tenth of a second, every remaining tick will be off by that amount or more.  Your second tick is scheduled based on your first tick.  This means the actual amount of total time passed is in exact, and the more ticks you have, the more error prone your total time is going to be.

So, for a start, I want to show you what a countdown object class might look like.  Then I'll walk through how we'd use this.

CRCountdown.h

typedef void (^CRCountdownCompletion)(void);

@interface CRCountdown : NSObject

- (void)startCountdownWithInterval:(NSTimeInterval)interval
                             ticks:(NSUInteger)ticks
                        completion:(CRCountdownCompletion)completion;

@property (readonly) NSUInteger ticksRemaining;
@property (readonly) NSTimeInterval interval;

@end

CRCountdown.m

@interface CRCountdown()

@property NSTimer *timer;
@property (readwrite) NSTimeInterval interval;
@property (copy) CRCountdownCompletion completion;

@end

@implementation CRCountdown

- (void)startCountdownWithInterval:(NSTimeInterval)interval ticks:(NSUInteger)ticks completion:(CRCountdownCompletion)completion {
    self.completion = completion;
    self.interval = interval;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:(interval * ticks) target:self selector:@selector(countdownComplete:) userInfo:nil repeats:NO];
}

- (void)stopCountdown {
    [self.timer invalidate];
}

- (NSUInteger)ticksRemaining {
    if (self.timer.isValid) {
        NSTimeInterval timeRemaining = [self.timer.fireDate timeIntervalSinceDate:[NSDate date]];
        return timeRemaining / self.interval;
    } else {
        return 0;
    }
}

- (void)countdownComplete:(NSTimer *)timer {
    if (self.completion) {
        self.completion();
    }
}

@end

Now, this will guarantee that our completion event happens at as accurate a time as possible.  We still can't guarantee that it will happen precisely at a specific moment, but the margin of error is drastically reduced by eliminating the possibility of compounding the error for each one of our "update ticks".

Instead, we set up a repeating NSTimer that's in charge of calling some code to update the UI.  This UI update code can look at ticksRemaining (and if necessary, multiply this by interval) to determine what it should update the UI to represent.

It's not even necessary to pass anything for the completion argument, as our interested object will already be polling ticksRemaining, so whenever this returns 0, we know that the timer is complete (complete-ish anyway).

But we can go one step further with our Countdown object and provide a means for including an update block that is fired on each tick, if we want.  For this, however, we're going to want two NSTimer's ticking away.

First, in our header, let's add another block typedef:

typedef void (^CRCountdownUpdate)(NSUInteger);

We also need to change our startCountdown... method to take an argument of this type:

- (void)startCountdownWithInterval:(NSTimerInterval)interval
                             ticks:(NSUInteger)ticks
                            update:(CRCountdownUpdate)update
                        completion:(CRCountdownCompletion)completion;

This means adding two more properties in our .m, an updateTimer (NSTimer *) and a CRCountdownUpdate:

@property NSTimer *updateTimer;
@property (copy) CRCountdownUpdate update;

We need to modify our countdownComplete: method so it will invalidate the updateTimer (so update never fires after completion):

- (void)countdownComplete:(NSTimer *)timer {
    [self.updateTimer invalidate];
    if (self.completion) {
        self.completion();
    }
}

And add an update method to handle the update ticks:

- (void)countdownUpdate:(NSTimer *)timer {
    if (self.update) {
        self.update(self.ticksRemaining);
    }
}

The final step is modifying our startCountdown... method to match how we updated the header and to take care of setting up the update timer:

- (void)startCountdownWithInterval:(NSTimeInterval)interval ticks:(NSUInteger)ticks completion:(CRCountdownCompletion)completion update:(CRCountdownUpdate)update {
    self.completion = completion;
    self.update = update;
    self.interval = interval;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:(interval * ticks) target:self selector:@selector(countdownComplete:) userInfo:nil repeats:NO];
    if (self.update) {
        self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(countdownUpdate:) userInfo:nil repeats:YES];
    }
}

Now, using this object is as simple as this:

CRCountdownUpdate update = ^(NSUInteger ticks) {
    self.infoLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)ticks];
};

CRCountdownCompletion completion = ^{
    self.infoLabel.hidden = YES;
    // do whatever else you want
};

CRCountdown *countdown = [[CRCountdown alloc] init];
[countdown startCountdownWithInterval:1.0
                                ticks:3
                               update:update
                           completion:completion];

Final version of the class I'm suggesting looks like this:

CRCountdown.h

typedef void (^CRCountdownCompletion)(void);
typedef void (^CRCountdownUpdate)(NSUInteger);

@interface CRCountdown : NSObject

- (void)startCountdownWithInterval:(NSTimeInterval)interval ticks:(NSUInteger)ticks completion:(CRCountdownCompletion)completion update:(CRCountdownUpdate)update;
@property (readonly) NSUInteger ticksRemaining;
@property (readonly) NSTimeInterval interval;

@end

CRCountdown.m

@interface CRCountdown()

@property NSTimer *timer;
@property NSTimer *updateTimer;
@property (readwrite) NSTimeInterval interval;
@property (copy) CRCountdownCompletion completion;
@property (copy) CRCountdownUpdate update;

@end

@implementation CRCountdown

- (void)startCountdownWithInterval:(NSTimeInterval)interval ticks:(NSUInteger)ticks completion:(CRCountdownCompletion)completion update:(CRCountdownUpdate)update {
    self.completion = completion;
    self.update = update;
    self.interval = interval;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:(interval * ticks) target:self selector:@selector(countdownComplete:) userInfo:nil repeats:NO];
    if (self.update) {
        self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(countdownUpdate:) userInfo:nil repeats:YES];
    }
}

- (void)stopCountdown {
    [self.updateTimer invalidate];
    [self.timer invalidate];
}

- (NSUInteger)ticksRemaining {
    if (self.timer.isValid) {
        NSTimeInterval timeRemaining = [self.timer.fireDate timeIntervalSinceDate:[NSDate date]];
        return timeRemaining / self.interval;
    } else {
        return 0;
    }
}

- (void)countdownUpdate:(NSTimer *)timer {
    if (self.update) {
        self.update(self.ticksRemaining);
        NSString *s = [NSString stringWithFormat:@"%lu", (unsigned long)self.ticksRemaining];
    }
}

- (void)countdownComplete:(NSTimer *)timer {
    [self.updateTimer invalidate];
    if (self.completion) {
        self.completion();
    }

    self.update = nil;
    self.completion = nil;
}

@end

This of course, could also be done with delegation rather than blocks, which might be an appropriate approach.

I've created a github repo with both the block-based and delegation-based approaches.  It can be found here.