texts: Refactor nested foreach loop based on object property

texts:
I'm using a levenshtein matching algorithm to match a title to a filename (for anime). I either use the main show title for matching or its alternative titles (flexget_titles).

For that I have the following snippet of code.

public function matchFilenameToShow($filename)
{
    $shows = $this->shows->getAll();
    $shortest = -1;
    $clean_name = $this->removeEpisodeNumber($this->cleanFilename($filename));
    foreach ($shows as $show) {
        if (!empty($show->flexget_titles_array)) {
            foreach ($show->flexget_titles_array as $title) {
                // calculate the distance between the input string filename,
                // and the current show name
                $lev = levenshtein(strtolower($clean_name), strtolower($title));
                // if this distance is less than the next found shortest
                // distance, OR if a next shortest distance to the word has not yet been found
                if ($lev <= $shortest || $shortest < 0) {
                    // set the closest match, and shortest distance
                    $matchedShow = $show;
                    $shortest = $lev;
                }
            }
        } else {
            // calculate the distance between the input string filename,
            // and the current show name
            $lev = levenshtein(strtolower($clean_name), strtolower($show->title));
            // if this distance is less than the next found shortest
            // distance, OR if a next shortest distance to the word has not yet been found
            if ($lev <= $shortest || $shortest < 0) {
                // set the closest match, and shortest distance
                $matchedShow = $show;
                $shortest = $lev;
            }
        }
    }
    return $matchedShow;
}

Obviously there is code repetition and I want to refactor this. However I'm not sure how to do it. I have a feeling that I need to extract that levenshtein part to a separate method, but I need to return 2 variables.


texts: Retry a Promise resolution N times, with a delay between the attempts

texts:
I want some JavaScript code to take 3 things as parameters:

A function returning a Promise.
The maximum number of attempts.
The delay between each attempt.

What I ended up doing is using a for loop. I did not want to use a recursive function : this way, even if there are 50 attempts the call stack isn't 50 lines longer.

Here is the typescript version of the code:

/**
 * @async
 * @function tryNTimes<T> Tries to resolve a {@link Promise<T>} N times, with a delay between each attempt.
 * @param {Object} options Options for the attempts.
 * @param {() => Promise<T>} options.toTry The {@link Promise<T>} to try to resolve.
 * @param {number} [options.times=5] The maximum number of attempts (must be greater than 0).
 * @param {number} [options.interval=1] The interval of time between each attempt in seconds.
 * @returns {Promise<T>} The resolution of the {@link Promise<T>}.
 */
export async function tryNTimes<T>(
    {
        toTry,
        times = 5,
        interval = 1,
    }:
        {
            toTry: () => Promise<T>,
            times?: number,
            interval?: number,
        }
): Promise<T> {
    if (times < 1) throw new Error(`Bad argument: 'times' must be greater than 0, but ${times} was received.`);
    let attemptCount: number;
    for (attemptCount = 1; attemptCount <= times; attemptCount++) {
        let error: boolean = false;
        const result = await toTry().catch((reason) => {
            error = true;
            return reason;
        });

        if (error) {
            if (attemptCount < times) await delay(interval);
            else return Promise.reject(result);
        }
        else return result;
    }
}

The delay function used above is a promisified timeout:

/**
 * @function delay Delays the execution of an action.
 * @param {number} time The time to wait in seconds.
 * @returns {Promise<void>}
 */
export function delay(time: number): Promise<void> {
    return new Promise<void>((resolve) => setTimeout(resolve, time * 1000));
}

Is this a "good" way of doing it? And if not, how could I improve it?


texts:
I recently read an article in which the authors present Algorithm 1 to compute a simultaneous confidence interval.  I was interested in implementing Algorithm 1 in R here.  The algorithm is freely available at the link.

Please review this to verify that I've implemented the algorithm correctly. It uses a toy example with the built-in R datasets "trees."  I tried to comment my code and name variables in a way similar to the published algorithm.

library(MASS)
alpha<-.05
B=100000
#Use toy example from R's trees dataset
myfit<-lm(Height~Girth+Volume, data=trees)
myfit
param<-coef(myfit)
coefficients<-length(param)
mycov<-vcov(myfit)
#Simulate 10K bootstrap samples using the estimated mean vector and covariance matrix
#from the regression model
#Step 1.
theata.tilde.b<-mvrnorm(B, mu=param, Sigma=mycov)
head(theata.tilde.b)

#Step 2
rbj<-apply(theata.tilde.b, 2, rank)

#Step 3.
sample.b.rank.upper<-apply(rbj, 1, max)
sample.b.rank.lower<-apply(rbj, 1, min)

boot.df<-data.frame(cbind(theata.tilde.b, rbj, sample.b.rank.upper, sample.b.rank.lower))
names(boot.df)<-c("B0", "B1", "B2", "Rank0", "Rank1", "Rank2", "SampleBRankUpper", "SampleBRankLower")

upper.index<-B*(1-alpha/2)
lower.index<-B*(alpha/2)
#Sort datasets by max and then min rank of the sample-b rank
upper<-(boot.df[order(boot.df$SampleBRankUpper),])
lower<-(boot.df[order(boot.df$SampleBRankLower),])

#Step 5
upper[upper.index,1:coefficients]
lower[lower.index,1:coefficients]


texts:
I have a class that spawns threads to process data. I am working on instrumentation code. When the process is started, time = System.currentTimeMillis(); When it completes, time = System.currentTimeMillis() - time; I have a method to retrieve this time:

/**
 * Get the time taken for process to complete
 *
 * @return Time this process has run if running; time it took to complete if not
 */
public long getRunTime() {
   return processRunning? System.currentTimeMillis() - time : time;
}

Is this a clear use of the ternary operator? Is my javadoc comment clear?


texts:
I have implemented a maze with

a function addCoordinate where x and y denote the x and y coord of grid and block type: zero means open and 1 means wall.
a printMaze function which prints the maze with * for wall and empty space for open spaces.

My implementation seems to be working fine but could there be a better way of doing this:

class Maze:
    board, max_x, max_y, list = [],2,2,[]

    def __init__(self):
        """
        Constructor - You may modify this, but please do not add any extra parameters
        """

    def addCoordinate(self, x, y, blockType):
        """
        Add information about a coordinate on the maze grid
        x is the x coordinate
        y is the y coordinate
        blockType should be 0 (for an open space) of 1 (for a wall)
        """
        if x > self.max_x:
            self.max_x = x
        if y > self.max_y:
            self.max_y = y
        if self.max_y >= len(self.board) or self.max_x >= len(self.board[0]):
            newboard = [[1 for a in range(self.max_x + 1)] for b in range(self.max_y + 1)]
            for i in range(len(self.board)):
                for j in range(len(self.board[i])):
                    newboard[i][j] = self.board[i][j]
            self.board = newboard
        self.board[y][x] = blockType
    def printMaze(self):
        """
        Print out an ascii representation of the maze.
        A * indicates a wall and a empty space indicates an open space in the maze
        """

        for i in range(self.max_x + 1):
            for j in range(self.max_y + 1):
                if self.board[i][j] == 0:
                    print " ",
                else:
                    print "*",
            print ""

def mazeTest():
    """
    This sets the open space coordinates for the example
    maze in the assignment.
    The remainder of coordinates within the max bounds of these specified coordinates
    are assumed to be walls
    """
    myMaze = Maze()
    myMaze.addCoordinate(1, 0, 0)
    myMaze.addCoordinate(1, 1, 0)
    myMaze.addCoordinate(7, 1, 0)
    myMaze.addCoordinate(1, 2, 0)
    myMaze.addCoordinate(2, 2, 0)
    myMaze.addCoordinate(3, 2, 0)
    myMaze.addCoordinate(4, 2, 0)
    myMaze.addCoordinate(6, 2, 0)
    myMaze.addCoordinate(7, 2, 0)
    myMaze.addCoordinate(4, 3, 0)
    myMaze.addCoordinate(7, 3, 0)
    myMaze.addCoordinate(4, 4, 0)
    myMaze.addCoordinate(7, 4, 0)
    myMaze.addCoordinate(3, 5, 0)
    myMaze.addCoordinate(4, 5, 0)
    myMaze.addCoordinate(7, 5, 0)
    myMaze.addCoordinate(1, 6, 0)
    myMaze.addCoordinate(2, 6, 0)
    myMaze.addCoordinate(3, 6, 0)
    myMaze.addCoordinate(4, 6, 0)
    myMaze.addCoordinate(6, 6, 0)
    myMaze.addCoordinate(7, 6, 0)
    myMaze.addCoordinate(5, 7, 0)

    myMaze.printMaze()

mazeTest()

Output:

*   * * * * * *
*   * * * * *
*         *
* * * *   * *
* * * *   * *
* * *     * *
*         *
* * * * *   * *


texts: Using Scanner.nextInt() whilst ignoring rest of line

texts:
I'm contemplating how to read an int using Scanner.nextInt(), and at the same time ignore the rest of the line or flush the input buffer to be ready for inputting the next number. Typical usage would be to read a number where the user is likely to add units or similar after the number, and I want the scanner to be cleared out before I output a new message and ready for the next number.

In the following code I firstly use Scanner.nextLine() to read rest of line, and in the second I attempted to use the Scanner.hasNext() to detect if anything was present. But it originally failed, so to get it to work I had to add a bug-fix related to writing the text "quit". The third read is just to finish off with a final read of an integer.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("1) Enter an integer (with some junk like units): ");
        int myFirstInt = scanner.nextInt();
        // Ignore rest of line
        scanner.nextLine();

        System.out.print("2) Enter an integer (and some junk afterwards): ");
        int mySecondInt = scanner.nextInt();

        // Clear out scanner before next read...
        String line;                    // Fix to avoid endless loop
        while (scanner.hasNext()) {
            line = scanner.next();
            if (line.equals("quit")) {  // Fix to avoid endless loop
                break;                  // Fix to avoid endless loop
            }                           // Fix to avoid endless loop
        }

        System.out.print("3) Enter the third integer: ");
        int myThirdInt = scanner.nextInt();

        System.out.printf("\nFirst: %d, Second: %d, Third: %d\n",
                          myFirstInt, mySecondInt, myThirdInt);
    }
}

A typical run with this code:

1) Enter an integer (with some junk like units):  123 kg
2) Enter an integer (and some junk afterwards):  45 stones 5 pound
 quit
3) Enter the third integer:  238

First: 123, Second: 45, Third: 238

The code now works (with the need for entering "quit" at the second prompt), but I'm wondering whether there is a safer or better method for clearing out the scanner, so I can get it ready for reading the next input. Hopefully with the out endless loop fix. The output is as expected.


texts: Counting Divisors of a number with restrictions on the divisors

texts:
Given a fraction p/q, I want to count the number of unit fraction solutions

$$\frac{p}{q} = \frac{1}{u} + \frac{1}{v}$$

with some contraints

$$lower \le u \le upper$$

By manipulating the first equation and completing a square you arrive at a formula

$$(pu - q)(pv - q) = q^2$$

So the number of solutions is related to the divisors of q squared. If we only look at the smaller of two divisors (which we will call a), it is a solution if it produces a valid unit fraction (1 / u).

$$a = pu - q \implies u = \frac{a + q}{p}$$

We are interested in a divisor a iff

$$p*lower - q \le a \le p * upper - q, \space a \equiv -q \mod p$$

To compute the answer I first get the prime factorisation of q, then I  double each power to get the prime factorisation of q squared. Using this I enumerate over all the possible divisors, computing each one by trying all possible combination of powers. When I generate one I check if it matches the above requirements.

def factor_m(p, q, lower, upper):
    num = q
    factors = dict()
    count = 0
    while num % 2 == 0:
        num //= 2
        count += 1
    if count:
        factors[2] = count

    current = 3
    while num > 1:
        count = 0
        while num % current == 0:
            num //= current
            count += 1
        if count:
            factors[current] = count
        current += 2

    start, end = p * lower - q, p * upper - q
    mod = -q % p
    total = 0
    for powers in product(*(range((2 * v) + 1) for v in factors.values())):
        number = 1
        for b, _power in zip(factors, powers):
            number *= b ** _power

        if start <= number <= end and number % p == mod:
            total += 1

    return total

I'm calling this function a lot with reasonably big values of q (around 10**14 currently) so anything that saves time here is a massive boost.

Examples:

>>> factor_m(2, 7, 0, 50)  # 3
>>> factor_m(5, 1775025265104, 355005053021, 710010106041)  # 4101
>>> factor_m(737, 1046035200, 1926400, 2838630)  # 1
>>> factor_m(105467, 1231689911361, 11678439, 23356877)  # 0

EDIT To guarantee all solutions are distinct I only call the function with values that satisfy the constraint

$$lower \lt upper \le q$$

EDIT2 I ran the full program through cProfile along with the program with modifications suggested by Josay. Unfortunately it is slower, I suspect because it almost doubles the number of function calls.

current_code - top 3 functions by time

672574 function calls (614969 primitive calls) in 19.526 seconds

 ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  53273   18.818    0.000   18.893    0.000 fast.py:40(factor_m)
   2957    0.295    0.000    0.298    0.000 fast.py:8(factor_p1)
57606/1    0.149    0.000   19.525   19.525 fast.py:75(f)

With Josay's changes - top 3 functions by time

1163833 function calls (1106228 primitive calls) in 19.835 seconds

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
53273   18.427    0.000   19.160    0.000 fast.py:61(factor_m)
53273    0.500    0.000    0.650    0.000 fast.py:42(get_factors)
 2957    0.297    0.000    0.301    0.000 fast.py:8(factor_v2)


texts:
How do I refactor this mess of if/else conditions so that it's more readable?

    ( Reverse_Path = [[]] -> Child = [c(New_Score,G1,Pos),P]
    ; otherwise -> Child = [c(New_Score,G1,Pos),P|Reverse_Path]
    ),
    (  memberchk(Child,NewAgenda) -> addChildren(Others,Reverse_Path,Current,NewAgenda,Target,Result)

    ;  otherwise ->
        (   NewAgenda=[] -> BrandNewAgenda = [Child|NewAgenda]
        ;   otherwise    ->
            (New_Score =< FP -> BrandNewAgenda = [Child|NewAgenda];
            otherwise  -> append(NewAgenda,[Child],BrandNewAgenda)
            )
        ),

    )).


texts: php function for gathering includes...is there a better way than this?

texts:
I am building a dynamic site. All data will be served through an index.php in my webroot, using jquery to update the content. In webroot, I have a folder 'i/' which contains the files I want to include. The main include files contain code which will be used on every page: globals.php, globals.css, globals.js, etc. plus library files, such as jquery.js. Then there are secondary includes that are used depending on the section or topic that has been loaded: topic1.php, topic1.css, topic1.js, etc.

I have written the following php function to call all the files that need to be declared in the head (stylesheets and javascript for now, but wanted to make it easy to add more filetypes in the future), allowing globals.php to be included before the html tag (and will probably include topics.php from inside globals.php). However, I'm not really sure if this is a very efficient function, or if there is a better way to do what I'm trying to:

function getIncludes($topic){
    $type=array("css","js");
    $library=array("js"=>array("jquery"));
    $scope=array("globals",$topic);
    foreach($type as $ext){
        $includes=array();
        if(array_key_exists($ext, $library)){
            foreach ($library[$ext] as $file){
                array_push($includes, $file);
            }
        }
        foreach($scope as $file){
            array_push($includes, $file);
        }
        foreach($includes as $file){
            if(file_exists('i/'.$file.'.'.$ext)){
                if($ext=="css"){
                    echo '<link rel="stylesheet" type="text/css" href="i/'.$file.'.'.$ext.'" />';
                }
                if($ext=="js"){
                    echo '<script type="text/javascript" src="i/'.$file.'.'.$ext.'"></script>';
                }
            }
        }
    }
}

Is this a good way of achieving my goal, or can I do better?


texts:
The following code is very slow. I was wondering if you can help me speed it up.

private void filter(List<CheckBox> boxList)
        {
            // refLanguageTabs is a TabControl the Tabcount is 9
            for (int i = 0; i < refLanguageTabs.TabCount; i++)
            {
                Control[] ctrls = refLanguageTabs.TabPages[i].Controls.Find(refLanguageTabs.TabPages[i].Name + "Grid", true);
                DataGridView dgv = ctrls[0] as DataGridView;

                // average row count is 3000
                for (int j = 0; j < dgv.RowCount; j++)
                {
                    for (int k = 0; k < boxList.Count; k++)
                    {
                        if (dgv.Rows[j].Cells[1].Value.ToString() != boxList[k].Name.ToString())
                        {
                            dgv.Rows[j].Visible = false;
                        }
                    }
                }
                dgv.Refresh();
            }
        }


texts: Inefficient Parsec parser to skip unreachable block

texts:
In a parser written with Parsec 3.1.11, I have a performance issue with parsing (or better, skipping) the unreachable branch of a if-then-else statement.

The syntax to be parsed is as follows:

_if (condition) {
  # block of statements
} _else {
  # block of statements
}

The _else branch is optional and only statically resolvable conditions are allowed.

The parser for the if-then-else block:

type MyParser a = ParsecT T.Text UserState (StateT UserState Identity) a

ifelseStmt :: MyParser -> [Statement]
  = do  reserved "_if"
        e <- parens expression
        if evalBoolExpr e
          then do b <- block
                  option [] $
                    do reserved "_else"
                       unparsedBlock
                  return b
          else do unparsedBlock
                  option [] $
                    do reserved "_else"
                       block

Now, parser unparsedBlock is meant to throw away the entire {...} block of the unreachable branch. Obviously this can in turn contain {..} blocks, which means curly brackets have to be matched.

This is the parser I wrote for it:

unparsedBlock :: MyParser -> [Statement]
  = do braces (many (do { noneOf "{}"; return []}  <|> unparsedBlock))
       return []

It works well, but the profiler shows that way too much time is spent on it, while I'd expect it to be rather efficient.

Can anyone see how I could implement unparsedBlock more efficiently?


texts: LeetCode - Weekly Contest 213 - Kth Smallest Instructions

texts:
Hi I participated in Leetcode weekly contest 213 and am facing issue with submission for below question
Kth Smallest Instructions

Bob is standing at cell (0, 0), and he wants to reach destination:
(row, column). He can only travel right and down. You are going to
help Bob by providing instructions for him to reach destination.
The instructions are represented as a string, where each character is
either:
'H', meaning move horizontally (go right), or 'V', meaning move
vertically (go down). Multiple instructions will lead Bob to
destination. For example, if destination is (2, 3), both "HHHVV" and
"HVHVH" are valid instructions.
However, Bob is very picky. Bob has a lucky number k, and he wants the
kth lexicographically smallest instructions that will lead him to
destination. k is 1-indexed.
Given an integer array destination and an integer k, return the kth
lexicographically smallest instructions that will take Bob to
destination.
Example 1 :
Input: destination = [2,3], k = 1
Output: "HHHVV"
Explanation: All the instructions that reach (2, 3) in lexicographic
order are as follows: ["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH",
"HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].
Constraints:
destination.length == 2
1 <= row, column <= 15
1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b.

I tried to create all the possible paths lexicographically and stop when count reached k, but it giving me TLE.
Below is my code :
public class Solution {
    String res = string.Empty;
    int count = 0;
    int K;
    public string KthSmallestPath(int[] destination, int k) {
        K=k;
        this.FindAllPaths("", destination[1], destination[0]);

        return res;
    }

    public void FindAllPaths(string currPath, int hRem, int vRem)
    {
        if(count == K)   return;
        if(hRem == 0 && vRem == 0)
        {
            res = currPath;
            count++;
            return;
        }

        if(hRem != 0)
        {
            this.FindAllPaths(currPath + 'H', hRem - 1, vRem);
        }

        if(vRem != 0)
        {
            this.FindAllPaths(currPath + 'V', hRem, vRem - 1);
        }
    }
}

Any idea on how can I  optimize the code so that it passes all the test cases.


texts: Huffman encoding successive-merge function

texts:
From SICP:

  Exercise 2.69.  The following
  procedure takes as its argument a list
  of symbol-frequency pairs (where no
  symbol appears in more than one pair)
  and generates a Huffman encoding tree
  according to the Huffman algorithm.

(define (generate-huffman-tree pairs)
    (successive-merge (make-leaf-set pairs)))

  Make-leaf-set is the procedure given
  above that transforms the list of
  pairs into an ordered set of leaves.
  Successive-merge is the procedure you
  must write, using make-code-tree to
  successively merge the smallest-weight
  elements of the set until there is
  only one element left, which is the
  desired Huffman tree. (This procedure
  is slightly tricky, but not really
  complicated. If you find yourself
  designing a complex procedure, then
  you are almost certainly doing
  something wrong. You can take
  significant advantage of the fact that
  we are using an ordered set
  representation.)

I wrote the following solution:

(define (generate-huffman-tree pairs)
  (successive-merge (make-leaf-set pairs)))

(define (successive-merge leaf-set)
  (define (iter result leaf-subset)
    (if (null? leaf-subset)
        result
        (let ((first-leaf (car leaf-subset)))
          (iter (make-code-tree first-leaf result) (cdr leaf-subset)))))
  (iter (make-code-tree (car leaf-set) (cadr leaf-set)) (cddr leaf-set)))

Is this a good answer?  Can it be improved?


texts: Publishing a description about a selected band

texts:
This is a basic program I wrote that lets you select a band, and give a description about the band and publish what you wrote.

Are there ways I can apply concepts of OOP to improve this code?  Any help and tips would be greatly appreciated!

(I tried to put this on JSFiddle, but it was rendering differently.)

        <title>Foo</title>

        <form name="form1">
            <input type="radio" name="band" value="Led Zeppelin" />Led Zeppelin

            <input type="radio" name="band" value="Red Hot Chili Peppers" />Red Hot Chili Peppers

            <input checked="checked" type="radio" name="band" value="The Beatles" />The Beatles

            <input type ="text" name="description" value="Enter something"/>

        </form>
        <button onclick="addEntry()">Add row</button>

        <button onclick="removeEntry()">Remove most recent entry</button>


texts: nodeJS, fs, path - creating new directorties

texts:
I wrote this function that takes 2 arguments - the path to an existing file - file, and the newRoot name. The function splits the new path into directories, replaces the first directory in the path to the file with newRoot, , then loops trough all the directories checking if the director exists, and if not creates one:

/**
 * Creates directories for the file in newRoot if not there
 * @param {String} file - the path to the file
 * @param {String} newRoot - the new root directory for the file
 */
functions.makeDirectory = (file, newRoot) => {
  let dirPath = path.dirname(file);
  let directories = dirPath.split('/');
  let currentPath = '';
  directories[0] = newRoot;
  directories.map(directory => {
    currentPath = path.join(currentPath, directory);
    if(!fs.existsSync(currentPath)) {
      fs.mkdirSync(currentPath);
    };
  });
};

The string operations here seem a bit redundat, but I can't figure out how to get rid of them. Is there a more optimal solution for this or am I on the right track?

Would it increase performance to rewrite the fs function as a promise?


texts:
I implemented a Hangman/guess the word clone in Python. This is my first attempt at making an actual interactive app instead of just a list of functions or a static program. It is also the first time I try to actually implement classes since I've been having a hard time wrapping my head around them. It's probably not the best or most practical application for a class, but it saved me the trouble of having to go around declaring globals and nonlocals throughout the code.

import json
import random
from os import system, name
import msvcrt
import colorama

class Hangman:
    def __init__(self):
        self.level = ""
        self.word = ""
        self.wrong_chars = []
        self.from_victory = 0
        self.from_defeat = 0
        self.game_state = ""
        self.on_repeat = True

    @staticmethod
    def cls():
        system('cls' if name == 'nt' else 'clear')

    def difficulty_scene(self):
        print("""
  DIFFICULTY LEVEL:
  ------------------

  (1) Very easy.
  Very long words (10+ characters) and 10 lives

  (2) Easy.
  Long words (8 or 9 characters) and 8 lives

  (3) Standard.
  Medium words (6 or 7 characters) and 6 lives

  (4) Hard.
  Short words (4 or 5 characters) and 4 lives

  (5) Impossible.
  Tiny words (3 characters) and 3 lives.

    """)
        self.level = input("  Select difficulty (1-5): ")

    def game_prep(self):
        self.word = word_list[-int(self.level) + 5][int(random.random()
                                                        * len(word_list))]
        self.wrong_chars = []
        self.from_victory = len(self.word)
        self.from_defeat = self.make_from_defeat()
        self.game_state = ""

    def make_from_defeat(self):
        return {
            "1": 10,
            "2": 8,
            "3": 6,
            "4": 4,
            "5": 3
        }.get(self.level, 6)

    def main_scene(self):
        colorama.init()

        print(f"\n  {'_' * len(self.word)}")

        while True:
            char = msvcrt.getch().decode('UTF-8')
            if char in self.word:
                for i in range(len(self.word)):
                    if char == self.word[i]:
                        print(f'\x1b[2;{i+3}H', end="")
                        print(char, end="")
                        self.from_victory -= 1
            else:
                self.wrong_chars.append(char)
                print(f'\x1b[4;{((len(self.wrong_chars) - 1) * 2) + 3}H', end="")
                print(char, end="")
                self.from_defeat -= 1
            if self.from_victory == 0 or self.from_defeat == 0:
                break

    def end_scene(self):
        if self.from_victory == 0:
            print("\n  YOU HAVE WON")
        elif self.from_defeat == 0:
            print("\n  YOU HAVE LOST")
            print(f"  your word was {self.word}")
        repeat = input("\n  Try again? (y/n):\n  ")
        if repeat == "y":
            self.on_repeat = True
        else:
            self.on_repeat = False

    def main(self):
        self.cls()
        self.difficulty_scene()
        self.cls()
        while self.on_repeat:
            self.game_prep()
            self.main_scene()
            self.cls()
            self.end_scene()
            self.cls()

game = Hangman()

if __name__ == '__main__':

    with open("words.json", "r") as read_file:
        word_list = json.load(read_file)

    game.main()

words.json is a 2-dimensional array of words sorted by length.


texts: Expect all values in an array to be greater than 30

texts:
I've given an array of elements and need to check that every single text is a number greater than 30. Sample input data:

40

31

32

101

Currently, I'm using .each() function to process every element one by one and then parseInt() and toBeGreaterThan() jasmine matcher:

var dataItems = element.all(by.css("ul.data-list > li.data-item"));
dataItems.each(function (elm) {
     elm.getText().then(function (text) {
         expect(parseInt(text)).toBeGreaterThan(30);
     });
});

Is there a simpler or better way to address the problem? Would it be appropriate to first map() into an array of integers and then apply the matcher to every element of an array?

What I am a bit concerned about in using the current approach is that it would fail at the very first element that is less than or equal to 30 preventing us to see what other values of an array are.


texts: Is there a simple way to use Underscorejs to achieve this?

texts:
I have an object, having key and values.  I'd like to pick the object and call the appropriate function from the key:

var requireViews = {
            "breadCrumbView": true,
            "headerView": false,
            "footerView": false
        };

var that = this;

    _.each(requireViews, function(value, key){
                    if(value){ //if true?
                        if(_.functions(that, key)) that[key](); //checking is that function, and calling the function
                    }
                })

Is it ok or can we minimize it further?


texts: Updating database based on selected check boxes

texts:
I posted the original question here, but I think it would be nice to have someone else's eye on this code for improving it.

public override void Update(UserProfileDto item)
{
    base.Update(item);

    var memberIntersestIds = _memberInterestService.GetAllPlusDeleted();

    var dbIds = memberIntersestIds.Select(p => p.InterestSubCategoryId);
    var union = dbIds.ToList().Union(item.InterestIds);

    if (item.InterestIds != null)
    {
        var guids = union as Guid[] ?? union.ToArray();
        foreach (var id in guids)
            if (_memberInterestService.IsSubInterestExist(id))
                _memberInterestService.Delete(id, item.Id, true);

        foreach (var id in guids)
        {
            if (!_memberInterestService.IsSubInterestExist(id))
                _memberInterestService.Add(new MemberInterestDto
                {
                    UserProfileId = item.Id,
                    InterestSubCategoryId = id
                });
            else
                _memberInterestService.Delete(id, item.Id, false);
        }
    }
    else
        foreach (var memberInterest in memberIntersestIds)
            _memberInterestService.Delete(memberInterest.InterestSubCategoryId, item.Id, true);
}

MemberIntersetService

public class MemberInterestService : IMemberInterestService
{
    public IQueryable<MemberInterest> Items { get { return _dbSet.Where(x => x.IsDeleted == false); } }

    public MemberInterestService(AppDbContext dbContext) : base(dbContext)
    {
        _dbSet = dbContext.MemberInterests;
    }

    public bool IsSubInterestExist(Guid subInterestId)
    {
        return _dbSet.Any(p => p.InterestSubCategoryId == subInterestId);
    }

    public bool IsSubInterestExistInItem(Guid subInterestId)
    {
        return Items.Any(p => p.InterestSubCategoryId == subInterestId);
    }

    public void Delete(Guid interestId, Guid userProfileId, bool delete)
    {
        var item = _dbSet.Single(x => x.InterestSubCategoryId == interestId && x.UserProfileId == userProfileId);

        //soft delete
        item.IsDeleted = delete;

        _dbSet.Update(item);
    }

    public IList<MemberInterestDto> GetAllPlusDeleted()
    {
        return _dbSet.Select(x => Mapper.Map<MemberInterest, MemberInterestDto>(x))
            .ToList();
    }
}


texts:
I want to backup my GitHub repositories since there is news about blocking GitHub in India. I wrote Python code to automate this and would like for it to be reviewed.

import os
import requests

API_TOKEN='xxxxx'
#from https://github.com/settings/applications

api_repo='https://api.github.com/user/repos'

url = '%s?access_token=%s' % \
(api_repo,API_TOKEN,)

r = requests.get(url).json()
git_urls = [repo['git_url'] for repo in r]
for i in git_urls:
  os.system("git clone "+i)


texts:
I am currently going through Codecademy's Python course (I don't come from a coding background but I'm thoroughly enjoying it) and I got to the end of one of the sections and thought, "Well it worked, but that seemed wildly inefficient."  I tried shortening unnecessary parts and came up with this:

lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

classlist = [lloyd, alice, tyler]

# Add your function below!

def get_average(student):
    average_homework = sum(student["homework"]) / len(student["homework"])
    average_quizzes = sum(student["quizzes"]) / len(student["quizzes"])
    average_tests = sum(student["tests"]) / len(student["tests"])
    average_total = average_homework * 0.1 + average_quizzes * 0.3 + average_tests * 0.6
    return average_total

def get_letter_grade(score):
    if score >= 90:
        return "A"
    if score < 90 and score >= 80:
        return "B"
    if score < 80 and score >= 70:
        return "C"
    if score < 70 and score >= 60:
        return "D"
    else:
        return "F"

def get_class_average(classlist):
    a = []
    for student in classlist:
        a.append(get_average(student))
    return sum(a) / len(a)

get_class_average(classlist)

Now this bit works, but I was wondering if there are more places I could trim the code down without losing the functionality (I'm guessing there is in the get_average function but the things I tried came back as errors because of the "name" field in the dictionary). Codecademy seems good for learning the fundamentals, but I wanted to get some insight into the "best" way to do things.  Should I not worry about reworking functional code to be more efficient at first and just learn the fundamentals, or should I keep trying to make the "best" code as I learn?


texts: A basic pure Python hash map using a tree

texts:
I would like feedback on my first attempt to understand how hash tables work. I've read some on how hash tables use modulo operations to find the location of a key.

Can you help me understand, compare the modulo approach with my attempt to use a tree?

import random
import hashlib
from collections import defaultdict
import timeit

def insert(key, value, table=[]):
    alphabet = lambda: [[] for i in xrange(23)]
    if not table:
        table = alphabet()
    get_hash = lambda x: hashlib.sha1(str(x)).hexdigest().upper()
    key_hash = get_hash(key)
    entry = table
    for i, char in enumerate(key_hash):
        ordinal = ord(char) - 48
        entry = entry[ordinal]
        #entry is a list representing 'char' at index 'i'
        entry_len = len(entry)
        if entry_len is 0:
            entry.extend((key, [value]))
            break
        elif entry_len is 2:
            extant_key, extant_values = entry[0], entry[1]
            if key == extant_key:
                extant_values.append(value)
                break
            del entry[:]
            #entry = []
            extant_hash = get_hash(extant_key)
            for i in xrange(i + 1, len(key_hash)):
                char, extant_char = key_hash[i], extant_hash[i]
                if char == extant_char:
                    entry.extend(alphabet())
                    ordinal = ord(char) - 48
                    entry = entry[ordinal]
                    #entry = []
                else: break
            if char != extant_char:
                entry.extend(alphabet())
                char_ord = ord(char) - 48
                entry[char_ord].extend((key, [value]))
                extant_ord = ord(extant_char) - 48
                entry[extant_ord].extend((extant_key, extant_values))
                #entry has empty lists except 2
                break
            else: pass
                #hash collision, to be continued
    return table

def get(key, table, pop=False):
    key_hash = hashlib.sha1(str(key)).hexdigest().upper()
    entry = table
    for i, char in enumerate(key_hash):
        ordinal = ord(char) - 48
        entry = entry[ordinal]
        entry_len = len(entry)
        if entry_len is 0:
            raise KeyError(key)
        elif entry_len is 2:
            items = entry[1]
            if pop:
                del entry[:]
                if not any(item for item in entry):
                    del entry
            return items
    raise KeyError(key)

def make_defaultdict(kv):
    d = defaultdict(list)
    for items in kv:
        k, v = items
        d[k].append(v)
    return d

def make_my_table(kv):
    t = []
    for items in kv:
        k, v = items
        t = insert(k, v, t)
    return t

kv = [(random.randint(1000, 9999), random.randint(1000, 9999))
     for i in xrange(1000000)]

dd = make_defaultdict(kv)
mt = make_my_table(kv)

validate = []
for key in dd.keys():
    if dd[key] == get(key, mt):
        validate.append(True)
    else:
        validate.append(False)

defaultdict_time = timeit.timeit(lambda: make_defaultdict(kv), number=1)
my_table_time = timeit.timeit(lambda: make_my_table(kv), number=1)

print 'Time to build defaultdict', defaultdict_time
print 'Time to build my table', my_table_time
print 'Both tables are identical', all(i for i in validate)

Time to build defaultdict 0.342477702698
Time to build my table 4.21419315689
Both tables are identical True


texts: Check if a string ends with a given suffix, without using .endswith()

texts:
I figured out how to do this assignment, but now that I have, I'd like to know if there is a cleaner way to do it. Below is what was required of the assignment, below that is my working function that got me the correct answer and further below that is the all the statements that it had to and did pass.

How can I make it better?

  Check if a string (first argument, str) ends with the given target
  string (second argument, target).

  This challenge cannot be solved with the .endsWith()

My Working Code:

function confirmEnding(str, target) {
  var targetLength = target.length;
  var anyString = str.substring(str.length - targetLength);
  return anyString == target;
}

Tests in needs to pass:

console.log(confirmEnding("Bastian", "n")); //should return true.
console.log(confirmEnding("Connor", "n")); //should return false.
console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")); //should return false.
console.log(confirmEnding("He has to give me a new name", "name")); //should return true.
console.log(confirmEnding("Open sesame", "same")); //should return true.
console.log(confirmEnding("Open sesame", "pen")); //should return false.
console.log(confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")); //should return false.


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

texts:
So I answered this question on SO and probably did someone's homework along the way.
In the original question the OP has the answer variable and wants it split to real and imaginary values with the original coefficient (q in the original post) as an array for each q from 1 to 10, so you get an array of arrays looking like:
[[1,-0.39002422, 1.84237253, -0.39002422, -1.84237253, -0.10997578, 0.51949688,-0.10997578, -0.51949688j],
[2, ...]
...
[10, ...]]

There are two things I'm unsatisfied with in the answer I gave that are the reason I'm asking for a CR.

The indexing: Isn't particularly readable, and I don't know how to make it more readable. For example [q-1, 2*_+1]. Would it have been better to create a variable j = q-1 because q-1 sees frequent use? Isn't that just moving the ugly to a different place?
The idea for the solution itself. The way I see it the original problem can be solved by splitting the answer array to a new array, but that feels somehow wrong. I can see several ways to create the new array, but I don't see a way to do it without creating the new array. Am I wrong and this is an OK solution or not, and why?

Thanks.
import numpy as np
export = np.empty([10,9])
for q in range(1,11):
    a0=1
    a1=3*q^2
    a2=4*q
    a3=np.sqrt(q)
    a4=q
    coeff=[a0, a1, a2, a3, a4]
    answer = np.roots(coeff)
    export[q-1, 0] = q
    for _ in range(len(answer)):
        export[q-1, 2*_+1] = answer[_].real
        export[q-1, 2*(_+1)] = answer[_].imag
with open("/tmp/latest_foo.csv", "ab") as output_file:
    np.savetxt(output_file, export, delimiter=",")


texts: Scan array for 3 consecutive numbers that sum to 7

texts:
Write a function lucky_sevens?(numbers), which takes in an array of
  integers and returns true if any three consecutive elements sum to 7.

lucky_sevens?([2,1,5,1,0]) == true # => 1 + 5 + 1 == 7
lucky_sevens?([0,-2,1,8]) == true # => -2 + 1 + 8 == 7
lucky_sevens?([7,7,7,7]) == false
lucky_sevens?([3,4,3,4]) == false

  Make sure your code correctly checks for edge cases (i.e. the first
  and last elements of the array).

While my code does seem to work (I did some test cases), I know it can be improved. There's no reason to have double puts and return statements. I'm also wondering if there are general improvements to the syntax itself that can make it much more readable.

def lucky_sevens?(numbers)
  i = 0
  while i < numbers.length - 2

    if numbers[i] + numbers[i + 1] + numbers[i + 2] == 7
        puts true
        return true
    end
    i+=1
    end
    puts false
    return false
end


texts:
I am writing a stop watch utility class in Java that I want to be thread-safe (concurrent).  Here is what I have right now:

public class Stopwatch {

    private volatile long beginTime;
    private final AtomicLong lastLap = new AtomicLong();
    private final AtomicReference<List<Long>> laps = new AtomicReference<List<Long>>();

    public synchronized void start() {
        reset();
        beginTime = System.nanoTime();
        lastLap.set(beginTime);
    }

    public long timeElapsed() {
        return toMilliseconds(timeElapsed(beginTime));
    }

    public void lap() {
        long lap = timeElapsed(lastLap.longValue());
        lastLap.addAndGet(lap);
        getLaps().add(toMilliseconds(lap));
    }

    public synchronized void reset() {
        beginTime = 0;
        lastLap.set(0);
        if (laps.get() != null) {
            laps.get().clear();
        }
    }

    public List<Long> getLaps() {
        laps.compareAndSet(null, Collections.synchronizedList(new ArrayList<Long>()));
        return laps.get();
    }

    private long toMilliseconds(long nano) {
        return nano / 1000000;
    }

    private long timeElapsed(long start) {
        return System.nanoTime() - start;
    }
}

A few notes, the compareAndSet call in getLaps is used to lazily initialize the list. I added the synchronized modifiers to the start and reset methods to prevent the scenario of multiple threads calling those methods simultaneously, which could possibly result in some fields being reset and some being initialized, giving odd behavior. I did not add the synchronized modifiers to the other methods because I anticipate them to operate as expected even when invoked from multiple threads, though, quite frankly, I'm not entirely sure if that is the case.

I would like this implementation to avoid locking as much as possible because the locking and waiting could give slightly inaccurate results for certain methods, like timeElapsed.

Do I need to make any modifications to make this class thread-safe?


texts: Handling of memorystream with streamwriter efficiency

texts:
My little program I'm working on generates charts (GUI) and (on another tab) lists the values my chart is fed from.

2011.01.01 0:00:00     456
2011.01.02 0:00:00     45
2011.01.03 0:00:00     46
2011.01.04 0:00:00     6
2011.01.05 0:00:00     1500
...

When I click on the "Generate Chart" button, after the chart generator code has run, the following method is also invoked (that generates the table above):

void FillGridDetails(List<NameSeries> chartDataIn)

This fills a grid with the values. (DateTime as key, and float as value, nothing special...)

// Creating the rows.
gridDetails.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(30) }); // First row (Date/Time)
int maxCount = chartDataIn[maxIndex].seriesData.Count;
int rowCount = 1;

// Create the memory stream to write the data in (later this will be written to a file if the users clicks the export button).
ms = new MemoryStream(); // This is a class level variable.
StreamWriter writer = new StreamWriter(ms) { AutoFlush = true };
foreach (var aDataRow in chartDataIn[maxIndex].seriesData)
{
    // Adding the first column's rows.
    Label lblDate = new Label() { Content = aDataRow.Key.ToString(dateFormatIn), HorizontalAlignment = HorizontalAlignment.Center };
    gridDetails.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(30) });
    gridDetails.Children.Add(lblDate);
    Grid.SetRow(lblDate, rowCount);
    Grid.SetColumn(lblDate, 0);
    writer.Write(aDataRow.Key.ToString() + ";");

    // Adding the further columns' rows.
    for (int i = 0; i < chartDataIn.Count; i++)
    {
        string value = chartDataIn[i].seriesData.ContainsKey(aDataRow.Key) ? chartDataIn[i].seriesData[aDataRow.Key].ToString() : "-";
        Label lblData = new Label() { Content = value };
        gridDetails.Children.Add(lblData);
        Grid.SetRow(lblData, rowCount);
        Grid.SetColumn(lblData, i + 1);

        if (i == chartDataIn.Count - 1)
        {
            writer.WriteLine(value == "-" ? "" : value);
        }
        else
        {
            writer.Write(value == "-" ? ";" : value + ";");
        }
    }

    rowCount++;
}

On this tab there is a CSV Export button, click:

SaveFileDialog dlg = new SaveFileDialog()
{
    FileName = "EM_ExportedData",
    DefaultExt = ".csv",
    Filter = "CSV comma separated values (.csv)|*.csv"
};

if ((bool)dlg.ShowDialog())
{
    //try
    //{
    using (FileStream file = new FileStream(dlg.FileName, FileMode.Create, FileAccess.Write))
    {
        ms.WriteTo(file);
        ms.Dispose();
        btnExportCSV.Content = Strings.CSVExported;
        btnExportCSV.IsEnabled = false;
        MessageBox.Show(String.Format(Strings.successfulSavedCSVFile, dlg.FileName));
    }
}

Could it cause any sort of disadvantages in memory efficiency? I'm thinking of, e.g., not closing the filestream or something. If I close the fileStream, later I can't access the memory stream because that's also closed. Any recommendations for this code part is much appreciated.

(What I wanted to do is this: store the values in the memory or somewhere (right after the generation) and when the user wants to export it is simply written to the file. I was also thinking of copy paste the foreach loop but only with the memory-writing parts.)


texts:
I got asked this question during my interview. You can find information about this question here.

  Pancake Sort

  Given an array of integers arr:

  Write a function flip(arr, k) that reverses the order of the first k elements in the array arr.
  Write a function pancakeSort(arr) that sorts and returns the input array. You are allowed to use only the function flip you wrote in the first step in order to make changes in the array.
  Example:

input:  arr = [1, 5, 4, 3, 2]

output: [1, 2, 3, 4, 5]

  Note: it’s called pancake sort because it resembles sorting pancakes on a plate with a spatula, where you can only use the spatula to flip some of the top pancakes in the plate. To read more about the problem, see the Pancake Sorting Wikipedia page. https://en.wikipedia.org/wiki/Pancake_sorting

My solution is to use flip function to implement my pancake_sort(arr).

The following property of the flipping function - if we call flip(arr, k), then the previous k-th element in the array is now the first element. Hence, if we find the maximal element, we can shift it to be the first element by one call to flip(arr, k), and then shift it to the last place by calling flip(arr, arr.length - 1). We can exploit this method further, by iterating i from arr.length - 1 to 1, finding the maximal element in the current ith prefix, flipping the maximal element once to move it to the first place in the array, and a second time to put it in the ith place in the array.

def flip(arr, i):
    # reverse arr[0...i]
    start = 0
    while start < i:
        temp = arr[start]
        arr[start] = arr[i]
        arr[i] = temp
        start += 1
        i -= 1

def pancake_sort(arr):
    # the main function that complete sorting
    # start from the array and one by one reduce the current size
    output = []
    curr_size = len(arr) - 1
    # find the index of the maxmium element inside the arr[0..curr_size -1]
    while curr_size > 0:
        mi = findMaxUpTo(arr, curr_size)
        if mi != curr_size:
            flip(arr, mi)
            # once I flip it
            # now move the maximum number to the end by reversing current array
            flip(arr, curr_size)
        curr_size -= 1
    return arr

def findMaxUpTo(arr, rightBound):
    best_index = 0
    max_val = None
    for i in range(rightBound + 1):
        if arr[i] > max_val:
            best_index = i
            max_val = arr[i]
    return best_index

I also ran my code against the following test cases:

Test Case #1
Input: [1]
Expected: [1]
Actual: [1]
Test Case #2
Input: [1,2],Expected: [1,2],
Actual: [1, 2]
Test Case #3
Input: [1,3,1],
Expected: [1,1,3],Actual: [1, 1, 3]
Test Case #4
Input: [3,1,2,4,6,5],
Expected: [1,2,3,4,5,6],
Actual: [1, 2, 3, 4, 5, 6]
Test Case #5
Input: [10,9,8,7,6,5,4,3,2,1],
Expected: [1,2,3,4,5,6,7,8,9,10],
Actual: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Test Case #6
Input: [10,9,8,6,7,5,4,3,2,1,9,10,8,7,6,5,4,3,2,1,10,9,8,7,6,5,4,3,2,1],
Expected: [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10],
Actual: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10]


texts:
I have the following command bonded to my button, It's supposed detect the current used theme and change it (Dark or Light).

  var existingResourceDictionary = Application.Current.Resources.MergedDictionaries
                .Where(rd => rd.Source != null)
                .SingleOrDefault(rd => Regex.Match(rd.Source.OriginalString, @"(\/MaterialDesignThemes.Wpf;component\/Themes\/MaterialDesignTheme\.)((Light)|(Dark))").Success);

            if (existingResourceDictionary == null)
                throw new ApplicationException("Unable to find Light/Dark base theme in Application resources.");

            if (existingResourceDictionary.Source.ToString().Contains("Light"))
            {
                Settings.Default.Theme = true;
                Settings.Default.Save();
            }
            else
            {
                Settings.Default.Theme = false;
                Settings.Default.Save();
            }

            var source =
                $"pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.{(Settings.Default.Theme ? "Dark" : "Light")}.xaml";
            var newResourceDictionary = new ResourceDictionary() { Source = new Uri(source) };

            Application.Current.Resources.MergedDictionaries.Remove(existingResourceDictionary);
            Application.Current.Resources.MergedDictionaries.Add(newResourceDictionary);

and in the ViewModel (when I run the application) It should detect the last changes made with the button above and apply the theme. I'm basically getting the value from the Settings that I changed above:

   var existingResourceDictionary = Application.Current.Resources.MergedDictionaries
          .Where(rd => rd.Source != null)
          .SingleOrDefault(rd => Regex.Match(rd.Source.OriginalString, @"(\/MaterialDesignThemes.Wpf;component\/Themes\/MaterialDesignTheme\.)((Light)|(Dark))").Success);

            if (existingResourceDictionary == null)
                throw new ApplicationException("Unable to find Light/Dark base theme in Application resources.");

            var source =
                $"pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.{(Settings.Default.Theme ? "Dark" : "Light")}.xaml";
            var newResourceDictionary = new ResourceDictionary() { Source = new Uri(source) };

            Application.Current.Resources.MergedDictionaries.Remove(existingResourceDictionary);
            Application.Current.Resources.MergedDictionaries.Add(newResourceDictionary);

The code is working fine but I feel like I could make it less repetitive and shorter?


texts: Scraping information from a webpage not knowing it's last page number

texts:
I've written some code in vba to scrape names and phone numbers from a webpage that has spread across some pages I don't wish to know of. The main interesting thing with this scraper is that It only needs to know the first page number then it traverse across all the pages and fetch the information I've mentioned above. I tried to make it error-free. Here is what I did:

Sub Yellowpage_Parser()

Const mlink = "https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=San%20Francisco%2C%20CA&page="
Dim http As New XMLHTTP60, html As New HTMLDocument
Dim post As HTMLHtmlElement

Do
    y = y + 1
    With http
        .Open "GET", mlink & y, False
        .send
        html.body.innerHTML = .responseText
    End With

        For Each post In html.getElementsByClassName("info")
            With post.getElementsByClassName("n")(0).getElementsByTagName("span")
                If .Length Then x = x + 1: Cells(x, 1) = .item(0).innerText
            End With

            With post.getElementsByClassName("phones phone primary")
                If .Length Then Cells(x, 2) = .item(0).innerText
            End With
        Next post

Loop While InStr(http.responseText, "next ajax-page")

    Set html = Nothing
    MsgBox "Collected totals are " & ActiveSheet.UsedRange.Rows.Count

End Sub


texts: Message Object - Best Practice? |  Consider data attribute for pulling text in

texts:
Is this best practice way to send messages to the user?

Update:  This has been changed to a simple function call.

/**
 *Message - Sends message to the .innerHTML of an element
 */

var Message = ( function ()
{
    var messages =
    {
        name:         'Please enter a valid name',
        email:        'Please enter a valid email',
        email_s:      'Please enter a valid email.',
        pass:         'Please enter password, 6-40 characters',
        url:          'Please enter a valid url',
        title:        'Please enter a valid title',
        tweet:        'Please enter a valid tweet',
        empty:        'Please complete all fields',
        same:         'Please make emails equal',
        taken:        'Sorry, that email is taken',
        validate:     'Please contact support to reset your password',
    };
    var MessageInternal = function (element)
    {
        this.element = element;
    };
    MessageInternal.prototype.display = function( type )
    {
        this.element.innerHTML = messages[ type ];
    };
    return MessageInternal;
} () );


texts:
In a frontend Javascript project I have to implement a generic timeout mechanism for a set of asynchronous tasks that the program needs to perform.

These are the conditions:

The tasks are functions that have a variable number of arguments, the last of which is the callback to be called in case of success: function (some, args, successCallback) { /* ... */ }
There is no built-in timeout handling mechanism for the tasks (I'm doing JSONP requests, flash interoperation).
External libraries cannot be used
Promises cannot be used (must be IE compatible)

Given the above, I have written the following generic timeout handling function:

var runWithTimeout = function (task, args, successCallback, timeoutCallback, timeoutInterval) {
  var timedOut = false;
  var success = false;

  var decoratedCallback = function(result) {
    if (!timedOut) {
      success = true;
      clearTimeout(timeoutId);
      successCallback(result);
    }
  };

  var allArgs = args.slice(0);
  allArgs.push(decoratedCallback);

  task.apply(null, allArgs);

  // if task completed synchronously, no need to check for timeout
  if(!success) {
    var timeoutId = setTimeout(function(){
      timedOut = true;
      timeoutCallback();
    }, timeoutInterval);
  }
};

For example, given the function:

var delayedTask = function (name, delay, callback) {
  setTimeout(function() {
    callback(name + ' - finished.');
  }, delay);
};

I can call it with my timeout handler like this:

var successCallback = console.log;
var timeoutCallback = function() { console.log('Timeout!'); };

runWithTimeout(delayedTask, ['short task', 500], successCallback, timeoutCallback, 1000);

Here's an illustration of how the mechanism works, using both a successful and a timeout task: http://jsbin.com/lecaha/edit?js,console

While my approach seems to work, there are a number of things that bother me about the code. I feel like it's not very readable and I'd like to avoid passing arguments as an array and the .apply() call if possible.

Are there ways to improve the code above?


texts: on using the strategy pattern to switch between database layers

texts:
I'd like to build an app in Flask that can switch between talking to a PostGresql and a Mongo DB.  As I understand it, the Strategy Pattern is about being able to switch algorithms that are referred to by some method call on the fly.  So, I think this pattern would be relevant because I want to switch out what abstract functions like create, read, update, delete do.  It sounds to me like strategy would be relevant here, but I'm not quite sure how to implement it.  Here's what I'm thinking:
I have this file to handle my routes:
from flask import Blueprint
from .models import Entity
api = Blueprint('api', __name__, url_prefix='/api')
from .models.EntityWrapper import Entity

@api.route('/entities', methods=['POST'])
def create_entity():
    entity = EntityWrapper(label="cheese")
    entity.save()
    return jsonify(entity)

@api.route('/entities')
def get_entities():
    entities = Entity.read()
    return jsonify(entities)

The save and read methods should do different things, depending on which database is being used.  The class they belong to, EntityWrapper, reads the environment variables and selects which kind of Entity class should be exported:
import os
from .Entity_mongo import Entity as MongoEntity
from .Entity_postgres import Entity as PostgresEntity
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())
DB_TYPE = os.environ.get("DB_TYPE")

Entity = None

if DB_TYPE == 'mongo':
    Entity = MongoEntity
elif DB_TYPE == 'postgres':
    Entity = PostgresEntity
else:
    raise Exception("'DB_TYPE' improperly defined in .env")

Here's Entity_posgres.py
from .Model_postgres import PostgresModel

class Entity(db.Model):
    __tablename__ = 'entities'
    id = db.Column(db.Integer, primary_key=True)
    label = db.Column(db.String(), nullable=False)

Since there are a number of methods that should all be handled "the postgres way" for any object, I'm bundling these into a class called PostgresModel. (A mimilar class would be defined for Mongo, doing this "the mongo way", but for sake of brevity I'll only show postgres).
# from .ModelABC import ModelABC
from ..extensions import postgres_db as db

# class PostgresModel(ModelABC, db.Model):
class PostgresModel(db.Model):
    def create(self, instance):
        # do some postgres create stuff
        db.session.add(instance)
        db.session.save()
    def read(self, cls):
        # do some postgres read stuff
        cls.query.all()
    def update():
        # do some postgres update stuff
        pass
    def delete():
        # do some postgres delete stuff
        pass

I can think of one way the stategy pattern might fit in here: PostgresModel could inherit from some ModelABC class, which would keep track of which strategy is currently being used to create, read, update, or delete.  It seems to be this class would look something like the following.  To tell the truth, I'm not even sure what advantages it could bring, but here's what it might look like:
from abc import ABC, abstractmethod

class ModelABC(ABC):

    def assign_strategy(self, strategy_key):
        pass

    def use_strategy(self, strategy, *args, **kwargs):
        if strategy == 'create':
            self.create_strategy(*args, **kwargs)
        elif strategy == 'read':
            self.read_strategy(*args, **kwargs)
        elif strategy == 'update':
            self.update_strategy(*args, **kwargs)
        elif strategy == 'delete':
            self.delete_strategy(*args, **kwargs)
        else:
            raise Exception('strategy name invalid')

    @abstractmethod
    def create_strategy(self):
        pass

    @abstractmethod
    def read_strategy(self):
        pass

    @abstractmethod
    def update_strategy(self):
        pass

    @abstractmethod
    def delete_strategy(self):
        pass

Am I on the right track with this strategy pattern, or is this not the right use case?


texts:
Description
A class representing an undirected graph. At the moment, it supports integer values as vertices. An example of the type of graph represented is shown in the following diagram:

It is represented internally as an array of adjacency lists. Each index of this array corresponds to a vertex number, and contains a List<int> of vertex numbers to which it is connected.
Purpose
Purely as an exercise in implementing a data structure. Implemented in C# after studying a Java-based implementation.
Code
The data structure class definition
public class UndirectedGraph
{
    // number of vertices
    private int _V;

    // number of edges
    private int _E = 0;

    // array of adjacency lists
    private List<int>[] _adj;

    /// <summary>
    /// Constructor to create a graph.
    /// </summary>
    /// <param name="v">Number of vertices</param>
    public UndirectedGraph(int v)
    {
        this._V = v;

        // create array of lists
        // initialise all lists to empty
        this._adj = new List<int>[v];
        for (int i = 0; i < this._adj.Length; i++)
            this._adj[i] = new List<int>();
    }

    // number of vertices
    public int V
    {
        get { return this._V; }
    }

    // number of edges
    public int E
    {
       get { return this._E; }
    }

    /// <summary>
    /// Add an edge to the graph.
    /// </summary>
    /// <param name="v">One vertex of the new edge.</param>
    /// <param name="w">The other vertex of the new edge.</param>
    public void addEdge(int v, int w)
    {
        // validate given node numbers
        if ((v > this._adj.Length) || (w > this._adj.Length))
            throw new ArgumentException("Invalid node number specified.");

        // add to adjacency lists
        this._adj[v].Add(w);
        this._adj[w].Add(v);
        // increment edge count
        this._E++;
    }

    /// <summary>
    /// Get an adjacency list for a vertex.
    /// </summary>
    /// <param name="v">The vertex.</param>
    /// <returns></returns>
    public List<int> getAdjacency(int v)
    {
        return this._adj[v];
    }

    /// <summary>
    /// Get a string representation of the graph's adjacency lists.
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        StringBuilder builder = new StringBuilder();
        builder.AppendLine(this._V + " vertices, " + this._E + " edges");
        for (int v = 0; v < this._V; v++)
        {
            builder.Append(v + ": ");
            foreach (var w in this._adj[v])
            {
                builder.Append(w + " ");
            }
            builder.AppendLine(string.Empty);
        }

        return builder.ToString();
   }
}

Sample usage. Prints out a string representation of the example graph in the diagram above to the console:
UndirectedGraph myGraph = new UndirectedGraph(7);
myGraph.addEdge(0,1);
myGraph.addEdge(0,2);
myGraph.addEdge(2,3);
myGraph.addEdge(2,4);
myGraph.addEdge(2,5);
myGraph.addEdge(5,6);
Console.Write(myGraph.ToString());

// RESULT:
7 vertices, 6 edges
0: 1 2
1: 0
2: 0 3 4 5
3: 2
4: 2
5: 2 6
6: 5

Questions

Any feedback about variable names, commenting and implementation details.
Changes, if any, to make it unit-testable.
Ways to include C# 7.0 features, if they haven't been already.
How to extend this to other data types, such as string.
Performance improvements might be interesting.


texts: Is this code with global variables good practice?

texts:
I am currently writing a game in C++ and have some variables that I want to be accessible from everywhere. For the examples, I will have the shared variable as an object of the class Input.

At the moment I am implementing it like this:

input.h:

#ifndef INPUT_H
#define INPUT_H
extern Input input;
#endif

init.cpp:

Input input;
int main(//args){
    input.doStuff();
}

Other files that use the object.cpp:

#include "input.h"

void method(){
    input.doStuff();
}

I've got this nagging doubt that I shouldn't be doing things in this way.  Is this doubt correct? What should I be doing and why?


texts: OO design of Reverse Polish Notation Calculator - follow-up

texts:
This is a revised version of my previous code.

This application will take input string like "3 2 + 1 -" and output 4 because it is the reverse Polish notation for (3+2)-1 = 4. This solution focuses on the design of classes.The current code has 2 operators (plus and minus) in default.  There are 2 constructors. 1 will create the default calculator. The other can take an additional HashMap that will map a string to an Operator.

The code works. Any further recommendations are much appreciated! Questions I have:

Do I need to write getters for fields that I didn't use, such as public String getInput().
I didn't write any setters for the non-static variables. Do I need them?

 import java.util.*;
 public class RPNCalculator {

    public Stack<Integer> stack;
    private String input;
    public Map<String, Operator> map;
    private String operators="";

    public RPNCalculator(String userInput){
        input = userInput;
        stack = new Stack<Integer>();
        // default hashmap initialization
        map = new HashMap<String, Operator>();
        map.put("+", new Plus());
        map.put("-", new Minus());
        // this string is constructed for later use in processInput()
        for(String key: map.keySet()){
            operators+= key;
        }
    }
    public RPNCalculator(String userInput, HashMap<String, Operator> mapInput){
        input = userInput;
        stack = new Stack<Integer>();
        this.map = mapInput;
        for(String key: map.keySet()){
            operators+= key;
        }
    }

    public Stack<Integer> getStack(){
        return this.stack;
    }
    public String getInput(){
        return this.input;
    }
    public void processInput(){
        StringTokenizer st = new StringTokenizer(input, " ");
        while (st.hasMoreTokens()){
            String str = st.nextToken();
            if(!operators.contains(str)){               //test whether the token is an operator
                stack.push(Integer.parseInt(str));
            }
            else{
                map.get(str).calc(this);
            }
        }
        if(stack.size()!=1){
            System.out.println("The input expression is not the correct format");
        }else{
            System.out.println(stack.pop());
        }
    }
}

Other supporting classes and driver (contains main):

public abstract class Operator {
    abstract void calc(RPNCalculator rpn);
}
public class Minus extends Operator {
    @Override
    void calc(RPNCalculator rpn) {
        int a = rpn.getStack().pop();
        int b = rpn.getStack().pop();
        rpn.getStack().push(b-a);

    }
}
public class Plus extends Operator {
    @Override
    void calc(RPNCalculator rpn) {
        int a = rpn.getStack().pop();
        int b = rpn.getStack().pop();
        rpn.getStack().push(a+b);

    }
}
public class RPNDriver {
       public static void main(String[] args) {
           System.out.println("starting calculator...");
           RPNCalculator rpn = new RPNCalculator("1 21 + 2 -");
           rpn.processInput();
       }
}


texts: Pair up elements of a sequence without overlap

texts:
I have a sequence (in this case actually an array) like this:

[| 1; 2; 3; 4; 5; 6; 7; 8; 9; 10|]

And want to produce a sequence of pairs like this:

[(1, 2); (3, 4); (5, 6); (7, 8); ...]

The following code works, but I can't help feeling that it's a lot of code. Is there a shorter, more idiomatic or more elegant way to do this.

[| 1; 2; 3; 4; 5; 6; 7; 8; 9; 10|]
|> Seq.pairwise
|> Seq.mapi (fun i t -> (i, t))
|> Seq.filter (fun (i, t) -> i % 2 = 0)
|> Seq.map (fun (i, t) -> t)


texts: Netflix Auto-Logout for obsessed girlfriend

texts:
background story my girlfriend watches about 12 TV-Show episodes everyday and i keep telling her it's not good. I have made this script that kicks her out of my account for 20 times in an hour.
However, After 20 logouts it gives out a Technical difficulties error and i want to improve as to why?
import sched, time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys

def excf():
    driver = webdriver.Chrome("C:/Users/anonymous/Downloads/chromedriver.exe");
    driver.get('https://www.netflix.com/ManageDevices');

    inputElement = driver.find_element_by_id("id_userLoginId")
    inputElement.send_keys('email_netflix')

    inputElementP = driver.find_element_by_id("id_password")
    inputElementP.send_keys('pass_netflix')
    inputElementP.send_keys(Keys.ENTER)

    time.sleep(3)

    python_button = driver.find_element_by_xpath('//button[text()="Sign Out"]')
    python_button.click()
    time.sleep(2)
    driver.quit()

s = sched.scheduler(time.time, time.sleep)
def logout(sc):
    print("Logging out")
    excf()

    s.enter(60, 1, logout, (sc,))

s.enter(60, 1, logout, (s,))
s.run()


texts: Best practice for asserting a positive IF condition

texts:
What's better - to leave the IF block blank to do nothing, or to add a statement that basically does nothing (each link already has a href attribute)?

export function fixRelativeLinksOutsideOfEpub(dom): void {
    const content = dom.window.document.querySelectorAll('a');
    content.forEach((element: HTMLElement) => {
        const href = element.getAttribute('href');
        if (href.indexOf('#') === 0) {
            // do nothing
        } else {
            element.setAttribute('target', '_blank');
        }
    });
}

export function fixRelativeLinksOutsideOfEpub(dom): void {
    const content = dom.window.document.querySelectorAll('a');
    content.forEach((element: HTMLElement) => {
        const href = element.getAttribute('href');
        if (href.indexOf('#') === 0) {
            element.setAttribute('href', `${href}`);
        } else {
            element.setAttribute('target', '_blank');
        }out
    });
}


texts:
Problem Statement

Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.
Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?
Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings.

Solution
//Valid Test Case For Reference
static void ransomeNoteTrue() {
    String a = "cde";
    String b = "abc";
    int result = makeAnagram(a, b);
    int expected = 4;
    assert (result == expected);
}

static int makeAnagram(String a, String b) {
    Character[] aArray = a.chars().mapToObj(x -> (char) x).toArray(Character[]::new);
    Character[] bArray = b.chars().mapToObj(x -> (char) x).toArray(Character[]::new);
    Map<Character, Long> aMap = getFrequencyMapFromArray(aArray);
    Map<Character, Long> bMap = getFrequencyMapFromArray(bArray);

    return countError(aMap, bMap);
}

private static int countError( Map<Character, Long> aMap, Map<Character, Long> bMap ) {
    long deletedChars = 0;

    for( char ch='a'; ch<='z'; ch++) {

        if ( aMap.containsKey(ch) && !bMap.containsKey(ch) )
            deletedChars += aMap.get(ch);

        else if( bMap.containsKey(ch) && !aMap.containsKey(ch) )
            deletedChars += bMap.get(ch);

        else if( bMap.containsKey(ch) && aMap.containsKey(ch) )
            deletedChars += Math.abs( aMap.get(ch) - bMap.get(ch));
    }

    return (int)deletedChars;
}

private static Map<Character, Long> getFrequencyMapFromArray(Character[] arr) {
    return Arrays.stream(arr)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}

The main function to review is makeAnagram().
Looking forward to your reviews on -

What other improvements can be done?
What other ways could be there to the problem, as the current
approach is brute force?

Thank you.


texts:
I'm looking for some feedback on my OCaml implementation of some methods to translate infix expressions to postfix and then evaluate them.

I'm very new to OCaml, coming from C#/Java and JavaScript so pretty much any advice is appreciated, in particular how to make it more idiomatic or "functional".

It seems like I have to reverse my stack at some point because I want to operate on both sides, is this unavoidable? Could I be using better exceptions for my helper functions? Is it good practice to declare helper functions like I did? apply_and_store and str_to_fn could be inside eval_postfix, is it better to have them encapsulated or to keep eval_postfix cleaner?

let explode_to_strings (s : string) : string list =
    Str.split (Str.regexp "[ \t]+") s;;

(* Method from pleac.sourceforge.net *)
let is_Integer (s : string) : bool =
    try ignore (int_of_string s); true with Failure _ -> false;;

let str_to_fn (s : string) : (int -> int -> int) =
    match s with
    | "+" -> (+)
    | "-" -> (-)
    | "*" -> ( * )
    | "/" -> (/)
    | _ -> raise (Invalid_argument "Not an operator");;

let apply_and_store (lst : 'a list) (fn : 'a -> 'a -> 'a) : 'a list =
    match lst with
    | one :: two :: tl -> fn two one :: tl
    | _ -> raise (Invalid_argument "List too short");;

let prec (s : string) : int =
    match s with
    | "+" | "-" -> 1
    | "*" | "/" -> 2
    | _ -> raise (Invalid_argument "Not in operator table");;

let infix_to_postfix (lst : string list) : string list =
    let rec
        push (elem : string) (output : string list) (ops : string list) : (string list * string list) =
            match ops with
            | [] -> (output, elem :: ops)
            | hd :: tl ->   if prec elem <= prec hd
                            then push elem (hd :: output) tl
                            else (output, elem :: ops)
    in
    let rec
        aux (l : string list) (output : string list) (ops : string list) : string list =
            match l with
            | [] -> ops @ output
            | hd :: tl ->   if is_Integer hd
                            then aux tl (hd :: output) ops
                            else let ret = push hd output ops in
                                aux tl (fst ret) (snd ret)
    in
    aux lst [] [];;

let eval_postfix (lst : string list) : int =
    let rec aux (l : string list) (stack : int list) : int =
        match l with
        | [] -> List.nth stack 0
        | hd :: tl ->   if is_Integer hd
                        then aux tl ((int_of_string hd) :: stack)
                        else aux tl (apply_and_store stack (str_to_fn hd)) in
    aux (List.rev lst) [];;

let eval_infix (s : string) : int =
    eval_postfix (infix_to_postfix (explode_to_strings s));;


texts: Using jQuery UI .position() in a backwards compatible way

texts:
Trying to implement this API in a way that works pre and post jQuery UI 1.9:

I have a subtle feeling that there should be a more elegant way.

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return n === 0 ? "" :(( n > 0 ) ? ("+" + n) : ("" + n));
}

var posOpts = {
    at: "left top",
    of: $target
};

if( isVersionAtLeast($.ui.version, 1, 9) ){
    posOpts.my = "left" + offsetString(markerOffsetX) +
       " top" + offsetString(markerOffsetY);
} else {
    posOpts.my = "left top";
    posOpts.offset = "" + markerOffsetX + " " + markerOffsetY;
}
$dropMarker.position(posOpts);


texts:
I have made a program that reads 3 numbers:

number of treasure chests
treasure hunter's position
number of moving instructions

It then reads a string (which symbolizes the treasure chests), being each character either T (chest has a treasure) or V (chest is empty). After that, it reads the moving instructions in the format %c %d, being the first character (direction) either E(left) or D(right) and then the number of steps.

When the treasure hunter moves, he loots the treasures which he stands in, and in the end the program tells how many he got.

The requirements are the following:

  1 ≤ number of treasure chests ≤ 100 000
  1 ≤ treasure hunter's position ≤ number of treasure chests
  1 ≤ number of moving instructions ≤ 100 000
  the number of steps is always higher than 0
  the treasure hunter never goes beyond the treasure chests

My working code which I wish to improve in every way possible is the following:

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

int main() {
  char e;
  int a, b, c, f, g = 0, i, j;
  scanf("%d %d %d", &a, &b, &c);
  char *d = malloc(a * sizeof(char));
  scanf("%s", d);
  for(i = 0; i < c; i++) {
    scanf(" %c %d", &e, &f);
    for(j = 0; j <= f; j++) {
      if(d[b - 1] != 'V') {
        d[b - 1] = 'X';
      }
      if(e == 'E') {
        b++;
      } else {
        b--;
      }
    }
  }
  for(i = 0; i < a; i++) {
    if(d[i] == 'X') {
      g++;
    }
  }
  printf("%d\n", g);
  return 0;
}

Example of input and output:

I:
5 3 3
TVTTT
D 1
E 2
D 3

O:
3


texts:
I have a number of jQuery animation effects applied to certain elements on the page:

jQuery("#bgd_balance").animate({
        backgroundPositionY: "0px",
        backgroundPositionX: "0px",
        'background-size':'100%'
},800,"swing");

jQuery(".balance_left_box").delay(2000).slideDown(200,"easeInCirc");

jQuery(".balance_left_box p.first-line").delay(2400).slideDown(600,"easeInCirc");

jQuery(".balance_left_box").delay(1000).animate({
    height:"270px",
    top:"64px"
},100,"easeInCirc");

The problem I'm facing is that when I'm tweaking delay of a certain element, I have to go through everything and adjust all other delays accordingly.

Is it possible to have something like this instead (pseudocode):

queue.add(
       delay(2000),
       jQuery(".balance_left_box").slideDown(200,"easeInCirc"),
       delay(2000),
       jQuery(".balance_left_box p.first-line")X.slideDown(600,"easeInCirc");
       delay(1000),
       jQuery(".balance_left_box").animate({
            height:"270px",
            top:"64px"
        },100,"easeInCirc");
).run();

I know I can achieve this "queuing" by adding callback function to animate() call but then resulting code will be really bulky and hard to read, in my opinion.


texts: Iterate through python iterable in chunk of n

texts:
I need a function to iterate through a python iterable in chunks. That is, it takes an iterable and a size of n and yields generators iterating through each chunk of size n. After some experimentation, I wrote this stupid hack because it seems there is no easy way to preemptively check whether an iterable has been exhausted. How can I improve this code?

def iterchunks(it, n):
    def next_n(it_, n_, return_first = None):
        if return_first is not None:
            n_ -= 1
            yield return_first
        for _ in range(n_):
            yield next(it_)

    # check if the iterator is exhausted by advancing the iterator,
    # if not return the value returned by advancing the iterator along with the boolean result
    def exhausted(it_):
        res = next(it_, None)
        return res is None, res

    while True:
        exhsted, rf = exhausted(it)
        if exhsted:
            return
        else:
            # if the iterator is not exhausted, yield the returned value along with the next chunk
            yield next_n(it, n, rf)


texts: Cryptographically Secure Pin Generator using RNGCryptoServiceProvider

texts:
In my system I have a SMS authentication. Users input their user-id and get sent an SMS with a 5 digit pin number they input in a website to log in. The pin has a lifetime of a few minutes.

This pin number needs to be fairly secure so hackers can't try to guess the pin.

I would like to get some comments about my approach and code.

Here is my Code:

public class PinGenerator : IPinGenerator
{
    public string GetPin()
    {
        var rand = GetRandomNumber();

        return (rand %99999).ToString().PadRight(5, '0');
    }

    private int GetRandomNumber()
    {
        using (var crypto = new RNGCryptoServiceProvider())
        {
            byte[] data = new byte[4];

            crypto.GetBytes(data);

            return Math.Abs(BitConverter.ToInt32(data, 0));
        }
    }
}


texts: Generating a random string of characters and symbols

texts:
After coding this, I was wondering if there are any ways in which I can improve upon it. It generates a random string of characters and symbols the same length as what is entered by the user. It uses a separate list for each char list but I am sure it is using a very long-winded method!

import random, sys
letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
lettersnum = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]
letterssym = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","#","*", "£", "$", "+", "-", "."]
lettersnumsym = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","#", "*", "£", "$", "+", "-", "."]

def generator(length, num, sym, caps):
    count = 0
    password = ""
    try:
        test = int(length)
    except ValueError:
        error("LENGTH NOT VALID NUMBER")
    if num.lower() == "yes" and sym.lower() == "yes":
        merge = lettersnumsym
    elif num.lower() == "yes":
        merge = lettersnum
    elif sym.lower() == "yes":
        merge = letterssym
    while count <= int(length):
        password = password + merge[random.randint(0, len(merge) - 1)]
        count = count + 1
    if caps.lower() == "uppercase":
        password = password.upper()
    elif caps.lower() == "lowercase":
        password = password.lower()
    print("PASSWORD:",password)

def error(error):
    print(error)
    sys.exit(0)

running = True
while running == True:
    length = input("How long do you want the password?")
    numbers = input("Do You Want It to Include Numbers?")
    symbols = input("Do You Want It To Include Symbols?")
    capital = input("Do You Want It To be uppercase or lowercase??")
    generator(length, numbers, symbols, capital)
    restart = input("Do You Want Restart?")
    restart = restart.lower()
    if restart in ("yes", "y", "ok", "sure", ""):
        print("Restarting\n----------------------------------")
    else:
        print("closing Down")
        running = False


texts: Object Attribute Stored in New List from Existing List of Objects

texts:
For my CS class I the task given was to take a given Person Class with a name and age attributes.
Then, with an existing list of Person Objects, create a function that returns a tuple of (mean, median, mode) on the given age attribute.
Simple enough, but I wondered if my solution is really all that efficient. I basically iterated a new list of ages from an existing list of Person objects, and that almost feels like there's a better opportunity to optimize a solution...
Wondering if I'm missing something obvious.
from statistics import mean, median, mode

class Person:

    def __init__(self, name, age):
        """
        initializes a person objects name and age
        """
        self._name = name
        self._age = age

    def get_age(self):
        """
        returns the private data member _age
        """
        return self._age

def basic_stats(person_list):
    """
    creates a list of ages from a list of person objects then calculates
    mean, median, and mode from the statistics module
    """
    age_list = [i.get_age() for i in person_list]

    return (mean(age_list), median(age_list), mode(age_list))


texts:
Write a function that returns a string length N of alternating strings: "A" and "B", starting with the 1st string. How could this be improved for be more performance or efficiency?

Eg: num = 5, should return "ABABA" & given num = 2, should return "AB".

function solution(num) {
 const str1 = 'A', str2 = 'B';
 let res = [];

 for(let i = 1; res.length < num; i++ ) {
  res.push(i % 2 ? str1 : str2);
 }

  console.log(res.join(''))
}

solution(5) // return "ABABA"


texts: Improvment of and looping in a regular expression pattern

texts:
My implemented regex pattern contains two repeating symbols: \d{2}\. and
(.*)
. I want to get rid of this repetition and asked myself if there is a way to loop in Python's regular expression implementation.

Note: I do not ask for help to parse a XML file. There are many great tutorials, howtos and libraries. I am looking for means to implement repetition in regex patterns.

My code:

import re

pattern = '''
<menu>
<day>\w{2} (\d{2}\.\d{2})\.</day>
<description>

(.*)

(.*)

(.*)

</description>
'''

my_example_string = '''
<menu>
<day>Mi 03.04.</day>
<description>

Knoblauchcremesuppe

Rindsbraten "Esterhazy" (Gem&uuml;serahmsauce)

mit H&ouml;rnchen und Salat

</description>
</menu>
'''

re.findall(pattern, my_example_string, re.MULTILINE)


texts:
The below produces the output I want. Namely, it initially displays the first item on the list and the first expander link. When an expander link is clicked, it hides that link, unhides one more item in the list, and unhides the next expander link.

I'm wondering if it can tightened up. JQuery is a definite no-no.

 window.onload = function() {
  var anchors = document.getElementsByTagName('a');
  for(var i = 0; i < anchors.length; i++) {
   var anchor = anchors[i];
   if(anchor.classList.contains('expander_link')) {
    anchor.onclick = function(e) {
     e.preventDefault();
     e.target.setAttribute('style', 'display:none');
     var href = e.target.getAttribute("href")
     var unhide = document.getElementById(href);
     unhide.setAttribute('style', '');
     var data = e.target.getAttribute("data");
     var link = "link_" + (parseInt(data)+1);
     var next = document.getElementById(link);
     next.setAttribute('style', '');
    }
   }
  }
 }
  body {
    margin: 15pt 20pt 0pt 20pt;
    padding: 0;
  }

  p {
    margin: 8pt 0 8pt 0;
    padding: 0;
  }

  .center {
    margin: auto;
    align-self: center;
    text-align: center;
  }

  h4 {
    color: #004080;
    font-size: 120%;
    margin: 100pt 0 0 0;
  }

  .nobullets {
    list-style: none;
  }

  .hidden {
    display: none;
  }`

  table {
    border-spacing: 0;
  }

  th, td {
    text-align: center;
    padding: 3pt;
    margin: 0;
  }

  ul {
   list-style-type: none;
   margin-left:0;
   padding-left:0;
  }

  ul ul {
    list-style: disc;
    margin-left: 20pt;
  }

  li[id]{
    border-top: 1px solid #AAAAAA;
  }

  a#link_0 + [id] {
    border-top: none;
  }

  .block {
    display: block;
   }

  .expander_link {
    padding-top: 8pt;
    padding-bottom: 30pt;
    font-size: 120%;
    font-weight: bold;
    color: #004080;
    text-align: center;
    align-self: center;
    text-decoration: none;
    display: block;
    border-top: 1px solid #AAAAAA;
  }

Expanding list

  part one

show part two

 part two

show the third part

part 3

show part 4

part 4


texts:
I have this coding and I think it works. However, I would like to understand if there is a better way to do this. This would automatically create new textboxes or delete them based on the given selected number.

<select id=cornercases name=cornercases>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
</select>


texts: Longest common substring using dynamic programming

texts:
I've written a short python script that attempts to solve the problem of finding the longest common substring using the dynamic programming technique. It is meant to be generalised so I could plug in any number of strings and it would find the longest common substring.

def longest_common_substring(*strings):
    table = defaultdict(int)
    for pos in product(*(range(len(s)) for s in strings)):
        same = len(set(s[i] for s, i in zip(strings, pos))) is 1
        table[pos] = table[tuple(map(lambda n: n - 1, pos))] + 1 if same else 0
    return max(table.items(), key=operator.itemgetter(1))

This works fine for a small number of short strings, but the space and time complexity absolutely blows up with longer strings.

I got this from wikipedia, and since this approach is clearly terrible for multiple longer strings (or maybe my implementation is just bad!?), I am wondering what I could do to improve it? Wikipedia also metions a generalised suffix trees... I am not familiar with them at all so would that be a better approach?

Also, if its my implementation, I'd love to know what's wrong and what I could do better in terms of space complexity.


texts: Saving a subscription plan with a payment

texts:
Is this acceptable for readability or would it be better to refactor it into smaller methods?

Tips?  Comments? Examples?

def save_with_payment
  if valid?
    charge = Stripe::Charge.create(:amount => (self.plan.price * 100).to_i,
                                   :currency => 'usd', :card => stripe_card_token, :description => "Charge for #{user.email}")
    self.stripe_charge_id = charge.id
    self.starts_at = Date.today
    self.amount = plan.price
    self.expires_at = 1.years.from_now
    save!
  end
rescue Stripe::InvalidRequestError => e
  logger.error "Stripe error while creating charge: #{e.message}"
  errors.add :base, "There was a problem with your credit card."
  false
end


texts: Combining arbitrary number of lists inside json

texts:
I have some JSON where each key stores an array, and I need to combine all those arrays into a single array.  My current solution doesn't seem the most friendly to review, but without forEach not able to return a value i'm struggling for a succinct solution.

config = {"levels": {"first": ["a", "b", "c"], "second": ["d", "e", "f"]}};

let combine = [];
Object.keys(config["levels"]).forEach(key=>combine.push(config["levels"][key]));
let levels = [].concat.apply([], combine);
// levels == ["a", "b", "c", "d", "e", "f"]

I never know how children config["levels"] will have there will be so this needs to be dynamic.


texts: Booting up my Ruby social aggregator app

texts:
Some time ago I started with a small Ruby project. I call it social_aggregator.
This software aggregates information from different networks to one xml-stream, which you can reuse. For instance on your personal website to show some of your activity to your audience or as your personal news feed.

I've a built in Webrick server, while I also want to support any other rack based server. So I have this two entry/start points:

config.ru:

$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'Aggregator'
require 'conf/router'

# Run aggregator
app = Thread.new{ Aggregator.new }
app.run

use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache

run Router.map

And the Aggregator.rb:

$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'conf/initializers/DatabaseInitializer'
require 'conf/initializers/ConsoleInitializer'
require 'app/plugins/PluginManager'
require 'app/utils/ArgumentParser'
require 'app/utils/Logging'
require 'app/utils/Setting'

# Main class
class Aggregator
    include Logging
    include Setting

    # The version constant
    AGGREGATOR_VERSION = '0.0.1' unless const_defined?(:AGGREGATOR_VERSION)

    # Stores the environment
    @@environment = :production

    # Stores the run state
    @@stop = false

    # Initialize the whole system
    def initialize(internal_server = false, arguments = [])
        options = ArgumentParser.parse(arguments)

        Logging::environment options.environment

        # Set up logger
        if options.quiet
            Logging::quiet = true
        end

        logger.info 'Starting up aggregator now'

        # Set environment to setting
        logger.info "Using #{options.environment} environment"
        @@environment = options.environment

        # Connect database with orm
        DatabaseInitializer.new(options.environment)

        unless options.environment == :test || options.console
            # Set up plugin manager
            @@plugin_manager = PluginManager.new

            if internal_server
                require 'conf/initializers/ServerInitializer'

                # Spawn new server
                ServerInitializer.new
            end

            logger.info "Aggregator is up and running"

            Signal.trap("SIGINT") do
                Thread.current.exit
            end

            start
        end

        if options.console
            ConsoleInitializer.new(options.environment)
        end
    end

    # Returns the current environment
    def self.environment
        @@environment
    end

    # Returns the version number
    def self.version
        AGGREGATOR_VERSION
    end

    # Returns the plugin manager
    def self.plugin_manager
        @@plugin_manager
    end

    # Shutdown the system
    def self.shutdown
        @@stop = true
    end

    private

    # Starts the aggregation
    def start
        @@plugin_manager.run

        if @@stop
            logger.info "Stopping aggregation now, due request to stop."
            return
        end

        logger.debug "Aggregation done. Next aggregation in #{setting.aggregate_timer} seconds."

        sleep setting.aggregate_timer
        start
    end
end

# Initialize aggregator
if __FILE__ == $PROGRAM_NAME
    app = Aggregator.new(true, ARGV)
end

Is that a good way to realize a built in server as well as support for other app server?
If you're interested in the project, you can find it here: https://github.com/openscript/social_aggregator


texts:
I'm looking for some feedback on my implementation of the algorithm. How can I improve it? I ran into problems when calculating the larger prime numbers > 46349 due to integer overflow, but fixed that by using sqrt instead of pow.

#include<iostream>
#include<math.h>
using namespace std;

int main(){
    int number;
    cin >> number;
    const int CAP = number;
    bool * prime = new bool[CAP];

    for(int i = 0; i < CAP; i++){ //sets all to true for the marking
        prime[i] = true;
    }

    for(int i = 2; i < number; i++){
        if(i <= sqrt(number) && prime[i] == true){
            for(int j = i*i; j < number; j++){ //if %i == 0 mark false
                if(j % i == 0){               //haven't tried another way
                    prime[j] = false;
                }
            }
        }
    }

    for(int i = 2; i < number; i++){
        if(prime[i] == true){
            cout << i << endl;
        }
    }

    return 0;
}


texts:
I am using Java, but coming from a JavaScript background. I have two objects:

a list of users
an Iterable of users preferences

I am joining them into a new users object that I call newUser, and then adding newUser to a List of User and returning that.
I need to match up users to their user preferences based on a shared id.  If I was using JS I would get the id of the user and filter the user preferences based on the same id.  I wasn't able to figure that out, so I used a for loop for users and then a foreach loop for users preferences and the used an if statement to find a match.
var users = service.getUsers();
List<User> value = new ArrayList<User>();
var usersPreferences = _userRepo.findAll();
for(int i =0; i < users.size(); i++){
    var user = users.get(i);
    boolean[] isFound = {false};
    usersPreferences.forEach(prefUser -> {
        if(prefUser.getId() == user.getId()){
            User newUser = new User(user, prefUser);
            value.add(newUser);
            isFound[0] = true;
        }
    });
    if(!isFound[0]){
        User newUser = new User(user);
            value.add(newUser);
    }
}
return value;