In your PlayerScript class, you have two variables, runSpeed, and jumpForce, and you initialize them in Start, like this:

void Start () {
    runSpeed = 20;
    jumpForce = 10;
}

This isn't necessary. Rather, you can do something like this:

public class PlayerScript : MonoBehaviour {
    public int runSpeed = 20;
    public int jumpForce = 10;
}

This will also mean that the variables runSpeed and jumpForce will have the default values of 20 and 10 in the Unity Editor as well.

In addition, in your SphereTriggerScript class, you also don't need to initialize playerObject in Start as well.

In your SphereTriggerScript class, in the method OnTriggerEnter, you never do a check to make sure that the collider is actually the Player GameObject. In order to do this, you'll have to wrap the contents of SphereTriggerScript.OnTriggerEnter in this if statement:

if(other.gameObject.name == playerObject.name)
{
    ...
}

This ensures that in case any other GameObject happens to collide with a power-up, that it won't be destroyed.

The UnityEngine namespace comes with a static class Random, which I prefer over System.Random while using Unity3D. Rather than having to instantiate System.Random, I can just call the methods directly from UnityEngine.Random.

Compare:

System.Random random = new System.Random();
int randomNumber = random.Next(0, 100);

To:

int randomNumber = (int)Random.Range(0, 100);

Other than the above, I just have a few small nitpicks:

The general style for storing an instantiated GameObject is the below example, not containing the Gameobject. prefix, and using as for a cast instead.

GameObject gameObject = Instantiate( ... ) as GameObject;

In addition, C# braces should be placed on the next line, not like Java braces, as seen in the below example.

if( ... )
{
    ...
}

Finally, you have a few magic numbers scattered across your code, so here's a small list of places containing magic numbers:

  script.jumpForce += 1;

  script.runSpeed += 1;

  int randomNumber = random.Next(0, 100);

  int randomHeightOffset = random.Next(2, 12);

Other than that, your code looks pretty nice! I'm excited to see where this game goes!


Given a list of integers, write a function that returns the largest sum of non-adjacent numbers? Numbers can be 0 or negative

What you implemented is the recursive solution:

sum(k)
  | k < 0 = 0
  | otherwise = max( sum(k-1), sum(k-2) + arr[k] )

You can also implement it iteratively using an O(n) extra space:

sum = int[n]
sum[0] = max(      0, arr[0] )
sum[1] = max( sum[0], arr[1] )
for (int k = 2; k < n; k++)
{
    sum[k] = max( sum[k-1], sum[k-2] + arr[k] )
}

You may notice that nothing but the two rightmost values will ever be used in the next iteration. We can get rid of the array entirely and store only those values instead, which leads to O(1) space usage.

s2 = max(  0, arr[0] )
s1 = max( s2, arr[1] )
for (int k = 2; k < n; k++)
{
    s0 = max( s1, s2 + arr[k] )
    s2 = s1
    s1 = s0
}


Recursive implementation of a zip function in F#

Based upon my comment on that answer I've toyed a little to make a recursive sequence expression with roughly the same performance (on my computer at least) as Seq.zip

let zipRec (s1: _ seq) (s2: _ seq) =
  use e1 = s1.GetEnumerator ()
  use e2 = s2.GetEnumerator ()

  let rec loop hasMoved1 hasMoved2 = seq {
    if hasMoved1 && hasMoved2 then
      yield e1.Current, e2.Current
      yield! loop (e1.MoveNext ()) (e2.MoveNext ())
  }

  loop (e1.MoveNext ()) (e2.MoveNext ())

without the recursive requirement it would be simpler this way

let zipRec (s1: _ seq) (s2: _ seq) = seq {
  use e1 = s1.GetEnumerator ()
  use e2 = s2.GetEnumerator ()

  while e1.MoveNext () && e2.MoveNext () do
    yield e1.Current, e2.Current
}


Transforming UCI-move into bitboard, chess

Option 1:
The most basic thing I can suggest is that if you have a mapping from one thing to another, and if that mapping is fixed, you should be using a mapping data type.
The mapping data type in python is the dict, which can be written in-line like so:
uci_bit = {
    'a': 2**7, 'b': 2**6, 'c': 2**5, 'd': 2**4,
    'e': 2**3, 'f': 2**2, 'g': 2**1, 'h': 2**0,
}

Alternatively, the dict() function returns a dictionary, and takes keyword arguments:
uci_bit = dict(a=2**7, b=2**6, c=2**5, d=2**4,
               e=2**3, f=2**2, g=2**1, h=2**0)

Same result either way. You could then access the dict using the standard square-bracket notation:
ch = uci[0]
mask1 = uci_bit[ch]

Or as a single expression:
mask1 = uci_bit[uci[0]]

Option 2:
However, there's another approach that has some potential. Looking things up in a dictionary has a cost. It's technically \$O(n)\$ but maybe there's a constant or two in there. So ...
Because the two components of the uci location are fixed-width ('a' and '2') you might be able to look them up in a string using the str.index method and get better performance.
Note: I wrote "might be". The way to know for sure is to write both bits of code and run a timing test on the alternatives. Look up the timeit module in the standard distribution.
Something like:
UCI_CHARS = 'hgfedcba'

mask1 = 2 ** UCI_CHARS.index(uci[0])
mask2 = 2 ** UCI_CHARS.index(uci[2])

You might also want to check the result of using dict versus str.index versus the int() function on the single-digit part of uci decoding.
Option 3:
It's not clear how many of these operations you are performing. If you are doing a single game, and there might be two dozen uci to bit operations, then it probably doesn't matter. But if you're doing a lot of games at the same time, it might behoove you to generate a dictionary containing all the UCI letter/number combinations, and do the lookup as a single operation. Something like:
for ch in 'abcdefgh':
    for digit in '12345678':
        uci = ch + digit
        bit = # whatever computation
        uci_bit[uci] = bit

This would let you decode 'a2' -> bits in a single step at the cost of the up-front loop.
Other considerations
I asked the Duck about bitboard, and was immediately presented with the fact that there is no single standard representation. Instead, there are different representations for different purposes and different CPU architectures.
A result of this is that you should definitely be doing this inside a class or function, and there should definitely be a "name" given to the kind of bitboard you want to compute, so that readers will understand which of the several options you are choosing. Rank-major versus File-major and big- versus little- endian representations are all valid, so make sure to include this information either in the class or function name, or in the commentary.
def uci_to_bitboard_lsf(uci: str) -> int:
    """ Convert UCI notation to bitboard(LSF, little-endian) """

    ...

Also, I suspect that using * may be a bug, and you should be using + instead. (It really should be a bitwise or, the | operator, but + will work.)


Matrix2x2 struct operators implementation in C++

Leading _

Some combinations of leading underscore are reserved specifically __ and _<CapitalLetter>, you're one character away from invalid code it's easier to stay away. See this answer.

Document Datatypes

The only way to discern what values are where in your matrix is to assume that the indices of your member variables are row/column, there is no documentation to that effect. I have to look at the out stream operator to figure that out. Always document assumptions or implicit behavior.

Scalar operations missing reverse operator

Matrix m1, m2;
double d;
m1 = m2 * d;

won't compile, you need to implement both version of asymmetric operators somehow.

Various matrix operations missing

For completeness there are quite a few operations missing, multiplication, inverse, determinant ...

const qualifier on returns will cause extra copy

Matrix m1, m2, m3;
m1 = m2 + m3;

will create an extra copy of the result matrix on the assignment. You marked the return value of + as const this means that when it's assigned to a non-const variable a copy will be created. You are doing this on all the binary operators is there a specific reason you did this ?

Fixed Matrices

There should be an easy way to get an identity, or a zero matrix it's not necessary but a nice to have.

Operator + might be inefficient

While delegating the addition to the += operator saves you from repeating some code it could be better to construct the correct matrix in place and return it

const Matrix2x2 operator+(const Matrix2x2& m1, const Matrix2x2& m2)
{
    return Matrix2x2{m1._00 + m2._00, m1._01 + m2._01,
                     m1._10 + m2._10, m1._11 + m2._11};
}

Btw you could use this form for all you operations.

Edit 1

const return value

You responded that this was something the lecturer advised you to do to protect against f() = x being written, if that is what he asks you should do it in that class. They are correct, having a const return value will prevent the compilation. This is a good thing as a statement like that most likely has no effect and the result of f() will immediately go out of scope.

struct X;

X function() {};
const X constFunction() {};

X newValue;
// Compiles correctly but there is no effect (in most cases)
// as the result of function() will be discarded immediately
// There would be an effect if operator= is overridden and has
// side effects. I would consider that a really bad idea.
function() = newValue;

// The following line won't compile, therefor telling you
// "Don't do this"
constFunction() = newValue;

In the code I usually work with i would definitely advise against it. In general I would be suspicious of any code that assigned directly to the result of a free function. I'd rather go with "Don't assign to the result of a free function" as a style rule. In modern c++ doing this prevents the use of move semantics on the result of your function.

With member functions this would be different returning a reference or a const references is something that may happen a lot. So there are cases where you might actually write object.getter() = x. But it's dealing with references as results and not values.

Operator efficiency

I changed the wording to reflect this being an option, it's great that you went and checked the assembly, i did the same (https://godbolt.org/g/Kh3BsJ). For me it looks like that for clang and gcc the solutions are equivalent except for a different use of registers, I am not qualified to say how this affects the actual performance. For MSVC the case looks different the while in place solution is almost the same as what clang/gcc do, the two call path is definitely longer. As a general thought, the simpler your code is the easier it will be to optimize for the compiler. This is a discussion to be had when the need for optimization arises. You're doing great, keep going.


SqlAlchemy model for users and timezones

I wouldn't bother making a separate table for timezones. That just makes you do joins unnecessarily. Just put the timezone name directly as an attribute of the UserTimezone table.


PHP session_set_saver_handler with session timeout

Since the code for logout.php is not provided, I'll just make assumptions. Your code is pretty clean but I think it could be improved a bit.

Miscellaneous

Both locked and timeout are defined but only used once. Since they are local variables, I consider that they could be removed and just replaced by their values.

Still concerning the timeout, I prefer working with proper date and time types provided by MySQL rather than working with timestamps stored as integers. The main reason is that there are a lot of functions at your disposition, like for example NOW() and TIMESTAMPDIFF(), which could be used to rewrite your query easily

SELECT TIMESTAMPDIFF(MINUTE, NOW(), updatedTime ) AS minutesSinceLastActivity, data FROM sessions WHERE session = :id AND locked = :locked

Once you have that, your condition is pretty simple : if($row['minutesSinceLastActivity'] > $this->accessTime) . Which leads me to another point, the naming of accessTime is pretty bad, I would define it as something like minutesInactivityBeforeLogout.

One last thing that I'm a bit unsure about (I know it works for C, don't remember for PHP), you could regroup the two conditions if($this->database->execute()) and if($this->database->rowCount() > 0) into one with the and operator. Since you'll use an and, if the execution of the query fails, execution the rest of the code in the if condition is unnecessary since it cannot change the result of the condition. Once again, this is something I know works in C, not quite sure about PHP.

How it works

You said you had a constant redirection loop with a previous version of your code. The main reason I could fin for that is that if you detect a timeout, you don't do anything on your MySQL table, which means you'll always end up in the same condition and doing always the same thing.

That's why you should keep your structure and query as it is (you could put the timeout condition in the query, but doing so, you would be unable to differentiate the case where the timeout is reached from the case where there is no record for the current id). The only thing that you have to do is for example to delete the record if the timeout condition is reached.


This is a binary search tree.
Do not cast the return value of malloc. It serves no purpose, and may mask a serious bug (in case stdlib.h is not included).
Lookup is usually implemented iteratively:

while (root) {
    if (root->id == id) {
        break;
    }
    root = (root->id < id)? root->right: root->left;
}
return root;

insert_node may use less indentation. Early return makes else unnecessary:

node *insert_node(node *root, int data, int node_id) {
    if (root == NULL)
        return newNode(data, node_id);
    node *cur;
    if (node_id < root->node_id) {
        cur = insert_node(root->left, data, node_id);
        root->left = cur;
    } else if (node_id > root->node_id) {
        cur = insert_node(root->right, data, node_id);
        root->right = cur;
    }
    return root;
}

You may want to inform the caller that the insertion failed due to id already present.


Glaring Deficiencies

What are you doing? You haven't bothered to explain your algorithm, either in the question body or in program comments.
Bugs. As pointed out by @Abhisek, your code prints 3 instead of 2. When you count the number of camelCase words, you should ignore whitespace, in fact, you should treat any non-alphabetic characters as lower-case, as per my understanding of the problem (although this is an edge case).
You haven't bothered to use any of Java's standard libraries. You would find the functions Character.isUpperCase(char), Character.isLowerCase(char) and Character.isWhitespace(char) extremely useful, instead of doing error-prone and language-limited manual checking. Also, String.isEmpty() is always a better check than String.length() == 0.
Non-descriptive naming. Your method does indeed solve a HackerRank problem, but that does not describe it properly. You could name it for what it does, something like getCamelCaseWordCount(String), as per some guidelines for Java method naming (Effective Java by Joshua Bloch).
You only use len once without the emptiness check. In fact, that is not required either, as the general code will handle that too. Just use the emptiness check to set the initial value of the word count to 0 or 1, depending on whether the input is empty or non-empty. respectively. You do not need to return early to avoid the loop as the loop won't iterate in the first place.
For that matter, as Strings are immutable, repeatedly calling .length() on the same String object does not have much overhead, so you do not need len even if you are concerned about the loop.
Avoid all the len business, and use a for-each loop. Kind of like:

for(char c : input.toCharArray()){//for JDK 1.5+
    ...
}

OR,

for(char c : input.chars()){//for JDK 1.8+
    ...
}

As usual, this is a 1-liner with Java 8 streams. This is an exact equivalent:

return in.isEmpty() ? 0 : 1 + in.chars().filter(Character::isUpperCase).count();

Note that the above returns a long, not an int. That's as per the Stream API.

Putting it all together,

Modified Code

public class Test{
    public static long getCamelCaseWordCountNormal(String in){
        long words = in.isEmpty() ? 0 : 1;
        for(char c : in.toCharArray()){
            if(Character.isUpperCase(c)){
                words++;
            }
        }
        return words;
    }

    public static long getCamelCaseWordCountStreams(String in){
        return in.isEmpty() ? 0 : 1 + in.chars().filter(Character::isUpperCase).count();
    }
}


Adding more responsibility to this endgame-analyzer class

You're using extension methods for cells; why do use for loops for rows? It strikes me as weird.  Also, there's plenty of repetition in your analyzer; you can do better by abstracting some things away (more on that below).

To answer your main question, instead of returning bool for whether somebody won, you can return Nullable<Player> where Player is an enum with X and O values. This would not in any way violate single responsibility principle because your class' responsibility is to analyze the game, and determine the winner. There is no point in finding out if somebody has won, if you don't know who that somebody is.

That being said, I think you could still do better with the implementation. Your GameEndAnalyzer analyzes each outcome manually, whereas you could've made it more generic by introducing a concept of “lines” and a few extension methods (somewhat less than you seem to have).

I re-wrote my earlier toy Tic Tac Toe implementation specifically to address your question, with the following separation:

Player is a simple enum:

enum Player {
    X,
    O
}

IBoard represents a board with an indexer by row and column and Size.

interface IBoard
{
    int Size { get; }
    Player? this [int row, int column] { get; set; }
}

(really, you don't need anything else in IBoard)
The implementation is trivial:

class Board : IBoard
{
    Player? [,] _cells;

    public int Size {
        get { return _cells.GetLength (0); }
    }

    public Board (int size)
    {
        _cells = new Player? [size, size];
    }

    public Player? this [int row, int column] {
        get {
            return _cells [row, column];
        } set {
            if (_cells [row, column].HasValue)
                throw new InvalidOperationException ("The cell is already claimed.");

            _cells [row, column] = value;
        }
    }
}

IBoardAnalyzer has a single method that scans the board to find the winner, similarly to yours:

interface IBoardAnalyzer
{
    Player? DetermineWinner (IBoard board);
}

All the actual heavy-lifting for scanning the board lives in BoardExtensions that can enumerate board rows, columns and diagonals. There is also an über-method called SelectAllLines that returns a sequence of all “lines” (rows, columns and diagonals) on the board. Note that BoardExtensions does no analysis; it only provides convenience methods for extracting data out of Board.

static class BoardExtensions
{
    public enum DiagonalKind {
        Primary,
        Secondary
    }

    public static IEnumerable<IEnumerable<Player?>> SelectAllLines (this IBoard board)
    {
        return board.SelectAllDiagonals ()
            .Concat (board.SelectAllRows ())
            .Concat (board.SelectAllColumns ());
    }

    public static IEnumerable<IEnumerable<Player?>> SelectAllRows (this IBoard board)
    {
        return from row in board.SelectIndices ()
               select board.SelectRow (row);
    }

    public static IEnumerable<IEnumerable<Player?>> SelectAllColumns (this IBoard board)
    {
        return from column in board.SelectIndices ()
               select board.SelectColumn (column);
    }

    public static IEnumerable<IEnumerable<Player?>> SelectAllDiagonals (this IBoard board)
    {
        return from kind in new [] { DiagonalKind.Primary, DiagonalKind.Secondary }
               select board.SelectDiagonal (kind);
    }

    public static IEnumerable<Player?> SelectRow (this IBoard board, int row)
    {
        return from column in board.SelectIndices ()
               select board [row, column];
    }

    public static IEnumerable<Player?> SelectColumn (this IBoard board, int column)
    {
        return from row in board.SelectIndices ()
               select board [row, column];
    }

    public static IEnumerable<Player?> SelectDiagonal (this IBoard board, DiagonalKind kind)
    {
        return from index in board.SelectIndices ()
               let row = index
               let column = (kind == DiagonalKind.Primary)
                   ? index
                   : board.Size - 1 - index
               select board [row, column];
    }

    public static IEnumerable<int> SelectIndices (this IBoard board)
    {
        return Enumerable.Range (0, board.Size);
    }
}

The implementation for BoardAnalyzer uses BoardExtensions to find the winner, but in itself is trivial:

class BoardAnalyzer : IBoardAnalyzer
{
    public Player? DetermineWinner (IBoard board)
    {
        return (
            from line in board.SelectAllLines ()
            let winner = DetermineLineWinner (line)
            where winner.HasValue
            select winner
        ).FirstOrDefault ();
    }

    static Player? DetermineLineWinner (IEnumerable<Player?> line)
    {
        try {
            return line.Distinct ().Single ();
        } catch (InvalidOperationException) {
            return null;
        }
    }
}

Finally, I implemented an IO which has a simple interface:

interface IGameIO
{
    Tuple<int, int> AskNextMove (Player player, IBoard board);
    void DisplayError (GameError error);
    void DisplayWinner (Player player);
}

And just as simple implementation:

class ConsoleGameIO : IGameIO
{
    public Tuple<int, int> AskNextMove (Player player, IBoard board)
    {
        Console.WriteLine ("\n\n");
        Console.WriteLine ("{0}, what is your move?\n", FormatPlayer (player));
        Console.WriteLine (FormatBoard (board));
        Console.Write ("\nType A1 to C3: ", FormatPlayer (player));

        return ParseMove (Console.ReadLine ().Trim ().ToUpperInvariant ());
    }

    public void DisplayError (GameError error)
    {
        switch (error) {
        case GameError.CellAlreadyOccupied:
            Console.WriteLine ("Bad move: cell is already occupied.");
            break;
        case GameError.CouldNotParseMove:
            Console.WriteLine ("Bad move. Valid moves are A1 to C3.");
            break;
        default:
            Console.WriteLine ("Something went wrong.");
            break;
        }
    }

    public void DisplayWinner (Player player)
    {
        Console.WriteLine ("Congatulations, {0}! You won.", FormatPlayer (player));
    }

    static string FormatBoard (IBoard board)
    {
        return string.Join ("\n", from row in board.SelectAllRows () select FormatRow (row));
    }

    static string FormatRow (IEnumerable<Player?> row)
    {
        return string.Join ("|", from cell in row select FormatCell (cell));
    }

    static string FormatPlayer (Player player)
    {
        return FormatCell (player);
    }

    static string FormatCell (Player? cell)
    {
        return cell.HasValue ? cell.Value.ToString () : "_";
    }

    static Tuple<int, int> ParseMove (string input)
    {
        return Tuple.Create (
            input [0] - 'A',
            input [1] - '1'
        );
    }
}

Finally, there goes the Game class with the run loop and Main method:

class Game
{
    IBoard board;
    IBoardAnalyzer analyzer;
    IGameIO io;

    public Game (IBoard board, IBoardAnalyzer analyzer, IGameIO io)
    {
        this.board = board;
        this.analyzer = analyzer;
        this.io = io;
    }

    public void Run ()
    {
        Player player = Player.X;
        Player? winner = null;

        do {
            Tuple<int, int> move;
            try {
                move = io.AskNextMove (player, board);
            } catch {
                io.DisplayError (GameError.CouldNotParseMove);
                continue;
            }

            if (!ValidateMove (move)) {
                io.DisplayError (GameError.CouldNotParseMove);
                continue;
            }

            try {
                board [move.Item1, move.Item2] = player;
            } catch (InvalidOperationException) {
                io.DisplayError (GameError.CellAlreadyOccupied);
                continue;
            }

            player = GetNextPlayer (player);
            winner = analyzer.DetermineWinner (board);

        } while (!winner.HasValue);

        io.DisplayWinner (winner.Value);
    }

    bool ValidateMove (Tuple<int, int> move)
    {
        return (move.Item1 >= 0 && move.Item1 < board.Size)
            && (move.Item2 >= 0 && move.Item2 < board.Size);
    }

    static Player GetNextPlayer (Player player)
    {
        switch (player) {
        case Player.X:
            return Player.O;
        case Player.O:
            return Player.X;
        default:
            throw new NotImplementedException ();
        }
    }

    public static void Main (string[] args)
    {
        var game = new Game (new Board (3), new BoardAnalyzer (), new ConsoleGameIO ());
        game.Run ();
    }
}

Check it out on Github.


Good things
You use good local variables, and you are consistent with your naming. The typical naming for T-SQL is using PascalCase, however there are no standards and snake_case or camelCase work just as good, as long as you are consistent (which you are).
You validate your values, although I am not quite sure why you chose 500 and 3 as arbitrary minimums (might be worth documenting).

Results are not very useful...
As written, your query returns this:
ViewCount Score
--------- -----
571       10
629       5
685       6
721       10
728       11
761       12
840       25
849       7
870       17
888       9
1065      10
...
Which is all well and good, except, it doesn't give much information. Let's say we rewrite it a bit like this:
IF (@min_views >= @allowed_min_views AND @min_score >= @allowed_min_score)
BEGIN
  SELECT
      ViewCount
    , Score
    , [User Link] = @user_id
    , [Post Link] = Id
    , CreationDate
    , [Tags] = Tags
    FROM Posts
    WHERE
      PostTypeId = @question
      AND OwnerUserId = @user_id
      AND ViewCount >= @min_views
      AND Score >= @min_score
    ORDER BY ViewCount DESC;
END

Notice I changed ORDER BY to DESC, I think it makes more sense to show highest first.
Then we get a more sensible result set, e.g.:


In modern systems, there's ssh-copy-id for this. But yeah it's not everywhere. In systems that don't have it, I have a similar script like yours, but to mimic the "standard", I call it ssh-copy-id.sh. Name it as you like, but I don't think "loadkey" really sums up the action of appending your public key to the authorized list file on a remote server. So I'd pick something better.

Cats are sure cute creatures, but you don't need one here:

cat ~/.ssh/id_rsa.pub | ssh -2 $host $installcat

You can use input redirection:

ssh -2 $host $install < ~/.ssh/id_rsa.pub

Lastly, the ssh ... echo hi stuff is repeated twice. It would be better to put it in a function. You can chain the different final echo + exit commands after the function with && normally.


Another variant of the code

I took your second (more functional) example and polished it a bit.

*) The const keyword is used instead of the let in two places. This prevents accidental/undesired re-assignment of a value to a local variable.

**) the type of the accumulatorMap and key can be inferred.

***) The .reduce() is simplified, since map.set(key, value) already returns you a map object.

getMyAvailabilities(startDate: Moment, endDate: Moment): Observable<Map<Moment, Availability>>
{
  const params = new URLSearchParams();                              // *
  params.set('startDate', startDate.format(this.formatDateString));
  params.set('endDate', endDate.format(this.formatDateString));

  return this.http
    .get(this.resourceUrl, { search: params })
    .map((response: Response) => {
      const result = response.json();                                // *
      return Object.keys(result)
        .reduce(
          (accumulatorMap, key) =>                                   // **
            accumulatorMap.set(moment(key), result[key]),            // ***
          new Map<Moment, Availability>()
        );
    });
}

Functional vs imperative — hopefully not off topic

Disclaimer

I don't think that Codereview.StackExchange is the right place to ask questions of that sort. The answers may get extremely subjective (and result in a "holy war"). The issue is that there's no universally objective criteria which could be used to justify that functional code is by definition better than imperative ...or vice versa.

I prefer functional...

Still, I chose the functional code snippet you provided and improved it, rather than the imperative. Here's the reason why, but please take it as an opinion.

In my experience, functional code is less buggy, so to speak. Now, I do not have any data to back this statement, and my guess is that the scientific studies on that subject are contradictory. Nevertheless, this is what I feel about it.

Reasoning behind "functional is better"

Here are a very few functional programming aspects and their possible effects:

Working with Maybe/Option [monad] makes the code more generalized, gets rid of explicit branching —> Simpler code. —> Defect likelihood reduces.
Using const instead of let or var prevents accidental object reassignment. No if-guards are needed. —> Defect likelihood reduces.
Pure functions do not modify the state, nor alter the input parameters, and always return same results for same inputs. —> Simpler code. —> Defect likelihood reduces.
...
I think you get my point but please do not trust me! Search online for more in-depth articles or blog posts. :)

Psychology matters

However, as you said, it takes time to adjust one's mindset, way of thinking, or habits — call it whatever you want — to harness functional programming aspects.

Remember how you touched a declarative (e.g. SQL), logic (e.g. Prolog), functional (e.g. Haskell, Lisp, Scala) or any other fundamental paradigm language for the first time. I bet it was not easy to grasp. For the first several weeks or months everyone in this position will write a lot of imperfect code and it's totally fine (as long as he/she is willing to revisit and fix it).

During this period the code may be more buggy, but this effect is temporary and diminishes with experience and learning time investments. It is important from the psychological standpoint to not make any conclusions at this point about whether the paradigm being adopted is good or bad. For the same reasons, it's extremely important to not judge a dev nor his code too strictly.

Anesthesia?

If you agree that the benefits are sweet, you want to push for functional code when possible. Still, the transition process may be painful. What do you do?

Well, here're the good news. The Divide and Conquer principle can be successfully applied. In fact, this is how I learn functional programming myself. You don't need to learn all the aspects at once (just like the SOLID principles, or design patterns).

Add one tool at a time to your toolkit and start harvesting the fruits.
Polish your skills over time and they become your second nature.
Experiment with what you've learnt.
Keep investing into the tools (in other words, make sure point 1. is repeated).
Retrospect and notice how the practices/aspects can be efficiently combined together. Often the case it happens intuitively without intentional search for it.
Be patient...
PROFIT!

P.S.

Many programming languages that have functional traits don't push a developer very hard towards writing functional code. This is especially true for the languages that acquired these traits as a result of evolution (like C# and latest versions of Java). Developers can still write imperative code even in Scala, the language does not prevent that.

Obviously, there's no silver bullet in programming. There will always be bugs out there, no matter what king of programming language we're talking about. It's the human beings who write the code, and we are not perfect in it. Realistic expectations may help a lot to achieve satisfaction instead of disappointment.


In exxp-aux, you call (mX-let b prod) and (mX-lex b prod).  You probably meant the two calls to be identical.

In exxp-let, you call (mX-let prod b).

mX-lex and mX-let are both implemented such that they would be faster if you call them with the larger multiplicand first and the smaller one second, because the second parameter controls the number of additions.  Since prod is likely to be larger than b, your exxp-aux will be slower.


As general practice, I prefer using positional arguments simply because they're easier to typecheck with mypy.  In the case of using some external API that doesn't have python3 type annotations (booo) I'd create a stub file that includes all of the types that I'm using and then code against that.

For your example, a quick search didn't turn up any existing mypy stubs, so I assume I'm stuck writing my own.  Here's how I'm gonna do it for the code sample you've provided:

from typing import List, TypedDict

class _Properties(TypedDict, total=False):
    title: str

class _AddSheet(TypedDict, total=False):
    properties: _Properties

class _Request(TypedDict, total=False):
    addSheet: _AddSheet

class _Body(TypedDict, total=False):
    requests: List[_Request]

def batchUpdate(spreadsheetId: str, body: _Body) -> None: ...

This is a very incomplete type declaration for that potentially massive _Body object (also, note that I'm assuming that none of these fields are required; omit the total=False if you want to enforce totality), but since I'm probably not going to use all of those fields, my strategy is going to be to add them to my declaration as I use them, and have that be the source of truth (i.e. as long as I declare it correctly once in that file, mypy will make sure I use it correctly everywhere else).

Now I can call that function in my code like this:

batchUpdate(
    spreadsheetId, {
        'requests': [{
            'addSheet': {
                'properties': {
                    'title': "some title"
                }
            }
        }]
    }
)

(BTW, if you want to completely ignore my advice about typing, this is the calling syntax I'd use regardless.)

The benefit of having added typing is that if I typo something, e.g. I misspell "properties", I'll get an error from mypy like this:

spreadsheet.py:22: error: Extra key 'prperties' for TypedDict "_AddSheet"

If I forget that requests is a list and I omit the brackets, I get:

spreadsheet.py:21: error: Incompatible types (expression has type "Dict[str, Dict[str, Dict[str, str]]]", TypedDict item "requests" has type "List[_Request]")

Getting a static error like this is a lot easier than having a typo in my server API call that results in a (possibly cryptic) runtime error.

My experience is that using the **kwargs syntax generally makes it harder to enforce good typing, so I tend to avoid it.


Finding the longest substring in common with two large strings

One big problem is that when you reach the longest common sequence and are ready to return, you re-run the previous iteration twice. Variables are your friends:

def find_longest(string1, string2):
    longest_seq = None

    for i in range(1, min(len(string1), len(string2))):
        # Store the current iteration's intersection
        current_seq = intersects(string1, string2, i)

        # If this was one character too long, return.
        # Else, a longer intersection was found. Store it.
        if current_seq == None:
            return longest_seq, i-1
        else:
            longest_seq = current_seq

    # If we get here, the strings were the same.
    # For consistency, return longest_seq and its length.
    return longest_seq, len(longest_seq)

By adding in the two variables, we were able to remove the if-statement at the beginning and now only have to call intersects() once in the for-loop.

Also, take a look at PEP8, the official Python style guide. It will help you fit Pythonic conventions more closely.

If you wanted to use a more complex, and quite possibly faster, solution, take a look into implementing a binary search algorithm. They provide search times that are very efficient for large data sets.


Wrapping a character code for a Caesar Cipher

Your solutions have subtle off-by-one errors. Your second solution partially fixes these by adding 1 to the result in some cases, but it doesn't fix the real problem, which is this:

(let [,,,
      code-range (- max-code min-code)]
  ,,,)

code-range needs to hold the number of integers from 32 to 126, inclusive. As Dijkstra famously noted, calculating this number is easy when you're using an inclusive-exclusive range, but when your range is inclusive on both ends, you need to account for that by adding 1:

(let [,,,
      code-range (- (inc max-code) min-code)]
  ,,,)

In response to your questions about repetition and performance: there's a function for that! Unlike rem, Clojure's mod function always returns a nonnegative value, so you can do this:

(defn wrap-shifted-code [char-code]
  (let [min-code 32
        max-code 126
        code-range (- (inc max-code) min-code)]
    (-> char-code (- min-code) (mod code-range) (+ min-code))))


The short answer is that you can't, not really anyways. You have no real control over how this code will be compiled. Since you mention iPad, the code is likely to be JIT-compiled to bytecode, prior to execution. How this is done depends (in part) on how the code is written, and how JS is implemented. The second factor, the implementation, is beyond your control.

You're also working with a canvas element. That's not JS that causes the bottleneck there, that's the DOM, which is gouverned by W3C, and is not part of ECMAScript in any way. JS merely has an API, via which it can request the DOM to change state. The DOM API isn't all that good: it's badly designed, slow, counter intuitive and one of the main reasons why many people claim JS is a terrible language. JS isn't, it's the DOM. But I'm going off course.

Inside that loop, which repeats 3600 times, you're calling a function which isn't part of your post (perhaps provide the source for that). But my guess is, that this function interacts with the dom (perhaps moves something about). If so: request a repaint, using the requestAnimationFrame method, it makes a huge difference!

After that, to further optimize your code, use jslint. As the page says, it will hurt your feelings, but it's the best way to teach yourself some good practices, like not declaring 10001 vars seperatly, but using:

var i, j, another = 123, someArray = [], andAnObject = {};

The main bottleneck, however is putImageData. this JSPerf demonstrates an alternative, up to x5000 more performant alternative!
It uses a neat little trick to buffer the states: it draws from one canvas onto the other, which is a lot faster. As is loading the image, then using:

drawing_board_canvas_twod.getContext('2d').drawImage(image_data, pencil_begin_x, pencil_begin_y);

But the way the image_data is gotten in your code still relies on the horrid getImageData, which is outpaced even by getting the img data pixel-by-pixed. Perhaps refer to this question on StackOverflow and all linked pages for details...

For now, the next to last thing I'd suggest is: look into how you call this repeat function of yours. If it's called in response to an event, check to see if you can't, perhaps, delegate that event, eliminating any excess event listeners is always good for performance. Are you using libs like jQuery? Get rid of them if you can, because they are slower than VanillaJS, if you know how to write good vanillaJS, of course.

The last, but certainly not least important thing I'd suggest: never ever use globals. Globals are risky, slow, and make for hellish debugging: your code relies on global variables, because the repeat function starts of with:

if(device_type==0)

device_type is not declared in the scope of repeat, so that implies it being a global variable. Learn about closures, scopes and how to use them. It's what makes JS worth your while.


Changing the view based on these if/else statements

First step, remove that first else

if (typeof response !== 'string') {
    mode = edit;
} else if (status.indexOf('Completed') !== -1) {
    mode = display;
} else if ((stage <= isEditable) && (code == 0 || code == 2)) {
    mode = edit;
} else {
    mode = display;
}

After this, your text and your code dont look the same to me... you need better variables or having methods:

var noResponse = typeof response !== 'string';
var statusIsNotCompleted = status.indexOf('Completed') !== -1;
var stageIsEditable = (stage <= isEditable) && (code == 0 || code == 2);
if (noResponse) {
    mode = edit;
} else if (statusIsNotCompleted) {
    mode = display;
} else if (stageIsEditable) {
    mode = edit;
} else {
    mode = display;
}

After this, is there an option in real life where putting else if (stageIsEditable) before else if (statusIsNotCompleted) make something not work? Otherwise, you could join them in a variable:

var yourThingIsEditable = noResponse ||  stageIsEditable;


Loading the resource identified by a script element's src attribute

The code looks well-formed. I'd like some comments though and maybe a bit of whitespace here and there.

However, I think there's a good chance this will actually fail. readystatechange fires several times during the lifetime of an XHR object. But your code doesn't actually check the XHR object's readyState, which is what the event is there to tell you about.

Instead it checks responseText, but if the file is large enough to fire several events during its download, responseText may only hold partial data. So responseText is truthy, and hasRun is set to true, but the code won't ever get the complete data.

There's are 5 distinct readyState values. You should be checking for the DONE state only.

Alternatively, for some (most, I believe) browsers you can simply hook your functions to onload, onerror and friends instead of of the general onreadystatechange.

You may also want to check the arguments: Does node exist? Is listener a function?

Lastly, how do you handle failures? A 404 will still give you responseText, just not anything useful. A simple solution would be something like Node.js's callback pattern, of having the listener receive 2 arguments: err and data. If err is truthy, something went wrong. You also want to simply pass the XHR object along as the 3rd argument, so the listener can make whatever checks it wants to (much like jQuery does).

function asyncGetContents(node, listener) {
  var xhr;

  // Example of handling a bad node argument
  // Adapt it to fit your needs
  if(!node) {
    throw new TypeError;
  }

  // Example of handling a bad listener argument
  // Adapt it to fit your needs
  if(typeof listener !== 'function') {
    throw new TypeError;
  }

  if(node.src) {
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      // check readyState
      if(xhr.readyState === XMLHttpRequest.DONE) {
        // check that the response code is 2xx
        if(xhr.status >= 200 && xhr.status < 300) {
          listener(null, xhr.responseText, xhr);
        } else {
          listener(xhr.status, null, xhr); // Provide a more useful error here
        }
      }
    };

    xhr.open('GET', node.src);
    if(node.type) {
      xhr.overrideMimeType(node.type);
    }
    xhr.send();
  } else {
    // we've only checked that node is truthy, not that it's
    // actually a script element, so node.textContent may
    // be `undefined`, but let's leave that to the listener
    listener(null, node.textContent, null);
  }
}


Python algorithm that converts array-like data into MathJax

This looks like a handy tool to have around, maybe we can make it even better.

Style

As per the official Python Style Guide (often known by his nickname PEP8), keyword-arguments of functions should have no whitespace around the =.

Matrix size

numpy arrays have a property called .shape which describes their number of rows and number of cols (in case of a 2D array at least). So

self.rows = len(self.matrix)
self.cols = len(self.matrix[0])

could become

self.rows, self.cols = self.matrix.shape

Since your code only works for 2D matrices, it's maybe also a good idea to check for that. The .ndim attribute can be of help here.

Type checking

type(matrix[0]) in (str,int,float) should instead be isinstance(matrix[0], (str, int, float)).

Checking None

The official recommendation is to always use if sth is None: when checking for None.

String joining

row = [str(x) for x in row]
body += ' & '.join(row) + '\\\\' + '\n'

could be done in a single line:

body += ' & '.join(str(x) for x in row) + '\\\\' + '\n'

This means you also don't have to reassign row to be something different than it was before.

String formatting

Since you said you're using Python 3.6, maybe have a look at f-strings for even more concise string formatting syntax. No matter if you choose to do this, maybe at least get rid of the old-style % formatting in augmented(...) by escaping { and } using a leading \.

Function output

I find it preferable if you'd let the user decide what he wants to do with what your function returns. So instead of printing and copying the formatted matrix code, maybe just return body and let the caller decide how to proceed from here. You could even define a "convenience" function (to_clipboard) that basically only does pyperclip.copy(...), although this is likely not necessary. Another idea would be to make at least the copy part opt-in via a "flag" bool parameter.

Class

Maybe a class is not the right tool here. A possible alternative would be to move what's done in __init__ into a "private" (read name starts with _) helper function and get rid of the class.

Missing backslash

There seems to be a little bug in both of your functions (see how bad code duplication is ;-)): body +='\end ... is likely missing an additional \.

Unused argument

If I'm not mistaken, the choosen_brackets argument of augmented is not used in the function.

Typo

choosen_brackets should likely be chosen_brackets


From a once over:

oneRoot and twoRoot are only needed in their respective if block, you should move the var statements to those if blocks.
This:

if(twodigit == 10) {
    lastURL = twoRoot + "9/";
    nextURL = twoRoot + "11/";
} else {
    lastURL = twoRoot + (twodigit - 1) + "/";
    nextURL = twoRoot + (twodigit + 1) + "/";
}

could simply be

    lastURL = twoRoot + (twodigit - 1) + "/";
    nextURL = twoRoot + (twodigit + 1) + "/";

I am not sure why you needed to call out the (twodigit == 10 case
urlData <- Not sure what this does at all
var oneslash = currentURL.substr(currentURL.length - 2); <- You are not using this
onedigit = oneslash.substr(0,1)*1; <- You already captured this in lastChar, you could simply do onedigit = +lastChar;
You have 0 comments..
You did not declare onedigit with var
You have some indentation trouble towards the end of your code.

I have something like this: ( also on http://jsfiddle.net/konijn_gmail_com/unQQ7/ )

function linkSet() {
    var currentURL = location.href;
    var lastURL = "";
    var nextURL = "";
    var lastChar = currentURL.charAt(currentURL.length - 2);
    var secondLastChar = currentURL.charAt(currentURL.length - 3);

    if(isNaN(lastChar) === true) {
        //Hide left button, hard code right button to go to ../2
        var leftContain = document.getElementById('leftcontainer');
        var rightContain = document.getElementById('rightcontainer');
        leftContain.style.display = "none";
        rightContain.style.width = "100%";
        rightContain.style.float = "none";
        lastURL = currentURL;
        nextURL = currentURL + "2/";
    } else if(isNaN(secondLastChar) === false) {
        //The page number is a double digit, simply derive last/next
        var twoRoot = currentURL.slice(0, -3);
        var twoSlash = currentURL.substr(currentURL.length - 3);
        var twoDigit = twoSlash.substr(0, 2) * 1;
        lastURL = twoRoot + (twoDigit - 1) + "/";
        nextURL = twoRoot + (twoDigit + 1) + "/";
   } else {
       //The page number is single digit, with a special case for page 2
        var oneRoot = currentURL.slice(0, -2);
        var oneDigit = +lastChar;
        if(onedigit == 2) {
            lastURL = oneRoot;
            nextURL = oneRoot + "3/";
        } else {
            lastURL = oneRoot + (oneDigit - 1) + "/";
            nextURL = oneRoot + (oneDigit + 1) + "/";
        }
    }
    document.getElementById("lastlink").href = lastURL;
    document.getElementById("nextlink").href = nextURL;
}

If I had to write the code for a personal project, I would not distinguish between 1 char and 2 chars ( what if there are over a thousands pages ? ), I would just get the number from the URL and build the buttons from that. The code in that case would be easier to follow as well (to me at least). ( http://jsfiddle.net/konijn_gmail_com/xNQ7m/ )

function hideLeftButton() {
    var leftContain = document.getElementById('leftcontainer');
    var rightContain = document.getElementById('rightcontainer');
    leftContain.style.display = 'none';
    rightContain.style.width = '100%';
    rightContain.style.float = 'none';
}

function linkSet() {
    var currentURL = location.href,
        parts = currentURL.split('/'),
        lastURL, nextURL;

    //Get rid of "" ( because URL ends with / )
    parts.pop();
    //Next part of the URL is the number ( or not )
    number = parts.pop();
    //Build up the root to append numbers to
    var root = parts.join('/') + '/';

    if (isNaN(number) === true) {
        hideLeftButton()
        lastURL = currentURL;
        nextURL = currentURL + '2/';
    } else if (number == 2) {
        lastURL = root;
        nextURL = root + '3/';
    } else {
        lastURL = root + (+number - 1) + '/';
        nextURL = root + (+number + 1) + '/';
    }
    document.getElementById('lastlink').href = lastURL;
    document.getElementById('nextlink').href = nextURL;
}


Searching for a substring in a ring queue

There were few bugs in the function.
1. pStr should point to the start of the buffer once it reaches the end of the buffer.
2. A flag should be set when a character matches and unset the flag when next coming character doesn't match.
Here the modified version that I believe is correct:

bool Buffer::contains(const char *pcSubstr){

const char *pcCurrentSubstr = pcSubstr;
const char *pStr = buffer + head;
bool seen = false;
for (; *pStr != 0 && *pcCurrentSubstr != 0; ++pStr){
    if(pStr == (buffer + MAX_BUFFER_SIZE)){
        pStr = buffer;
    }
    if(*pStr != *pcCurrentSubstr){
        pcCurrentSubstr = pcSubstr;
        if(seen){
            --pStr;
        }
        seen = false;
        continue;
    }
    seen = true;
    ++pcCurrentSubstr;
}
return (*pcCurrentSubstr == 0);
}


@flornquake points at the good direction (use string and collections.Counter) but I'd still modify some details:

alphabet = alphabet[:26] and text = text.lower(): My advice is not to override existing variables with new values, it makes code harder to understand. Use different names.
if char in alphabet: Make sure you perform inclusion predicates with hashes, sets or similar data structures, not lists/arrays. O(1) vs O(n).
Functions should return values (hopefully related with their name). Here it makes sense to return the counter.

I'd write:

import collections
import string

def count_letters(filename, case_sensitive=False):
    with open(filename, 'r') as f:
        original_text = f.read()
    if case_sensitive:
        alphabet = string.ascii_letters
        text = original_text
    else:
        alphabet = string.ascii_lowercase
        text = original_text.lower()
    alphabet_set = set(alphabet)
    counts = collections.Counter(c for c in text if c in alphabet_set)

    for letter in alphabet:
        print(letter, counts[letter])
    print("total:", sum(counts.values()))

    return counts


Disclaimer: I know nothing about Frege, all comments apply to Haskell only.

1)

Running hlint on your code shows places where you can remove $ and brackets. Please do it!

2)

In exec, you always do exec prog tape after finishing current instruction. So you are iterating the list in some sense. This is a fold.

exec :: [Op] -> Tape -> IO Tape
exec prog tape = foldM f tape prog

  where f (Tape ls c rs) Plus    = return $ Tape ls (c+1) rs
        f (Tape ls c rs) Minus   = return $ Tape ls (c-1) rs
        f (Tape ls c rs) GoLeft  = let (hd, tl) = uncons ls in return $ Tape tl hd (c:rs)
        f (Tape ls c rs) GoRight = let (hd, tl) = uncons rs in return $ Tape (c:ls) hd tl
        f tape           Output  = printAsChar (cell tape) >> return tape
        f (Tape ls _ rs) Input   = do n <- getChar
                                      return $ Tape ls (digitToInt n) rs

        f tape again@(Loop loop) | cell tape == 0 -> return tape
                                 | otherwise -> do tape' <- exec loop tape
                                                   f tape' again

3)

printAsChar i = putStr $ [chr i]

hlint will tell you the $ is redundant:

printAsChar i = putStr [chr i]

You can use putChar:

printAsChar i = putChar (chr i)

and finally get:

printAsChar =  putChar . chr

You have a strange asymmetry - output uses chr, and input digitToInt. These are not inverses! digitToInt '0' is 0, but chr 0 is '\NUL', not '0'.

If you want to output numbers longer than 1 character, use

printAsString = putStr . show

4)

I would merge execute and exec:

 execute :: [Op] -> IO Tape
 execute = foldM f (Tape [] 0 [])
   where f = ...

5)

 putStrLn $ "\n" ++ show tape ++ "\n"

putStrLn already adds '\n" to the end, you might remove it.

6)

If you remove the requirement to print the tape (is it needed for debugging only?), you can use an infinite list:

 execute = foldM f (Tape (repeat 0) 0 (repeat 0))

and get rid of uncons:

       f (Tape (hd:tl) c rs) GoLeft  = return $ Tape tl hd (c:rs)
       f (Tape ls c (hd:tl)) GoRight = return $ Tape (c:ls) hd tl


Rather than a global Trie object I would make a TrieNode object that inherits from dict.

This can inherit from dict.
This can overload __missing__ to simplify insert.
Search isn't needed in the way I used it.

Make a function build_trie, that builds and populates the trie from "en-dict.txt".
build_board should really be called main and the code that builds the board should be moved into it's own function.
find_words should be moved into main.
build_trie should be called from main and passed to where it needs to be used.

When possible don't use global. If you think it's impossible, then you're likely wrong.

In this case you can move the value out of the function into main and pass it where it's needed.

In other cases using a class, a closure or other ways can solve the issue.
dictionary_check should only display words. And the first part of the function can be removed with the new TrieNode.
Move next_move out of words_from, just make it a global constant.
board[row][column] != "-" relies on mutating board I would recommend not mutating input to functions.
words_from can be simplified by passing the current node, as then you're not trie.searching.
In words_from len(new_string) >= 3 is an artificial limitation, that should be moved out of the function.
get_permutations can be simplified by changing words_from to return an empty list on bad input.
I would move set_permutations out of get_permutations, as it doesn't have much purpose in that function.
I merged words_from and set_permutations to use a while loop, I found this to make the code easier to understand and make.
Don't print and return, use raise.

For the most part your code seems to be fairly good, there's some pitfalls your falling down. But on a micro - line by line - scale your code is pretty good.

The problem I saw with your code is not seeing the big picture, and not following SRP.

Improving SRP should be fairly easy for you. If you're thinking of putting a comment that says the code is performing a different task, move it into a function.

To help with the big picture, when you follow SRP think to yourself if you should split the code into 2/3 functions and should call the three functions in succession. Like I changed main to do.

class TrieNode(dict):
    def __init__(self, value=None):
        super().__init__()
        self.value = value

    def __missing__(self, key):
        value = TrieNode()
        self[key] = value
        return value

    def insert(self, word):
        current = self
        for char in word:
            current = current[char]
        current.value = word

def build_trie():
    trie = TrieNode()
    with open("en-dict.txt", "r", encoding="utf8") as file:
        for line in file:
            trie.insert(line.strip())
    return trie

def board_from_string(string):
    if len(string) != 16:
        raise ValueError("Must enter 4*4 grid (16 characters)")
    return [
        [*string[0:4]],
        [*string[4:8]],
        [*string[8:12]],
        [*string[12:16]]
    ]

AROUND = [
    (dx, dy)
    for dx in range(-1, 2)
    for dy in range(-1, 2)
    if not (dx == dy == 0)
]

def get_words(trie, board):
    stack = []
    for row in range(4):
        for column in range(4):
            stack.append((trie, row, column, set()))
    while stack:
        node, row, column, parents = stack.pop()
        if row in (4, -1) or column in (4, -1) or (row, column) in parents:
            continue
        char = board[row][column]
        if char not in node:
            continue
        node = node[char]
        if node.value is not None:
            yield node.value
        for dx, dy in AROUND:
            stack.append((node, row + dx, column + dy, parents | {(row, column)}))

def display(words):
    words = sorted({w for w in words if len(w) >= 3})
    print('\n'.join(words))
    print(f"======\n{len(words)} words")

def main():
    string = "playthiswordgame"
    trie = build_trie()
    board = board_from_string(string)
    words = get_words(trie, board)
    display(words)

if __name__ == "__main__":
    main()


C - Improving (really) big number addition

Function Error

What is myResult[0] when carry == 0?

if (carry) myResult[0] = '1';

Improvements

As code is not changing the the contents of the string, use const for potential compiler optimization and clarity to reviewers that code is in fact not changing the characters.

// char * addStrings(char* string1, char* string2)
char * addStrings(const char* string1, const char* string2)

Code that allocates memory should clearly say that as a comment and/or function name.

// Returns an allocated string representing the sum of ....
char * addStrings(
// or
char * addStrings_alloc(

Really big strings can exceed length INT_MAX.  Use size_t for indexing arrays and string lengths.  size_t is the return type of strlen().

// int maxSize =  strlen(maxString);
size_t maxSize =  strlen(maxString);

// int i = maxSize - 1;
// for (; i >= 0; i--) {
size_t i;
for (i = maxSize; i > 0; ) {
  i--;

Check the return value of malloc()

char * myResult = malloc(maxSize + 2);
if (myResult == NULL) return NULL;

No need for carry to besize_t`.

// size_t carry = 0;
int carry = 0;

No provision for - numbers. (or ones with a leading '+')
No provision for trimming leads '0' in answer with input like addStrings("007", "007")
No provision for non-digits as in addStrings("x", "007")
Simplification

   // x = maxString[i] - '0';
   // if (carry) x++;
   x = maxString[i] - '0' + carry;

Below processing should have happened in the function.

  // Removing the initial space allocated by storage if we didn't overflow
  ... (result[0] == ' ') ? result + 1 : result)

Minor

Nomenclature.  size is the size need for the array.  length is the length of the string (not counting the null character).  Suggest maxLength.

// int maxSize =  strlen(maxString);
int maxLength =  strlen(maxString);

Why the comment? Seems unneeded  // Avoid -std=c99 flag
No provision for NULL input  addStrings(NULL, "007") - but then NULL is not a valid string.  For an interview question, I'd at least suggest that inputs may need sanitizing before use.
Style: Even single if() are easier to debug/maintain with {}

// if (carry) myResult[0] = '1';
if (carry)  {
  myResult[0] = '1';
}

Test driver simplification.  free(NULL) is OK.

// if (result) {
//  free(result);
//  return 0;
//}
free(result);

Test driver function error - off by 1

// if (argc < 2) {
if (argc < 3) {
// or better
if (argc != 3) {

I'd expect code to be tested and give a reasonable (or a least defined) result with addStrings("", "7") and addStrings("", "")


Taking 2 command line inputs and verifying that they are integers, within the correct range of values

This is unrelated to performance, but it may still be helpful in general:

You should print those errors to stderr via fprintf():

fprintf(stderr, "Warning: Check number of arguments.\n");

fprintf(stderr, "Warning: Please enter a valid integer.\n");

fprintf(stderr, "Warning: Bad input.\n");

Are you using a pre-C99 version of C?  If not, you should be initializing the loop counter variables within the loop conditions, not outside of them.
It's common to provide the types of expected arguments (starting with whatever gets printed from argv[0]) if this check fails. You could also specify the number of expected arguments so that the user isn't left guessing, in case the objective isn't already clear.

fprintf(stderr, "Warning: Check number of arguments (must be 2).\n");

You shouldn't try to do everything in main(), and it doesn't look like those checks after the arguments check belong there.

Instead, consider providing separate functions for both that get called from main(). They can return a boolean value and, if it's an erroneous one, the program can then terminate from main().
If I'm not mistaken, the for loop is supposed to check both argv[1] and argv[2] for valid data types.

If so, you could either:

Do two separate checks without a loop (to maybe make it a little more cleaner)
If you may consider expanding it for additional arguments, use argc as part of the outer loop sentinel value instead of hard-coding the 2 (which could be seen as a "magic number" instead anyway)


Normalization, division and reshaping processes on an HDF5 file

It seems that all your code could be vectorized with the help of numpy broadcasting.

At first, instead of using all these norm_vec[:, ...] = ... you could create two vectors of length 17 containing values you use to normalize the data.

I assume normalizing values to be mean and standard deviation (please tell me if I'm wrong), so I'll be calling them mean and std correspondingly.

mean is a np.ndarray with values [-3.059, -1.5707, ..., -0.05] and std is a np.ndarray with values [6.117, 3.6647, ..., 2.67] (indicies ranging from zero to 16).

Using this notation, for loop could be rewritten:

for j in range(len(hdf5_file["vector"])):

        norm_vec = (hdf5_file["vector"][j] - mean) / std

        reshaped_vec = norm_vec.reshape(500 * 17)
        jointMatrix = np.vstack((jointMatrix, reshaped_vec))

This should give a certain speed-up. However, the code could be further optimized by vectorizing the loop itself.

The whole code now looks like this:

def pre_proc_data():

    hdf5_file = h5py.File("/home/Data.hdf5")
    norm_vec = (hdf5_file["vector"] - mean) / std
    # from 3d to 2d
    return norm_vec.reshape(-1, 500 * 17)

jointMatrix = pre_proc_data()


Project Euler 8 - Largest product in a series

I think your current code is working- it seems like it’s getting the same answer as other people who say they solved it (i.e. 23514624000). So I think it belongs here.
Right now, if you wanted to use this for any string of digits and any length of consecutive numbers, it would be \$O(n^2)\$ time complexity because you would have to multiply at most (length-of-series / 2) * (length-of-series / 2) numbers. Something you could use to fix that is a deque from the collections module. You could use it to know what to divide and what to multiply to get the current product, and you could also use it to track how many zeros are in the current sequence of consecutive numbers. If you do this then you only need to multiply or divide at most (length-of-series * 2) - 1 numbers, so it’s \$O(n)\$.
import collections

def find_max_prod(n, series):

    if len(series) < n:
        return 0

    current_nums = collections.deque(maxlen=n)
    zero_count = 0
    max_prod = 1
    my_iter = iter(series)

    for _ in range(n):
        next_n = int(next(my_iter))
        max_prod *= next_n
        current_nums.append(next_n)
        if next_n == 0:
            zero_count += 1

    current_prod = max_prod if max_prod > 0 else 1

    for str_n in my_iter:
        n_out = current_nums.popleft()
        n_in = int(str_n)
        current_nums.append(n_in)
        if n_in == 0:
            zero_count += 1
        if n_out == 0:
            zero_count -= 1
        else:
            current_prod //= n_out
        if n_in != 0:
            current_prod *= n_in
            if current_prod > max_prod and zero_count == 0:
                max_prod = current_prod

    return max_prod

or with Toby Speight‘s suggestion:
import collections

def max_of_substr(n, substr):
    current_nums = collections.deque(maxlen=n)
    my_iter = iter(substr)
    max_prod = 1

    for _ in range(n):
        next_n = int(next(my_iter))
        max_prod *= next_n
        current_nums.append(next_n)

    current_prod = max_prod

    for str_n in my_iter:
        n_out = current_nums.popleft()
        n_in = int(str_n)
        current_nums.append(n_in)
        current_prod //= n_out
        current_prod *= n_in
        if current_prod > max_prod:
            max_prod = current_prod

    return max_prod

def find_max_prod(n, series):
    max_substr_generator = (
        max_of_substr(n, substr)
        for substr in series.split('0')
        if len(substr) >= n
        )
    return max(max_substr_generator, default=0)


Haskell has a great package for testing performance called Criterion. When you're trying to compare the performance between variations of the same function, head right for it.

Here's a small example with a few other versions of primeCands I dreamed up.

module Main where

import Criterion
import Criterion.Main

import Data.Ratio

primeCands_cmap :: [Integer]
primeCands_cmap = concatMap (\i -> [6*i-1, 6*i+1]) [1..]

dropThirds :: [a] -> [a]
dropThirds (a:b:_:ds) = a : b : dropThirds ds
dropThirds xs         = xs

primeCands_dropOdds :: [Integer]
primeCands_dropOdds = dropThirds [5,7..]

interleave :: [a] -> [a] -> [a]
interleave (a:as) (b:bs) = a : b : interleave as bs
interleave as     bs     = as ++ bs

primeCands_interleave :: [Integer]
primeCands_interleave = interleave [5,11..] [7,13..]

primeCands_allOdds :: [Integer]
primeCands_allOdds = [5,7..]

main :: IO ()
main = defaultMain [
         bgroup "prime candidates"
                   [ bench "concatMap"  $ nf distantElement primeCands_cmap
                   , bench "dropThirds" $ nf distantElement primeCands_dropOdds
                   , bench "interleave" $ nf distantElement primeCands_interleave
                   ]
       , bgroup "odds" [ bench "odds" $ nf furtherElement primeCands_allOdds ]
                   ]
  where
    index = 1000000
    distantElement = (!! index)
    furtherElement = (!! (ceiling $ (fromIntegral index) * (4 % 3)))

And the results of the criterion benchmark (compiling with -O2)—

benchmarking prime candidates/concatMap
time                 6.918 ms   (6.631 ms .. 7.160 ms)
                     0.995 R²   (0.992 R² .. 0.999 R²)
mean                 6.668 ms   (6.615 ms .. 6.753 ms)
std dev              193.5 μs   (107.1 μs .. 297.1 μs)
variance introduced by outliers: 10% (moderately inflated)

benchmarking prime candidates/dropThirds
time                 4.548 ms   (4.463 ms .. 4.639 ms)
                     0.996 R²   (0.993 R² .. 0.998 R²)
mean                 4.488 ms   (4.430 ms .. 4.546 ms)
std dev              183.5 μs   (153.8 μs .. 216.7 μs)
variance introduced by outliers: 22% (moderately inflated)

benchmarking prime candidates/interleave
time                 4.100 ms   (4.030 ms .. 4.172 ms)
                     0.996 R²   (0.993 R² .. 0.998 R²)
mean                 4.484 ms   (4.399 ms .. 4.558 ms)
std dev              241.0 μs   (215.5 μs .. 271.9 μs)
variance introduced by outliers: 31% (moderately inflated)

benchmarking odds/odds
time                 5.529 ms   (5.500 ms .. 5.568 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 5.521 ms   (5.506 ms .. 5.546 ms)
std dev              54.27 μs   (34.21 μs .. 93.68 μs)

In this case you can see that the concatMap version runs a bit slower (about ⅓) than the versions that don't flatten lists. I question whether you are prematurely optimizing however, I would imagine that the slight difference in prime candidate generation timings are dwarfed by the actual prime checking function you've written.


Optimization notes.

Allocate the temporary array once, and pass it down to the recursive invocations.

 Do not fall back to the insertion sort immediately. Postpone it until all the recursions complete, and insertion sort the entire array once.
It feels scary to insertion sort the entire array. Wouldn't it degrade performance to \$O(n^2)\$? The answer is no. The array is already "almost sorted": every element is at most OPTIMIZED away from its final destination. Therefore, an inner loop does at most OPTIMIZED iterations per element, and the overall complexity is \$O(n * \texttt{OPTIMIZED})\$. This observation also hints that OPTIMIZED should be in a ballpark of \$\log n\$.
Edit: I don't know what I was thinking. The above is totally wrong (it is valid for quicksort, but not here), except the observation that OPTIMIZED should be in a ballpark of \$\log n\$.

A little-known trick allows to cut the number of comparisons in the insertion sort in half. Instead of
  while (j >= left && arr[j] > key)

consider first comparing key to arr[left]:
  if (key < arr[left]) {
      // The key shall land at the left. No need to compare values anymore
      for (j = i; j > 0; j--) {
          arr[j] = arr[j-1];
      }
  } else {
      // arr[left] is a natural sentinel. No need to compare indices anymore
      for (j = i; arr[j] > key; j--) {
          arr[j] = arr[j-1];
      }
  }

Now if you opt for a postponed insertion sort, it could be optimized even more: find the min among first OPTIMIZED elements and swap it with arr[0]. Now there is no need to test for key < arr[left] - it is guaranteed to fail. Go straight into the unguarded loop.


Given an array of N elements, answer Q queries asking if there exist two elements from two specified range with a given XOR value

Avoid non-standard headers. Especially giant composite-headers like <bits/stdc++.h>. They make your program unportable and/or  slow compilation down.
You are using using namespace std;.
That's a bad idea, read "Why is “using namespace std;” considered bad practice?".
Aside from its obscuring impact if you ever used the typedefs, vi and ll are unused. Remove to minimize confusion.
Do you know std::unordered_set? That's better for representing a set than std::unordered_map...
Anyway, you should change the algorithm but we'll get there later.
You should consider whether swapping the ranges can speed things up.
The conditional operator (ternary operator, exp ? true_exp : false_epp) is perfect for choosing the value to use.
You never check for input-failure or inputs being out-of-range.

Now the algorithm:

Consider initializing a std::unordered_multimap, or if duplicates are plentiful a std::unordered_map of sorted std::vector from the input-array.
Then for each query check every element in the smaller range whether element xor x is in the whole array, and filter that down to the second range.


The following workaround will wrap your keys and values with double quotes.  Such hacks will always be vulnerable to edge cases.  To avoid sprinting down a rabbit hole of possibilities (I can think of a few cases off the top of my head -- 1. keys/values already containing quotes 2. declared empty/null keys ...there will be more), I'll just provide a solution for your sample input.

For now, I'm using \w to ensure that the space before bar is not included.  There are several ways to do this action, but I would need to have intimate knowledge of your project data to develop the expression that I feel is "best / most robust".

If you discover any fringe cases that break this simple regex pattern, please update your question and I can create a patch.

Code: (Demo)

$unquoted_json = <<<NOTJSON
{foo:{qux:1,quux:0}, bar:{}}
NOTJSON;

$quoted_json = preg_replace('~\w[^:{},]*~', '"$0"', $unquoted_json);
$array = json_decode($quoted_json, true);
var_export($array);
echo "\n---\n";
echo json_encode($array);

Output:

array (
  'foo' =>
  array (
    'qux' => '1',
    'quux' => '0',
  ),
  'bar' =>
  array (
  ),
)
---
{"foo":{"qux":"1","quux":"0"},"bar":[]}


Some improvements:

Use of refresh() as a function used to generate the number values, which generate the values AND writes into the DOM element.

Use of a function to manage all user messages, write_message()

Remove of all the old fashion HTML tags, and change it for CSS.

A function for managing spending the "credits" to make it easier to manage them.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>www.loseloselose.com</title>

    Lucky Number Slots

    <svg width="550" height="250" viewBox="0 0 1600 500">

    <rect x="0" y="10" width="500" height="500" fill="black" stroke="white" stroke-width="10">
    </rect>

    <rect x="550" y="10" width="500" height="500" fill="black" stroke="white" stroke-width="10">
    </rect>

    <rect x="1100" y="10" width="500" height="500" fill="black" stroke="white" stroke-width="10">
    </rect>

    <text x="100" y="415" font-family="courier" font-size="500" fill="white" id="first">
    0
    </text>

    <text x="650" y="415" font-family="courier" font-size="500" fill="white" id ="second">
    0
    </text>

    <text x="1200" y="415" font-family="courier" font-size="500" fill="white" id="third">
    0
    </text>
    </svg>

    <input type="button" value="Click Here To Spin" onClick="refresh()">

    Add Credit

0


Finding nth lowest value without any Math max or min methods

I decided to make a more efficient solution to a Google interview question

The purpose of such interview questions is to get signal as to whether you understand asymptotic efficiency or not; your answer indicates you do not. It will also be looking for signal as to whether you understand the asymptotic performance characteristics of various data structures.

sort is O(n lg n) time complexity in the typical case, but max and min can be implemented in O(n) time complexity; whether you can recognize that or not, and write the code accordingly, is the test.

  I believe it is more efficient because you can use my method to find any nth lowest value in the array so it solves for all cases.

That's not the sort of "efficiency" they're looking for. The question they're asking is not "can you solve a more general problem, and therefore be more efficient in terms of lines of code written per problem solved?"  The question they are asking is "can you find the algorithm that makes more efficient use of machine resources?".

If you wanted to use this solution in a Google-style interview and impress the interviewers, what you need to do is to make the argument that your sorting solution is more efficient in terms of amortized costs.

Exercise: under what circumstances is the amortized cost of the "least n" query on an arbitrary unsorted array lower if you spend the time sorting the array once?

  Please let me know if there is anything I can do to improve this solution

Google-style interviewers will be looking primarily for signal as to whether you can write correct code, and provide test cases and logical arguments that demonstrate its correctness. Summing up:

You haven't found a correct solution.
You haven't made any argument for correctness.
You have provided a single test case.
You haven't found the asymptotically efficient solution.

This would be an easy "no hire" for a Google interviewer.

So, this gives you some things to concentrate on:

Solve the problem that was posed; if you feel the need to solve a more general problem, say why.
Have a good working understanding of asymptotic performance; I do not expect candidates to be able to rattle off the Master Theorem (I have had a grand total of one candidate in 20 years do so, and they did it wrong) but I do expect candidates to be able to tell me if an algorithm is sublinear, linear, superlinear, quadratic, exponential, and so on.
Follow good coding practices: don't mutate your inputs, for example.
Create a correct solution.
Make a cogent, clear, correct argument that explains why your solution is correct.
Provide test cases that convince the interviewer that you've thought about ways your algorithm could go wrong.


Perfect-forwarding while implementing emplace

You are using std::forward correctly. However, there are several other things worth noting about your code:

why do you need a private counter instead of re-using m_s.size() that will automatically update itself after each emplace_back()?
are you sure that you don't need additional template arguments Compare and Allocator instead of relying on their defaults std::less<T> and std::allocator<T>?
since you are using C++11 already, please use auto to get rid of the pair<itererator, bool> (and if you are using C++14, you can also use auto for the return type).
try also to write using iterator = typename std::set<T>::iterator; because left-to-right is much easier to parse than right-to-left of the current typedef.


Style

The overall reading of these methods is pretty good and the code is well structured.

The documentation is good to read and to understand.

Your style is a little bit inconsistent. It's about the using of braces {} for single statement if's . One time at the guard clause you use braces and later on for the if(throwErrors)  you don't use them.
Speaking about throwErrors, the method won't ever throw errors but one Exception so a better name could be either shouldThrowException or throwsException.

Speaking about Serialize() method
I don't like ref parameters that much and I try to avoid them if there is a better/different way to solve this.
For the Serialize() method the usage of an ref parameter could be avoided by passing a StringBuilder instead of a string as argument.
You for sure would need to check if the passed in StringBuilder is not null but you could just pass it afterwards to this overload of the Serialize() method.


Reversing a string, accurately and efficiently.

You are doing it accurately, yes. But, not very efficiently (although there are worse ways to do things).

NOTE:: Palacsint is right that you are not handling null input and surrogate-pairs in the input data. Your solution is not completely accurate. Consider this answer a discussion of the efficiency only.... though I have also updated this answer to include a solution which deals with surrogate pairs efficiently

To understand the efficiency side of things, you have to understand Java String internals.

Strings are immutable, cannot be changed.
Java is relatively slow at allocating/cleaning memory, try to avoid it.
Java can 'inline' method calls and make methods really fast.

So, the best way to make Java efficient is to create/use as little memory as possible, and still end up with a new String (instead of changing an existing string).

Your code has 1 string already, you are creating another string. You cannot avoid that.

What you can avoid though is what happens in between.

Your 'In Between'

What you are doing in between is a bit messy, and wasteful:

    char[] array = new char[s.length()];
    array = s.toCharArray();

You create a new array, then you throw it away, and replace it with the s.toCharArray()... why?

Could be just:

    char[] array = s.toCharArray();

Also, you have a loop that swaps the chars... this is implemented like:

for(int i=0; i<array.length/2; i++) {

This could be faster if you did it backwards ( could be - depending on which Java you use).

for (int i = array.length / 2; i >= 0; i--) {

This way it only has to do the array.length / 2 one time (though, as I say, some Java implementations will perhaps compile it to work out for you).

Finally, the charArrayToString() is serious overkill....

Converting to a StringBuilder then to a String is a waste of time/resources...

return charArrayToString(array);

can be

return new String(array);

EDIT: Also, as has been mentioned by Richard Miskin... and I assumed you were already using a StringBuilder .... StringBuilder is much more efficient in a single-thread situation than StringBuffer. Unless you have good reason, you always should use StringBuilder.

Efficient in-between ....

public String reverse(String s) {
    char[] array = s.toCharArray();
    char tmp;
    for(int i = (array.length - 1) / 2; i >= 0; i--) {
        tmp = array[i];
        array[i] = array[array.length-1-i];
        array[array.length-1-i] = tmp;
    }
    return new String(array);
}

Edit: a different way:

Here are some performance numbers...

String Reverse                           => 4473870 (hot 19.74881ms)
String Reverse Surrogate Aware           => 4473870 (hot 22.73488ms)
String Reverse B                         => 4473870 (hot 25.16192ms)
String Reverse StringBuilder             => 4473870 (hot 31.60709ms)
String Reverse StringBuilder NoNullCheck => 4473870 (hot 31.72952ms)
String Reverse Orig                      => 4473870 (hot 36.83827ms)

For each of those 'hot' runs, I am reversing the order of 479829 words (linux.words) (and there are 4473870 characters in the data excluding newlines).

the code I suggested above as the 'efficient in-between' does it in 20 milliseconds
based on the discussion about null and Surrogate Pairs, the following code does this 'right', and runs in 23 milliseconds:

public String reverse(final String s) {
    if (s == null) {
        return null;
    }
    final char[] array = s.toCharArray();
    char tmp;
    for(int i=array.length/2; i >= 0; i--) {
        tmp = array[i];
        array[i] = array[array.length-1-i];
        array[array.length-1-i] = tmp;
    }
    //surrogate pairs will have been swapped.
    //identify, and un-swap them.
    for (int i = 1; i < array.length; i++) {
        if (Character.isHighSurrogate(array[i]) && Character.isLowSurrogate(array[i - 1])) {
            tmp = array[i];
            array[i] = array[i - 1];
            array[i - 1] = tmp;
        }
    }
    return new String(array);
}

The following code does it in 25 milliseconds

public String reverse(String s) {
    char[] array = new char[s.length()];
    for(int i=array.length - 1, j = 0; i >= 0; i--, j++) {
        array[i] = s.charAt(j);
    }
    return new String(array);
}

@palacsint's recommendation does it in 31 milliseconds:

public static String reverse(final String str) {
    if (str == null) {
        return null;
    }
    return new StringBuilder(str).reverse().toString();
}

@palacsint's recommendation (without the null-check) does it in 31 milliseconds:

public static String reverse(final String str) {
    return new StringBuilder(str).reverse().toString();
}

Your code does it in 37milliseconds.

If you look at the code, my code creates three objects (char[] and new String() (which creates char[] as well))

The s.charAt() code also creates three objects, but has a lot of calls to String.charAt().

The @palacsint recommendation creates 4 objects (StringBuffer, StringBuffer's internal char[], String, and String's internal char[]);

That is true with and without the null-check.

Your code creates 5 objects (6 if you count the first array which is likely to be compiled out...)  : (char[] array, new StringBuffer, StringBuffer's char[], String, and String's char[])

My guess is that there is a close correlation between our times simply because it takes 5ms to create 480,000 objects on the heap, plus some overhead of actual work.


Quite nicely structured. some remarks

main() - while you have the guard and also an extra printing function there is a little mess in main(). It has got some game logic (the loop), it has got some UI (input and printing). split it into a run() function with parameters and a interactive main(). parameters to run() should be an initial board and the visualisation callback.
some non-portable OS calls - while acceptable for a test program you should think of a better solution. functions used by an importer should not depent on that. there are also patterns to throw import errors on wrong OS to give correct and immediate information.
seeding - usually shall be done once at program start only. you gave the user the chance to reproduce a board - nicely done. but what about the fallback (which btw. gives a ValueError currently)? What happens if someone imports your module and tries to generate random boards without seed? you will generate identical boards. check why, this is a very important lesson.
deepcopy - you don't need a copy, you want an empty table. this is confusing. implement something like empty_table()


Overall this looks pretty good, but there are some places where you can write more idiomatic Python. Some general comments:

More docstrings and comments would be nice. For example: what is a “domestic” URL, and why does it match com/net? Explain why the code is written this way – it will make things much easier if you have to debug/modify a program later.
Using single letter variable names is a bad habit. It’s better to use words, because they’re more descriptive and make the program easier to read. (They’re also easier to grep for later!)
The Python convention for variable names is lowercase_with_underscores, not dromedaryCase. (The exception is class names, which are PascalCase.)

Now some specific comments about your Python style:

Don’t use str as a variable name; this is the name of a builtin function. Overriding the names of the builtin functions is a bad practice, because it will cause all sorts of bugs later.
To avoid excessive indentation, I’d combine the two if statements at the end of listDomains into a single line:

if is_valid(my_str) and is_domestic(get_domain(my_str)):
     domains.add(get_domain(my_str))

Rather than doing if match: return True; else: return False in isValid and isDomestic, you can just do return match. That’s shorter, easier to read and more idiomatic.
In getDomain(), you should explain the format of the line that you’re expecting, so that I know why you’re taking the element in index 1.
In makeHostsFile, rather than having explicit open() and close() calls, the Python idiom is to use a with statement:

with open('hosts', 'w') as f:
    for domain in domains:
        f.write('0.0.0.0 {domain}\n'.format(domain))

Note also that I’ve used new-style string formatting rather than string concatenation; this is the preferred way to do this sort of construction.
I would extend the makeHostsFile function to take an optional path to the hosts file, so that this code is more portable.
Rather than doing your program at top-level, wrap it in a main() function and call as follows:

def main():
    import os
    hosts_file = 'C:/Windows/System32/drivers/etc/hosts'
    make_hosts_file(list_domains(sources), hosts_file)

if __name__ == '__main__':
    main()

The code inside main() is only executed if the script is run directly, but if you import this file from another program, it will be ignored. That makes it easier to reuse this code, because there aren’t any funny side-effects from importing it.

In terms of speed, the regexes seem pretty simple. Is there any reason you couldn’t just do

def is_valid(line):
    return ('0.0.0.0' not in line) and ('127.0.0.1' not in line)

def is_domestic(line):
    return line.endswith('.com') or line.endswith('.net')

which feels like it would probably be a lot faster?


Finding the smallest number whose digits sum to N

The program should look more like this:
public static void main(String[] args) {
    int m = askInt("Enter the value of M: ", 100, 10000),
        n = askInt("Enter the value of N: ", 1, 100);
    long solution = findSolution(m, n);
    System.out.println("Minimum number is: " + solution);
    System.out.println("Total number of digits: " + numberOfDigits(solution));
}

Notable differences:

Your program isn't object-oriented anyway, so there's no point in instantiating a and calling input() as an instance method.  (Furthermore, it's weird that input(), which is an instance method, stores its results in static variables instead of instance variables.)
There is a lot of repetition within input().  A general-purpose integer-prompting routine, used for both M and N, would be better.
m, n, and ndigit should not be static variables, as that makes them essentially global variables.  Any function in the class can alter their values as a side-effect, making your code harder to analyze — you have to read all of the code to understand any of it.
The solution needs to be a long, in case N is large. As @OleTange pointed out, if N is 99, then the solution must be at least 99999999999, which won't fit in an int. Note that brute-force enumeration is a very poor strategy for such large numbers.

Here's how I would write askInt():
static int askInt(String prompt, int min, int max) {
    int result;
    System.out.println(prompt);
    while ((result = sc.nextInt()) < min || result > max) {
        System.out.println("Invalid input, enter again: ");
    }
    return result;
}

Note that it returns a value to the caller, rather than setting some variable as a side-effect.

Assuming that we stick with your brute-force algorithm (and indeed there is a much faster way), these functions could be improved:
static int sumOfDigits(long num) {
    int sum = 0;
    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}

static int numberOfDigits(long num) {
    return (int)Math.log10(num) + 1;
}

Arithmetic is preferable to converting numbers to strings and back.  Keep in mind that the stringification process itself involves similar arithmetic operations, and therefore must be slower than arithmetic.  Dealing with strings also incurs a cost for allocating memory for them.
I've chosen num as the parameter names to avoid confusion with the N in the problem statement.

As for the solution search itself, there are two bugs:

The problem calls for the solution to be strictly greater than M.
The problem does not state that the solution should be capped at 10000.  (For example, given M = 10000 and N = 2, the solution should be 10001.)

public static long findSolution(int m, int n) {
    for (long i = m + 1; ; i++) {
        if (sumOfDigits(i) == n) {
            return i;
        }
    }
}


Global Variables

Dim sheetCount As Integer
Dim datatoFind

Global variables make the code harder to maintain, modify, and debug.  It would be better to pass the data as parameters between the sub routines.  This makes it easier to determine exactly what data is being passed into your subroutines.

Private or Public modifiers should be used instead of Dim when declaring a global variable.

Constant Expressions

Dim mainSheet As String: mainSheet = "All Programs"
Dim nameColumnStart As String: nameColumnStart = "A"
Dim startColumn As Integer: startColumn = 10 'J Column'
Dim EndColumn As Integer: EndColumn = 33 'AG Column'

The variables above should be declared as constants.

Const mainSheet As String = "All Programs"
Const nameColumnStart As String = "A"
Const startColumn As Integer = 10 'J Column'
Const EndColumn As Integer = 33 'AG Column'

namesStart and namesEnd

Why initiate the values below if you are not going to use the initial values?

Dim namesStart As Integer: namesStart = 1
Dim namesEnd As Integer: namesEnd = 200

namesStart = InputBox("Please enter start value")
namesEnd = InputBox("Please enter end value")

Consider using Application.InputBox because you can specify the type of data it returns.

Dim namesStart As Integer
Dim namesEnd As Integer
Const namesStartDefault As Integer = 1
Const namesEndDefault As Integer = 200

namesStart = Application.InputBox(Prompt:="Please enter start value", Default:=namesStartDefault, Type:=1)
namesEnd = Application.InputBox(Prompt:="Please enter end value", Default:=namesEndDefault, Type:=1)

If namesStart < namesStartDefault Then
    MsgBox "Start vaule must be greater than or equal to " & namesStartDefault, vbCritical
    Exit Sub
End If

Selecting and Activating Objects

Selecting and Activating Objects should be avoided unless absolutely necessary, watch Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset).   I would wager to bet that of the 20 minutes that it takes to run your code 19+ minutes are spent needlessly activating worksheets.

Using Application.ScreenUpdating = False would probably cut the time in half.

Function Find_Data

SpecialCells(xlLastCell) should only be used when you don't know the data structure.

lastCol isn't used.

 lastCol = ActiveCell.SpecialCells(xlLastCell).Column

vRow is never declared.  The v prefix implies a variant when it should clearly be long.

ColumnName implies a string value.  I would use CoumnIndex instead.

Refactored Code

Private Const mainSheet As String = "All Programs"

Private Sub CommandButton1_Click()
    Application.ScreenUpdating = False
    Const LastColumn = 34
    Dim namesStart As Integer
    Dim namesEnd As Integer
    Const namesStartDefault As Integer = 1
    Const namesEndDefault As Integer = 200

    namesStart = Application.InputBox(Prompt:="Please enter start value", Default:=namesStartDefault, Type:=1)
    namesEnd = Application.InputBox(Prompt:="Please enter end value", Default:=namesEndDefault, Type:=1)

    If namesStart < namesStartDefault Then
        MsgBox "Start vaule must be greater than or equal to " & namesStartDefault, vbCritical
        Exit Sub
    End If

    Dim r As Long, c As Long
    With ThisWorkbook.Worksheets(mainSheet)
        For r = namesStartDefault To namesEndDefault
            For c = 2 To LastColumn
                .Cells(r, c).Value = Find_Data(.Cells(r, 1).Value, c)
            Next
        Next
    End With

End Sub

Private Function Find_Data(ByVal EmployeeName As String, ByVal ColumnIndex As Integer) As Single
    Dim result As Single
    Dim ws As Worksheet
    Dim r As Long
    For Each ws In ThisWorkbook.Worksheets
        With ws
            If Not .Name = mainSheet Then
                For r = 2 To .Range("A" & .Rows.Count).End(xlUp).Row
                    If InStr(1, .Cells(r, 1).Value, EmployeeName, vbTextCompare) > 0 Then
                        result = result + .Cells(r, ColumnIndex).Value
                    End If
                Next
            End If
        End With
    Next
    Find_Data = result
End Function


Video playback loop using promise chaining and setTimeout

You could try something like this:
export class LoopStep {
    public onStart(): Promise<void> { // entry point
        return this.onLoop();
    }

    private onLoop(): Promise<void> {
        return this.loopAndResolve();
    }

    private loopAndResolve(): Promise<void> { // start loop
        if (this.isLooping) { // exit condition when turned to false
            this.player.setTime(this.start);
            this.player.play();
            setTimeout(() => this.loopAndResolve(), this.duration * 1000);
        } else {
            return Promise.resolve();
        }
    }
}

// Anywhere else
loopsStep.onStart().then(() => console.log('exiting loop successfully')); // OK

One of the best things of Typescript is the type safety. It's easier to keep track of the promises you're passing from one function to another if you declare them in the return type.
In your case, where you just want a cleaner way to resolve a Promise, you can use Promise.resolve();. It's pretty straightforward to use and very useful. DOCS
(Don't forget the parenthesis when calling onStart!)


Preventing duplicate submission in Rails

That can be done easily by Rails validation, and scope attribute:

# Baseline Model
validates :user_id, uniqueness: { scope: :patient_id }

That mean user_id can present many times in Baseline table, but only one can be connected to exact patient_id.


Java helper function to round a number to the specified number of decimal places

This question makes assumptions which are not supported by the actual implementations of double in Java (or most other languages).

double is a floating-point number format, which has a number of odd behaviours that simply do not support 'rounding' in a consistently accurate way.

Consider the following code:

    double d = (v * 10 + 4) / 10_000_000.0;
    double rescale = round(d, 6) * 1_000_000_000.0;

That code takes an input value v, multiplies it by 10, adds 4, and then divides it by 10 million.

Consider an input value 65. Take that, multiply by 10, and add 4, to get 654. Now, divide 654 by 10 million, to get 0.0000654.

Now, round that value to 6 decimals, and get: 0.0000650, right?

Then multiply that by 1 billion to get 65000

Unfortunately, the actual result is:

64999.999999999990000000

The reason is that 0.000065 does not exist. Sure, many things that print numbers in Java will print a rounded value for you, but any math you do will have small errors inconsistent with your expectations.

The bottom line?

Rounding floating-point numbers to any fractional value will result in occasional errors.

The solution is to keep everything as a BigDecimal number. Do not use your method unless you know what you are sacrificing.

Here is an ideone, it loops through small values until it finds one which causes errors. The first error it finds is at 65 millionths.