Shortest pathway across a snakes and ladders board (Update)

Named tuples are a good idea here. If you need to mutate the data you should instead use dataclasses.dataclass. But as there is no need here it's good.
I'd suggest changing your nodes to contain snakes, ladders, and the start and end of the board. This is as you don't need to build the empty spaces as they are only used as distances.

Since you need the distance between two nodes, then you need to calculate the distance at creation, not during the calculations.
I've simplified calculating the distance between each node. You should take into account the following special cases:

If the distance between two nodes is 12, and there is a snake or ladder halfway between them, it takes 3 rather than 2 turns to travel between the nodes.
If there are 6 snakes or ladders after a node it's impossible to pass them without visiting those nodes.

Currently you have Edge with a start, end and cost. I would suggest you instead split this into a Node with a start, end and edges. And an Edge that has a distance and a node.

It should be noted that the start and end should only be used when creating the graph. The node will then just turn into glorified list.
It should be noted that Node should be called Vertex if you want to keep with 'pure' graph theory naming.
Please ignore my implementation of Dijkstra's algorithm, it's not great. And half way I came across some hashing problems, hence the path[node[:2]] ickyness. I don't recommend you take inspiration from it - unless it's how not to code.

This means if the graph is setup, incorrectly, to have two ladders over the same space, then some bugs may appear.

All of this together can look like:

from collections import namedtuple
from dataclasses import dataclass, field
from typing import *  # Against best-practice but shhh
import math

Edge = namedtuple('Edge', 'distance node'.split())

class Node(namedtuple('Node', 'start end edges'.split())):
    def __str__(self):
        return f'{self.start} -> {self.end}'

@dataclass(order=True)
class Path:
    distance: int
    current: Node=field(compare=False)
    previous: Node=field(compare=False)

@dataclass
class Graph:
    nodes: List[Node]

    def shortest_paths(self, start: Node) -> Dict[Node, Path]:
        if start not in self.nodes:
            raise ValueError("Graph doesn't contain start node.")
        paths = {}
        queue = []
        for node in self.nodes:
            path = Path(float('inf'), node, None)
            paths[node[:2]] = path
            queue.append(path)

        paths[start[:2]].distance = 0
        queue.sort(reverse=True)
        while queue:
            node = queue.pop()
            for neighbor in node.current.edges:
                alt = node.distance + neighbor.distance
                path = paths[neighbor.node[:2]]
                if alt < path.distance:
                    path.distance = alt
                    path.previous = node
            queue.sort(reverse=True)
        return paths

    def shortest_path(self, start: Node, end: Node) -> List[Tuple[int, Node]]:
        if end not in self.nodes:
            raise ValueError("Graph doesn't contain end node.")
        paths = self.shortest_paths(start)
        node = paths[end[:2]]
        output = []
        while node is not None:
            output.append((node.distance, node.current))
            node = node.previous
        return list(reversed(output))

def build_nodes(snakes: List[Tuple[int, int]], size: int) -> List[Node]:
    return [
        Node(1, 1, []),
        Node(size, size, [])
    ] + [
        Node(start, end, [])
        for start, end in snakes
    ]

# There are some edgecases that will need to be handled.
def calculate_distance(start: Node, end: Node, nodes: List[Node]):
    distance = int(math.ceil((end.start - start.end) / 6))
    start.edges.append(Edge(distance, end))

def add_edges(nodes: List[Node]):
    for start in nodes:
        for end in nodes:
            if end.start > start.end:
                calculate_distance(start, end, nodes)

def build_graph(edges: List[Tuple[int, int]], size: int):
    nodes = build_nodes(edges, size)
    add_edges(nodes)
    start, end = nodes[:2]
    return Graph(nodes), start, end

if __name__ == '__main__':
    graph, start, end = build_graph(
        [
            (  2, 520),
            (530, 500),
            (510, 999)
        ],
        1000,
    )
    for dist, node in graph.shortest_path(start, end):
        print(dist, node)

This outputs:

0 1 -> 1
1 2 -> 520
3 530 -> 500
5 510 -> 999
6 1000 -> 1000


Not bad. Here are some suggestions:

var circularQueue = [];
var originalUnshift = circularQueue.unshift;
circularQueue.unshift = function(element) {
    if (this.length === this.MAX_LENGTH) {
        this.pop();
    }
    return originalUnshift.call(this, element);
}

I think overriding the unshift function here is an overkill here, as it's used only once. You can use a regular array in limit and define an unshift function there. Also, circularQueue won't be visible outside limit this way.

waitId = null ;
clearTimeout(waitId);

You're calling clearTimeout with null as an argument, which has no effect. You don't need to clear the timeout here anyway, it has already expired (you're inside the callback it has triggered).

function dequeue() {
    callQueue.shift()();

    if (mayProceed()) {
        return dequeue();
    }

    if (callQueue.length) {
        waitId = setTimeout(dequeue, timeToWait());
    }
}

There's a hidden do-while loop here. Since mayProceed() is known to be true when dequeue is called, this can be made a while loop:

while (mayProceed()) {
    callQueue.shift()();
}

The relation between the mayProceed() condition and the callQueue.length condition isn't obvious, which makes it hard to understand this function. It'll be easier to understand if it's obvious that the first condition is the-second-condition-and-something-else. This can be accomplished after introducing some helper functions:

function dequeue() {
    while (callsPending() && canCallNow()) {
        callQueue.shift()();
    }

    if (callsPending()) {
        waitId = setTimeout(dequeue, timeToWait());
    }
}

function limited() {
    callQueue.push(() => {
        invokeTimes.unshift(performance.now())
        fn.apply(this, arguments);
    });

It'll be simpler to just store the arguments lists in an array, instead of having an array of anonymous functions. You can update invokeTimes when you shift the callQueue in dequeue.

    if (mayProceed()) {
        return dequeue();
    }

    if (waitId === null) {
        waitId = setTimeout(dequeue, timeToWait());
    }
}

This logic is implemented in dequeue now. You can just call it.

function timeToWait() {
    var ttw = RUN_WINDOW - timeForMaxRuns();
    return ttw < 0 ? 0 : ttw;
}

The ternary expression can be replaced with Math.max(0, ttw).

limited.cancel = function() {
  clearTimeout(waitId);
};

This cancels scheduled calls to the function, but they will be performed after calling the function again. Is this intended?

The code of limit after applying these suggestions:

function limit(fn) {
    var argumentLists = [],
      invokeTimes = [],
      waitId = null;

    function dequeue() {
        while (callsPending() && canCallNow()) {
            logInvocation(performance.now());
            fn.apply(this, argumentLists.shift());
        }

        if (callsPending()) {
            waitId = setTimeout(dequeue, timeToWait());
        }
    }

    function limited() {
        argumentLists.push(arguments);
        dequeue();
    }

    limited.cancel = function() {
      clearTimeout(waitId);
    };

    return limited;

    function logInvocation(time) {
        if (invokeTimes.length === MAX_RUNS_PER_WINDOW) {
            invokeTimes.pop();
        }
        return invokeTimes.unshift(time);
    }

    function callsPending() {
        return argumentLists.length > 1;
    }

    function canCallNow() {
        return timeToWait() === 0;
    }

    function timeToWait() {
        var now = performance.now();
        var timeOfInvocation = invokeTimes[MAX_RUNS_PER_WINDOW - 1] || 0;
        var ttw = timeOfInvocation + RUN_WINDOW - now;
        return Math.max(0, ttw);
    }
}

It would be nice to make MAX_RUNS_PER_WINDOW and RUN_WINDOW arguments of limit instead of constants.


Bash script to send emails when web server does not respond

I am impressed with the consistency of your code. You have obviously put effort in to making sure it is well presented, etc. It makes it easy to read.

The first thing I notice is the she-bang line, you have #!/bin/sh this should be #!/bin/bash... right? The script uses Bash specific features that don't exist in classic /bin/sh, such as [[. Although it may appear to work with #!/bin/sh in your system, chances are that your /bin/sh is symlinked to /bin/bash (typically in Linux). This is not something you can rely on (it will break spectacularly in Solaris, for example), so when using Bash-specific features, then you should use #!/bin/bash in the she-bang.

Then, there are some shortcuts you are missing though, and these are standard processes available on most Unix commands.... wget has an exit code! Use it.

wget saves the web content to a file in the local directory. It will not override files, so you may end up with many copies of the same content. I recommend redirecting the URL contents to the stdout by using -O - argument for wget.

Error handling is a critical part of any script. It's not always easy in bash, but it can be done.

You have used the redirection >| in a few places. This caught me by surprise. I admit I looked it up. In my experience the noclobber setting is seldom set, but that may just be for me. That's just an observation. Your site may be set up differently.

Finally, bash has function support, which allows you simplify logic substantially

Consider the following:

#!/bin/bash

url="http://lon3213:8111"
path="/tmp/cmb_pinger/"

# File where I check and write the status of the server
# so I don't end up sending more e-mails for the same
# downtime. It writes 0 if no email has been sent yet
# and 1 if the email has been already sent.

log="check"
emails="email1@example.com,email2@example.com"

error() {
    local message="$@"
    >&2 echo $message
    exit 1
}

setFlag() {
    local flag=$1
    echo $flag >| "$path$log" || error "Unable to set flag to $flag"
}

# Create file if it doesn't exist
[[ -d "$path" ]] || mkdir -p "$path" || error "Unable to create directory $path"
[[ -f "$path$log" ]] || setFlag 0

# Website cannot be reached
output=$(wget -O - $url 2>&1)
success=$?

if [[ $success -eq 0 ]]
then
    setFlag $success
else
    # Emails have not yet been sent
    if [[ $(cat "$path$log") == "0" ]]; then
        echo $output | mail -s "Dashboard is down" $emails || error "Unable to send mail to $emails"
        setFlag $success
    fi
fi


Decorators are a tool that you use when you have many functions that share a behaviour, for example a particular calling convention or treatment of results. See the Python Decorator Library on the Python wiki for some examples, and this answer on Stack Overflow for a tutorial.

Here you only have two functions, so it doesn't seem likely that decorators will be helpful. Use the right tool for the job!

Anyway, comments on your code.

No docstrings! What do these functions do and how do you call them?
The else: continue in get_rows() is unnecessary.
The regular keyword argument to triangle is ignored.
Your function triangle seems very long for what it's doing. Why not use Python's format language to do the padding? Like this:

def triangle(n, invert=True):
    """Print inverted triangle of asterisks (with `n`+1 rows) to standard output.
    Print it the right way up if keyword argument `invert=False` is given.
    """
    for i in reversed(xrange(n + 1)) if invert else xrange(n + 1):
        print('{:>{}}{:>{}}'.format('*', n - i + 1, '*' if i else '', 2 * i))


Overlapping rectangles - multidimensional arrays

Class selection

First, I believe a multidimensional array is not good enough for describing rectangles. For instance, it's easy to forget what dimension responsible for what direction:

int[][] FirstRectangle = new[] { new[] { 2, 4 }, new[] { 8, 7 } };

What exactly is 2, 4, 8 and 7?
You have to remember. It's a bad design.

Instead you could use the built-in Rectangle struct or reinvent the wheel - write your own type.
In the latter case, it makes sense to move processing methods into your type.

Naming

I personally think that a method name should describe what the method do and what it returns.

So my suggestion is to rename methods Overlapping → IsOverlapping and GetOverlappingArea → PrintOverlappingArea.
Alternatively you could keep the name GetOverlappingArea (or Overlap, OverlapWith) and modify its code to create and return a new Rectangle instance which contains data of overlapping area. This method could be useful in the future.

Local variables should be named using camelCase: xOverlapping, yOverlapping.

Other notes

Instead of

if (XOverlapping && YOverlapping)
{
    return true;
}
else
{
    return false;
}

You could just

return XOverlapping && YOverlapping;

Summarizing

public class Rectangle
{
    public readonly int Left;
    public readonly int Right;
    public readonly int Top;
    public readonly int Bottom;

    public Rectangle(int left, int right, int top, int bottom)
    {
        Left = left;
        Right = right;
        Top = top;
        Bottom = bottom;
    }

    public bool IsOverlapping(Rectangle other)
    {
        bool xOverlapping = other.Left <= Right && Left <= other.Right;
        bool yOverlapping = other.Top <= Bottom && Top <= other.Bottom;
        return xOverlapping && yOverlapping;
    }

    public Rectangle OverlapWith(Rectangle other)
    {
        if (!IsOverlapping(other))
        {
            return null;
        }

        int left = Math.Max(Left, other.Left);
        int right = Math.Min(Right, other.Right);
        int top = Math.Max(Top, other.Top);
        int bottom = Math.Min(Bottom, other.Bottom);

        return new Rectangle(left, right, top, bottom);
    }

    public override string ToString()
    {
        return $"Left={Left}, Right={Right}, Top={Top}, Bottom={Bottom}";
    }
}

TODO

What else should be done?

It always make sense to validate all input arguments in all public methods and constructors.
If you plan to compare rectangles with each other, it makes sense to implement IEquatable<Rectangle> interface and override the GetHashCode() method and optionally define == and != operators.


A simple Decryption Program using Python

Use built in methods!

Your position_in_alphabets function can be reduced to one line. In fact, replace y = ... with the following:

alphabets.index(character) + 1

index returns the first occurrence of the character in question. Since you're working with the alphabet, it will return the position of the character in that string. Then you just need to add one.

Never trust user input

Instead of trusting the user will only enter lowercase characters after telling them to do so, call .lower() on the input to change the string to all lowercase letters.

I'm going to step through each line of the main function now.

f"" strings

I would use f"" strings so you can directly format your variables in your strings. In this case, it reduces the clutter that print("...", var, "...", var, "...") causes. It would instead be print(f"... {var} ... {var} ...").

Naming conventions (PEP 8)

a isn't really a good parameter name. A variable/parameter name should represent what that variable is holding or is doing. I would use string, since you're working with them in this program.

def decrypt(string):

Use enumerate

enumerate allows you to work through an iterable with the index and the value at that position in the iterable. It gets rid of having to iterable[i] and all that junk.

output = ''
spaces = 0
for index, character in enumerate(string):

Allowing spaces

Spaces are really easy to deal with. If the character is a space, simply add " " to the output and continue, quite literally, to the next iteration.

if character == " ":
    output += " "
    spaces += 1
    continue

Compress your computations

Instead of having a bunch of one character variable names x, y, z, I would do all the computations in one step and assign them to a variable. I've done so, and used position, because that's what you're calculating.

position = (index + 1) + (alphabet.index(character) + 1) - 26

Simplify your reassignments

Have a look at this:

if position > len(alphabet):
    position %= len(alphabet)

It's the same thing as position = position % len(alphabet), but shorter (also called in place modulus). It also works for the other operators (+-*/).

Don't make variables you don't need

The sole purpose of alpha is to hold the value at the passed position in alphabet, then you add alpha to output. How about you just skip the first step and add it right to output?

output += alphabet[position - 1]

All in all, your final program looks like this:

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def decrypt(string: str) -> str:
    output = ''
    spaces = 0
    for index, character in enumerate(string):
        if character == " ":
            output += " "
            spaces += 1
            continue
        position = (index + 1) + (alphabet.index(character) + 1) - len(alphabet)
        if position > len(alphabet):
            position %= len(alphabet)
        output += alphabet[position - 1 - spaces]
    return output

word = input("Please enter the word to be decrypted: ").lower()
output = decrypt(word)
print(f"The word '{word}' decrypted is '{output}'")

We use spaces to shift the index back for every space we've encountered.


Simple class exercise - min, max, and average of vector items

First, of all, this class has a setSales member much like the setgolf member of the class you posted in your last question.  I think it suffers from all the same issues that I've mentioned; there's not really anything I can add, so I'll leave those comments to represent this, too.

Now to the main issue, which I'd say is the calcAvg member.  It should in any case be const; finding and caching the average of a vector doesn't change external state, and were you to ever print the vector (without first modifying it) you'd come to the same result.

As things are, calcAvg doesn't need access to most of the members of Sales.  It looks to me like you should just write a free average function template that takes an std::vector<T> const& and returns the average (of type T).

Also, about the caching: whether you should do this or not depends on how the class is used.  I wouldn't expect this class to be used as such, but you know better.  I would delay it until the thing is printed; in that case, you'd have to make your minimum, average and maximum all mutable, and probably also of type std::atomic<double>.  This isn't necessarily better: look at the usage and choose.

Finally, as a minor detail, there's no need to use at when you can easily prove that the index is in-bounds anyway, and you can use std::accumulate for calculating the average.


I do not believe the current answer solves your optimization need, I believe the correct answer is to usefindOneAndUpdate.  This will cut down on the steps need to achieve this same goal.  The update function will handle all of the if checks, it will only update fields supplied in the req.body.

User.findOneAndUpdate({ username: req.params.username }, req.body, function (error, User) {
      if (User) {
        res.json({
            success: true,
            message: 'User updated'
        });
      } else {
        // ALWAYS RETURN res.send please
        return res.send(err);
      }
    });

http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate for additional docs.

WARNING If res.body has properties that are set as undefined, it will overwrite existing values.  You should validate inputs coming in to ensure this is not the case.


Traverse all switch branches without goto

As Dan Lyons stated in his comment you could use the goto case ... instead of custom goto labels. Check the example on the link he provided.

If you want to avoid using goto completely. I suggest you take the adding of the items out of the switch/case and place that in methods. And then, in every case you call the appropriate method to add the necessary items. Example:

List<KpiGroup> kpiGroups = new List<KpiGroup>();

public static List<KpiGroup> GetKpiGroups(int siteId, int topLevelProjectId, SiteDetailsModel.KpiCategory category, bool applyMapFilters)
{
    switch (category)
    {
        case SiteDetailsModel.KpiCategory.Wbs: AddWbsGroups(); break;
        case SiteDetailsModel.KpiCategory.Task: AddTaskGroups(); break;
        case SiteDetailsModel.KpiCategory.SysConfig: AddSysConfigGroups(); break;
        case SiteDetailsModel.KpiCategory.Any:
            AddWbsGroups();
            AddTaskGroups();
            AddSysConfigGroups();
            break;
        default:
            throw new ArgumentOutOfRangeException(String.Format("GetKpiGroups {0}", category.ToString()));
    }

    return kpiGroups;
}

public void AddWbsGroups(int siteId, int topLevelProjectId)
{
    kpiGroups.Add(KPIGetActiveSite(siteId, topLevelProjectId));
}

public void AddTaskGroups(int siteId, int topLevelProjectId)
{
    kpiGroups.Add(KPIGetTicketStatus(siteId, topLevelProjectId));
    kpiGroups.Add(KPIGetTicketSeverityClosed(siteId, topLevelProjectId));
    kpiGroups.Add(KPIGetTicketSeverityOpen(siteId, topLevelProjectId));
    kpiGroups.Add(KPIGetTicketOwnerOpen(siteId, topLevelProjectId));
    kpiGroups.Add(KPIGetTicketOwnerClosed(siteId, topLevelProjectId));
    kpiGroups.Add(KPIGetTicketActivity(siteId, topLevelProjectId));
    kpiGroups.Add(KPIGetActiveSite(siteId, topLevelProjectId));
}

public void AddSysConfigGroups(int siteId, int topLevelProjectId)
{
    kpiGroups.Add(KPIGetSysConfigOverview(siteId, topLevelProjectId));
    kpiGroups.Add(KPIGetSysConfigDeviceTypes(siteId, topLevelProjectId));
    kpiGroups.Add(KPIGetSysConfigLevel(siteId, topLevelProjectId));
}

It looks like overkill using the methods but your code still looks clean, readable and maintainable. It's up to you, use this method or the suggestion from Dan Lyons.


Let me share my thoughts. From the SOLID perspective your example is very simple and does not explicitly break any principles.

The only thing that you should not do in large-scale production code is to couple your application code (MovementManager, etc.) with execution host (Console app project).

What you should usually do is to put your application code into separate assembly(ies), employ some DI Container and create a Composition Root (also preferable in separate assembly). Application code/assemblies must not have any references to DI Container or Composition Root. On the other side, your execution host (Console App project) must reference Composition Root and Application Code assemblies, and resolve an instance of MovementManagerFactory via DI Container. Then you can use MovementManagerFactory to create your MovementManager with appropriate iMovement object.

You would need MovementManagerFactory because your MovementManager constructor requires iMovement object. To simplify things I'd rather remove that constructor and instead pass iMovement object to the Move() method directly:

public class MovementManager
{
    public void Move(iMovement movement)
    {
        movement.Move();
    }
}

As a side note: everywhere in your application when you use new operator to create an instance of a class, you potentially make your code tightly coupled. It is especially true when that 'new-ed' class belongs to another module or component.

Dependency Injection in .NET by Mark Seemann is an excellent book about design of loosely coupled application.


My suggestions:

The variables m and n are initialized but never used

The function get_neighbors:
def get_neighbors(coord: Tuple[int, int]) -> List[Tuple]:
    delta_row    = [0, 1, 0, -1]
    delta_column = [1, 0, -1, 0]

    neighbors = []
    for i in range(len(delta_row)):
        new_x = coord[0] + delta_row[i]
        new_y = coord[1] + delta_column[i]

        if -1 < new_x < m and -1 < new_y < n:
            neighbors.append((new_x, new_y))

    return neighbors

Can be simplified to:
def get_neighbors(r: int, c: int) -> List[Tuple]:
    neighbors = (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)
    return [(r, c) for r, c in neighbors if -1 < r < m and -1 < c < n]

Instead of unpacking coord you can pass the row r and column c directly. This also improves the runtime by roughly 30%.

Alternative approach
An alternative and faster approach is to use recursion:
def recursive(grid: List[List[str]]) -> int:
    islands = 0
    m, n = len(grid), len(grid[0])

    def sink_neighbors(row, col):
        grid[row][col] = '0'
        if row > 0 and grid[row - 1][col] == '1':
            sink_neighbors(row - 1, col)
        if row < m - 1 and grid[row + 1][col] == '1':
            sink_neighbors(row + 1, col)
        if col > 0 and grid[row][col - 1] == '1':
            sink_neighbors(row, col - 1)
        if col < n - 1 and grid[row][col + 1] == '1':
            sink_neighbors(row, col + 1)

    for r in range(m):
        for c in range(n):
            if grid[r][c] == '1':
                islands += 1
                sink_neighbors(r, c)
    return islands

Running the recursive solution on LeetCode:
Runtime: 120 ms, faster than 98.12% of Python3 online submissions for Number of Islands

This is the running time of the original, improved, and recursive solutions on a random grid of 1 million elements:
Runtime original: 2.345 s
Runtime improved: 1.544 s
Runtime improved2: 1.097 s
Runtime recursive: 0.696 s

Full code
from collections import deque
from typing import List, Tuple
import random
from time import perf_counter as pc

def original(grid: List[List[str]]) -> int:
    m = len(grid)
    n = len(grid[0])

    def get_neighbors(coord: Tuple[int, int]) -> List[Tuple]:
        delta_row = [0, 1, 0, -1]
        delta_column = [1, 0, -1, 0]

        neighbors = []
        for i in range(len(delta_row)):
            new_x = coord[0] + delta_row[i]
            new_y = coord[1] + delta_column[i]

            if -1 < new_x < m and -1 < new_y < n:
                neighbors.append((new_x, new_y))

        return neighbors

    islands = 0

    for i in range(len(grid)):
        for j in range(len(grid[0])):
            coord = (i, j)
            if grid[coord[0]][coord[1]] == "1":
                islands += 1
                q = deque([coord])
                while len(q) > 0:
                    c = q.popleft()
                    grid[c[0]][c[1]] = "0"
                    for neighbor in get_neighbors(c):
                        if grid[neighbor[0]][neighbor[1]] == "1":
                            q.append(neighbor)
                            grid[neighbor[0]][neighbor[1]] = "0"

    return islands

def improved(grid: List[List[str]]) -> int:
    m, n = len(grid), len(grid[0])

    def get_neighbors(r: int, c: int) -> List[Tuple]:
        neighbors = (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)
        return [(r, c) for r, c in neighbors if -1 < r < m and -1 < c < n]

    islands = 0

    for row in range(m):
        for col in range(n):
            if grid[row][col] == "1":
                islands += 1
                q = deque([(row, col)])
                while len(q) > 0:
                    r, c = q.popleft()
                    grid[r][c] = "0"
                    for r, c in get_neighbors(r, c):
                        if grid[r][c] == "1":
                            q.append((r, c))
                            grid[r][c] = "0"

    return islands

def improved2(grid: List[List[str]]) -> int:
    m, n = len(grid), len(grid[0])
    islands = 0
    for row in range(m):
        for col in range(n):
            if grid[row][col] == '1':
                islands += 1
                grid[row][col] = '0'
                q = [(row, col)]
                while q:
                    r, c = q.pop(0)
                    for r, c in (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1):
                        if 0 <= r < m and 0 <= c < n and grid[r][c] == '1':
                            grid[r][c] = '0'
                            q.append((r, c))
    return islands

def recursive(grid: List[List[str]]) -> int:
    islands = 0
    m, n = len(grid), len(grid[0])

    def sink_neighbors(row, col):
        grid[row][col] = '0'
        if row > 0 and grid[row - 1][col] == '1':
            sink_neighbors(row - 1, col)
        if row < m - 1 and grid[row + 1][col] == '1':
            sink_neighbors(row + 1, col)
        if col > 0 and grid[row][col - 1] == '1':
            sink_neighbors(row, col - 1)
        if col < n - 1 and grid[row][col + 1] == '1':
            sink_neighbors(row, col + 1)

    for r in range(m):
        for c in range(n):
            if grid[r][c] == '1':
                islands += 1
                sink_neighbors(r, c)
    return islands

if __name__ == "__main__":
    N = 1000
    random_grid = [[str(random.randint(0, 1)) for _ in range(N)] for _ in range(N)]
    res = []

    # Benchmark
    for f in original, improved, improved2, recursive:
        random_grid_copy = [row[:] for row in random_grid]
        t0 = pc()
        res.append(f(random_grid_copy))
        t1 = pc()
        print(f'Runtime {f.__name__}: {round(t1 - t0, 3)} s')

    # Correctness
    assert all(x == res[0] for x in res)


First, some style notes:

When defining a sequential piece of data, it's conventional to use a vector instead of a list:

(def matrix [[1 2 3 4] [5 6 7 8] [9 10 11 12] [13 14 15 16]])

This avoids having to write those pesky 's.
It's conventional to leave no whitespace between an opening bracket and its first contained element, and similarly between a closing bracket and its last contained element:

(def big-matrix
  [[1 2 3 4 5 6 7 8 9]
   [32 33 34 35 36 37 38 39 10]
   [31 56 57 58 59 60 61 40 11]
   [30 55 72 73 74 75 62 41 12]
   [29 54 71 80 81 76 63 42 13]
   [28 53 70 79 78 77 64 43 14]
   [27 52 69 68 67 66 65 44 15]
   [26 51 50 49 48 47 46 45 16]
   [25 24 23 22 21 20 19 18 17]])

If you think it's more readable, though, you could align the single-digit numbers in the first row with the double-digit numbers in the other rows (as you did in your question):

[ 1  2  3  4  5  6  7  8  9]

It's conventional to indent the function body the same amount as the argument vector in multi-arity functions, and to indent the "then" part of an if expression by two spaces. If you don't have an "else" expression, it's conventional to use when instead of if.

Also, it's conventional to use the idiom (seq ,,,) instead of the more verbose (not (empty? ,,,)) and to use case instead of cond when you're comparing a value to several constants:

(defn spiral
  ([matrix]
   (spiral matrix :first-row))
  ([matrix op]
   (when (seq matrix)
     (case op
       :first-row (str (print-first-row matrix) " " (spiral (rest matrix) :last-els))
       :last-els  (str (print-last-elements matrix) " " (spiral (map butlast matrix) :last-row))
       :last-row  (str (print-last-row-reversed matrix) " " (spiral (butlast matrix) :first-els))
       :first-els (str (print-first-elements-reversed matrix) " " (spiral (map rest matrix) :first-row))))))

Your approach of converting everything to strings as early as possible and then implementing your logic as string concatenation causes a lot of verbosity in your code. I would instead try to work with richer data (sequences of numbers, in this case) as much as possible:

(defn first-row [matrix] (first matrix))
(defn last-elements [matrix] (map last matrix))
(defn last-row-reversed [matrix] (reverse (last matrix)))
(defn first-elements-reversed [matrix] (reverse (map first matrix)))

(defn drop-first-row [matrix] (rest matrix))
(defn drop-last-elements [matrix] (map butlast matrix))
(defn drop-last-row [matrix] (butlast matrix))
(defn drop-first-elements [matrix] (map rest matrix))

(defn spiral
  ([matrix]
   (spiral matrix :first-row))
  ([matrix op]
   (when (seq matrix)
     (case op
       :first-row (concat (first-row matrix)
                          (spiral (drop-first-row matrix) :last-els))
       :last-els  (concat (last-elements matrix)
                          (spiral (drop-last-elements matrix) :last-row))
       :last-row  (concat (last-row-reversed matrix)
                          (spiral (drop-last-row matrix) :first-els))
       :first-els (concat (first-elements-reversed matrix)
                          (spiral (drop-first-elements matrix) :first-row))))))

Then you can use clojure.string/join to convert to a string as the last step:

(require '[clojure.string :as str])

(str/join " " (spiral matrix))
;=> "1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10"

This solution still has a lot of repetition, though; you basically have four of everything, one for each direction of the spiral. You could eliminate this repetition by just taking the top row each iteration, then rotating the rest of the matrix by an angle of \$\tau/4\$ counterclockwise.

So first you need a function to perform that sort of rotation. To visualize the algorithm I'm going to use, get a square physical object and hold it in front of you. Rotate it by an angle of \$\tau/2\$ around the axis passing through its top-left corner and its bottom-right corner. Then rotate it by an angle of \$\tau/2\$ around the axis passing through the midpoints of its left and right sides. You should see that this is equivalent to rotating the object by an angle of \$\tau/4\$ counterclockwise around the axis perpendicular to its surface.

Coming back to matrices, that first rotation is just transposing the matrix, and the second rotation is just reversing the order of its rows. Clojure has a built-in reverse function, and you could write a transpose function yourself, but there's already one available in core.matrix, so I'm just going to use that. Add the library to your dependencies:

[net.mikera/core.matrix "0.52.1"]

The transpose function is in the clojure.core.matrix namespace:

(require '[clojure.core.matrix :as m])

And now we can write our rotate function easily:

(defn rotate [matrix]
  (reverse (m/transpose matrix)))

Now that all the pieces in place, we can write our spiral function. If the matrix is empty ((seq matrix) returns nil), we just return nil. Otherwise, the spiral sequence of the matrix is equal to the concatenation of the first row of the matrix with the spiral of the rotation of the rest of the matrix:

(defn spiral [matrix]
  (when (seq matrix) (concat (first matrix) (-> matrix rest rotate spiral))))

I'm using the thread-first macro -> here because I think it makes it easier to read. Sanity check:

(str/join " " (spiral matrix))
;=> "1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10"


I didn't like the strings in the ErrorSystem call, so I factored them out. Comments and additional answers are still welcome.

class Component {
    constructor(data) {
        this.data = data;
    }
}

class Entity {
    constructor(id) {
        this.id = id;
        this.components = [];
    }

    type(component) {
        return component.prototype === undefined?
            component.constructor.name:
            component.prototype.constructor.name;
    }

    get(component) { return this.components.find(c => this.type(c) === this.type(component)); }

    set(component) {
        const included = this.get(component);
        if (included === undefined) this.components.push(component);
        else this.components[this.components.indexOf(included)] = component;
    }
}

class System {
    constructor(components, callback) {
        this.components = components;
        this.callback = callback;
    }

    run(entities) {
        entities.forEach(e =>
            this.components.every(c => e.get(c) !== undefined) &&
            this.callback(e)
        );
    }
}

class ErrorComponent extends Component {
    constructor(error) {
        super(error);
    }
}

class ErrorSystem extends System {
    constructor() {
        super(
            [ErrorComponent],
            e => console.error(e.get(ErrorComponent).data)
        );
    }
}

const testComponent = new ErrorComponent("test");

const testEntity = new Entity("test");
testEntity.set(testComponent);

const entities = [testEntity];
const testSystem = new ErrorSystem();
testSystem.run(entities);


Device-dependent image descriptor fields

I'm afraid, it's hard to use. To create a size, I need to do something like

new DevicePreDefinedImageSize(
    DevicePreDefinedImageSizeMode.REAL_SIZE,
    number)

I don't think I could ever remember this. What about:

Size.newRealSize(number)

This can be done easily, all you need are three static methods. You can otherwise keep you classes as they are.

@Override
public int getDownSampleFactor() {
    throw new UnknownError("????");
}

This is a real pain. I can see that there's no downSampleFactor, but throwing four question marks isn't really helpful. I'd return 0. Though it may hide errors, it can make it easier to use.

Or, when you're defining so many classes, what about making them so that the unwanted method doesn't really exist? Declare it only where it makes sense.

Personally I wouldn't do six classes for this.


The code works as it is, but it uses a number of local variables that aren't actually needed.  An alternative approach might be this:

clist *cmerge(clist *c1, clist *c2, clist *c3) {
    clist *ret;
    clist *curr = NULL;
    while (1) {
        if (c3 && (!c2 || (c2 && c3->num < c2->num))) {
            clist *temp = c2;
            c2 = c3;
            c3 = temp;
        }
        if (c2 && (!c1 || (c1 && c2->num < c1->num))) {
            clist *temp = c1;
            c1 = c2;
            c2 = temp;
        }
        // use c1 as next node
        if (curr) {
            curr->next = c1;
            curr = curr->next;
        } else {
            ret = curr = c1;
        }
        if (c1) {
            c1 = c1->next;
        } else {
            return ret;
        }
    }
    return ret;   // never actually reached
}

The code works by arranging the three lists so that the smallest next number is always pointed to by c1.  That simplifies appending the node to the result list.

Another approach is to use the two-list merge twice.  That approach has the advantage that it could easily be adapted to be a variadic function taking any number of lists at a slight cost in efficiency.

Performance Testing

Results of time testing on two Linux boxes are shown below, demonstrating that this code runs measurably faster than the original.

First, here's the test harness code:

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <time.h>
#include <math.h>

/*
 * the various implementations go here
 */

/* start at some number in (0,100) and increment by
 * some other number in (0,10) for count iterations
 * passed pointer is assumed to have count contiguous
 * nodes.
 */
clist *fill_random_list(int count, clist *curr) {
    clist *first = NULL, *last = NULL;
    assert(curr != NULL);
    int increment = rand() % 10;
    for (int n=rand() % 100 ; count; --count, ++curr) {
        curr->num = n;
        n += increment;
        curr->next = NULL;
        if (last == NULL) {
            first = last = curr;
        } else {
            last->next = curr;
            last = curr;
        }
    }
    return first;
}

// return true iff list is sorted
bool is_sorted(clist *list)
{
    if (list == NULL) {
        return true;
    }
    int prev = list->num;
    for (list = list->next; list; list = list->next) {
        if (prev > list->num) {
            return false;
        }
        prev = list->num;
    }
    return true;
}

int main()
{
    const size_t list_size = 5000000;
    srand(time(NULL));
    clist *one = malloc(list_size * sizeof(clist));
    clist *two = malloc(list_size * sizeof(clist));
    clist *three = malloc(list_size * sizeof(clist));
    clist *big;
    struct {
        const char *name;
        clist* (*func)(clist*, clist*, clist*);
        double elapsed;
    } tests[] = {
        { "original", cmerge_orig, 0 },
        { "Edward", cmerge_edward, 0 },
        { "mdfst13", cmerge_mdfst13, 0 },
        { NULL, NULL, 0}
    };

    for (int iterations = 100; iterations; --iterations) {
        for (size_t i=0; tests[i].func; ++i) {
            fill_random_list(list_size, one);
            assert(is_sorted(one));
            fill_random_list(list_size, two);
            assert(is_sorted(two));
            fill_random_list(list_size, three);
            assert(is_sorted(three));
            clock_t start = clock();
            big = tests[i].func(one, two, three);
            tests[i].elapsed += (double)(clock() - start)/CLOCKS_PER_SEC;
            assert(is_sorted(big));
        }
    }
    // print results
    for (size_t i = 0; tests[i].func; ++i) {
        printf("%12s\t%.10f\t%f%% %s than %s\n", tests[i].name, tests[i].elapsed,
            100.0*fabs(tests[i].elapsed-tests[0].elapsed)/tests[0].elapsed,
            (tests[i].elapsed > tests[0].elapsed ? "slower" : "faster"),
            tests[0].name
        );
    }
    free(one);
    free(two);
    free(three);
}

The code creates three sorted lists with random-ish values.  It uses assert() to rather gracelessly bail out on error (either a supposedly sorted list isn't or out of memory) and the timing doesn't account for possible rollover, but it works well enough for this purpose.

Merging 3 lists, each 5,000,000 items, cumulative time for 100 iterations

x86_64, 8 core, 3.4GHz, gcc 5.3.1

    original    2.3338780000    0.000000% faster than original
      Edward    2.2184270000    4.946745% faster than original
     mdfst13    4.1236940000    76.688499% slower than original

ARM v7, 4 core, 900MHz, gcc 4.6.3

    original    57.1399730000   0.000000% faster than original
      Edward    53.4537210000   6.451267% faster than original
     mdfst13    63.4887120000   11.110854% slower than original

Compile command:

  gcc -O2 -Wall -Wextra -pedantic -std=c99 mergetest.c -o mergetest


At the heart of the solution, there should be a function that converts decimal degrees into a d°mm'ss" string.  Assuming that the input is in a reasonable domain (between 0 and 360, for example), the conversion algorithm should be simple and regular.  Above all, it should be purely mathematical at this point — you shouldn't be trying to do any string parsing.

Your format string had lots of unnecessary concatenation.

public static string ToDegMinSec(double dec)
{
    int degrees = (int)dec;
    dec = 60 * (dec - degrees);
    int minutes = (int)dec;
    dec = 60 * (dec - minutes);
    int seconds = (int)dec;
    return string.Format("{0}.{1:00}'{2:00}\"", degrees, minutes, seconds);
}


Assembler PIC programming, is this correct?

A general disclaimer to this answer should be that I don't know the hardware you're working with, but most of this should be applicable to many architectures.

Potential optimization #1

Your code seems correct, but you can make it shorter and potentially more efficient by moving the first memory load before the branch:

movf var1, w     ; We're going to load one of the variables anyway

btfsc portC, 3
goto add

movwf temp
movf var2, w
movwf var1
movf temp, w
movwf var2
return

add addwf var2, f

Performing the load before the branch might mean the branch instruction could be executed at the same time as the load, since they don't share any data.

Potential optimization #2

Using a XOR swap should be more efficient, like so:

movf  var1, w   ; load from var1 to w
xorwf var2, w   ; w = var1 xor var2
xofwf var2, f   ; var2 = w xor var2 = (var1 xor var2) xor var2 = var1
xorwf var1, f   ; var1 = w xor var1 = (var1 xor var2) xor var1 = var2

This should have several advantages:

There is no temporary variable and therefore no reads or writes are associated with it.
The first XOR doesn't perform a memory write so it should be completed faster.
No moving memory around until the variables are assigned their final values, so if the hardware is able to cache the values of var1 and var2 from the first two instructions, the last two could gain a performance boost.

I should state again that I don't know the hardware, so this is mostly educated speculation, but my code should be faster even without assumptions 2 and 3.

Furthermore, there's nothing stopping you from combining both ideas, of course. You probably should.


I think you can optimize it like :

def fill_attributes()
  if (!$array[:status_id])
    $array[:status_id] = @customer.status_id
    $array[:status]= get_attribute_name('status',$array[:status_id] )
  end

  if (!$array[:color_id])
    $array[:color_id] = @customer.color_id
    $array[:color]= get_attribute_name('color',$array[:color_id] )
  end

end

Private

def get_attribute_name(relator, relator_id)
  relator = relator.classify.constantize.find(relator_id)
  !relator.nil? ? relator.name : nil
end

Hope this will help you .


Conway's Game of Life - Conventional JavaScript?

Looks quite good overall; not much to criticise. (I'm not looking at the overall structure or logic - just the style; the game of life can be written in so many ways)

Anyway, what I have is very trivial:

Missing indentation in the bodies of tick and getLiveNeighbourCount
Don't use a for...in loop for arrays (in isCellAlive); better and clearer to use a regular for-loop like you do elsewhere.
You ought to define myapp as window.myapp. Right now it's implicitly global, because it's missing a var declaration, but you might as well make that explicit (or perhaps it doesn't need to be global at all?)
Some more comments in the code itself would probably be nice.


From what you can find on the docs you are pretty close. I may change a couple things a little just to be on the safe side:

Change:

user = authenticate(username=request.POST["username"], password=request.POST["password1"])

To:

user = authenticate(username=form.cleaned_data['username'], form.cleaned_data['password1'])

The first way is not wrong, but using validated data on forms is a better practice than using the raw post request. Is better to be consistent.


Formatting a CAN bus message as a string

I would start with extracting the message formatting logic to a separate method. It will make profiling and performance testing easier.

foreach (var item in messages.GetConsumingEnumerable(_cancellationTokenSource.Token))
{
    formatted = FormatSingleMessage(item);
    formattedMessages.Add(formatted);
}

Then you can check the FormatSingleMessage method independently to see if the problem is really there.

When you format the messages, you perform several operations on strings. Strings are immutable, so each operation creates a new string on the heap. All these strings have to be garbage collected, which is another expensive operation.

Try to use a StringBuilder instead and compare performance of both approaches. Depending on the size of the messages, you might see a big improvement.


Project Euler #4: Finding the largest palindrome that is a product of two 3-digit numbers

Here are some suggestions in addition to the existing answers.
<chrono>
In general, the C++ std::chrono API is more flexible and
type-safe than the C functions in <ctime>, so consider using
std::chrono to time the function.
is_palindrome
In C++, it is usually not advised to declare multiple variables on one
line.  Taking small types like int by value is more efficient than
by reference and gives you a free copy to use.  To prevent errors, I
would also add an assertion to ensure that the input is a nonnegative
integer:
bool is_palindrome(int number) {
    assert(number >= 0);

    int original = number;
    int reversed = 0;

    while (number > 0) {
        reversed *= 10;
        reversed += number % 10;
        number /= 10;
    }

    return reversed == original;
}

Note that your version suffers from overflow problems for certain
large values of number, which this version does not fix.
Mathematical optimizations
By analyzing the problem mathematically, some optimizations can be
achieved.  The largest product of two 3-digit numbers is \$ 999 \times
999 = 998001 \$, so the answer will be at most a six-digit number.
For now, let's just assume that the answer is \$ \ge 900000 \$.  Thus,
the palindromes are restricted to the form \$ 9abba9 \$, where \$a\$
and \$b\$ are single-digit numbers.
By applying the divisibility rule for \$11\$, we see that \$
9abba9 \$ is a multiple of \$11\$.  Therefore, at least one of the
3-digit factors is a multiple of \$11\$ — we'll call this factor
the primary factor.  Since the product is an odd number, the primary
factor is odd as well, so we can start from \$979\$, the largest odd
3-digit multiple of \$11\$, and subtract \$22\$ at a time.  Our search
would stop if the primary factor becomes lower than \$900\$, since
\$899 \times 999 = 898101 < 900000\$, meaning our assumption would be
invalid.
Here's my result:
#include <algorithm>
#include <cassert>
#include <climits>
#include <iostream>

bool is_palindrome(int number) {
    assert(number >= 0);

    int original = number;
    int reversed = 0;

    while (number > 0) {
        reversed *= 10;
        reversed += number % 10;
        number /= 10;
    }

    return reversed == original;
}

int main() {
    int max_product = INT_MIN;

    for (int primary = 979; primary >= 900; primary -= 22) {
        for (int secondary = 999; secondary >= 900; secondary -= 2) {
            int product = primary * secondary;

            if (is_palindrome(product)) {
                max_product = std::max(product, max_product);
                break; // break out of the inner loop
            }
        }
    }

    if (max_product < 900000) {
        std::cout << "No result >= 900000\n";
    } else {
        std::cout << "Found: " << max_product << '\n';
    }
}

(wandbox)
The result is 906609, which is correct.


Random Distribution to fit an Average Python

If you want to express the field or distribution in a wave form, you should consider doing a Fourier Transformation on the function. Now, I must admit that I haven't understood exactly the sort of distribution function you are looking for. Numpy already has implementations for Gaussian distribution and such in the random module.

You can easily do so by:

numpy.random.normal(loc=7, scale=1.0, size=None)

This will produce a normal distribution with μ=7 and σ2=1.0

Now, about your code

def randlist(minn, maxn, goaln, countn):
    nlist = []

Consider renaming this function to the distribution's name that you are looking for. Such as normal for a normal distribution. Rename minn and maxn to min_ or max_. Since you are trying to avoid clashes with the keywords, you could also try using synonyms such as low and high.

for i in range(0, countn):

range(countn) is enough to start the list from 0.

if len(nlist) > 10:
    ave = numpy.mean(nlist)
    if ave > goaln:
        a = random.uniform(minn, goaln)
    else:
        a = random.uniform(goaln, maxn)
else:
    a = random.uniform(minn, maxn)

Since you are adding the first 10 numbers randomly to the list, you can do so inside the nlist itself in the form of a list comprehension (see sample code below).

def weighted_distribution(low, high, ev, count, start=10):
    result = [random.uniform(low, high) for i in range(start)]
    for i in range(count-start):
        if numpy.mean(result)> ev:
            result.append(random.uniform(low, ev))
        else:
            result.append(random.uniform(ev, high))
    return result

ev is the expected value for this distribution (mean).


Is it better practice to have void method throw an exception or to have the method return a boolean?

There's quite a few questions about this on stackoverflow but I think my general rule tends to be leave exceptions for exceptional circumstances and booleans for where failure occurances is an accepted/known possible behaviour.

So I personally probably prefer your option 2 (interested to see what others think), where if anything the exception is thrown a bit higher up the chain.  That way I could re-use the isValid logic elsewhere and deal with the failure without needing to wrap it in an exception handler.

Of course, I think this is probably a case by case basis and depends on the kind of logic being checked.

I'm sure I remember a really good Q&A on this somewhere but can't quite find it.  However found a couple of discussions:

Throw exception or return boolean - SO

Throwing exceptions - SO

EDIT:  To further comment after the edits, perhaps you could also consider the option of returning status codes (enums) instead of the exceptions if there are a number of options.  This has the benefit of being more efficient however as some have mentioned on SO could expose unecessary workings if this is a API or assembly.  Some links I found on SO about this with some good discussions were:

Exception or error code enum
to use error codes or not

And there were more.  I see this coming down to a few options.

Throw exception
Return true/false
Return a status/error code enum

All probably have their place.  Exceptions do occur the most overhead so if performance is an issue or the routine is called in many places perhaps this is not the best solution.  I also saw mention that it was not necessarily a good idea to use exceptions to control the flow of application logic which it would seem to be doing in your case?

Basically my thoughts are to use return true/false, use a status error code, and then exceptions in that order.

An alternative suggestion might be something along the lines of (whether it's a decent alternative or not hopefully someone might comment on ???):

public int playWord(string w) {
    Word word = new Word(word);
    if (word.isValid()) {
       return word.getScore();
    } else {
       throw new InvalidDataException(word.GetErrorMessage());
    }
}

class Word {
   private String word;
   private String errorMessage = null;

   public Word(string w) {
       word = w;
   }

   public boolean IsValid() {
       // TODO: perform various checks calling private methods as required and if fail store against errorMessage
      return errorMessage == null;
   }

   public String GetErrorMessage() {
      return errorMessage;
   }

   public int getScore(string word) {
     // return the score of the word no matter what it is
   }
}


Spearman correlations between Numpy array and every Pandas DataFrame row

Since Spearman correlation is the Pearson correlation coefficient of the ranked version of the variables, it is possible to do the following:

Replace values in df rows with their ranks using pandas.DataFrame.rank() function.
Convert v to pandas.Seriesand use pandas.Series.rank() function to get ranks.
Use pandas.corrwith() function to calculate Spearman correlation - Pearson correlation on ranked data.

import pandas as pd
import numpy as np
from scipy.stats import spearmanr

n_rows = 2500
cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

df = pd.DataFrame(np.random.random(size=(n_rows, len(cols))), columns=cols)
v = np.random.random(size=len(cols))

# original implementation
corr, _ = zip(*df.apply(lambda x: spearmanr(x,v), axis=1))
corr = pd.Series(corr)

# modified implementation
df1 = df.rank(axis=1)
v1 = pd.Series(v, index=df.columns).rank()
corr1 = df1.corrwith(v1, axis=1)

Calculation time of the modified version:

    %%timeit
    v1 = pd.Series(v, index=df.columns).rank()
    df1 = df.rank(axis=1)
    corr1 = df1.corrwith(v1,axis=1)
    >> 495 ms ± 13.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Checking corr and corr1 for equality proves that the results are the same:

    print(corr.var()-corr1.var(), corr.mean()-corr1.mean(), corr.median()-corr1.median())
    >> (0.0, 0.0, 0.0)


Print input lines longer than 80 characters in C

That's too complicated a solution.

It also not only imposes an arbitrary limit on the maximum possible input line length, it fails to check that the input doesn't exceed this limit.

80 is the only significant number in this program.
There's no need to worry about anything more than that.

Simply get characters into an 80 character buffer.

If you get '\n' before it fills, empty the buffer.

Otherwise, print the full buffer and get and print characters until the next '\n'.


Just a few things:

uint16_t for a size type is really small. To be precise, the maximum value of uint16_t is 2^16 - 1, or 65535. That's 64 kb of data only, which is not enough for most applications, if you consider that modern PCs have gigabytes of memory available. For sizes in general, size_t suggests itself, and offers plenty of bits for addresses (on most modern pc architectures, at least).
Why all of these functions pointers in the struct? Unless your main design goal is maximum flexibility and genericity, all you're likely achieving is bloating your struct.
Comparing a variable of type uint16_t against 0 as in if (idx >= queue->size || idx < 0) is pointless. The u in uint16_t stands for "unsigned", and variables of the type can only take values in the range [0, 2^16 - 1].
// Move the pointer up the stack -- Does this leak memory?
*queue->data++;

Not only does this leak data, it makes freeing the memory actually impossible! free can only be called on pointers directly obtained from  malloc and friends. As soon as you increment the pointer, free will automatically cause undefined behavior. Under all circumstances, you have to keep a pointer to the start around, or do some index shenanigans.
sizeof(unsigned char) is guaranteed to be 1 by definition. You don't need to multiply by that when you're allocating memory.
It's usually a good idea to check for malloc failures. If malloc fails to allocate memory, it returns NULL, which can be easily checked against and which allows you to exit gracefully, rather than (hopefully) crashing with a segfault.
For that very same reason, i.e. that malloc can fail, directly assigning from realloc is dangerous, since realloc can also fail and return NULL, in which case you lose the pointer to the original memory if you're not careful (leading to a certain leak down the line).
Similarly, check for NULL on all the pointers you receive from a user. Calling any of your functions with NULL as the first argument is going to lead to undefined behavior, which you should guard against.


Handle the empty list correctly

Let’s suppose I try to do a quick select on the empty list: your code throws an IndexError.

>>> from quickselect import quick_select
>>> quick_select([], 0, 0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "quickselect.py", line 10, in quick_select
    return numbers[start]
IndexError: list index out of range

It would be better if it returned a useful error message in this case: for example, raising a ValueError if you detect the passed in list is empty:

if not numbers:
    raise ValueError('Cannot perform quickselect on an empty list')

Better bounds checking

The first time I used your code, I had an off-by-one error in the end parameter. I made the following call:

>>> x = [1, 2, 3]
>>> quick_select(x, 0, len(x), 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "quickselect.py", line 15, in quick_select
    j = end - 1
IndexError: list index out of range

Similar calls where you use len(numbers) instead of len(numbers) - 1 will cause different varieties of IndexError. It would be better if this code had a docstring and/or error messages to push me in the right direction – tell me if my start or end variables don’t make sense for the list that I’ve passed in.

Or even better – don’t let me handle them at all. They’re required parameters for the recursive step, but if I’m passing you a list, I probably want to run quick select over the entire list. For that case, make those parameters optional, and pick sensible defaults:

def quick_select(numbers, k, start=None, end=None):
    if start is None:
        start = 0
    if end is None:
        end = len(numbers) - 1

(If those still aren’t the correct defaults, you definitely need a better docstring and error checking.)

Bug: elements are not selected according to their sort order

It’s possible that I’ve misunderstood the algorithm – in which case, please correct me in the comments. Consider the following example:

>>> from quickselect import quick_select
>>> for k in [0, 1, 2, 3]:
...     print(k, quick_select([0, 1, 2, 3], 0, 3, k))
...
0 1
1 0
2 3
3 2

My intuition is that the quickselect result should match the values in the original list. Your code doesn’t seem to be handling that correctly.

I found this bug using Hypothesis to test your code:

from hypothesis import given
from hypothesis.strategies import integers, lists

@given(lists(integers(), min_size=1))
def test_smallest_is_smallest(xs):
    x = quick_select(xs, 0)
    assert x == sorted(xs)[0]

It looks for the smallest element in the list using your algorithm, then compares that to the result if it sorts and takes the first element with sorted(). If they don’t match, it raises an error. That produced the example above.

Hypothesis could do some very powerful testing of this sort of function. (Disclaimer: I’m one of the project owners on GitHub.)

Bug: results are dependent on the initial sort order

Your function shuffles the elements of the list. In theory, this shouldn’t affect the result, right? The smallest element of a list is invariant under shuffling. In practice, it’s a bit different. Compare the following examples:

>>> quick_select([1, 2, 3], 0, 2, 0)
1
>>> quick_select([1, 2, 3], 0, 2, 1)
3

>>> x = [1, 2, 3]
>>> quick_select(x, 0, 2, 0)
1
>>> quick_select(x, 0, 2, 1)
2

I didn’t find this bug with Hypothesis – I was just playing with the example in the previous bug, and stumbled upon it by accident.

Absence of comments

You’ll notice I haven’t actually reviewed any of the code you’ve written. I’m not familiar with the quickselect algorithm, and the Wikipedia page is more complicated than I care to read on a Saturday evening.

There aren’t any comments in your code – this makes it quite difficult to understand. It would be good if there were some comments to explain the purpose of the algorithm – why do we choose this pivot? Why does the algorithm work this way? Why do we know this is correct? etc.

Not only does that make the code much easier to read, review and maintain, it would also make it more likely that you’d spot where the bugs are, because you can see where it deviates from the correct quickselect algorithm.


Right now, the relationship between the hide/show "buttons" and the columns is pretty fragile. You're dependent on the buttons being in the same exact order as the columns. If you add or remove a button, the indices stop making sense; you can't rely on the 3rd button always being linked to the 3rd column and vice versa.

I'd suggest giving the buttons (or whatever element you use to hide/show columns) a data-column attribute or something similar to make it explicit that this button controls that column. Similarly, the th cells can carry a data-column attribute or simply an ID to identify them.

For instance:

<button type="button" data-column="#column-abc">Hide/show</button>

      A column
      Another column
      Yet another column

  ...

Now it's explicit that the button will hide column #column-abc. And it'll simplify the code too, since relationships between things are no longer just assumed or implied.

Secondly, you're (in a sense) trying to both hide and show the column, and just seeing what works. It'd be simpler to just do a hasClass("hidden") check. There are also some jQuery selector magic you can use.

Something like this, for instance:

// global click handler for any element with a "data-column" attribute
$("[data-column]").on("click", function () {
  var button = $(this),                   // the element that was clicked
      header = $(button.data("column")),  // the cell referenced by the button
      table = header.closest("table"),    // the table in which the cell resides
      index = header.index() + 1,         // convert to CSS's 1-based indexing
      selector = "tbody tr td:nth-child(" + index + ")",  // selector for all body cells in the column
      column = table.find(selector).add(header); // all cells in the column

  // toggle the "hidden" class on all the column cells
  column.toggleClass("hidden");
});

Here's a demo


One of the main changes you'll probably want to make is to change number and areaCode from functions to values. As your code is right now, every time you use number it is having to recompute your top code block. The same goes for areaCode.

At first glance I don't see a reasonable way to eliminate the conditional statements that you step though to calculate number. Because of that, there isn't a great way to utilize pattern matching. So IMO you may as well take advantage of the fact that conditional statements are expressions in Scala.

Another small tweak I made in calculating number was to change "0000000000" to "0" * 10. Its not so hard to count out ten zeros, but if you needed a larger amount of them you now know about this other method.

I added class fields for the other subsections of a typical phone number, e.g. exchangeCode and stationNumber.

Finally I utilized string interpolation for your toString method as to my mind it makes the expression easier to mentally parse.

class PhoneNumber(phoneNumber: String) {
  val number = {
    val tmpNumb = phoneNumber.filter(_.isDigit)
    if (tmpNumb.startsWith("1") && tmpNumb.length == 11) tmpNumb.drop(1)
    else if (tmpNumb.length != 10) "0" * 10
    else tmpNumb
  }

  val areaCode      = number.take(3)
  val exchangeCode  = number.drop(3).take(3)
  val stationNumber = number.drop(6).take(4)

  override def toString = s"($areaCode) $exchangeCode-$stationNumber"
}


(defn snoc [xs x] (concat xs [x]))

There is a reason snoc is not defined by default in clojure: Since appending at the end of a singly linked list takes O(n) time, this is actually quite expensive. When building up non-lazy lists tail-recursively in a functional language, you often build the list the wrong way around (using cons instead of snoc) and then reverse it at the end to avoid that cost.

However in this case there is actually a nicer way: by using a lazy sequence rather than a strict list, we can avoid the need for loop/recur and save the cost of building up the list. We can also separate the logic of creating the Fibonacci numbers from the logic which decides how many numbers we want by first creating a lazy sequence containing all Fibonacci numbers and then using take-while to take those less than the given maximum. This will lead to the following code:

;; A lazy sequence containing all fibonacci numbers
(def fibs
  (letfn
    [(fibsrec [a b]
      (lazy-seq (cons a (fibsrec b (+ a b)))))]
    (fibsrec 1 1)))

;; A function which returns all fibonacci numbers which are less than max
(defn fibs-until [max]
  (take-while #(<= % max) fibs))


Convert a start and end date chosen by a user to epoch

The while loop isn't really a problem. You need some way to loop back and re-ask the user input if something went wrong (e.g. they entered wrong data).

However, there are a couple of improvements that you can make:

You are opening a stream with

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

but you are never closing it. This can lead to a resource leak. Starting with Java 7, you can deal easily with this by using the try-with-resources statement. Also, instead of using a BufferedReader, it would be easier to use a Scanner and its nextLine() method.

try (Scanner scanner = new Scanner(System.in)) {
    // read user input with scanner.readLine();
}

This has other advantages: you don't need to catch any IOException so the code is cleaner.

try (Scanner scanner = new Scanner(System.in)) {
    while (confirm){
        System.out.print("\nChoose start date (MM/dd/yyyy hh:mm:ss): ");
        String datetimestart = scanner.nextLine();

        System.out.print("\nChoose end date (MM/dd/yyyy hh:mm:ss): ");
        String datetimeend = scanner.nextLine();
        // ...
    }
}

You should respect Java naming conventions for your variables and methods. Instead of datetimestart, prefer dateTimeStart (camel-case) and epochEnd. In the same way, instead of rectime_choice_period, prefer recTimeChoicePeriod (arguably, you could have another more descriptive name).
In the same way, you should respect the Java braces style

}else {System.err.println("Wrong date! Start date should be before end date!");}

should be rewritten

} else {
    System.err.println("Wrong date! Start date should be before end date!");
}

Don't hardcode the date format "MM/dd/yyyy HH:mm:ss". You should refactor that into a constant instead:

private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";

in this way, if the pattern should ever change, you don't need to update the 4 occurences where it appears.
You are constructing twice a SimpleTextFormat when you could only construct one:

DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
epochStart = formatter.parse(dateTimeStart).getTime() / 1000;
epochEnd = formatter.parse(dateTimeEnd).getTime() / 1000;

As a side-note also, consider using imports instead of writing explicitely the fully qualified name of the class: import java.text.SimpleDateFormat;.
Avoid declarations of all the variables at the start of the method. Declare them only when they are needed. So, replace

String datetimeend = null;
// ...
datetimestart = scanner.nextLine();

with

String dateTimeEnd = scanner.nextLine();

You don't need the parentheses inside if ((epochend - epochstart) > 0). A simple if (epochend - epochstart > 0) suffices and avoids extra parentheses.
Avoid useless comments: //enter start date adds no value as a comment. Good comments don't repeat the code but clarify its intent.
Also, avoid useless temporary variables:

long[] period = {epochstart, epochend};
return period;

can just be written return new long[] { epochStart, epochEnd };.
In the code parsing the String into long, why are you catching the general Exception since you already have a catch clause for the ParseException? It is not necessary and should be removed.


Using callbacks in a Restangular service

Well, when you're already using promises you also just return that instead of using a callback.  Then you can also chain more promises at the end and add error handling.  Other than that it looks fine; I don't see what you'd really change there.

myApp.controller('CustomerController', ['$scope', 'Teams', function($scope, Teams) {
    Teams.getList().then(function(results) {
        $scope.teams = result;
    }, function(error) {
        ...
    });
}]);
myApp.factory('Teams', ['Restangular', function(Restangular) {
    var Teams = {};
    Teams.getList = function() {
        return Restangular.all('teams').getList();
    };
    return Teams;
}]);

If you want to get rid of Teams, I've seen this variant as well:

myApp.factory('Teams', ['Restangular', function(Restangular) {
    var getList = function() {
        return Restangular.all('teams').getList();
    };

    return {
        getList: getList
    };
}]);


Quicksort in JavaScript assuming an immutable array

Your code looks quite good. It is easy to read and understand.

I don't know how efficient it is, though. The reorder function creates lots of objects (3 arrays, and a return object). I think there are more efficient ways to implement this. Since you got the algorithmic complexity correct, I would not worry about these performance issues too much. If the code is fast enough, it's good enough. And it's readable, which is often more important.

Instead of let larger = [], you can write const larger = [] since the variable larger is only ever assigned once. Sure, you later modify the contents of the array, but the variable still points to the same array as before.

Instead of the for (let i = 0 loop, you can use the simpler for (const elem of arr) loop, which will free your code from the many [i] brackets.

There are some more unnecessary brackets in that function, in the expression arr[pivot]. This expression is evaluated more often than necessary. I would change the pivot element to be the value itself instead of the array index.

The sort function returns the original array in some cases, and a new array in the other cases. That is inconsistent. The caller of the sort function might assume that they may modify the array afterwards, and depending on the array size, this may or may not affect the original array, which you defined as immutable. Therefore you should return a copy of the array in every case.

You should write lots of automated tests. Having just a single example is not enough to cover all cases. I have written a few test cases for you, feel free to add more.

After applying all these suggestions, the code looks like this:

const reorder = (arr, pivot) => {
    const larger = []
    const smaller = []
    const equals = []
    for (let elem of arr) {
        if (elem < pivot) {
            smaller.push(elem)
        } else if (elem > pivot) {
            larger.push(elem)
        } else {
            equals.push(elem)
        }
    }
    return {
        smaller: smaller,
        equals: equals,
        larger: larger
    }
}

const sort = (arr) => {
    if (arr.length <= 1) {
        return arr.slice()
    }
    const pivotIndex = Math.floor(arr.length / 2)
    const result = reorder(arr, arr[pivotIndex])
    return [...sort(result.smaller), ...result.equals, ...sort(result.larger)]
}

const testcase = (unsorted, expected) => {
    const actual = sort(unsorted)
    const actualStr = actual.join(', ')
    const expectedStr = expected.join(', ')
    if (actualStr !== expectedStr) {
        console.log('error:', 'input:', unsorted, 'expected:', expected, 'actual:', actual)
    }

    if (actual.length !== 0) {
        const beforeModification = unsorted.join(', ')
        actual[0] += 1
        const afterModification = unsorted.join(', ')
        if (beforeModification !== afterModification) {
            console.log('error:', 'unsorted:', unsorted, 'before:', beforeModification, 'after:', afterModification)
        }
    }
}

testcase([], [])
testcase([1], [1])
testcase([3, 1, 1, 1, 2], [1, 1, 1, 2, 3])
testcase([0, 5, 4, 8, 9, 3, 7, 1, 2, 6], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


Count occurrences of a specific sequence in a list of many numbers

Try to keep your solution as general as possible. If I'm reading your code snippet right, you're trying to solve the problem for two patterns simultaneously. Instead, write a simple function that takes a list and a pattern, and just loops through the list counting occurrences of the pattern. This is a nice use case for list slices: given a list a, a[i:j] is a list consisting of elements i through j-1 of a.

def count_sequence(lst, seq):
     count = 0
     len_seq = len(seq)
     upper_bound = len(lst)-len_seq+1
     for i in range(upper_bound):
         if lst[i:i+len_seq] == seq:
             count += 1
     return count

Try to avoid exceptions if possible*. A rule of thumb is that exceptions are for exceptional situations. In your case, you're designing your code around the fact that you're going to get IndexErrors, whereas the function I wrote keeps the array bounds in mind and thus won't raise IndexErrors. Additionally, never write except: pass. The point of the except block is to catch errors and do something with them, so don't pass over them.

* Python itself doens't always follow this advice; for example, loops in Python are ended by raising the StopIteration exception. Nevertheless, for user-level code it's usually a good idea to only use exceptions if absolutely necessary.


Minor observations:

I'd just hardcode the charset in this case. Doing so is faster to write (and a lot more explicit) than building it with a bunch of loops.
The modulo operator % is a good friend to have for this, as it'll let you "wrap around" array indices.

Overall, there's too much code here, I think. This is just counting in base 62.

It'd be awesome if Number.prototype.toString() accepted 62 as an argument, but, unfortunately, it only seems to accept bases 2-36. Similarly, it'd be great if we could somehow use the built-in base64 encoding function (btoa), but it's, well, base 64 (and it's got other issues). So we do have to roll our own.

Now, if this was base 10, we could obviously just do

var limit = Math.pow(10, 5); // i.e. 100000

for(var i = 0 ; i < limit ; i++) {
  console.log(i);
}

which will print 0-99999.

Using this same basic setup, we can print our base62 values. Our limit will be \$base^{numberOfDigits}\$ just like \$10^5\$ will end up printing five 9s. So for 0-ZZZZZ we'll need to loop from zero to Math.pow(62, 5).

And of course, we'll have to do the actual base62 conversion. The basic algorithm is:

Get the char corresponding to \$value\bmod base\$ (e.g. charset[538 % 62] => charset[42]) and add it to the output string.
Set \$value\$ to the quotient of \$\frac{value}{base}\$ (e.g. Math.floor(538 / 62) => 8).
If value is bigger than zero, go to step 1. Otherwise, return the output.

In code:

var output = "";
do {
  output = charset[value % base] + output;
  value = (value / base) | 0; // bitwise floor trick
} while(value > 0);
return output;

Putting it all together, I get this:

// define our base62 function (using an IIFE)
var toBase62 = (function () {
  var charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
      base = charset.length; // 62, natch

  return function (value) {
    // TODO: It'd be nice to guard against negative values here (see comments)
    var string = "";
    do {
      string = charset[value % base] + string;
      value = (value / base) | 0;
    } while(value > 0);
    return string;
  }
}());

// loop for a long, long time
for(var i = 0, l = Math.pow(62, 5) ; i < l ; i++) {
  console.log( toBase62(i) );
}

Note that it takes forever to print all the 916,132,832 values from 0 up to \$62^5\$. JS ain't that fast. I haven't explored optimization, so for testing, I'd advice using (much) fewer iterations.


Proper use of type_info in relation to mapping components to a type

type_info:

Using the type_info reference is a viable approach, but it can be made better with  type_index in conjunction with an unordered_map.

static_cast:

I don't think there is a way around the cast here. You can make it slightly less verbose by defining a template helper method that wraps the type cast:

template<class T>
T * Entity::GetComponent()
{
    return static_cast<T *>(components.at(&typeid(T)));
}

// Usage:
PerkList * perkList = entity->GetComponent<PerkList>();

One nice extra of this approach is that you can replace the static_cast inside with a dynamic_cast during debug/dev builds and check that the types are self-consistent. Then add a preprocessor to use the faster static_cast for a "release" build if you need to squeeze every cycle.

Pointers:

Returning a raw pointer to IComponent is questionable to say the least. A raw pointer conveys no ownership, so it is very easy to leak or delete the objects multiple times when you have raw pointers flying around like this. You should take a look at shared_ptr and weak_ptr before further expanding your implementation. Or perhaps return just a reference (IComponent &) if the caller of GetComponent() should not own the object.

Minor details:

Don't add void to the parameter list of functions/methods that take no parameters. This is a C-ish style. C++ does not require that; () is just as good. So avoid the unnecessary verbosity.
Empty destructors/constructors should be omitted or made defaults.


Use a for loop where fit

public static string MergeMultipleLinesIntoOneLine(int numberOfLines)
{

    var stringResult = new StringBuilder();

    for (var line = 0; line < numberOfLines; line++)
    {
        Console.WriteLine("Please enter phrase #{0}: ", line);
        stringResult.Append(Console.ReadLine() + " ");
    }

    return stringResult.ToString();
}

MergeMultipleLinesIntoOneLine was very weird, when looping a fixed number of times, you should always use a for loop.

Refactor further

isPalindrome does two things:

It cleans the string.
It actually checks if it a palindrome.

These are two things, so we need two functions:

public static string clean(string s)
{
    string regexPattern = @"(?i)[^a-z]";
    string replacement = "";
    return Regex.Replace(s, regexPattern, replacement).ToLower();
}

and:

public static bool IsPalindrome(string someString)
{
    var amendedString = clean(someString);
    string reverseAmendedString = new string(amendedString.Reverse().ToArray());
    return amendedString.Equals(reverseAmendedString);
}

Do not put types into the name of the variables.

I am talking about regexPattern

Use constants

The cleaner Regex should be a class constant.

private const string cleaner = @"(?i)[^a-z]";

And replacement is unlikely to change, just use ""

clean is now simpler:

public static string clean(string s)
{
    return Regex.Replace(s, cleaner, "").ToLower();
}

Variables should be declared in the smallest possible scope, so putting the pattern inside the function is best. @Mat's Mug suggests inlining it, and I agree for such small a pattern.

Avoid unnecessary variables

bool isPalindrome = IsPalindrome(mergedLine);

Delete that line, just use:

Console.WriteLine(isPalindrome(mergedLine) ? "Palindrome" : "Not a palindrome");

Also isPalindrome can use less verbose names and be reduced to:

public static bool IsPalindrome(string someString)
{
    var cleaned = clean(someString);
    return cleaned.Equals(amendedString.Reverse().ToArray());
}

Seriously reducing noise.

Single responsibility system

@t3chb0t rightfully noted that isPalindrome still does two things, in fact, it is better to implement it like:

public static bool IsPalindrome(string text)
{
    return text.Equals(text.Reverse().ToArray());
}

And be careful to pass in cleaned strings.
Now it really does only one thing.


Some quick coding style remarks:

I'm not a fan of K&R style brackets, and it's a style rarely seen in C# code.
I like to see access modifiers on everything. Makes things a lot clearer.
generateDirection, generateVertices etc: method names should be in PascalCase.
You use the opposite of the usual C# style of having underscores in front of private instance field names, instead you use them for parameters. This is very confusing.
'L' and 'R' are used repeatedly, so why not convert these into constants?
Why do you leave a space between your method name and the bracket, e.g. direction.Add ('R');?
direction and dragon are List<T>s, yet their names do not indicate that they are collections. Collection names should be plural, IMHO. I'd even argue this should be the case for Stack<char> stack, though that is a borderline case.
Comment should tell me why, not what. If the method call is generateVertices();, I shouldn't need to be informed //generate vertices and fill dragon -- unless your method name doesn't tell me everything I need to know.
generateDirection starts with a multi-line comment explaining what the method does. I'd expect such an explanation in the <summary>, not in the body of the method.
public int iterations = 4; Why is this public? Why isn't this a const? Is it your intention that this amount can be changed by code calling the HeighwayGenerator? If so, than it should be a property with a getter/setter, or perhaps you should keep iterations private and only allow it to be changed through a method.

Concerning this logic:

for (int i = 0; i < _tempCount; i++) {
    char _tempChar = stack.Pop ();
    if (_tempChar == 'R') {
        direction.Add ('L');
    }
    if (_tempChar == 'L') {
        direction.Add ('R');
    }
}

I fail to see how _tempChar (a badly named variable, by the way) can be anything other than 'L' or 'R', so the second if can just as well be an else.

But this code can be even simpler:

for (int i = 0; i < _tempCount; i++) {
    direction.Add((stack.Pop() == 'R') ? 'L' : 'R');
}

The same remark as the previous one can be said of this code:

if(direction[i] == 'R'){
    transform.Rotate (Vector3.forward, -90.0f);
    transform.position += magnitude * transform.right;
    dragon.Add (transform.position);
}
if (direction[i] == 'L') {
    transform.Rotate (Vector3.forward, 90.0f);
    transform.position += magnitude * transform.right;
    dragon.Add (transform.position);
}

You seem to have copy-pasted three lines which are almost identical for both cases, except for one parameter. If you're doing that, you should extract those lines into a method, or if you feel that's overkill you should simplify your code:

for (int i = 0; i < direction.Count; i++) {
    transform.Rotate (Vector3.forward, (direction[i] == 'R' ? -90.0f : 90.0f));
    transform.position += magnitude * transform.right;
    dragon.Add (transform.position);
}


The way I see it there are two accordion styles.

Expand and Contract (ec) the one Section where multiple Sections can be
Expanded or Contracted.
Only one Section is Expanded at any given time. (ecp ec paired)

HTML

<button class="link" type="button" onclick ="ec('s1')">Button</button>

<button class="link" type="button" onclick ="ec('s2')">Button</button>

JS

I have two functions one for each the two EC methods.
function ec() is for EC method 1
functions ecp() is for EC method 2, pairs the current selected section with the previous.
Normally obe one of these functions is used on a web page.

The div id="s999" is for the initial value for prev so there is no null value to prev.

The reason I have var disp = div.style.display; is for when the same section is selected as previously.  I do not care if prev is expanded or contracted just contracting it is much quicker than an else if to check its display state.  But I need to remember what I am doing with the passed id.

If the same section is clicked and I toggle the display state, if it is being expanded the prev toggle would contract it again.

The line of code:

var y=div.offsetTop;window.scrollTo(0, y-64);

Takes the expanded section and puts it at the top of the Browser window. When all are contracted, it scrolls to the very top or the page.

The reason I use an array for the toggle is to eliminate the else if that would otherwise be required.

Working Snippet

  var toggle=[]
 toggle[''] = 'block';
    toggle['none'] = 'block';
    toggle['block'] = 'none';
    function ec(id){
      div = document.getElementById(id);
      div.style.display=toggle[div.style.display];
      var y=div.offsetTop;window.scrollTo(0, y-24);
    }

    var prev = document.getElementById('s999');
    function ecp(id){
      div = document.getElementById(id);
      var disp = div.style.display;
      prev.style.display='none';
      div.style.display=toggle[disp];
      prev=div;
      var y=div.offsetTop;window.scrollTo(0, y-24);
    }
body{background:#333;font-size:.8em;}
.btn1,.btn2{padding: .2em;margin:.2em 0 0 0;border-radius: 3px 3px 3px 3px;font: 700 1em Arial,Helvetica,Calibri,sans-serif;overflow: visible;border:1px solid #2985EA;color: #fff;background-color:#2985EA;
background-image: -o-linear-gradient(bottom, #2ef 0%, #02f 100%);
background-image: -moz-linear-gradient(bottom, #2ef 0%, #02f 100%);
background-image: -webkit-linear-gradient(bottom, #2ef 0%, #02f 100%);
background-image: -ms-linear-gradient(bottom, #2ef 0%, #02f 100%);
background-image: linear-gradient(to bottom, #2ef 0%, #02f 100%);}
.btn1{width:96%;}
.btn2{width:48%;}
h3{margin:0;}
p{margin:.1em .4em;}
.s1,.s2,.s3,.s4{display:none;padding:0;margin:0;}
.s1{color:#f0f;}
.s2{color:#0f0;}
.s3{color:#f00;}
.s4{color:#0ff;}
#s999{min-height:40em;}
<!DOCTYPE html>
<title>Expand Contract</title>
<button class="btn1" type="button" onclick ="ec('s1')">Section One </button>

This Section toggles when Section One button is clicked

Section 1 content
goes here.

<button class="btn1" type="button" onclick ="ec('s2')">Section Two</button>

This Section toggles when Section Two button is clicked

Section 2 content
goes here.

<button class="btn2" type="button" onclick ="ecp('s3')">Section Three </button>
<button class="btn2" type="button" onclick ="ecp('s4')">Section Four</button>

This Section toggles when Section Three button is clicked
And if Expanded will Contract when Button Four is clicked

Section 3 content
goes here.

This Section toggles when Section Four button is clicked
And if Expanded will Contract when Button Three is clicked

Section 4 content
goes here.

&#x2002;


PHP: Succint and scalable function to get what financial year we are in

Ways of improving:

According to information provided the crucial function's purpose is "to return a particular menu number for the current year". Thus, the function name would be more descriptive with name getFinYearMenuNumber.

The preconditions are:

your financial year flows through "April to April" month periods
there's starting year 2019 and ending year 2015 for the whole interval.To make the function more unified those boundaries could be passed as input parameters:

function getFinYearMenuNumber($yearFrom, $yearTo)

The main issue of the current approach is that it'll inevitably perform 5 excessive if checks (they could be at least mutually exclusive if ... else if ... else if ...).

Instead, we can just perform 2 subsequent checks:

if the current year falls in the needed interval
if the current month is following or preceding the starting month (April)

The final version:

function getFinYearMenuNumber($yearFrom, $yearTo) {
    $curr_month = (int) date('m');    # current month number
    $curr_year = (int) date('Y');     # current year
    $curr_date = new DateTime();

    if ((new DateTime("$yearFrom-04")) <= $curr_date && $curr_date <= (new DateTime("$yearTo-04"))) {
        if ($curr_month > 3) {
            return $curr_year - $yearFrom + 1;
        } else if ($curr_month < 4) {
            return $curr_year - $yearFrom;
        }
    }

    return 0;
}

print_r(getFinYearMenuNumber(2019, 2025));


Entity Framework Code First Softball Stats Database Schema

It depends on how you are planning on aggregating the stats.

Right now you have fields in your stat table that appear to really only apply when they are associated with a specific entity (player or team). For example, what does RBI on a stats record associated with a team mean?

I would avoid a design where a field like RBI means different things depending on what it's associated with. I'd personally prefer something like RBI to be only associated with a player.

In the case you do want to generate stats like "give me all RBI for the game" too and store it in the same field, you can use table per hierarchy and make entities TeamStats and PlayerStats based on a discriminator, and have RBI on the base class. I will caution that this approach is more difficult to set up and can lead to difficulty when maintaining it.

Another option is to track stats by player and compute team stats/game stats on demand (maybe via a stored proc, etc). The drawback there is that if doing so becomes computationally expensive then you have to worry about staging the data and dealing with possibly out-of-date data.

I would recommend setting up the following relationship structures:

Players belong to Teams
Games have their own Id and 2 Team FKs (so two teams can play multiple times)
A Stat is the stats for a player for 1 game, that has a composite PK consisting of Player Id and Game Id (I think this is no longer a hassle with EF).

The stats-per-player-per-game approach will allow you the most flexibility but also potentially the most on-demand computational overhead, but I'd start there until you start experiencing bottlenecks.

Since you're going to be doing decimal computations I'd avoid float and go with decimal to avoid potential loss of precision.

As for how to present the computed stats, I'd use stored procedures/functions whose results get mapped to web API models so the data is immutable as soon as you get it from the database. If that becomes annoying or too complex, you can also go the route of querying and aggregating/computing the stats in a middle application layer. I would avoid doing any computations on the front end.


I think the main cause of your delays is not a nested for but rather a fact that you extract all data from your mongodb collection into memory. What you can do is

You can calculate formatted date once.
Then you can query just those users that contain given event date instead of populating all users in memory. Here's the guide

This will look roughly like the following

const dt = datetime.create();
dt.offsetInDays(0);
const formatted = dt.format('d/m/Y');

User.find({
        "events": {
            eventDate: formatted
        }
    }).lean(true).exec((err, users) => {
        let getTEvent = [];
        //nested loops() //callbacks

        for (let i = 0 ; i < users.length; i++) {
          if(users[i].events && users[i].events.length) {
            for (let j = 0; j < users[i].events.length; j++) {
                if(users[i].events[j].eventDate === formatted) {
                  getTEvent.push({events: users[i].events[j]});
                }
            }
          }
        }

   return res.json(getTEvent)
});


As others have mentioned, use the PDO library for database work and there is no reason to use gobals. Another thing I would highly recommend, is to use exceptions, they're amazing. I'm glad to see you using the password_* library though.

I have wrote a simple authentication class to get you started, and should by no means be used in a production environment.

class Auth
{
    private $dbh;
    private $config;
    private $user;

    public function __construct(PDO $dbh, array $config = array())
    {
        $this->dbh = $dbh;
        $this->config = $config;
        session_start();

        if ($this->isLoggedIn()) {
            $this->user = $this->getLoggedInUser();
        }
    }

    public function login($username, $password)
    {
        // check if user is already logged in

        // now validate your input data

        $user = $this->findUserByUsername($username);
        var_dump($user);

        if ($user) {
            if (password_verify($password, $user->password)) {
                $_SESSION['username'] = $user->username;
                $this->user = $user;

                return true;
            }

            throw new Exception('The password is incorrect');
        }

        throw new Exception("The username {$username} could not be found");
    }

    public function register(array $data)
    {
        // data validation goes here

        if ($data['password'] !== $data['password_again']) {
            throw new Exception("The passwords do not match");
        }

        if ($this->findUserByUsername($data['username'])) {
            throw new Exception('The username ' . $data['username'] . ' already exists');
        }

        $hash = password_hash($data['password'], PASSWORD_BCRYPT, array('cost' => 11));
        $sql = 'INSERT INTO users(username, password) VALUES (:username, :password)';

        $stmt = $this->dbh->prepare($sql);
        $stmt->bindParam(':username', $data['username'], PDO::PARAM_STR);
        $stmt->bindParam(':password', $hash, PDO::PARAM_STR);
        $result = $stmt->execute();

        if ($result) {
            $this->login($data['username'], $data['password']);

            return true;
        }

        throw new Exception('Something went seriously wrong');
    }

    public function logout()
    {
        if ($this->isLoggedIn()) {
            unset($_SESSION['username']);

            return true;
        }

        return false;
    }

    public function isLoggedIn()
    {
        return array_key_exists('username', $_SESSION);
    }

    public function getLoggedInUser()
    {
        if ($this->user === null) {
            $this->user = $this->findUserByUsername($_SESSION['username']);
        }

        return $this->user;
    }

    protected function findUserByUsername($username)
    {
        $stmt = $this->dbh->prepare('SELECT * FROM users WHERE username = :username');
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_OBJ);
    }
}

$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$auth = new Auth($dbh);

try {

    // login example
    //$auth->login($_POST['username'], $_POST['password']);

    // register example
    //$auth->register($_POST);

} catch (Exception $e) {

    die($e->getMessage());
}

// logout
if (isset($_GET['logout'])) {
    $auth->logout();
}

// check if logged in
if ($auth->isLoggedIn()) {
    $username = $auth->getLoggedInUser()->username;

    echo '
Welcome ' . ucfirst($username) . '
';
    echo '
Logout
';
}


Creating nested list comprehension of files starting with specific string

Review

Bug on Capitalization

mm = regex.match('^([a-z]+)([0-9]{4,5})|^([a-z]+)', input)

This does not work for the given use case of California1998

But it can be easily fixed by adjusting the regex to include [A-Za-z] capital letters
Stop overshadowing!

You use multiple built-in keywords as variable names ie, input dir this makes it that the overshadowed functions can no longer be used further in the program
import regex?

I think this should be import re, since that's what the library is called
Unnecesarry operations

The sort and consecutive conversion do nothing at all

Secondly you loop over the directory twice! This can be avoided by doing it one loop.
Don't print errors raise them

And make sure the user get's back useful information in the error message this generic message is not very helpful :)

Alternative

Look into the glob module this does what you require,

>>> import glob
>>> glob.glob("./California1998*")
['./California1998_reform_paper.jpg', './California1998_reform_paper.txt', './California1998_reform_paper.pdf']


No getter/setter on model with many instance vars

Getters and setters are not evil, period.

Mindlessly setting and getting fields of an object is bad, though. Especially with this syntax (setX, getX).

Simple example showing the difference between mindless and thoughtful setter :

# Mindless
class CartesianPoint {
    private $x;
    private $y;

    public function setX($x) {
        $this->x = $x;
    }

    public function setY($y) {
        $this->y = $y;
    }
}

# Thoughtful
class CartesianPoint {
    private $x;
    private $y;

    public function plot($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }
}

Can you spot the differences ? You don't want to be able to only set X or Y location of a cartesian point, because that is not how it works.

Note that object is written in bold in the second sentence. Your Organization class is merely a data structure here. There's no sense attached to it, it doesn't follow rules and doesn't use its own logic.

In conclusion, if something has some logic/sense about it that the external world knows (should know) nothing about, make an object, but so far, Organization should only have public fields, and absolutely no methods inside. That's not an object.