texts:
I have this authenticate! method where I am trying to retrieve their account based on the subdomain, then find the user. if user is found & their password is matched, we return success, else fail in all other cases. here is the code:

def authenticate!
    account = Account.find_by(subdomain: subdomain)
    if account
      u = account.users.find_by email: params["user"]["email"]
      if u.nil?
        fail!
      else
        u.authenticate(params["user"]["password"]) ? success!(u) : fail!
      end
    else
      fail!
    end
end

Now, I could simply this further by moving subdomain into a helper method,

def subdomain
  ActionDispatch::Http::URL.extract_subdomains(request.host, 1)
end

def authenticate!
      account = Account.find_by(subdomain: subdomain)
      if account
        u = account.users.find_by email: params["user"]["email"]
        if u.nil?
          fail!
        else
          u.authenticate(params["user"]["password"]) ? success!(u) : fail!
        end
      else
        fail!
      end
end

But how to I simply these nested conditionals?


texts:
I am trying to write a program which, given a number as an input, prints the prime factors AND the exponents of the prime factors of that number.

Example:

Input:

20

Output:

2^2 5^1

And this is the code that I've come up with:

#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>

std::vector<int>factors;
std::map<int,int>factormap;

int main()
{
    int n;
    scanf("%d",&n);

    for(int i = 2; i < n + 1; i++)
    {
        while(n%i < 1)
        {
            //Populate a vector of integers with the prime factors of the given number
            factors.push_back(i);
            n /= i;
        }
    }

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

        if(factormap.count(factors[i]) == 0)
        {
            //If the number hasn't been added yet, add it to the std::map
            //map is designed this way: <number, how many times it appears>
            factormap.insert(std::pair<int,int>(factors[i],std::count(factors.begin(), factors.end(), factors[i])));
        }
    }

    for(std::map<int,int>::iterator it=factormap.begin(); it != factormap.end(); ++it)
    {
        printf("%d^%d ", it->first, it->second);
    }
    printf("\n");

}

And it works as I intended but I feel like I'm putting too much effort into this. Is there an easier and more elegant way to accomplish this?


texts: Handling default value for int64_t representing an edge in an adjacency matrix

texts:
I'm writing an adjacency matrix, in this moment I'm trying to figure out how to indicate a default numeric value for an unassigned edge. There is the macro _I64_MAX but it is said that it's a bad practice to use macros. I wish to know if there's other way to assign such value (as a keyword as in the case of nullptr instead of NULL) or if what I'm doing is OK.
Why don't I use 0? Because the distance for an edge which start and end vertex is the same is:
$$e=(v_i,v_i);~~~||e||=0$$
AdjacencyMatrix::AdjacencyMatrix(const SinglyLinkedList &vertices) : vertices_(vertices)
{
    this->edge_matrix_ = new int64_t *[this->vertices_.Size()];
    for (size_t i = 0; i < this->vertices_.Size(); i++)
    {
        this->edge_matrix_[i] = new int64_t[this->vertices_.Size()];
        for (size_t j = 0; j < this->vertices_.Size(); j++)
        {
            this->edge_matrix_[i][j] = _I64_MAX;
        }
    }
}


texts:
I tried implementing Integer Partition (enumerating all possible sets of whole numbers whose sum is a given integer).

Looking at @rolfl's answer, I reasoned that with a stack data structure, we shouldn't need to use recursion, since recursion implicitly stores state in the call stack.  I also tried to address @JeffVanzella's criticism about separation of concerns by converting the class into an iterator.

My solution ended up being a bit more monstrous than I had anticipated.  It looks nothing like the elegant original, and runs more slowly too.  Therefore, I suspect that a better iterative solution is possible.

import java.util.Iterator;

public class Partition implements Iterator<String> {
    /**
     * Fixed-capacity stack of ints.  As used in Partition.next(), the
     * invariant is that elements towards the top of the stack are never
     * larger than elements underneath.  (In other words, the array
     * elements are nonincreasing.
     */
    private static class IntStack {
        private int[] data;
        private int size;

        IntStack(int capacity) {
            this.data = new int[capacity];
            this.size = 0;
        }

        public void push(int datum) {
            this.data[this.size++] = datum;
        }

        public int pop() {
            return this.data[--this.size];
        }

        public boolean isEmpty() {
            return this.size == 0;
        }

        /**
         * Returns the elements as a space-delimited string.
         */
        public String toString() {
            // toString() of an empty stack is never used in practice...
            if (this.isEmpty()) return "";

            StringBuilder sb = new StringBuilder(String.valueOf(this.data[0]));
            for (int i = 1; i < this.size; i++) {
                sb.append(' ').append(String.valueOf(this.data[i]));
            }
            return sb.toString();
        }
    }

    //////////////////////////////////////////////////////////////////////

    private IntStack stack;

    public Partition(int n) {
        if (n <= 0) throw new IllegalArgumentException();
        stack = new IntStack(n);
        stack.push(n);
    }

    @Override
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    @Override
    public String next() {
        String retval = stack.toString();

        int top;
        int ones = 0;

        // Count the ones at the top of the stack. Stop at "top", which is the
        // next element other than a 1.
        while (1 == (top = stack.pop())) {
            if (stack.isEmpty()) {
                // n has been completely partitioned into n ones.  All done!
                return retval;
            }
            ones++;
        }

        // Transfer 1 from top to ones, then write out the remainder in as few
        // numbers as possible, observing the stack invariant that entries
        // must be nonincreasing.
        stack.push(--top);
        for (ones++; ones > 0; ones -= top) {
            stack.push(top < ones ? top : ones);
        }
        return retval;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        Partition p = new Partition(n);
        while (p.hasNext()) {
            System.out.println(p.next());
        }
    }
}


texts:
In the effort to improve my C knowledge, I tried creating a wildcard search function:

bool wildcard(char *value, char *wcard) {
    size_t vsize = strlen(value);
    size_t wsize = strlen(wcard);

    bool no_match = false;

    if (wsize > vsize) {
        return false;
    }

    for (int w = 0, v = 0; w < wsize; w++, v++) {
        switch (wcard[w]) {
            case MULTICHAR:
                if (w == wsize) {
                    goto match;
                } else {
                    w++;
                    while (v < vsize) {
                        if (wcard[w] == value[v++]) {
                            v--;
                            break;
                        }
                    }
                    if (no_match) {
                        goto no_match;
                    }
                }
                break;
            case ONECHAR:
                break;
            default:
                if (wcard[w] != value[v]) {
                    goto no_match;
                }
        }
    }

    match:
    return true;

    no_match:
    return false;
}

I have tested this by doing:

printf("Result: %d <- Should be true\n",wildcard("Hello World","Hello*"));
printf("Result: %d <- Should be true\n",wildcard("Hello World","*Hello*"));
printf("Result: %d <- Should be true\n",wildcard("Hello World","He?lo*"));

All return 1.

You can see the project here.

Any tips or improvements are welcome.

Note

I've already found a bug. If the wcard in present in the string, it will return true even if there is more data there.

Example:

wildcard("Hello World","Hello")

This will return true when it shouldn't.


texts: Replace all occurrences with the properties of an object

texts:
The basic idea is to replace all special expressions, e.g., [%InvoiceNo%], [%DueDate%], in a string with the properties of an object, Invoice invoice.

string str = "Your invoice [%InvoiceNo%] will be due on [%DueDate%]";
Invoice invoice = new Invoice { InvoiceNo = "123456", DueDate = DateTime.Parse("2011.12.29") };
string result = GetNewValue(str, invoice);
//The expected result is: Your invoice 123456 will be due on 11/29/2011

I think the simplest way to implement GetNewValue() could be

private string GetNewValue(string str, Invoice invoice)
{
    str = str.Replace("[%InvoiceNo%]", invoice.InvoiceNo);
    str = str.Replace("[%DueDate%]", invoice.DueDate.ToString());
    return str;
}

However, in my case, Invoice has a hundred properties and the target string only contains one or two properties. I rewrite GetNewValue() in the way I think it should work more efficiently. Here is my code

private string GetNewValue(string str, Invoice invoice)
{
    List<string> expressions = new List<string>();
    List<string> fields = new List<string>();

    var startIndices = str.IndicesOf("[%");
    var endIndices = str.IndicesOf("%]");
    int startLen = "[%".Length;
    int endLen = "%]".Length;

    for (int i = 0; i < startIndices.Count; i++)
    {
        expressions.Add(str.Substring(startIndices[i],
                                      endIndices[i] - startIndices[i] + endLen));
        fields.Add(str.Substring(startIndices[i] + startLen,
                                 endIndices[i] - startIndices[i] - startLen));
    }

    for (int i = 0; i < expressions.Count; i++)
        str = str.Replace(expressions[i], invoice.GetValueByName(fields[i]).ToString());

    return str;
}

StringExtender IndicesOf()

public static List<int> IndicesOf(this string target, string search)
{
    List<int> indices = new List<int>();
    int startIndex = 0;
    int index;

    while ((index = target.IndexOf(search, startIndex)) > -1)
    {
        indices.Add(index);
        startIndex = index + 1;
    }

    return indices;
}

GetValueByName() using Reflection

public class Invoice
{
    // Properties
    ......

    public object GetValueByName(string name)
    {
        PropertyInfo myProperty = typeof(Invoice).GetProperty(name);
        return myProperty.GetValue(this, null);
    }
}

How can I improve this code? Fast, less memory usage, or one-liner
Don't tell me the first approach is better. Orz
Thanks :)


texts:
I'm currently developing a small Angular tagging module which will enable me to populate an array from a text input, pretty much like Selectize to give an example.

I'm using a BehaviorSubject and give back the same BehaviorSubject as Observable to which I then subscribe and push the filtered value in an array.

I have the feeling that my code is somewhere in between traditional code and reactive programming. If someone would help reviewing my code I'd be very grateful.

Here's the component code:

form-select.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';

import {Observable} from 'rxjs/Observable';

import { BehaviorSubject }   from 'rxjs/BehaviorSubject';

@Component({
  selector: 'app-form-select',
  templateUrl: './form-select.component.html',
  styleUrls: ['./form-select.component.scss']
})
export class FormSelectComponent implements OnInit {

  private items = [];
  private selectItemArray$ = new BehaviorSubject<string>(undefined);

  @ViewChild('formselectinput') public selectInput

  constructor() {

    let subscription = this.observeSelectItem().subscribe(
      value => {
        return this.items.push(value);
      }
    );
    //If truthy
    this.items = this.items.filter(value=>!!value === true)

  }

  ngOnInit() {}

  observeSelectItem():Observable<string>{
    return this.selectItemArray$.asObservable();
  }

  updateItemArray(item){
    return this.selectItemArray$.next(item);
  }
  selectItem(item){
    this.selectInput.nativeElement.value = "";
    console.info(this.selectInput);
    return this.updateItemArray(item);
  }
  }

}

form-select.component.html

    {{item}}
      &times;

   <input id="form-select-input" type="text" name="form-select"
   #formselectinput
   [(ngModel)]="ingredient">

   {{formselectinput.value}}


texts:
I want to make sure if it's good. Maybe there is another better solution.

List<String[]> list = new ArrayList<String[]>();
    for (int i = 0; i < 3; i++) {
        String[] arr = { String.valueOf(i) };
        list.add(arr);
    }

    String json = new Gson().toJson(list);
    System.out.println(json);

Expected output:

[
[
"0"
],
[
"1"
],
[
"2"
]
]


texts: Data class where i need to set values for different fields at different times

texts:
I am creating a request for an api using below class-

class ABCDRequest {

    @JsonProperty("name")
    private var name: String? = null

    @JsonProperty("question")
    private var question: String? = null

    @JsonProperty("ans")
    private var ans: String? = null

    fun getName(): String? {
        return name
    }

    fun setName(userName: String?) {
        this.name = userName
    }

    fun getQuestion(): String? {
        return question
    }

    fun setQuestion(ques: String?) {
        this.question = ques
    }

    fun getAns(): String? {
        return ans
    }

    fun setAns(answer: String?) {
        this.ans = answer
    }

}

I need both setter and getter methods and i need to set values for different fields at different times(not at time time of creation of object for this class).

Is the above way idle or is there any 1 or few lines code for this in kotlin?


texts:
This is a continued discussion from (Different path for grid move (part 2)) to optimize for space complexity (using only cur list, other than a cur and another pre lists), and since it is new code and I make a new post.

  Given a m * n grids, and one is allowed to move up or right, find the different number of paths between two grid points.

My major idea is, if move r steps right, u steps up, we can find (1) solutions for r-1 steps right and u steps up, then combine with one final right step (2) solutions for r steps right and u-1 steps up, then combine with one final up step.

Source code in Python 2.7,

def grid_move_v2(rights, ups):
    cur = [1] * (ups + 1)
    for r in range(1, rights+1):
        for u in range(1, ups+1):
            cur[u] = cur[u] + cur[u-1]
    return cur[-1]

if __name__ == "__main__":
    print grid_move_v2(2,3)
    print grid_move_v2(4,2)


texts:
I have written a function to calculate all strong components in a graph.

How do I make this cleaner and nicer?

import java.util.*
import kotlin.math.min

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

typealias Graph<T> = Map<T, List<T>>

fun getScc(graph: Graph<String>, allNodes: Set<String>): MutableList<List<String>> {
    val discoveryTime = mutableMapOf<String, Int>()
    val lowest = mutableMapOf<String, Int>()
    val stack = ArrayDeque<String>()
    var index = 0
    val strongComponents = mutableListOf<List<String>>()
    val resolved = mutableSetOf<String>()
    fun dfs(node: String) {
        index += 1
        discoveryTime[node] = index
        lowest[node] = index
        stack.addLast(node)
        for (neb in graph[node] ?: mutableListOf()) {
            if (neb in resolved) {
                continue
            }
            if (neb in discoveryTime) { //ancestor
                lowest[node] = min(discoveryTime[neb]!!, lowest[node]!!)
            } else {
                dfs(neb)
                lowest[node] = min(lowest[neb]!!, lowest[node]!!)
            }
        }
        if (lowest[node] == discoveryTime[node]) {
            val sc = mutableListOf<String>()

            val neb = stack.pollLast()!!
            resolved.add(neb)
            sc.add(neb)

            if (neb == node) {
                strongComponents.add(sc)
                return

            }
            while (stack.size > 0 && stack.peekLast()!! != node) {
                val neb = stack.pollLast()!!
                resolved.add(neb)
                sc.add(neb)
            }
            if (stack.size > 0 && stack.peekLast()!! == node) {
                val neb = stack.pollLast()
                resolved.add(neb)
                sc.add(neb)
            }

            strongComponents.add(sc)
        }
    }

    for (node in allNodes) {
        if (node !in resolved) {
            dfs(node)
        }
    }
    return strongComponents
}

```


texts: Run code after making a certain number of requests using RxJS

texts:
I'm experimenting with reactive JS by writing mocha tests. I wrote a test that makes a certain number of requests to an API before stopping. However, this being my first experience with RxJS, I don't know if I'm doing things in the best way. Are there any obvious mistakes I'm making here?

   it('uses canary', function(done) {
  var eventEmitter = new EventEmitter();
  var iterations = 3;
  var source = Rx.Observable.fromEvent(eventEmitter, 'data').take(iterations);

  var subscription = source
     .subscribe(
        function(data) {
           console.log(data);
        },
        function(err) {
           if (err) {
              throw err;
           }
        },
        function() {
           console.log('completed');
           done();
        }
     );

  for (var k = 0; k < iterations; k++) {
     request(app)
        .get('/api/canarycanary')
        .set('Accept', 'application/json')
        .expect('Content-Type', /json/)
        .end(function(err, res) {
           eventEmitter.emit('data', res.body);
        });
  }

});


texts: An echo program, mostly in C and completely from scratch

texts:
This is an echo program with no runtime or standard library. It's meant to be compiled with -nostdlib on an amd64 Linux system.

static signed long mywrite(int fd, const void *buf, unsigned long count) {
    signed long retval;
    __asm__ __volatile__(
        "syscall" :
        "=a" (retval) :
        "a" (1), "D" (fd), "S" (buf), "d" (count) :
        "rcx", "r11", "memory"
    );
    return retval;
}

static void myexit(int status) __attribute__((__noreturn__));
static void myexit(int status) {
    __asm__ __volatile__(
        "syscall" :
        :
        "a" (60), "D" (status) :

    );
    __builtin_unreachable();
}

static unsigned long mystrlen(const char *str) {
    const char *pos = str;
    while(*pos) ++pos;
    return pos - str;
}

static void writearg(char *str, char end) {
    unsigned long size = mystrlen(str) + 1;
    unsigned long written = 0;
    str[size - 1] = end;
    do {
        signed long result = mywrite(1, str + written, size - written);
        if(result < 0) myexit(1);
        written += result;
    } while(written < size);
}

void _start(void) __attribute__((__naked__, __noreturn__));
void _start(void) {
    __asm__(
        "pop %rdi\n\t"
        "mov %rsp, %rsi\n\t"
        "jmp mymain"
    );
}

static void mymain(int argc, char *argv[]) __attribute__((__noreturn__, __used__));
static void mymain(int argc, char *argv[]) {
    if(argc <= 1) {
        myexit(mywrite(1, "\n", 1) != 1);
    }
    int i;
    for(i = 1; i < argc - 1; ++i) {
        writearg(argv[i], ' ');
    }
    writearg(argv[i], '\n');
    myexit(0);
}

Some of my concerns:

Is my program's behavior fully compliant with the standard for echo?
Am I making any unwarranted assumptions that could make my code not work on a future release of Linux (or compiler)? In particular, are popping argc and the way I'm overwriting null terminators in argv values okay?
Since my code is Linux-on-amd64-only anyway, are there any other assumptions that I can make? For example, can I assume that Linux will always have continuous argv values, and so just make one big write call after swapping out all the nulls, instead of one per argument? (I know I'd still have to loop write in case of partial writes. I also know I could just copy the strings around myself, but I'd rather write them from where I got them.)
Instead of having _start as an assembly stub and my real code in mymain, is there any way I can put my real code in _start but still be able to safely get ahold of the command-line arguments?


texts:
I'm a HPC guy so I'm all about "make it work, then make it fast." I have a little bash script which gets a Physical Source Lines Of Code (PSLOC) and Logical SLOC (currently just of Java code, but it would work for C and C++ too). It works by finding all *.java files in a directory and then goes through each file found and uses sed to delete stuff I don't want. It first does PSLOC by deleting all comments, whitespace, and blank lines. It then gets LSLOC by taking PSLOC and deleting all lines starting with # or @, replacing {}()'s with a blank space, deleting whitespace, and finally deleting blank lines. I get the line count for PSLOC and LSLOC with wc -l.

This works, but I'm a scripting noob and haven't done anything like this before. What I'm wondering is how can I make this script faster and easier to read/maintain:

#!/bin/bash
DIR="C:/dev/somejavafolder"
LANGUAGE="java"
find "$DIR" -type f -name "*.$LANGUAGE" > filelist
while read FILE; do

   PSLOC="$FILE.psloc"
   LSLOC="$FILE.lsloc"

   # Get PSLOC
   sed -e "s/\/\/.*$//" $FILE > $PSLOC # deletes all /* to */ lines
   sed -i -e 's|/\*|\n&|g;s|*/|&\n|g' $PSLOC # ^
   sed -i -e '/\/\*/,/*\//d' $PSLOC # deletes all // lines
   sed -i -e 's/^[ \t]*//' -e 's/[ \t]*$//' $PSLOC # deletes all whitespace
   sed -i -e '/^$/d' $PSLOC # deletes all blank lines

   wc -l $PSLOC

   # Get LSLOC
   sed -e 's/#.*//' $PSLOC > $LSLOC # deletes all # lines
   sed -i -e 's/@.*//' $LSLOC # deletes all # lines
   sed -i -e 's/{/ /g;s/}/ /g;s/)/ /g;s/(/ /g' $LSLOC # replaces {}() with spaces
   sed -i -e 's/^[ \t]*//' -e 's/[ \t]*$//' $LSLOC # deletes all whitespace
   sed -i -e '/^$/d' $LSLOC # deletes all blank lines

   wc -l $LSLOC

done < filelist

find "$DIR" -name "*.*sloc" -type f -delete

This gets PSLOC and LSLOC counts of 531 java files (~80524 lines) in about 4 minutes.

Edit: per @choroba's suggestion, I changed the file to

#!/bin/bash
DIR="C:/dev/somejavafolder"
LANGUAGE="java"
find "$DIR" -type f -name "*.$LANGUAGE" > filelist
while read FILE; do

   PSLOC="$FILE.psloc"
   LSLOC="$FILE.lsloc"
   sed -e "s/\/\/.*$//" -e 's|/\*|\n&|g;s|*/|&\n|g' -e '/\/\*/,/*\//d' -e 's/^[ \t]*//' -e 's/[ \t]*$//' -e '/^$/d' $FILE > $PSLOC # deletes all /* to */ lines
   wc -l $PSLOC
   sed -e 's/#.*//' -e 's/@.*//' -e 's/{/ /g;s/}/ /g;s/)/ /g;s/(/ /g' -e 's/^[ \t]*//' -e 's/[ \t]*$//' -e '/^$/d' $PSLOC > $LSLOC # deletes all # lines
   wc -l $LSLOC

done < filelist

find "$DIR" -name "*.*sloc" -type f -delete

and the runtime went down to about 80 seconds. Awesome! Any other ideas?

Edit 2: So now it's even more succinct without writing the changes to files, just spitting out the linecount. How would I go about spitting the two numbers resulting from sed ... | wc -l on the same line separated by a space without doing some assignment like a=($(sed ... | wc -l)) and using echo?

#!/bin/bash
DIR="C:/dev/somejavafolder"
LANGUAGE="java"

wc -l `find $DIR -type f -name '*.java'` > OSLOC
sed -i -e "s/^[ \t]*//" -e "s/[ \t]*$//" OSLOC

find "$DIR" -type f -name "*.$LANGUAGE" > filelist
while read FILE; do

   # Get PSLOC
   sed -e "s/\/\/.*$//" -e "s|/\*|\n&|g;s|*/|&\n|g" -e "/\/\*/,/*\//d" -e "s/^[ \t]*//" -e "s/[ \t]*$//" -e "/^$/d" $FILE | wc -l

   # Get LSLOC
   sed -e "s/\/\/.*$//" -e "s|/\*|\n&|g;s|*/|&\n|g" -e "/\/\*/,/*\//d" -e "s/#.*//" -e "s/@.*//" -e "s/{/ /g;s/}/ /g;s/)/ /g;s/(/ /g" -e "s/^[ \t]*//" -e "s/[ \t]*$//" -e "/^$/d" $FILE | wc -l

done < filelist

find "$DIR" -name "*.*sloc" -type f -delete


texts: Parallel scheduler for running actions at designated times

texts:
I've been trying to learn Haskell on and off for a couple years. I had a project for building a parallel web scraper, and I figured I'd try to use Haskell for it. Here's the part used to schedule tasks: basically, it opens a Chan that can be used to send jobs, which is simply an IO action with the time when it should be run. I'd be thankful for any (constructive) remarks.

Here's the main Scheduler module:

{-|
Module      : Scheduler
Description : Run IO actions at a designated time, in parallel
-}
module Scheduler (startScheduler, InputJobChan, Job(..)) where

import System.Timeout (timeout)
import Control.Concurrent.Chan (Chan, newChan, readChan)
import Control.Concurrent (forkIO)
import Data.Time.Clock.POSIX (getPOSIXTime, POSIXTime)
import qualified Data.PQueue.Min as PQ

-- |Main job type used to describe jobs that are sent to the scheduler.
data Job = Job { action :: InputJobChan -> IO(), time :: POSIXTime }
instance Eq Job where
  (==) j1 j2 = time j1 == time j2
instance Ord Job where
  (<=) j1 j2 = time j1 <= time j2
-- |Queue type used to send jobs to the scheduler
type InputJobChan = Chan [Job]
-- |Internal priority queue used to find the next job to run
type JobPQueue = PQ.MinQueue Job

-- |Start the scheduler and return an input queue used to send jobs
startScheduler :: IO InputJobChan
startScheduler = do
  chan <- newChan
  _ <- forkIO $ processJobs_ chan PQ.empty
  return chan

-- |Internal function doing most of the work
processJobs_ :: InputJobChan -> JobPQueue -> IO()
processJobs_ chan jobs
  -- If we don't have any jobs in queue, wait until we get some
  | PQ.null jobs = do
    returnedJobs <- readChan chan
    print "Got new jobs!"
    processJobs_ chan (PQ.fromList returnedJobs)
  -- otherwise wait until it's time to run the first job
  | otherwise = do
      let (job, others) = PQ.deleteFindMin jobs
      print $ "current: " ++ show (time job) ++ " (" ++ show (PQ.size others) ++ " others in queue)"
      now <- getPOSIXTime
      -- delay in microseconds
      let microsecondTimeout = round $ 1000000 * (time job - now)
      print $ "preparing to wait " ++ show microsecondTimeout ++ " for new messages on the queue..."
      readResult <- timeoutReadChan chan microsecondTimeout
      case readResult of
        Nothing -> do
          print "no new jobs, running current job action..."
          action job chan
          processJobs_ chan others
        Just returnedJobs -> do
          print "Enqueuing new jobs ..."
          let newJobs = PQ.union jobs (PQ.fromList returnedJobs)
          processJobs_ chan newJobs

-- |Listen to a chan at most t microseconds, return Nothing if nothing was read
timeoutReadChan :: Chan a -> Int -> IO (Maybe a)
timeoutReadChan chan t
  | t <= 0    = return Nothing
  | otherwise = timeout t (readChan chan)

And here is some simple test code:

import Scheduler
import System.Random.MWC (createSystemRandom)
import System.Random.MWC.Distributions (exponential)
import Control.Monad
import Data.Time.Clock.POSIX
import Control.Concurrent.Chan (writeChan)
import Control.Concurrent (threadDelay)

-- |Create jobs at random, simulating a poisson process
createRandomJobs :: InputJobChan -> IO ()
createRandomJobs chan = do
  gen <- createSystemRandom
  forM_ [1..15::Int] $ \n -> do
    delay <- exponential 1 gen
    now <- getPOSIXTime
    let job = Job { action = \_ -> putStrLn $ "hello " ++ show n, time = now + 1 }
    writeChan chan [job]
    threadDelay $ round $ 1000000 * delay

main :: IO ()
main = do
  chan <- startScheduler
  createRandomJobs chan


texts:
I made a SHA256 hash bruteforcer as my first program in Rust. It's very specific to what I'm trying to bruteforce and I'll probably never find it.

I translated it from Python to make it faster, but can I make it even faster than this?

// Disable snake case warning
#![allow(non_snake_case)]

extern crate crypto;
extern crate rand;

use self::crypto::digest::Digest;
use self::crypto::sha2::Sha256;
use std::{i64, fs, process};
use std::time::Instant;
use rand::Rng;

fn main() {
   // Local variables
   let listWin = ["black","green","orange","orange","orange","black","black","orange","black","black","black","orange","black","black","orange","orange","green","black","orange","black","black","orange","orange","black","black","black","orange","black","black","orange","orange","orange","orange","black","orange","black","black","orange","orange","black","black","orange","green","black","orange","orange","orange","orange","green","black"];
   let public_seed = "2132110516";
   let round_ = 4645230;

   let now = Instant::now();
   let mut nbOfTry: u32 = 0;
   let mut roundVerif = 0;
   let mut predict;

   loop {
      let randomSeed = &CreateSeed(32);
      predict = PredictColor(randomSeed, public_seed, round_);

      // Check if the hash is correct by predicting the first 50 round of the day
      while predict == listWin[roundVerif] {
         roundVerif += 1;
         predict = PredictColor(randomSeed, public_seed, round_ + roundVerif as u32);

         if roundVerif > 45 {
            fs::write("seed.txt", randomSeed).expect("Unable to write file");
            process::exit(1);
         }
      }
      roundVerif = 0;

      nbOfTry += 1;
      if nbOfTry % 1000000 == 0 {
         println!("{}", nbOfTry);
         println!("In {} secondes", now.elapsed().as_secs());
      }
   }
}

//---------------------------------------------------
// CreateSeed()
//---------------------------------------------------
// Description : Creates a random seed
//
// Input      : Number of byte
// Output     : Random seed with a len of 2*nbByte
//---------------------------------------------------
fn CreateSeed(nbByte: u8) -> (String){
   let mut rng = rand::thread_rng();
   let mut seed = String::new();
   let mut byte: String;

   for _x in 0..nbByte {
      let rand = rng.gen::<u8>();
      byte = format!("{:x}", rand);

      if rand <= 15 {byte = format!("0{}", byte);}
      seed = format!("{}{}", seed, byte);
   }
   return seed;
}

//---------------------------------------------------
// PredictColor()
//---------------------------------------------------
// Description : Predict the roll
//
// Input      : server_seed : serveur seed
//              public_seed : public seed
//              round_      : First round of the day
// Output     : --
//---------------------------------------------------
fn PredictColor(server_seed: &str, public_seed: &str, round_: u32) -> (String){
   let toHash;
   let mut hasher = Sha256::new();

   // Hash everything
   toHash = format!("{}-{}-{}",server_seed, public_seed, round_ );
   hasher.input_str(&toHash[..]);
   let hash_ = hasher.result_str();

   // Get the roll number from the hash
   let decNumber = i64::from_str_radix(&hash_[..8], 16);
   let roll = decNumber.unwrap() % 15;

   // Print the color
   if roll == 0 {return "green".to_owned();}
   else if roll >= 1 && roll <= 7 {return "orange".to_owned();}
   else if roll >= 8 && roll <= 14 {return "black".to_owned();}
   else{return "failed".to_owned();}
}


texts: Setting header color on scroll for each post

texts:
On this site this site, I have some code which you can see below which figures out the offset for each post from the top of the document and assigns a colour from each post to the header when it scrolls into view. I am having to wait for the window load event until the code works which really is not very elegant. Can anyone see how I can improve this code?

$(window).load(function() {
    var $header = $("header");
    var numberOfSections = $("section").length;
    var sectionOffsets = [];

    for(var i = 0; i < numberOfSections; i++) {
        sectionOffsets.push($("section").eq(i).offset().top);
    }

    $(window).scroll(function () {
         $("section").each(function () {
            if ($(window).scrollTop() > $(this).offset().top - 180) {
                $("header").css('color', $(this).data("colour"));
            }
        });
    }).scroll();
});


texts: Find missing element in an array of unique elements from 0 to n

texts:
The task is taken from LeetCode

  Given an array containing n distinct numbers taken from 0, 1, 2, ...,
  n, find the one that is missing from the array.

  Example 1:

Input: [3,0,1]
Output: 2

  Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

  Note:

  Your algorithm should run in linear runtime complexity. Could you
  implement it using only constant extra space complexity?

My approach is to subtract the sum from 0-n and the sum of the elements in the array. For the sum of the number from 0 to n I use the Gauss forumula: (n * (n + 1)) / 2. For the sum in the array I will have to iterate through the whole array and sum up the elements.

My solution has time complexity of \$O(n)\$ and space complexity of \$O(1)\$.

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    if (nums.length === 0) return -1;
    const sumOfNums = nums.reduce((ac, x) => ac + x);
    const sumTillN = (nums.length * (nums.length + 1)) / 2;
    return sumTillN - sumOfNums;
};


texts: Naive JS implementation of tidyr's gather function

texts:
Tidyr is an R package for creating tidy data.
(tl;dr)
In short, it provides an interface (gather) for restructuring a table into a "tidy" format. For our purposes here, it suffices to explain that each row should only contain a value for one observation. The row could contain several fields, but these are fixed factors / categorical variables (at least for the sake of this post.)

Understanding the transformation

Tidyr is intended for tabular data. However, I'm working with D3.js, in which data rows are represented as objects, not arrays.

We'd like to be able to do the following in JavaScript:

const data = [
  {Factor1: 'x1', A: 1, B: 74, C: 0.3},
  {Factor1: 'x2', A: 2, B: 89, C: 0.12},
  {Factor1: 'x3', A: 3, B: 30, C: 0.5}
  ];

const fields = ['A', 'B', 'C'];
const out = gather(data, 'Factor2', 'Value', ...fields);
out.forEach(item => { console.log(item); });

...which should produce...

Object {Factor2: "A", Value: 1, Factor1: "x1"}
Object {Factor2: "B", Value: 74, Factor1: "x1"}
Object {Factor2: "C", Value: 0.3, Factor1: "x1"}
Object {Factor2: "A", Value: 2, Factor1: "x2"}
Object {Factor2: "B", Value: 89, Factor1: "x2"}
Object {Factor2: "C", Value: 0.12, Factor1: "x2"}
Object {Factor2: "A", Value: 3, Factor1: "x3"}
Object {Factor2: "B", Value: 30, Factor1: "x3"}
Object {Factor2: "C", Value: 0.5, Factor1: "x3"}

Gather

Again, gather provides an interface for performing such transformations. Here's the signature of the original function, from Tidyr's documentation:

gather(data, key, value, ..., na.rm = FALSE, convert = FALSE, factor_key = FALSE)

Above, key and value are the names of the two resulting columns. The column labeled by the key parameter is to take on the names of the headings of the altered columns. This is Factor3 above. Similarly, the column labeled by the value parameter is to take on the values of the same column's value... this is Value in the example above.

Anyway, the code is otherwise the same as originally posted. Here's my version of gather:

function with_fields(record, fields) {
  // Returns record with only properties specified in fields
  return fields.reduce((acc, key) =>
    {acc[key] = record[key]; return acc;}, {});
}

function split_record(record, ...fields) {
  let with_f = with_fields(record, fields);
  let other_fields = Object.keys(record)
    .filter(key => !(fields.includes(key)));
  let without_f = with_fields(record, other_fields);
  return [without_f, with_f];
}

function gather(data, key_label, value_label, ...columns) {
  // Convert wide JSON representation of CSV into long format
  let lengthen = record => Object.keys(record)
    .map(key => ({[key_label]: key,
                [value_label]: record[key]}));

  return data
    // Separate columns to be made long
    .map(record => split_record(record, ...columns))
    .map(([left, right]) => [left, lengthen(right)]) // lengthen
    // nested arrays of long records
    .map(([left, right]) => right
      .map(long_pair => Object.assign({}, long_pair, left)))
    .reduce((acc, arr) => acc.concat(arr), []); // flatten
}

Note

My implementation of gather is not as fully-featured as the original (e.g. no slicing columns out of the data set by index.)
I've also renamed key and value to key_label and value_label so that it's clear that labels - not an actual key:value pair - are being provided as input.
Finally, I had some errors in the original example code that I've fixed. The original post was somewhat broken, so I've rewritten it to avoid a lock. @MikeBrant isn't crazy. I've also implemented a number of his suggestions in this gist.


texts: Function to find factors of a number, optionally including 1 and the number itself

texts:
I have a function for finding factors of a number in Python

def factors(n, one=True, itself=False):
    def factors_functional():
        # factors below sqrt(n)
        a = filter(lambda x: n % x == 0,
                   xrange(2, int(n**0.5)+1))
        result = a + map(lambda x: n / x, reversed(a))
        return result

factors(28) gives [2, 4, 7, 14]. Now i want this function to also include 1 in the beginning of a list, if one is true, and 28 in the end, if itself is true.

([1] if one else []) + a + map(lambda x: n / x, reversed(a)) + ([n] if itself else [])

This is "clever" but inelegant.

if one:
    result = [1] + result
if itself:
    result = result + [n]

This is straight-forward but verbose.

Is it possible to implement optional one and itself in the output with the most concise yet readable code possible? Or maybe the whole idea should be done some other way - like the function factors can be written differently and still add optional 1 and itself?


texts: Python program to find the topic with the most meeting time dedicated to it

texts:
I must create a program for information regarding schedules and topics of meetings at work.
The data relating to the meetings are stored in an "M" matrix with 5 columns, in which the generic row [g, m, in, fin, arg] denotes the fact that a meeting has been scheduled for day "g" of month "m", from hours "in" to "fin" hours, on the topic "arg".
Write a function "common_argument(M)" that returns the topic to which more time is dedicated.
I wrote the function and correctly returns the element but is it ok or is it too long?

def common_argument(M):
    element = M[0][4]
    for i in range(len(M)):
        if M[i][4] != element:
            if period(M, element) < period(M, M[i][4]):
                element = M[i][4]
    return element

 def period(M,c):
        s = 0
        for i in range(len(M)):
            if c in M[i]:
                if M[i][2] != M[i][3]:
                     if M[i][2] > M[i][3]:
                         s += M[i][2] - M[i][3]
                     if M[i][3] > M[i][2]:
                         s += M[i][3] - M[i][2]
         return s

common_argument([[10, 1, 15, 17, 'Vendite'],
    [10, 1, 17, 18, 'Progetti'],
    [16, 2, 10, 12, 'Vendite'],
    [16, 2, 13, 15, 'Progetti'],
    [5,3,10, 13, 'Progetti']])


texts: Simply implementing a repeating HTML form with a total

texts:
Since the repetition mode didn't make to HTML5, I was wondering how to succinctly implement it in Javascript. I've already spent a few hours on this jsbin. Be great to get a review.

  <button onclick="addRow();">Add row</button>

  Pence per kiloWatt hour
    <input id="price" required type="number" step="0.1" value="12.2" />

  <button onclick="grandTotal()">TOTAL COST</button>
    <output id=grandtotal>

  <form id=template onsubmit="return false" oninput="doCalc(this)">
    <input name="quantity" min=0 type="number" value="1">
    <input type="text" value="Washing machine">
    <input name="wattage" min=0 type="number" value="1000">
    <input name="minutes" min=0 type="number" value="60">

      <output name="total"></output>
      GBP
  </form>

Javascript:

function doCalc(el) {
  price = document.getElementById("price").value;
  console.log("price", price);
  el.total.value = (price * el.quantity.valueAsNumber * el.wattage.valueAsNumber / 1000 * (el.minutes.valueAsNumber / 60) / 100).toFixed(2);
}

function addRow() {

  var itm = document.getElementById("template");
  var cln = itm.cloneNode(true);
  document.getElementById("repeatafterme").appendChild(cln);

}

function grandTotal() {
  t = document.getElementsByName("total");
  gt = 0.0;
  for (i = 0; i < t.length; i++) {
    console.log(t[i].value);
    gt = parseFloat(gt) + parseFloat(t[i].value);
  }
  console.log("Grand total:", gt);
  document.getElementById("grandtotal").value = gt.toFixed(2);

}

Outstanding issues I don't know how to solve:

I use a form since that's easier to get the values in vanilla Javascript IIUC. I had issues with a table row.
Currently only calculates on input change. Would be nice if I could trigger this somehow on startup
Furthermore when any form changes, would be nice if the grand total could update. I am not sure what event I should latch onto.
I cloneNode by id, but that also clones the id. Not sure what the best practice is to avoid id duplication


texts:
Description

The code does particle simulation. In this code, some particles take steps with a certain distribution length. if particles go beyond a curve, the code put them back.

Code

   #include <iostream>
#include <vector>
#include <fstream>
#include <random>
#include <cmath>
using namespace std;
double randnum (double aa, double bb)  //defining a function to create random numbers
{
  static std::default_random_engine generator;
  std::uniform_real_distribution<double> distribution (aa,bb);
  return distribution(generator);
}

int main() {
    double dr;
    double a = 1.0;               //minimum value for generated random number with power-law distribution
    int N = 100000;                  //number of time steps
    double u;                    //uniform random number used to create random number with desired distribution
    int Particles = 1000;       //number of particles
    int H = 500;                    //potential parameter
    int h = 200;                    //potential parameter
    double C = 0.004;                  //potential parameter
    double A = 0.002;              //Potential Parameter
    double Delta = 1/7;            //Assymetric Parameter
    double b = 25.0;               //maximum value for generated random number with power-law distribution
    double  phi;   //first angle
    std::vector<double>  x(Particles);
    std::vector<double>  pre_x(Particles);  //x_copmpnent of i'th particle position in previous step
    std::vector<double>  pre_y(Particles);
    std::vector<double>  J(N);
    std::vector<double>  y(Particles);
    for(int i = 0; i < Particles; i++)  //Initializing initial angle
        {
        pre_x[i] = 0;
        pre_y[i] = 200;
        }

    ofstream myfile;
    myfile.open ("J.txt");
    if(alph < 1.01 && alph > 0.99)
        B = 1  //renormalazation constant for distribution
        for(int i = 0; i < N; i++)  //time steps
            {
            J[i] = 0;
            for (int j = 0; j < Particles; j++)  //Particles
                {
                 u = randnum(0,1);
                 dr = pow( pow( a, 1-alph ) + u * (1-alph)/B, 1/(1-alph));
                 phi = randnum(0,M_PIl);
                 x[j] = pre_x[j] + cos(phi) * dr;
                 y[j] = pre_y[j] + sin(phi) * dr;
                 while( (sin(A * x[j]) + Delta * sin(C * x[j])/2) * h + H < y[j] || y[j] < 0)
                     {
                     u = randnum(0,1);
                     dr = pow( pow( a, 1-alph ) + u * (1-alph)/B, 1/(1-alph));
                     phi = randnum(0,M_PIl);
                     x[j] = pre_x[j] + cos(phi) * dr;
                     y[j] = pre_y[j] + sin(phi) * dr;
                     }
                 pre_x[j] = x[j];
                 pre_y[j] = y[j];
                 J[i] = J[i] + cos(phi);
                 }
                     myfile<<J[i]/Particles<<endl; //Outputs array to txtFile
            }
            myfile.close();
    }

Concerns:

code seems slow
general code quality

It is slow or in other words, I think is possible to make it faster. I need both "N" and "Particles" to be large values. With this condition, how can I make the code to run faster? Is there any change which could improve the run-time? Any other feedback is welcome as well.


texts:
Task: convert this array of hashes:

animals = [
  {"cats" => 3},
  {"dogs" => 5 }
]

to this hash:

{
  "cats" => 3,
  "dogs" => 5
}

This is my solution, any feedback is appreciated :-)

animals.reduce({}) {|m,e|
  e.each{|k,v| m[k] = v}; m
}


texts:
This a solution to the CodeEval's challenge "Lucky Tickets".

After a failed attempt with brute-force calculations (no surprise here), I have tried to implement an algorithm that I found on StackOverflow.

The code runs without errors and my results match the output given in the example. However, when I submit the code for evaluation I obtain a "partially solved" status and a low score (17.5/100).

It is certain my code can be optimized (especially the use of dictionary which I believe takes a toll on the memory usage) however I have, yet, not found a better way. Also I do not understand the reason why this code only partially solves the problem.

public class LuckyTickets: ChallengeTemplate
   {
      /// <summary>
      /// N = total ticket length (2, 4, 6, etc.)
      /// Key : N/2
      /// Value : Dictionary where
      ///             Key = calculated sum for the N/2 digits
      ///             Value = how many times this sum is found
      /// </summary>
      Dictionary<int, Dictionary<double, BigInteger>> allSums = new Dictionary<int, Dictionary<double, BigInteger>>();

      public override void Execute()
      {
         // initialize the dictionary, f(0,0) = 1
         allSums.Add(0, new Dictionary<double, BigInteger>());
         allSums[0].Add(0, 1);

         // each line contains an even number corresponding to the length of the ticket
         foreach (var line in this.Lines)
         {
            int halflength = int.Parse(line) / 2;

            if (!allSums.ContainsKey(halflength))
            {
               allSums.Add(halflength, new Dictionary<double, BigInteger>());
            }

            // calculate the maximum sum we can possibly find (eg. if ticket length = 6, max sum is 9+9+9 = 27)
            double maxSumPossible = 9 * halflength;
            // recursively, for each sum, find how many times we can calculate it with n digits
            for (double i = maxSumPossible; i >= 0; i--)
            {
               GetSumCount(halflength, i);
            }

            BigInteger total = 0;
            foreach (var kv in allSums[halflength])
            {
               total += (kv.Value * kv.Value);
            }
            Console.WriteLine(total.ToString("#"));
         }
      }

      private BigInteger GetSumCount(int n, double sum)
      {
         // does this length exist?
         if (!allSums.ContainsKey(n))
         {
            allSums.Add(n, new Dictionary<double, BigInteger>());
         }

         // if the count has already been calculated, return it
         BigInteger count;
         if (allSums[n].TryGetValue(sum, out count))
         {
            return count;
         }
         else if (n >= 1 && sum >= 0)
         {
            // apply algorithm:
            // f(n, m) = f(n-1, m) + f(n-1, m-1) + f(n-1, m-2)
            count = 0;
            for (int i = 0; i <= 9; i++)
            {
               count += GetSumCount(n - 1, sum - i);
            }

            allSums[n][sum] = count;

            return count;
         }
         else
         {
            return 0;
         }
      }
   }


texts: Match favorite data from db with data coming from api

texts:
I have a mutableListOf a sealed class.
I am trying to compare the result coming from the api with the ones saved in the db so I can update my UI base on isSaved attribute. Here is my code :

sealed class MasterList(val type: Type) {

    data class FavoriteList(
        val list: List<Info>
    ): MasterList(Type.FAVORITE)

    data class Child1List(
        val title: String,
        val list: List<Info1>
    ) : MasterList(Type.CHILD_1)

    data class Child2List(
        val title: String,
        val list: List<Info2>
    ) : MasterList(Type.CHILD_2)
}
data class Info(
    val fname: String,
    val lname: String,
    val age: String,
    val address: String
)
data class Info1(
    val fname: String,
    val lname: String,
    val isSaved: Boolean
)
data class Info2(
    val age: String,
    val address: String,
    val isSaved: Boolean
)
enum class Type {
    FAVORITE,
    CHILD_1,
    CHILD_2
}
fun loadInfo(): List<MasterList>? {
    val resultList = mutableListOf<MasterList>()
    val savedResult = MasterList.FavoriteList(localStroage.getAllFavorite())
    val feedResult = api.fetchAllInfo()
    return if (feedResult == null)
        null
    else {
        resultList.add(0, savedResult)
        resultList.addAll(feedResult)
        markSavedInfo(feedResult,savedResult.list)
        // I need to compare my savedResult with feedResult to put isSaved to true if it exist
        return resultList
    }
}
private fun markSavedInfo(feedResult: List<MasterList>, favoriteList: List<Info>) {
    feedResult.forEach {
        when (it.type) {
            Type.CHILD_1 -> {
                (it as MasterList.Child1List).list.forEach {
                    val name = it.fname
                    for (saved in favoriteList) {
                        if (name == saved.fname)
                            println("Result $name")
                    }
                }
            }
            Type.CHILD_2 -> {
                (it as MasterList.Child2List).list.forEach {
                    val age = it.age
                    for (saved in favoriteList) {
                        if (age == saved.age)
                            println("xxx: Result $age")
                    }
                }
            }
        }
    }
}

this is the best I could do , it's markSavedInfo function but I don't think it's the best solution !


texts:
Using Pandas to read a 14k lines CSV with many empty cells - what I call "Emmenthaler data", lots of holes :-) . A very short, simplified sampler (urlbuilder.csv):

"one","two","three"
"","foo","bacon",""
"spam","bar",""

The cells contain information to match against this web API, like this:

http://base_URL&two="foo"&three="bacon"
http://base_URL&one="spam"&two="bar"

Leaving values empty in the URL (``...one=""&two="bar"`) would give wrong results. So I want to use just the non-empty fields in each row. To illustrate the method:

import pandas as pd

def buildurl(row, colnames):
    URL = 'http://someAPI/q?'
    values = row.one, row.two, row.three  # ..ugly..

    for value,field in zip(values, colnames):
        if not pd.isnull(value):
            URL = '{}{}:{}&'.format(URL, field, value)

    return URL

df = pd.read_csv('urlbuilder.csv', encoding='utf-8-sig', engine='python')
colnames = list(df.columns)

for row in df.itertuples():
    url = buildurl(row, colnames)
    print(url)

It works and it's probably better than a cascade of if not isnull's. But I still have this loud hunch that there are much more elegant ways of doing this. Yet I can't seem to find them, probably I'm not googling for the right jargon.

Please comment


texts:
I need to test performance of a function in PHP. This has to happen accurately, of course. In the end I need to know how long it takes for a function to perform. What I'm doing now:

<?php
$start = microtime(true);
while (microtime(true) != $start + 1); // Wait a second to start up

$loops = 10;
$avg = 0;
for ($i = 0; $i < $loops; $i++) {
    $start = microtime(true);
    for ($c = 0; $c < 1000; $c++) {    // the 1000 may vary depending on the function
        theFunction();
    }
    $end = microtime(true);

    echo "Take $i: " . ($end-$start) . "s\n";

    $avg *= $i;
    $avg += $end - $start;
    $avg /= $i + 1;
}

echo "Average: " . $avg . "s\n";
?>

Is this a good way to test performance of a function in PHP? It returns about the same result all the time, within a margin of ~5% when the server does nothing else.

Let's assume the environment is clean (i.e. the server doesn't have to do anything else in the meanwhile), would this code be good for testing, or does it count too much or too little?


texts:
I'm finally "done" with my small prototype for an element inside my website. I'm just a learner in the jQuery code and that reflects in my code. It's bloated, a lot of functions do the same thing, but for a red or green button which results in this kind of code.

$('.submenu').on('click','.rood',function() {
    $(this).closest('.container_vragen').fadeOut(400, function() {
        $(this).closest('.container_vragen').css({overflow : 'hidden', color : 'red'});
        $(this).closest('.container_vragen').appendTo("#niet_geregeld");
        $(this).closest('.container_vragen').fadeIn(400);
    });
});

$('.submenu').on('click','.groen',function() {
    $(this).closest('.container_vragen').fadeOut(400, function() {
        $(this).closest('.container_vragen').css({overflow : 'hidden', color : 'green'});
        $(this).closest('.container_vragen').appendTo("#geregeld");
        $(this).closest('.container_vragen').fadeIn(400);
    });
});

As you can see most of the functions are the same, only the color and the .appedTo id changes. What's the best way to merge this code? I'm thinking there needs to be an if statement which filters what button is clicked. But I can't figure it out on my own.


texts: Listening for several connections in an async method

texts:
Is there a better way to structure a method that returns a task that queues several inbound socket connections?

    public Task Start(CancellationToken token)
    {
        return Task.Run(
            () =>
            {
                var acceptCount = new SemaphoreSlim(10);
                while (!token.IsCancellationRequested)
                {
                    acceptCount.Wait(token);
                    if (token.IsCancellationRequested)
                        break;

                    var args = new SocketAsyncEventArgs();
                    args.UserToken = acceptCount;
                    args.Completed += AcceptInbound;
                    if (!this.socket.AcceptAsync(args))
                        AcceptInbound(this.socket, args);

                }
            },
            token);
    }
    private void AcceptInbound(object sender, SocketAsyncEventArgs e)
    {
        ((SemaphoreSlim)e.UserToken).Release();
        Socket connectedClient = e.AcceptSocket;
    }


texts:
Looking for feedback on this code to reverse a double linked list. Things I am potentially looking for but missed -> redundant operations, extra / unnecessary arithmetic, improvement in code style. Thank yoU!

typedef struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
} Node;

void reverse(Node** head) {

    Node* curr = *head;
    Node* prev_ptr = NULL;
    Node* next_ptr = NULL;
    while (curr != NULL) {
        prev_ptr = curr->prev;
        next_ptr = curr->next;
        curr->prev = next_ptr;
        curr->next = prev_ptr;
        (*head) = curr;
        curr = next_ptr;

    }

}


texts: Extracting information and returning specific data

texts:
The purpose of this code is to return an address for one of the seven judicial circuits for the cases that is passed into the function.

I am taking a Node ID, which is a 3-digit number the circuit number is the first digit and the county number is the last two digits.

Set oNode = XmlDoc.SelectSingleNode("/Record/CelloXml/Integration/Case/Hearing/Court/NodeID")
Dim Addresses() = (
    "Title /n Street Address /n City, State Zip"
    ,"Title /n Street Address /n City, State Zip"
    ,"Title /n Street Address /n City, State Zip"
    ,"Title /n Street Address /n City, State Zip"
    ,"Title /n Street Address /n City, State Zip"
    ,"Title /n Street Address /n City, State Zip"
    ,"Title /n Street Address /n City, State Zip")

Select Case oNode/100
    Case 1
        ReturnData = Addresses(0)
    Case 2
        ReturnData = Addresses(1)
    Case 3
        ReturnData = Addresses(2)
    Case 4
        ReturnData = Addresses(3)
    Case 5
        ReturnData = Addresses(4)
    Case 6
        ReturnData = Addresses(5)
    Case 7
        ReturnData = Adresses(6)
End Select

Am I using the best coding practices and VBScript that I can be using?


texts: Populate Comboboxes with Hashtables using PowerShell

texts:
Background

This is a PowerShell program that uses XAML code from Visual Studio to create a GUI. In this program, there are various Comboboxes (Drop-down menus) used to select different features of the program.

What I'm Trying To Acheieve:

I am trying to populate the Comboboxes with the data stored in the different Hashtables.

The Problem

There are different Comboboxes with different names that need to be populated. I cannot iterate through an array of the different Comboboxes. This is because I cannot (or haven't discovered the solution) have an array of objects. Therefore, this is the solution that I have resulted to. This works and solves my problem. However, I want to make the code more efficient and cleaner looking. I want to hear insight from other programmers as to how they would solve this problem, because I am curious.

The Code

For($i = 0; $i -lt $ColumnsHashTable.Column1.Length; $i++) {

    $UI.Combobox1.Items.Add($ColumnsHashTable.Column1[$i])

}

For($i = 0; $i -lt $ColumnsHashTable.Column2.Length; $i++) {

    $UI.Combobox2.Items.Add($ColumnsHashTable.Column2[$i])

}

For($i = 0; $i -lt $ColumnsHashTable.Column3.Length; $i++) {

    $UI.Combobox3.Items.Add($ColumnsHashTable.Column3[$i])

}

For($i = 0; $i -lt $ColumnsHashTable.Column4.Length; $i++) {

    $UI.Combobox4.Items.Add($ColumnsHashTable.Column4[$i])

}

For($i = 0; $i -lt $ColumnsHashTable.Column5.Length; $i++) {

    $UI.Combobox5.Items.Add($ColumnsHashTable.Column5[$i])

}


texts:
This method add all numbers in list and return it as double

public HashMap<String, Double> add(HashMap<String, List<? extends Number>> map){
    HashMap<String, Double> result = new HashMap<>();

    map.forEach((key, value) -> {
        Double sum = 0.0;

        for (Number num : value){
            sum += num.doubleValue();
        }

        result.put(key, sum);
    });
    return result;
}

Testing my method with different types

public static void main(String[] args) {
    Adder adder  = new Adder();
    HashMap<String, List<? extends Number>> hashMap = new HashMap<>();

    List<Integer> list1 = new ArrayList<>();
    list1.add(1);
    list1.add(2);
    list1.add(3);

    List<BigDecimal> list2 = new ArrayList<>();
    list2.add(new BigDecimal("9.87654321e300"));
    list2.add(new BigDecimal("987654321"));
    list2.add(new BigDecimal("987654321"));

    hashMap.put("list1", list1);
    hashMap.put("list2", list2);

    System.out.println(adder.add(hashMap));

}

Is there way to improve this?


texts:
I've written a piece of code. Would like to know is the below piece of code unit testable or does it need any kind of refactoring.

MatchCilentUrls is the primary method for matching two urls. Based on my business logic i am matching the Urls.

Appreciate your comments on this.

    public bool MatchClientUrls(string redirectUrl, string whiteListUrls)
    {
        if (String.IsNullOrEmpty(redirectUrl) || String.IsNullOrEmpty(whiteListUrls))
            throw new ArgumentNullException();

        var urlList = whiteListUrls.Split(';');

        var redirectUrlScheme = string.Empty;
        var redirectUrlDomain = string.Empty;
        var urlScheme = string.Empty;
        var urlDomain = string.Empty;

        ParseUrl(redirectUrl, out redirectUrlScheme, out redirectUrlDomain);

        foreach (var url in urlList)
        {
            urlScheme = string.Empty;
            urlDomain = string.Empty;

            ParseUrl(url, out urlScheme, out urlDomain);

            if (String.IsNullOrEmpty(redirectUrlScheme) || String.IsNullOrEmpty(urlScheme))
            {
                if (redirectUrlDomain.StartsWith(urlDomain, StringComparison.OrdinalIgnoreCase) || urlDomain.StartsWith(redirectUrlDomain, StringComparison.OrdinalIgnoreCase))
                    return true;
            }
            else
            {
                if (redirectUrlScheme == urlScheme)
                {
                    if (redirectUrlDomain.StartsWith(urlDomain, StringComparison.OrdinalIgnoreCase) || urlDomain.StartsWith(redirectUrlDomain, StringComparison.OrdinalIgnoreCase))
                        return true;
                }
            }
        }

        return false;
    }

    private void ParseUrl(string url, out string scheme, out string domain)
    {
        scheme = string.Empty;
        domain = string.Empty;

        var index = url.IndexOf("//");
        if (index > 0)
        {
            scheme = url.Substring(0, index - 1);
            domain = url.Substring(index + 2);
        }
        else
        {
            domain = url;
        }
    }

    public bool ValidateUrl(string url)
    {
        var regEx = @"^(http(s)?://)?[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$";

        if(Regex.IsMatch(url, regEx))
            return true;
        else
            return false;

    }


texts: Brute-force search for solution to an unsolved mathematical inequality

texts:
From this Wikipedia article, the following unsolved problem is presented as a
result of Waring's problem:

It has been proven that a finite number of k exist, and so far none are known. The follow code is meant to brute-force search for a solution:

#include <boost/multiprecision/cpp_dec_float.hpp>
//#include <cmath>
#include <iostream>

typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<1000>> arbFloat;

enum returnID {success = 0, precisionExceeded = 1};

int main(){
    arbFloat k;

    for(k = 6; pow(3, k) - (pow(2, k) * floor(pow(1.5, k))) <= pow(2, k) - floor(pow(1.5, k)) - 2; ++k);

    if(pow(3, k) - (pow(2, k) * floor(pow(1.5, k))) <= pow(2, k) - floor(pow(1.5, k)) - 2){
        std::cout << "Solution at k = " << k << ".\n";
        return returnID::success;
    } else {
        std::cout << "Error: Precision exceeded at k = " << k << ".\n";
        return returnID::precisionExceeded;
    }
}

I am using the Boost multiprecision library cpp_dec_float, which works for large integers and decimals. The data type needs to be able to work with integers, because the solution for k needs to be a positive integer. The data type needs to work with decimals because (3/2)^k (equivalently 1.5^k) returns a decimal.

In the code I have commented out the cmath library, because it appears to be included in boost/multiprecision/cpp_dec_float.

In the for-loop, I use <= to be equivalent to the pseudocode !>.

After the for-loop, I re-check if it is a solution because currently if the precision is exceeded, it breaks the for-loop. The if-else checks if it is has either exceeded precision or is an actual solution.

The precision in this example code is 1000 (line 5), but this is changed manually as I search for larger and larger numbers that may be a solution.

I am trying to squeeze every ounce of speed out of this code, so any optimizations that make it quicker will be of great help!

I am running this code on Ubuntu 16.04, and I compile it using g++ with the -Ofast flag for the highest possible optimization during compilation.

Thanks!


texts: Flask app to administrate network interfaces

texts:
I made a Flask app that consists of 3 pages.

Index: Indexes to the 2 pages
SubnetOverview: SSH's into the server and executes ifconfig, then returns the output to a webpage.
AddSubnet: Has a HTML form where the administrator can fill in the desired VLAN id and subnet. This gets added to the netplan file and netplan apply gets executed to apply the changes.

    #Flask app that interacts with a router running on a virtual machine, enbales administrator to list current network interfaces and make a new subinterface via SSH.

from flask import Flask, render_template, request, redirect
import paramiko
import ssl

app = Flask(__name__)

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.load_cert_chain('certificates/cert.pem', 'certificates/key.pem')

SERVER_IP = "192.168.0.80"
SERVER_USERNAME = "root"
SERVER_PASSWORD = "secret123"
SERVER_PORT = 22
SERVER_IFCONFIG = "/sbin/ifconfig"

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/SubnetOverview')
def SubnetOverview():
    #Try to SSH into the server and execute the command
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(SERVER_IP, port=SERVER_PORT, username=SERVER_USERNAME, password=SERVER_PASSWORD)
    stdin, stdout, stderr = client.exec_command(SERVER_IFCONFIG, get_pty=True)
    output = stdout.readlines()
    output = ''.join(output)
    output = output.replace("\r\n", "<br />")
    client.close()
    return render_template('SubnetOverview.html', ssh_output=output)

@app.route('/AddSubnet', methods = ['POST', 'GET'])
def AddSubnet():
    if request.method == 'POST':
        #Getting the data from the HTML form
        formdata = request.form.to_dict()
        vlanid = formdata.get('vlanid')
        address = formdata.get('address')
        command = "    vlan" + vlanid + ":\n      id: " + vlanid + "\n      link: eth0\n      addresses: [ \"" + address + "\" ]\n"
        #Opening an SFTP connection
        transport = paramiko.Transport((SERVER_IP, SERVER_PORT))
        transport.connect(username=SERVER_USERNAME, password=SERVER_PASSWORD)
        sftp = paramiko.SFTPClient.from_transport(transport)
        file=sftp.file('/etc/netplan/01-network-manager-all.yaml', "a", -1)
        file.write(command)
        file.flush()
        SERVER_COMMAND = "sudo netplan apply"
        sftp.close()
        transport.close()
        #Opening SSH connection to send a command that apply's the config
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(SERVER_IP, port=SERVER_PORT, username=SERVER_USERNAME, password=SERVER_PASSWORD)
        stdin, stdout, stderr = client.exec_command(SERVER_COMMAND, get_pty=True)
        client.close()
        return redirect("/SubnetOverview")
    return render_template('AddSubnet.html')

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=443, ssl_context=context)


texts:
While learning about functional programming the simple sieve example was brought up in Haskell. I wanted to try a Kotlin implementation using sequences.

Are there any other quick wins without modifying the structure too much?

import kotlin.coroutines.experimental.buildSequence
import kotlin.system.measureTimeMillis

fun sieve(isPrime: Int, ints: Sequence<Int>): Boolean = with(ints.first()){
    return when {
        isPrime  < 2 -> false
        isPrime == 2 -> true
        isPrime == this -> true
        isPrime.rem(2) == 0 -> false
//        isPrime.and(1) == 0 -> false // same way to check if number is even
        this > isPrime -> false
        else -> sieve(isPrime, ints.filter { n -> n.rem(this) != 0 })
    }
}

fun main(args: Array<String>) {
    val lazySeq = buildSequence { for (i in 3..Int.MAX_VALUE step 2) yield(i) }
    println("Duration = ${measureTimeMillis { println("isPrime(4057) = ${sieve(4057, lazySeq)}") }}ms")
//    (2..200).forEach { println("isPrime($it) = ${sieve(it, lazySeq)}") }
}


texts: Number of paths in a grid (lattice) graph

texts:
I am trying to solve a variant of the very popular question in which we find the number of distinct valid paths on a directed graph. The graph's nodes make up a m x n lattice (grid), and the edges only lead down and right. The goal is to find how many distinct paths start at the top left corner of and end in the bottom right.

So one possible path might be down m, right n.

In this variant of the problem, there is a complication. A rectangular area inside the lattice is blocked -- no paths can go through it. (The edges that would normally lead to these nodes don't exist)

I am using Dynamic Programming to solve with a time complexity of \$O(m*n)\$.

It works pretty good with small value for rows and columns but for bigger values it throws OutOfMemoryError.

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

public class GeekForGeeks{

public static void main(String[] args) throws NumberFormatException,
        IOException {
    // TODO Auto-generated method stub

    BufferedReader inp = new BufferedReader(
            new InputStreamReader(System.in));

                    String[] s1 = inp.readLine().split(" ");
        int row = Integer.parseInt(s1[0]);
        int col = Integer.parseInt(s1[1]); // Input for the value of row &
                                            // col

        String[] s2 = inp.readLine().split(" ");
        int r1 = Integer.parseInt(s2[0]);
        int c1 = Integer.parseInt(s2[1]);
        int r2 = Integer.parseInt(s2[2]);
        int c2 = Integer.parseInt(s2[3]); // Input for the value of row &
                                            // column of blocked path

        int[][] A = new int[row][col];

        for (int i = 0; i < row; i++)
            for (int j = 0; j < col; j++)
                A[i][j] = 1;

        for (int i = r1 - 1; i < r2; i++)
            for (int j = c1 - 1; j < c2; j++)
                A[i][j] = 0;

        int answer = numOfPaths(A, row, col);
        System.out.println(answer);
    }

}

private static int numOfPaths(int A[][], int row, int col) {

    long mod = (long) Math.pow(10, 9) + 7;
    int[][] B = new int[row][col]; // new matrix to store number of paths
    // if starting point blocked then no path is there to reach right down
    if (A[0][0] == 0) {
        return 0;
    } else {
        int i, j;
        for (i = 0; i < col; i++) {
            if (A[0][i] == 0)
                break; // exit from the for loop, and set remaining elements
                        // the first row set to ZERO
            B[0][i] = A[0][i];
        }

        while (i < col)
            B[0][i++] = 0; // When any starting row is blocked then all the
                            // row down will also be blocked and
                            // have no path to be reached from starting
                            // point.

        for (i = 1; i < row; i++) {
            if (A[i][0] == 0)
                break;// exit from the for loop, and set remaining elements
                        // in the first column set to ZERO
            B[i][0] = A[i][0];
        }
        while (i < row)
            B[i++][0] = 0; // When any column is blocked all starting column
                            // towards right will be blocked

        for (i = 1; i < row; i++)
            for (j = 1; j < col; j++)
                if (A[i][j] != 0)
                    B[i][j] = (int) (((B[i - 1][j] % mod) + (B[i][j - 1] % mod)) % mod);
        // otherwise, we enter the sum of the value above and left

        return B[row - 1][col - 1]; // return the last column and row.
    }
}


texts:
The monkey-banana problem: There many variations to this problem, but the basic premise is that a monkey is in a room with a banana and
  a chair, and the monkey cannot reach the banana until he moves the
  chair close to the banana (so as to reach it), then climbs the chair
  and gets the banana.

  (Note : Often times, the chair is replaced with a box or a similar
  object that the monkey can climb on. Also, a stick may be added to the
  mix, which the monkey needs to swing at the banana in order to make it
  drop to the floor.)

I came up with this program to solve a simple monkey-banana problem in AI (no stick).  I think it's overly simple, but I would like to know what you think.

on(floor,monkey).
on(floor,chair).
in(room,monkey).
in(room,chair).
in(room,banana).
at(ceiling,banana).

strong(monkey).
grasp(monkey).
climb(monkey,chair).

push(monkey,chair):-
    strong(monkey).

under(banana,chair):-
    push(monkey,chair).

canreach(banana,monkey):-
    at(floor,banana);
    at(ceiling,banana),
    under(banana,chair),
    climb(monkey,chair).

canget(banana,monkey):-
    canreach(banana,monkey),grasp(monkey).

Should I add location attributes as well? I think that I have hard-coded a lot of things, or maybe having the stick included in the problem would make a better search tree?


texts: Using tweet as command to shut down Ubuntu

texts:
I want to use Tweets sent out by a twitter account as a command to shut down Ubuntu. For this, I've written a Python script using tweepy, a Python library for Twitter. I scheduled the script to run half past the hour every hour (for eg at 5:30, 6:30, and so on) using crontab.

Here's the script:

import tweepy
import os
from datetime import datetime
p=None

api= tweepy.API()

for status in api.user_timeline('tweetneag4'):
    while p==None:    #so that it checks only the first tweet
        if status.text.count(str((datetime.now().hour)+1))< 2 and str((datetime.time.now().hour)+1)==10:
            p=1
            pass
        elif str((datetime.now().hour)+1) in status.text:
            print "System shut down in 20 mins."
            os.system('shutdown -h +20')
            p=1

Here is a sample tweet:

#loadshedding schedule in 10mins: 15:00-21:00 #group4 #nea

The twitter account (@tweetneag4) tweets an alert 30 mins and 10 mins before the power outage begins (here, the account tweets if and only if there's a power outage next hour). What I've tried to do is check at 5:30 whether it posts a tweet regarding 6 o'clock. I've done this by seeing if the tweet contains the string "6"(when checking at 5). When checking for ten o'clock, an additional complication arises because it may contain "10" in two scenarios- first as in 10 o'clock and second as in 10mins later. (I'm sure there's a better way of doing this)

If you see the twitter feed, things should be clearer. How could I improve so that the code become more elegant?


texts: Finding the longest path in an equally-weighted tree

texts:
Its purpose is to find the longest path in an equally-weighted tree denoted as such:

3
1 2
2 3

The first number denotes both the number of vertices and the number of edges (3 - 1).

(defn farthest [edg current-node entry-node len]
    (let [
        farthest-key (atom current-node)
        farthest-val (atom len)
        ]
        (do
            (dorun
                (map
                    (fn [n]
                        ; check if theres a way to this node and that we're not going back
                        (if (not= n entry-node)
                            (let [new (farthest edg n current-node (+ len 1))
                                  new-val (second new)
                                  new-key (first new)]
                                (if (> new-val @farthest-val)
                                    (do
                                        (reset! farthest-val new-val)
                                        (reset! farthest-key new-key)
                                    )
                                )
                            )
                        )
                    )
                    (aget edg current-node)
                )
            )

            [@farthest-key @farthest-val]
        )
    )
)

(defn main []
    (let [edge-count (read)
          edges (atom
                    (to-array
                        (repeat edge-count [])
                    )
                )]

        (dotimes [n (- edge-count 1)]
            (let [edge-a (- (read) 1)
                  edge-b (- (read) 1)]
                (aset @edges edge-a
                    (conj (aget @edges edge-a) edge-b)
                )
                (aset @edges edge-b
                    (conj (aget @edges edge-b) edge-a)
                )
            )
        )

        (let [
            ft (farthest @edges 0 0 0)
            ftv (first ft)
            sol (farthest @edges ftv ftv 0)
            ]
            (println (second sol))
        )
    )
)

(main)

I've taken multiple attempts to optimize it, but I'm still struggling to make it run under the allowed time (1 second for a tree of up to 10000 vertices/connections). The most notable improvement was a change of the data structure from a connection matrix to a bunch of neighbourhood lists.

It is a university assignment, but I'm perfectly fine with disclosing that I got help here. I feel that I've already given it everything that I can and it simply requires more intricate knowledge about Clojure and its performance in particular, rather than a purely algorithmic change. (I know for a fact that one my colleagues managed to fit in the allocated time using the same algorithm on the same grading system).


texts: Compare 2 List to get a List with active players

texts:
I have a little problem: I have a list with all the users that have logged in the game and a list that has all the names of the active players and I make a List with all the players as a List<T> (It's a Lists  List).

public void CheckNames()
{
    results.Clear();
    for (int i = 0; i < TC.chatters.viewers.Length; i++)
    {
        if (!TotalPlayerNames.Contains(TC.chatters.viewers[i]))
        {
            TotalPlayerNames.Add(TC.chatters.viewers[i]);
            TotalPlayers.Add(new PlayerReal(TC.chatters.viewers[i]));
        }
        if (TotalPlayerNames.Contains(TC.chatters.viewers[i]))
        {
            results.AddRange(TotalPlayers.FindAll(x => x.displayName == TC.chatters.viewers[i]));
            for (int j = 0; j < results.Count; j++)
            {
                results[j].active = true;
            }

        }
    }

    ActivePlayers = results;
    for (int k = 0; k < TotalPlayers.Count; k++)
    {
        bool check = false;
        for (int i = 0; i < TC.chatters.viewers.Length; i++)
        {

            if (TotalPlayers[k].displayName == TC.chatters.viewers[i] && !check)
            {
                TotalPlayers[k].active = true;
                check = true;
            }
            else if (TotalPlayers[k].displayName != TC.chatters.viewers[i] && !check && ((TC.chatters.viewers.Length-1)==i))
            {
                TotalPlayers[k].active = false;
                check = true;
            }

        }
    }
}

There's no problem if I have 100-300 players playing but I DO have a huge problem if 1000-10000 players are playing... any help on this? This method executes each 20 seconds.


texts: Validating a string for a positive number, null/empty string

texts:
I have a method in which I am accepting a String clientId and that has below requirements:

clientId can be a positive number greater than zero. But if it is negative number or zero, then throw IllegalArgumentException with a message.
clientId cannot be a null or empty string. But if it is, then throw IllegalArgumentExceptionwith a message.
clientId can be a normal string as well. For example - it can be abcdefgh or any other string.

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public Builder setClientId(String clientId) {
    checkNotNull(clientId, "clientId cannot be null");
    checkArgument(clientId.length() > 0, "clientId can't be an empty string");
    checkArgument(!clientId.matches("-\\d+|0"), "clientId must not be negative or zero");
    this.clientId = clientId;
    return this;
}

This code works fine. Is there any other better way to write above logic? I am using Google Guava preconditions class for this. I have lot of other methods as like above in which I am using Google Guava preconditions to do some sanity checking.


texts:
I am using Laravel 5.3, and currently working on models.

I have the following code:

$result = TheEpisode::find($id)->with('TheParts')->take(1)->get()->each(function ($item) {
      $item->TheParts->makeHidden("title");
});

The purpose of this code is to display all the data from TheEpisode and TheParts, but exclude the title from there.

Can this be improved, like not using a loop to exclude the title attribute?


texts:
Task:

  Given a set of points on a line and a set of segments on a line. The
  goal is to compute, for each point, the number of segments that
  contain this point.

  Input Format

  The first line contains two non-negative integers \$s\$ and \$p\$ defining the number of segments and the number of points on a
  line, respectively. The next \$s\$ lines contain two integers \$a_i, b_i\$
  defining the \$i\$th segment \$[a_i, b_i]\$. The next line contains \$p\$
  integers defining points \$x_1, x_2, \dots, x_p\$.

  Constraints

  \$1 \le s, p \le 50000\$
  \$−10^8 \le a_i \le b_i ≤ 10^8\$ for all \$0 \le i \lt s\$
  \$−10^8 \le x_j \le 10^8\$ for all \$0 \le j \lt p\$

  Output Format

  Output \$p\$ non-negative integers \$k_0, k_1, \dots , k_{p−1}\$ where \$k_i\$ is the number of segments which contain \$x_i\$.

My solution

For each point \$x_i\$ consider a pair (\$x_i, p\$). For each segment \$[a_i, b_i]\$ consider two pairs: (\$ai, 'l'\$) and (\$b_i, r\$) (\$p, l, r)\$ stand for point, left, and right, respectively).

Example: given three points \$x_1 = 5, x_2 = 8, x_3 = 3\$ and two segments \$[a_1, b_1] = [4, 10], [a_2,b_2] = [2, 6]\$. We then create the following list:

\$(5, p), (8, p), (3, p), (4, l), (10, r), (2, l), (6, r)\$

And then we sort it:

\$(2, l), (3, p), (4, l), (5, p), (6, r), (8, p), (10, r)\$

Now, let's scan it from left to right. The first item indicates the beginning of a segment (as it has l). The next is a point and we know that it is covered by one segment. The next item (4,l) indicates that we have the second segment. The next item (5,p) is a point and it is covered by two segments. The next item indicates the end of some segment, and so on.

import sys

def fast_count_segments(starts, ends, points):
    cnt = [0] * len(points)
    segments_num = 0

    listpoints = [(x, 'l') for x in starts]
    listpoints += [(x, 'p') for x in points]
    listpoints += [(x, 'r') for x in ends]

    listpoints.sort(key=lambda x: x[0], reverse=False)

    for p in listpoints:
        if p[1] == 'l':
            segments_num += 1
        elif p[1] == 'r':
            segments_num -= 1
        else:
            cnt[points.index(p[0])] = segments_num

    return cnt

if __name__ == '__main__':
    input = sys.stdin.read()
    data = list(map(int, input.split()))
    n = data[0]
    m = data[1]
    starts = data[2:2 * n + 2:2]
    ends   = data[3:2 * n + 2:2]
    points = data[2 * n + 2:]
    cnt = fast_count_segments(starts, ends, points)
    for x in cnt:
        print(x, end=' ')

Sample

Input:

2 3
0 5
7 10
1 6 11

Output:

1 0 0

For large input, my code run very slow, so I really need some reviews on my solution and my code to help reduce the runtime.


texts: Convert three functions into a single function

texts:
Is it possible to combine all the functions into a single function?  I'm providing my fiddle as well.

I am trying to test it for different scenarios..
but I am not sure how to combine all the scenarios into one..

var myNumbersToSort = [null, -1, 2, 0.001, -3, 4, 0.3,1,-0.0001];

function getClosestToZero(set) {
  if(0 === set.length) return null;
  var closest = set[0], result = 0;
  for(var i in set) {
     var next = set[i];
     if(Math.abs(closest) > Math.abs(next)) {
       result = i;
       closest = next;
     }
  }
  return closest;
}

function getClosestToZeroWithNaN(set) {
    var closest;
    if(set instanceof Array) {
        for(var i = 0; i < set.length; i++) {
            var val = set[i];
            if(!isNaN(val)){
                val = Number(val);
                var absVal = Math.abs(val);
                    if(typeof closest == 'undefined' || Math.abs(closest) > absVal)                       {
                    closest = val;
                }
            }
        }
    }
    return closest;
}
function getClosestToZeroOnlyNumbers(set) {
    var closest;
    if(set instanceof Array) {
        for(var i = 0; i < set.length; i++) {
            var val = set[i];
            if(typeof val == "number"){
                var absVal = Math.abs(val);
                    if(typeof closest == 'undefined' || Math.abs(closest) > absVal)                       {
                    closest = val;
                }
            }
        }
    }
    return closest;
}

document.getElementById('output').innerHTML = (getClosestToZeroOnlyNumbers(myNumbersToSort));


texts:
I have a RoR 4 app, and its model have these associations:

has_many :accreditations
has_one :legal, -> { where(kind_cd: Accreditation.legal) }, class_name: 'Accreditation'
has_many :departments, -> { where(kind_cd: Accreditation.department) }, class_name: 'Accreditation'

So, you see that these associations similar, but legal & departments have more conditions than accreditations. Can I replace class_name: 'Accreditation' with something like using :accreditations?


texts:
I have the following code in Python which opens and closes a file in every iteration (using with keyword). In 95 % of iterations the file will be the same, so there's no need to open and close it again. Is it possible to optimize it if this optimization has sense?

import sys
import re

def createFileName(str, index, number_of_words, suffix):
  pattern = re.compile("[a-zA-Z]+")
  matchList = re.findall(pattern, str)
  matchList = [x.lower() for x in matchList]
  matchList = matchList[0:number_of_words]
  return index + "_".join(matchList) + suffix

if __name__ == "__main__":

  d = [("aaa", True), ("bbb x yyy aa" False), ("ccc aa", False), ("ddd bbb", True), ("eee ddd", False), ("fff x a b" True)] # this list of tuples is just for illustration, it will be usually much bigger.

  fileName = createFileName(d[0][0], "00", 3, ".txt")
  with open(fileName, "a") as f:
    f.write(d[0][0] + "\n")
  i = 1
  for x in d[1:]:
    if x[1]:
      fileName = createFileName(x[0], "%02d" % i, 3, ".txt")
      i = i + 1
    with open(fileName, "a") as f:
      f.write(x[0] + "\n")


texts: Possible memory leak in a for loop macro

texts:
I was reading about similar problems to the one I am having, and my guess is that I am having a 'memory leak'. I'm not sure exactly what that means, or how to correct it.  Could you take a look at my code and help me optimize?  LastRow in this bit is a little over 70000.

start = Timer
For Row = 4 To LastRow
DoEvents
    If Original.Cells(Row, 4) <> "" Then
    Application.StatusBar = "Progress: " & Row & " out of " & LastRow & ": " & Format(Row / LastRow, "0.00%")
        'VLookUp method
'''''        Data.Cells(DataRow, 1).value = Original.Cells(Row, 4).value
'''''        Data.Cells(DataRow, 2).value = Original.Cells(Row, 39).value
'''''        Result = Evaluate("Vlookup('New Cost Data'!A" & DataRow & ",'PupFile Data'!B:D,3,false)")
'''''
'''''        If IsError(Result) = True Then
'''''            Data.Cells(DataRow, 3) = "No Old Cost"
'''''            DataRow = DataRow + 1
'''''        ElseIf Result = 0 Then
'''''            Data.Cells(DataRow, 3) = "No Old Cost"
'''''            DataRow = DataRow + 1
'''''        Else
'''''            Data.Cells(DataRow, 3) = Result
'''''            Data.Cells(DataRow, 4) = Format((Data.Cells(DataRow, 2) - Result) / Result, "0.00%")
'''''            DataRow = DataRow + 1
'''''        End If

    'Find() method
        Set RNGFound = Range(Pup.Cells(2, 2), Pup.Cells(Pup.Cells(Rows.count, 2).End(xlUp).Row, 2)).Find(Original.Cells(Row, 4))
        If Not RNGFound Is Nothing Then
           PupRow = Range(Pup.Cells(2, 2), Pup.Cells(Pup.Cells(Rows.count, 2).End(xlUp).Row, 2)).Find(Original.Cells(Row, 4), lookat:=xlWhole, searchorder:=xlRows, MatchCase:=True).Row
           Data.Cells(DataRow, 1).Value = Original.Cells(Row, 4).Value
           Data.Cells(DataRow, 2).Value = Original.Cells(Row, 39).Value
           Data.Cells(DataRow, 3).Value = Pup.Cells(PupRow, 4).Value
           Data.Cells(DataRow, 4) = (Data.Cells(DataRow, 2) - Data.Cells(DataRow, 3)) / Data.Cells(DataRow, 3)
        Else
            Data.Cells(DataRow, 1).Value = Original.Cells(Row, 4).Value
            Data.Cells(DataRow, 2).Value = Original.Cells(Row, 39).Value
            Data.Cells(DataRow, 3) = "No old Cost"
        End If
        DataRow = DataRow + 1
    End If
Next Row
Application.StatusBar = False
finish = Timer - start
MsgBox finish
Stop

The Vlookup() method took me about 500 seconds, but it slowed down considerably from the beginning. The find() method looked like it was taking much longer, so I am probably going with the vlookup, but what about the actual slowing down of the code? Is there something I need to change, or is slowing down over time just 'what happens'?


texts: CSV-simplified: A small open source project

texts:
I'm working on a small open source project called CSV-simplified for a course I'm taking (Bloc), and I'm looking for some feedback and potential collaborators. I don't actually know an programmers, so I'm hoping someone here may be interested in helping out.

The basic idea of CSV-simplified is a browser app capable of reading a CSV file and displaying it on the page. I would like to expand upon this by creating an intuitive user interface to allow the user to perform searches and queries on the uploaded file. I'm currently using JavaScript, jQuery, and PapaParse to just display an uploaded file.

I'm looking for any help, suggestions, or feedback on improving and building upon this program. The first thing I'd like to see improved is how the file is displayed, I think editing the JS and adding some CSS could really spruce it up.

Here's the GitHub repo of what's done so far. Here's a Codepen that shows the basic logic that's currently working on the app.

HTML

<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />

JavaScript

document.getElementById('txtFileUpload').addEventListener('change', upload, false);

function upload(evt) {

    var data = null;
    var file = evt.target.files[0];
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function(event) {
        var csvData = event.target.result;
        var data = Papa.parse(csvData, {header : false});
        console.log(data.data);
        var arrayLength = data.data.length;
        console.log(arrayLength);
        for (var i = 0; i < arrayLength; i++) {
            console.log(data.data[i]);
            $("#header").append("
" +
            JSON.stringify(data.data[i]) + "
");
        }
    };
    reader.onerror = function() {
        alert('Unable to read ' + file.fileName);
    };
}


texts:
I have an action bar component. It helps do the CRUD operation for different component.  Its only job is emit events.  The emitted events are listened by the caller component. I am using a switch case logic to emit different events. An input is passed to this component as @Input() itemType: string, which holds the string as to which component called for action, to decide which event to emit. Another input @Input('actionMode') mode: string;, helps the component decide which HTML to display.

Here are the two files:
Component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-actions',
  templateUrl: './actions.page.html',
  styleUrls: ['./actions.page.scss'],
})
export class ActionsPage implements OnInit {
  @Input('itemType') itemName: string;
  @Input('actionMode') mode: string;

  @Output() deleteSummary = new EventEmitter<void>();
  @Output() editSummary = new EventEmitter<void>();
  @Output() saveSummary = new EventEmitter<void>();
  @Output() cancelSummary = new EventEmitter<void>();

  @Output() editCompetency = new EventEmitter<void>();
  @Output() deleteCompetency = new EventEmitter<void>();
  @Output() saveCompetency = new EventEmitter<void>();
  @Output() cancelCompetency = new EventEmitter<void>();

  constructor() {}

  ngOnInit() {
    if (this.mode !== 'question' || 'answer') console.log('Incorrect mode in the action bar');
  }

  onDelete() {
    switch (this.itemName.toLowerCase()) {
      case 'summary':
        this.deleteSummary.emit();
        break;
      case 'competency':
        this.deleteCompetency.emit();
        break;
      default:
    }
  }
  onEdit() {
    switch (this.itemName.toLowerCase()) {
      case 'summary':
        this.editSummary.emit();
        break;
      case 'competency':
        this.editCompetency.emit();
        break;
      default:
    }
  }

  onSave() {
    switch (this.itemName.toLowerCase()) {
      case 'summary':
        this.saveSummary.emit();
        break;
      case 'competency':
        this.saveCompetency.emit();
        break;
      default:
    }
  }

  onCancel() {
    switch (this.itemName.toLowerCase()) {
      case 'summary':
        console.log('emitted Cancel');
        this.cancelSummary.emit();
        break;
      case 'competency':
        this.cancelCompetency.emit();
        break;
      default:
    }
  }
}

The HTML is the following: Component.html

<div *ngIf="mode === 'question'">
  <ion-buttons slot="end">
    <ion-button slot="end" size="small" color="secondary" (click)="onEdit()" routerDirection="forward">
      <ion-icon slot="icon-only" name="create-outline" fill="clear">Edit</ion-icon>
    </ion-button>

    <ion-button slot="end" size="small" color="danger" (click)="onDelete()">
      <ion-icon slot="icon-only" name="trash-outline" fill="clear">Delete</ion-icon>
    </ion-button>
  </ion-buttons>
</div>

<div *ngIf="mode === 'answer'">
  <ion-button (click)="onSave()" type="button" color="primary">
    <ion-icon slot="start" name="save"></ion-icon>
    Save
  </ion-button>

  <ion-button (click)="onCancel()" color="warning" type="button">
    <ion-icon slot="start" name="close-outline"></ion-icon>
    Cancel
  </ion-button>
</div>

Is this a good way to do it ? Although very readable, but seems to me kind of tedious, especially when the number of components grow.

Can I use TypeScript Generics in this case?


texts:
Looking for review, good practices, optimizations, clean code tips etc.

final class Pixel {

    private final int color;

    public Pixel(int color) {
        this.color = color;
    }

    public int getColor() {
        return color;
    }
}

/**
 * Rotates an image by ninety degrees.
 *
 * Complexity:
 * O(row * col)
 */
public final class Rotate {

    private Rotate() { }

    /**
     * Rotes the image in anti clockwise direction.
     *
     * @param   image the image to be rotated.
     * @return  the titled image.
     * @throws  NPE
     */
    public static Pixel[][] rotateAntiClockWise(Pixel[][] image) {
        int col = image.length;
        int row = image[0].length;

        final Pixel[][] rotatedPixel = new Pixel[row][col];

        for (int i = 0; i < image.length; i++) {
            for (int j = 0; j < image[0].length; j++) {
                rotatedPixel[image[0].length -1 -j][i] = image[i][j];
            }
        }
        return rotatedPixel;
    }

    /**
     * Rotates the image in clockwise direction.
     *
     * @param   image the image to be rotated.
     * @returns the rotated image.
     * @throws  NPE
     */
   public static Pixel[][] rotateClockWise(Pixel[][] image) {
       int col = image.length;
       int row = image[0].length;

       final Pixel[][] rotatedPixel = new Pixel[row][col];

       for (int i = 0; i < image.length; i++) {
           for (int j = 0; j < image[0].length; j++) {
               rotatedPixel[j][image.length -1 - i] = image[i][j];
           }
       }
       return rotatedPixel;
   }

   public static void main(String[] args) {
       //   int[][] m = { {1, 2, 3, 4} ,
       //                {10, 20, 30, 40}};
       Pixel[][] image = new Pixel[2][4];
       image[0][0] = new Pixel(1);
       image[0][1] = new Pixel(2);
       image[0][2] = new Pixel(3);
       image[0][3] = new Pixel(4);

       image[1][0] = new Pixel(10);
       image[1][1] = new Pixel(20);
       image[1][2] = new Pixel(30);
       image[1][3] = new Pixel(40);

       Pixel[][] rotatedAntiClockNinetyDegreeImage = rotateAntiClockWise(image);

       /*
        * Expected:
        *
        * 4  40
        * 3  30
        * 2  20
        * 1  10
        *
        */
       for (int i = 0; i < rotatedAntiClockNinetyDegreeImage.length; i++) {
           for (int j = 0; j < rotatedAntiClockNinetyDegreeImage[0].length; j++) {
               System.out.print(rotatedAntiClockNinetyDegreeImage[i][j].getColor() + " ");
           }
           System.out.println();
       }

       System.out.println("==========================================");

       Pixel[][] rotatedClockWiseNinetyDegreeImage = rotateClockWise(image);

       /*
        * Expected:
        *
        * 10  1
        * 20  2
        * 30  3
        * 40  4
        *
        */
       for (int i = 0; i < rotatedClockWiseNinetyDegreeImage.length; i++) {
           for (int j = 0; j < rotatedClockWiseNinetyDegreeImage[0].length; j++) {
               System.out.print(rotatedClockWiseNinetyDegreeImage[i][j].getColor() + " ");
           }
           System.out.println();
       }
    }
}


texts: Initializing and populating a Python dictionary, key -> List

texts:
I have a simple task that comes up often my work. I need to create a dictionary for an id key to a list of data associated with that key. I'm wondering if there is a better way to do this than the one I am using. The pattern is so common that I feel there must be better solution.

value_list_dict = {}

for line in f:
  line.strip()
  rec = line.split("\t")
  my_key = rec[0]
  important_value = rec[5] #or what ever it is

  # the repetitive pattern I find myself doing a lot of.
  if my_key not in value_list_dict:
    value_list_dict[my_key] = []
  value_list_dict[my_key].append(important_value)

While this solution is fairly concise and clear to me, I wonder if there is a better way.

I think that writing a custom function for this might be less readable although I'm open to suggestions.