texts:
I would like to display this data, callable at any time, but I'm not sure if this is the best practice to do so.

countries = [
   dict(Name = "China", Population = "1,363,560,000"),
   dict(Name = "India", Population = "1,242,070,000"),
   dict(Name = "United States", Population = "317,768,000"),
   dict(Name = "Indonesia", Population = "249,866,000"),
   dict(Name = "Brazil", Population = "201,032,714"),
   dict(Name = "Pakistan", Population = "186,015,000"),
   dict(Name = "Nigeria", Population = "173,615,000"),
   dict(Name = "Bangladesh", Population = "152,518,015"),
   dict(Name = "Russia", Population = "143,700,000"),
   dict(Name = "Japan", Population = "127,120,000"),
   dict(Name = "Mexico", Population = "119,713,203"),
   dict(Name = "Philippines", Population = "99,329,000"),
   dict(Name = "Vietnam", Population = "89,708,900"),
   dict(Name = "Egypt", Population = "86,188,600"),
   dict(Name = "Germany", Population = "80,716,000"),
   dict(Name = "Iran", Population = "77,315,000"),
   dict(Name = "Turkey", Population = "76,667,864"),
   dict(Name = "Thailand", Population = "65,926,261"),
   dict(Name = "France", Population = "65,844,000"),
   dict(Name = "United Kingdom", Population = "63,705,000"),
   dict(Name = "Italy", Population = "59,996,777"),
   dict(Name = "South Africa", Population = "52,981,991"),
   dict(Name = "South Korea", Population = "50,219,669"),
   dict(Name = "Colombia", Population = "47,522,000"),
   dict(Name = "Spain", Population = "46,609,700"),
   dict(Name = "Ukraine", Population = "45,410,071"),
   dict(Name = "Kenya", Population = "44,354,000"),
   dict(Name = "Argentina", Population = "40,117,096"),
   dict(Name = "Poland", Population = "38,502,396"),
   dict(Name = "Sudan", Population = "37,964,000"),
   dict(Name = "Uganda", Population = "35,357,000"),
   dict(Name = "Canada", Population = "35,344,962"),
   dict(Name = "Iraq", Population = "34,035,000"),
   ]

print countries


texts:
This code uses the Rabin-Karp algorithm to compare two text files. It takes a few minutes when both files contain around 1000 words. How can it be improved?
class RollingHash:
    def __init__(self, text, sizeWord):
        self.text = text
        self.hash = 0
        self.sizeWord = sizeWord

        for i in range(0, sizeWord):
            #subtract out the ASCII value of "a" to start the indexing at zero
            self.hash += (ord(self.text[i]) - ord("a")+1)*(26**(sizeWord - i -1))
        #start index of current window
        self.window_start = 0
        #end of index window
        self.window_end = sizeWord

    def move_window(self):
        if self.window_end <= len(self.text) - 1:

            self.hash -= (ord(self.text[self.window_start]) - ord("a")+1)*26**(self.sizeWord-1)
            self.hash *= 26
            self.hash += ord(self.text[self.window_end])- ord("a")+1
            self.window_start += 1
            self.window_end += 1

    def window_text(self):
        return self.text[self.window_start:self.window_end]

def rabin_karp(word, text):
    if word == "" or text == "":
        return None
    if len(word) > len(text):
        return None

    rolling_hash = RollingHash(text, len(word))
    word_hash = RollingHash(word, len(word))
    word_hash.move_window()

    for i in range(len(text) - len(word) + 1):
        if rolling_hash.hash == word_hash.hash:
            if rolling_hash.window_text() == word:
                return i
        rolling_hash.move_window()
    return None


texts:
The following (stripped) program receives UDP packets on port 5000 and forwards them to port 5001. It may throw socket errors on startup (e.g.: if the port is already in use), but I am not too worried about that.

import socket

RECEIVE_IP = "0.0.0.0"
RECEIVE_PORT = 5000
RECEIVE_BUFFER_SIZE = 4096

SEND_IP = "127.0.0.1"
SEND_PORT = 5001

send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

receive_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receive_socket.bind((RECEIVE_IP, RECEIVE_PORT))

while True:
    string = receive_socket.recv(RECEIVE_BUFFER_SIZE)
    send_socket.sendto(string, (SEND_IP, SEND_PORT))

I would like to make sure the program keeps running after a successful startup. Is it enough to try/catch the socket errors?

while True:
    try:
        string = receive_socket.recv(RECEIVE_BUFFER_SIZE)
        send_socket.sendto(string, (SEND_IP, SEND_PORT))
    catch socket.error:
        print 'Oops!'

Or is there anything else I need to worry about? Would I ever need to rebind receive_socket for instance?

Bonus question: the real problem here is that I am not aware how to test this program for failure. Would anyone have a recommendation?


texts:
Just a plain button, in different sizes. I wanted to achieve exactly the same styling cross browser for both anchors, inputs and buttons.

I'm just wondering if this could be improved.

Markup

<!DOCTYPE html>

        <title>CSS button</title>
        <link rel="stylesheet" href="css/main.css">

        Sign up
        Sign up
        Sign up
        Sign up

        <input type="submit" class="button button-tiny button-primary" value="Sign up">
        <input type="submit" class="button button-primary" value="Sign up">
        <input type="submit" class="button button-medium button-primary" value="Sign up">
        <input type="submit" class="button button-large button-primary" value="Sign up">

        <button class="button button-tiny button-primary">Sign up</button>
        <button class="button button-primary">Sign up</button>
        <button class="button button-medium button-primary">Sign up</button>
        <button class="button button-large button-primary">Sign up</button>

CSS

body,
input,
button {
    font: 14px "Trebuchet MS", sans-serif;
}

input::-moz-focus-inner,
button::-moz-focus-inner {
    border: 0;
    padding: 0;
}

.button {
    padding:8px 16px;
    display:inline-block;
    text-decoration:none;
    border-radius:3px;
    border:0;
    margin:0;
}

input[type="submit"].button,
button.button {
    cursor:pointer;
    outline:none;
}

.button-tiny {
    font-size:12px;
    padding:6px 14px;
}

.button-medium {
    font-size:16px;
    padding:10px 18px;
}

.button-large {
    font-size:18px;
    padding:12px 20px;
}

.button-primary {
    background:slategrey;
    color:#fff;
}

.button-primary:hover {
    background:lightslategrey;
};


texts:
I find IndexedDB cumbersome and want to wrap the functionality with rxjs observables.  I've come up with an angular2 service that seems to fit the bill, but I'm wondering if I'm using the observables correctly or if there might be any subscriptions I'm missing (plnkr):

Usage:

this.localDbService.set('storeName', key, value)
  .subscribe(
    x => console.log('stored key ', x),
    err => console.error('error storing value', err)
  );

this.localDbService.get('storeName', key)
  .subscribe(
    x => console.log('got value', x),
    err => console.error('error getting value', err)
  );

The service opens the database in the constructor and provides it using a ReplaySubject.  This is the first thing I think might have a better solution.  I want some sort of observable that will provide me with a single value but only after initialization has finished, and provide the same value any time it is called.  I use a ReplaySubject(1) and use .take(1) on it, so any subscribers will not get a value until one is provided, and will only get a single value and won't have to unsubscribe.  Should I perhaps use an AsyncSubject?

Also I'm catching errors in storing and querying and passing any errors from db creation up to the caller, am I missing anything here?:

store(storeName: string, key: any, value: any): Observable<any> {
  return Observable.create((observer: Observer<any>) => {
    try {
      this.db.take(1).subscribe(db => {
        if (!db) {
          observer.error("IndexDB not supported!");
          return;
        }

        var txn = db.transaction([storeName], "readwrite");
        var store = txn.objectStore(storeName);
        var req = store.add(value, key);
        req.onerror = function(err) {
          observer.error(err);
          return;
        };
        req.onsuccess = function(e: any) {
          observer.next(e.target.result);
          observer.complete();
        };
      });
    } catch(err) {
      observer.error(err);
    }
  });
}


texts:
It has been a long time I used c++.
So I brushing over concepts for interview preparation.
Can you please help me with code review?
If you have any observations/bugs/alternatives please point out.
For better formatting, I have shared code here feel free to open issues. :)
Thanks a ton in advance.

#include <cstring>
#include <memory>
#include <utility>

class Test {
public:
    //Default constructor
    Test() = default;

    //Copy constructor
    Test(const Test& other) : m_size(other.m_size), m_buffer(new char[m_size]()) {
        strncpy(m_buffer.get(), other.m_buffer.get(), m_size);
    }

    //Parametarized constructor
    Test(std::size_t len, const char* data) : m_size(len), m_buffer(new char[len]()) {
        strncpy(m_buffer.get(), data, m_size);
    }

    //Move constructor
    Test(Test&& other) noexcept {
        Test temp(other);
        swap(*this, temp);
    }

    //Assignment operator
    Test& operator=(Test other) {
        if(this != &other) {
            swap(*this, other);
        }
        return *this;
    }

    //Move assignment operator
    Test& operator=(Test&& other) noexcept {
        if(this != &other) {
            Test temp(other);
            swap(*this, temp);
        }
        return *this;
    }

    //Destructor
    ~Test() {
        m_size = 0;
        m_buffer = nullptr;
    }
private:
    std::size_t m_size = 0;
    std::unique_ptr<char[]> m_buffer = nullptr;

    static void swap(Test& first, Test& second) noexcept{
        using std::swap;
        swap(first.m_size, second.m_size);
        swap(first.m_buffer, second.m_buffer);
    }
};


texts: Finding the maximum distance from the starting node

texts:
I've tried everything to make my program faster but with 250 nodes my code takes around 9 seconds to print the result, and with 5000 nodes it took around 260 seconds.

Is there a way to make my program faster?

I took the BFS function from here.

  The site(connections) should consist of three towns each of which is connected to
  directly the other one by a road. The distance between two towns A and
  B is the minimum number of pairs of directly connected towns on the
  way from A to B. Two towns are connected directly by a road R if there
  is no other town on R between A and B. The distance of any possible
  site from the capital city is equal to the sum of the distances from
  each of the three towns representing the site from the capital city.

Output: the maximum possible distance of a site from the capital city, the number of all sites which are located at the maximum distance from the capital city.

  there are two most distant sites from the capital in node 9, the sites
  are {0, 1, 3} and {2, 3, 5} and their distance from the capital is 10

Input first line (nodes_count, pairs_number, capital)
Next all the pairs

Input

10 17 9
0 1
0 3
1 3
1 4
2 3
3 4
2 5
3 5
3 6
4 6
4 7
5 6
6 7
6 8
7 8
7 9
8 9

Output

10 2

My code

from collections import defaultdict
from queue import Queue

def read_nodes(pairs_number):
    for _ in range(pairs_number):
        yield map(int, input().split())

def parse_input(tree):
    nodes_count, pairs_number, capital = map(int, input().split())
    for node1, node2 in read_nodes(pairs_number):
        tree[node1].append(node2)
        tree[node2].append(node1)
    return tree, capital, nodes_count

def traverse_path(fromNode, toNode, nodes):
    def getNeighbours(current, nodes):
        return nodes[current] if current in nodes else []

    def make_path(toNode, graph):
        result = []
        while 'Root' != toNode:
            result.append(toNode)
            toNode = graph[toNode]
        result.reverse()
        return result

    q = Queue()
    q.put(fromNode)
    graph = {fromNode: 'Root'}

    while not q.empty():
        current = q.get()
        for neighbor in getNeighbours(current, nodes):
            if neighbor not in graph:
                graph[neighbor] = current
                q.put(neighbor)
        if current == toNode:
            return make_path(toNode, graph)
    return []

def distant_sites(graph_dic, capital, nodes_count):
    distance_with_connections = defaultdict(list)
    node_distance = {}
    for towns in range(nodes_count):
            towns_distance = len(traverse_path(capital, towns, graph_dic)) - 1
            node_distance[towns] = (towns_distance)
    for town1, neighbours in graph_dic.items():
        for town2 in neighbours:
            if town1 > town2:
                for neighbour_of_town2 in graph_dic[town2]:
                    if town2 > neighbour_of_town2:
                        if neighbour_of_town2 in neighbours:
                            town_connection = (town1, town2, neighbour_of_town2)
                            distance = (node_distance[town1]) + (node_distance[town2]) + (node_distance[neighbour_of_town2])
                            distance_with_connections[distance].append(town_connection)
    max_distance = max(distance_with_connections)
    return max_distance, len(distance_with_connections[max_distance])

if __name__ == '__main__':
    graph_dic, capital, nodes_count = parse_input(defaultdict(list))
    max_distance, number_of_connections = distance_sites(graph_dic, capital, nodes_count)
    print(max_distance, number_of_connections)


texts: Two strings are permutations of each other

texts:
I am trying to remove the character from the list generated from the second string.
At the end, if the array is empty it is the permutation of two strings else not.

Is this logic fine?

def is_permutation(string1, string2):
    if len(string1) != len(string2):
        return False
    string2 = list(string2)
    for char in string1:
        if char in string2:
            string2.remove(char)
    if not string2:
        return True
    return False

if __name__ == '__main__':
    print(is_permutation("abc", "cba"))
    print(is_permutation("bc", "ab"))
    print(is_permutation("dog", "god"))


texts:
Watson gives to Sherlock an array: A1, A2, ⋯, AN. He also gives to
  Sherlock two other arrays: B1, B2, ⋯, BM and C1, C2, ⋯, CM. Then Watson asks
  Sherlock to perform the following program:

  for i = 1 to M do
   for j = 1 to N do
     if j % B[i] == 0 then
         A[j] = A[j] * C[i]
    endif
 end do
end do

  Can you help Sherlock and tell him the resulting array A? You should print all the array elements modulo (1000000007).

  Input Format

  The first line contains two integer numbers N and M. The
  next line contains N integers, the elements of array A. The next two
  lines contains M integers each, the elements of array B and C.

  Output Format

  Print N integers, the elements of array A after
  performing the program modulo (1000000007).

  Sample Input

4 3
1 2 3 4
1 2 3
13 29 71

  Sample Output

13 754 2769 1508

If we brute force, it will time out.  Please suggest ways on making this efficient.

import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;

public class SherlockArray {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String line1 = in.nextLine();
    StringTokenizer st = new StringTokenizer(line1, " ");

    int n = Integer.parseInt(st.nextToken());
    int m = Integer.parseInt(st.nextToken());
    Long[] b = new Long[m];

    String strA = in.nextLine();
    String[] stA = strA.split(" ");
    BigInteger aBI[] = new BigInteger[n];
    for (int ia = 0; ia < stA.length; ia++) {
        aBI[ia] = new BigInteger(stA[ia]);
    }

    String strB = in.nextLine();
    String[] stB = strB.split(" ");
    for (int ib = 0; ib < stB.length; ib++) {
        b[ib] = Long.parseLong(stB[ib]);
    }

    String strC = in.nextLine();
    String[] st3 = strC.split(" ");
    for (int ic = 0; ic < m; ic++) {
        for (int index = b[ic].intValue(); index <= n; index += b[ic]
                .intValue()) {
            aBI[index - 1] = aBI[index - 1].multiply(new BigInteger(st3[ic]));
        }
    }

    for (int ia = 0; ia < n; ia++) {
        aBI[ia] = aBI[ia].mod(new BigInteger("1000000007"));
        System.out.print(aBI[ia] + " ");
    }

}

}


texts: Super Compact Bresenham's Line Algorithm v2

texts:
I recently posted here about an implementation of the Besenham's line algorithm that I wrote. I've been hard at work improving it and redoing it from the ground up. However I still can't seem to beat BLA--not sure if I'm testing wrong or if it's something else.
void bresenprecalc(int x1, int y1, int x2, int y2) {
    // Initialization, x,y directions and horz/vert line length.
    int dx = x2 - x1, dy = y2 - y1,
        dxA = sign(dx), dyA = sign(dy),
        dxB = abs(dx), dyB = abs(dy),
        // Set case 1 by default (dyB >= dxB).
        xm=0, ym=dyA,
        yxm=dxB, xym=dyB;

    // Set case 1 if dxB >= dyB.
    if (dxB >= dyB) {
        xm = dxA; ym = 0;
        yxm = dyB; xym = dxB;
    }

    // Incremental error check (see Bresenhams algorithm).
    int er2 = yxm - xym,
        er = yxm - (xym>>1);

    // draw x1,y1 (starting pixel).
    // End when x1 OR y1 reach EOL (faster than AND).
    for(;x1!=x2 || y1!=y2;) {
        // Error check above/below the line.
        if (er >= 0) {
            // If we've crossed the line, adjust the pixel diagonally.
            x1 += dxA;
            y1 += dyA;
            er += er2;
        } else {
            // Move in primary vertical/horizontal direction of the line.
            x1 += xm;
            y1 += ym;
            er += yxm;
        }

        // draw x1,y1 (line pixel).
    }
};

Without Comments:
void bresenprecalc(int x1, int y1, int x2, int y2) {
    int dx = x2 - x1, dy = y2 - y1,
        dxA = sign(dx), dyA = sign(dy),
        dxB = abs(dx), dyB = abs(dy),
        xm=0, ym=dyA,
        yxm=dxB, xym=dyB;

    if (dxB >= dyB) {
        xm = dxA; ym = 0;
        yxm = dyB; xym = dxB;
    }

    int er2 = yxm - xym,
        er = yxm - (xym>>1);

    // draw x1,y1 (starting pixel).
    for(;x1!=x2 || y1!=y2;) {
        if (er >= 0) {
            x1 += dxA;
            y1 += dyA;
            er += er2;
        } else {
            x1 += xm;
            y1 += ym;
            er += yxm;
        }
        // draw x1,y1 (line pixel).
    }
};

I honestly think I've squeezed everything out of this implementation. I'm out of ideas.


texts: Shorthand for isset($var['foo']) ? $var['foo'] : ''

texts:
I feel like I write this a lot in PHP:

 $val = isset($var['foo']) ? $var['foo'] : '';

Is there a shorter way to write this? I can't use the ternary operator because the conditional is an isset check, not the value of the function itself.


texts: React - passing the return of a function as prop

texts:
The code below works as intended but I'm not sure the way I'm passing it to a component is correct. Also, I don't think the way I wrote this function is recommended. It's not a pure function and probably should be split into two functions where one needs the output of the other.
'books' and 'authors' are 'state' objects in this functional component. The author list is dynamic based on the users choices (author list checkboxes). As I said, it works fine but it's probably not written the way it should:
const selectedBooks = (books, authors) => {
    // get the list of the currently selected authors and save it in a list.
    const authorList = authors.filter(author => author.active).map(item => item.name);
    // filter the list of books for the currently selected authors
    const bookList =  books.filter(book => authorList.includes(book.source.name));
    return bookList;
}

And then it's passed:
<BookList books={selectedBooks(books, authors)} />

EDIT based on the comment:
That's what I thought. So would I do the following:
const selectedBooks = (books, authors) => {
        // get the list of the currently selected authors and save it in a list.
        const authorList = authors.filter(author => author.active).map(item => item.name);
        // filter the list of books for the currently selected authors
        const bookList =  books.filter(book => authorList.includes(book.source.name));
        return bookList;
    }

const booksToPass = selectedBooks(books, authors);

...

<BookList books={booksToPass} />


texts: Sectioning element choice for main content in HTML5 Bones

texts:
The new HTML5 Bones template uses the following example for the main content (I removed some parts (like ARIA, comments, aside, …) not relevant for this question):

Getting Started

    …

Introduction

Welcome to HTML5 Bones. This is a template that contains comments to aid you with setting up your HTML5 document.

Instructions

Read the comments in this template

Decide how you think your content may fit into the template

Start building your document

The whole document has the following outline:

  HTML5 BonesUntitled SectionGetting StartedUntitled SectionIntroductionInstructionsDid you know?

This outline is correct for the document. But I wonder if the use of the section element and the article elements is correct.


texts:
This is my little Sudoku solver in Rust. It iterates through empty cells and checks which numbers are absent from the corresponding row, column, and square. If there is one possible candidate, it fills in the answer and moves on to the next empty cell.

Clearly I should be reading from an input rather than hard-coding the puzzle. What other ways can I improve the readability and make it more idiomatic?

type Cell = (usize, usize);

struct Grid {
    data: [[u8; 9]; 9],
    current: Cell,
}

impl Grid {
    // Search possible candidates for a given cell.
    // If one candidate exists, return it.
    fn check(&mut self, cell: Cell) -> Option<u8> {
        let mut candidates = [true; 9];
        for i in 1..10 {
            candidates[i-1] &= self.check_row(cell, i as u8);
            candidates[i-1] &= self.check_column(cell, i as u8);
            candidates[i-1] &= self.check_square(cell, i as u8);
        }

        if candidates.iter().fold(0, |acc, &x| acc + x as i32) == 1 {
            return Some(candidates.iter()
                                  .position(|&x| x == true)
                                  .unwrap() as u8 + 1);
        }
        None
    }
    fn check_row(&self, cell: Cell, num: u8) -> bool {
        let row = self.data[cell.0];
        for i in row.iter() {
            if *i == num { return false; }
        }
        true
    }
    fn check_column(&self, cell: Cell, num: u8) -> bool {
        for row in self.data.iter() {
            if row[cell.1] == num { return false; }
        }
        true
    }
    fn check_square(&self, cell: Cell, num: u8) -> bool {
        let mut square: (usize, usize) = (cell.0 / 3, cell.1 / 3);

        square.0 *= 3;
        square.1 *= 3;

        for row in (square.0)..(square.0 + 3) {
            for column in (square.1)..(square.1 + 3) {
                if self.data[row][column] == num { return false; }
            }
        }
        true
    }
}

// Iterate through empty cells.
impl Iterator for Grid {
    type Item = Cell;

    fn next(&mut self) -> Option<Self::Item> {
        let starting_point = (self.current.0, self.current.1);
        loop {
            self.current.0 = (self.current.0 + 1)%9;
            if self.current.0 == 0 {
                self.current.1 = (self.current.1 + 1)%9;
            }
            if (self.current.0, self.current.1) == starting_point {
                return None;
            }
            if self.data[self.current.0][self.current.1] == 0 { break }
        }
        Some(self.current)
    }
}

fn main () {
    let mut grid = Grid {
        data: [ [1,6,4,0,0,0,0,0,2],
                [2,0,0,4,0,3,9,1,0],
                [0,0,5,0,8,0,4,0,7],
                [0,9,0,0,0,6,5,0,0],
                [5,0,0,1,0,2,0,0,8],
                [0,0,8,9,0,0,0,3,0],
                [8,0,9,0,4,0,2,0,0],
                [0,7,3,5,0,9,0,0,1],
                [4,0,0,0,0,0,6,7,9] ],
        current: (0, 0),
    };

    loop {
        if let None = grid.next() { break; }
        let empty_cell = grid.current;
        match grid.check(empty_cell) {
            Some(i) => {
                grid.data[empty_cell.0][empty_cell.1] = i;
            },
            None => continue,
        }
    }

    for row in grid.data.iter() {
        println!("{:?}", row);
    }
}


texts: Find all collection properties of an object and get their values

texts:
I have a chunk of code that get's all of the ICollection properties of the passed in object and then takes all of their values and adds them to another ICollection.

  End goal is to see which properties have child objects in them and
  thus finding out how many dependents the object has.

The object is an EntityFramework entity so the children would be other entities. I'm not entirely convinced that I'm actually grabbing the correct properties (although in my tests so far it works) and I'm not convinced I'm parsing them efficiently either. Here's the code, and I welcome any recommendations:

public class DependencyValidator<TEntity> :
    IDependencyValidator<TEntity>
    where TEntity : class {
    private readonly Type IEnumerableType = typeof(IEnumerable);
    private readonly Type StringType = typeof(String);

    public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Dependencies(
        TEntity entity) {
        if (entity == null) {
            return Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>();
        }

        ICollection<KeyValuePair<string, IEnumerable<string>>> dependents = new List<KeyValuePair<string, IEnumerable<string>>>();

        entity.GetType().GetProperties().Where(
            p =>
                this.IEnumerableType.IsAssignableFrom(p.PropertyType)
                && !this.StringType.IsAssignableFrom(p.PropertyType)).ForEach(
            p => {
                IEnumerable values = (p.GetValue(entity) as IEnumerable);
                ICollection<string> children = new List<string>();

                foreach (var value in values) {
                    children.Add(value.ToString());
                }

                dependents.Add(new KeyValuePair<string, IEnumerable<string>>(p.Name, children));
            });

        return dependents;
    }
}


texts:
The Greed game, from Ruby Koans, where you roll up to 5 dice:

A set of three ones is 1000 points. A set of three numbers (other than ones) is worth 100 times the number.
A one (that is not part of a set of three) is worth 100 points. A five (that is not part of a set of three) is worth 50 points. Everything else is worth 0 points.

I broke my solution into four methods.
def score(dice)
  (1..6).reduce(0) { |sum, n| sum + points(dice, n) }
end

def points(dice, num)
  ((dice.count(num) / 3) * triple(num)) + ((dice.count(num) % 3) * bonus(num))
end

def triple(num)
  num == 1 ? 1000 : (num * 100)
end

def bonus(num)
  [1, 5].include?(num) ? 50 + (50 * (num % 5)) : 0
end

I suspect there's a way to avoid having to pass the dice array into points(), but I can't figure it out. Maybe using a yield somewhere?


texts:
I have a class, which is meant to show a full screen modal controller with a set of actions (apart from actions it also has some static content, a lot of labels and images which are irrelevant, so I omitted approximately 500 lines of code to keep it simple). It looks as follows:

import UI_Framework

class DescriptionViewController: UIViewController {

    var actions: [(title: String, action: () -> Void)]! {
        didSet {
            setUpActions(actions)
        }
    }

    private var actionStackView: UIStackView!

    // MARK: Lifecycle

    init(actions: [(title: String, action: () -> Void)]? = nil) {
        super.init(nibName: nil, bundle: nil)
        if let actions = actions {
            self.actions = actions
        } else {
            self.actions = [(title: "Close", action: { [weak self] in
                 guard let strongSelf = self else {
                     return
                 }
                 strongSelf.dismiss(animated: true)
            }]
        }
    }

    func viewDidLoad() {
        super.viewDidLoad()
        actionStackView = UIStackView(axis: .horizontal, spacing: 20)
        view.addSubview(actionStackView)
        actionStackView.fillSuperView()
        setUpActions(actions)
    }

    // MARK: Private

    private func setUpActions(_ actions: [(title: String, action: () -> Void)]) {
        guard let actionStackView = actionStackView else {
            return
        }

        actionStackView.subviews.forEach { $0.removeFromSuperview() }
        actions.map { CustomButton(title: $0.title, onClick: $0.action) }.forEach { actionStackView.addArrangedSubview($0) }
    }

}

Important note - I cannot define default actions during first phase of initialization because these actions are actually referencing to the class instace itself.

The idea behind having actions property force unwrapped instead of optional is because it's actually not supposed to have a nil value, as it may get somewhat confusing: what is meant by nil? Empty array of actions or default actions? It's especially crucial in the constructor, as it can take any of the values and should treat them differently. So the force-unwrapped property explains it by itself - do not make me nil, set empty array if you want empty array, keep it explicit and clear. Even if anyone sets it to nil by mistake it should get easily discovered - app will just crash.

However there is an opinion that force-unwrapping should be avoided at any cost to not introduce an error-prone code which might crash the app.

What is the better approach here?


texts: Find words that can be typed using only one row on a keyboard

texts:
on leetcode.com, there is a question with the following description:

  Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
  link to the question here.

Here is my implementation:

class Solution {
public:
    std::vector<std::string> findWords(std::vector<std::string>& words)
    {
        std::unordered_set<char> firstRow = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'};
        std::unordered_set<char> secondRow = {'A','S','D','F','G','H','J','K','L'};
        std::unordered_set<char> thirdRow = {'Z','X','C','V','B','N','M'};
        std::vector<std::string> result;

        size_t vecSize = words.size();
        for(size_t i = 0; i < vecSize; ++i)
        {
                if(sameRow(words[i], firstRow))
                    result.push_back(words[i]);
                else if(sameRow(words[i], secondRow))
                    result.push_back(words[i]);
                else if(sameRow(words[i], thirdRow))
                    result.push_back(words[i]);
        }
        return result;
    }
    bool sameRow(const std::string& words, const std::unordered_set<char>& row)
    {
                size_t wordSize = words.size();
                for(size_t j = 0; j < wordSize; ++j)
                {
                    if(row.find(toupper(words[j])) == row.end())
                    {
                       return false;
                    }
                }
        return true;
    }
};


texts:
The given code find the minimum element in a sorted array rotated by some fixed distance.
Eg: [1, 2, 3, 4, 5, 6, 7] -> [3, 4, 5, 6, 7, 1, 2]

The elements in the array are all unique. Just wanted to check if the code handles all edge cases and is correct.

def findMin(ary):

    def recurse(lo, hi):
        # Base cases
        if (ary[lo] < ary[hi]):
            return ary[lo]
        if (hi - lo == 1):
            return min(ary)

        mid = lo + (hi - lo) / 2
        if (ary[mid] < ary[hi]):
            return recurse(lo, mid)
        else:
            return recurse(mid, hi)

    return recurse(0, len(ary) - 1)

ary = (3, 4, 5, 6, 7, 1, 2)
print findMin(ary) # 1


texts:
This feels wrong:

private decimal ConvertStringToDecimal(string decimalString, decimal defaultReturnValue)
{
    var returnDecimal = defaultReturnValue;

    try
    {
    returnDecimal = decimal.Parse(decimalString.Trim());
    }
    catch (Exception)
    {
    // naughty
    }

    return returnDecimal;
}

but I think this is the only way to transform a string from a third party system to a decimal whilst returning a default. Does anyone have any suggestions on how to improve this?


texts: Controller method to add a product, stored across three database tables

texts:
I have some questions on how I can improve this "add" action method in a controller.

Using a single form, the user can upload a product to be displayed on the site.  A Product is composed of three entities: Product, ProductFeatures and ProductMedias (stored in three database tables).

To prepare data for insertion and upload, I have created two helper classes with static methods to simplify the controllers. (This approach should help with rollback if necessary).

In one action (the add method of Products controller), I do multiple tasks:

The setProductByForm method in ProductsTable creates an empty Product entity, populates it with form data, and saves it in the database.

public function setProductByForm($form)
{
     $product = $this->newEntity();
     $product = $this->patchEntity($product, $form);
     return $this->save($product);
}

The uploadFiles method in UploadFilesComponent stores the common images.
A method in the ModelUtils class calls other methods that prepare and tranform the data in entities.

public static function prepareProductsFeatures($formValues, $productId)
{
    $productFeaturesArray = self::createProductsFeaturesArray($formValues);
    $productFeaturesEntities = self::createProductsFeaturesEntitiesArray(
        $productFeaturesArray, $productId
    );
    return $productFeaturesEntities;
}

I create the URL where thumbnail will stored (using a method in the UploadUtils class).

public static function getOutputThumbUrl($mainImage, $productId)
{
    return str_replace(PRODUCTS_IMAGES_FOLDER . $productId,
        PRODUCTS_THUMB_FOLDER, $mainImage);
}

The thumbnail is stored.
Methods in ModelUtils transform data into entities and save them in MediasTable.

What is the best way to separate concepts and operations?

Note: I've tried to use afterSave but it's impossible to access request->data from it.

Controller action

public function add()
{
    $this->autoRender = false;

    if ($this->request->is('post'))
    {
        $productSaved = $this->Products->setProductByForm($this->request->data);

        if($productSaved)
        {
            $this->loadModel('ProductFeatures');
            $productFeaturesSaved = $this->ProductFeatures->setProductFeaturesEntities(
                ModelUtils::prepareProductsFeatures($this->request->data, $productSaved['id'])
            );

            $imagesUploaded = $this->UploadFile->uploadFiles(
                PRODUCTS_IMAGES_FOLDER . $productSaved['id'], $this->request->data['file']
            );

            $outputThumbUrl = UploadUtils::getOutputThumbUrl($imagesUploaded[0]['url'], $productSaved['id']);

            $thumbUploaded = $this->UploadFile->resizeImage([
                'input' => $imagesUploaded[0]['url'], 'output' => $outputThumbUrl,
                'width' => 250, 'height' => 250, 'mode' => 'stretch'
            ]);

            $this->loadModel('Medias');
            $thumbSaved = $this->Medias->setMediaEntity(
                ModelUtils::prepareMediaThumb($productSaved['id'], $outputThumbUrl)
            );
            $mediasSaved = $this->Medias->setMediasEntities(
                ModelUtils::prepareMedias($imagesUploaded, $productSaved['id'])
            );
        }
    }
}

Full source code

ProductsController class
ModelUtils class
UploadUtils class
ProductsTable class
MediasTable class
ProductFeaturesTable class


texts: Haskell Hspec/Quickcheck test for numeric function

texts:
I'm learning to use HSpec and QuickCheck.
As example I was implementing the Pseudocode from Wikipedia:Extended Euclidean Algorithm. You can  find the project at github for the implementation of the tested code.
In particular I wonder about two practices:

selection of test cases - I took two trivial samples, examples from the wikipedia page and took three property tests.
Generation of cases - the a>0 && b>0 seems inefficient to me.

I'm most interested what would be a good practice to confirm two algorithms produce the same results.
module EuclidSpec  ( spec )
where

import Test.Hspec
import Test.Hspec.Core.QuickCheck
import Test.QuickCheck
import Lib

spec :: Spec
spec = do
  describe "Trivial" $ do
    it "trivial example 99 1" $
       let trivial = extendedEuclid 99 1
       in  trivial `shouldBe` (EuclidRes 1 (0) 1)
    it "trivial example 99 99" $
       let trivial = extendedEuclid 99 99
       in  trivial `shouldBe` (EuclidRes 99 (0) 1)
  describe "Examples" $ do
    it "explanation example 99 78" $
       let wikiExample = extendedEuclid 99 78
       in  wikiExample `shouldBe` (EuclidRes 3 (-11) 14)
    it "explanation example flipped 78 99" $
       let wikiExample = extendedEuclid 78 99
       in  wikiExample `shouldBe` (EuclidRes 3 14 (-11) )
    it "explanation example 99 78" $
       let wikiExample = extendedEuclid 240 46
       in  wikiExample `shouldBe` (EuclidRes 2 (-9) 47)
  describe "properties" $ do
      it "both numbers divisible a%gcd == 0, b%gcd ==0" $ property $
            prop_divisible
      it "bezout a*s+b*t = gcd" $ property $
            prop_bezout
      it "recursive and iterative algorithm have same result" $ property $
            prop_same_as_recursive

prop_divisible a b = a>0 && b>0 ==> a `mod` d ==0 && b `mod`d == 0
  where EuclidRes d s t = extendedEuclid a b

prop_bezout a b = a>0 && b>0 ==> a*s + b*t == d
  where EuclidRes d s t = extendedEuclid a b

prop_same_as_recursive a b = a>0 && b>0 ==> extendedEuclid a b == extendedEuclid' a b


texts:
I work quite a lot with file reading and writing in C/Win32 and I started wondering if my code is completely ugly and how I can improve it. I wrote two simple examples of reading a file, and I wonder how these functions could be improved. Are these methods bad - and how they can be improved? I use MSVC so the code might contain MS-specific macros or keywords.

BOOL read_file(PCHAR filename, PBYTE *outdata, DWORD *outsize)
{
    DWORD check = 0;
    BOOL success = FALSE;
    HANDLE hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if(hFile != INVALID_HANDLE_VALUE)
    {
        if((*outsize = GetFileSize(hFile, NULL)) != INVALID_FILE_SIZE)
        {
            if((*outdata = malloc(*outsize)) != NULL)
            {
                if(ReadFile(hFile, *outdata, *outsize, &check, NULL) && check == *outsize)
                {
                    success = TRUE;
                }
            }
        }
    }

    if(hFile != INVALID_HANDLE_VALUE)
    {
        CloseHandle(hFile);
    }

    return success;
}

BOOL read_file2(PCHAR filename, PBYTE *outdata, DWORD *outsize)
{
    DWORD check = 0;
    BOOL success = TRUE;
    HANDLE hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        success = FALSE; goto _end;
    }

    if((*outsize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE)
    {
        success = FALSE; goto _end;
    }

    if((*outdata = malloc(*outsize)) == NULL)
    {
        success = FALSE; goto _end;
    }

    if(!ReadFile(hFile, *outdata, *outsize, &check, NULL) || check != *outsize)
    {
        success = FALSE; goto _end;
    }

_end:

    if(hFile != INVALID_HANDLE_VALUE)
    {
        CloseHandle(hFile);
    }

    return success;
}

Questions:

Which one is better, and why?
What is bad about the above examples?
Can you show a better example or how you would do it?


texts: Translate boolean flags to collection of numbers in scala

texts:
I'm having trouble to implement the following requirement in a functional way in scala. Given a predefined number of boolean flags, I want to build up a collection of numbers. For each (true) flag, a hardcoded number should be included in the collection.

This is the unsatifying solution I have so far:

  def createCodeArray(flagA:Boolean, flagB:Boolean, flagC:Boolean): Seq[Int] = {
    val codes = ListBuffer.empty[Int]

    if(flagA) codes += 2
    if(flagB) codes += 7
    if(flagC) codes += 12

    return codes
  }

I'm trying to achieve to same with pattern matching, but I don't want to list all the possible combinations. Also, I'd like to avoid mutable data-structures.

Any suggestion on how to write this in a functional way is much appreciated


texts:
This program calculates common factor for given numbers. The original use case is to find a possible resolution for pixel games that scale well with new screen resolutions (that's why I don't have any check and optimizations for big numbers and use simple brute force).

(define (fun1 l d)
    (if (apply = (map (lambda (x) (remainder x d)) l))
        (print d)))

(define (fun2 l)
    (do ((i 1 (+ i 1)))
        ((= i (apply min l)) i)
        (fun1 l i)))

(fun2 `(1080 720))

I'm learning lisp and scheme and want to know if there's any way to make this code more functional and lispy.

Also, I'm wondering if (apply = (1 2 3) is the right way to do it. I haven't found another way to force feed list of numbers to the = function or break numbers out of the list.


texts: Finding the sum closest to a target number

texts:
Wallace the Weightlifting Walrus is training for a contest where it will have to lift 1000 kg. Wallace has some weight plates lying around, possibly of different weights, and its goal is to add some of the plates to a bar so that it can train with a weight as close as possible to 1000 kg.

  In case there exist two such numbers which are equally close to 1000 (e.g. 998 and 1002), Wallace will pick the greater one (in this case 1002).

  Help Wallace the Weightlifting Walrus and tell it which weight it will have to lift.

  Input

  The first line of the input contains the number of plates n (1≤ n ≤ 1000). Each of the following n lines contains one positive integer less than or equal to 1000, denoting the weight of each plate.

  Output

  Output one integer, the combined weight closest to 1000.

  https://open.kattis.com/problems/walrusweights

e.g if n = [4, 900, 500, 498, 4], the output will be 1002

var input = [4, 900, 500, 498, 4];
function walrusWeight(input) {
  var target = 1000;
  var optimum = 0;
  var sums = [];
  sums.push(optimum);

  for(var i=0; i < input.length; i++) {
    var newSums = [];
    for(var j=0; j < sums.length; j++) {
      var newSum = sums[j] + input[i];
      if (newSum <= target) {
        newSums.push(newSum);
        if (newSum > optimum) {
          optimum = newSum;
        }
      } else if ((Math.abs(target-newSum) < Math.abs(target-optimum)) || (Math.abs(target-newSum) == Math.abs(target-optimum) && newSum > optimum)) {
    optimum = newSum;
    }
  }
  sums = sums.concat(newSums);
 }
 return optimum;
}

walrusWeight(input);


texts: Simulated arcade with a slot machine and number-guessing game

texts:
I am creating an arcade type thing in Python. Could someone suggest ways to simplify this code, or any other tips? All help is much appreciated.

I think the higherorlower function is particularly over-complicated.

import time
import random
tokens = 10000

def main():
    menu = int(input("What would you like to play?(Enter the corresponding number for each one)\n1. Slot Machine - 20 coins per turn\n2. Higher or Lower - 10 coins per turn\n"))
    if menu == 1:
        slotmachine(tokens)
    if menu == 2:
        higherorlower(tokens)

def tokencheck(cost):
    while True:
        if tokens >= cost:
            break
        else:
            print ("You do not have enough tokens")

def game_end():
    time.sleep(2)
    retry = input("Enter the corresponding letter for each one.\nM. Menu\nQ. Quit the arcade\n")
    if retry == "m" or retry == "M":
        main()
    if retry == "q" or retry == "Q":
        print("BYE BYE!")

def slotmachine(tokens):
    tokencheck(20)
    print ("You are playing slot machine!")
    print ("To win 1000 tokens you need to get 3 of the same number on each shake!")
    while True:
        tokencheck(20)
        shake = input("Press Enter to Shake!")
        tokens -= 10
        a,b,c = [random.randint(0,9),random.randint(0,9),random.randint(0,9)]
        print(a, b, c)
        if a != b or a != c:
            pass
        else:
            print ("You win 1000 tokens!")
            tokens = tokens + 1000
            print ("You now have", tokens, "tokens!")
            break
    game_end()

def higherorlower(tokens):
    goes = 0
    tokencheck(10)
    print ("You are playing higher or lower!")
    time.sleep(2)
    print ("You have to predict whether the next number (from 1 - 10) will be higher or lower than the current number.\nYou get 100 tokens for each round which you predict correctly.\nIf you predict incorrectly you will lose all of your earnings.")
    time.sleep(4)
    print("Cashout by inputting C.\n")
    time.sleep(1)
    num = random.randint(1,10)
    while True:
            tokens+=10
            time.sleep(1)
            print (num)
            choice = input("Higher or Lower (H/L)\n")
            if (choice == "C" or choice == "c") and goes >= 100:
                break
            if (choice == "C" or choice == "c") and goes < 100:
                "Cannot checkout!"
                pass
            else:
                pass
            num1 = random.randint(1,10)
            print (num1)
            time.sleep(1)
            if (num1 >= num and (choice == "H" or choice == "h")) or (num1 <= num and (choice == "L" or choice == "l")):
                print("You are correct and have earned 100 tokens!\n")
                tokens+=100
                num = num1
                goes+=100
                pass
            else:
                print("You are incorrect and have lost all of your earnings")
                tokens -= goes
                time.sleep(1)
                print ("You now have", tokens "tokens remaining.")
                break
    game_end()

print ("Welcome to the arcade!")
time.sleep(0.5)
print("You have", tokens, "tokens remaining.")
time.sleep(1)
main()


texts:
import java.util.ArrayList;

import java.util.Collections;

import java.util.HashSet;

public class LargestPalindrome{
    static ArrayList<String> palinList=new ArrayList<String>();

    public static void splitString(){
        String actualString="ABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOOD";
        for(int i=0 ; i<actualString.length() ; i++){
            for(int j=i ; j<actualString.length() ; j++){
                findPalindrome(actualString.substring(i,j));
            }
        }

    }
    public static void findPalindrome(String actualStr){
        String reversedStr="";
        //int palindromeCount=0;

        for(int i=actualStr.length()-1 ; i>=0 ; i--){
            reversedStr+=actualStr.charAt(i);
        }

        if(actualStr.equals(reversedStr)&&actualStr.length()>=3){
            //System.out.println(actualStr);
            palinList.add(actualStr);
        }
    }

    public static String largestPalindromeCheck(ArrayList<String> palList){
        int maxLength=palList.get(0).length();
        int index=0;
        for(int i=1 ; i<palList.size() ; i++){
            if(palList.get(i).length()>maxLength){
                maxLength=palList.get(i).length();
                index=i;
            }
        }
            return palList.get(index);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        splitString();
        //System.out.println(palinList);
        System.out.println(largestPalindromeCheck(palinList));
    }
}

Please review the code and provide feedback on best practices and code optimization.


texts:
I am a newbie to native JavaScript and am pretty much coming to grips with the operators, etc. At the moment I am currently constructing a slide.

"use strict";

 var intSeconds = 3;

 function loadSlider(){

flickrImgsShown = 0;
sliderImages = new Array(slides + 10);
sliderImages[0] = document.querySelector(".img");

    for (var i = 1; 1 < sliderImg; i++ ) {
        sliderImages[i] = document.querySelector(".img" + (i + 1));
        document.querySelector(".identifer" + i);
    }

    function next() {

        flickrImgsShown++;
        if(flickrImgsShown == slides)
            flickrImgsShown = 0;
        transition();

        clearInterval(slideTimer);
        slideTimer = setInterval(timer, interSeconds * 1000);
    }

    function prev () {

        flickrImgsShown--;
        if(flickrImgsShown == -1)
            flickrImgsShown = slides -1;
        transition();

        clearInterval(slideTimer);
        slideTimer = setInterval(timer, interSeconds * 1000);
    }

    slideTimer = setInterval(timer, intSeconds * 1000);

    function timer() {

        flickrImgsShown--;
        if(flickrImgsShown == -1)
            flickrImgsShown = slides -1;
        transition();
    }

}

I am not a fan of the getelementbyidand style.visibility in my code. Is there a better method I can apply to call out an ID or change a style in the DOM?


texts: Determining if variables (integers) are greater or less than 0

texts:
Hobbyist here. I think my case/when logic needs to be cleaned up a bit. I'd also appreciate critique on the other parts...but I'm more interested in cleaning up the case/when statements...

puts "please assign an integer to x:"
x = gets.chomp.to_i

if (x > 0)
  value_of_x = true
else
  value_of_x = false
end

puts "now please assign an integer to y:"
y = gets.chomp.to_i

if (y > 0)
  value_of_y = true
else
  value_of_y = false
end

case
when (value_of_x == true) && (value_of_y == true)
  puts "two variables are > 0"
when ((value_of_x == true) && (value_of_y == false)) || ((value_of_x == false) && (value_of_y == true))
  puts "at least one variable is > 0"
else
  puts "no variables are > 0"
end


texts: Dynamically loading jQuery when it's not available or version isn't high enough

texts:
I'm writing a script for others to use on their websites. I'd like to use jQuery in this script. Because I don't have control over what frameworks people use on their sites, I need to make sure jQuery is available and that it's version 1.8 or higher. Here's my take on it. Does anyone see anything I could/should be doing differently? Is there a better way of doing this?

//start anon function for whole script
;(function(){
    var $,
        hasOwn = ({}).hasOwnProperty,
        //get ie version returns false if ie>=11 or not ie
        ieVersion = function(){
            var v = 3,
                div = document.createElement('div'),
                all = div.getElementsByTagName('i');
            while(div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->', all[0]);
            return (v > 4 ? v : ('documentMode' in document ? document.documentMode : false));
        }(),
        //get which version of jQuery is currently added to the site
        jqVersion = function(){
            return 'jQuery' in window && !!window.jQuery ? parseFloat(window.jQuery.fn.jquery) : false;
        },
        //set the correct jquery version to use based on which version of ie is in use. Use an array in the case of one or more being down
        jqSrc = (!!ieVersion && ieVersion > 4 && ieVersion < 9) ? ['//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js', '//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min.js'] : ['//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js', '//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.min.js'],
        //check jquery version and if it is above 1.8 use it, if not then get own version
        jqCheck = function(first){
            var version = jqVersion();
            if(!version || version < 1.8){
                getScript(jqSrc.shift(), jqCheck);
            }else{
                if(!!first){
                    $ = window.jQuery;
                }else{
                    $ = window.jQuery.noConflict(true);
                }
                load();
            }
        },
        //function to loop and load jquery script
        getScript = function(url, callback){
            var script = document.createElement('script'),
                tag = document.getElementsByTagName('script')[0],
                done = false;
            script.type = 'text/javascript';
            script.async = !0;
            script.src = url;

            script.onload = script.onreadystatechange = script.onerror = function(){
                if(!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')){
                    done = true;
                    if(typeof(callback) === 'function'){
                        callback.call(this);
                    }
                    script.onload = script.onreadystatechange = script.onerror = null;
                }
            };

            tag.parentNode.insertBefore(script, tag);
        },
        load = function(){
            //Start script
            window.myGlobalFunction = new function(){
                var privateVar = 'private',
                    privateFunc = function(){
                        return true;
                    };

                this.publicVar = 'public';

                this.publicFunc = function(){
                    return true;
                };
            };
        };

    //make sure json is avaiable, if not add it
    if(!hasOwn.call(window, 'JSON') || !hasOwn.call(JSON, 'parse') || (typeof(JSON.parse) !== 'function')){
        getScript('//cdnjs.cloudflare.com/ajax/libs/json3/3.3.1/json3.min.js', function(){
            //all functions are built start by checking for jQuery and it's builder
            jqCheck(true);
        });
    }else{
        //all functions are built start by checking for jQuery and it's builder
        jqCheck(true);
    }
})();


texts: Reverse Dictionary: Group from child array elements and get its minimum key

texts:
Objective

I have following array and would like to group by each child and get its smallest Id:-

var list = new[]
{
    new { Id = 1, Childs = new [] { 'a', 'b' } },
    new { Id = 2, Childs = new [] { 'a' } },
    new { Id = 3, Childs = new [] { 'a', 'c' } },
    new { Id = 4, Childs = new [] { 'b' } },
    new { Id = 5, Childs = new [] { 'b' } },
    new { Id = 6, Childs = new [] { 'b', 'c' } },
};

Attempt

var groups = list
                .SelectMany(item => item.Childs)
                .Distinct() // for each unique child
                .ToDictionary(
                    child => child, // with each child as key
                    child => list.Where(item =>
                                item.Childs.Any(c =>
                                    c == child)) // get items with corresponding child
                                .Min(item => item.Id)); // extract min Id

foreach (var g in groups)
{
    Console.WriteLine($"{ g.Key }: { g.Value }");
}

// Prints
// a: 1
// b: 1
// c: 3

Rationale

a contains in Id 1, 2 and 3 and the smallest is 1.

Improvement

I'm trying to solve it with LINQ and thinking GroupBy would be the go-to solution but I'm stuck with splitting each child element as the key.

I would really appreciate if someone have any idea to solve it in a more elegant way!


texts: Shader for 1-bit color palette + a VFX ramp

texts:
I'm making a Unity game with a "1-bit" color palette, a la Downwell - the vast majority of the screen will end up being in black and white, but unlike true 1-bit graphics, some highlights and visual effects will use additional colors. In my case, those effects will output values along a range of colors making up a single color ramp - all the colors between green and pink inclusive, by default. It's also a low resolution, large-pixel game, and uses the pixel perfect camera package to enforce that.
I want to be able to switch out the exact black, white, and color ramp values that are used at runtime, the same way that Downwell does through the ability to unlock additional palettes. That seems like a good job for shaders, so I finally buckled down and wrote some shader code for this. Now I want to check for room for improvement in terms of potential performance bottlenecks or general shader style.
This component is attached to the main camera:
using UnityEngine;

public class ColorPaletteApplier : MonoBehaviour
{
    public Material Material;

    void OnRenderImage (RenderTexture source, RenderTexture destination)
    {
        Graphics.Blit(source, destination, Material);
    }
}

And this is the shader that I wrote:
Shader "Color Palette"
{
    Properties
    {
        [PerRendererData] _MainTex ("Texture", 2D) = "white" {}
        _BlackColor ("Black Color", Color) = (0, 0, 0, 1)
        _WhiteColor ("White Color", Color) = (1, 1, 1, 1)
        _RampTex ("Ramp LUT", 2D) = "defaulttexture" {}
    }

    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex, _RampTex;
            float4 _BlackColor, _WhiteColor;

            inline fixed4 convertBlackAndWhite (fixed4 input)
            {
                bool closerToWhite = round(input.r);
                return closerToWhite ? _WhiteColor : _BlackColor;
            }

            // input is assumed to be somewhere on a lerp between (0, 1, 0) and (1, 1, 0)
            // these colors are chosen so that one channel goes from 0 to 1, the other two channels are always the same value, and all three channels are never equal
            inline fixed4 convertEffectRamp (fixed4 input)
            {
                float i = input.r;

                // for effect pixels that break the g or b assumptions, we can assume they occupy subpixel positions and that the pixel perfect camera averaged their true value with the background pixel. we'll fix that by making the effects override the background color
                if (input.g == 0.5)
                {
                    // undo average with black
                    i *= 2;
                }
                else if (input.b == 0.5)
                {
                    // undo average with white
                    i = i * 2 - 1;
                }

                return tex2D(_RampTex, i);
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                return (col.r == col.g && col.g == col.b) ? convertBlackAndWhite(col) : convertEffectRamp(col);
            }
            ENDCG
        }
    }
}

I'm using a 128x1 PNG for the ramp lookup texture.


texts: How to rewrite recursion in a more ruby way

texts:
def get_all_friends(uid, client)
  friends = client.friendships.friends(uid: uid)
  total = friends.total_number
  get_friends(total, 0, uid, client)
end

def get_friends(total, cursor, uid, client)
  left = total
  count = [200, left].min

  friends = client.friendships.friends(uid: uid, count: count, cursor: cursor)
  left -= count
  next_cursor = friends.next_cursor

  return friends if (left == 0 || next_cursor == 0)

  more_firends = get_friends(left, next_cursor, uid, client)
  more_firends.users << friends.users
  return more_firends
end

get_all_friends(uid, observer.client).users.map do |info|
  user = User.find_or_create_by_uid_and_name(uid: info.id, name: info.name)
  follow(user)
  user
end

This code is written in a functional style. Maybe there is a more natural way to structure it with Block.

And how can I reuse the code when client.friendships.friends(uid: uid, count: count, cursor: cursor) differs?

Update:

I reconstruct the code. It now looks more clean and general.

def get_all_friends(client, uid)
  fetch_all do |count, cursor|
    client.friendships.friends(uid: uid, count: count, cursor: cursor)
  end
end

def fetch_all(&fetch_proc)
  res = fetch_proc.call(10, 0)
  total = res.total_number
  return res if total <= 10
  fetch(total, 0, &fetch_proc)
end

def fetch(total, cursor, &fetch_proc)
  left = total
  count = [200, left].min

  res = fetch_proc.call(count, cursor)
  left -= count
  next_cursor = res.next_cursor

  if (left == 0 || next_cursor == 0)
    return res
  end

  more_res = fetch(left, next_cursor, &fetch_proc)
  more_res.users << res.users
  more_res
end


texts: Project Euler problem 1 in Python - Multiples of 3 and 5

texts:
I'd like suggestions for optimizing this brute force solution to problem 1.  The algorithm currently checks every integer between 3 and 1000.  I'd like to cut as many unnecessary calls to isMultiple as possible:

'''
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.
'''

end = 1000

def Solution01():
    '''
        Solved by brute force
        #OPTIMIZE
    '''
    sum = 0
    for i in range(3, end):
        if isMultiple(i):
            sum += i
    print(sum)

def isMultiple(i):
    return (i % 3 == 0) or (i % 5 == 0)


texts: Mutualising multi-threaded calls to EJB from Servlet

texts:
I have a Servlet that makes an EJB call to a backing server which takes about a second to return some data that changes reasonably regularly.

I can't cache the data on the servlet-side, so I have decided to put the call to the EJB into a separate thread and use a Future to get the data as late as possible. There is no reason why an invocation of a servlet concurrent to an existing invocation can't use the data returned from the first request to the EJB.  For instance, if there is already a thread waiting for the data from the EJB, don't make another request; use the data from the first request.

public MyServlet extends HttpServlet {

  //this lock protects all access to currentRosterRequest
  private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();

  private RosterEJB rosterEJB=...;

  //the executor service that will process the roster request
  private static final ExecutorService ROSTER_FETCH_EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
      return new Thread(r, "roster-fetch");
    }
  });

  //the roster request task - this never changes, it never needs parameters
  private static final Callable<ArrayList<String>> ROSTER_FETCH_TASK = new Callable<ArrayList<String>>() {

      @Override
      public ArrayList<String> call() throws Exception {
          try {
              return rosterEJB.getRoster();
          } finally {
              //one way or another the roster request has terminated
              LOCK.writeLock().lock();
              try {
                  //clear out the static variable
                  MyServlet.currentRosterRequest = null;
              } finally {
                  LOCK.writeLock().unlock();
              }
          }
      }
  };

  //the currently active request
  private static Future<ArrayList<String>> currentRosterRequest = null;

  public void doGet(...) {

    //obtain or create the current roster request
    final Future<ArrayList<String>> localRosterRequest = getLocalRosterRequest();

    //do other things

    //wait up to two seconds for data from the roster request
    final Boolean hasAccess = localRosterRequest.get(2, TimeUnit.SECONDS).contains(user.toLowerCase());

    //etc
  }

  private Future<ArrayList<String>> getLocalRosterRequest() {
    Future<ArrayList<String>> localRosterRequest;
    LOCK.readLock().lock();
    try {
        localRosterRequest = currentRosterRequest; //get a reference to the current request, if there is one
    } finally {
        LOCK.readLock().unlock();
    }
    if (localRosterRequest == null) { //if there wasn't a current request
        LOCK.writeLock().lock();
        try {
            if (currentRosterRequest == null) { //if there still isn't a current request, create a new one
                currentRosterRequest = ROSTER_FETCH_EXECUTOR_SERVICE.submit(ROSTER_FETCH_TASK);
            }
            localRosterRequest = currentRosterRequest; //get a reference to the current request
        } finally {
            LOCK.writeLock().unlock();
        }
    }
    return localRosterRequest; //return the reference to the current request
  }
}

(I have left the majority of the servlet out - the main thing I want reviewing is the method getLocalRosterRequest().)

My aims:

If there is a request already underway, don't create a new request, use the existing one.
If a new GET comes in when there is no request underway, create a new request, and make it available to subsequent callers.
Avoid deadlocks!

My questions:

Is this threadsafe? I can't see a way that threads could block.
Does it put the servlet container at risk? I'm using Tomcat 6
Is there a better way?


texts: Changes all floats in a pandas DataFrame to string

texts:
Below I created a function to format all the floats in a pandas DataFrame to a specific precision (6 d.p) and convert to string for output to a GUI (hence why I didn't just change the pandas display options). Is this the most efficient way to convert all floats in a pandas DataFrame to strings of a specified format?

import pandas as pd

df = pd.DataFrame({'x':[5.4525242,6.5254245,7.254542],'y':[5.4525242,6.5254245,7.254542]})

def _format_floats(df):

    df.loc[:,df.dtypes==float]=df.loc[:,df.dtypes==float].apply(lambda row: ["{:.6f}".format(num) for num in row])

_format_floats(df)

#Example output numbers changes to string with 6 decimals
df.iloc[0,0]
#'5.452524'


texts: Thread pausing/resuming/canceling with Qt

texts:
I have written this code to be able to suspend (or to cancel) a worker executed in a separate thread in Qt.

To do it, I have used an instance QWaitCondition and QMutex.

#ifndef MYWORKER_H
#define MYWORKER_H

#include <QObject>
#include <QMutex>
#include <QWaitCondition>

class MyWorker : public QObject
{
    Q_OBJECT
public:
    explicit MyWorker(QObject *parent = 0);
    ~MyWorker();
    void restart();
    void pause();

signals:
    void finished();

public slots:
    void doWork();
    void cancelWork();

private:
    QMutex m_continue;
    QWaitCondition m_pauseManager;
    bool m_cancelRequested;
    bool m_pauseRequired;
};

#endif // MYWORKER_H

Here is the code of myworker.cpp

#include "myworker.h"

#include <QDebug>

MyWorker::MyWorker(QObject *parent) :
    QObject(parent),
    m_cancelRequested(false),
    m_pauseRequired(false)
{
}

MyWorker::~MyWorker()
{
}

void MyWorker::restart()
{
    this -> m_pauseRequired = false;
    this -> m_pauseManager.wakeAll();

}

void MyWorker::pause()
{
    this -> m_pauseRequired = true;
}

void MyWorker::doWork()
{
    // Write your code here
    for(int i = 0; i < 4000000000; i++)
    {
        if (i % 100000 == 0) {
            qDebug() << i;
        }

        if (m_pauseRequired) {
            m_pauseManager.wait(&m_continue);
        }

        if (this -> m_cancelRequested()) {
            break;
        }
    }

    // Write your code above"

    emit finished();
}

void MyWorker::cancelWork()
{
    this -> restart();
    this -> m_cancelRequested = true;
}

Here is the snippet to use this code :

this -> m_thread = new QThread();
this -> m_worker = new MyWorker();
this -> m_worker-> moveToThread(this -> m_thread);
connect(m_thread, SIGNAL(started()), m_worker, SLOT(doWork()));
connect(m_worker, SIGNAL(finished()), m_thread, SLOT(quit()));

this -> m_thread -> start();

// To suspend the work
this -> m_worker -> pause();

// To stop the work
this -> m_worker -> cancelWork();

Do you have any advice on improving this code, or do you have a better solution?


texts: Image Scrolling in UITableView with Parse

texts:
I'm trying to create an app that is scalable. One of the main features of the app is to view images from a database to a UITableView. Here is my code:

import UIKit

class HomePageTableViewController : UITableViewController {

private var imageObjects: [ImageParseObject] = []
private var skipNumObjects = 0
private var notificationKey = "bananasaregood"

override func viewDidLoad() {
  super.viewDidLoad()
  tableView.rowHeight = UITableViewAutomaticDimension
  tableView.estimatedRowHeight = 320
  loadMoreImages()
  NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshData", name: notificationKey, object: nil)
}

func loadMoreImages() {
  let query = PFQuery(className: "ImagePost")
  query.limit = 25
  query.skip = skipNumObjects
  query.findObjectsInBackgroundWithBlock({
    objects, error in
    if error != nil {
      print(error)
    } else {
      self.imageObjects += self.convertPFObjectsToImageParseObjects(objects!)
    }
  })
  skipNumObjects += 25
}

 func refreshData() {
    tableView.reloadData()
 }

 func convertPFObjectsToImageParseObjects(pfObjects: [PFObject]) -> [ImageParseObject] {
   var imgObjects: [ImageParseObject] = []
   for i in 0..<pfObjects.count {
     let object = pfObjects[i]
     imgObjects.append(ImageParseObject(imageObject: object, index: i))
  }
  return imgObjects
  }

 }

 extension HomePageTableViewController {

 override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
   return 1
 }

 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return imageObjects.count
  }

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! HomePageTableViewCell
   let imageParseObject = imageObjects[indexPath.row]
   cell.imagePost.image = UIImage(named: "default")
   cell.imagePost.file = imageParseObject.image
   cell.imagePost.loadInBackground()
   cell.userImage.image = UIImage(named: "default")
   cell.userImage.file = imageParseObject.userImage
   cell.userImage.loadInBackground()
   cell.timeAgo.text = imageParseObject.timeAgo!
   return cell
 }
}

extension HomePageTableViewController {

override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
  if tableView.contentOffset.y >= tableView.contentSize.height - tableView.frame.height {
    print("Reached the end")
    loadMoreImages()
   }
 }
 }

Ideally, I would like this app to have the versatility to scale to thousands of users. So if I have thousands of images in the database it will still run smoothly. I'm not sure if I've accomplish that, that's why I'm asking for review. Do you think this code would fail in large scale?

Basically what I'm doing is I'm storing the objects, ImageParseObject, in an array, (Storing objects aren't as expensive as storing the images) the objects contain references to the actual image files in the database. When I load my tableview I simply reference the file and load them in the background. When I scroll to the end, I loadMoreImages(). The NSNotificationCenter is a start signal, I reload my tableview only after the first ImageParseObject is ready.


texts: Inheritance or DI in Presenter classes in MVP

texts:
In MVP pattern we can use DI when our presenter classes need services as follows:

class APresenter
{
    Public Presenter(DataService dataService, PermissionService permissionService)
    {
        //
    }

    // can use services injected through parameter...
}

As my all most all the presenter classed need these services, I can use inheritance instead, as follows:

class BasePresenter()
{
    DataService DataService = new DataService();
    PermissionService PermissionService = new PermissionService();
}

class APresenter :BasePresenter
{
    public APresenter()
    {
        //
    }

    // can use services inherited...
}

NOTE: Here I've not shown the Models and Views injected through the constructor of presenter classes

Is there a difference in these methods when it comes to dependency?
What would be the most suitable option out of these two to be implemented in some what small size project which is having about 20 presenter classes?


texts:
I will start by saying I have gotten this to work, and the question is about how improve the script to make it better/faster.
I need to compare a series of files to each other. Let's say I have the below files:
filename0   filename1   filename2

What I have done is:
Z=0 # Beginning number
Y=2 # Final number

X=$Z # Initial file number
((W=Y+1)) # Number for ranges

while [[ $Z -lt $W ]]
do
    while [[ $X -lt $W ]]
    do
        obabel filename$Z.xyz -oconfabreport -xf filename$X.xyz -xr 0.2 > Results.$Z.$X
    ((X=X+1))
    done
    ((Z=Z+1))
    ((X=Z))
done

It compares files like this:
filename0 filename0
filename0 filename1
filename0 filename2
filename1 filename1
filename1 filename2
filename2 filename2

I am using openbabel's confabreport tool to find RMSD of structures. Is there a better way of doing this in bash scripting? Such as skipping a self comparison or ones that have already been compared? Or just a faster way of achieving the same thing? Please let me know if I need to provide any additional information, or if this question would be better somewhere else.


texts:
I have made a simple program that, given a string and how many times to repeat it, it waits a second and types that string N times, followed by an enter key. It is made for applications like skype. The waiting is so that you can get from the console to the application on time.

Dim i
Set s = WScript.CreateObject("WScript.Shell")
i = WScript.Arguments(0)
t = CInt(WScript.Arguments(1))
WScript.Sleep 1000
For c = 1 to t
    s.SendKeys CStr(CInt(100 * (c-1) / (t-1))) + "{%}: " + i + "{ENTER}"
Next

How can this be improved? I hope there is a dynamic way to change to a certain application, as that would make the could more readable and better.


texts: Function for accessing and searching dictionaries using /slashed/paths (like xpath)

texts:
So I have some data being returned to me in the form of a deeply nested Dict and I need to parse multiple values from it which may or may not be there. I saw this library (https://github.com/akesterson/dpath-python) and tried to come up with a simplified version that fits into one function.
I think its pretty good but I'm wondering if I missed something or there's some small way to improve it?
from typing import Dict, Union
import re
import copy

def dict_query(d: Dict, path: str) -> Union[object, None]:
    """
    # Example usage:
    >>> d = {'a': [{}, {'b': 9}]}
    >>> print( dict_query(d, 'a/[1]/b') )
    9
    """
    keys = path.split("/")
    val = copy.deepcopy(d)
    for key in keys:

        idx = re.search("\[(\d+)\]", key)
        if idx:
            # handle list index
            if isinstance(val, (list, tuple)):
                idx = int(idx.group(1))
                val = val[idx]
            else:
                return None
        elif isinstance(val, dict):
            # handle dict key
            val = val.get(key)
        else:
            return None
    return val

# tests of searching nested dicts
d = {'a': {'b': 1}}
print( dict_query(d, 'a/b') ) # 1
print( dict_query(d, 'a/c') ) # None
print( dict_query(d, 'a/') ) # None
print( dict_query(d, 'c/b') ) # None
# tests of searching nested dicts + lists
d = {'a': [{}, {'b': 1}]}
print( dict_query(d, 'a/[0]') ) # {}
print( dict_query(d, 'a/[1]') ) # {'b': 1}
print( dict_query(d, 'a/[1]/b') ) # 1
print( dict_query(d, 'a/[1]/c') ) # None
print( dict_query(d, 'a/[0]/a') ) # None
print( dict_query(d, '[1]/b') ) # None


texts:
I am learning how to code in Python by myself and have never coded before, I just want to know if there is any way I can upgrade my PasswordGenerator.

#!/usr/bin/env python3
import random

def passwordgenerator():
    mypw = ""
    count = 0
    alphabet_number =    "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    symbols = "!?@%#$"
    running1 = True
    while running1:

        if len(symbols) == 1:

            #  Reset symbols
            symbols = "!?@%#$"

        if len(alphabet_number) == 1:

            #  Reset letters/numbers
            alphabet_number = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

        elif count == pw_length:

            if mypw.isupper() or mypw.islower():  # check if there is only upper     or only lower letter and rerun if True
                passwordgenerator()

            else:
                x = mypw
                y = list(x)  # creates a list and put the pw in to shuffle it
                random.shuffle(y)
                mypw = "".join(y)

                print(mypw)
                input("\nPress <Enter> to close the program")
                running1 = False

        elif count % 4 == 0:

            #  pick a random symbol every 3 loop and add it to the pw
            symbols_index = random.randrange(len(symbols))
            new_symbols = symbols[symbols_index]
            mypw = mypw + new_symbols

            # delete the symbols that is picked so there are no duplicate
            symbols_list_change = symbols.replace(new_symbols, "")
            symbols = symbols_list_change

        else:

            # pick a random number or letter and add it to the pw
            next_index = random.randrange(len(alphabet_number))
            new_alphabetnumber = alphabet_number[next_index]
            mypw = mypw + new_alphabetnumber

            # delete the symbols that is picked so there are no duplicate
            an_list_change = alphabet_number.replace(new_alphabetnumber, "")
            alphabet_number = an_list_change

        count += 1

if __name__ == '__main__':
    print("/!\ 12 Characters is a minimum for good security /!\ ")

    print("=" * 55)  # just to make it pretty

    running = True
    while running:
        pw_length = input("How many Characters do you want?\n")

        if pw_length.isdigit():  # verify if user input a number
            pw_length = int(pw_length)
            passwordgenerator()
            running = False
        else:
            print("A number is needed")


texts:
Akka-http supports WS connections like that:

def route =
    path("register") {
      parameter('name) { name ⇒
        handleWebSocketMessages(pubSub.openNewConnection(UserId(id))))
      }
    }

But implementation of WS requires some machinery:

we should store all connected clients
we should be able send messages to these clients
in case of disconnect we should update this map.

So I suggest the following code for it. But I'm new to akka-http, if you have any ideas how to improve this code, you're welcome!

import akka.NotUsed
import akka.actor.{ActorRef, ActorSystem, Status}
import akka.stream.Materializer
import akka.stream.scaladsl.{Flow, Source}
import cats.Monad
import com.hello.UserId
import com.hello.Logging
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.stream.OverflowStrategy
import akka.stream.scaladsl._
import org.reactivestreams.Publisher
import akka.stream.scaladsl.Sink

import scala.concurrent.Future

class PubSub()(implicit system: ActorSystem, mat: Materializer) extends Logging {
  implicit val ec = system.dispatcher

  private var wsConnections: Map[UserId, ActorRef] = Map.empty[UserId, ActorRef]

  def getConnections = wsConnections.size

  def openNewConnection(id: UserId): Flow[Message, Message, NotUsed] = {
    closeConnection(id)

    val (actorRef: ActorRef, publisher: Publisher[TextMessage.Strict]) =
      Source.actorRef[WsMsg.Out](16, OverflowStrategy.fail)
        .map(msg => TextMessage.Strict(Codec.encodeWsMsg(msg)))
        .toMat(Sink.asPublisher(false))(Keep.both).run()

    val sink: Sink[Message, Unit] = Flow[Message]
      .watchTermination()((_, ft) => ft.foreach { _ => closeConnection(id) })
      .mapConcat {
        case TextMessage.Strict(msg) =>
          Codec.decodeWsMsg(msg).fold(err => {
            log.info(s"Unknown message $msg. Parsing error: $err")
            Nil
          }, msg => List(msg))
        case _                       =>
          Nil
      }
      .mapAsync(4) {
        case WsMsg.In.Ping(n) =>
          actorRef ! WsMsg.Out.Pong(n)
          Future.successful("Pong!")
        case msg              =>
          //TODO send to dispatcher
          Future.successful {
            log.info(s"Dispatching $msg")
          }
      }
      .to(Sink.ignore)

    log.info(s"Opening WS connection for $id")
    wsConnections += id -> actorRef
    Flow.fromSinkAndSource(sink, Source.fromPublisher(publisher))
  }

  def sendToPlayer(id: UserId, msg: WsMsg.Out) = wsConnections.get(id).foreach(ar => ar ! TextMessage(msg.toString))

  def closeConnection(id: UserId) = {
    wsConnections.get(id).foreach { ar =>
      log.info(s"Closing WS connection for $id")
      ar ! Status.Success("Done")
    }
    wsConnections -= id
  }
}

And simple codecs using json circe without any implicits:

import io.circe._
import io.circe.generic.auto._
import io.circe.parser._
import io.circe.syntax._
import WsMsg._

object Codec {

  def decodeWsMsg(json: String): Either[Error, In] = {
    decode[WsMsg.In](json)
  }

  def encodeWsMsg(msg: WsMsg.Out): String = {
    msg.asJson.noSpaces
  }
}

I'm using akka 2.5.11 and akka-http 10.1.0.


texts:
A recent assignment asks me to create a program that checks for parentheses balance in a given string. As I can't find any duplicate questions that have code written in C, I decided to post another one.

I tried to make a stack that stores currently opened / unclosed parentheses and checks with each character in array, if it is unbalanced the program flags and depending on the flag boolean prints different value.

Is this the best way? Are there any situations where this program will print incorrect outputs? How can I make it take less time if the input is extremely long?

This is the code:

#include<stdio.h>
int main(){
    int pilepointer=-1,flag=0,i;
    char line[10001],pile[10001];
    gets(line);
    for(i=0;line[i]!=NULL;i++){
        switch(line[i]){
        case '(':
            pilepointer=pilepointer+1;
            pile[pilepointer]='(';
            break;
        case '[':
            pilepointer=pilepointer+1;
            pile[pilepointer]='[';
            break;
        case '{':
            pilepointer=pilepointer+1;
            pile[pilepointer]='{';
            break;
        case ')':
            if(pile[pilepointer]=='('){
                pile[pilepointer]==NULL;
                pilepointer=pilepointer-1;
                break;
            }
            else{
                flag=1;
                break;
            }
        case ']':
            if(pile[pilepointer]=='['){
                pile[pilepointer]==NULL;
                pilepointer=pilepointer-1;
                break;
            }
            else{
                flag=1;
                break;
            }
        case '}':
            if(pile[pilepointer]=='{'){
                pile[pilepointer]==NULL;
                pilepointer=pilepointer-1;
                break;
            }
            else{
                flag=1;
                break;
            }
        }
    }
    if(flag==1){
        printf("No\n");
    }
    else{
        printf("Yes\n");
    }
    return 0;
}


texts:
Following along another code review (Printing out JSON data from Twitter as a CSV) I would like to submit a slightly adapted code for review.

This code imports JSON data obtained from Twitter and prints out just the tweet author and if there are any users the author mentions in the tweet.  User_mentions is a field that is provided in the JSON output.  The difficult part I've encountered is that an author sometimes doesn't mention anyone, or mentions 5 other user.  So I'm not sure of the best way to account for this, besides what I've cobbled together below.

My ultimate goal:
Create an edgelist from this data to then put into a network visualization tool. I've been converting the output (example below) from this code using a UNIX command (also below) I wrote, but if anyone has a better way to do this within this code, please do let me know.

Format after code:

author1,mention1,mention2,mention3
author1,mention4
author2 author3,mention5
author4,mention3,mention6

Ultimate format in CSV:

author1,mention1
author1,mention2
author1,mention3
author1,mention4
author3,mention5
author4,mention3
author4,mention6

Python Code:

import json
import sys

tweets=[]

# import tweets from JSON
for line in open(sys.argv[1]):
try:
    tweets.append(json.loads(line))
except:
pass

# create a new variable for a single tweets
tweet=tweets[0]

# pull out various data from the tweets
tweet_author = [tweet['user']['screen_name'] for tweet in tweets]
tweet_mention1 = [(tweet['entities']['user_mentions'][0]['screen_name'] if len(tweet['entities']['user_mentions']) >= 1 else None) for tweet in tweets]
tweet_mention2 = [(tweet['entities']['user_mentions'][1]['screen_name'] if len(tweet['entities']['user_mentions']) >= 2 else None) for tweet in tweets]
tweet_mention3 = [(tweet['entities']['user_mentions'][2]['screen_name'] if len(tweet['entities']['user_mentions']) >= 3 else None) for tweet in tweets]
tweet_mention4 = [(tweet['entities']['user_mentions'][3]['screen_name'] if len(tweet['entities']['user_mentions']) >= 4 else None) for tweet in tweets]
tweet_mention5 = [(tweet['entities']['user_mentions'][4]['screen_name'] if len(tweet['entities']['user_mentions']) >= 5 else None) for tweet in tweets]
tweet_mention6 = [(tweet['entities']['user_mentions'][5]['screen_name'] if len(tweet['entities']['user_mentions']) >= 6 else None) for tweet in tweets]
tweet_mention7 = [(tweet['entities']['user_mentions'][6]['screen_name'] if len(tweet['entities']['user_mentions']) >= 7 else None) for tweet in tweets]
tweet_mention8 = [(tweet['entities']['user_mentions'][7]['screen_name'] if len(tweet['entities']['user_mentions']) >= 8 else None) for tweet in tweets]
tweet_mention9 = [(tweet['entities']['user_mentions'][8]['screen_name'] if len(tweet['entities']['user_mentions']) >= 9 else None) for tweet in tweets]
tweet_mention10 = [(tweet['entities']['user_mentions'][9]['screen_name'] if len(tweet['entities']['user_mentions']) >= 10 else None) for tweet in tweets]

#outputting to CSV
out = open(sys.argv[2], 'w')

rows = zip(tweet_author, tweet_mention1, tweet_mention2, tweet_mention3,    tweet_mention4, tweet_mention5, tweet_mention6)

from csv import writer
csv = writer(out)

for row in rows:
    values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
    csv.writerow(values)

out.close()

UNIX command:
Used to take the output of this code and format as an edgelist. If this part can be worked into the above code, it would be much appreciated!

cat [file.txt] | sed 's/,/ /g' | awk '{print $1, $2 "##" $1, $3 "##" $1, $4 "##" $1, $5 "##" $1, $6 "##" $1, $7 "##" $1, $8 "##" $1, $9 "##" $1 $10}' | sed 's/##/\n/g' | sed 's/ /,/g'


texts:
If the user clicks a button, I need to run the following actions:

Show and hide div
Add and remove attributes
Add and remove CSS class

We archive the same but I'm not sure this is the correct approach or not. Can anyone help improve this?

HTML

<button id="mybutton" ng-click="showAlert()">Click me</button>

Value: {{myvalue}}

Change Mode

        link text

Text Contents

JS

function MyCtrl($scope) {

    $scope.myvalue = false;//Show and hide DIV
    $scope.atribut=false; // Set Attribute value
    $scope.isActive=false; // Add and Remove CSS Class
    $scope.showAlert = function(){
      $scope.myvalue =!$scope.myvalue;
      $scope.atribut=!$scope.atribut;
      $scope.isActive=!$scope.isActive;
    };

CSS

.red{color:red;}
.blue{color:blue;}

Demo


texts:
Please be brutal, and judge my code as if it was written at a top 3 tech company, straight out of college. (The method signature, and input parameter is given by the problem, so don't worry about that)

Worst case complexity: \$ O \left( n^2 \right) \$

Space complexity: \$ O \left( n \right) \$

Time it took me to solve this:
6 minutes (I got it right the first shot, and passed all the test cases)

Problem:

  Given a string S, find the longest palindromic substring in S. You may
  assume that the maximum length of S is 1000, and there exists one
  unique longest palindromic substring.

  public String longestPalindrome(String s) {
        String longestPalindrome = "";
        for(int i = 0; i < s.length(); i++){
            for(int j = s.length()-1; j >= 0 && j != i; j--){
                if(isPalindrome(s.substring(i,j+1))){
                    if(s.substring(i, j+1).length()>longestPalindrome.length()){
                        longestPalindrome = s.substring(i, j+1);
                        return longestPalindrome;
                    }
                }
            }
        }
        return longestPalindrome;
    }
    public boolean isPalindrome(String s){
        int end = s.length()-1;
        for(int i=0; i<s.length()/2; i++){
            if(s.charAt(i)!=s.charAt(end)){
                return false;
            }
            end--;
        }
        return true;
    }


texts:
My Model

public class AccountListFilterModel
{
    public int page { get; set; }
    public int pagesize { get; set; }
    public string sortOrder { get; set; }
    public string packageTypeFilter { get; set; }
    public string usernameFilter { get; set; }
    public string accountStatusFilter { get; set; }
    public string nameSurnameFilter { get; set; }
    public DateTime startDate { get; set; }
    public DateTime endDate { get; set; }
    public string dateFilter { get; set; }
    public int screenCountFilter { get; set; }

}

My Controller

 public ViewResult Index(AccountListFilterModel accountListFilter){}

My View

@{
var currentPageNumber = Request["page"];
var currentPageSize = Request["pagesize"];
var currentSortOrder = Request["sortOrder"];
var currentUsernameFilter = Request["usernameFilter"];
var currentAccountStatusFilter = Request["accountStatusFilter"];
var currentPackageTypeFilter = Request["packageTypeFilter"];
var currentnameSurnameFilter = Request["nameSurnameFilter"];
var currentDateFilter = Request["dateFilter"];
var currentScreenCountFilter = Request["screenCountFilter"];
var currentScreenCountSortFilter = Request["screenCountSortFilter"];}

and

                Account Name

How can I shorten my code at View ?


texts:
I am not sure if I should be using recursion or not or if it even helps in increasing the performance of my algorithm. I feel as though I am creating and replacing too many arrays by calling my inner rotate() function.

Should I add a check to convert rotation -270 to 90 and vice-versa so that I am rotating less often?

Please refer to the JSFiddle I have provided for details and clarification on the functions involved in the code below: JSFiddle Demo

var rotateMatrix = function (matrix, n, direction) {
    var ret = matrix.slice();

    var rotate = function(direction, matrix) {
        var r = zeroArr(n, n);
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < n; j++) {
                if (direction < 0) {
                    r[i][j] = matrix[n - j - 1][i];
                } else {
                    r[i][j] = matrix[j][n - i - 1];
                }
            }
        }
        return r;
    };

    for (var turn = Math.abs(direction); turn > 0; turn -= 90) {
        ret = rotate(direction, ret);
    }

    return ret;
};

var tile = [
    ['A', 'B', 'C'],
    ['D', 'E', 'F'],
    ['G', 'H', 'I']
];

trace2('Rotate +180', printMatrix(rotateMatrix(tile, 3, 180)));
trace2('Rotate +90', printMatrix(rotateMatrix(tile, 3, 90)));
trace2('Orginal', printMatrix(tile));
trace2('Rotate -90', printMatrix(rotateMatrix(tile, 3, -90)));
trace2('Rotate -180', printMatrix(rotateMatrix(tile, 3, -180)));

Output:

Rotate +180:

 I| H| G
--+--+--
 F| E| D
--+--+--
 C| B| A

Rotate +90:

 C| F| I
--+--+--
 B| E| H
--+--+--
 A| D| G

Orginal:

 A| B| C
--+--+--
 D| E| F
--+--+--
 G| H| I

Rotate -90:

 G| D| A
--+--+--
 H| E| B
--+--+--
 I| F| C

Rotate -180:

 I| H| G
--+--+--
 F| E| D
--+--+--
 C| B| A


texts: Timing how long garbage collection is taking in C#

texts:
I'm concerned about how much time my application could be spending during garbage collection so I'm trying to figure out how to add some code to instrument this.

Based on some examples:

https://msdn.microsoft.com/en-us/library/cc713687(v=vs.110).aspx
http://www.codeproject.com/Articles/101136/Garbage-Collection-Notifications-in-NET

I've come up with the code below. I'm see GC taking around 200 ms locally.
Does anyone know if the code below is reasonable? Or is there a better way?

class Program
{
    public static void Main(string[] args)
    {
        var done = false;
        var load = new List<byte[]>();

        var pollGC = new Action(() =>
        {
            // Register for a notification.
            GC.RegisterForFullGCNotification(10, 10);
            Console.WriteLine("Registered for GC notification.");

            Stopwatch gcTimer = new Stopwatch();

            while (!done)
            {
                // Check for a notification of an approaching collection.
                GCNotificationStatus s = GC.WaitForFullGCApproach();
                if (s == GCNotificationStatus.Succeeded)
                {
                    Console.WriteLine("GC is about to start.");
                    load.Clear();
                    gcTimer.Restart();
                }

                // Check for a notification of a completed collection.
                s = GC.WaitForFullGCComplete();
                if (s == GCNotificationStatus.Succeeded)
                {
                    Console.WriteLine("GC has finished in {0} ms", gcTimer.ElapsedMilliseconds);
                }

                Thread.Sleep(500);
            }
            GC.CancelFullGCNotification();

            Console.WriteLine("Finished monitoring GC");

        });

        var doWork = new Action(() =>
        {
            while (!done)
            {
                try
                {
                    load.Add(new byte[10000]);
                }
                catch (OutOfMemoryException)
                {
                    Console.WriteLine("Out of memory. {0}", load.Count);
                }
            }
        });

        Console.WriteLine(GCSettings.IsServerGC);

        Task.Run(pollGC);
        Task.Run(doWork);

        Console.ReadLine();
        done = true;
        GC.CancelFullGCNotification();

        Thread.Sleep(2000);
    }
}


texts: Extracting components of a street address

texts:
I have got the following function in my class that I think can be further be improved but I'm lacking ideas how:

...
private function populateAddressVars()
{
    if (!$this->service_results || !$this->service_results->results[0]) {
        return false;
    }

    foreach ($this->service_results->results[0]->address_components as $component) {
        if (in_array('street_number', $component->types)) {
            $this->streetNumber = $component->long_name;
        }
        if (in_array('locality', $component->types)) {
            $this->locality = $component->long_name;
        }
        if (in_array('postal_town', $component->types)) {
            $this->town = $component->long_name;
        }
        if (in_array('administrative_area_level_2', $component->types)) {
            $this->country = $component->long_name;
        }
        if (in_array('country', $component->types)) {
            $this->country = $component->long_name;
        }
        if (in_array('administrative_area_level_1', $component->types)) {
            $this->district = $component->long_name;
        }
        if (in_array('postal_code', $component->types)) {
            $this->postcode = $component->long_name;
        }
        if (in_array('route', $component->types)) {
            $this->streetAddress = $component->long_name;
        }
    }
}
...

Can it be further improved?


texts: Selecting a random student from a class list

texts:
This selects a random student from a class list, stored in a .ss file:

from Tkinter import Tk,Button,StringVar,Entry,Label
import random, tkFileDialog, tkMessageBox
root= Tk()
root.wm_title("Random Student Selector")
current=StringVar()
kids=[]
addKidName=Entry(root)
def addkid():
    kids.append(addKidName.get())
addKid=Button(root, text="Add a student", command=addkid)
def choosekid():
    try:
        chosen=random.choice(kids)
    except IndexError:
        tkMessageBox.showinfo("Empty class", "You need to add a student")
    current.set(chosen)
chooseKid=Button(root,text="Pick random student", command=choosekid)
chosenKid=Label(root,textvariable=current)
def loadfile():
    global kids
    loadedfile=tkFileDialog.askopenfile(mode='r', filetypes=[("Text files","*.ss")])
    try:
        kids=loadedfile.read().split(",")
    except AttributeError:
        tkMessageBox.showinfo("No file selected", "You need to select a file")
loadFile=Button(root,text="Load a class",command=loadfile)
def savetofile():
    savefile=tkFileDialog.asksaveasfile()
    stringToSave=""
    for i in kids:
        stringToSave=stringToSave+i+","
    stringToSave=stringToSave[:-1]
    savefile.write(stringToSave)
saveToFile=Button(root,text="Save a file",command=savetofile)
 addKid.grid(row=0,column=1)
addKidName.grid(row=0,column=0)
chooseKid.grid(row=1,column=1)
chosenKid.grid(row=1,column=0)
loadFile.grid(row=2,column=0)
saveToFile.grid(row=2,column=1)
root.mainloop()


texts:
I'm trying to make a program that calculates your k/d ratio (kill/death, which is used in FPS games to make people believe that it's skill), how many kills you need without dying once to reach a goalKD. It also has a part that calculates how many battles you need if you give the program your average battle kills and battle deaths.

Is there a efficient way to program it? Currently, the way I'm doing it is getting me into programmer-efficiency hell.

For i = 1 to 100000 {
    While GoalKD>KDratio {
      Kills = BattleKills + Kill
      Deaths = BattleDeaths + Death
      KDratio = Kills / Deaths
      i++
  }
}

I'm programming this in SmallBasic because I'm most familiar with it, and I think it's easily readable. Also, if possible, don't give the answer right away; give me some hints for me to practice my mind. Add the answer in a spoiler box.