texts:
I'm writing a little tool for mangling MP3 collections and, as a challenge, I decided to write in in Hy, a dialect of Python that uses Lisp syntax.  Like every good developer, I wrote out my list of policies that I want the tool to obey: "If the user doesn't specify a genre on the command line, use the most popular genre found in all ID3 tags in this directory," "If the user doesn't specify an album name and the most popular album is an empty string, try to derive the album name from the directory."

When I was writing that, I realized that the filter for each file's fields could be expressed as an anonymous function over the collection that contains the knowledge on what to do on a per-file basis, based upon the various policies:

(defn make-artist-deriver [opts found likely]
  (cond [(.has_key opts "artist") (fn [tag file] (get opts "artist"))]
        [(.has_key opts "usedir") (fn [tag file] found)]
        [true (fn [tag file] (or tag (sfix found) (sfix likely)))]))

(defn make-album-deriver [opts found likely]
  (cond [(.has_key opts "album") (fn [tag file] (get opts "album"))]
        [(.has_key opts "usedir") (fn [tag file] found)]
        [true (fn [tag file] (or (ascii-or-nothing likely) (sfix found)))]))

(defn make-genre-deriver [opts found likely]
  (cond [(.has_key opts "genre") (fn [tag file] (get opts "genre"))]
        [true (fn [tag file] likely)]))

(defn make-title-deriver [opts found likely]
  (cond [(.has_key opts "usefilename") (fn [tag file] (title-strategy file))]
        [true (fn [tag file] (or tag (title-strategy file)))]))

This seems like the right way to do things, with each function having the same type signature, and each generated function having the same type signature, so that at the end all I do is run the generated functions through a map-of-files of a map-of-fields of the entries.  The user can see the various policies, and it works.

I'm new to Lisp, and I've never seen an example of what I'm doing here.  Not in Clojure, or Steel Bank, or Racket, and I have been reading a lot of Lisp in the past couple of months.  I can see what I'm doing throughout the code, but I'm afraid that my code might be idiosyncratic and strongly influenced by closure-heavy languages like JavaScript, which is what I write professionally.

Is what I've written idiomatically correct?  Am I writing maintainable code?

The whole example can be found at here.


texts:
I have a function here and wondered how well this can be refactored.

I currently have this:

status=`git status 2>&1 | tee`
dirty=`echo -n "${status}" 2> /dev/null | grep "modified:" &> /dev/null; echo "$?"`
untracked=`echo -n "${status}" 2> /dev/null | grep "Untracked files" &> /dev/null; echo "$?"`
ahead=`echo -n "${status}" 2> /dev/null | grep "Your branch is ahead of" &> /dev/null; echo "$?"`
newfile=`echo -n "${status}" 2> /dev/null | grep "new file:" &> /dev/null; echo "$?"`
renamed=`echo -n "${status}" 2> /dev/null | grep "renamed:" &> /dev/null; echo "$?"`
deleted=`echo -n "${status}" 2> /dev/null | grep "deleted:" &> /dev/null; echo "$?"`
bits=''
if [ "${renamed}" == "0" ]; then
  bits=">${bits}"
fi
if [ "${ahead}" == "0" ]; then
  bits="*${bits}"
fi
if [ "${newfile}" == "0" ]; then
  bits="+${bits}"
fi
if [ "${untracked}" == "0" ]; then
  bits="?${bits}"
fi
if [ "${deleted}" == "0" ]; then
  bits="x${bits}"
fi
if [ "${dirty}" == "0" ]; then
  bits="!${bits}"
fi
if [ ! "${bits}" == "" ]; then
  echo " ${bits}"
else
  echo ""
fi

I have played with it a little bit but I'm not an expert with bash so refactoring this is a little tricky, here is my attempt:

gitstatus=(
  "renamed;renamed:;>"
  "dirty;modified:;!"
  "untracked;Untracked files;?"
  "ahead;Your branch is ahead of;*"
  "newfile;new file:;+"
  "deleted;deleted:;x"
)

bits=''

for status in "${gitstatus[@]}"; do

  value=(${status//;/ })
  check=`echo -n "${value[0]}" 2> /dev/null | grep "${value[1]}" &> /dev/null; echo "$?"`

  if [ "${check}" == "0" ]; then
    bits="${value[2]}${bits}"
  fi

done

if [ ! "${bits}" == "" ]; then
  echo " ${bits}"
else
  echo ""
fi


texts: Performance for simple code that converts a RGB tuple to hex string

texts:
I'm rewriting a full color Mandelbrot Set explorer in Python using tkinter. For it, I need to be able to convert a Tuple[int, int, int] into a hex string in the form #123456. Here are example uses of the two variants that I came up with:

>>>rgb_to_hex(123, 45, 6)
'#7b2d06'

>>>rgb_to_hex(99, 88, 77)
'#63584d'

>>>tup_rgb_to_hex((123, 45, 6))
'#7b2d06'

>>>tup_rgb_to_hex((99, 88, 77))
'#63584d'

>>>rgb_to_hex(*(123, 45, 6))
'#7b2d06'

>>>rgb_to_hex(*(99, 88, 77))
'#63584d'

The functions I've come up with are very simple, but intolerably slow. This code is a rare case where performance is a real concern. It will need to be called once per pixel, and my goal is to support the creation of images up to 50,000x30,000 pixels (1500000000 in total). 100 million executions take ~300 seconds:

>>>timeit.timeit(lambda: rgb_to_hex(255, 254, 253), number=int(1e8))
304.3993674000001

Which, unless my math is fubared, means this function alone will take 75 minutes in total for my extreme case.

I wrote two versions. The latter was to reduce redundancy (and since I'll be handling tuples anyways), but it was even slower, so I ended up just using unpacking on the first version:

# Takes a tuple instead
>>>timeit.timeit(lambda: tup_rgb_to_hex((255, 254, 253)), number=int(1e8))
342.8174099

# Unpacks arguments
>>>timeit.timeit(lambda: rgb_to_hex(*(255, 254, 253)), number=int(1e8))
308.64342439999973

The code:

from typing import Tuple

def _channel_to_hex(color_val: int) -> str:
    raw: str = hex(color_val)[2:]
    return raw.zfill(2)

def rgb_to_hex(red: int, green: int, blue: int) -> str:
    return "#" + _channel_to_hex(red) + _channel_to_hex(green) + _channel_to_hex(blue)

def tup_rgb_to_hex(rgb: Tuple[int, int, int]) -> str:
    return "#" + "".join([_channel_to_hex(c) for c in rgb])

I'd prefer to be able to use the tup_ variant for cleanliness, but there may not be a good way to automate the iteration with acceptable amounts of overhead.

Any performance-related tips (or anything else if you see something) are welcome.


texts:
The following searches recursively for all the mark down files - i. ending with the extension .md - inside a folder. It then stores the text of the files in an array. Finally, it sums their word count using a wordCount() function (from the compromise package).
import nlp from 'compromise'
import fs from 'fs'
import path from 'path'

const filePaths = searchRecursive(`${__dirname}/test`, '.md')

const fileTexts = filePaths.map((filePath: string) => {
    return fs.readFileSync(filePath, 'utf-8')
}) // -> ['one two', 'one two three']

let totalWordCount = 0

fileTexts.forEach((fileText: string) => {
    totalWordCount += nlp(fileText).wordCount()
})

console.log(totalWordCount) // -> 5

function searchRecursive (dir: string, pattern: string) {
    ...
}

I've heard that forEach shouldn't be used in functional programming. How can I modify this code so it doesn't use forEach?


texts:
I wrote a simple Pomodoro Timer in Python 3:

from datetime import datetime, timedelta
from gi import require_version
require_version('Notify', '0.7')
from gi.repository import Notify
import sys

class State:
    #length: the length of the state in minutes
    def __init__(self, length):
        if not length == None:
            self.length = length

class Clock:
    work = None
    sBreak = None
    lBreak = None

    numWork = 4
    remWork = numWork #number of work sessions remaining
    remBreaks = numWork - 1 #number of short break sessions remaining
    current = None #the current state
    endtime = None #datetime object for end time of current

    def __init__(self, workTime, sBreakTime, lBreakTime):
        if workTime == None or sBreakTime == None or lBreakTime == None:
            exit(1)
        self.work = State(workTime)
        self.sBreak = State(sBreakTime)
        self.lBreak = State(lBreakTime)
        self.states = [self.work, self.sBreak, self.lBreak]

    def change(self):
        if not self.current == None and not self.current in self.states:
            exit(1)

        title = ''
        timeStr = 'End Time: '

        #current doesn't exist: start the first work period
        if self.current == None:
            self.current = self.work
            title = 'Work Period'

        #in work state now: either short or long break
        elif self.current == self.work:
            self.remWork -= 1
            if self.remBreaks == 0:
                self.current = self.lBreak
                title = 'Long Break'
            else:
                self.current = self.sBreak
                title = 'Short Break'
        #in short break now: start work
        elif self.current == self.sBreak:
            self.remBreaks -= 1
            self.current = self.work
            title = 'Work Period'
        #in long break now: reset number of work and short break periods
        elif self.current == self.lBreak:
            self.current = self.work
            title = 'Work Period'
            self.remWork = self.numWork
            self.remBreaks = self.numWork - 1
        self.endtime = datetime.now() + timedelta(seconds = self.current.length)
        timeStr +=  self.endtime.strftime("%H:%M")
        Notify.init("a")
        notifyme=Notify.Notification.new(title,timeStr)
        notifyme.show()

    def tickTock(self):
        self.change()
        while True:
            if datetime.now() >= self.endtime:
                self.change()

def main():
    try:
        lengths = sys.argv[1:]
        workLen = int(lengths[0])
        sbLen = int(lengths[1])
        lbLen = int(lengths[2])

        clock = Clock(workLen, sbLen, lbLen)
        clock.tickTock()
    except:
        print("One or more arguments were invalid.")
        exit(1)

if __name__ == '__main__':
    main()

First of all, is this a good way to simulate the timer? Also, is there a way to get around using self.variable_name every time I want to use a variable in the Clock class? Finally, what would be a good package to look into if I wanted to extend this into a GUI application?


texts: Check if specific key exists in 2-dimensional array

texts:
I am writing a "collision detection" in PHP and want to check if a specific "area" is still free in the two-dimensional target array.

I use the following code to do that, but I think there might be a better (= faster) solution than looping over every possible position in the array and check whether it's set or not.

public function CheckForCollision($top, $left, $size, $collision_array) {

       $possible_x = range($left, $left+$size-1);
       $possible_y = range($top, $top+$size-1);

       // Slow solution, improve this: Check every possible value in the $collision_array with our "might be"-values
       foreach($possible_x as $x)
       {
          foreach($possible_y as $y)
          {
             if($collision_array[$x][$y] == 1) { return false; break; }
          }
       }

       return true;
    }

Any ideas on this?


texts:
I'd like a review of Haskell tree heap code in Turning a tree into a heap in Haskell.

module Heapify where

data Tree a = Leaf a | Node (Tree a) a (Tree a)
   deriving Show

ourTree = Node (Node (Leaf 8) 2 (Leaf 4))  3  (Node (Leaf 1) 7 (Leaf 9))

atTop :: Tree a -> a
atTop (Leaf a) = a
atTop (Node _ a _) = a

replaceTop :: Ord a => Tree a -> a -> Tree a
replaceTop (Leaf _) a = Leaf a
replaceTop (Node l _ r) a = heapify (Node l a r)

adjustLeft :: Ord a => Tree a -> Tree a
adjustLeft (Leaf a) = Leaf a   -- But we shouldn't ask to do this.
adjustLeft  node@(Node l a r)
     | topL <= a = node
     | otherwise = Node (replaceTop l a) topL r
         where topL = atTop l

adjustRight :: Ord a => Tree a -> Tree a
adjustRight (Leaf a) = Leaf a   -- But we shouldn't ask to do this.
adjustRight  node@(Node l a r)
     | topR <= a = node
     | otherwise = Node l topR (replaceTop r a)
         where topR = atTop r

doTop :: Ord a => Tree a -> Tree a
doTop (Leaf a) = Leaf a
doTop node@(Node l a r)
    | atTop l > atTop r = adjustLeft node
    | otherwise         = adjustRight node

heapify :: Ord a => Tree a -> Tree a
heapify (Leaf a) = Leaf a
heapify (Node l a r) = doTop (Node (heapify l) a (heapify r))


texts:
The problem can be viewed here, since it's styled. I don't think I should just copy and paste.

I implemented recessive function and dynamic programming to solve it. It can successfully passed UVa Judge with a score of 612ms, but it's not fast enough for this site. Which test my code against 200000 lines of input, and giving only 2s.

#include <cstdio>
#include <iostream>

int cycleLength(long long int);

int cycleLengthResult[1000001];

int main(int argc, char *argv[])
{
    int i = 0, j = 0, cur = 0, max = 0, k = 0, s = 0;
    for (i = 1 ; i < 1000001 ; ++ i ) cycleLength(i);

    while ( scanf("%d%d", &i, &j) != EOF )
    {
        printf("%d %d ", i, j);
        if ( i > j )
        {
            s = i;
            i = j;
            j = s;
        }
        max = 0;
        for ( k = i ; k <= j ; ++ k )
        {
            cur = cycleLengthResult[k];
            if (cur > max) max = cur;
        }
        printf("%d\n", max);
    }

    return 0;
}

int cycleLength(long long int arg)
{
    if ( arg > 1000000 )
    {
        if (!(arg & 1))
            return 1 + cycleLength(arg/2);
        else
            return 1 + cycleLength(arg*3+1);
    }
    if (!cycleLengthResult[arg])
    {
        int valueForArg = 0;
        if (arg == 1)
            valueForArg = 1;
        else if (!(arg & 1))
            valueForArg = 1 + cycleLength(arg/2);
        else
            valueForArg = 1 + cycleLength(arg*3+1);

        cycleLengthResult[arg] = valueForArg;
    }
    return cycleLengthResult[arg];
}


texts: Get RSS feeds and store them into database

texts:
It is my first program in Clojure. It read RSS feed's list from text file, get each feed and store  result into sqlite database.

project.clj:

(defproject cowl "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.8.0"],
                 [org.clojars.scsibug/feedparser-clj "0.4.0"]
                 [org.clojure/java.jdbc "0.3.7"]
                 [org.xerial/sqlite-jdbc "3.7.2"]]
  :main cowl.core/fetch
)

core.clj:

(ns cowl.core
  (:require [cowl.rss :as rss]
            [cowl.db :as db]))

(defn fetch []

  "Fetch information from RSS and store it to DB"

  (with-open [r (clojure.java.io/reader "settings\\feed-list.txt")]
    (doseq [line (line-seq r)
           entry (rss/process-feed line)]

      (db/insert-entity (:title entry) (:link entry) (:source entry)))))

entity.clj:

(ns cowl.entity)

(defn make-entity [title, link, source]
    {:title title, :link link, :source source})

rss.clj:

(ns cowl.rss
  (:require
    [cowl.entity :as entity]
    [cowl.db :as db]
    [feedparser-clj.core :as rss]))

(defn construct-entry [source, entry]
    (entity/make-entity (:title entry) (:link entry) source))

(defn process-feed [url]

    "Gets the feed URL and returns list of entites"
    (let [feed (rss/parse-feed url)
        construct-foo (partial construct-entry (:title feed))]

        (map construct-foo (:entries feed))))

db.clj:

(ns cowl.db
  (:require
    [clojure.java.jdbc :as sql]))

(def db {:classname "org.sqlite.JDBC", :subprotocol "sqlite", :subname "work.db"})

(defn create-db []
  (sql/execute! db ["drop table if exists entities"])
  (let [q (sql/create-table-ddl :entities
                                [:title :text]
                                [:link :text :primary :key]
                                [:source :text])]
  (sql/execute! db [q])))

(defn insert-entity [title, link, source]
    (let [result (sql/update! db :entities { :title title :source source} ["link=?" link])]
        (if (zero? (first result))
            (sql/insert! db :entities { :title title :link link :source source}))))

(defn get-records []
    (sql/query db "select id, title, link, source from entities"))


texts:
I'm a beginner at JavaScript and I'm working on building a mini-framework just to become familiar with what good code looks like.  In my application I often have the need for the user to enter in a list of things they want to send to the server for querying purposes.  So currently I have this fiddle.  When I user enters in something into the text box the JS will check to see if that item has already been entered and disallow it if it has, or it will add the text entered into the text box and the user can see what they're going to send to the server (that part is taken out for brevity's sake).  I know this isn't quite there, but I would like to do something like $('#control').holder(optionsForHolderControl) and allow the behavior to be as dynamic as possible.  While I know that I'm not quite there yet, I would like to know what the experts out there would change about my code as it stands right now (organization, is it OK to have these closures in there, do the functions need to be properties, etc).

$(document).ready(function () {
    $('#textButton').click(function () {
        var options = {
            button: '#textButton',
            textBox: '#textBox',
            catcher: '#catcher'
        };
        //fxn call
        stick($(options.textBox), options.catcher);
    });
    //this takes text entered into a text box and makes a div with a strip class
    //and puts it inside the holder div
    function stick(textBox) {
        /***********variables*****************/
        var text = $(textBox).val();
        var holderArray = [];
        //gets all of the text elements
        $('.holder .strip').each(function () {
            holderArray.push($(this).text());
        });
        /*************functions***************/
        function addStrip() {
            var $strip = $('<div>').text(text).appendTo(catcher).addClass('strip');
        }

        function clearTextbox() {
            $(textBox).val('');
            $(textBox).focus();
        }
        //duplicates aren't allowed in the holder container
        if ($.inArray(text, holderArray) != -1) {
            alert('that item has already been entered');
        }
        else {
            addStrip();
        }
        clearTextbox();
    };
});


texts:
I am looking to improve my code structure. In this code it is opening all the links with ?pid= in the url. However, the structure of the code can be improved.

for a in self.soup.find_all(href=True):
    href = a['href']
    if not href or len(href) <= 1:
        continue
    if href[0] == '/':
        href = (domain_link + href).strip()
        if href.lower().find("?pid=") != -1:
            href = href.strip()
        elif 'javascript:' in href.lower():
            continue
        elif 'reviews' in href.lower():
            continue
    elif href[:4] == 'http':
        if href.lower().find("?pid=") != -1:
            href = href.strip()
    elif href[0] != '/' and href[:4] != 'http':
        href = ( domain_link + '/' + href ).strip()
        if href.lower().find("?pid=") != -1:
            href = href.strip()
    if '#' in href:
        indx = href.index('#')
        href = href[:indx].strip()
    if href in links:
        continue
    links.append(self.re_encode(href))
self.dict['a_href'] = links


texts:
Is it possible to reify the graph of lambda terms expressed as parametric HOAS. Not quite sure if it is

data PLambda a where
   Var   ∷ a → PLambda a
   Lam   ∷ (a  → PLambda a) → PLambda a
   App   ∷ PLambda a  → PLambda a  → PLambda a

newtype Lambda = Hide { reveal ∷ ∀ a. PLambda a}

data PLambdaNode a n where
   GraphVar ∷ a → PLambdaNode a n
   GraphLam ∷ (a → PLambdaNode a n) → PLambdaNode a n
   GraphApp ∷ n → n → PLambdaNode a n

instance MuRef (PLambda a) where
  type DeRef (PLambda a) = PLambdaNode a
  mapDeRef :: Applicative f => (forall b. (MuRef b, DeRef (PLambda a) ~ DeRef b) => b -> f u) -> PLambda a -> f (PLambdaNode a u)
  mapDeRef f (Var x) = pure $ GraphVar x
  mapDeRef f (Lam l) =  let
               b = (\a → f (l a ∷ PLambda a)) -- a → f u
             in GraphLam <$> (undefined ∷ f (a → PLambdaNode a u))
  mapDeRef f (App l x) =  GraphApp  <$> f l <*> f x


texts:
I have made a LinkedList class. This is a singly-linked-list and I want to make a forward_iterator for this class without using Boost. I have made the code and I want to know whether I have implemented it correctly. The source I referred to make this code is here.

template <class T>
struct node
{
    T data;
    node *next;
};

template <class T>
class LinkedList
{
    private :
    node<T> *start;
    unsigned int numElements;
    // Assume all functions are implemented
};

Iterator Code :

class iterator : public std::iterator<std::forward_iterator_tag,node<T>*>
{
    node<T>* itr;

    public :

    iterator (node<T>* temp) : itr(temp) {}
    iterator (const iterator& myitr) : itr(myitr.itr) {}
    iterator& operator++
    {
        itr = itr->next;
        return *this;

    }
    bool operator== (const iterator& rhs)
    {
        return itr == rhs.itr;

    }
    bool operator!= (const iterator& rhs)
    {
        return itr != rhs.itr;

    }
    T& operator*()
    {
        return itr->data;
    }

};

Is the above implementation correct? If not, then what changes should I make?  Also, does anything else need to be implemented?


texts: Skiena's Programming Challenges: The Trip problem

texts:
I have the following solution for the Trip problem from Skiena's and Revilla's Programming Challenges (full problem description here).

#include <stdio.h>

double truncate_to_2_decimals(double n)
{
    return (double)((int)(n*100.0)) / 100.0;
}

double mean(int n, double numbers[])
{
    double r;
    int i;
    for(i = 0; i < n; i++) {
        r += numbers[i];
    }
    return r / (double)n;
}

double min_exchange(int n, double expenses[])
{
    double r;
    double mu = mean(n, expenses);
    int i;
    for(i = 0; i < n; i++) {
        double e = expenses[i];
        if(e < mu) {
            r += mu - e;
        }
    }
    return truncate_to_2_decimals(r);
}

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

    while(scanf("%d", &n_students) != EOF) {
        if(n_students == 0) {
            break;
        }
        double expenses[n_students];
        int i;
        for(i = 0; i < n_students; i++) {
            scanf("%lf", &expenses[i]);
        }
        printf("$%.2lf\n", min_exchange(n_students, expenses));
    }
    return 0;
}

The solution handles both the sample input and the following "tricky" input correctly:

4
9999.10
9999.10
9999.00
9999.10
3
1.01
0.99
0.99
0

Output:

$0.07
$0.01

Yet for some reason the online judge returns a "Wrong Answer" error. What could I be missing?


texts: Best way to include image_tag inside link_to

texts:
What is the most elegant and readable way to in include (potentially long) image_tag calls inside of link_to?

Example

<%= link_to image_tag('buckminsterfullerene.png', width: '210', height: '60', alt: 'Molecular structure of Buckminsterfullerene'), 'some_long_path.html', title: 'Buckminsterfullerene', rel: 'tooltip', relative: true %>


texts:
The following is a function that takes an area as an input and outputs some resulting calculations.

I thought an object was useful for creating multiple instances with different custom properties overwriting the defaults to make comparisons easy.

The getter and the setters are there so when one property is updated the update() is run to make sure all related properties are updated too.

I have a few of these relatively complicated models to turn from excel sheets into javascript functions so any advice on using many variable and interconnected properties or just the overall code would really be helpful.

function Cistern (inArea){
    // Private
    var _this = this,
        _type = 'Cistern';

    this.getType = function(){
        return _type;
    }

    // Public properties
    this.precipitationPerEvent = 0;
    this.totalStorageNeeded =  0;
    this.tankCost = 0;
    this.systemBaseCost = 0;

    // Public Variables & Defaults
    var properties = {
        area: inArea,
        maxRainEvent: 2,
        tankType: 'C',
        primaryUse: 'O',
        buildingStories: 3,
        fixtureNumber: 10,
        maintenanceLevel: 'M'
    }

    this.update = function(){
        var tankCostPerGallon = 0,
            pumpSize = 0,
            pumpCost = 0;
        // Storage Volume
        _this.precipitationPerEvent = Math.ceil(_this.area*(_this.maxRainEvent/12) * 7.48);
        _this.totalStorageNeeded = Math.ceil((_this.precipitationPerEvent / 100)) * 100;
        // Capital Costs
        if (_this.tankType === 'C'){
            tankCostPerGallon = 1.66;
        } else if (_this.tankType === 'P'){
            tankCostPerGallon = 1.43;
        } else if (_this.tankType === 'S'){
            tankCostPerGallon = 2.51;
        } else if (_this.tankType === 'F'){
            tankCostPerGallon = 1.33;
        }
        _this.tankCost = _this.totalStorageNeeded * tankCostPerGallon;
        if (_this.primaryUse === 'I'){
            pumpSize = Math.ceil(((62.4 * (_this.buildingStories * 10) * (_this.fixtureNumber * this.buildingStories * 0.00891))/550)/0.5);
        } else {
            pumpSize = 0.5;
        }
        pumpCost = -100.71 * Math.pow(pumpSize, 2) + 1327.7 * pumpSize - 39.38;
        _this.systemBaseCost = Math.ceil(_this.tankCost + (_this.tankCost * 0.6) + pumpCost);
        if (_this.primaryUse === 'I'){ _this.systemBaseCost += 2250};
    }

    // Build Getters & Setters
    Object.keys(properties).forEach(function (prop) {
        Object.defineProperty(this, prop, {
            // Create a new getter for the property
            get: function () {
                return properties[prop];
            },
            // Create a new setter for the property
            set: function (val) {
                if (properties[prop] != val){
                    properties[prop] = val;
                    this.update();
                }
            }
        })
    }, this);

    this.update();
}


texts: Search files from large directory and sub-directories

texts:
Essentially I have a large directory with many sub-folders and different formats of files.  It reads through XML, JAVA, .txt, etc, in search of a selected String inputted by the user.  The results come back as snippets, reading a certain amount of characters previous and after the selected string has been found.

It does function as planned...I send the results as snippets and links to the main pages through REST calls via Spring and AJAX.  It does take about 5 - 7 seconds on a localhost server to return the results for a directory that is 19,405 Files, 9,610 Folders.

private ArrayList<String> pathNames = new ArrayList();
private HashMap<String, String> snippets = new HashMap<String, String>();

public HashMap readFiles(String search, String dirPath) {

    snippets.clear();
    InputStream stream = null;

    //Method to get all the files in main and sub folders
    listDirectory(dirPath);

    for (int i = 0; i < pathNames.size(); i++) {

        try {
            stream = new FileInputStream(pathNames.get(i));
            BufferedReader br = new BufferedReader(new    InputStreamReader(stream));

            Field chars = br.getClass().getDeclaredField("cb");
            chars.setAccessible(true);

            Field f = br.getClass().getDeclaredField("nChars");
            f.setAccessible(true);

            Field ff = br.getClass().getDeclaredField("nextChar");
            ff.setAccessible(true);

            String line;
            //not used
            int lineNum = 0;
            String path = pathNames.get(i);
            while ((line = br.readLine()) != null) {

                //Getting through to Java Source Code - uh oh

                // int charCount = (int) f.get(br);
                char[] cb = (char[]) chars.get(br);
                int nextChar = (Integer) ff.get(br);

                //not used
                lineNum++;

                if (line.contains(search)) {
                    String lines = "";
                    for (int t = nextChar - 200; t < nextChar + 100; t++) {
                        lines += cb[t];
                    }

                    snippets.put(pathNames.get(i), lines);

                }
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchFieldException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return snippets;
}


texts:
I have made a program to take x number of die and rolls them y number of times, then stores the data into an array so that I may output a CSV file. Everything works as intended, but I am having trouble figuring out how to increase the number of die to anything substantial. Right now I am using a switch, but linearly adding code like this seems inefficient, not to mention it will crash with amounts larger than 4 die. Is there some shortcut for adding variable number of switch statements? Any other methods would work as well, I am just not clever enough to come up with any as of yet.

import javax.swing.JOptionPane;

public class histogram {
public static void main(String[] M83cluster) {

    // # of die
    String N = JOptionPane.showInputDialog("How many dice would you like to roll?");
    int numofDie = Integer.parseInt(N);
    // # of rolls
    String M = JOptionPane.showInputDialog("how many times would you like to roll?");
    int numofRolls = Integer.parseInt(M);
    int maxValue = numofDie*6;
    int[] taco = new int[maxValue]; // for every die there will be at most 6 values.

    // rolls the die and obtains a value.
    for (int i=0;i<numofRolls; i++) {
        int oneTotalRoll = 0;
        for (int k=0;k<numofDie; k++) {
             oneTotalRoll += (int)(1+6*Math.random());
        }

        //int oneTotalRoll = (int) (valueofDice * numofDie);
        System.out.println("ROLL: " + oneTotalRoll);

        // for each roll, increment taco[] array.
        switch (oneTotalRoll) {
            case 4: taco[0] += 1;
                break;
            case 5: taco[1] += 1;
                break;
            case 6: taco[2] += 1;
                break;
            case 7: taco[3] += 1;
                break;
            case 8: taco[4] += 1;
                break;
            case 9: taco[5] += 1;
                break;
            case 10: taco[6] += 1;
                break;
            case 11: taco[7] += 1;
                break;
            case 12: taco[8] += 1;
                break;
            case 13: taco[9] += 1;
                break;
            case 14: taco[10] += 1;
                break;
            case 15: taco[11] += 1;
                break;
            case 16: taco[12] += 1;
                break;
            case 17: taco[13] += 1;
                break;
            case 18: taco[14] += 1;
                break;
            case 19: taco[15] += 1;
                break;
            case 20: taco[16] += 1;
                break;
            case 21: taco[17] += 1;
                break;
            case 22: taco[18] += 1;
                break;
            case 23: taco[19] += 1;
                break;
            case 24: taco[20] += 1;
                break;
            case 25: taco[21] += 1;
                break;
        }
    }
    System.out.println("-------");

    String gorgon = null;  // prints outcome
    for (int g=0; g<maxValue ; g++) {
        String gigabolt = (taco[g] + ",");
        gorgon += gigabolt;
        // System.out.print(gigabolt);
    }
    if (gorgon.endsWith(","))
        gorgon = gorgon.substring(4, gorgon.length() - 1);
    System.out.print(gorgon);
}
}


texts: Support static typing / analysis with dependency injection

texts:
I am working on creating a test library, and I found DI to be pretty convenient, maybe even to create more functional coding patterns.

Normally we can have an awkward before-hook setup in Node.js testing libraries, and it's always a little unclear when things actually get initialized and refactoring can be harder than it should be:

let client;

before(function(){
    return client = ...     // client requires asynchronous initalization
});

it('tests client', function(){
   assert(client.isConnected);   // client is declared / initialized...right?
});

I've always hated that pattern, sometimes just for ergonomic reasons. It just seems awkward to me. Because client will be in scope in places where it is not yet initialized.

I thought about avoiding this pattern and finally devised a way around it, it basically looks like this:

describe('parent', function(){

    inject(() => {
        return {
            client: new Client({port: 7033}).ensure()  // returns a promise
        }
    });

    describe('child',  (client) => {

       // client has been initialized, and is injected here

        it('tests client', function(){
          // ok we know for sure client is defined
          assert(client.isConnected);
        });

    });

});

as you can see in any child block, we can inject parameters from the parent block.

This is simply a nicety, and makes things easier to grok and less error prone. Maybe even more functional programming style, not sure.

My real concern is supporting static typing, with TypeScript and allowing for at least some static analysis for correctness.

My question is - does anyone know if there is some ES7 or ES8 feature (maybe annotations/decorators?) that can somehow allow for some name checking or type checking in this kind of scenario?

I don't want to create some crazy feature that is so dynamic that it's hard to use.

Basically the way it works currently is that Promise.resolve is called for key/value returned from the inject hook, then this value is injected into the child blocks, by name. So the parameter to the child block callback function will have to match the key of the returned object from the inject hook. This is an API feature in progress and looking for constructive criticism.

To clarify, this would be an alternative API design option:

   inject('client', () => {
        return new Client({port: 7033}).ensure()
    });

then we could use the string 'client' as the matching value to determine where to inject the client variable. Of course, you would only be able to return a single value from this, and not a tuple.

I am also looking for a good way to implement this with callbacks instead of promises. I am not going to reinvent the wheel, so somewhere along the way we should use the async library or similar, here is what I think is the best option:

   inject.cb(j => {
        async.parallel({a: foo(), b: bar()}, j);
    });

    describe('child',  (a, b) => {

       // a and b have been initialized, and are injected here

    });

this way my library could work with any other library that fired a final callback with this signature:

function complete(err, results){}

where results is a simple key-value map; j would be the library callback which accepts the above arguments.

Another issue of course, is handling immutability, because the same object(s) will get injected into multiple places:

    inject('client', () => {
        return new Client({port: 7033}).ensure()
    });

    describe('child1',  (client) => {

       // client is the same object as the below child block

    });

    describe('child2',  (client) => {

       // client is the same object as the above child block

    });

So should make client immutable somehow.


texts:
I would just like some input on how I may improve my code(in terms of content not formatting) without changing the output. It's just a simple magic 8 ball program using dialog boxes.

import java.security.SecureRandom;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class MagicEightBall {

    public static void main(String[] args) {

        String answers[] = {"It is certain", "It is decidedly so", "Without a doubt",
            "Yes - definitely", "You may rely on it", "As I see it, yes",
            "Most likely", "Outlook good", "Signs point to yes",
            "Yes", "Reply hazy, try again", "Ask again later",
            "Better not tell you now", "Cannot predict now", "Concentrate and ask again",
            "Don't count on it", "My reply is no", "My sources say no",
            "Outlook not so good", "Very doubtful"};

        //constructs a random number generator
        SecureRandom randomNumber = new SecureRandom();
        ImageIcon image = new ImageIcon("8ball_small.jpg");
        int counter = 0;

        //while loop allows the user to continue asking questions until they click no
        while(counter != 1) {
            //prompts the user to enter a question
            String answer = JOptionPane.showInputDialog(null,
                    "PLease enter a yes or no question:",
                    "WELCOME: Have your questions answered!", JOptionPane.INFORMATION_MESSAGE);

            //displays the answer
            if(answer != null)
                JOptionPane.showMessageDialog(null, answer+ "\n" + answers[randomNumber.nextInt(answers.length)],
                "The Magic-8 Ball has responded.", JOptionPane.PLAIN_MESSAGE, image);

            //gives the user the option to click yes or no to continue asking questions
            counter = JOptionPane.showConfirmDialog(null, "", "Would you like to ask again?",
                    JOptionPane.YES_NO_OPTION, 0, image);
        }

        //displays name after user enters no
        JOptionPane.showMessageDialog(null, "Programmed by my name", "Goodbye! Your answers have been answerd.",
                JOptionPane.PLAIN_MESSAGE, image);
    }
}


texts: Find the combination of matches which are closest to each other

texts:
Problem - Given three sorted arrays find combinations which are closest to each other.

example -

i/p - 3,8,18  7,11,16  10,15,19
o/p - (8,7,10)

i/p - 2,2,6  11,15,15  8,8,18
o/p - (6,11,8)

Kindly review this scala code and suggest improvements

import scala.math.Ordering._

object NearestMatch {

  def main(args: Array[String]) = {
    val size = args(0).toInt
    val range = args(1).toInt
    val (a,b,c) = (Array.fill(size)(scala.util.Random.nextInt(range)).sorted,
           Array.fill(size)(scala.util.Random.nextInt(range)).sorted,
           Array.fill(size)(scala.util.Random.nextInt(range)).sorted)

   println(a.mkString(","))
   println(b.mkString(","))
   println(c.mkString(","))

  var (i,j,k) = (0,0,0)
  var (pa,pb,pc) = (0,0,0)

  var curDiff = 12345 // a very large number
  while (i < a.size && j < b.size && k < c.size) {
    val min = Math.min(a(i), Math.min(b(j), c(k)))
    val max = Math.max(a(i), Math.max(b(j), c(k)))
    val newDiff = max-min

    if (curDiff > newDiff) {
      pa = i
      pb = j
      pc = k
      curDiff = newDiff
    }

    if (a(i) == min) i+=1
    else if (b(j) == min) j+=1
    else k+=1
  }
   println(a(pa), b(pb), c(pc))
  }
}


texts: Setting alternative records true if its even count else leave last record

texts:
I have an attendance list like this.

problem: I need to set In and Out alternatively. but if I have only 3 records then I need to set 0 record In true. 1 record out is true. and 3 record has is both In Out is false. I tried like this its working fine. but I was checking is there any better way

ObservableCollection<EmployeeAttandance> attendancesPerDay = new ObservableCollection<EmployeeAttandance>();
if (attendancesPerDay.Count % 2 == 0)
{
    int counter = 0;
    foreach (var attendance in attendancesPerDay)
    {
        if (counter % 2 == 0)
            attendance.In = true;
        else
            attendance.Out = true;
        counter++;
    }
}
else
{
    int counter = 0;
    foreach (var attendance in attendancesPerDay)
    {
        if (attendancesPerDay.IndexOf(attendance) == attendancesPerDay.Count - 1)
            continue;
        if (counter % 2 == 0)
            attendance.In = true;
        else
            attendance.Out = true;
        counter++;
    }
}


texts: Return path between graph nodes using depth-first search

texts:
This code is meant to implement a Graph class which has a method that returns a path between 2 nodes using depth-first search.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

from queue import PriorityQueue
from copy import deepcopy

class Graph:
    def __init__(self):
        self.verts = set()

    def add_vert(self, id):
        new_vert = Vertex(id)
        self.verts.add(new_vert)
        return new_vert

    def get_vert(self, id):
        for vert in self.verts:
            if vert.id == id:
                return vert
        return None

    def dfs(self, start, end):
        path_stack = []
        visited = set()
        path_stack.append([start])

        while path_stack:
            cur_path = path_stack.pop()
            last = cur_path[-1]
            visited.add(last)

            if last != end:
                path_stack = self.push_paths_in_order(path_stack, cur_path, visited)
            else:
                return cur_path
        return None

    def push_paths_in_order(self, path_stack, cur_path, visited):
        last = cur_path[-1]
        queue = PriorityQueue()

        for neighbour in last.neighbours:
            if neighbour not in visited:
                    # make queue like max heap so that we can push
                    # paths to path_stack in increasing order
                    dist_to_neighbour = last.neighbours[neighbour] * -1
                    queue.put((dist_to_neighbour, neighbour))

        while not queue.empty():
            new_path = deepcopy(cur_path)
            next_vert = queue.get(0)[1]
            new_path.append(next_vert)
            path_stack.append(new_path)
        return path_stack

class Vertex:
    def __init__(self, id):
        self.id = id
        self.neighbours = dict()

    def add_neighbour(self, to, weight):
        self.neighbours[to] = weight


texts: Project Euler #9 in Swift - Special Pythagorean triplet

texts:
I just finished Project Euler #9 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.

  A Pythagorean triplet is a set of three natural numbers, a < b < c,
  for which,

  a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.

  There exists exactly one Pythagorean triplet for which a + b + c =
  1000. Find the product abc.

import Foundation

func getSpecialPythagoreanTriplet(sum:Int) -> Int {

    for var c = 2; c < sum; c++ {

        for var b = 1;b < c; b++ {

            for var a = 0; a < b; a++ {

                if (sum % (a + b + c)) == 0 && a * a + b * b == c * c {
                    let minSum = a + b + c
                    a *= sum / minSum
                    b *= sum / minSum
                    c *= sum / minSum
                    return a * b * c
                }
            }
        }

    }
    return -1
}

func euler9() {
    let number = getSpecialPythagoreanTriplet(1_000)

    println(number)
}

func printTimeElapsedWhenRunningCode(operation:() -> ()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed : \(timeElapsed) s")
}

printTimeElapsedWhenRunningCode(euler9)

The code executes in 0.000274002552032471 s


texts: Solving Knight's Travails Problem without using vector for position

texts:
I'm trying to implement a solution to the The Odin Project - Project 2: Knight’s Travails in Clojure (Functional Programming) based on the solution posted by benjdelt.

I would like to know your opinion about what should I change to make the code clearer and more functional (as in Functional Programming) and how should I document it.

I don't know if this code is considered functional. I am relying heavily on recursions, is this ok? If not, how can I reduce (or use any other method) to make it more functional?

Note: Instead of using a vector with position x and y "[x, y]", I chose to represent the chess board by the square index, e.g. the first square is at index 0, the second square is at index 1 ... the last square is at index 63.

(def board
 "- Not used anywhere yet, just shows how the board looks like. -"
  [(vec (range 0 8))
   (vec (range 8 16))
   (vec (range 16 24))
   (vec (range 24 32))
   (vec (range 32 40))
   (vec (range 40 48))
   (vec (range 48 56))
   (vec (range 56 64))])

(defn knight-moves
  "Get all the allowed moves of a knight at `node` position.
  Excludes all the moves that go out of the board."
  ([node]
  (let [a (- node 17)
        b (- node 15)
        c (- node 10)
        d (- node 6)
        e (+ node 6)
        f (+ node 10)
        g (+ node 15)
        h (+ node 17)
        all-neighbours [a b c d e f g h]
        possible-neighbours (vec (remove #(or (neg? %) (> % 63)) all-neighbours))]
    {:neighbours possible-neighbours :current-node node :parent-node nil}))
  ([node parent]
   (let [a (- node 17)
         b (- node 15)
         c (- node 10)
         d (- node 6)
         e (+ node 6)
         f (+ node 10)
         g (+ node 15)
         h (+ node 17)
         all-neighbours [a b c d e f g h]
         possible-neighbours (vec (remove #(or (neg? %) (> % 63)) all-neighbours))]
     {:neighbours possible-neighbours :current-node node :parent-node parent})))

;; (knight-moves 35)

(defn nodes
  "Get all the neighbours and subsequent neighbours of `starting-node`.
  Given a `node`, return a vector of maps with all the possible neighbours and
  subsequent neighbours.
  Given a `node` and a `parent`, return a vector of maps with all the possible
  nodes and subsequent neighbours and save its parent location."
  ([starting-node]
  (let [movements (knight-moves starting-node)]
    ;; For each neighbours of `starting-node`, calculate its subsequent neighbours.
    (vec (for [node (:neighbours movements)]
           (knight-moves node (knight-moves starting-node))))))
  ([starting-node parent]
   (let [movements (knight-moves starting-node)]
     (vec (for [node (:neighbours movements)]
            (knight-moves node (knight-moves starting-node parent)))))))

;; (nodes 35)

(defn backtracking
  "Return the parent location of each subsequent node in `path`."
  ([final-node] (backtracking final-node []))
  ([final-node path]
   (if (:parent-node final-node)
     (recur (:parent-node final-node) (merge path (:current-node final-node)))
     (reverse (distinct path)))))

(defn find-path
  "Given a `starting-node`, calculate the path to the `goal-node`"
  ([starting-node goal-node]
   (find-path (knight-moves starting-node) goal-node []))
  ([starting-node goal-node path]
   ;; If not yet arrived at goal
   (if-not (= (:current-node starting-node) goal-node)
     ;; Create a new node with the current-node as parent and add it to path.
     ;; Iterate through all nodes to find the path.
     (let [new-node (nodes (:current-node starting-node) starting-node)
           path (concat path new-node)]
       (recur (first path) goal-node (vec (concat (rest path) new-node))))
     ;; If path found, return the path
     (backtracking starting-node))))

;; (find-path 27 28)

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (find-path 27 28))

(-main)
; => (27 12 18 28)


texts: Collection to hold maximum number of running Tasks

texts:
I need a collection/bag (something) that will hold some maximum number of running Task objects. Adding a new running Task to the collection should block the calling thread (there are many threads trying to add a task so it should be thread safe) until there is an available slot for the new Task to be added if the maximum number of running tasks is reached. This is what I have so far and it is working fine.

Can you find any problems with this code? Or is there some built-in class that can handle this kind of task?

public class ConcurrentTaskLimiter
{
    public int MaxWorkingTasks { get; }
    private readonly Task[] _tasks;
    private readonly bool[] _finished;

    public ConcurrentTaskLimiter(int maxWorkingTasks)
    {
        MaxWorkingTasks = maxWorkingTasks;
        if ((1 <= maxWorkingTasks) == false)
            throw new ArgumentOutOfRangeException(nameof(maxWorkingTasks), maxWorkingTasks, "Must be >= 1");
        _tasks = new Task[maxWorkingTasks];
        _finished = new bool[maxWorkingTasks];

        for (int i = 0; i < MaxWorkingTasks; i++)
        {
            _tasks[i] = Task.FromResult(0); // use this as finished tasks
            _finished[i] = true;
        }
    }

    public void BlockAdd(Task t)
    {
        if (t == null)
            throw new ArgumentNullException(nameof(t));

        if (t.Status == TaskStatus.Canceled
            || t.Status == TaskStatus.Faulted
            || t.Status == TaskStatus.RanToCompletion)
            return;

        lock (this)
        {
            int i;
            while (true)
            {
                for (i = 0; i < MaxWorkingTasks; i++)
                {
                    if (_finished[i])
                    {
                        _tasks[i] = t;
                        _finished[i] = false;
                        return;
                    }
                }
                i = Task.WaitAny(_tasks);
                _finished[i] = true;
            }
        }
    }
}


texts: Python: Loop through folders, convert XLSX files to CSV removing non ASCII

texts:
As the subject suggests:

Loop recursively through folders
All files are XLSX
Remove all non ASCII characters
Save as a CSV

Can it be improved with regards to speed? Would using openpyxl help?

import os
import xlrd
import csv

for subdir, dirs, files in os.walk("C:\Users\Alan\Downloads\Knowledge"):
    for file in files:
        filepath = subdir + os.sep + file

        wb = xlrd.open_workbook(filepath)
        sh = wb.sheet_by_index(0)
        csv_file = open(filepath.replace(".xlsx","")+'_csv.csv','wb')
        wr = csv.writer(csv_file,quoting=csv.QUOTE_ALL)

        for rownum in xrange(sh.nrows):
            wr.writerow([unicode(val).encode('ascii','ignore') for val in sh.row_values(rownum)])

        csv_file.close()


texts:
I'm trying to reduce the boilerplate code for the visitor/double dispatcher pattern. First I've created a way to enforce the dispatcher to declare the dispatch(T) function for every type supported and also a dispatch_gen(T) for the generic case which I don't need to implement. This is not too hard:

/*
A generic way to get the type of a base class using a tag function
*/
template <typename T, typename U>
T base_of(U T::*);

/*
Generic dispatcher
*/
template <typename... T>
struct double_dispatcher_impl;

template <typename Head>
struct double_dispatcher_impl<Head> {
    virtual void dispatch(Head*) = 0;
};

template <typename Head, typename... Tail>
struct double_dispatcher_impl<Head, Tail...> : public double_dispatcher_impl<Tail...> {
    using double_dispatcher_impl<Tail...>::dispatch;

    virtual void dispatch(Head*) = 0;
};

template <typename... T>
struct double_dispatcher;

template <typename Head, typename... Tail>
struct double_dispatcher<Head, Tail...> : public double_dispatcher_impl<Head, Tail...> {
    using Base = decltype(base_of(&Head::dispatch_id));
    using double_dispatcher_impl<Head, Tail...>::dispatch;

    virtual void dispatch_gen(Base* b) { b->dispatch(this); }
};

The dispatch_id() is just a hacky way to get the base class, it server as a tag. Now the base class for a visitable/dispatchable:

template <typename D>
struct double_dispatchable {
    virtual void dispatch(D* d) { }
    void dispatch_id() { }
};

This gives me a relatively "nice" usage. Here's a simple example:

struct Circle;
struct Rect;
struct Triangle;
typedef double_dispatcher<Circle, Rect, Triangle> shape_disp;

struct Shape : public double_dispatchable<shape_disp> { };
struct Circle : public Shape    { void dispatch(shape_disp* disp) { disp->dispatch(this); } };
struct Rect : public Shape      { void dispatch(shape_disp* disp) { disp->dispatch(this); } };
struct Triangle : public Shape  { void dispatch(shape_disp* disp) { disp->dispatch(this); } };

struct my_dispatcher : public shape_disp {
    void dispatch(Circle* c)    { std::cout << "Circle!" << std::endl; }
    void dispatch(Rect* c)      { std::cout << "Rect!" << std::endl; }
    void dispatch(Triangle* c)  { std::cout << "Triangle!" << std::endl; }
};

Now there's still a lot of repetitive code in there (the callbacks for the subclasses). How could I improve the pattern? Can I remove the repetitive code with metaprogramming and generics, without using macros?


texts: Async linked list to and from async iterable

texts:
I'm working on some stuff that works better with (immutable async) linked lists such as this:
{ value: 'one', next: async () => { value: 'two', next: async () => null } }

Here next is an async function that returns either null or the next linked list. But I'd also be able to convert from and to iterables. So here is my iterableToLinked function:
Utils.iterableToLinked = async function(iterable) {
    var iterator = (iterable[Symbol.asyncIterator] || iterable[Symbol.iterator]).call(iterable);
    var cache = [];

    var listFromGenerator = async function(index) {
        var length = cache.length;

        if (index < length) {
            return cache[index];
        }
        else {
            var item = await iterator.next();

            if (item.done)
                return null;

            cache.push({
                value: item.value,
                next: async () => await listFromGenerator(length + 1)
            });

            return await listFromGenerator(index);
        }
    };

    return await listFromGenerator(0);
};

That method should work with iterables and iterators (since if I understand correctly, iterators are also iterables but not the other way around), both async and sync, so I can pass arrays, generators and async generators to it.
For symmetry, I want the reverse function to return an iterable (not an iterator):
Utils.linkedToIterable = function(node) {
    return {
        [Symbol.asyncIterator]: async function*() {
            var current = node;

            while (current) {
                yield await current.value;
                current = await current.next();
            }
        }
    };
}

I'm still a little confused with the difference between (sync and async) generators, iterables and iterators, so I wonder if anyone can spot issues with my code.


texts:
I have this function which returns the time that a Tweet was created based on the created_at value that comes when a timeline is pulled. I also check whether or not the tweet was created more than 2 hours ago, and if it was, have an action execute. I was wondering, is there a way that this code could be shortened down because it currently feels very long. I thought about using a switch statement instead of all the ifs, but it didn't really shorten the function down at all.

function timeAgo(dateString) {
   var rightNow = new Date();
   var then = new Date(dateString);
   if ($.browser.msie) {
      then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
   }
   var diff = rightNow - then;
   var second = 1000;
   var minute = second * 60;
   var hour = minute * 60;
   var day = hour * 24;
   var week = day * 7;
   if (isNaN(diff) || diff < 0) {
      return "";
   }
   if (diff < second * 2) {
      return {tAgo: "right now", timeCheck: false};
   }
   if (diff < minute) {
      return {tAgo: Math.floor(diff / second) + " seconds ago", timeCheck: false};
   }
   if (diff < minute * 2) {
      return {tAgo: "about 1 minute ago", timeCheck: false};
   }
   if (diff < hour) {
      return {tAgo: Math.floor(diff / minute) + " minutes ago", timeCheck: false};
   }
   if (diff < hour * 2) {
      return {tAgo: "about 1 hour ago", timeCheck: false};
   }
   if (diff < day) {
      return {tAgo: Math.floor(diff / hour) + " hours ago", timeCheck: true};
   }
   if (diff > day && diff < day * 2) {
      return {tAgo: "yesterday", timeCheck: true};
   }
   if (diff < day * 365) {
      return {tAgo: Math.floor(diff / day) + " days ago", timeCheck: true};
   }
   else {
      return {tAgo: "over a year ago", timeCheck: true};
   }
}


texts: Storing a ByteBuffer into a Cassandra database

texts:
I have a couple of fields which I am trying to put together into a single ByteBuffer before storing it in a Cassandra database.

That byte array which I will be writing into Cassandra is made up of three byte arrays as described below:

short employeeId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] attributeValue = os.toByteArray();

Now, I will write employeeId, lastModifiedDate and attributeValue together into a single byte array and that resulting byte array will be written into Cassandra.  I will then have my C++ program retrieve that byte array data from Cassandra and then deserialize it to extract employeeId, lastModifiedDate and attributeValue from it.

To do this, I am using ByyteBuffer with BigEndian byte order format.

I have put up this code together:

public static void main(String[] args) throws Exception {

        String text = "Byte Buffer Test";
        byte[] attributeValue = text.getBytes();

        long lastModifiedDate = 1289811105109L;
        short employeeId = 32767;

        int size = 2 + 8 + 4 + attributeValue.length; // short is 2 bytes, long 8 and int 4

        ByteBuffer bbuf = ByteBuffer.allocate(size);

        bbuf.order(ByteOrder.BIG_ENDIAN);
        bbuf.putShort(employeeId);
        bbuf.putLong(lastModifiedDate);
        bbuf.putInt(attributeValue.length);
        bbuf.put(attributeValue);

        bbuf.rewind();

        // best approach is copy the internal buffer
        byte[] bytesToStore = new byte[size];
        bbuf.get(bytesToStore);

        // write bytesToStore in Cassandra...

        // Now retrieve the Byte Array data from Cassandra and deserialize it...
        byte[] allWrittenBytesTest = bytesToStore;//magicFunctionToRetrieveDataFromCassandra();

        ByteBuffer bb = ByteBuffer.wrap(allWrittenBytesTest);

        bb.order(ByteOrder.BIG_ENDIAN);
        bb.rewind();

        short extractEmployeeId = bb.getShort();
        long extractLastModifiedDate = bb.getLong();
        int extractAttributeValueLength = bb.getInt();
        byte[] extractAttributeValue = new byte[extractAttributeValueLength];

        bb.get(extractAttributeValue); // read attributeValue from the remaining buffer

        System.out.println(extractEmployeeId);
        System.out.println(extractLastModifiedDate);
        System.out.println(new String(extractAttributeValue));

}

Is there any better way of doing this?
Are there some minor improvements that can be made here?
Can anyone take a look and let me know whether this is the right way to use ByteBuffer? This is my first time using it, so I'm having a bit of a problem.


texts: Return true from enumerable that calls function unless that function ever returns false

texts:
Is there a tighter way to write this code?

foreach(var processName in processNames)
{
    bool launched = launch(processName);
    if (!launched)
    {
        return false;
    }
}
return true;

I'm not sure what this kind of approach is called. But basically if any false the whole thing is false, otherwise it's true. The closest I can get is:

return !processNames.Any(process => !launch(process));

but I think the first approach is better because it's easier to understand.


texts:
I've created a little hangman game. It's pretty simple, and not to exciting but I want to know if there's a way I could turn this little game into something more extravagant and more exciting. How can I take this delicate piece of crap machinery into something a little more fun and a bit more complicated? For example:

Can I turn the list that is shown into a single string?
Is there a better way to use a random word?
Am I using the for and while loop in the correct syntax?

Source:

from random import randint

WORD_LIST = {
    'rand_word_1': 'sergeanty',
    'rand_word_2': 'amphipneustic',
    'rand_word_3': 'hypochil',
    'rand_word_4': 'grus',
    'rand_word_5': 'depressed',
    'rand_word_6': 'distortedly',
    'rand_word_7': 'unselected',
    'rand_word_8': 'crakow',
    'rand_word_9': 'preendorsing',
    'rand_word_10': 'convenient'
}

HANGMAN = (
    """
    x-------x
    """,
    """
    x-------x
    |
    |
    |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |       |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |      /
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |      / \\
    |
    GAME OVER
    """
)

MAX = len(HANGMAN) - 1
num = randint(1, 10)
num_string = str(num)
words = 'rand_word_{}'.format(num_string)
WORD_TO_GUESS = WORD_LIST[words]
HIDDEN = ['_'] * len(WORD_TO_GUESS)
LETTERS_GUESSED = []

def begin_game():
    hang_size = 0
    print "\tHANGMAN!"
    word_arr = list(WORD_TO_GUESS)

    while hang_size < MAX:
        print str(HIDDEN)
        user_guess = raw_input('Guess a letter dude: ')

        if user_guess in LETTERS_GUESSED:
            print 'You already guessed that.. PAY ATTENTION!'
            user_guess = raw_input('Guess a letter dude: ')

        if user_guess in word_arr:
            print "Yeah yeah.. We're all impressed.. It's in the word woohoo.."

            for num in range(len(word_arr)):
                if user_guess == word_arr[num]:
                    HIDDEN[num] = user_guess
                    if HIDDEN.count('_') == 0:
                        print 'You win! Finally you did something right!'
                        quit()

        else:
            print "{}.. Really? That's the best you can do.. Not in my word..".format(user_guess)
            hang_size += 1
            print HANGMAN[hang_size]

begin_game()


texts: VIM colors downloader in Python, using multiprocessing

texts:
I recently posted this script:

VIM colors downloader in Python

But since I'm not allowed to update the code there, I wanted to get an idea on this version, that uses multiprocessing:

import os
import json
import requests
from bs4 import BeautifulSoup
from multiprocessing import Process

class Spider:
    def __init__(self, total_pages=40):
        self.base_url = "http://vimcolors.com"
        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):
        try:
            full_path = os.path.join(self.download_dir, name)
            # If we have already downloaded this file, just skip
            if os.path.isfile(full_path):
                raise Exception('File: {} already exists; skipping.'.format(name))

            # Get the response
            response = requests.get(url)
            if response.status_code == 404:
                raise Exception('File not found: {}'.format(url))

            # Try downloading the file
            with open(full_path, 'wb') as file_path:
                file_path.write(response.content)
        except Exception as e:
            print(e)
        else:
            print('Downloaded', name)

    def crawl(self):
        def repo_formatter(scheme):
            base_url = scheme['github_repo']['address'].replace('github.com', 'raw.githubusercontent.com')
            return '{}/master/colors/'.format(base_url)

        # Loop over all the pages
        for page in range(self.total_pages):
            page_source = requests.get(self.base_url, params={'page': 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']:
                file_name = data['name'] + '.vim'
                process = Process(target=self.download, args=(file_name, repo_formatter(data),))
                process.daemon = True
                process.start()

        print('\n\nAll done.')

colors_spider = Spider()
colors_spider.crawl()

Everything is working. I just wanted to know, is multiprocessing a good choice in this case?


texts:
I've just implemented a search box, so I can search on employee object by (name, part of the name, phone, email ...).
Ex. if the name: Moamen Abdulraouf Mansour, I can search with ( moamen | moa | moamen mansour ...).
The Idea I've followed is:

split some values from the object to be not included in the search.
convert each object of the array to one string,
then replace extra spaces and some special Arabic letters with another letter (آ أ إ => ا) and so on.
then convert the search text string to an array of words.
After that, going through each object and find if it includes all words on the search text
finally, return this object to be the result.

the JSON looks:
{
      "id": "0",
      "ORGANIZATION_NAME": "ORGANIZATION NAME",
      "ORGANIZATION_NAME_LINK": "....",
      "ORGANIZATION_TYPE_CODE": "MIN",
      "ORGANIZATION_TYPE": "type",
      "pid": "99999",
      "ORIGINAL_ORGANIZATION_LEVEL": 0,
      "DeptUrl": "MI0",
      "IsCreated": true,
      "ManImageUrl": "https://....jpg",
      "EMPLOYEECODE": "90000419",
      "EMP_NO_ERP": "90000419",
      "TITLE": "السيد",
      "USER_FULL_NAME": "employee name",
      "USER_POSITION_TITLE": "title",
      "USER_EMAIL": "..@domain.com",
      "SEX_CODE": "M",
      "USER_EXTENSION": "4999",
      "USER_MOBILE": "1234",
      "USER_HOME_PHONE": "1234"
    },...

and this is the JS:
let searchBtn = document.getElementById('searchBtn');
let myList = document.getElementById('myList');
let arr = [];
let searchKeyword;
var resultsSize = 5;

async function getUserAsync(keywords) {
  let response = await fetch('http://localhost:3000/users');
  let data = await response.json();
  return data;
}

searchBtn.addEventListener('keyup', (e) => {
  // get serach text, remove spaces from start and end and remove more than one space between, then convert to array of words
  searchKeyword = e.target.value
    .replace(/\s+/g, ' ')
    .replace(/[\u0623|\u0622|\u0625]/g, 'ا')
    .replace(/[\u0649]/g, 'ي')
    .replace(/[\u0629]/g, 'ه')
    .trim()
    .split(' ');

  getUserAsync(searchKeyword).then((data) => {
    arr = data;

    if (searchKeyword[0].length > 2) {
      let filtered = arr.filter(function (el) {
        let {
          id,
          DeptUrl,
          pid,
          IsCreated,
          TITLE,
          SEX_CODE,
          ManImageUrl,
          ORGANIZATION_TYPE,
          ORGANIZATION_TYPE_CODE,
          ORIGINAL_ORGANIZATION_LEVEL,
          fortags,
          ...rest
        } = el;

        let elCompind = Object.values(rest)
          .join()
          .replace(/\s+/g, ' ')
          .replace(/[\u0623|\u0622|\u0625]/g, 'ا')
          .replace(/[\u0649]/g, 'ي')
          .replace(/[\u0629]/g, 'ه');

        let checkAllWords = searchKeyword.map((item) => {
          return elCompind.includes(item);
        });

        return checkAllWords.includes(false) ? false : true;
      });
      appendFiltered(filtered.slice(0, resultsSize));
    } else {
      appendFiltered([]);
    }
  });
});

function appendFiltered(filteredArray) {
  // reset container HTML
  myList.innerHTML = '';

  filteredArray.forEach((element) => {
    // console.log(element);
    let node = document.createElement('div'); // Create a node

    node.innerHTML = `

${element.USER_FULL_NAME}

${element.ORGANIZATION_NAME}

${element.USER_EMAIL}

${element.USER_POSITION_TITLE}

    `;
    myList.appendChild(node); // Append to body
  });
}

the code works well, but I believe this code can be improved.


texts: Check robustness of function to add an interval to a date

texts:
Background of the problem

My Class level variables:

    static int secondsInterval = 100000000;
    static long secondsSpecial=0;
    static Date dateSecondsReg;
    static Integer intValue;

I have a function which uses the standard Java Calendar:

The function accepts a value in long(Which is seconds elapsed from a certain date till now)  and a date(Start date) then based on this calculates seconds elapsed for sometime in future. The problem I was running into earlier was that the
cal.add(Calendar.HOUR,intValue); would only accept int values as args and I used to add seconds earlier, now I changed it to Hours so that I dont get an Integer Overflow.

public static void secondsToNotify(long seconds, String d){
        Date dt = Convert(d);
        System.out.println(""+dt);
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        secondsSpecial = secondsInterval*(1+(seconds/secondsInterval));
        System.out.println(""+(secondsSpecial));

        long hour = (secondsSpecial /60)/60;
        System.out.println(""+hour);

        if(hour >= Integer.MAX_VALUE){

        }else{
            intValue =  (int) (long)hour;
        }

        cal.add(Calendar.HOUR,intValue);
        dateSecondsReg = cal.getTime();
        System.out.println(""+dateSecondsReg);
        System.out.println(""+secondsSpecial);
    }

The code in:

secondsSpecial = secondsInterval*(1+(seconds/secondsInterval));

is important for me to get an integer division to drop off the residue.

Is this fine or there is something more behind the scenes?


texts:
I have been working on a few games which all have a need to create "events" randomly over time.  The intervals need to get shorter as time goes on if the event is negative or they need to get longer as time goes on if the event is positive in order to make the game harder the longer you play.

In my head, this picture describes how the intervals should change over time.  At first, the minimum and maximum possible time change linearly, but there is a limit for both of them which can not be exceeded once it is met.

Below is my implementation.  It is intended to be used by another object which will actually create the event.  The parent object should repeatedly call ShouldDoEvent with the amount of time that has passed since the last time it was called.

My concern is that the getNextInterval method only makes sense if you have the picture in your head and have worked out the algebra.  How can I make that method clearer?

using UnityEngine;
using System.Collections;

public class RandomIntervals
{
    private Vector2 _startMax;
    private Vector2 _startMin;
    private Vector2 _endMax;
    private Vector2 _endMin;

    private float _elapsedTime = 0;
    private float _nextEvent = -1f;
    private System.Random _random = new System.Random();

    public RandomIntervals(Vector2 startMax, Vector2 startMin, Vector2 endMax, Vector2 endMin)
    {
        _startMax = startMax;
        _startMin = startMin;
        _endMax = endMax;
        _endMin = endMin;
    }

    public bool ShouldDoEvent(float deltaTime)
    {
        _elapsedTime += deltaTime;

        if (_elapsedTime < _nextEvent) return false;

        _nextEvent = _elapsedTime + getNextInterval();
        return true;
    }

    private float getNextInterval()
    {
        float max, min;

        if (_elapsedTime <  _endMax.x)
        {
            float percentBetween = _elapsedTime / _endMax.x;
            var maxPoint = _startMax + percentBetween * (_endMax - _startMax);
            max = maxPoint.y;
        }
        else
        {
            max = _endMax.y;
        }

        if (_elapsedTime < _endMin.y)
        {
            float percentBetween = _elapsedTime / _endMin.x;
            var minPoint = _startMin + percentBetween * (_endMin - _startMin);
            min = minPoint.y;
        }
        else
        {
            min = _endMin.y;
        }

        return min + ((float)_random.NextDouble()) * (max - min);
    }
}


texts: PHP Status class : pattern or anti-pattern

texts:
I want to abstract some code which does a bunch of checks and returns a boolean - since I am using the business logic in several places. But I also want to get back the reason why, if it was returned FALSE. I have this in mind...
class ContactCanBeContactedCheck
{
    public $not_contactable_reason;

    const REASON_DECEASED = 0;
    const REASON_OPTED_OUT = 1;

    public function __invoke(Contact $contact)
    {
        // Deceased
        if ($contact->is_deceased) {
            $this->not_contactable_reason = static::REASON_DECEASED;
            return FALSE;
        }

        // Opted out
        if ($contact->opt_out) {
            $this->not_contactable_reason = static::REASON_OPTED_OUT;
            return FALSE;
        }

        return TRUE;
    }
}

I would then call the code like so...
$contact_can_be_contacted_check = new ContactCanBeContactedCheck;
$contact_can_be_contacted_check($contact);
$reason = $contact_can_be_contacted_check->not_contactable_reason;

I think this must be a well-trodden path: needing a decision, plus a reason for said decision. Is this a suitable approach or is there another more widely accepted?


texts: Update URL with new parameter value in controller action

texts:
I have an action that takes an id as a parameter and gets the corresponding item with the help of a web service. The web service's method that returns the item will either return the item with the requested id, or will create a new item (new version of the item) with a new id. So, in the case that a new item is created, the response's header should be updated with the new item's id.

Here's what the route corresponding to that controller action looks like:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "default",
        "MyArea/{Controller}/{action}/{id}",
        new { controller = "MyController", action = "Index", id = UrlParameter.Optional }
    );
}

So when an user requests the item with the id 12, the request's path will look like:

  MyArea/MyController/MyAction/12

Let's say the web service creates a new version of the above item, and its id is 13, I'd like to update the URL accordingly. Here's what my action looks like:

[HttpGet]
public async Task<ActionResult> EditItem(int id)
{
    try
    {
        Item myItem = await _myWS.Channel.GetItemAsync(id);

        // If a new version has been created, change the url in order to show the new id
        if (myItem.Id != id)
        {
            Response.StatusCode = 301;
            string newUrl = Request.Path;
            int lastSlashIndex = newUrl.LastIndexOf("/");
            if (lastSlashIndex > 0)
                newUrl = newUrl.Substring(0, lastSlashIndex + 1) + myItem.Id;

            Response.AddHeader("Location", newUrl);
            Response.End();
        }

        return View("MyView", (ItemViewModel)myItem);
    }
    catch (Exception ex)
    {
        throw new ApplicationException(ex.Message);
    }
}

I was wondering if there was a better way to reconstruct the URL with the updated id. I also tried reconstructing the URL with the Request.RequestContext.RouteData.Values, but I thought the code was less readable and more complicated, but I don't like the string replace neither, because I think it's less long term friendly.

Bonus

The reason I reconstructed the URL this way instead of a simple redirection it's because I thought the way I was doing avoided a second call to the action, but I was wrong. Is there a "hack" to avoid redirection and to just update the shown URL?


texts: Regex to find addresses and phone numbers

texts:
I am trying to optimize my Java code where I am parsing an address field.

Address fields have the format:

full_address;phone; full_address;phone; full_address;phone;

where full_address = addresstype^street^city^state^zip
and where street = street1;street2;street3;street4;

So my string is

final String string = "Billing^Tata;3001 Garden Parkway^^NJ^;100-00-0009;Home^Goggle;3341 Main Parkway^^NY^;;";

My object location stores each of the above attributes.

//regular expression to match the address type
Pattern newPattern = Pattern.compile("(([^\\^]*)\\^([^\\^]*)\\^([^\\^]*)\\^([^\\^]*)\\^([^;]*);([^;]*);)");
Matcher newMatcher = newPattern.matcher(addressLongText);
List<Location> discreteListOfLocations = new ArrayList<Location>();
MatchResult result = null;
while (newMatcher.find())
{
    result = newMatcher.toMatchResult();
    Location location = new Location();
    location.setAddressTypeCdValue(result.group(2));
    String[] str_arr = result.group(3).split(";");
    if (str_arr.length > 0)
    {
        location.setStreetAddress1(str_arr[0]);
    }
    if (str_arr.length > 1)
    {
        location.setStreetAddress2(str_arr[1]);
    }
    if (str_arr.length > 2)
    {
        location.setStreetAddress3(str_arr[2]);
    }
    if (str_arr.length > 3)
    {
        location.setStreetAddress4(str_arr[3]);
    }
    location.setCity(result.group(4));
    location.setState(result.group(5));
    location.setZip(result.group(6));
    discreteListOfLocations.add(location);
}

I am a bit confused how to optimize the regex so that it is easier for someone else to understand what my regex is doing. Any idea or suggestion will be helpful.


texts: Using repository in a FormRequest in Laravel for custom business rule validation

texts:
This is my app/Http/Requests/Organisation/CreateOrganisationRequest.php

<?php

namespace App\Http\Requests\Organisation;

use App\Contracts\OrganisationInterface;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Api\BaseApiController;
use Symfony\Component\HttpKernel\Exception\HttpException;

class CreateOrganisationRequest extends FormRequest
{
    private $organisationRepository;

    public function __construct(
        array $query = array(),
        array $request = array(),
        array $attributes = array(),
        array $cookies = array(),
        array $files = array(),
        array $server = array(),
        $content = null,
        OrganisationInterface $organisationRepository
    ) {
        parent::__construct($query, $request, $attributes, $cookies, $files, $server, $content);
        $this->organisationRepository = $organisationRepository;
    }

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|min:3|max:60|unique:organisations,name'
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function() {
            $this->checkIfMaxOrganisationLimitReached();
        });
    }

    private function checkIfMaxOrganisationLimitReached()
    {
        $currentOrganisationsCount = $this->organisationRepository->myOrganisationCount();
        $maxOrganisationsLimit = auth()->user()->max_organisations;

        if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit) {
            throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, {$maxOrganisationsLimit}.");
        }
    }
}

and it's used in the controller like this:

public function store(CreateOrganisationRequest $request)
{
    $validatedData = array_merge(
        $request->validated(),
        ['owner_id' => auth()->user()->id]
    );

    $organisation = $this->organisationRepository->create($validatedData);

    return $this->success(
        fractal($organisation, new OrganisationTransformer()),
        $this::Created
    );
}

This works and get's the job done, but I am unsure if this is a good approach in Laravel.

P.S. The HttpException that I throw is handled by app\Exceptions\Handler.php.

Another approach I've considered is to add a custom attribute to User model like this:

public function getOrganisationCountAttribute()
{
    if ($this->account_owner) {
        return $this->organisations()->count();
    }
    return 0;
}

and update my CreateOrganisationRequest (i.e. the FormRequest) by removing the repository and do this instead in my business rule validation:

private function checkIfMaxOrganisationLimitReached()
{
    $currentOrganisationsCount = auth()->user()->organisation_count;
    $maxOrganisationsLimit = auth()->user()->max_organisations;

    if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit) {
        throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, {$maxOrganisationsLimit}.");
    }
}


texts: Predefined values for some values in a template function like with a #define macro (e.g. template)

texts:
I want to overload an operator (e.g. operator<<) with different types, but also change only 1 or 2 values in the function itself.

I want to get some fancy output of a vector with the primitive integer types.
I have tried to create a template function like template<int width, typename T> operator<<... but this would need to set the width and typename explicitly with each call of the operator<< e.g.

I have a following minimal code example (which is not the shortest tbh):

main.cpp

#include <iostream>
#include <vector>

#include "utils.h"

using namespace std;

int main(int argc, char* argv[]) {
  vector<int8_t> vec_s_1 = {1, 2, 3, -1, -2, -123};
  vector<uint8_t> vec_u_1 = {1, 2, 3, 127, 128, 129};
  vector<int16_t> vec_s_2 = {1, 2, 3, -1, -2, -123};
  vector<uint16_t> vec_u_2 = {1, 2, 3, 127, 128, 129};
  vector<int32_t> vec_s_3 = {1, 2, 3, -1, -2, -123};
  vector<uint32_t> vec_u_3 = {1, 2, 3, 127, 128, 129};
  vector<int64_t> vec_s_4 = {1, 2, 3, -1, -2, -123};
  vector<uint64_t> vec_u_4 = {1, 2, 3, 127, 128, 129};

  cout << "vec_s_1: " << vec_s_1 << endl;
  cout << "vec_u_1: " << vec_u_1 << endl;
  cout << endl;
  cout << "vec_s_2: " << vec_s_2 << endl;
  cout << "vec_u_2: " << vec_u_2 << endl;
  cout << endl;
  cout << "vec_u_3: " << vec_u_3 << endl;
  cout << "vec_s_3: " << vec_s_3 << endl;
  cout << endl;
  cout << "vec_s_4: " << vec_s_4 << endl;
  cout << "vec_u_4: " << vec_u_4 << endl;

  return 0;
}

utils.h

#ifndef MODULO_SEQUENCE_UTILS_H
#define MODULO_SEQUENCE_UTILS_H

#include <vector>
#include <iomanip>
#include <ostream>
#include <sstream>

using namespace std;

template<typename T>
ostream& operator<<(ostream& os, const vector<T>& obj);

#endif // MODULO_SEQUENCE_UTILS_H

utils.cpp

#include "utils.h"

#define GET_FUNCTION(WIDTH, TYPENAME, MASK) \
template<> ostream& operator<<(ostream& os, const vector<TYPENAME>& obj) { \
  size_t size = obj.size(); \
  os << "["; \
  for (size_t i = 0; i < size; ++i) { \
    if (i > 0) { \
      os << ", "; \
    } \
    stringstream ss; \
    ss << "0x" << hex << uppercase << setw(WIDTH) << setfill('0') << (obj[i] & MASK); \
    os << ss.str(); \
  } \
  os << "]"; \
  return os; \
}

GET_FUNCTION(2, int8_t, 0xFF)
GET_FUNCTION(2, uint8_t, 0xFF)
GET_FUNCTION(4, int16_t, 0xFFFF)
GET_FUNCTION(4, uint16_t, 0xFFFF)
GET_FUNCTION(8, int32_t, 0xFFFFFFFF)
GET_FUNCTION(8, uint32_t, 0xFFFFFFFF)
GET_FUNCTION(16, int64_t, 0xFFFFFFFFFFFFFFFF)
GET_FUNCTION(16, uint64_t, 0xFFFFFFFFFFFFFFFF)

So far it is working like expected and the output is like I wanted to have it. It is solved by calling #define for each function separately (which is a really looking ugly code).

The output looks like this:

vec_s_1: [0x01, 0x02, 0x03, 0xFF, 0xFE, 0x85]
vec_u_1: [0x01, 0x02, 0x03, 0x7F, 0x80, 0x81]

vec_s_2: [0x0001, 0x0002, 0x0003, 0xFFFF, 0xFFFE, 0xFF85]
vec_u_2: [0x0001, 0x0002, 0x0003, 0x007F, 0x0080, 0x0081]

vec_u_3: [0x00000001, 0x00000002, 0x00000003, 0x0000007F, 0x00000080, 0x00000081]
vec_s_3: [0x00000001, 0x00000002, 0x00000003, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFF85]

vec_s_4: [0x0000000000000001, 0x0000000000000002, 0x0000000000000003, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFF85]
vec_u_4: [0x0000000000000001, 0x0000000000000002, 0x0000000000000003, 0x000000000000007F, 0x0000000000000080, 0x0000000000000081]

I need the different widths of the leading zeros in the output plus the mask for getting the exact hex number for each type.

My question is: How can/could I achieve the same result with only using templates?


texts:
I need to divide scoreResult into pages (which is already ordered by score column from highest to lowest), and each page cannot contain too many records (e.g. 12 is a limitation in my example), and each page cannot contain duplicate id1, and each page needs to be ordered by score from highest to lowest.

Here is my working code; I am seeking advice, especially of smarter and more efficient solutions.

scoreResult = [
#id1,id2,score",
"1,28,300.1",
"4,5,209.1",
"20,7,208.1",
"23,8,207.1",
"16,10,206.1",
"1,16,205.1",
"1,31,204.6",
"6,29,204.1",
"7,20,203.1",
"8,21,202.1",
"2,18,201.1",
"2,30,200.1",
"15,27,109.1",
"10,13,108.1",
"11,26,107.1",
"12,9,106.1",
"13,1,105.1",
"22,17,104.1",
"1,2,103.1",
"28,24,102.1",
"18,14,11.1",
"6,25,10.1",
"19,15,9.1",
"3,19,8.1",
"3,11,7.1",
"27,12,6.1",
"1,3,5.1",
"25,4,4.1",
"5,6,3.1",
"29,22,2.1",
"30,23,1.1"
]

PageLimit = 12

def pageResult():

    #store final resutls
    pages = {}
    # store dictionary to see if page exists
    # key = host_id+#+page_id, value = item
    pageDict = {}
    # key: page ID, value: # of items
    pageCount = {}
    for item in scoreResult:
        page= 0
        host_id=item.split(',')[0]

        while pageDict.has_key(str(host_id)+'#'+str(page)) or (pageCount.has_key(page) and pageCount[page] >= PageLimit):
            #print page
            page += 1
        pageDict[str(host_id)+'#'+str(page)] = True
        if pages.has_key(page):
            pages[page].append(item)
        else:
            pages[page]=[]
            pages[page].append(item)

        if pageCount.has_key(page):
            pageCount[page] += 1
        else:
            pageCount[page] = 1

    for k,v in pages.items():
        print k
        print v

if __name__=="__main__":
    pageResult()


texts: Setting instance data attributes to None in __init__

texts:
In Python 3.7, I frequently find myself writing something like this in __init__:
    self.foo: Optional[Foo] = None

For example:
window = Window()
# do some more setup here before going to user
path = get_path_from_user()
window.build(path)

class Window:
    def __init__(self):
        self.image: Optional[Image] = None

    def build(self, path):
        self.image = Image(path)

I justify this to myself as:

Wishing to keep __init__ light (for maximum reuseabilty) or
Being unable to complete the instance when __init__ executes.

However, I typically don't use the None value for any real meaning in the code. In this example, suppose a Window is meaningless without an image. It's just a placeholder until build is called so...
Is this an anti-pattern when doing so for either of the two reasons?
If so, what is a better way to do it?
(Your opinion is what I'm seeking)
Simply removing the line from __init__ flags a code inspection warning in PyCharm: "Instance Attribute instantiated outside __init__". This seems reasonable to me as it ensures I'm able to look in __init__ and know I'm always seeing all the data attributes.


texts: How to run canvas animation without effecting other javascript code

texts:
It seems to be the case that the canvas animation affects other JavaScript functions when I use window.onload = function() {. Please let me know the best practice to use animation without affecting other JavaScript.

window.onload = function() {
  //canvas init
  var canvas = document.getElementById("snow");
  var ctx = canvas.getContext("2d");

  //canvas dimensions
  var W = window.innerWidth;
  var H = window.innerHeight;
  canvas.width = W;
  canvas.height = H;

  //snowflake particles
  var mp = 250; //max particles
  var particles = [];
  for (var i = 0; i < mp; i++) {
    particles.push({
      x: Math.random() * W, //x-coordinate
      y: Math.random() * H, //y-coordinate
      r: Math.random() * 4 + 1, //radius
      d: Math.random() * mp //density
    });
  }

  //Lets draw the flakes
  function draw() {
    ctx.clearRect(0, 0, W, H);

    ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
    ctx.beginPath();
    for (var i = 0; i < mp; i++) {
      var p = particles[i];
      ctx.moveTo(p.x, p.y);
      ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true);
    }
    ctx.fill();
    update();
  }

  //Function to move the snowflakes
  //angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
  var angle = 0;

  function update() {
    angle += 0.01;
    for (var i = 0; i < mp; i++) {
      var p = particles[i];
      //Updating X and Y coordinates
      //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
      //Every particle has its own density which can be used to make the downward movement different for each flake
      //Lets make it more random by adding in the radius
      p.y += Math.cos(angle + p.d) + 1 + p.r / 2;
      p.x += Math.sin(angle) * 2;

      //Sending flakes back from the top when it exits
      //Lets make it a bit more organic and let flakes enter from the left and right also.
      if (p.x > W + 5 || p.x < -5 || p.y > H) {
        if (i % 3 > 0) {
          //66.67% of the flakes
          particles[i] = {
            x: Math.random() * W,
            y: -10,
            r: p.r,
            d: p.d
          };
        } else {
          //If the flake is exitting from the right
          if (Math.sin(angle) > 0) {
            //Enter from the left
            particles[i] = {
              x: -5,
              y: Math.random() * H,
              r: p.r,
              d: p.d
            };
          } else {
            //Enter from the right
            particles[i] = {
              x: W + 5,
              y: Math.random() * H,
              r: p.r,
              d: p.d
            };
          }
        }
      }
    }
  }

  //animation loop
  setInterval(draw, 33);
};
body {
  background: tomato;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="snow" style="display:block;position:fixed;z-index:999;pointer-events:none;"></canvas>


texts:
This piece of code calculates the sum of all prime numbers below 1 million.

It stood out to me that the Ruby script is around 20% faster. I know that Go should be faster just for being a compiled language. So how can I make the Go code run faster than it already does?

I'm interested in solutions involving goroutines, pointers, both, etc.

In Go:

Execution time: ~4.6s

package main

import (
    "fmt"
    "time"
)

func main() {
    t1 := time.Now()

    // Create slice containing values from 0 to 1 million
    a := []int{}
    for i := 0; i < 1000000; i++ {
        a = append(a, i)
    }

    done := false
    factor := 1
    for !done {
        // Get the next factor to be used as a filter for slice `a`
        factor = nextPrime(a, factor)

        var modified bool
        // Filtering slice `a`
        for i, v := range a {
            if v%factor == 0 && v > factor {
                a[i] = 0 // This is equivalent to eliminating the value
                modified = true
            }
        }

        if !modified {
            done = true
        }
    }

    var sum int
    for _, v := range a {
        sum += v
    }
    fmt.Println(sum - 1)

    t2 := time.Now()
    fmt.Println("Execution duration:", t2.Sub(t1))
}

// Doesn't return a prime literaly, but the least value to be used
// to filter out non prime numbers from an array or slice
func nextPrime(a []int, factor int) (newFactor int) {
    for _, v := range a {
        if v > factor {
            newFactor = v
            break
        }
    }
    return
}

In Ruby:

Execution time: ~3.5s

t1 = Time.now

def next_prime(a, t)
  a.each { |m| return m if m > t }
end

a=(2..999_999).to_a

complete = false

until complete
  t ||= 1
  t = next_prime(a, t)
  presize = a.size
  a.map! { |m| m%t == 0 && m > t ? nil : m }
  a.compact!
  complete = true if a.size == presize # when factoring stops shortening the array, we're done
end

r = 0
a.each { |m| r+=m }
puts r

t2 = Time.now
puts t2 - t1


texts:
I run a coding dojo at work. For one session I'm to showing that you can use a kata to get into a new language.

I'm using the FizzBuzz Kata to to show F# (and JavaScript) because it is short.  The problem is I am very new to F# and find myself devolving to objects instead of being functional.

Thus, I would like to see better ways of doing this (using nunit):

namespace FizzBuzzFSharp
    open NUnit.Framework

    module FizzBuzzer =
        let FizzBuzz number =
            match number with
            | i when i % 3 = 0 && i % 5 = 0 -> "FizzBuzz"
            | i when i % 5 = 0 -> "Buzz"
            | i when i % 3 = 0 -> "Fizz"
            | _ -> number.ToString()

        [<Test>]
        [<TestCase(1, "1")>]
        [<TestCase(2, "2")>]
        [<TestCase(3, "Fizz")>]
        [<TestCase(4, "4")>]
        [<TestCase(5, "Buzz")>]
        [<TestCase(6, "Fizz")>]
        [<TestCase(7, "7")>]
        [<TestCase(8, "8")>]
        [<TestCase(9, "Fizz")>]
        [<TestCase(10, "Buzz")>]
        [<TestCase(11, "11")>]
        [<TestCase(12, "Fizz")>]
        [<TestCase(13, "13")>]
        [<TestCase(14, "14")>]
        [<TestCase(15, "FizzBuzz")>]
        [<TestCase(30, "FizzBuzz")>]
        let WhenNumber_ThenResult(number, expected) =
            Assert.AreEqual(expected, FizzBuzz(number));


texts:
I am very new to JS and am having a bit of a problem with making this happen.

function updateDisplay23() {

  var statElem = document.getElementById("stat_ht");

  if (statElem) {

    statElem.innerHTML = stats["ht"];

  }

}

I load all the functions from the index at the startup then call the function with:

updateDisplay23()

This works fine and loads the info to the index page as desired. The problem is I have 30 or so functions, and may add many more. This is a lot of calls, I would like to combine them all into one function call.  Someone hinted this may be possible.


texts:
This is my second game in React (I posted a country guessing game 2 days ago). Please review my code.

Preview

Alert: May work only in Google Chrome (I build here)

import React, { Component } from 'react';
import './MemoryGame.css';

class MemoryGame extends Component {
  constructor(props) {
    super(props);
    //Array of memory images
    this.ImagePieces = ['cat', 'cat', 'dog', 'dog', 'horse', 'horse',
    'pig', 'pig', 'snake', 'snake', 'fish', 'fish'];
    this.tempCheckArr = [];
    this.state = {
      showImg: Array(this.ImagePieces.length).fill('hidden'),
      divClick: true,
      compareImgArr: [],
      counter: 0
    }
    this.checkMatch = this.checkMatch.bind(this);
  }

  //Shuffle memory game images
  componentWillMount() {
    function shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
          let j = Math.floor(Math.random() * (i + 1));
          [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    }
    shuffleArray(this.ImagePieces);
  }

  //Check for match function
  checkMatch(key, e) {
    //For later hidding images purposes
    this.tempCheckArr.push(key.toString());

    //Create copy of (compareImgArr) and add img src, for later compare
    const imgSrc = e.target.firstChild.src;
    const compareImgArr = [...this.state.compareImgArr];
    compareImgArr.push(imgSrc);

    //Set current clicked item as 'visible' in main array 'showImg'
    const arr = this.state.showImg
    arr[key] = 'visible';

    //Update state, counter for block user click method
    //after unhidding two pieces
    this.setState({
      showImg: arr,
      compareImgArr: compareImgArr,
      counter: this.state.counter + 1
    });

    //Check if 2 items are clicked - if yes - disable clicking
    if (this.state.counter % 2) {
      this.setState({
        divClick: false
      });
      //Check if pictures are matching
      if (compareImgArr[0] === compareImgArr[1]) {
        this.tempCheckArr = [];
        this.setState({
          compareImgArr: [],
          divClick: true
        });
      } else {
        //If pictures not match turn them back to hidden
        var tempArr = this.state.showImg
        // eslint-disable-next-line
        var firstElement = parseInt(this.tempCheckArr[0]);
        // eslint-disable-next-line
        var secondElement = parseInt(this.tempCheckArr[1]);
        setTimeout(()=>{
          tempArr[firstElement] = 'hidden';
          tempArr[secondElement] = 'hidden';
          this.tempCheckArr = [];
          this.setState({
            showImg: tempArr,
            compareImgArr: [],
            divClick: true
          })
        }, 1500)
      }
    }
  }

  render() {
    return(

Memory Game

          {this.ImagePieces.map((text, i) => {
            return (

 this.checkMatch(i, e) : undefined}>

            )
          })}

    )
  }
}

export default MemoryGame;