My first Haskell: dice rolling Yesterday morning I decided to stop procrastinating and start learning me some Haskell.

So far I've made this, which is a simple cli 'dice rolling' utility that can be used like:

$ ./dice 3d20
You rolled: 17

The code looks like this:

import Data.List.Split
import Data.Char
import Control.Monad
import Control.Monad.Random
import System.Environment

type Dice = (Int, Int)

diceCode :: String -> Dice
diceCode die = (parts!!0, parts!!1)
  where
    parts = [read x :: Int | x <- take 2 (splitOn "D" (map toUpper die))]

rollDie :: (RandomGen g) => Int -> Rand g Int
rollDie sides = getRandomR (1, sides)

rollDice :: (RandomGen g) => Dice -> Rand g Int
rollDice dice = liftM sum (sequence(replicate rolls (rollDie sides)))
  where
    rolls = fst dice
    sides = snd dice

main = do
  args <- getArgs
  roll <- evalRandIO (rollDice (diceCode (args!!0)))
  putStrLn ("You rolled: " ++ show roll)

I was able to get the diceCode 'parsing' function by myself without too much trouble.

The rollDie function is almost straight from an example in the Control.Monad.Random docs, which helped a lot.

I struggled for quite a while to find a recipe for summing the rolls in rollDice... it seemed to me I ought to use msum but I couldn't find a way to make it work. liftM sum seems to do exactly what I wanted though.

I also found the use of tuples quite cumbersome. In Python I could just do:
    rolls, sides = dice
but I seem to have to use the horribly-named fst and snd functions to access the members in Haskell (?)

I guess the next part of my adventure is to try and incorporate this into a larger program, eg a simple game.  It seems like the monadically-wrapped random int values are going to force the rest of the code to be 'monad-aware' (i.e. lots of use of liftM) and I wonder if there is a way to avoid this?

The list comprehension you use in diceCode is a bit overkill: after all, you only want to split the list of characters into two. You can use break instead.

Here I have to use fmap tail to act on the second list because break retains the value it breaks the list at (the 'd' character here). This would be a good place to handle the sort of errors that would arise if there is no 'd' in the string.

diceCode :: String -> Dice
diceCode die = (read rolls, read sides) where
  (rolls, sides) = fmap tail $ break ('D' ==) $ fmap toUpper die

Your rollDice is a bit complex. Here is how I would rewrite it:

(rolls, sides) on the left hand side exposes the two components of the tuple
[1..rolls] generates a list of length rolls
mapM (const $ rollDie sides) replaces all the numbers in that list with an invocation of rollDie sides and performs the same job as sequence thus returning an Random g [Int]
sum <$> (or fmap sum $) goes under the Random g part and sums the elements in the [Int] value.

Putting all this together we get:

rollDice :: (RandomGen g) => Dice -> Rand g Int
rollDice (rolls, sides) = sum <$> mapM (const $ rollDie sides) [1..rolls]

The rest of the code is quite idiomatic. One thing I was a bit concerned about is the fact that a Dice is represented as a pair of Ints: to understand which is which, you need to read the code manipulating them and if you make a mistake the compiler won't warn you: they have the same type! It's quite annoying. One thing you could do is use a record type instead in order to name the two fields:

data Dice' = Dice' { rolls :: Int
                   , sides :: Int }

This way you can access them by their names, build the Dice' using the named syntax, etc.


JavaScript/jQuery string handling Recently I wrote some code to take two arrays of data and create a title. Each array could have 0-n elements. However, the multiple if statements seem messy to me. Is there a nicer way to do this? Perhaps one that harnesses the power of jQuery better?

var campaign_names = data["campaign_names"];
var list_names = data["list_names"];
var title;

if (campaign_names && campaign_names.length > 1) {
  campaign_names = campaign_names.join(", ");
} else if (campaign_names) {
  campaign_names = campaign_names[0];
}

if (list_names && list_names.length > 1) {
  list_names = list_names.join(", ");
} else if (list_names) {
  list_names = list_names[0];
}

if (campaign_names && list_names) {
  title = campaign_names + " & " + list_names;
} else if (campaign_names) {
  title = campaign_names;
} else if (list_names) {
  title = list_names;
}

Fun question,

if (campaign_names && campaign_names.length > 1) {
  campaign_names = campaign_names.join(", ");
} else if (campaign_names) {
  campaign_names = campaign_names[0];
}

is equivalent to

if (campaign_names && campaign_names.length ) {
  campaign_names = campaign_names.join(", ");
}

if you initialized campaign_names and list_names to '' you could simplify the last part to

if (campaign_names && list_names) {
  title = campaign_names + " & " + list_names;
} else {
  title = campaign_names + list_names;
}

Personally I would go for this:

var campaigns = data["campaign_names"] || [],
    lists = data["list_names"] || [],
    title;

if (campaigns.length) {
  campaigns = campaigns .join(", ");
}

if (lists.length) {
  lists = lists.join(", ");
}

if (campaigns && lists) {
  title = campaigns + " & " + lists;
} else {
  title = campaigns + lists;
}

If I was feeling ternary that day I would write the last part as

  title = campaigns + (campaigns&&lists) ? " & " : "" + lists;


Gravity simulation using Numpy and Pygame This is a simple gravity simulator coded in Python 3.7 using Numpy and Pygame. I was wondering if it can be optimized further. Initially I had coded it using pure Python lists, using nested loops to calculate forces between each body, but then the good people of Reddit suggested me to use Numpy, Cython or Numba to improve the runtime of the code. Some even suggested a few highly optimized algorithms which are used to improve the time complexity of N-Body simulations like the Barnes Hut algorithm. For v2, I decided to use Numpy and have kept Barnes-Hut for the scope of future. Here is the implementation in numpy :

Can it be optimized further?

import sys
import time

import numpy as np
import pygame

G = 6.67408e-11 * 100_000_000  # Otherwise the bodies would not move given the small value of gravitational constant
NUM_OF_BODIES = 4000
WIDTH = 1200
HEIGHT = 800
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (109, 196, 255)

vx = np.zeros((NUM_OF_BODIES,),dtype=np.float)
vy = np.zeros((NUM_OF_BODIES,),dtype=np.float)

px = np.random.uniform(low=10, high=WIDTH-10,size=NUM_OF_BODIES)
py = np.random.uniform(low=10, high=HEIGHT-10,size=NUM_OF_BODIES)

m = np.random.randint(1,25,size=NUM_OF_BODIES)

fx = np.zeros((NUM_OF_BODIES,),dtype=float)
fy = np.zeros((NUM_OF_BODIES,),dtype=float)

pygame.init()
size = WIDTH, HEIGHT
screen = pygame.display.set_mode(size)

font = pygame.font.SysFont('Arial', 16)
text = font.render('0', True, BLUE)
textRect = text.get_rect()
while True:
    screen.fill(BLACK)
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    in_t = time.time()
    for i in range(0,NUM_OF_BODIES):
        xdiff = (px - px[i])
        ydiff = (py - py[i])

        distance = np.sqrt(xdiff ** 2 + ydiff ** 2)

        f = G * m[i] * np.divide(m,distance ** 2)

        sin = np.divide(ydiff,distance)
        cos = np.divide(xdiff,distance)

        fx_total = np.nansum(np.multiply(f, cos))
        fy_total = np.nansum(np.multiply(f,sin))

        vx[i] = vx[i] + fx_total / m[i]
        vy[i] = vy[i] + fy_total / m[i]

        px[i] = px[i] + vx[i]
        py[i] = py[i] + vy[i]

        pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(px[i], py[i], m[i],m[i]))
    print(time.time() - in_t)
    pygame.display.flip()

The positions of the bodies are modified in-place, while the loop is running. It means that in your universe the action is not equal to reaction. Your simulation will exhibit some nonrealistic behaviors, like drift of the center of the mass.
Euler integration method is not the most accurate. Consider Runge-Kutta. At least, monitor the motion invariants (total energy, momentum, and angular momentum of the ensemble), and do corrective actions when they start diverging.
After f = m[i] * ... and f_total / m[i] the mass cancels. Multiplication and division could be safely omitted.
Along the same line, scale the masses by G once, before the simulation begins.


What do you think about this usage of for loop in JavaScript? Algorithm that I had to write is a perfect case for while, or do..while loop, however I found out that if I will implement it with a for loop I will save few lines of code and also scope of variables will be more appropriate. Take a look at the following code:

        for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top && offset !== 0; i++ ) {
            fakePosition.top -= i * 10;
            offset = this.documentView.getOffsetFromPosition( fakePosition );
            fakePosition = this.documentView.getRenderedPosition( offset );
        }

As you can see second parameter is very atypical as for for loops. My mine reason to switch to this loop was fact that I need iterator (i) and offset variables inside loop (and only there).

What do you think about this approach?

As you can see second parameter is very atypical as for for loops

Which is why it shouldn't be a for loop, because as you write yourself(!) "[it] is a perfect case for while, or do..while loop". Saving a few lines of code and variable scope is not a good reason to obscure the code. You will (or should) be losing any perceived time/line benefit in writing the comments necessary to explain your trickery. If you want to limit variable scope, declare a new scope or function.

As @Raynos alludes to in the comments, you should avoid "magic", or rather, complicated expressions in your for loops (and other conditional statements). It might not look bad to you now (though it probably will in X months), but consider what happens when your boss/client asks you to add support for a special case. Very quickly it'll look like this:

    for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top && offset !== 0 && currentPosition.top != -1 /* browser XYZ gives bogus answer */ && offset < fakePosition.bottom /* handle condition explained in ticket #123 */; i++ ) {
        fakePosition.top -= i * 10;
        offset = this.documentView.getOffsetFromPosition( fakePosition );
        fakePosition = this.documentView.getRenderedPosition( offset );
    }


Implementation of Prim's Algorithm to find minimum spanning tree What is the time complexity of the following code? I'm implementing Prim's Algorithm with adjacency matrix representation of the graph and priority queue.

from graph import adj_mtx, AP
import heapq as hq

lv, visited, h = float('inf'), {}, []  # O(n), lv stands for 'large_value' used to determine infinite distance, h is the heap

def prims_mst(adj_matrix, src):
    hq.heappush(h, (0, (src, None)))  # O(logn)
    curr_dist = {item.value: lv if item.value != src else 0 for item in AP}  # curr_dist stands for current distances from the source

    while len(h) != 0:
        # print h[0]
        curr_nd = hq.heappop(h)[1][0]  # first element of the tuple is the value, second is the node  # O(1)
        visited[curr_nd] = True  # O(1)
        for nd, dst in enumerate(adj_matrix[src]):  # O(n) -> n is the number of nodes
            if nd not in visited and curr_dist[nd] > curr_dist[curr_nd] + adj_matrix[curr_nd][nd]:
                curr_dist[nd] = curr_dist[curr_nd] + adj_matrix[curr_nd][nd]
                hq.heappush(h, (curr_dist[nd], (nd, curr_nd)))  # O(logn)
        print h

1. Problem

The code in the post does not implement Prim's algorithm! Prim's algorithm constructs a minimum spanning tree. But the code in the post does not construct a tree.

(It could certainly be modified to construct the tree, but you have to actually do it!)

2. Analysis

The key thing to spot about the code in the post is that a node might get added to the queue more than once. This is becasue a node is added to the queue every time a new route is discovered to that node that is shorter than the previously known best route.

In particular, the \$n\$th node to be visited can be added to the queue up to \$n-1\$ times (because a new and better route might be discovered via any of the previous \$n-1\$ nodes to be visited). So the while loop is executed \$O(n^2)\$ times, and on each iteration of the while loop the inner for loop takes \$O(n)\$, giving a runtime of \$O(n^3)\$ overall.

But with an adjacency matrix it is possible to implement Prim's algorithm in \$O(n^2)\$ (see Wikipedia). So you have some work to do!

3. Other review points

There's no docstring. What does prims_mst do? What does it return? What arguments should I pass? I think that if you had stopped and written a docstring then you might have spotted the problem in section 1.
The variables visited and h are global. This means that you can only call prims_mst once — on the second call, the global variables have the wrong initial values. (Or else you have to remember to reset these variables, which is inconvenient and easy to forget.) It also means that the code can't be used from multiple threads.
Names like nd and lv and dst are hard to read. There is no danger of running out of vowels, so nothing will go wrong if you write node and distance instead.
Similarly, instead of importing a module and giving it a hard-to-read alias:

import heapq as hq

consider importing the names you need:

from heapq import heappop, heappush

The variable lv is used only once, so you could just inline its value at the point of use.
Because the graph is given as an adjacency matrix (and because of the enumerate line), we know that the nodes can be labelled with consecutive integers. But the construction of curr_dist uses AP to get the nodes. It would be better to construct it in the way that you use it:

# For each node, the shortest distance from src found so far.
best_distance = [float('inf')] * len(adj_matrix)
best_distance[src] = 0

This avoids the dependency on AP.
The line:

while len(h) != 0:

can be simplified to:

while h:

Instead of representing the set of visited nodes as a dictionary mapping nodes to True, use a set.
This line assigns a variable dst that is not used anywhere:

for nd, dst in enumerate(adj_matrix[src]):

An improvement would be to write:

for node, distance in enumerate(adj_matrix[curr_nd]):

and then you could use distance instead of adj_matrix[curr_nd][nd], saving a couple of indexing operations each time.
The heap entries are data structures of the form:

(distance, (node, parent))

The code for getting data out of these entries is hard to understand because the tuple lookup [1][0] doesn't have any distinctive meaning:

curr_nd = hq.heappop(h)[1][0]

It would be better to use a collections.namedtuple:

HeapEntry = namedtuple('HeapEntry', 'distance node parent')

and then you can write:

current_node = heappop(h).node

which is much easier to understand.


Pascal Triangle calculation with BigIntegers On a well known programming challenges website(CW) there is a Kyu2 eggs height problem that can be solved utilizing a variation of Pascals Triangles properties.

The problem asks to solve f(n, m) and the solution is the sum of Pascal's Triangle row m up to cell/column n, so the sum of
f(i) = (m + 1 - i) * f(i-1) / i for i = 1 to n.

On the second variation of that problem (Kyu1) it is asked that you solve the same challenge linearly with the f(n, m) output being orders of magnitude bigger.

I've tried to solve the challenge with the code below, but it exceed the allowed time constrains to solve the challenge.

using System.Numerics;
public class EggChallenge
{
    private static BigInteger mo = new BigInteger(998244353);
    public static BigInteger Height(BigInteger n, BigInteger m)
    {
        return n == 0 || m == 0 ? 0 : BigInteger.Remainder(SumHeight(n+1, m), mo);
    }

    public static BigInteger SumHeight(BigInteger n, BigInteger m)
    {
        BigInteger BigInt = new BigInteger(1);
        BigInteger BigIntegerSum = new BigInteger(0);

        for(int i = 1; i < n; i++)
        {
            BigInt = BigInteger.Divide(BigInteger.Multiply(m + 1 - i, BigInt), (BigInteger)i);
            BigIntegerSum = BigInteger.Add(BigIntegerSum, BigInt);
        }

        return BigIntegerSum;
    }
}

The above code solves test cases such as:

EggChallenge.Height(10000,100000);
EggChallenge.Height(80000,100000);
EggChallenge.Height(3000,BigInteger.Pow(2,200));

But it's not able to beat the actual challenge time constrains.

I don't think the algorithm is what to improve has it seems to run at O(n), but I could be very wrong.

So far I've tried memorization in a BigInteger[] to release the cost of the constant addition, but it performed worst then the current code.

My question is how would this code be improved performance wise, which techniques could be applied to improve code performance?, and if possible why are those the best to apply?

initial challenge details
linear challenge details

using System.Numerics;
public class EggChallenge
{
    private static BigInteger mo = new BigInteger(998244353);
    public static BigInteger Height(BigInteger n, BigInteger m)
    {
        return n == 0 || m == 0 ? 0 : BigInteger.Remainder(SumHeight(n+1, m), mo);
    }

    public static BigInteger SumHeight(BigInteger n, BigInteger m)
    {
        BigInteger BigInt = new BigInteger(1);
        BigInteger BigIntegerSum = new BigInteger(0);

        for(int i = 1; i < n; i++)
        {
            BigInt = BigInteger.Divide(BigInteger.Multiply(m + 1 - i, BigInt), (BigInteger)i);
            BigIntegerSum = BigInteger.Add(BigIntegerSum, BigInt);
        }

        return BigIntegerSum;
    }
}

C# supports operator overloading subject to some constraints, and BigInteger has all of the arithmetical operators implemented. So you can improve legibility a lot by using standard operators rather than BigInteger.OperatorName(foo, bar).

Local variables in C# normally begin with a lower case letter, so using upper case is not very helpful. In addition, BigInt doesn't tell me anything useful: I know that the type is BigInteger because I can see the declaration, but what does the variable mean?

Renaming and using overloaded operators I get rewritten code which IMO is easier to read:

    BigInteger Height(BigInteger n, BigInteger m)
    {
        return n == 0 || m == 0 ? 0 : SumHeight(n + 1, m) % mo;
    }

    BigInteger SumHeight(BigInteger n, BigInteger m)
    {
        BigInteger term = 1;
        BigInteger sum = 0;

        for (int i = 1; i < n; i++)
        {
            term = (m + 1 - i) * term / i;
            sum += term;
        }

        return sum;
    }

  I don't think the algorithm is what to improve has it seems to run at
  O(n), but I could be very wrong.

I'm afraid that you are very wrong. The code is performing \$O(n)\$ arithmetical operations on BigIntegers, but an arithmetical operation on a BigInteger is not \$O(1)\$. The fundamental problem is this:

        ... SumHeight(n + 1, m) % mo;

It should instead be

        ... SumHeight(n + 1, m, mo);

with the % being applied regularly inside the loop:

        for (int i = 1; i < n; i++)
        {
            term = (m + 1 - i) * term % mo;
            term = ModDiv(term, i, mo); // I'll come back to this
            sum += term;
        }

        return sum % mo;

The massive advantage is that you no longer need BigInteger: it suffices to use long (or maybe ulong: it's a matter of taste because 998244353 was chosen such that long would work in languages like Java which don't have ulong).

I infer from your comment on an earlier answer that you haven't studied modular arithmetic. This is quite understandable: I think it's safe to say that 99% of programmers will never use it in their careers. But although it is irrelevant for most line-of-business programming, it is quite important in code contests/challenges (interpreted broadly to include katas, Project Euler, etc.) because they frequently use modular arithmetic to make large test cases feasible. If you find katas either enjoyable or useful for your CV, it's probably worth your time to study.

The properties I'm relying on are (treating % as an operator on arbitrary-width integers and assuming that we're avoiding overflow, which is % Pow(2, IntegerTypeWidth)):

((a % m) + (b % m)) % m == (a + b) % m
((a % m) * (b % m)) % m == (a * b) % m

Now I can come back to modular division. Essentially ModDiv(term, i, mo) needs to calculate a modular reciprocal of i (i.e. j such that i * j % mo == 1) and then return term * j % mo. There is always such a j as long as it is coprime with mo, and 998244353 is deliberately chosen to be a prime number, deliberately chosen so that you can divide by any number which isn't a multiple of it. The standard approach to calculate a modular reciprocal is the extended Euclidean algorithm, and is described in so many millions of web pages that I won't try to give my own explanation here.

To wrap up the explanation, I must address a point raised by Rick Davin. If you rewrite SumHeight so that n and m are both long, how to handle the test case m = BigInteger.Pow(2, 200)? If we look at how m is used, it takes part in addition and multiplication. So the way to do this is to do the modulo in BigInteger and then cast to long:

    long Height(BigInteger n, BigInteger m)
    {
        return n == 0 || m == 0 ? 0 : SumHeight((long)n + 1, (long)(m % mo), mo);
    }


JavaScript function that reuses a modal for adding, deleting, and viewing an item I have a table that has buttons per row that makes views/edit an item in a modal and they have a layout like so:

    <button class="btn btn-sm btn-default" onclick="setModalMode('view', '8')" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>
    &nbsp;
    <button class="btn btn-sm btn-info" onclick="setModalMode('update', '8')" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>
    &nbsp;
    <button class="btn btn-sm btn-danger" onclick="setModalMode('delete', '8')" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>

It calls the setModalMode functiton and toggles the mode of the modal:
let modal = 'div#license-add';
let $form = $('form#modal-form');
let modalMode = ''; // this is used by my AJAX function to point what URL should my requests go
let rowObjects = []; // this gets filled up by values on a different function everytime my table generates

function setModalMode(mode, id) {
    loadingOverlay(false, modal);
    modalMode = mode;

    let title = 'Modal title';
    let inputsDisabled = false;
    let hasData = true;
    let needsButton = true;
    let isDelete = false;

    if (mode === 'add') {
        title = 'Add new license';

        hasData = false;
    } else if (mode === 'update') {
        title = 'Updating license';
    } else if (mode === 'view') {
        title = 'Viewing license';

        needsButton = false;
        inputsDisabled = true;
    } else if (mode === 'delete') {
        title = 'Delete this license?';

        inputsDisabled = true;
        isDelete = true;
    } else {
        return;
    }

    if (hasData) {
        let data = rowObjects['license', id];

        $form.find('input#email').val(data.email);
        $form.find('input#key').val(data.activation_key);
        $form.find('input#expiration').val(moment(data.expiration).format('MM/DD/YYYY'));
        $form.find('select#type-select').val(data.type);
        $form.find('input#hidden-id').val(data.id);
    } else {
        $form.find(':input').val('');
    }

    if (needsButton) {
        if (isDelete) {
          $('#deleteButton', modal).show();
          $('#submitButton', modal).hide();
        } else {
          $('#deleteButton', modal).hide();
          $('#submitButton', modal).show();
        }
    } else {
        $('#submitButton', modal).hide();
        $('#deleteButton', modal).hide();
    }

    $('h4#modal-title', modal).text(title);
    $form.find(':input').prop('disabled', inputsDisabled);
}

Although the code does its job perfectly well, I feel like my code is a mess of if statements

Avoid inline handlers - they have way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with addEventListener instead.
While you could iterate over all buttons and add a listener to each, consider using event delegation instead: add a single click listener to the table, and on click, if the click was on a button, examine the button's attributes or index to see which one was clicked, and examine the data-id attribute to get the ID.
Something along the lines of:

    <button data-mode="view" class="btn btn-sm btn-default" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>
    &nbsp;
    <button data-mode="update" class="btn btn-sm btn-info" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>
    &nbsp;
    <button data-mode="delete" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>

$(table).on('click', 'button', function() {
  const { id, mode } = this.dataset;
  // ...
});

Always use const when you can - see https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6. let permits reassignment, which makes the code's intent harder to understand at a glance - whenever a developer sees a let, they may well think "This was declared with let, not const, so I need to be on the lookout for where this will get reassigned."
Give functions names with verbs - the loadingOverlay function might be more readable if it was named something like showLoadingOverlay or loadOverlay or something of the sort. (not sure what it does)
Accidental use of the comma operator - rowObjects['license', id] is equivalent to rowObjects[id]. Did you mean rowObjects['license' + id]? Consider using a linter to warn you about these sorts of potential mistakes automatically.
Array keys should be numeric only - if your keys are going to contain non-numeric strings like license, or if you aren't going to have all elements of an array filled, use an object instead:
const rowObjects = {};

Assigning titles concisely can be done by making an object indexed by mode string. When you need to figure out the title to set, just look up the property on the object: see below.
Abstract separate functionality into functions - see this anecdote. While you don't have to go that far, if you have a non-trivial block of code that does something somewhat separate from the rest of the code in a section, consider putting it into a function instead. I'd put the population of the $form into a function - see below.
Button toggling Instead of needsButton and inputsDisabled, consider hiding both buttons by default, then showing one or the other depending on whether delete, or something other than view was pressed:
const titlesByMode = {
    add: 'Add new license',
    update: 'Updating license',
    view: 'Viewing license',
    delete: 'Delete this license?',
};
$(table).on('click', 'button', function() {
    showLoadingOverlay(false, modal);
    const { id, mode } = this.dataset;
    modalMode = mode;
    if (mode === 'add') {
        $form.find('input').val('');
    } else {
        populateForm(id);
    }
    $form.find(':input').prop('disabled', mode === 'view' || mode === 'delete');

    $('h4#modal-title', modal).text(titlesByMode[mode]);
    // Hide both buttons by default:
    $('#submitButton', modal).hide();
    $('#deleteButton', modal).hide();
    if (mode === 'delete') {
        $('#deleteButton', modal).show();
    } else if (mode !== 'view') {
        $('#submitButton', modal).show();
    }
});

const populateForm = (id) => {
    const data = rowObjects['license' + id];

    $form.find('input#email').val(data.email);
    $form.find('input#key').val(data.activation_key);
    $form.find('input#expiration').val(moment(data.expiration).format('MM/DD/YYYY'));
    $form.find('select#type-select').val(data.type);
    $form.find('input#hidden-id').val(data.id);
};
```


Apply one random deduction pattern onto different lists with same index in Python I am trying to apply certain random deduction pattern to different lists - different in items but having the same numbers of items. I wrote this code - I know it is pretty messy- but it seems it does the work. Please help me to make it better. To explain, better the base list changes each time the random pattern applied to the list. But the indexes that are deducted each time are from the same previous deducted list.

import random as rm
num = 30
n = 7
slp = 1

def main():
    indxLst = []
    L = [x for x in xrange(num)]
    index = [x for x in xrange(num)]
    indexLst = []
    for e in range(1,n):
        lChng = [ L[y]+e for y in xrange(num)]

        get = int((num/e)* slp)
        index = rm.sample(index,get)
        index.sort()

        print "Index %d ="%e,index
        indexLst.append(index)
        lChng = [lChng[x] for y, x in enumerate(indexLst[e-1]) ]

        lChng.sort()
        print "List %d ="%e,lChng
main()

For example the index list I get is the following each time I deduct:

Index 1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
Index 2 = [0, 2, 5, 8, 9, 10, 12, 16, 19, 20, 21, 22, 24, 26, 28]
Index 3 = [0, 2, 5, 12, 19, 20, 21, 22, 24, 26]
Index 4 = [2, 5, 19, 20, 21, 22, 24]
Index 5 = [5, 19, 20, 21, 22, 24]
Index 6 = [19, 20, 21, 22, 24]

List (n) is deducted from list (n-1)

The code is not bad, but is a little redundant and messy.

Some comments:

There is no need to shorten the included module random because it's already short and legible.
If you are going to use global variables (module level variables) at least they should be in uppercase. It makes more easy to understand the code when reading it because you don't have to look for the variable in the code. You know they're up there. Another option is reading those variables from, say, a file if you plan to apply the script to multiples instances of the problem.
indxLst = [] it's declared but not used.
xrange() it's good for looping because it generates the new value on demand, but there is no point in using it if you're going to exhaust it right away (i.e. L = [x for x in xrange(num)] that is equivalent to L = range(num)). On the other hand, in the only place you are using range(1, n) that's the place you should be using xrange() because you're on a loop and there is no need to generate the whole range right away, you have time until you reach the last element.
The initialization for L and index it's the same. In this case you could initialize them both to the same object using the syntax: x = y = obj. But it's a minor thing and can be troublesome since both variables are pointing to the same obj.
The code should contain "some kind of logic flow". In the revised code I order it like: "calculate index; show index", "calculate Lchg; show Lchg".
The name of lChng should be something that relates to L, so possible names could be LChng, L_chng, L_tmp, etc. But the l in upper case. Also maybe you could improve the name of the variables. num it's generic and it doesn't tell you much, also index. But if the names are specified that way then it's okay.
indexLst seems to be unuseful because you put list in there only to use the same list you put 2 lines afterwards. If you don't need to whole indexes lists stored there's no point in having it there.
Last. This two lines:

lChng = [ L[y]+e for y in xrange(num)]
lChng = [lChng[x] for y, x in enumerate(indexLst[e-1]) ]

Can be replaced by:

Lchg = [L[i]+e for i in index]

Since you are puting index in indexLst only to pick it up again by indexLst[e-1].

Revised code:

import random

NUM = 30
N = 7
SLP = 1

def main():
    L = index = range(NUM)
    for e in xrange(1, N):
        get = (NUM/e) * SLP
        index = random.sample(index, get)
        index.sort()
        print "Index %d =" % e, index
        Lchg = [L[i]+e for i in index]
        Lchg.sort()
        print "List %d =" % e, Lchg

main()


Numeric integrity check I'm a beginning C programmer. I need a function that will take a string and determine if it's a number. The data is coming from files created by different people and the number formats WILL vary. So the function needs to decide if it was Supposed to be a number and if so, I will call the right conversion function (atoi/strtoi, atol/strtol etc etc.) So it needs to consider ints and floats, some with dollar signs, some with commas, some not. If a human would recognize it as a number the function should too.

The function works exactly as I want it to, and I haven't been able to break it no matter what I throw at it, but I'm sure there are better ways to do the job, and I'm equally sure there are problems with the way I'm doing it that I just am too inexperienced to know about yet. So Please, take a look and let me know of any potential pitfalls I may encounter with this function, feel free to suggest alternative ways if you're inclined.

Here's what I have come up with. As I've said it works, the example takes one or more command line args to simplify testing and there is no error checking yet, I will add that to the working program, but for function testing in a controlled setting I'm looking purely for functionality and problems that I might not know about with the way I'm handling the function.

Since the $ is significant to the shell it has to be enclosed in quotes but that won't be a problem when implemented because the data won't be coming from the command line.

Anything I should be aware of, or should consider with this code? More efficient mechanisms for accomplishing this would be appreciated. If there is a library function for this it has escaped my detection but would love to pointed in the right direction.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int check_is_numeric(const char *arr)
{
    //define valid characters for any numeric value
    char numdig[] = {'0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', ',', '.', '$'};
    int j=0;
    int notnum = 0;
    int hasdec = 0;

    while (arr[j] != '\0')  {
        for(int b = 0; b < 13;b++){
            //use hasdec to indicate a decimal in the string
            //but don't allow more than one.
            if( arr[j] == numdig[b] && hasdec < 2) {
                if (b == 11) {++hasdec;}
                notnum =0;
                break;
            } else {
                notnum =1;
            }
        }
        if(notnum){break;}
        ++j;
    }
    if(!notnum) {
        if(!hasdec){return 1;}
        else {return 2;}
    } else {
        return 0;
    }
}

int main(int argc, char *argv[])
{

    char *argvarray[argc];
    for(int j=0; j< argc; j++){
        argvarray[j] = malloc(strlen(argv[j] + 1));
        strcpy(argvarray[j], argv[j]);
    }

    int i = 0;
    for(int j=1; j< argc; j++){
        //pass each arg to the function
        //function should accept anything a human would recognize as a number
        //and return 0 for non number, 1 for int and 2 for float
        i = check_is_numeric(argvarray[j]);
        switch(i) {
            case 0:
                printf("%s is not a number.\n", argvarray[j]);
                break;
            case 1:
                printf("%s is an integer.\n", argvarray[j]);
                break;
            case 2:
                printf("%s is a floating point number.\n", argvarray[j]);
                break;
        }
    }
    return 0;
}

Using strtol() and strtod() would be a preferable way to determine if a string converts to a number.  By using various locale settings, code can work with thousands separators too.  This is a advanced task for a learner, so we will stick with your code.
Avoid magic numbers.  Rather than code 13, use a derived limit.

// for(int b = 0; b < 13;b++){
for(int b = 0; b < sizeof numdig / sizeof numdig[0] ;b++){

Avoid negated variable names.  Rather than notnum --> valid_num
For boolean variables like notnum/valid_num, use tpye bool.  Be sure to include stdbool.h
Use standard functions like strspn().  This replaces the entire while loop.  Make numdig[] both static and const for better optimization and greater clarity as to its use.

static const char numdig[] = {"0123456789,$."};
bool hasdec = false;
bool valid_num = arr[strspn(arr, numdig)] == '\0';

// search for dp separate
if (valid_num) {
  char *p = strchr(arr, '.');
  // dp found, see if another exist.
  if (p) {
    hasdec = true;
    valid_num = strchr(p+1, '.') == NULL;
  }
}

Good use of const in function signature.

int check_is_numeric(const char *arr)

Surprised signs '-' and '+' were not allowed.
Surprised optional leading whitespace was not allowed; very idiomatic in C.
Tests.  I would have like to see the coding goals specifics and some of your sample test data to assess how thorough the claim "function works exactly as I want it to".  I suspect input like "1,234,,456.0" will pass.
Advanced: '.' as decimal point and ',' as thousands separators is locale dependent.  Research <local.h> for details to make a function that works outside the "C" locale.

char dp = localeconv()->decimal_point[0];

Code looks like it ends with no return. Drop else.  Avoid !.

 if(valid_num) {
   if(hasdec) return 2;
   return 1;
 }
 return 0;


C++ template type traits for class members I have written type traits for checking, if given class T has_member, then if it either has_non_static_function_member, has_static_function_member or has_non_function_member. These type traits don't take function arguments of the member nor return type to check signature validity (I will provide other type traits for this matter).

I want to know if it can be done somehow simpler, and if the current code doesn't have some logical errors. Personally, I think I might have overcomplicated the implementation.

Here is initial version:

#include <iostream>
#include <type_traits>

template<class, class = void>
struct has_member_xxx : std::false_type
{ };

template<class T>
struct has_member_xxx<
    T,
    std::void_t<
        decltype(&T::xxx)
        >
    > : std::true_type
{ };

template<class, class = void>
struct has_non_static_member_function_xxx : std::false_type
{ };

template<class T>
struct has_non_static_member_function_xxx<
    T,
    std::enable_if_t<
        std::is_member_function_pointer<
            decltype(&T::xxx)
        >::value>
    > : std::true_type
{ };

template<class, class = void>
struct has_static_member_function_xxx : std::false_type
{ };

template<class T>
struct has_static_member_function_xxx<
    T,
    std::enable_if_t<
        (!has_non_static_member_function_xxx<T>::value) &&
        std::is_function<typename std::remove_pointer<decltype(&T::xxx)>::type>::value
        >
    > : std::true_type
{ };

template<class, class = void>
struct has_non_function_member_xxx : std::false_type
{ };

template<class T>
struct has_non_function_member_xxx<
    T,
    std::enable_if_t<
        has_member_xxx<T>::value &&
        (!has_non_static_member_function_xxx<T>::value) &&
        (!has_static_member_function_xxx<T>::value)
        >
    > : std::true_type
{ };

struct A
{
    int xxx;
};

struct B
{
    int xxx();
};

struct C
{
    static int xxx();
};

int main()
{
    std::cout << std::boolalpha;
    std::cout << "has member xxx: " << std::endl;
    std::cout << "A: " << has_member_xxx<A>::value << std::endl;
    std::cout << "B: " << has_member_xxx<B>::value << std::endl;
    std::cout << "C: " << has_member_xxx<C>::value << std::endl << std::endl;

    std::cout << "has non-static member function xxx" << std::endl;
    std::cout << "A: " << has_non_static_member_function_xxx<A>::value << std::endl;
    std::cout << "B: " << has_non_static_member_function_xxx<B>::value << std::endl;
    std::cout << "C: " << has_non_static_member_function_xxx<C>::value << std::endl << std::endl;

    std::cout << "has static member function xxx" << std::endl;
    std::cout << "A: " << has_static_member_function_xxx<A>::value << std::endl;
    std::cout << "B: " << has_static_member_function_xxx<B>::value << std::endl;
    std::cout << "C: " << has_static_member_function_xxx<C>::value << std::endl << std::endl;

    std::cout << "has non-function member xxx" << std::endl;
    std::cout << "A: " << has_non_function_member_xxx<A>::value << std::endl;
    std::cout << "B: " << has_non_function_member_xxx<B>::value << std::endl;
    std::cout << "C: " << has_non_function_member_xxx<C>::value << std::endl << std::endl;
}

Code is also on Coliru for convenience.

If xxx is a non-accessible data member (e.g. private) your code fails to compile with gcc. However this seems to be gcc bug. (stackoverflow question) Still if your code is supposed to be compilable with gcc you should consider this.
The templates give false for non-accessible (e.g. private) members. That is usually good though, because someone using quering about a class should only see the public interfacce anyway. Still consider what the intended behavior of your templates should be.
If xxx is of reference type, then your has_member_xxx will give false, because taking an address to member of reference type is not allowed.
has_member_xxx is also false if xxx is a static data member with deleted or non-accessible operator&(), although this is a pathological case because I don't see a good reason to use operator&() in that way. You might want to take std::addressof instead to avoid such a case.
has_member_xxx will also not detect member function templates, because the address of a function template cannot be taken. However that is probably expected behavior.
The same issue also arises for overloaded member functions, though. The adress of overloaded function can also not be taken. This is probably not intended behavior.

If you could specify exactly what your templates are supposed to detect / not detect that would be helpful.


Python logging: show variable name without specifying it explicitly A lot of the Python code that I write looks something like this:

import logging
import shlex
import subprocess

logger = logging.getLogger(__name__)

def execute(system_command, **kwargs):
    """Execute a system command, with sane defaults."""
    # Question is mainly about these two lines:
    logger.info("system_command: '%s'", system_command)
    logger.debug("kwargs: %s", kwargs)
    process = subprocess.run(
        shlex.split(system_command),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        **kwargs)
    if process.returncode != 0:
        logger.info(process.stdout.strip())
        logger.error(process.stderr.strip())
    return process

The logging statements are typically added when I am trying to debug something, but then i forget to remove them and they stay there.

My question is: "Does this code look reasonable?". Is there a way for me to write logger.debug(arg1) and the logger to automatically show the name of the variable being printed, for the sake of DRY?

This is good for narrowing down dirty fixes. I used to do this, but don't think it's the correct solution to the problem. Instead if you make smaller functions that are less complicated, and you have a test suite to test these functions, you should reduce the amount of bugs that you have, and not need this. The only time I used something like this, other than when I was debugging, was for a school project that was anal about logging.

You're correct, this isn't very DRY. To make it dry however would be best with a decorator, and inspect.signature.
This way, you can use the standard decorator sugar, to allow for easily toggleable debugging on the functions.
This for example could be:

@log(logger, debug=False)
def fn(arg1, arg2):
    ...

@log(logger, debug=True)
def fn(arg1, arg2):
    ...

The difference being that the second turns debugging on, where the former doesn't. It won't show anything.
Doing this, you can also include default arguments and types to every function, without any extra effort.
To do this could be with:

from inspect import signature, Parameter
import logging

logger = logging.getLogger(__name__)
DEBUG = True

def log(logger_=None, debug=False):
    debug = DEBUG and debug
    if logger_ is None:
        logger_ = logger
    def wrapper(fn):
        sig = signature(fn)
        formats = {}
        for name, param in sig.parameters.items():
            fmt = '{}() {}'.format(fn.__name__, name)
            if param.annotation is not Parameter.empty:
                fmt += ': {0.__name__}'.format(param.annotation)
            if param.default is not Parameter.empty:
                fmt += '={!r}'.format(param.default)
            fmt += ' -> {value}'
            formats[name] = fmt
        def inner(*args, **kwargs):
            if debug:
                ba = sig.bind(*args, **kwargs)
                ba.apply_defaults()
                for key, value in ba.arguments.items():
                    logger_.debug(formats[key].format(value=value))
            return fn(*args, **kwargs)
        return inner
    return wrapper

@log(debug=True)
def execute(system_command, **kwargs):
    process = subprocess.run(
        shlex.split(system_command),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        **kwargs)
    if process.returncode != 0:
        logger.info(process.stdout.strip())
        logger.error(process.stderr.strip())
    return process

@log(debug=True)
def test(a: int, b:str='b'):
    return a, b

test(1)
# Displays:
# test() a: int -> 1
# test() b: str='b' -> b

Also I'd not be surprised if there is a somewhat large performance difference, with and without the occurrence of @log. Which should be something to keep in mind.


Which syntax is preferred to create a Hash in Ruby on Rails? I am writing some code in Ruby on Rails to Create an object.

I am using Ruby 2.0 and Rails 4.0.3 in my Application.

I have a Model called:

class GroupUsers < ActiveRecord::Base
  belongs_to :users
  belongs_to :group

This is basically a ManyToMany mapping between Users and Groups.
So, today I was creating an object for this Model.

But I found out I could follow two syntax for this, as follows

GroupUsers.create( :user => user, :group => group )

Or

GroupUsers.create( user: user, group: group )

Basically since this is related to creating a Hash so it must be a question of the best practice in Ruby.

Which syntax should be preferred ?

It depends. I prefer the newer syntax because I feel that it is more readable. As others have pointed out, however, the newer syntax is only compatible with Ruby 1.9.2+.

You should be aware, however, that the new syntax does not entirely replace the hash rocket syntax. This is because you can only use the newer syntax with symbols.

{ "text": :hello } #=> syntax error, unexpected ':', expecting =>

If you want to use strings and methods, you will still need to use the has rocket:

{ method_name => :hello }
{ "a_string" => :hello }

Personally, from my experience of reading and watching educational materials, the newer syntax is preferred where possible. It's also less keystrokes: : instead of => is easier for me.


Extracting data from meshgrid output I am trying to extract data from meshgrid output where zCs is 1000 x 1000 matrix of z values which is produced from meshgrid of s using bin2mat. s is a struct which has x, y, z data. res is 1000.

Based on the threshold I am trying to extract logical which is then used to extract data from s whose z values are between the thresholds.

This code is working but very slow as shown on the screenshot.

xi = linspace(min(s.X),max(s.X),res);
yi = linspace(min(s.Y),max(s.Y),res);

[~,~, iBins] = histcounts(s.X,xi);
[~,~, jBins] = histcounts(s.Y,yi);

n_pts = length(s.X);

in1 = zCs > 0.0030 & zCs < 0.1500;
Ind = find(in1(:));

[nrows ncols] = size(in1);

I = rem(Ind-1,nrows)+1;
J = (Ind-I)/nrows + 1;

%
%
% [I,J] = ind2sub(size(in1), Ind);
N_true = length(I);

hwb = waitbar(0,'Please wait...');

in = false(n_pts,1);
  for k = 1:N_true
      in3 =  iBins == J(k) & jBins == I(k);
      in = in | in3;

      waitbar(k / N_true);

  end
  close(hwb);
  sum(in);

xk = s.X(in);
yk = s.Y(in);
zk = s.Z(in);

Welcome to the world of vectorization!

Your loop checks all elements in iBins and jBins against each of the elements in J and I. You do in = in | in3 to fill in with all the True values.

Now, this is the prime example of something that can be vectorized. Vectorization means that instead of working with one by one element in a vector, you work with the entire vector at the same time. This is much faster in MATLAB, as it's what MATLAB is designed to do.

A very short example (let's disregard jBins and I for a minute):

iBins = [4  2  3  8  6  4  2]
J     = [1  4  2  6  7]

Now, we can loop through J, and do in = in | in3 to get the following (this is the resulting in after each iteration:

k = 1
in3 = 0  0  0  0  0
in  = 0  0  0  0  0
k = 2
in3 = 0  1  0  0  0
in  = 0  1  0  0  0
k = 3
in3 = 0  0  1  0  0
in  = 0  1  1  0  0
k = 4
in3 = 0  0  0  1  0
in  = 0  1  1  1  0
k = 5
in3 = 0  0  0  0  0
in  = 0  1  1  1  0

The last in = 0 1 1 1 0 is the result after the loop.

Instead of looping like this, we can check the vectors against each other, and create a matrix:

    4  2  3  8  6  4  2
    -  -  -  -  -  -  -
1 | 0  0  0  0  0  0  0
4 | 1  0  0  0  0  1  0
2 | 0  1  0  0  0  0  1
6 | 0  0  0  0  1  0  0
7 | 0  0  0  0  0  0  0

If we check each row for true values, we'll see that we have true values in the second, third and fourth row, the same as above. How to do this?

logical_matrix = bsxfun(@eq, iBins, J.');
in = any(logical_matrix, 2);

Note that I transposed J, so that the two arguments to bsxfun are orthogonal.

Let's bring back jBins and I:

You must have true values in the same positions in the two matrices, so:

logical_matrix = bsxfun(@eq, iBins, J.') & bsxfun(@eq, jBins, I.');
in = any(logical_matrix, 2);

logical_matrix isn't a good name, I just couldn't think of a better word at the moment. You can skip it entirely, and do any(bsxfun..., 2).

If you have MATLAB R2016b or newer you can simply do:

in = any((iBins == J.') & (jBins == I.'), 2);

instead of bsxfun.

The rest of the code:

I recommend having parentheses in the below line, to make it sure what you compare, and make sure MATLAB works in the correct order.

in1 = (zCs > 0.0030) & (zCs < 0.1500);

It behaves the right way in the line above, but it's not always clear which order MATLAB will execute such commands (do == have precedence over < or not?) An example where the order is the other way around:

1 == 1 + 2 == 2
ans = 0
(1 == 1) + (2 == 2)
ans = 2

It might make sense when you know what the entire code does, but I had to read the code many times to understand what in and in3 were. The same goes with zCs.

You never use ncols, so you can do: nrows = size(in1, 1) or [nrows, ~] = size(in1). This is a very fast operation, so speed doesn't really matter, it's up to you to decide what you think is easiest to read and write. Anyway, MATLAB recommends that you separate output arguments with comma: [nrows, ncols] = size(in1) (I'm quite sure the editor gives you a recommendation (orange line in the scroll bar to the right).

waitbar is a time consuming operation, but you might want it there when debugging.


Dynamic programming with Project Euler #18 I just wanted to get an opinion on my dynamic-programming Haskell implementation of the solution to Project Euler problem 18.

The Problem:

  By starting at the top of the triangle below and moving to adjacent
  numbers on the row below, the maximum total from top to bottom is 23.

  $$\begin{array}{ccc}
  &   &   & \color{red}{3} \\
  &   & \color{red}{7} &   & 4 \\
  & 2 &   & \color{red}{4} &   & 6 \\
8 &   & 5 &   & \color{red}{9} &   & 3 \\
\end{array}$$

  That is, 3 + 7 + 4 + 9 = 23.

  Find the maximum total from top to bottom of the triangle below:

                            75
                          95  64
                        17  47  82
                      18  35  87  10
                    20  04  82  47  65
                  19  01  23  75  03  34
                88  02  77  73  07  63  67
              99  65  04  28  06  16  70  92
            41  41  26  56  83  40  80  70  33
          41  48  72  33  47  32  37  16  94  29
        53  71  44  65  25  43  91  52  97  51  14
      70  11  33  28  77  73  17  78  39  68  17  57
    91  71  52  38  17  14  91  43  58  50  27  29  48
  63  66  04  68  89  53  67  30  73  16  69  87  40  31
04  62  98  27  23  09  70  98  73  93  38  53  60  04  23

  NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67 is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method!

My code:

--Find the maximum total from top to bottom of the triangle below
import Data.Array
import System.Environment (getArgs)
import Control.Applicative ((<$>))

main :: IO()
main = do
  path <- head <$> getArgs
  triangle <- read_triangle path
  putStrLn $ show $ max_path triangle (tri_size triangle) 1

tri_size :: Array Int (Array Int Int) -> Int
tri_size triangle = case bounds triangle of
  (s, f) -> (f - s) + 1

--the triangle in this case is a 2d array
--(similar to how pascal's triangle is mathematically described)
--read the tree
read_triangle :: FilePath -> IO (Array Int (Array Int Int))
read_triangle fp = (tri . reverse . lines) <$> readFile fp
  where
    tri lines = listArray (1, length lines) (map row lines)
    row line = listArray (1, length $ nums line) (nums line)
    nums = map (read :: String -> Int) . words

--OPT(r,i) = v_ri + max(OPT(r-1,i), OPT(r-1,i+1))
--OPT(N,i) = v_ri
max_path :: Array Int (Array Int Int) -> Int -> Int -> Int
max_path triangle row index = (opt!row)!index
  where opt = listArray (1,row) $ (triangle!1 : map f [2..row])
    f r = listArray (1,rsize r) $ map (g r) [1..(rsize r)]
    g r i = triangle!r!i + max (opt!(r-1)!i) (opt!(r-1)!(i+1))
    rsize r = tsize - r + 1
    tsize = tri_size triangle

Where can I cut down on repetition/is there anything I could include to make this more concise/readable? Does anything I do show a general misunderstanding of stuff like monads or Haskell's laziness?

Your code is correct, fast, and I'd like to emphasize that you thoroughly include types for your functions, which greatly helps readability.

While arrays offer fast performance, I'd say that in this case operations with indexes and bounds of the arrays cloud the main idea considerably. Therefore I'd offer to use lists and functions native to lists that avoid indexing (the same could be also achieved with arrays, by writing similar functions for them).

The main idea, computing the maximum path lengths for one row, can be then nicely described by zipping:

-- OPT(r,i) = v_ri + max(OPT(r+1,i), OPT(r+1,i+1))
opt :: [Int] -- ^ the current row
    -> [Int] -- ^ the maximum paths from the previous row
    -> [Int]
opt row mxs = zipWith (+) row $ zipWith max mxs (tail mxs)

Then, computing the maximum path can be expressed as folding opt over a list of lists that represents a triangle:

-- Given a triangle (the first row containing `n` elements, the last row 1
-- element), compute the maximum path.
max_path :: [[Int]] -> Int
max_path = head . foldr opt (repeat 0)

where we start with an infinite list of zeros. This is safe, as we always only access a finite number of elements of this starting list.

While the algorithm remains the same, avoiding explicit indexing makes it more readable.

Minor notes:

it's customary to write f . g $ x instead of f $ g $ x to emphasize function composition
putStrLn . show can be replaced by just print

(I suggest you to try out hlint, which gives many interesting hints how to improve a Haskell program, including the two above.)


Merge some child values back into the parent multidimensional array This is a wonky PHP function I came up with to merge some select values from child arrays into the original.  It could really use some help simplifying / making it more elegant.

Is there a built-in method I'm overlooking?  array_push didn't work for me because the data needed to be flat.

The problem

What I've got:

array(
    array(
         'nice_value' => 'yup',
         'nice_value2' => 'yup again',
         'ono' => array(
              'nice_value3' => 'yup yup yup',
              'bad value' => 'nope'
          )

    ),
    // array with the same format
    [...]

);

What I need:

array(
    array(
         'nice_value' => 'yup',
         'nice_value2' => 'yup again',
         'nice_value3' => 'yup yup yup'
    ),
    // array with the same format
    [...]

);

The wonky solution

// calling in multidimensional array from an api
            $lists = $all_lists['data'];
// keys to merge into the parent array, 'key_to_be' => 'key_that_is'
            $keys_to_merge = array('members' => 'member_count');
// init the function
            $newList = merge_selected_values($lists, $keys_to_merge);

// start writing our function
            function merge_selected_values($list, $keys_to_merge) {
// initialize our return array
            $newList = array();
// start a counter
            $ii = 0;
// begin loop
            foreach($list as $key => $value) {
// get first series of array, this is what we want to merge into
                if (is_array($value)) {
// loop through these values
                   foreach ($value as $kk => $vv) {
// find all arrays that are children of our parent array
                      if (is_array($vv)) {
// loop through these child arrays
                          foreach ($vv as $stats_key => $stats_value) {
// start looping through the keys that we want to merge
                             foreach ($keys_to_merge as $keys => $vals) {
// if the key matches
                                 if ($stats_key === $vals) {
// create a variable to hold it
                                     ${$vals} = $stats_value;
                                 }
                             }
                         }
                      }
                   }
// start looping through keys to merge again
                   foreach ($keys_to_merge as $keys => $vals) {
// find the keys we merged
                       if (${$vals}) {
// create an array that is the merger, merge to existing array if it .. exists
                           if($newList[$ii]) {
                               $newList[$ii] = array_merge($newList[$ii], array($keys => ${$vals}));
                            }  else {
                              $newList[$ii] = array_merge($value, array($keys => ${$vals}));
                           }
                       }
                   }
               }
              $ii++;
            }
            return $newList;
            }

What's the criteria for deciding which keys to keep?

Check out the array_walk_recursive() function. For example, the following matches any element with a key that starts with "nice_value".

$array = /*your array example*/;
$filtered = array();
array_walk_recursive($array, function($val, $key) use(&$filtered) {
    if (strpos($key, 'nice_value') === 0) {
        $filtered[$key] = $val;
    }
});


Energy curve plotter I am not much experienced in Python, just write some small script. All my codes are procedural. They work fine, and I always check them with pep8.

One of them is:

#!/usr/bin/python3
import os
import sys
import numpy as np
import scipy as sp
import scipy.optimize
import matplotlib.pyplot as plt

def f(x, a, b, c, d):
    return a + b*x + c*x**2 + d*x**3

data = []
fout = "tmpft"  # sys.argv[1] + "_trial.dat"
with open(fout, "w") as of:
    for subdir, dirs, files in os.walk(sys.argv[1]):
        for inp in files:
            if inp.endswith("SCF.out"):
                fsys = subdir + "/" + inp
                # print(fsys)
                with open(fsys) as finp:
                    for line in finp:
                        if "lattice constant  ALAT" in line:
                            lata = float(line.strip()[-7:])/1.88973
                        if " ERR " in line:
                            mom = line.strip()[61:70]
                        if "SCF - cycle converged" in line:
                            etot = float(line.lstrip()[10:25])
                            of.write("{:<10f} {:<15f} {:<15f}\n"
                                     .format(lata,  etot, float(mom)))

ffout = sys.argv[1]+".dat"
with open(ffout, "w") as ff:
    ff.write("#lat(A)          ETOT          MOM\n")
    with open(fout, "r") as uns:
        for line in sorted(uns):
            ff.write(line)
values = np.genfromtxt(fout, dtype=None, delimiter='   ', usecols=[0, 1, 2])
os.remove(fout)
etot = values[:, 1]
latp = values[:, 0]

popt, pcov = sp.optimize.curve_fit(f, latp, etot)
res = sp.optimize.minimize(lambda x: f(x, *popt), 2.8)
print('Function is minimized for {0}.'.format(float(res['x'])))
with open(ffout, 'a') as ff:
    ff.write('#Function is minimized for {0}\n'.format(float(res['x'])))

# Plot data
pout = sys.argv[1]+".png"
x = sp.linspace(2.80, 3.05, 100)
y = f(x, *popt)
plt.plot(x, y, lw=3)
plt.xlabel("Lattice Parameter")
plt.ylabel("Energy")
plt.title(sys.argv[1])
plt.scatter(latp, etot, s=60)
plt.scatter(res['x'], f(res['x'], *popt), color='red', s=80)
plt.savefig(pout)
plt.show()

This works fine, i.e. gives me proper/correct result. But I wonder if this is a good way of writing Python. If I take this as my standard example (most of my Python interaction is like this: read a file, fetch some data, post-process it and plot), how I can make it better? By "better", I mean, optimized, reusable and readable.

Like, as I already said, most of my python involves reading a line that matched a string. So, I would like to have it as a function (in C/fortran sense) etc.

"Better" is obviously fairly subjective. After a quick glance I would like to make a few suggestions:

If you already imported scipy, you don't need to import
scipy.optimize separately. You can either limit the importing by just
importing the (sub)modules you need, which is cleaner. Or you can
import the entire module and just use what you need.
Especially in terms of usability and readability for later (especially rereading your own code), I would suggest adding some docstring to describe what it does: https://www.python.org/dev/peps/pep-0257/#id16
Similarly I would use a clearer naming convention. The program won't run faster if you call it "energy_curve_calculator_function_using_curve_fit" or "f", but when you look into your files, you will know the difference.
Lastly, I would also advise you add a comment block (or one line) between each section of code explaining what it does.

Right now pep8 only checks that your lines aren't too long. I would concentrate a little more on making sure someone who didn't write the code (or you in a few months) can read what it's doing based on the flow, comments where needed and the variable names.


High performance primitive dynamic array Unfortunately Java does not support generic programming with primitive types. Using collections classes with boxed types may increase memory usage by a factor of 3-4 (e.g. int being 32-bit and Integer 128-bit). Throughput may be lower, with some tests demonstrating boxed types being at least 10 times slower. This seems consistent with my own measurements. I have not found any official (Oracle) or otherwise reputable implementations of primitive arrays, so here I go.

The goal is to write a fast and simple linear container for primitives. It is intended to be as similar as possible to ArrayList. It will at least implement the common array operations size(), add(int value), add(int index, int value), set(int index, int value), get(int index), remove(), remove(int index) and clear(). A few operations, like contains(Object obj) and indexOf(Object obj) will be left out, because they rely on reference types, not value types.

I'm interested in performance optimizations. Hopefully someone better knows how this code can be optimized further. Below is the implementation of int-vector, iVector. The name is only a preliminary placeholder, and vectors for other primitives can be created by changing the classname and the int-types in the implementation.

public class iVector {
    private int[] data;
    private int length = 0;

    //Constructors
    public iVector(){
        data = new int[10];
    }
    public iVector(int initialCapacity){
        if(initialCapacity < 10)
            initialCapacity = 10;
        data = new int[initialCapacity];
    }

    //Methods
    public int size(){
        return length;
    }

    public void ensureCapacity(final int capacity){
        if(capacity <= data.length) return;
        int[] newData = new int[capacity];
        System.arraycopy(data, 0, newData, 0, data.length);
        data = newData;
    }

    public void add(final int value){
        if(length == data.length)
            ensureCapacity(data.length + data.length/2); // Grow by approx. 1.5x
        data[length] = value;
        ++length;
    }

    public void add(final int index, final int value){
        if (index >= length || index < 0)
            throw new ArrayIndexOutOfBoundsException(index);
        if (length == data.length)
            ensureCapacity(data.length + data.length / 2); // Grow by approx. 1.5x
        for (int i = length; i > index; --i)
            data[i] = data[i - 1];
        data[index] = value;
        ++length;
    }

    public void set(final int index, final int value){
        if(index >= length)
            throw new ArrayIndexOutOfBoundsException(index);
        data[index] = value; //if (index<0) or (index>data.length), IndexOutOf. is thrown
    }

    public int get(final int index){
        if(index >= length)
            throw new ArrayIndexOutOfBoundsException(index);
        return data[index]; //if (index<0) or (index > data.length), IndexOutOf. is thrown
    }

    public void remove(){ // Remove last element
        if(length == 0) return;
        --length;
    }

    public int remove(int index){ // Removes and returns the removed value
        final int result = get(index);
        --length;
        for(; index < length; ++index)
            data[index] = data[index + 1];
        return result;
    }

    public void clear(){ // Make empty
        length = 0;
    }
}

There is a small bug: In the method add(int, int), it should probably be

if (index > length || index < 0)
    throw new ArrayIndexOutOfBoundsException(index);

instead of

if (index >= length || index < 0)
    throw new ArrayIndexOutOfBoundsException(index);

Inserting at the index length would just mean appending an element to the end of the iVector, so an index of length wouldn't be invalid.
Also, data.length + data.length/2 might overflow for very large values of length. You could prepare for this by checking whether Integer.MAX_VALUE - data.length/2 >= data.length.
In the method ensureCapacity(int), it would suffice to copy length elements instead of data.length elements, since the values of all elements in data with an index equal to or greater than length are irrelevant.
You could simply call add(length, value) from add(int value), because right now, the code of add(int) is effectively duplicated in add(int, int). If the reason for this is performance due to the unnecessity of argument validation, this would probably only be relevant for a very large number of successive additions, and for this, you could make a separate bulk method like addAll (which could also employ other optimizations like calling System.arraycopy instead of manually copying each element via iteration).
public void remove(){
    if(length == 0) return;
    --length;
}

Can be written more concisely as:

public void remove(){
    if(length != 0) --length;
}

remove() returns void whereas remove(int index) returns the value previously at index. This is inconsistent. I suggest you make remove() also return the previously last element.
It occurred to me that, if the internal array can contain "vacant lots" at the end, it could also contain vacant lots at the beginning. For example, consider this array with a capacity of 10, containing 6 elements:

abcfgh----

Now, if you want to delete a from the array, your code would do this:

bcfgh-----

I.e. delete the first element and shift all subsequent elements to the left by one position. But it would be much more efficient to do this:

-bcfgh----

This would also require a pointer to the first element in addition to a field that stores the number of elements in the iVector. And if you want to insert or delete an element, you could calculate for each direction how many elements would have to be shifted, and then perform the cheaper of the two variants and update the respective pointer accordingly. For example, if you now want to insert e between c and f, a "left-push" would require two elements to be moved (bc), whereas a "right-push" would require three elements to be moved (fgh), so the left-push variant would be cheaper:

bcefgh----

In fact, the array could even wrap around. If you now want to insert d before e, you could do this:

cdefgh---b

While this would make simple get or set operations a tiny bit more expensive, because you would have to calculate the index for the internal array from the public index for the iVector, I guess that this can save quite a bit of performance for add or remove operations on the lower half of the iVector.

Update

So I've tried to implement the wraparound suggestion myself, and the code now seems to be about twice as fast as your version when removing and inserting from/to random positions in the vector. When only operating on the upper half, it is, of course, a little bit slower, because the overhead is never compensated for by shifting fewer elements than your original code. Here is my implementation:

public class IntArrayList {
    private int[] data;
    private int size;
    private int indexOfFirstElement;

    public IntArrayList() {
        this(10);
    }

    public IntArrayList(int initialCapacity) {
        data = new int[Math.max(initialCapacity, 10)];
        size = 0;
        indexOfFirstElement = 0;
    }

    public int size() {
        return size;
    }

    /**
     * Returns the index of the element in the internal array that is
     * {@code offset} positions away from the element at the index
     * {@code index}, wrapping around the array if necessary.
     * {@code offset} can be negative, in which case the distance will be
     * traveled to the left of the original element rather than to the right.
     * This method assumes that the passed index is valid and that the
     * absolute value of {@code offset} is not greater
     * than the length of the internal array. If these conditions are not
     * met, the returned index might not be valid.
     *
     * @param index  a valid index for the internal array
     * @param offset the distance from the element at index {@code index}; may be negative
     * @return the index of the array element at the specified distance
     */
    private int indexForOffset(int index, int offset) {
        int offsetIndex = index + offset; //might overflow
        if (data.length - index <= offset) { //includes cases where the previous line overflows
            offsetIndex -= data.length;
        } else if (offsetIndex < 0) { //cannot be the result of an overflow
            offsetIndex += data.length;
        }
        return offsetIndex;
    }

    public void ensureCapacity(final int capacity) {
        if (capacity > data.length) {
            int[] newData = new int[capacity];
            if (size != 0) {
                if (indexOfFirstElement <= indexForOffset(indexOfFirstElement, size - 1)) {
                    System.arraycopy(data, indexOfFirstElement, newData, 0, size);
                } else {
                    System.arraycopy(data, indexOfFirstElement, newData, 0, data.length - indexOfFirstElement);
                    System.arraycopy(data, 0, newData, data.length - indexOfFirstElement, indexOfFirstElement + size - data.length);
                }
            }
            data = newData;
            indexOfFirstElement = 0;
        }
    }

    /**
     * Converts an index for this {@code IntArrayList} to the
     * corresponding index for the internal array. This method
     * assumes that the passed index is valid. If it is not,
     * the returned index might not be valid as well.
     *
     * @param publicIndex A valid index for this {@code IntArrayList}
     * @return the index pointing to the corresponding element in the internal array
     */
    private int internalArrayIndex(int publicIndex) {
        int internalArrayIndex = publicIndex + indexOfFirstElement;
        if (internalArrayIndex < 0 || internalArrayIndex >= data.length) {
            internalArrayIndex -= data.length;
        }
        return internalArrayIndex;
    }

    public void add(final int value) {
        add(size, value);
    }

    public void add(final int index, final int value) {
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException(index);
        }

        if (size == data.length) {
            if (data.length == Integer.MAX_VALUE) {
                throw new OutOfMemoryError();
            } else {
                int newCapacity = data.length + data.length / 2; // Grow by approx. 1.5x
                if (newCapacity < 0) { //overflow
                    newCapacity = Integer.MAX_VALUE;
                }
                ensureCapacity(newCapacity);
            }
        }

        int internalInsertionIndex = internalArrayIndex(index);
        if (index >= (size + 1) >>> 1) { //right-push
            moveRangeWrapping(data, internalInsertionIndex, 1, size - index);
        } else { //left-push
            internalInsertionIndex = indexForOffset(internalInsertionIndex, -1);
            moveRangeWrapping(data, indexOfFirstElement, -1, index);
            indexOfFirstElement = indexForOffset(indexOfFirstElement, -1);
        }
        data[internalInsertionIndex] = value;
        size++;
    }

    public void set(final int index, final int value) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException(index);
        }
        data[internalArrayIndex(index)] = value;
    }

    public int get(final int index) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException(index);
        }
        return data[internalArrayIndex(index)];
    }

    public int remove() {
        return remove(size - 1);
    }

    public int remove(int index) {
        final int result = get(index);

        int internalDeletionIndex = internalArrayIndex(index);

        if (index >= size / 2) { //right-side-pull
            moveRangeWrapping(data, indexForOffset(internalDeletionIndex, 1), -1, size - index - 1);
        } else { //left-side-pull
            moveRangeWrapping(data, indexOfFirstElement, 1, index);
            indexOfFirstElement = indexForOffset(indexOfFirstElement, 1);
        }

        size--;
        return result;
    }

    public void clear() {
        size = 0;
        indexOfFirstElement = 0;
    }

    @Override
    public int hashCode() {
        int hashCode = 1;
        for (int i = 0; i < size; i++) {
            hashCode = 31 * hashCode + get(i);
        }
        return hashCode;
    }

    //moves a range without wrapping around
    private static void moveRange(int[] array, int sourceStartPosition, int destinationStartPosition, int length) {
        if (sourceStartPosition < 0 || destinationStartPosition < 0 || length < 0
                || sourceStartPosition > array.length - length
                || destinationStartPosition > array.length - length) {
            throw new IndexOutOfBoundsException();
        }
        int offset = destinationStartPosition - sourceStartPosition;
        if (offset > 0) {
            for (int i = destinationStartPosition + length - 1; i >= destinationStartPosition; i--) {
                array[i] = array[i - offset];
            }
        } else if (offset < 0) {
            for (int i = destinationStartPosition; i < destinationStartPosition + length; i++) {
                array[i] = array[i - offset];
            }
        }
    }

    //moves a range, wrapping around if necessary; requires that the foremost element
    //in the direction to be moved would not overwrite another element from the range to be moved
    private static void moveRangeWrapping(int[] array, int sourceStartPosition, int offset, int length) {
        if (length < 0 || length > array.length - Math.abs(offset)
                || sourceStartPosition < 0 || sourceStartPosition >= array.length) {
            throw new IndexOutOfBoundsException();
        }
        if (offset > 0) {
            if (sourceStartPosition > array.length - length - offset) {
                if (sourceStartPosition > array.length - length) {
                    moveRange(array, 0, offset, sourceStartPosition + length - array.length);
                }
                int tempStartPosition = Math.max(array.length - offset, sourceStartPosition);
                moveRange(array, tempStartPosition, tempStartPosition + offset - array.length, (sourceStartPosition < array.length - length ? sourceStartPosition + length : array.length) - tempStartPosition);
            }
            if (array.length - offset > sourceStartPosition) {
                moveRange(array, sourceStartPosition, sourceStartPosition + offset, Math.min(length, array.length - offset - sourceStartPosition));
            }
        } else if (offset < 0) {
            //sourceEndPosition is from 1 to array.length, inclusive
            int sourceEndPosition = sourceStartPosition + length;
            if (sourceEndPosition > array.length || sourceEndPosition < 0) {
                sourceEndPosition -= array.length;
            }

            if (sourceEndPosition + offset < length) {
                if (sourceEndPosition < length) {
                    moveRange(array, sourceStartPosition, sourceStartPosition + offset, array.length - sourceStartPosition);
                }
                int tempStartPosition = Math.max(0, sourceEndPosition - length);
                moveRange(array, tempStartPosition, tempStartPosition + offset + array.length, Math.min(-offset, sourceEndPosition) - tempStartPosition);
            }
            if (sourceEndPosition + offset > 0) {
                int tempStartPosition = Math.max(-offset, sourceEndPosition - length);
                moveRange(array, tempStartPosition, tempStartPosition + offset, sourceEndPosition - tempStartPosition);
            }
        }
    }
}

I've renamed length to size because I found length just too confusing with data.length always coming up somewhere. I've also replaced some of your ArrayIndexOutOfBoundsExceptions with IndexOutOfBoundsExceptions, since an ArrayIndexOutOfBoundsException is only meant for arrays, and not for any index-based data structure.

Unfortunately, the method moveRangeWrapping is an eyesore. Maybe this can be mitigated by introducing more local variables, but the problem is the constant threat of overflows, which often requires the comparison statements in a way that they don't lend themselves to use local variables (e.g. if (sourceStartPosition > array.length - length) instead of if (sourceStartPosition + length > array.length)), so I'm not sure how much can be done about this.

In addition, I've implemented hashCode() so that it produces a hash equivalent to the hash code of an analogous List<Integer>, which can be used both for testing purposes and to prevent clever compiler optimizations (hopefully).


Saturated signed addition So this a exercise from the book COMPUTERS SYSTEMS A PROGRAMMERS PERSPECTIVE

I need to add two signed numbers and in case it overflows or underflows return TMAX (011..1b) or TMIN (100..0b) respectively. In this case we can assumed two's complement representation.

The book imposes a set of rules that the solution must follow :

Forbidden:

Conditionals, loops, function calls and macros.
Division, modulus and multiplication.
Relative comparison operators (<, >, <= and >=).

Allowed operations:

All bit level and logic operations.
Left and right shifts, but only with shift amounts between 0 and w - 1
Addition and subtraction.
Equality (==) and inequality (!=) tests.
Casting between int and unsigned.

My code

int saturating_add(int x , int y) {
    int sum = x + y;
    int w = (sizeof(int) << 3) -1;
    int mask = (~(x ^ y) & (y ^ sum) & (x ^ sum)) >> w;
    int max_min = (1 << w) ^ (sum >> w);
    return  (~mask & sum) + (mask & max_min);
}

Compiled code in my machine

Note: I used the following command -> gcc -O2 -S sat_add.c.

leal    (%rdi,%rsi), %edx
    movl    %edx, %eax
    movl    %edx, %ecx
    xorl    %esi, %eax
    xorl    %edi, %esi
    xorl    %edx, %edi
    notl    %esi
    sarl    $31, %ecx
    andl    %esi, %eax
    addl    $-2147483648, %ecx
    andl    %edi, %eax
    sarl    $31, %eax
    movl    %eax, %esi
    andl    %ecx, %eax
    notl    %esi
    andl    %edx, %esi
    leal    (%rsi,%rax), %eax
    ret

So I want to know if there is a better solution in terms of elegance and performance. Also if there is a solution that compiles to a single instruction in x86_64 (Maybe PADDS although this instruction may not be the one I am looking for). Also any other kind of feedback is welcome.

Undefined behavior from signed overflow
Technically, your first line causes undefined behavior:

int sum = x + y;

It should be written instead as:
int sum = (unsigned int) x + y;

In C, signed integer overflow is undefined behavior but unsigned integer overflow is not.  Your compiler probably will treat the two lines above identically, but to be safe you should use the unsigned add.
Save a couple of instructions
This line here could be optimized:

int mask = (~(x ^ y) & (y ^ sum) & (x ^ sum)) >> w;

to this:
int mask = (~(x ^ y) & (x ^ sum)) >> w;

If x and y have the same sign, then you only need to check one of them against sum instead of both of them.  This saves 2 assembly instructions when you compile it.


Rails: create a relationship between comment and user I'm trying to connect the create of a comment to the current_user. I have a model comment which is a polymorphic association.

class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t|
      t.string :content
      t.references :commentable, polymorphic: true
      t.timestamps
    end
  end
end

In the controller I'm trying to connect the @comment.user = current_user.
controllers/comments_controller.rb

  def create
    @comment = @commentable.comments.new comment_params
    @comment.user = current_user
    @comment.save
    redirect_to @commentable, notice: 'Comment Was Created'
  end

But I get the following error:

  NoMethodError: undefined method `user=' for #
  Did you mean?  user_id=

I would rather set up a relationship from which I can get to a user (The creator of comment) from the comment itself. For example @comment.user instead of just having the id.

I have the following models:

class Question < ApplicationRecord
  belongs_to :user
  has_many :comments, as: :commentable
  has_rich_text :content
end

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :posts
  has_many :questions
  has_one_attached :avatar

  before_create :set_defaults

  def set_defaults
    self.avatar = 'assets/images/astronaut.svg' if self.new_record?
  end
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

Since comment is a polymorphic association, I'm not sure if it should be connected to user via a belongs_to to user.

[5] pry(#<Questions::CommentsController>)> @comment
=> #<Comment:0x00007fb3e6df72e8
 id: nil,
 content: "some test content",
 commentable_type: "Question",
 commentable_id: 1,
 created_at: nil,
 updated_at: nil,
 user_id: nil>
[6] pry(#<Questions::CommentsController>)>

Does this mean, I should create a foreign_key in the comments migration to a user? How can I go about getting the creator of the comment from the comment itself? Something like @comment.creator or @comment.user?

Don't think your question belongs to this code review section. You would have gotten help much faster if had posted in stackoverflow instead. Anyway there are couple points you need to check.

The CreateComments migration must have been updated (or at least there was another migration that changed the table) because the migration does not say anything about user_id column but the your model has that.
Since comment is a polymorphic association, I'm not sure if it should be connected to user via a belongs_to to user. You are confused between the polymorphic association relation and the user's relation of a comment. They are different, a comment belongs to a Question (or Post, Thread... that why you have polymorphic here) and also belongs to a user who created the comment. Even better, you can have another polymorphic association for commenter (I will skip it to avoid adding noise to your question)
Does this mean, I should create a foreign_key in the comments migration to a user? NO
How can I go about getting the creator of the comment from the comment itself? Something like @comment.creator or @comment.user? They are just methods rails generated for you after you setup the association, so yeah you can have whatever you want

Here is what I would do to get comment.commenter and comment.commenter= to work:

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
  belongs_to :commenter, class_name: 'User', foreign_key: 'user_id'
end


JavaScript function for finding perfect numbers The following function has been created for finding "Perfect Numbers".

About Perfect Numbers: Wikipedia

function findPerfectNumbers(upperLimit, currentTry = 2) {
  let perfectNumbers = [];
  let divisor;
  let sum;

  if (typeof upperLimit !== 'number' || isNaN(upperLimit) ||
          upperLimit < 2) {
    throw new TypeError(`First parameter is expected to a ` +
                      `number larger then 1 which is not NaN.`);
  }

  while (currentTry <= upperLimit) {  // <------- Start outer loop
    divisor = 2;
    sum = 0;

    while (currentTry >= divisor) {   // <------- Start inner loop
      let fraction = currentTry / divisor;
      let leftOver = currentTry % divisor;

      if (leftOver === 0) {
        sum += fraction;
      }

      divisor++;
    }                                 // <-------- End inner loop

    if (sum === currentTry) {
      perfectNumbers.push(currentTry);
    }

    currentTry++;
  }                                   // <-------- End outer loop

  return perfectNumbers;
}

// ------------ Demo ... --------------------------
console.log(findPerfectNumbers(1000));               // Returns : [6, 28, 496]
console.log(findPerfectNumbers(8140, 8100));         // [8128]
console.log(findPerfectNumbers(33550340, 33550335)); // [33550336]

It finds the first five Perfect Numbers. So I suppose my algorithm is basically correct.

But practically it doesn't work well.

Currently, it has a runtime complexity of \$O(n^2)\$. Therefore it becomes practically unusable from the fourth Perfect Number on upwards.

Therefore my question to the programmers who are more advanced than me:

Is there a way to improve the runtime complexity of the function?
If it isn't possible to change the algorithm, are there performance tricks one could use? like for example using shift operators instead of arithmetic operators?

All hints, comments, and tips concerning the points described above and the function in general appreciated.

If you check the wikipedia article you linked, you'll see the following:

  It was not until the 18th century that Leonhard Euler proved that the formula \$2^{p−1}(2^p − 1)\$ will yield all the even perfect numbers. Thus, there is a one-to-one correspondence between even perfect numbers and Mersenne primes; each Mersenne prime generates one even perfect number, and vice versa. This result is often referred to as the Euclid–Euler theorem.

A Mersenne prime is a prime that's constructed from \$2^p−1\$, where \$p\$ is prime. Not all values of \$p\$ produce a Mersenne prime, but it makes for much simpler code for finding perfect numbers:

For a prime \$p\$
Calculate \$m = 2^p-1\$
If \$m\$ is prime, it's a Mersenne prime
And thus \$2^{p-1}m\$ is a perfect number

So you'll want code to generate prime numbers, and code to check whether a number is prime.

There are a bunch of ways to generate primes (like this for starters) but for illustration let's use the simplest way: Loop through numbers, and check if they're prime. That's also the same feature we'll need later to check for Mersenne primes anyway.

const isPrime = (n) => {
  const limit = Math.sqrt(n);
  for(var i = 2 ; i <= limit ; i++) {
    if(n % i === 0) return false;
  }
  return true;
}

I.e. if a number is divisible by anything between 2 and its own square root, it's not prime.

Now, let's use that to generate, say, 10 primes:

const primes = [];
var i = 2;
while(primes.length < 10) {
  if(isPrime(i)) primes.push(i);
  i++;
}

So now we have 10 primes. Again, this is a very naïve way to do things, but it works for illustrative purposes.

So now, we can loop through those primes, and use them to construct Mersenne primes (sometimes), and from there, perfect numbers:

primes.forEach(p => {
  const m = Math.pow(2, p) - 1; // calculate 2^p - 1

  if(!isPrime(m)) {
    return; // go to next prime if m isn't a (Mersenne) prime
  }

  // calculate and print the perfect number
  const perfectNumber = Math.pow(2, p - 1) * m;
  console.log(perfectNumber);
});

Another way to write (and get an array back) might be:

const perfectNumbers = primes
  .map(p => { return {p: p, m: Math.pow(2, p) -1} })
  .filter(pair => isPrime(pair.m))
  .map(pair => pair.m * Math.pow(2, pair.p - 1));

Point is, from the first 10 primes you get the first 7 perfect numbers:

6
28
496
8128
33550336
8589869056
137438691328

in a few milliseconds.

So that's cool. But don't overdo it; this is not a simple problem. Wikipedia notes that only 49 Mersenne primes are known to date (the largest has 44,677,235 digits!) and thus only 49 perfect numbers. And in JavaScript, things will go wrong long before that: Since all JS numbers are 64-bit floats they simply can't hold large enough values.

The largest integer that a JS number can hold without introducing floating point errors is Number.MAX_SAFE_INTEGER, which is 9,007,199,254,740,991. Pretty big, sure, but only big enough for the first 7 perfect numbers listed above. The 8th should be 2,305,843,008,139,952,128 but the closest JS can do is 2,305,843,008,139,952,000. Oh well.

You might try looking just for the many-orders-of-magnitude-smaller Mersenne primes, and skip the actual calculation of the corresponding perfect number. If you have a Mersenne, you have a perfect number, after all. Unfortunately though, the 8th Mersenne prime is already \$2^{61} - 1\$ and thus too big to store. So in regular JS, you'll have to be happy with the first 7 Mersenne primes/perfect numbers.


IoC component registration How do you list your referenced solution assemblies for IoC registration? I was really tired of typing something strange as new [] { typeof(SomeType).Assembly, … }. What do you think about the following approach?

Use case:

class Program
{
    static void Main(string[] args)
    {
        foreach (var a in Solution.Assemblies)
            Console.WriteLine(a);
    }
}

Where Solution.Assemblies is:

public static class Solution
{
    static IEnumerable<string> AssemblyNames => new[] {
        "ValueCache", "ValueCache.Tests", "LazyProxies", "ConsoleApplication1", "ClassLibrary1"
    };

    public static IEnumerable<Assembly> Assemblies => AssemblyNames
        .Select(an => Load(an))
        .Where(a => a != null);

    [DebuggerHidden]
    static Assembly Load(string assemblyName)
    {
        try
        {
            return Assembly.Load(new AssemblyName(assemblyName));
        }
        catch
        {
            return null;
        }
    }
}

… being generated by Solution.tt file:

<#@ template debug="false" hostSpecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="EnvDte" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Diagnostics;

namespace SolutionConfiguration
{
    public static class Solution
    {
        static IEnumerable<string> AssemblyNames => new[] {
            <#= String.Join(", ", from name in new SolutionAssemblyNames(Host)
                                  select $"\"{name}\"") #>
        };

        public static IEnumerable<Assembly> Assemblies => AssemblyNames
            .Select(an => Load(an))
            .Where(a => a != null);

        [DebuggerHidden]
        static Assembly Load(string assemblyName)
        {
            try
            {
                return Assembly.Load(new AssemblyName(assemblyName));
            }
            catch
            {
                return null;
            }
        }
    }
}

<#+

    class SolutionAssemblyNames : IEnumerable<string>
    {
        public SolutionAssemblyNames(ITextTemplatingEngineHost host)
        {
            Host = host;
        }

        public IEnumerator<string> GetEnumerator() => Assemblies.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
        IEnumerable<string> Assemblies => Projects
            .Select(p => p?.Properties?.Item("AssemblyName")?.Value as string)
            .Distinct().Where(a => !string.IsNullOrWhiteSpace(a));

        IEnumerable<Project> Projects => VisualStudio.Solution.Projects.OfType<Project>();
        DTE VisualStudio => (Host as IServiceProvider).GetService(typeof(DTE)) as DTE;
        ITextTemplatingEngineHost Host { get; }
    }
#>

This is a fascinating solution. I kept looking at it and thinking "There must be an easier way!" but every possible solution I came up with had a fatal flaw.

All I really have, then, is nitpicking:

public static IEnumerable<Assembly> Assemblies => AssemblyNames
        .Select(an => Load(an))

Can be simplified to:

public static IEnumerable<Assembly> Assemblies => AssemblyNames
    .Select(Load)

SolutionAssemblyNames is looking fairly dense. I'd add 1 line of whitespace between each property to make it a bit more readable.