texts:
The purpose of the code is to calculate the least amount of coins needed to produce correct amount of change given a dollar or cent user input. I'm just starting out and appreciate any pointers in how this code could/should be optimized.

The code works but I feel there is some redundancy with all those "while" loops. Using modulo math was another suggestion in order to solve the problem but I felt more comfortable using this solution for now.

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main (void)
{

// Variables//
float change;
int num = 0;
int quarter = 25;
int dime = 10;
int nickel = 5;
int penny = 1;

// Input of change//
do
{
    printf("How much change is owed?  ");
    change = get_float();
}
while (change <= 0);

printf("%.2f\n",change);

// conversion from dollars to cents (need to look over use of rounding)

int cents = (change * 100);

//Coin count//

while ( cents >= quarter)
{
cents -= quarter;
num++;
}

while (cents >= dime)
{
cents -= dime;
num++;
}

while (cents >= nickel)
{
cents -= nickel;
num++;
}

while (cents >= penny)
{
cents -=penny;
num++;
}

printf("%d\n", num);
}


texts:
char* Migrated[]={"026","109"};

int isMigrated(char* codeB)
{
    int i;
    int n=sizeof(Migrated)/sizeof(*Migrated);

    for(i=0;i<n;i++)
    {
        if(strcmp(Migrated[i],codeB)==0)
            return 0;
    }
    return -1;
}

is this function optimised from execution time perspective ?

Migrated should contain at maximum 200 value all of them are 4 byte .


texts: Find and delete an item from a singly linked list in Python

texts:
Given a Singly Linked-List, implement a method to delete the node that contains the same data as the input data.

Example:
delete(1->2->3->4,3) ==> 1->2->4

class SinglyLinkedList:
    #constructor
    def __init__(self):
        self.head = None

    #method for setting the head of the Linked List
    def setHead(self,head):
        self.head = head

    #method for deleting a node having a certain data
    #method for deleting a node having a certain data
    def delete(self,data):
        if self.head is None:
            return None
        else:
            cur  = self.head
            prev = None
            while cur.data != data and cur.next is not None:
                prev = cur
                cur = cur.next

            # when found
            if cur.data == data:
                # if head
                if cur == self.head:
                    if cur.next is None:
                        self.head = None
                    else:
                        self.head = cur.next
                else:
                    if cur.next is None:
                        prev.next = None
                    else:
                        prev.next = cur.next
            else:
                return None


texts: Very basic isomorphic JavaScript application

texts:
I'm trying to update my skillset by learning how to write isomorphic JavaScript applications.  For my stack, I've chosen React and Express - no database yet.

The problem many people seem to face when it comes to writing these kinds of applications is getting data from the server to the client so the view can be rendered properly client-side.  Apparently the best way to do this is to JSON encode the data and include that in the server-rendered page.

All of this is done and working, but I would really appreciate if somebody who knows what they're doing could weigh in on my techniques before I develop bad habits.

A working repository (very small) is available on GitHub, but I have included the relevant concerning code below.

To get the data to the client, I pass it down through React until it hits the base template, where it is encoded and included in an invisible element:

return this.isServer ? (

            <title>{ this.props.title || "Untitled" }</title>
            <link rel="stylesheet" href="/static/theme/style.scss"/>

            {
                //If data is to be passed into the view, encode it as JSON and insert it into a hidden element
                this.props.data &&
                    <x-data>
                        { new Buffer(JSON.stringify(this.props.data)).toString("base64") }
                    </x-data>
            }

My Files

                { this.props.children }

) : this.props.children;

The application is rendered into the  element on the server, and if this code is running on the client, it is handled elsewhere, in my client entrypoint:

import App from "./views/index.jsx";

//Get data from server, which is passed down through the x-data element
//It is base64 encoded JSON
let props = {};
let xData = document.body.querySelector("x-data");
if (xData) {
    let json = JSON.parse(window.atob(xData.innerText));
    Object.assign(props, json);
}

//All pages will export an App class which renders the current page
ReactDOM.render(
    React.createElement(App, props),
    document.body.querySelector("main")
);

The App class is the base React component to render this specific page.  I'm not sure how I'll work out having multiple pages in the future, but this is how I have it working now.

Am I following a proper design pattern, or have I invented some mutant hellspawn technique that should be vanquished with a quick rm -rf?


texts: Implementing EXCEPT functionality for social networking exercise

texts:
I am taking Stanford's Introduction to Databases Self-Paced online course. I have gone through the videos in the SQL mini-course, and I am having trouble completing the exercises.

The following is the question from the SQL Social-Networking Query Exercises, Question 5:

  For every situation where student A likes student B, but we have no
  information about whom B likes (that is, B does not appear as an ID1
  in the Likes table), return A and B's names and grades.

The database can be found here or download the schema + data.

My answer to this question is as follows:

SELECT H1.name, H1.grade, H2.name, H2.grade
FROM (SELECT * FROM Likes L1
WHERE L1.ID2 NOT IN (SELECT L2.ID1 FROM Likes L2)) F INNER JOIN
Highschooler H1 ON F.ID1 = H1.ID INNER JOIN Highschooler H2 ON F.ID2 =
H2.ID;

I want to avoid using the WHERE L1.ID2 NOT IN... part of the query.

In particular, I'd like to use two result sets.

The first being the entire Likes relation:
SELECT *
FROM Likes L1;

Then I'd like to take the results from the following query:
SELECT L2.ID
FROM Likes L2

And then someone filter the first result set such that it only includes the tuples in result set 1 if L1.ID2 is not in result set 2.

I feel like there's a join or maybe set operator that can do this?


texts:
I need some review on my implementation of input iterator. I am currently re-implementing std::vector, and need input_iterator for a specific constructor.
Any criticism is much appreciated! Thank you.
#ifndef INPUT_ITERATOR
#define INPUT_ITERATOR

template<typename T>
class input_iterator
{
private:
    T* input_iter;

public:
    using reference = T&;
    using const_reference = const T&;
    using value_type = T;
    using pointer = T*;
    using const_pointer = const T*;

    constexpr input_iterator() noexcept : input_iter{ nullptr } {}

    constexpr explicit input_iterator(pointer inputIter) noexcept : input_iter{ inputIter } {}

    constexpr explicit input_iterator(const input_iterator& other) noexcept : input_iter{ other.input_iter } {}

     ~input_iterator() noexcept = default;

    constexpr reference operator=(const input_iterator& other){
        if (input_iter != other.input_iter)
            input_iter = other.input_iter;
        return *this;
    }

    constexpr const_reference operator*() const {
        return *this;
    }

    constexpr const_pointer operator->() const {
        return this;
    }

    constexpr input_iterator& operator++() {
        ++input_iter;
        return *this;
    }

    constexpr input_iterator& operator++(int) {
        input_iterator current{ input_iter };
        ++(*this);
        return current;
    }

    constexpr bool operator==(const input_iterator& other) const noexcept {
        return (input_iter == other.input_iter);
    }

    constexpr bool operator!=(const input_iterator& other) const {
        return !(input_iter == other.input_iter);
    }

};

#endif
```


texts:
I was solving this Leetcode challenge about Hamming Distance. Would love feedback on my syntax and code style. Here's the challenge description:

  The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

  Given two integers x and y, calculate the Hamming distance.

  Note:
  0 ≤ x, y < 231.

  Example:

  Input: x = 1, y = 4

  Output: 2

  Explanation:

1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

  The above arrows point to positions where the corresponding bits are
   different.

Here's my solution:

   def hammingDistance(x: 'int', y: 'int') -> 'int':

    bin_x = bin(x)[2:]
    bin_y = bin(y)[2:]
    len_x = len(bin_x)
    len_y = len(bin_y)

    if len_x != len_y:
        if len_x > len_y:
            zeros = '0' * (len_x - len_y)
            bin_y = zeros + bin_y
        else:
            zeros = '0' * (len_y - len_x)
            bin_x = zeros + bin_x

    dist = 0
    for x,y in zip(bin_x, bin_y):
        if x!=y:
            dist += 1

    return dist


texts:
Given an array of integers, replace every element with the next
  greatest element (greatest element on the right side) in the array.
  Since there is no element next to the last element, replace it with
  -1.

  Input:

  The first line of input contains an integer T denoting the number of
  test cases. The first line of each test case is N,N is the size of
  array. The second line of each test case contains N input A[i].

  Output:

  Print the modified array.

  Constraints:

  1 ≤ T ≤ 50 1 ≤ N ≤ 100 1 ≤ A[i] ≤ 1000

  Example:

  Input:

2
6
16 17 4 3 5 2
4
2 3 1 9

  Output:

17 5 5 5 2 -1
9 9 9 -1

My approach:

/*package whatever //do not write package name here */

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Collections;

class GFG {

    private static int [] calcNewArr(int [] arr)
        {
            int [] ans = new int[arr.length];
            ans[0] = getNextBiggest(arr,1);
            for (int i = 1; i < arr.length - 1; i++)
                {
                    ans[i] = getNextBiggest(arr,i+1);
                }
            ans[ans.length - 1] = -1;
            return ans;
        }

    private static int getNextBiggest (int [] arr, int start)
        {
            int max = Integer.MIN_VALUE;
            for (int i = start; i < arr.length; i++ )
                {
                    if ( max < arr[i])
                        {
                            max = arr[i];
                        }
                }
            return max;
        }

    public static void main (String[] args) throws IOException {
       BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
       String line = br.readLine();

       int numTests = Integer.parseInt(line);
       String line2;
       String line3;
       int size;
       int [] arr;
       int [] result;

       for (int i = 0; i < numTests; i++)
        {
            line2 = br.readLine();
            size = Integer.parseInt(line2);
            line3 = br.readLine();
            String []inps = line3.split(" ");
            arr = new int[size];
            for (int j = 0; j < size; j++)
                {
                 arr[j] = Integer.parseInt(inps[j]);
                }
            result = calcNewArr(arr);
            for (int k = 0; k < size; k++)
                {
                    System.out.print(result[k] + " ");
                }
           System.out.println();
        }

    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?

2.Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference


texts: My first-ever jQuery works, but it's not efficient. Any pointers?

texts:
I've written my first completely self-written jQuery today. I just used the jQuery docs and I'm reasonably proud I got it to work, and working fine. It's not a very complex problem I'm solving, just an animated UI element, but it are my first steps, and I want to make sure I'm starting off right.

I think it's a lot of code for what I'm trying to achieve, and I'm looking for pointers or tips on how I could improve my code. I'm not at all averse to scrapping all jQuery here and doing it with pure JS either.

jQuery(document).ready(function () {
    event.preventDefault();
    var nav = jQuery(".navigation-menu");
    var button = jQuery(".navigation-title");

    function showNav() {
        nav.show('fast');
        button.removeClass('closed');
        button.addClass('open');
    }

    function hideNav() {
        nav.hide('fast');

        if (button.hasClass('open')) {
            button.removeClass('open');
        }

        button.addClass('closed');
    }

    hideNav();

    button.click(function () {
        if (button.hasClass('closed')) {
            showNav();
        } else if (button.hasClass('open')) {
            hideNav();
        } else if (!button.hasClass('open') || !button.hasClass('closed')) {
            hideNav();
        }
    });
});

Here's the fiddle: http://jsfiddle.net/yeawg/2/

I'm also wondering: am I using event.preventDefault() right?


texts: Showing the minimum of letters needed for a palindrome

texts:
This shows the minimum of letters needed for a palindrome.  It needs tweaking since it works fine for words 1-9 characters, but becomes slow for words with 10-12 characters, and for 13+ characters it really takes a lot of time. Any help is appreciated.

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <malloc.h>

typedef struct _el {
    char ch;
    struct _el* next;
} lst;

typedef struct _lst {
    char* string;
    struct _lst* next;
} elmt;

char* _remove(char*, int);
int min(int , int);
elmt* _ncptr(char [], int, elmt*, int );
int minfinal(char [], int, int );
elmt* _add(elmt* root, elmt* elm);
int _count(elmt* root);
int _last_p(elmt* root);
int ispnd(char [], int);
int __exist (elmt* root, char* str, int h);
int max(int, int);
lst* add(lst* root, char n);
int exist(lst* root, char n);

int main() {
    int l, min;
    char b[50];
    printf("Insert the word:");
    scanf("%s", b);
    l = strlen(b) - 1;
         printf("%d letters needed.\n", minfinal(b, 0, l));
    _getch();
    return 0;
}

int min(int a, int b) {
    return ((a>b) ? b : a);
}

elmt* _ncptr(char v[], int quant, elmt* root, int count) {
    int cnt_, lvar;
    int len = strlen(v)-1;
    if(!root) {
        root = (elmt*)malloc(sizeof(elmt));
        root->string = (char*)malloc(len+1);
        strcpy(root->string, v);
        root->next = '\0';
    }
    if(quant == 0) return root;
    if(count > 0) {
        int i;
        elmt *n_el, *tmp = root;
        i = 0;
        while(i < count) {
            int j;
            j = 0;
            for(j = 0; j < strlen(tmp->string); j++) {
                n_el = (elmt*)malloc(sizeof(elmt));
                n_el->string = _remove(tmp->string, j);
                n_el->next = '\0';

                if(__exist(root, n_el->string, i+j+1)) continue;
                root = _add(root, n_el);
            }
            tmp = tmp->next;
            i++;
        }
        return( _ncptr( v, quant-1, root, _count(root)-count ) );
    }
    else {
        //MAYBE IT's FIRST CALL OF THE FUNCTION
        int i,j;
        elmt* n_el;
        i = strlen(v);
        for(j = 0; j < i; j++) {
            n_el = (elmt*)malloc(sizeof(elmt));
                n_el->string = _remove(v, j);
                n_el->next = '\0';
                root = _add(root, n_el);
        }
        return( _ncptr( v, quant-1, root, _count(root) ) );
    }
}

char* _remove(char* str, int i) {
    int j,k;
    char* nstr = (char*)malloc(strlen(str));
    nstr[0] = '\0';
    for(j = 0, k = 0; j < strlen(str); j++) {
        if(j == i) { continue; }

        nstr[k] = str[j];
        k++;
    }
    nstr[k] = '\0';
    return nstr;
}

elmt* _add(elmt* root, elmt* elm) {
    elm->next = root;
    return elm;
}

int _count(elmt* root) {
    long int l_var;
    for( l_var = 0; root && root->string; l_var++, root=root->next );
    return l_var;
}

int minfinal(char v[], int n, int i) {
    elmt* g = NULL;
    if(ispnd(v, i)) return 0;

    g = _ncptr(v, i, g, 0);

    return( strlen(v) - _last_p(g) );
}

int ispnd(char v[], int z) {
    int i, j, k;
    k = 0;
    for(i = 0, j = z; i < j; i++, j--) {
        if(v[i] != v[j]) {
            k = 1;
            break;
        }
    }
    return !k;
}

int _last_p(elmt* root) {
    int l_var = 0;
    for(; root; root=root->next ) {
          if(strlen(root->string) == 0) continue;
        if(!ispnd(root->string, strlen(root->string)-1)) continue;
        l_var = max( l_var, strlen(root->string) );
    }
    return l_var;
}

int __exist (elmt* lstt, char* str, int h) {
    int i,j;
    for(j=0; lstt, j <= h; lstt = lstt->next, j++ ) {
        i = strcmp(lstt->string, str);

        if(!i) return 1;
    }
    return 0;
}

int max(int a, int b) {
    return (a > b ? a : b );
}


texts:
I'm doing K&R C Exercises.  I could use a code review to see how I can improve my logic. The excercise is:

  Write a program that prints its input one word per line with getchar.

My basic idea is we need to know whether or not we're in a word. We use the IN status.  Every time we hit a blank space, tab, or newline, the status is changed to OUT.

Please offer only suggestions based on what i'm learning in the book up to this point, "symbolic constants,  if else, and loops only." Also thoughts on my comments would be welcome.

// Exercise1.11.cpp : Defines the entry point for the console application.
/*
 Write a program that prints its input one word per line.
*/

#include "stdafx.h"

#define IN 1
#define OUT 0

int _tmain(int argc, _TCHAR* argv[])
{
    int status = OUT;
    int c;

    while ((c = getchar()) != EOF){

        // Check to see if char is not a new line, blank or space.
        if ((c != '\n' && c !=' ' && c != '\t') ){

            if (status == OUT){
                putchar('\n');
                status = IN;
            }

            putchar(c);
        }
        else {
            // char is a new line, blank or tab, so don't process them.
            status = OUT;
        }
    }

    return 0;
}


texts: Implement a blocking counter with a reader/writer lock

texts:
I'm trying to implement a blocking counter that may have several readers and writers at the same time:

class BlockingCounter {
public:
    BlockingCounter(int count) : count_(count) {
        // init lock_;
    }
    ~BlockingCounter() {
        // destroy lock_;
    }

    void Increment() {
        pthread_rwlock_wrlock(&lock_);
        count_++;
        pthread_rwlock_unlock(&lock_);

    }

    void Decrement() {
        pthread_rwlock_wrlock(&lock_);
        count_--;
        pthread_rwlock_unlock(&lock_);

    }

    int GetCount() {
        pthread_rwlock_rdlock(&lock_);
        int count = count_;
        pthread_rwlock_unlock(&lock_);
        return count;
    }

private:
    pthread_rwlock_t lock_;
    int count_;

};

Does this code have problems under multi-threading circumstances?

I intended to use it like this:

Main thread:

BlockingCounter *counter = new BlockingCounter(10);

// Here 10 threads are started. See code below.
while (counter->GetCount() > 0) {
  ConditionVar.wait();
}
// Main thread resumes execution.

Other 10 thread(s):

// Do stuff
counter.Decrement();
ConditionVar.notify();


texts: Organize JavaScript for video player controls

texts:
I have a small piece of code, and the problem is that I don't know how to organize it. There are tons of tutorials about JS code organization but I feel that those are for large scale apps. Also, I'm not sure if having the setInterval function where it is now is a big no no, can you come up with some critique/ideas?

YUI().use('node', function (Y) {
    // Access DOM nodes.

    var chapterTime = [0, 30, 49, 68, 90, 105, 127, 153, 182, 209],
        buttons = Y.one('ul'),
        currentChapter = 0,
        prevChapter = 0,
        myPlayer = videojs('example_video_1');

    buttons.delegate('click', function () {
        var button_name =  this.ancestor().get('id'),
            chapter = button_name.slice(1);

            playChapter(chapterTime[chapter-1], this);
    }, 'a');

    function playChapter(chTime, chButton) {
        myPlayer.play();
        setTimeout(function(){ myPlayer.currentTime(chTime); },100);
        Y.all('#nav a').setStyle('backgroundColor', "#999");
        chButton.setStyle('backgroundColor', '#666');
    }

    setInterval(function(){
        var playbackTime = myPlayer.currentTime(),
            i = 0,
            chapterFound = false;
            //console.log(chapterTime);

        while (i <= 9 && chapterFound == false){
            if (playbackTime >= chapterTime[i] && playbackTime < chapterTime[i+1]){
                currentChapter = i + 1;
                chapterFound = true;
            } else {
                i++;
            }
        }

        if (currentChapter != prevChapter){
            var button = Y.one('#c' + currentChapter);
            Y.all('#nav a').setStyle('backgroundColor', '#999');
            button.one('a').setStyle('backgroundColor', '#666');
            prevChapter = currentChapter;
        }
    },1000);
});


texts: Manually writing a function matrixpower() in R

texts:
Problem 1 - Matrix powers in R

  R does not have a built-in command for taking matrix powers.

  Write a function matrixpower() with two arguments mat and k that  will
  take integer powers k of a matrix mat.

My attempted solution.

matrixMul <- function(mat1, mat2)
{
    rows <- nrow(mat1)
    cols <- ncol(mat2)

    if(rows == cols)
    {
        matOut <- matrix(nrow = rows, ncol = cols) # empty matrix

        for (i in 1:rows)
        {
            for(j in 1:cols)
            {
                vec1 <- mat1[i,]
                vec2 <- mat2[,j]

                mult1 <- vec1 * vec2

                matOut[i,j] <- sum(mult1)
            }
        }

        return(matOut)
    }
    else
    {
        return (matrix( rep( 0, len=25), nrow = 5))
    }
}

matrixpower<-function(mat1, k)
{
    pow1 <- abs(k)

    rows <- nrow(mat1)
    cols <- ncol(mat1)

    matOut <- diag(1, rows, cols)

    if(pow1 == 0)
    {
        return(matout)
    }
    if (pow1 == 1)
    {
        matOut <- mat1
    }

    if(pow1 > 1)
    {
        for (i in 1:pow1)
        {
            matOut <- matrixMul(matOut, mat1)
        }
    }

    if(k < 0)
    {
        matOut <- solve(matOut)
    }

    return (matOut)
}

mat1 <- matrix(c(1,2,3,4), nrow = 2, ncol=2)
pow1 <- matrixpower(mat1, -2)
pow1

I have a few questions here.

Is there any room for improvement in this code?
Does this problem ask for manual implementation of multiplication? Or, should the use of %*% suffice?


texts:
I use this idiom to parse command line arguments in Perl:

my @args;
my $encode = 1;

while (@ARGV) {
    for (shift(@ARGV)) {
        ($_ eq '-h' || $_ eq '--help') && do { &usage(); };
        # ... more options here
        ($_ eq '--') && do { push(@args, @ARGV); undef @ARGV; last; };
        ($_ =~ m/^-.+/) && do { print "Unknown option: $_\n"; &usage(); };
        push(@args, $_);
    }
}

This let's me do things like:

Supports command line arguments in arbitrary order
Supports using -- to use any following arguments "as is", without parsing
Stop parsing and print usage message on -h, or --help
Raise error if a -something flag is detected that is not matched by any of the parsing rules

Here's a short example script using this idiom:

#!/usr/bin/env perl

use strict;
use warnings;

&usage() unless @ARGV;

my @args;
my $encode = 1;

while (@ARGV) {
    for (shift(@ARGV)) {
        ($_ eq '-h' || $_ eq '--help') && do { &usage(); };
        ($_ eq '-D' || $_ eq '--decode') && do { $encode = ! $encode; last; };
        ($_ eq '--') && do { push(@args, @ARGV); undef @ARGV; last; };
        ($_ =~ m/^-.+/) && do { print "Unknown option: $_\n"; &usage(); };
        push(@args, $_);
    }
}

sub usage {
    $0 =~ m|[^/]+$|;
    print "Usage: $& [-h|--help] [-D|--decode]\n";
    print "\n";
    print "Encode (= default) or decode Base64\n";
    exit 1;
}

use MIME::Base64;
if ($encode) {
    print map(&MIME::Base64::encode_base64($_), @args);
} else {
    print map(&MIME::Base64::decode_base64($_), @args);
}

Is this a good technique for parsing command line arguments in Perl?
Is there a better way?

I'm also interested in improvement ideas about the short script itself too.


texts:
Recently, I wanted to change my vim colors to something new. So I went to the vim colors website and then I decided that I wanted to download ALL the colors.

So I wrote this simple Python script that will download all the files from: Vim Colors

I'm still learning Python and it would be amazing to get some feedback / suggestions if possible.

import os
import json
import requests
from bs4 import BeautifulSoup

class Spider:
    def __init__(self, total_pages=40):
        self.base_url = "http://vimcolors.com/?page="
        self.total_pages = total_pages
        self.download_dir = 'colors/'
        # If we don't have the download directory
        if not os.path.isdir(self.download_dir):
            print(self.download_dir, 'does not exist, trying to create it...')
            # create it...
            os.mkdir(self.download_dir)

    def download(self, name, url):
        # If we have already downloaded this file, just skip
        if os.path.isfile(self.download_dir + name):
            print('File:', name, 'already exists; skipping.')
            return

        try:
            # Get the response
            response = requests.get(url)
            # If response is 404 (Not Found), just exit
            if response.status_code == 404:
                raise Exception('File not found')
            # Create the file
            with open(self.download_dir + name, 'wb') as file_path:
                # Write content to the file
                file_path.write(response.content)
                # Confirm the download
                print('Downloaded', name)
        except:
            # This is a very generic error, perhaps I'll change it sometime :)
            print('Could not download the file', name)
            pass

    def crawl(self):
        def repo_formatter(scheme):
            return scheme['github_repo']['address'].replace('github.com', 'raw.githubusercontent.com') \
                   + '/master/colors/' + scheme['name'] + '.vim'

        # Loop over all the pages
        for page in range(self.total_pages):
            page_source = requests.get(self.base_url + str(page + 1))
            plain_text = page_source.text
            soup = BeautifulSoup(plain_text, 'lxml')

            # Get the data
            json_data = json.loads(soup.find('div', {'id': 'data'}).attrs['data-colorschemes'])

            # Download the files
            for data in json_data['colorschemes']:
                self.download(data['name'] + '.vim', repo_formatter(data))

colors_spider = Spider()
colors_spider.crawl()


texts: Loading a file from a FAT32 filesystem in 16 bit real mode on x86 (Intel syntax assembly)

texts:
I am writing a bootloader that needs to load a file from a FAT32 filesytem. Since I need to load both the root directory first to find the start of the file, and then the actual file, I wrote a function to load a sequence of clusters from the disk to 0x8000 in memory (since the bootloader is loaded from 0x7C00-0x7DFF and I use 0x7E00-0x7FFF to load sections of the FAT).

loadClusterChain: ; ARGS: eax = first cluster number
    pusha

    ; Set the memory location to load the file to 0x8000
    mov dx, 0x8000

    loadClusterChainLoop:

    ; Store the cluster number (eax) and additional offset (dx) for later
    push dx
    push eax

    ; Update the disk address packet
    mov word [dapDataOffset], dx

    ; Account for the cluster numbers being shifted by 2
    sub eax, 2

    ; Calculate how many sectors the cluster is from the start of the data area
    xor ebx, ebx
    mov bl, byte [bpbSectorsPerCluster]
    mul ebx

    ; Add the start of data area to the root directory offset
    add eax, dword [diskDataAreaStart]

    ; Update the disk address packet start sector
    mov dword [dapStartSector], eax

    ; Update the disk address packet sector count
    push eax
    xor ax, ax
    mov al, byte [bpbSectorsPerCluster]
    mov word [dapSectorCount], ax
    pop eax

    ; Load the file cluster
    mov ah, 0x42
    mov dl, byte [bpbDriveNumber]
    mov si, diskAddressPacket
    int 0x13
    jc diskError

    ; Retrieve the value of eax but keep it in the stack
    pop eax
    push eax

    ; Divide by 128 to calculate the FAT sector to load
    shr eax, 7

    ; Get the number of reserved sectors
    xor ebx, ebx
    mov bx, word [bpbReservedSectors]

    ; Add the reserved sectors to the FAT sector, so eax = relevant FAT sector
    add eax, ebx

    ; Update the disk address packet start sector
    mov dword [dapStartSector], eax

    ; Update the disk address packet sector count
    mov word [dapSectorCount], 1

    ; Update the disk address packet data offset to load the fat to 0x7E00
    mov word [dapDataOffset], 0x7E00

    ; Load the FAT sector
    mov ah, 0x42
    mov dl, byte [bpbDriveNumber]
    mov si, diskAddressPacket
    int 0x13
    jc diskError

    ; Get the offset of clusters into the FAT sector by getting the remainder when divided by 128
    pop eax
    and ax, 0x007F

    ; Multiply offset by 4 to get it in bytes
    shl ax, 2

    ; Calculate the memory address of the cluster in the FAT
    add ax, 0x7E00

    ; Read cluster value
    mov bx, ax
    mov eax, dword [bx]

    ; Set bx = 512*bpbSectorsPerCluster
    xor bx, bx
    mov bl, byte [bpbSectorsPerCluster]
    shl bx, 9

    ; Restore the value of dx and add bx to move dx to the memory location of the end of the file parts loaded so far
    pop dx
    add dx, bx

    ; See if this is the end of the chain
    cmp eax, 0x0FFFFFFF
    jne loadClusterChainLoop

    ; Ensure the file ends with 0, so when scanning the root entries we will definitely stop
    mov bx, dx
    mov [bx], byte 0

    popa
    ret

Here are some of the variables used. diskDataAreaStart is not 0 when the code runs as the actual value is calculated before the function is called. The other variable names are mostly self-explanatory.

diskDataAreaStart       dd 0

diskAddressPacket:
    dapSize         db 0x10
    dapReserved     db 0x00
    dapSectorCount      dw 0
    dapDataOffset       dw 0
    dapDataSegment      dw 0
    dapStartSector      dq 0

I know it's a fairly niche piece of code, but I would be very grateful if someone could give me feedback on it - if I could do something more efficiently or even feedback on how clear my comments were and how easy the code was to follow along would be highly appreciated.


texts:
I'm building a list of filters for a website user to filter on, such as a product category page. I'm giving the user the option to filter on brandname, model name, or gender.

To avoid serverside code I'm trying to build it clientside. So, I'm looking on the different data-attr and building an array of filtering values of what's actually available to filter on.

I have made it work, but I'm not sure it's the most efficient way to do it.

HTML:

JS:

// Loop through all div's with .mix class

var Genders = [];
var Brands =  [];
var Models = [];
$( ".mix" ).each(function() {
   // build arrary with Gender

   if ($(this).attr('data-Gender')) {
           genderFilter = $(this).attr('data-Gender');
            var found = jQuery.inArray(genderFilter, Genders);
       if (found >= 0) { } else {
                // Element was not found, add it.
                Genders.push(genderFilter);
            }
   }
   // build arrary with Models
    if ($(this).attr('data-Brand')) {
           brandFilter = $(this).attr('data-Brand');
            var found = jQuery.inArray(brandFilter, Brands);
       if (found >= 0) { } else {
                // Element was not found, add it.
                Brands.push(brandFilter);
            }
   }
   // build arrary with Brands
    if ($(this).attr('data-Model')) {
           modelFilter = $(this).attr('data-Model');
            var found = jQuery.inArray(modelFilter, Models);
       if (found >= 0) { } else {
                // Element was not found, add it.
                Models.push(modelFilter);
            }
   }
});

console.log( Models.length );
console.log ( Models);
console.log( Brands.length );
console.log ( Brands);
console.log( Genders.length );
console.log ( Genders);

JSFiddle


texts: This script works but keeps timing out with longer inputs. How can I improve its speed? [Ruby]

texts:
The script takes a string such as this: (15, 176) (65, 97) (72, 43) (102, 6) (191, 189) (90, 163) (44, 168) (39, 47) (123, 37) and breaks it into an array of arrays. It then computes the largest possible number of choices, with the guideline that each selected array has to have both numbers smaller than the previous selection. For the above string, the right output would be 4.

people = File.read(ARGV[0])
people = people.sub("\(", '').sub(/\)$/, '').split("\) \(")
people.map! { |p| p.split(', ') }

count = 0
test = people.permutation.to_a
test.each do |perm|
  test_count = 0
  perm.each_with_index do |item, i|
    test_case = perm[i+1]
    unless test_case == nil
    test_count += 1 if item[0] > test_case[0] && item[1] > test_case[1]
    end
  count = [count, test_count].max
  end
end

p count

Anyways, it works but is sloooow, especially with longer strings. How can I speed this up? I know the nested loops can be problematic and as the string grows the number of permutations grows. Any advice would be much appreciated.

Edit: I am running this on Ruby 1.8.7.

Edit: New attempt at the problem/script:

people = '(15, 176) (65, 97) (72, 43) (102, 6) (191, 189) (90, 163) (44, 168) (39, 47) (123, 37)'
#people = File.read(ARGV[0]).chomp
people = people.sub("\(", '').sub(/\)$/, '').split("\) \(")
people.map! { |p| p.split(', ').map {|a| a.to_i } }

ht = people.sort_by { |h| h[0] }
wt = people.sort_by { |w| w[1] }
a_i = []

ht.each do |item|
  a_i << wt.index(item)
end

def subgen( array, count=1, t=(array.length+1) )
  if array.length == 1
    return count
  end
  without = subgen(array[0..-2], count, t)
  if array[0] > array[-1] || array[-1] > t
    return without
  else
    with = subgen(array[0..-2], count+=1, t = array[-1])
    return [with, without].max
  end
end

current = 0
a_i.each_with_index do |item, j|
  test = a_i[j..-1]
  current = [current, subgen(test)].max
end

p current

This has been thoroughly tested and works, but there has to be a way to make it faster. Any ideas?


texts: Dictionary foreach loop with multiple occurences

texts:
A little look on what are Dictionaries:

dictWordCounter<string, int>
dictWordPercent<string, double>
topTwentySeven<string, double>

WordCounter is the number of words. For example, if the word frog is 10 times it will be {frog, 10}.
WordPercent is the percent after some math in the program. For example, frog could be {frog, 0,55}.
topTwentySeven is the top 27 values from the WordPercent dictionary that I want to operate on.

So, I need to count something like this:

If a word is just one, count it normally
If a word is twice or more, count it x2
Total number of words (after x2) must be still 27, not more

For example if it was "topThree" and words:

{Frog, 2}, {Monkey, 1}, {Giraffee, 1}, and their values from Percent Dictionary would be {Frog, 0,1}, {Giraffee, 0,2}, {Monkey, 0,45}, I want to count: 0,1*0,1*0,2 and (1-0,1) * (1-0,1)*(1-0,2).

Could someone look on this and check if it can be improved?

   var topTwentySeven = dictWordPercent.OrderByDescending(kvp => Math.Abs(kvp.Value - 0.5))
        .Take(27)
        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

    int compare = 0;
    double temp2 = 1.0, A = 1.0, B = 1.0;
    for (int counter = 0; counter < 27; )
    {

        foreach (var word in topTwentySeven)
        {
        dictWordCounter.TryGetValue(word.Key, out compare);
            if (compare >= 2 && counter < 26)
            {
                temp = word.Value;
                temp2 = temp * temp;
                A *= temp2;
                B *= (1 - temp2);
                counter = counter + 2;

            }
            else if (compare == 1 && counter < 27)
            {
                temp = word.Value;
                A *= temp;
                B *= (1 - temp);
                counter = counter + 1;
            }
            else if (counter >= 27)
            {
                //Do nothing
            }
        }
    }

int top27C = topTwentySeven.Count();

double aN = 0.0, bN = 0.0;
aN = Math.Pow(A, (1 / top27C));
bN = Math.Pow(B, (1 / top27C));

I need both A and B.

totalSum = Math.Round(((aN / (aN + bN)) * 100), 2);


texts: Indexing columns to make a MySQL query faster

texts:
I have this query here that I am trying to make more efficient as it is taking an extremely long amount of time, about 40s on 3 million records.

The query basically takes X amount of rows per company and turns them into columns for a given existing column.

SQLFiddle

SET @sql = NULL;
SET @sql1 = NULL;
SET @sql2 = NULL;
SET @sql3 = NULL;
SET @sql4 = NULL;
SET @sql5 = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then experience_rate end) AS `', year, '-Pen`' ) ORDER BY year ) INTO @sql1 FROM spooner_pec;
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then mco_name end) AS `', year, '-MCO`' ) ORDER BY year ) INTO @sql2 FROM spooner_pec;
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then premium_range end) AS `', year, '-Prem`' ) ORDER BY year ) INTO @sql3 FROM spooner_pec;
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then employer_rating_plan end) AS `', year, '-Rating`' ) ORDER BY year ) INTO @sql4 FROM spooner_pec;
SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when year = ', year, ' then risk_group_number end) AS `', year, '-Gr Num`' ) ORDER BY year ) INTO @sql5 FROM spooner_pec;
SET @sql = CONCAT(
    'SELECT policy_number AS PolicyNumber,
    coverage_status_code As CoverageStatusCode,
    primary_name AS PrimaryName,
    primary_dba_name AS DBA,
    address1 AS Address1,
    address2 AS Address2,
    city AS CityName,
    state AS StateID,
    zipcode AS ZipCode,
    zip_plus_four AS ZipCode4,
    business_area_code AS PhoneAreaCode,
    business_phone AS PhoneNumber,
    business_extension AS PhoneExtension,
    business_contact_first_name AS FirstName,
    business_contact_last_name AS LastName,
    county_description AS County, ', @sql1, ', ', @sql2, ',', @sql3, ',', @sql4, ',', @sql5, '
    FROM spooner_pec GROUP BY policy_number');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

One of my coworkers mentioned indexing but I think the columns that are taking the longest are the ones that I am creating to pivot the data. Is there any way to index those?


texts:
I'm trying to flatten a binary tree into a linked list.

I have a working, correct solution:

# Definition for a binary tree node.
  class TreeNode:
      def __init__(self, x):
          self.val = x
          self.left = None
          self.right = None

def insert(root, node):
    if root.right is None:
        root.right = node
        return None
    else:
        insert(root.right, node)
class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if root is None:
            return None
        if root.left is None and root.right is None:
            return root
        left = self.flatten(root.left)
        right = self.flatten(root.right)
        root.left = None
        if left:
            root.right = left
            insert(root.right, right)
        else:
            root.right = right
        return root

I'm not certain, but I think the time complexity is \$O(n^2)\$. How do I make it run faster? Specifically, how do I modify it so that it runs in optimal time complexity (linear time)?


texts: Reusable user control (ascx) design for multiple web application

texts:
My company's web application projects are heavily based on user controls. One common case  is like we want to reuse the UI visual elements but note the packaged original logic .

I have read some very smelly code in some user controls code behinde.

if(WebConfig.CurrentProject == "xxx")
{
    //do xxx's logic
    ddlPostalCode.DataSouce= this.addressManager.getUSAPostal();
}
else
{
    //do yyy's logic
    ddlPostalCode.DataSouce= this.addressManager.getUKPostal();
}

//Or use configuration
if(config.enableAlpha)
{
   //Do alpha's logic
    ddlPostalCode.DataSouce= this.addressManager.getAlphaPostalCode();
}

And these logics normally involving manipulating server controls .

So I am thinking, if we just want to reuse the visual element and parts of its logic.
Why don't we make the server and its event handler public ?

//In xxx.ascx.cs
public EventHandler AddressControl_Init;

protected override void OnInit(EventArgs e)
{
     if(this.AddressControl_Init!= null)
     {
         this.AddressControl_Init(sender, e);
     }
     else
     {
        //Default logic.
     }
}

//In xxx.ascx.designer.cs
public  public global::XYZ.Controls.Basic.XYZDropDownList ddlPostalCode;

//In the code behinde of the page using this address ascx.
//HostingPage.aspx.cs
protected override void OnPreInit(EventArgs e)
{
    this.AddressControl.AddressControl_Init += new EventHandler(USAAddressControl_Init);
}

void USAAddressControl_Init(object sender, EventArgs e)
{
    //Now i can use any business manager class here to populate the source data.
    this.AddressControl.ddlPostalCode.DataSource = Anymanager.GetMarsCode();
    this.AddressControl.ddlPostalCode.DataBind();
}

This is a very simple example, but it also can be a very flexsiable solution.
It decouple the logic behinde the user control. Let the user, the page to deside the control's logic.

Is there any better elegent ways to solve my problem?


texts:
I know I can use Sieves to make this faster, but I wondered if there's anything I'm missing with this implementation of the "naive" algorithm.

On my PC running the command (first million primes):

  g++ -std=c++11 -Wall -Wextra -Ofast primes.cpp -o primes && time ./primes 15485863

this takes approximately 9.3 secs.

#include <climits>
#include <cstdio>
#include <string>
#include <vector>

typedef unsigned long long ull;

int main(int argc, char *argv[])
{
    ull limit = ULLONG_MAX;
    if (argc > 1) limit = std::stoi(argv[1]);

    std::vector<ull> primes;
    primes.push_back(2);
    printf("2 is prime\n");
    primes.push_back(3);
    printf("3 is prime\n");
    primes.push_back(5);
    printf("5 is prime\n");
    int inc = 2;
    for (ull i = 7; i <= limit; i += inc) {
        bool isprime = true;
        for (ull j = 0; primes[j] * primes[j] <= i && j < primes.size(); j++) {
            if (i % primes[j] == 0) {
                isprime = false;
                break;
            }
        }

        if (isprime) {
            printf("%llu is prime\n", i);
            primes.push_back(i);
        }
        inc == 2 ? inc = 4 : inc = 2;
    }
}


texts: Advent of Code 2017 Day 6 (part 2) in Functional Programming (FP)

texts:
I wanted to practice functional programming (FP) without using any library but using vanilla JS only. So I took a problem from Advent of Code (the 2nd part of Day 6).

You can only access the 2nd part if you type in the solution for the 1st part: 3156 or look at my solution for part 1.

  --- Part Two --- Out of curiosity, the debugger would also like to know the size of the loop: starting from a state that has already been
  seen, how many block redistribution cycles must be performed before
  that same state is seen again?

  In the example above, 2 4 1 2 is seen again after four cycles, and
  so the answer in that example would be 4.

  How many cycles are in the infinite loop that arises from the
  configuration in your puzzle input?

This is my FP solution:

/*jshint esversion: 6*/

const banks = `2    8   8   5   4   2   3   1   5   5   1   2   15  13  5   14`;
const parse = input => input
  .split('\t')
  .map(c => parseInt(c));
const copy = input => input.slice();

const INPUT = parse(banks);
const redistribute = (input, index, toBeDistributed) => {
  if (!toBeDistributed) return input;
  const nextIndex = index + 1;
  const nextInput = input;
  ++nextInput[nextIndex % input.length];
  return redistribute(nextInput, nextIndex, --toBeDistributed);
};
const isUnique = toCheck => state => toCheck.toString() !== state.toString();

const solveDaySix = input => {
  let banks = copy(input);
  const states = [input];
  let cycle = 0;
  let foundState = [];
  while (true) {
    ++cycle;
    const max = Math.max(...banks);
    const index = banks.indexOf(max);
    banks[index] = 0;
    banks = copy(redistribute(banks, index, max));
    const stateIsUnique = isUnique(banks);

    if (!states.every(stateIsUnique)) {
      foundState = copy(banks);
      break;
    }
    states.push(copy(banks));
  }
  cycle = 0;
  while (true) {
    ++cycle;
    const max = Math.max(...banks);
    const index = banks.indexOf(max);
    banks[index] = 0;
    banks = copy(redistribute(banks, index, max));
    const stateIsUnique = isUnique(banks);

    if (banks.toString() === foundState.toString()) {
      break;
    }
  }
  return cycle;
};

console.log("solution ", solveDaySix(INPUT));

I got 2 while loops that are nearly identical. Is there a way to refactor them? I tried to refactor them into one function. But that function takes and returns 4 parameters:

/*jshint esversion: 6*/

const banks = `2    8   8   5   4   2   3   1   5   5   1   2   15  13  5   14`;
const parse = input => input
  .split('\t')
  .map(c => parseInt(c));
const copy = input => input.slice();

const INPUT = parse(banks);
const redistribute = (input, index, toBeDistributed) => {
  if (!toBeDistributed) return input;
  const nextIndex = index + 1;
  const nextInput = input;
  ++nextInput[nextIndex % input.length];
  return redistribute(nextInput, nextIndex, --toBeDistributed);
};
const isUnique = toCheck => state => toCheck.toString() !== state.toString();
const getCycle = (banks, states, foundState, condition) => {
  let cycle = 0;
  while(true) {
    ++cycle;
    const max = Math.max(...banks);
    const index = banks.indexOf(max);
    banks[index] = 0;
    banks = copy(redistribute(banks, index, max));
    const stateIsUnique = isUnique(banks);
    if (condition(states, foundState, banks)) {
      foundState = copy(banks);
      return { banks, states, cycle, foundState };
    }
    states.push(copy(banks));
  }
};

const solveDaySix = input => {
  let banks = copy(input);
  let states = [input];
  let cycle = 0;
  let foundState = [];

  let {banks: nextBanks, states: nextStates, foundState: nextFoundState } = getCycle(banks, states, [], (s, f, b) => !s.every(isUnique(b)));

  let {cycle: secondCycle} = getCycle(nextBanks, nextStates, nextFoundState, (states, nextFoundState, b) => b.toString() === nextFoundState.toString());
  return secondCycle;
};

console.log("solution ", solveDaySix(INPUT));

Even though it works, I have a hunch that there is a more elegant way.


texts: Acquiring a hash containing a key and a value

texts:
I am new to Ruby and not familiar with a lot of Array features. I feel like this code can be written in a couple of fewer lines.

The idea is: I have a Definition class and a Field class. I abstracted them as Hashes to make my life easier although they should be classes.

Definition contains an Id and a Name
Field contains an Id and a Value

I want a resulting Hash that contains a Name key for each corresponding Value. However, if the name is repeated, then I need to include the Id in the Name.

Here's the code for generating mock objects:

# name and id
def mock_definitions
  d = []

  d << {
    :name => "custom def 1",
    :id   => 1
  }

  d << {
    :name => "custom def 2",
    :id   => 2
  }

  d << {
    :name => "custom def 2",
    :id   => 3
  }

  d
end

def mock_fields
  f = []

  f << {
    :id => 1,
    :value => "Value For Custom Definition 1"
  }

  f << {
    :id => 2,
    :value => "Value For Custom Definition 2"
  }

  f << {
    :id => 3,
    :value => "Value For Custom Definition 3"
  }

  f
end

def all_mocks
  return mock_definitions, mock_fields
end
############# END OF MOCK ###############

and the main logic preceded by helper functions:

def build_counter_cache(definitions = [])
  counter_cache = Hash.new

  definitions.each do |d|
    if counter_cache.has_key?(d[:name])
      counter_cache[d[:name]] +=1
    else
      counter_cache[d[:name]] = 1
    end
  end

  counter_cache
end

def build_fields_cache(fields = [])
  fields_cache = Hash.new

  fields.each do |f|
    fields_cache[f[:id]] = f[:value]
  end

  fields_cache
end

def build_search_to_replace_mapping(fields = [], definitions = [])
  counter_cache = build_counter_cache(definitions)
  custom_fields_cache = build_fields_cache(fields)

  mapping = Hash.new

  definitions.each do |d|
    search_text = ''
    replace_text = ''

    if counter_cache[d[:name]] == 1
      search_text = "{{#{d[:name]}}}"
    else
      search_text = "{{#{d[:name]}_#{d[:id]}}}"
    end

    if custom_fields_cache.has_key?(d[:id])
      replace_text = custom_fields_cache[d[:id]]
    end

    #puts "#{search_text} maps to #{replace_text}"
    mapping[search_text] = replace_text
  end

  mapping
end

### main logic begins here ###
# mocks
definitions, fields = all_mocks
mapping = build_search_to_replace_mapping(fields, definitions)

mapping.each do |key, value|
  puts "#{key} *** maps to *** #{value}"
end


texts: Loops to merge documents and renumber pages

texts:
I have a for loop implementation for merging documents and page re-numbering. But since I am modifying the collection while iterating, I suspect that the code might break. As foreach doesn't allow collection modification, I have implemented it with for.

Is there any better way to implement/optimize this part of code? Also, is it possible to reduce these 3 loops to a single one?

// Merge Document Sequence
for (int k = 0; k < response.documents.Count; k++)
{
    string presentDocument = string.Empty;
    string laterDocument = string.Empty;

    presentDocument = response.documents[k].docType;
    if ((response.documents.Count - 1) != k)
        laterDocument = response.documents[k + 1].docType;

    if ((laterDocument == presentDocument))
    {
        response.documents[k].pages.AddRange(response.documents[k + 1].pages);
        response.documents.RemoveAt(k + 1);
        k = k - 1;
    }
}

// Page Re-numbering
for (int i = 0; i < response.documents.Count; i++)
{
    for (int j = 0; j < response.documents[i].pages.Count; j++)
        response.documents[i].pages[j].pageNo= j + 1;
}


texts: Light weight C++ Signals/Slots or Event System

texts:
This assumes there is no need to aggregate results from the listeners of a broadcast signal.

Technically I guess the slots are whatever your std::function holds, so they aren't special. So I guess this is more of a Signals/Connections design.

The "connection" or Signal<T...>::Listener is the owner of the callback. It's ideal to have this owned by the object that has the callback function or on the object your lambda captures. That way when that object goes out of scope so does the callback, which prevents it from being called anymore.

You could dump listeners into a container on the object and forget about them. Or store specifically named instances of them which is very useful for switching the object you're listening to or disconnecting.

template <typename... FuncArgs>
class Signal
{
    using fp = std::function<void(FuncArgs...)>;
    std::forward_list<std::weak_ptr<fp> > registeredListeners;
public:
    using Listener = std::shared_ptr<fp>;

    Listener add(const std::function<void(FuncArgs...)> &cb) {
        // passing by address, until copy is made in the Listener as owner.
        Listener result(std::make_shared<fp>(cb));
        registeredListeners.push_front(result);
        return result;
    }

    void raise(FuncArgs... args) {
        registeredListeners.remove_if([&args...](std::weak_ptr<fp> e) -> bool {
            if (auto f = e.lock()) {
                (*f)(args...);
                return false;
            }
            return true;
        });
    }
};

usage

Signal<int> bloopChanged;

// ...

Signal<int>::Listener bloopResponse = bloopChanged.add([](int i) { ... });
// or
decltype(bloopChanged)::Listener bloopResponse = ...

// let bloopResponse go out of scope.
// or re-assign it
// or reset the shared_ptr to disconnect it
bloopResponse.reset();


texts: Simple multiple producer and single consumer concurrency pattern

texts:
Anyone please review and share your feedback for the following code.
Multiple producers generate random integer numbers and a single consumer receives it to display only odd numbers out of it.

package main

import (
"fmt"
"time"
"math/rand"
"sync"
)

var msgs = make(chan int)
var dummy = make(chan bool)
var wg sync.WaitGroup

func main() {
    defer close(msgs)
    defer close(dummy)
    numberOfProducers := 10
    go func() {
        for i := 0; i < numberOfProducers ; i++ {
            go produce() // Multiple producers
        }
        dummy <- true
    }()
    go consume() // Single consumer go routine
    <- dummy
}

func produce() {
     wg.Add(1)
     msgs <- getRandomIntegerNumber()
}

// Single consumer
func consume () {
    for {
      msg := <-msgs
      if ( msg % 2 != 0) {
         fmt.Printf(" The number %d is odd \n", msg);
      }
      wg.Done()
    }
}

func getRandomIntegerNumber() int {
     rand.Seed(time.Now().UnixNano())
     return rand.Intn(1000)
}


texts: Map in which values are concretions of a generic class

texts:
Let's say I have a pool of adapter classes. All of them are concretions of a generic interface, such as:

interface Adapter<Target,Source> {
    Target adapt(Source object);
}

Now, my idea was to implement such a pool as a map in which keys are target and source classes:

final DoubleKeyMap<Class<?>, Class<?>, Adapter<Class<?>,Class<?>>> adapters;

And clients can ask the pool for the appropriate adapter in this manner:

(Adapter<Target, Source>) adapters.get(targetClass, sourceClass);

However, I'm not sure this is the 'best' way of accomplishing it.


texts: Asynchronous wrapper for database connection

texts:
I'm using a database that has a library for access to it. Connection is done synchronously, it's blocking and I do not have a way to abort it. To connect, I have to write:

var _loader = new DatabaseDriverLoader();
DatabaseDriver _driver = _loader.Connect(connectionString, login, password);

I wanted to improve it:

Be able to connect asynchronously (not waiting for actual connection)
Be able to cancel the connection if I need to

Here's a wrapper that I created:

public class DatabaseConnection : IDisposable
{
    private DatabaseDriver _driver;
    private DatabaseDriverLoader _loader

    public event EventHandler ConnectionFailed;
    public event EventHandler ConnectionEstablished;
    public event EventHandler ConnectionLost;

    public async Task ConnectAsync(string connectionString, string login, string password, CancellationToken cancellationToken)
    {
        var connectionTask = Task.Run(() =>
        {
            try
            {
                var _loader = new DatabaseDriverLoader();
                DatabaseDriver _driver = _loader.Connect(connectionString, login, password);
            }
            catch (Exception e) { }
        });

        await Task.Run(async () =>
        {
            while(!connectionTask.IsCompleted && !cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(100);
            }
        });

        cancellationToken.ThrowIfCancellationRequested();

        if (_driver == null)
        {
            ConnectionFailed?.Invoke(this, EventArgs.Empty);
            return;
        }
        ConnectionEstablished?.Invoke(this, EventArgs.Empty);

        _driver.ConnectionToServerLost += OnConnectionLost;
    }

    public void Dispose()
    {
        if (_driver != null)
        {
            _driver.ConnectionToServerLost -= OnConnectionLost;
            _driver.Dispose();
        }
        _loader?.Dispose();
    }

    public DatabaseDriver GetDriver()
    {
        return _driver;
    }

    private void OnConnectionLost(object sender, EventArgs e) => ConnectionLost?.Invoke(sender, e);
}

Here's how I would use that class:

private async Task ConnectWithDatabase()
 {
  //Delete old connection instance
  _dbConnectionTokenSource?.Cancel();
  if (_dbConnection != null)
  {
      _dbConnection.ConnectionEstablished -= OnDbConnectionEstablished;
      _dbConnection.ConnectionLost -= OnDbConnectionLost;
      _dbConnection.ConnectionFailed -= OnDbConnectionFailed;

      _dbConnection.Dispose();
  }

//Create new connection instance
  _dbConnection = new DatabaseConnection();
  _dbConnection.ConnectionEstablished += OnDbConnectionEstablished;
  _dbConnection.ConnectionLost += OnDbConnectionLost;
  _dbConnection.ConnectionFailed += OnDbConnectionFailed;

  _dbConnectionTokenSource = new CancellationTokenSource();
  var token = _dbConnectionTokenSource.Token;

  try
  {
      await _dbConnection.ConnectAsync(
          ConnectionString,
          Login,
          Password,
          token)
      .ConfigureAwait(false);
  }
  catch (TaskCanceledException e)
  { }
 }

I wanted to ask you kindly for review of this code, because I'm not really sure if this is done correctly.
I don't know if it is a good idea to use an event for successful connection. Maybe Connect method should return successful Task when connection occurs?

I'm not sure if cancellation is done correctly. In my use case there might be situations where DatabaseConection is canceled and disposed before connection occurs successfully.

I am not sure if it's a good idea to create new threads in DatabaseConnection, because clients of this class might not want it? - at least I read somewhere that it's not a good design, but I'm not sure why.

I will be happy to hear any opinion, always good to learn something new.


texts: Extracting first non-null property inside list using Java 8's Optional

texts:
I am writing a Java method to extract a String property, called number, from a Person object.

A Person object has several properties that can be null and number belongs to house, which belongs to addresses, which belongs to metadata which finally belongs to our person.

As addresses is a list of Address objects, I want to extract the first non-null number. That is what I have so far:

public class HouseNumberResolver {
    public static String numberFrom (Person person) {
        return Optional.ofNullable(person)
                .map(Person::getMetadata)
                .map(Metadata::getAddresses)
                .map(HouseNumberResolver::getFirstHouseNumber)
                .orElse("");
    }

    private static String getFirstHouseNumber(List<Address> addresses) {
        for (Address address : addresses) {
            String number = Optional.ofNullable(address)
                    .map(Address::getHouse)
                    .map(House::getNumber)
                    .orElse(null);

            if (number != null) {
                return number;
            }
        }

        return null;
    }
}

However, I feel that this is quite ugly. Ideally, I wanted to have something like:

    private static String getFirstHouseNumber(List<Address> addresses) {
        for (Address address : addresses) {
            Optional.ofNullable(address)
                .map(Address::getHouse)
                .map(House::getNumber)
                .ifPresent(number -> return number)
                .orElse(null)
        }
    }

That would return the number there, but it seems like this is not possible.

Any recommendations are welcome.


texts: Efficiently filter a large (100gb+) csv file (v1)

texts:
EDIT: This question was followed up by this question, with improved code.

I have a set of pretty large files (>2 GB, over 30m rows) containing intraday data in the following format:

TIC, Date, Time, Bid, Offer
AAPL, 20090901, 09:45, 145, 145.5
AAPL, 20090902, 09:45, 145, 145.5
AAPL, 20090903, 09:45, 145, 145.5

I also have a file that contains exactly those dates that I'm interested in, for each firm, like so:

AAPL, 20090902
AAPL, 20090903

Next I want to extract a subset of the large intra-day files, to only keep those firm-days that occur in the dates of interest file. I solved this by creating a dictionary (one for each Ticker), that contains a list of dates as its values. I iterate over each line, and identify whether the current line's date exists in the dictionary.

Is there a faster way of accomplishing this, such as loading in multiple rows per iteration? Would it help to load it directly into a PostgreSQL server and querying it there? It currently runs through ~ 2 GB of data in 180 seconds. I would also appreciate any other feedback.

ROOT_DIR = "C:/Files"
os.chdir(ROOT_DIR)

with open("firm_dates_of_interest.csv") as f:
    d = {}
    lines = f.readlines()
    for line in lines:
        firm = line.split(",")[1]
        d[firm] = []
    for line in lines:
        firm = line.split(",")[1]
        date = line.split(",")[2]
        d[firm].append(date.strip())

for root, dir, files in os.walk(os.path.join(ROOT_DIR, 'Srcfiles'):
    for file in files:
        basename = os.path.splitext(file)[0]
        filename = file

        start = datetime.datetime.now()
        tokeep = []
        for i, line in enumerate(open(os.path.join(root, filename))):
            line = line.split(",")
            if line[0] in d.keys():
                if line[1] in d[line[0]]:
                    tokeep.append(line)
        elapsed = datetime.datetime.now() - start
        print("This file took me " + str(elapsed.seconds) + ' seconds...')

        with open(os.path.join(root, basename+' EXTRACT' + '.csv'), 'w') as f:
            for i, line in enumerate(tokeep):
                f.write(",".join(line))
        tokeep = []


texts: Correct way to refer to a view in Android

texts:
What is the correct way of referring to a view (a) or (b).?

(a).

TextView textView = (TextView) rootView.findViewById(R.id.text);
textView.setText("Some Text");

(b).

((TextView) rootView.findViewById(R.id.text)).setText("Some Text");

I sometimes use the combination of both in my code. Will that affect my structure negatively in any way?

Is there any disadvantage / advantages when using any of those?


texts:
I have written an age calculator that takes a birthDate as input.

I'd like a general review of this. I'm especially concerned about the message variable and the lines after the try/catch statement.

namespace Age
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    Console.Write("Enter your birtdate: ");
                    DateTime birthDate = DateTime.Parse(Console.ReadLine());

                    int Days = (DateTime.Now.Year * 365 + DateTime.Now.DayOfYear) - (birthDate.Year * 365 + birthDate.DayOfYear);
                    int Years = Days / 365;
                    string message = (Days >= 365) ? "Your age: " + Years + " years" : "Your age: " + Days + " days";

                    Console.WriteLine(message);
                }
                catch
                {
                    Console.WriteLine("You have entered an invalid date.\n");
                }

                Console.WriteLine("Exit? (y/n)");
                string userValue = Console.ReadLine();

                if (userValue == "y")
                {
                    Environment.Exit(0);
                }
            }
        }
    }
}


texts: PHP - How can I refactor this store function (which handles different database operation for user types) in order to reduce duplication?

texts:
I'm simply using Slim PHP MVC framework in my API project. PDO::FETCH_ASSOC is used in the database calls. So no data objects. The router handles requests and pass to the controller. controller calls the necessary model to do database operations and response is delivered.

This is the scenario that I want to handle different user types. Each user_type has user_type based specific db transaction to be done. I want to make this more reusable and remove code duplication.

Sorry if there's any wrong thing here, and for my English.

My Route

$this->post('/users/preferences', \UserPreferenceController::class . ':store')

UserPreferenceController => Controller

public function store($request, $response, $args){
    $parsedBody = $request->getParsedBody();
    $user_id = $parsedBody['user_id'];
    $preferences = $parsedBody['preferences'];

    $user = $this->User->getUserInfo($user_id);

    if ($user["type_id"] == 'Admin') {
        $preferenceAdded = $this->User->AddAdminUserPreferences($user_id, $preferences); // DB transaction operation
    } else if ($user["type_id"] == 'Customer') {
        $preferenceAdded = $this->User->AddCustomerUserPreferences($user_id, $preferences); // DB transaction Operation
    } else if ($user["type_id"] == 'Sales') {
        $preferenceAdded = $this->User->AddSalesUserPreferences($user_id, $preferences); // DB transaction Operation
    }

    // return if the transaction is rollbacked
    if(!$preferenceAdded){
        return $response->withJSON([
            "error" => true,
            "message" => "cannot add preferences for user"
            "data" => $user_id
        ]);
    }

    if ($user["type_id"] == 'Admin') {
        $staisticsAdded = $this->User->AddAdminUserPreferencesStatistics($user_id, $preferences); // DB transaction operation
    } else {
        $staisticsAdded = $this->User->AddOtherUserPreferencesStatistics($user_id, $preferences); // DB transaction operation
    }

    // return if the transaction is rollbacked
    if(!$staisticsAdded ){
        return $response->withJSON([
            "error" => true,
            "message" => "cannot add statistics for user"
            "data" => $user_id
        ]);
    }

    return $response->withJSON([
        "error" => false,
        "message" => "operation completed successfully"
        "data" => null
    ]);
}

User.php => User model

public function getUserInfo($user_id)
{
    $sql = "SELECT id, name, email, type_id FROM users WHERE id= :id";
    $stmt = $this->db->prepare($sql);
    $result = $stmt->execute(['id' => $user_id]);
    return $stmt->fetch()[0];
}

public function AddAdminUserPreferences($user_id, $preferences)
{
    $this->db->beginTransaction();

    try {
        // $sql1 execute (common function for every user_type)
        // rollback if $sql1 fails

        // $sql2 execute (a user_type specific function)
        // rollback if $sql2 fails

        $this->db->commit();
        return true;
    } catch(\PDOException $e){
        $this->db->rollBack();
        return false;
    }
}

My Container

$container = $app->getContainer();

$container['UserPreferenceController'] = function ($c) {
    return new App\Controllers\UserPreferenceController($c);
};

$container['User'] = function ($c) {
    return new App\Models\User($c);
};


texts: A Pythonic implementation of Conway's Game of Life

texts:
I've just finished implementing Conway's Game of Life in python-3.6:

import curses
import numpy as np
import time

from collections import defaultdict
from enum import Enum
from typing import List

class State(Enum):
    ''' enum class to represent possible cell states '''
    dead = 0
    alive = 1

class Board:
    ''' Board class to represent the game board '''
    def __init__(self, m : int, n : int, init : List[List[int]]):
        self.m = m   # the number of rows
        self.n = n   # the number of columns
        self.board_ = [
            [State(init[i][j]) for j in range(self.n)] for i in range(self.m)
        ]

    def __str__(self) -> str:
        ''' return the __str__ representation of a Board object
            * represents a live cell, and a space represents a dead one
        '''
        return '\n'.join([
            ''.join(
                    ['*' if cell.value else ' ' for cell in row]
            ) for row in self.board_]
        )

    @property
    def population(self):
        ''' population — the number of live cells on the board '''
        return sum(cell.value for row in self.board_ for cell in row)

    def count_live_neighbours(self, x : int, y : int) -> int:
        ''' count the live neighbours of a cell '''
        count = 0
        for i in range(x - 1, x + 2):
            for j in range(y - 1, y + 2):
                if (i == x and j == y) or i < 0 or j < 0:
                    continue
                # handle IndexErrors raised during invalid indexing operations
                try:
                    count += self.board_[i][j].value
                except IndexError:
                    continue

        return count

    def next_cell_state(self, x : int, y : int) -> State:
        count = self.count_live_neighbours(x, y)
        cur_state = self.board_[x][y]
        # determine the next state based on the current state and
        # number of live neighbours
        if count in {2, 3} and cur_state == State.alive:
            return cur_state
        elif count == 3 and cur_state == State.dead:
            return State.alive

        return State.dead

    def next_board_state(self) -> List[List[State]]:
        ''' return board configuration for the next state '''
        return [
            [self.next_cell_state(i, j) for j in range(self.n)] for i in range(self.m)
        ]

    def advance_state(self):
        ''' update the board configuration with the config for the next state '''
        self.board_ = self.next_board_state()

    def has_live_cells(self) -> bool:
        ''' return whether there are any live cells or not '''
        return any(cell.value for row in self.board_ for cell in row)

if __name__ == '__main__':
    arr = np.random.choice([0, 1], (20, 100), p=[0.90, 0.1])
    board = Board(arr.shape[0], arr.shape[1], init=arr.tolist())

    step = 0
    while board.has_live_cells():
        step += 1
        print(board)
        print('f{step} {board.population}')
        board.advance_state()

        time.sleep(.1)

To run the code, just invoke python3.6 conway.py. The board shape is fixed; but the configuration is randomly generated with NumPy.

My aim with this project was:

Implement a concise and pythonic version of the algorithm
Get better with Python's OOP constructs
Kill time :-)

There are a few redundant functions and properties which felt would be useful at some point of time.

My next step with this program would likely be to host it on a server and let people run it on their browser with a Step and Run button. This might influence how I'd need to structure my code.


texts: Simplifying a Scrabble Word Finder - Python

texts:
I'm very new to coding and am trying to work through projects for practical review of what I know, but I would like to be able to simplify/improve what I've made.

This is a project I saw online that I tried to tackle today.  The task was to create something that would provide a list of the best possible words to play given a set of letters on your rack.

scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
         "x": 8, "z": 10}

def calc_score(word):
    """Calculate the score of a given word."""
    word_score = 0
    for x in word:
        word_score += scores[x]
    return word_score

def look_up():
    """Create the variable containing the master list of words."""
    read_dict = open("sowpods.txt", "r")
    master = read_dict.read()
    read_dict.close()
    master = master.split("\n")
    return master

word_master = look_up()

def rack_check(f_rack):
    """Check the letters in the rack against the SOWPOD dictionary and
    append valid words to a list."""
    valid_list = []
    for item in word_master:
        letter_bank = list(f_rack)
        for letter in item:
            if letter in letter_bank:
                valid = True
                letter_bank.remove(letter)
            else:
                valid = False
                break
        if valid == True:
            valid_list.append(item)
    return valid_list

def dict_maker():
    """Create a dictionary of the words with their scores."""
    valid_dict = {}
    f_list = rack_check(list((raw_input("Letters: ")).lower()))
    for i in f_list:
        valid_dict[i] = calc_score(i)
    return valid_dict

def list_print():
    """Print a list of the words in descending order of value."""
    dict = dict_maker()
    sort_dict = sorted(dict.items(), key=lambda k: k[1], reverse=True)
    for x in sort_dict:
        print x[0], "-", x[1]

list_print()

Calling the "list_print()" function runs through all the other necessary functions, but I feel like it could be cleaner.  Any feedback would be greatly appreciated.


texts:
I am learning F# and implemented Conway's Game of Life as an exercise (There are also other implementations on CodeReview). I have tried to forget all my object-oriented background and practice "functional thinking".

Any feedback is welcome, especially related to alternative (more functional) solutions.

open System

[<EntryPoint>]
let main argv =

    let rows = 30
    let columns = 30
    let size = rows*columns

    let combine listX listY = [
        for x in listX do
        for y in listY do
        yield x, y ]

    let createRandomBoard =
        let rnd = new Random(10)
        [1..size]
        |> List.map (fun x -> if rnd.NextDouble() < 0.2 then 1 else 0)
        |> List.toArray

    let board = createRandomBoard

    let toBoardLine (line : int[]) : string =
        line |> Array.fold (fun agg i -> agg + (if i = 1 then "X" else ".")) ""

    let drawBoard () =
        [0..rows-1]
        |> List.iter (fun y -> printfn "%A" (board.[y*rows..y*rows+columns-1] |> toBoardLine))

    let indexToCoordinates index = (index % columns + 1, index / columns + 1)
    let coordinatesToIndex (x, y) = (y - 1) * columns + (x - 1)

    let getLivingNeighboursCount idx =
        let x, y = indexToCoordinates idx
        let (minX, maxX) = (if x = 1 then columns else x - 1), (if x = columns then 1 else x + 1)
        let (minY, maxY) = (if y = 1 then rows else y - 1), (if y = rows then 1 else y + 1)
        combine [minX; x; maxX] [minY; y; maxY]
        |> List.filter (fun com -> com <> (x,y))
        |> List.map coordinatesToIndex
        |> List.map (fun x -> board.[x])
        |> List.sum

    let indexToNewState idx =
        let state = board.[idx]
        let livingNeigbours = getLivingNeighboursCount idx
        (if livingNeigbours = 3 || (livingNeigbours = 2 && state = 1) then 1 else 0)

    let updateState () =
        [0..size-1]
        |> List.iter (fun idx -> (Array.set board idx (indexToNewState idx)))

    while true do
        Console.Clear();
        updateState ()
        drawBoard ()
        System.Threading.Thread.Sleep(200);

    Console.ReadLine()
    0


texts:
I'd like to find out how I can make my function more efficient:

public boolean addAll(int i, Collection<? extends T> c) {
    for (T x : c)
        add(i++, x);
    return true;
}

public void add(int i, T x) {
    if (n + 1 > a.length) resize();
    System.arraycopy(a, i, a, i+1, n-i);
    a[i] = x;
    n++;
}

protected void resize() {
    T[] b = f.newArray(Math.max(2 * n,1));
    System.arraycopy(a, 0, b, 0, n);
    a = b;
}

I'm not sure what else I can do to implement a more efficient way to use my addAll() function.


texts: Showing the slide named in the query string and hiding the others

texts:
I have this all figured out now thanks to the help of a mod.  Here's the working code:

     <script>
    jQuery(document).ready(function() {
    var queryString = location.search;
    var regEx = new RegExp("slide[0-9]");
    var match = queryString.search(regEx);

    if (match === -1) {
        return;
    }
    else {
        var slideNumber = queryString.substring(match + 5);
        var slide = jQuery('li#slide' + slideNumber);
        var slides = jQuery('li[id^=slide]').not(slide);

        if (slide.length) {
        slides.addClass('hideMe');
        stopSlideShow();
        slide.addClass('lonelySlide').show();
        slide.css('opacity', '1');
        }
    }

    function stopSlideShow() {
        jQuery('.flexslider').flexslider({
            slideshow: false
        });

        jQuery('ol.flex-control-nav.flex-control-paging, a.flex-prev, a.flex-next').hide();
    }
});
</script>

Basically I needed to set variables to remove my DRY code and then create a function for stopping the slider and hiding the slider direction navs and paging dots.  If someone uses a slide number in the query string that doesn't exist, the slideshow will return itself.  If the slide number does exist then it will return the slide requested, stop the slideshow and remove the slide navs and paging dots.  This code was causing a funky fade in issue when it was originally presented to me, so i pulled the stopSlideShow() function out of show() and ran it before show() runs to get rid of the fade in effect.  If anyone else has additional suggestions for the code, that would be great!


texts:
I implemented median filter in Python in order to remove the salt & pepper noise from the images. It is working fine and all but I would love to hear your advice or opinions.

def median_filter(data, filter_size):
    temp = []
    indexer = filter_size // 2
    for i in range(len(data)):

        for j in range(len(data[0])):

            for z in range(filter_size):
                if i + z - indexer < 0 or i + z - indexer > len(data) - 1:
                    for c in range(filter_size):
                        temp.append(0)
                else:
                    if j + z - indexer < 0 or j + indexer > len(data[0]) - 1:
                        temp.append(0)
                    else:
                        for k in range(filter_size):
                            temp.append(data[i + z - indexer][j + k - indexer])

            temp.sort()
            data[i][j] = temp[len(temp) // 2]
            temp = []
    return data


texts: How to apply Python generators to finding min and max values?

texts:
I'm solving yet another problem in HackerRank (https://www.hackerrank.com/challenges/determining-dna-health/problem). In short: you are given 2 arrays (genes and health), one of which have a 'gene' name, and the other - 'gene' weight (aka health). You then given a bunch of strings, each containing values m and n, which denote the start and end of the slice to be applied to the genes and health arrays, and the 'gene'-string, for which we need to determine healthiness. Then we need to return health-values for the most and the least healthy strings.

My solution is below, and it works, but it's not scalable, i.e. it fails testcases with a lot of values.

import re
if __name__ == '__main__':
    n = int(input())

    genes = input().rstrip().split()

    health = list(map(int, input().rstrip().split()))

    s = int(input())
    weights = []
    for s_itr in range(s):
        m,n,gn = input().split()
        weight = 0
        for i in range(int(m),int(n)+1):
            if genes[i] in gn:
                compilt = "r'(?=("+genes[i]+"))'"
                matches = len(re.findall(eval(compilt), gn))
                weight += health[i]*matches
        weights.append(weight)
    print(min(weights), max(weights))

Can you advise on how to apply generators here? I suspect that the solution fails because of the very big list that's being assembled. Is there a way to get min and max values here without collecting them all?

Example values:

genes = ['a', 'b', 'c', 'aa', 'd', 'b']
health = [1, 2, 3, 4, 5, 6]
gene1 = "1 5 caaab" (result = 19 = max)
gene2 = "0 4 xyz" (result = 0 = min)
gene3 = "2 4 bcdybc" (result = 11)

This case returns 0 19

UPD: Follow-up question on optimized (but still not working) solution here.


texts: Matching PEP8 style with long one line for loop

texts:
I'm working with Python 2.7.5 and I'm trying to make it match the PEP8 coding style.  I have a few one line for loops but the issue is that they are each above 80 characters in length. Is it bad practice for me to make them multiple lines for the sake of PEP8?

So should something like this:

patient = ([d['patient'] for d in doctor for s in sections if d == s['doctor']])

Be changed to something like this:

patient = []
for d in doctor:
  for s in sections:
   if d == s['doctor']:
    patient.append(d['patient'])

I find the first code block easier to read but it doesn't follow the PEP8 style guide so I was wondering if you had any tips.


texts: Coding style in Ruby format in an method and variable assign

texts:
Case 1_a:

  zip_file = file.sub(directory, '').sub!(/^\//, '')
  zipfile.add( zip_file, file)

Case 1_b:

  zipfile.add(
    file.sub(directory, '').sub!(/^\//, ''),
    file)

Case 2 : If the String contains lots of parameters , I prefer write in an array.But I'm not sure to have a line break behind [ is better, or not

  def run_remote_focus()

    self.setup_remote_focus()
    created_at=(Time.now.to_f*1000000).to_i.to_s

    settings=[
      "-i #{params[:remote_focu][:ip]}",
      "-u #{params[:remote_focu][:username]}",
      "-p #{params[:remote_focu][:password]}",
      "-s #{params[:RemoteFocu].values.join(':')}",
      "-m #{params[:af_type]}",
      "-t #{params[:remote_focu][:tester]}",
      "-n #{@remote_focu.id}",
      "-c #{created_at}"
    ]

    cmd=["ruby",
         "-I #{@rf[:lib]}",
         "#{@rf[:bin]}",
         " #{settings.join(' ')}"
         ]
    cmd_str=" #{cmd.join(' ').strip()} & "

Case 3 : I can not tell what is the problem, but it just seems weird

@rf={
     folder: "#{Rails.root}#{ENV["module_remote_focus_folder_path"]}",
     bin: "#{Rails.root}#{ENV["module_remote_focus_bin_path"]}",
     lib: "#{Rails.root}#{ENV["module_remote_focus_lib_path"]}"
     }

@rf={folder: "#{Rails.root}#{ENV["module_remote_focus_folder_path"]}",
     bin: "#{Rails.root}#{ENV["module_remote_focus_bin_path"]}",
     lib: "#{Rails.root}#{ENV["module_remote_focus_lib_path"]}"}


texts: JSON Parser, pulls data from a JSON file for analysis

texts:
This is the first time I have programmed something that I will actually personally use, so I am happy about that. I tried to write good code whilst applying functional programming concepts. So no state, and a concise function.

I know that when making the lists it pulls information from the JSON that doesn't get used later in the program. The data will be used once I get continue to develop the program further.

At the end there is a dictionary containing hero ID keys and name values. I cut out most of it to minimize the length of this post.

import json
import requests
def parsestats(herodata):
    return [(hero['heroId'],
    hero['pickBan']['pick']['matchCount']/ # Divide by next line
        herodata['matchPickCount']*1000,
    hero['pickBan']['ban']['matchCount']/  # Divide by next line
        herodata['matchBanCount']*1000,
    hero['pickBan']['pick']['wins']*100,
    hero['pickBan']['ban']['wins']*100,
    hero['pickBan']['pickLastWeek']['matchCount']/ # Divide by next line
        herodata['matchLastWeekPickCount']*1000,
    hero['pickBan']['banLastWeek']['matchCount']/  # Divide by next line
        herodata['matchLastWeekBanCount']*1000,
    hero['pickBan']['pickLastWeek']['wins']*100,
    hero['pickBan']['banLastWeek']['wins']*100)
            for hero in herodata['heroes']]
print(f"{'Hero,':<20}{'Value':>7}")
for hero in sorted(
    [(uni[0], imm[1]*((uni[3] if uni[3] > imm[3] else imm[3])-50))
    for uni, imm in zip(
        sorted(parsestats(json.loads(requests.get(
        'https://api.stratz.com/api/v1/Hero/directory/simple').text))),
        sorted(parsestats(json.loads(requests.get(
        'https://api.stratz.com/api/v1/Hero/directory/simple?rank=8').text))))
    ],
    key=lambda tup: tup[1], reverse = True):
    print("{:<20}{:>7.2f}".format({1: 'Anti-Mage', 2: 'Axe', 3: 'Bane', 4: 'Bloodseeker', 5: 'Crystal Maiden', 6: 'Drow Ranger', 7: 'Earthshaker', 8: 'Juggernaut', 9: 'Mirana', 10: 'Morphling', 11: 'Shadow Fiend', 12: 'Phantom Lancer', 13: 'Puck', 14: 'Pudge', 15: 'Razor', 16: 'Sand King', 17: 'Storm Spirit', 18: 'Sven', 19: 'Tiny', 20: 'Vengeful Spirit', 21: 'Windranger', 22: 'Zeus', 23: 'Kunkka', 25: 'Lina', 26: 'Lion', 27: 'Shadow Shaman', 28: 'Slardar', 29: 'Tidehunter', 30: 'Witch Doctor', 31: 'Lich', 32: 'Riki', 33: 'Enigma', 34: 'Tinker', 35: 'Sniper', 36: 'Necrophos', 37: 'Warlock', 38: 'Beastmaster',39: 'Queen of Pain', 40: 'Venomancer', 41: 'Faceless Void', 42: 'Wraith King', 43: 'Death Prophet', 44: 'Phantom Assassin', 45: 'Pugna', 46: 'Templar Assassin', 47: 'Viper', 48: 'Luna', 49: 'Dragon Knight', 50: 'Dazzle', 51: 'Clockwerk', 52: 'Leshrac', 53: 'Nature\'s Prophet', 54: 'Lifestealer', 55: 'Dark Seer', 56: 'Clinkz', 57: 'Omniknight', 58: 'Enchantress', 59: 'Huskar', 60: 'Night Stalker', 61: 'Broodmother', 62: 'Bounty Hunter', 63: 'Weaver', 64: 'Jakiro', 65: 'Batrider', 66: 'Chen', 67: 'Spectre', 68: 'Ancient Apparition', 69: 'Doom', 70: 'Ursa', 71: 'Spirit Breaker', 72: 'Gyrocopter', 73: 'Alchemist', 74: 'Invoker', 75: 'Silencer', 76: 'Outworld Devourer', 77: 'Lycan', 78: 'Brewmaster', 79: 'Shadow Demon', 80: 'Lone Druid', 81: 'Chaos Knight', 82: 'Meepo', 83: 'Treant Protector', 84: 'Ogre Magi', 85: 'Undying', 86: 'Rubick', 87: 'Disruptor', 88: 'Nyx Assassin', 89: 'Naga Siren', 90: 'Keeper of the Light', 91: 'Io', 92: 'Visage', 93: 'Slark', 94: 'Medusa', 95: 'Troll Warlord', 96: 'Centaur Warrunner', 97: 'Magnus', 98: 'Timbersaw', 99: 'Bristleback', 100: 'Tusk', 101: 'Skywrath Mage', 102: 'Abaddon', 103: 'Elder Titan', 104: 'Legion Commander', 105: 'Techies', 106: 'Ember Spirit', 107: 'Earth Spirit', 108: 'Underlord', 109: 'Terrorblade', 110: 'Phoenix', 111: 'Oracle', 112: 'Winter Wyvern', 113: 'Arc Warden', 114: 'Monkey King', 119: 'Dark Willow', 120: 'Pangolier',
        121: 'Grimstroke', 129: 'Mars'}[hero[0]], hero[1]))


texts: Number to german decimal format converter function

texts:
I have a function that formats a number (even a float) to a  German decimal format. I got this function from here https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript and it works. But every time I want to format a number that I stored in a variable I have to add .format(2, 3, '.', ',').

EX: I have an int :45122.9 and I want to format it I have this function:

Number.prototype.format = function(n, x, s, c) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
        num = this.toFixed(Math.max(0, ~~n));

    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};
var netto=45122.9;
document.write(netto.format(2, 3, '.', ',')+ ' ' +'€');

This will format my number as such 45.122,90  €.

Is there a way to name the function, let´s say... "formatNumber", add this part to it format(2, 3, '.', ',') and than just call it like this: document.write(formatNumber(netto)); ?


texts: Sieve of Sundaram for Project Euler 7: Python implementation slower than C++ and R

texts:
A friend of mine recently started learning R, and she complained to me that R is very slow. She was working on Project Euler Problem 7, which asks for the value of the 10001st prime number. For comparison, I decided to write the exact same program in C++ (which I use most frequently), R (which I do not use regularly, but used for comparison), and Python (because I wanted to advise her to switch her learning from R to Python).

The program follows these steps:

Find the upper bound on the Nth prime.
Fill a prime number sieve (Sieve of Sundaram) large enough to capture the upper bound.
Count the primes in the prime number sieve until the Nth prime is found.

To my surprise, the Python solution was significantly slower than the R version. Here are the results from time for the three implementations:

C++: real 0.002s, user 0.001s, sys 0.001s
R: real 2.239s, user 2.065s, sys 0.033s
Python: real 13.588s, user 13.566s, sys 0.025s

I tried using numpy arrays instead of lists, but to little effect.

I would appreciate an explanation of why the Python implementation is so slow relative to the other two. I would also appreciate tips on how to use lists in R and Python more efficiently. Is there a better way to do this?

C++:

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

const int N = 10001;

int main()
{
  int max = floor(N*(log(N) + log(log(N))));
  vector<bool> marked(max/2, false);
  for (size_t i = 1; i < marked.size(); i++) {
    for (size_t j = 1; j <= i; j++) {
      size_t m = i + j + 2*i*j;
      if (m < marked.size()) {
        marked[m] = true;
      } else {
        break;
      }
    }
  }
  int count = 1;
  for (size_t m = 1; m < marked.size(); m++) {
    if (not marked[m]) count++;
    if (count == N) {
      cout << 2*m + 1 << endl;
      break;
    }
  }
  return 0;
}

R:

n <- 10001
max <- n*(log(n) + log(log(n)))
marked <- vector(mode="logical", length=max/2)
for (i in 1:length(marked)) {
  for (j in 1:i) {
    m <- i + j + 2*i*j
    if (m > length(marked)) break
    marked[m] <- T
  }
}
count <- 1
for (i in 1:length(marked)) {
  if (!marked[i]) count <- count + 1
  if (count == n) {
    print(2*i + 1)
    break
  }
}

Python:

from math import log

n = 10001
max = n*(log(n) + log(log(n)))
marked = [False] * int(max/2)
for i in range(1, len(marked)):
    for j in range(1, i + 1):
        m = i + j + 2*i*j
        if m > len(marked):
            break
        marked[m] = True
count = 0
for i in range(0, len(marked)):
  if not marked[i]:
      count += 1
  if count == n:
      print 2*i + 1
      break


texts: Loading content from external HTML files

texts:
I'm using jQuery's .get() method to load content from external HTML files into my main index file. I created 25 different functions, function videoLoad1(), function videoLoad2() etc, for the 25 videos that I'm loading separately when its corresponding link is clicked. The content that is being swapped out in my HTML index file is the video src and video details. I'm new to jQuery and have been trying to find a more practical way of writing the code.

HTML - links for the onclick function:

cars.com: be honest

cars.com: tag

HTML for video inclusion:

External HTML file that is being loaded via $.get() (file name is cars_bh.html):

Video

Now Playing

cars.com: be honest

<video id="kz-player" width="100%" height="100%" controls preload>
    <source src="vid/CarscomBeHonest.mp4"  type='video/mp4;'>
    <source src="vid/CarscomBeHonest.webmhd.webm" type='video/webm;'>
    <source src="vid/CarscomBeHonest.oggtheora.ogv"  type='video/ogg;'>
</video>

jQuery function:

function videoLoad2() {

$("a#cars_hb").click(function(e) {
e.preventDefault();
e.stopPropagation();
$.get('cars_hb.html', function( data ) {
  $('#kz-video').html( data );
  });
});

//close overlay/hide content
$('.close').click(function (e) {
e.stopPropagation();
$('#kz-player')[0].pause();
$('#kz-video').hide();
$('.close').fadeOut(800);
$('#video_overlay').fadeOut(800);
});
}


texts: Inserting and updating time spans in XML

texts:
I need help to refactor my code. I usually had a hard time figuring out how to make my code reusable.

I have an XML file that hold the data for each Tag element. Tag element should have child nodes LastClocked, and TotalClocked. I first thought of creating Tag object and do serialization. But, I found Linq to XML is much easier. I would really appreciate if you guys can tell me what to improve for my code.

namespace StopWatch.Models
{
    public class TagCollection
    {
        private XElement doc;
        private IEnumerable<XElement> tagElements;

        public TagCollection()
        {
            if(File.Exists("TagsData.xml"))
            {
               doc = XElement.Load("TagsData.xml");
            }
            else
            {
                //TODO: Create XML
            }
        }

        public void Save(TimeSpan clocked, string tags)
        {
            tagElements = from t in doc.Elements("Tag")
                          where (string)t.Attribute("Name") == tags
                          select t;

            TimeSpan lastClocked = TimeSpan.Parse((string)
                                   (from lc in tagElements.Descendants("LastClocked")
                                    select lc).First());

            lastClocked = lastClocked.Add(clocked);

            if (!tagElements.Any())
            {
                Insert(clocked, tags);
            }
            else
            {
                Update(clocked, lastClocked);
            }

            doc.Save("TagsData.xml");
        }

        private void Update(TimeSpan clocked, TimeSpan lastClocked)
        {
            foreach(XElement tagElement in tagElements)
            {
                tagElement.SetElementValue("LastClocked", clocked.ToString());
                tagElement.SetElementValue("TotalClocked", lastClocked.ToString());
            }
        }

        private void Insert(TimeSpan clocked, string tags)
        {
            XElement newTag = new XElement("Tag",
                                    new XAttribute("Name", tags),
                                    new XElement("LastClocked", clocked.ToString()),
                                    new XElement("TotalClocked", clocked.ToString()));

            doc.Add(newTag);
        }
    }
}


texts:
I have a few classes that form a class hierarchy where some objects point to others. In the usual case, I create these object on the stack.  In other cases, I need to clone these object to do some temporary work so as not to affect the original set.

For the case where one object points to another, if the objects are located in the heap, then the "pointer" object should delete the "pointee" upon destruction; if the objects are located on the stack, then, of course, no objects should delete'd.

Hence, I want objects to know be "heap aware," i.e., know whether they were allocated in the heap vs. the stack.  Here is a base class such that other classes can derive from to know:

/**
 * A %heap_aware_impl implements the ability to know whether an object (that is
 * not part of an array) resides in heap memory via \c new or on the stack.
 */
class heap_aware_impl {
public:
  /**
   * An explicit no-op assignment operator is needed because the \c const data
   * member makes the compiler delete the auto-generated one.  We should
   * allow assignment of derived class objects, but in what memory the object
   * was created must remain fixed.
   */
  heap_aware_impl& operator=( heap_aware_impl const& ) {
    return *this;
  }

  /**
   * Gets whether this object resides in the heap and can be explicitly deleted
   * by deleting a pointer to it.
   *
   * @return Returns \c true only if this object resides in the heap; \c false
   * only if it resides on the stack.
   */
  bool can_delete() const {
    return in_heap_;
  }

public:
  void* operator new( size_t size ) {
    next_in_heap_ = true;
    return ::operator new( size );
  }

  void* operator new( size_t size, std::nothrow_t const &nothrow ) noexcept {
    next_in_heap_ = true;
    return ::operator new( size, nothrow );
  }

#ifndef NDEBUG
  void operator delete( void *p ) {
    assert( next_in_heap_ );
    next_in_heap_ = false;
    ::operator delete( p );
  }
#endif /* NDEBUG */

protected:
  heap_aware_impl() : in_heap_( next_in_heap_ ) {
    next_in_heap_ = false;
  }

#ifndef NDEBUG
  /**
   * This is intentionally non-virtual since nobody will delete an object via a
   * pointer to a %heap_aware_impl.  Derived classes can have their destructors
   * virtual.
   */
  ~heap_aware_impl() {
    next_in_heap_ = in_heap_;
  }
#endif /* NDEBUG */

private:
  bool const in_heap_;
  static thread_local bool next_in_heap_;
};

thread_local bool heap_aware_impl::next_in_heap_ = false;

/**
 * A %heap_aware is the public API class.  It takes care of doing virtual
 * inheritance from %heap_aware_impl so further derived classes can't forget.
 */
struct heap_aware : virtual heap_aware_impl {
};

Thoughts?