texts:
I quickly created this function in Lisp that resembles

numpy.random.randint(low, high=None, size=None, dtype='I')

The goal is simply to have a function that creates a list of random integers between low and high and that the list has a certain shape. I did not add the ability to choose the dtype as well, but this would be a possibility.

My function for doing this is the following:

(defun randint (&key (start 0) end (shape '(1)))
  (if (> (length shape) 3)
    (error "Shape can be maximally 3 long")
  (loop for i from 1 upto (first shape)
        if (not (null (rest shape)))
        collect (loop for j from 1 upto (first (rest shape))
                      if (not (null (rest (rest shape))))
                      collect (loop for k from 1 upto (first (rest (rest shape)))
                                    collect (+ start (random (+ 1 (- end start)))))
                      else
                      collect (+ start (random (+ 1 (- end start)))))
        else
        collect (+ start (random (+ 1 (- end start)))))))

Is there a more concise or more elegant way of writing this in Common Lisp?


texts:
I have written a class that acts like a stopwatch using C++11's std::chrono library. I wrote this because I find it difficult to benchmark my cpp code properly, this class just combines chrono's functionality and gives it a nice interface
I have two classes, stopwatch.h and lapwatch.h. The second one has the functionality of a stop watch but also has a lap function which you can use to multiple intervals
stopwatch.h
#ifndef STOPWATCH_H_
#define STOPWATCH_H_
#include <chrono>

template<typename duration = std::chrono::milliseconds>
class StopWatch
{
public:
  using clock      = std::chrono::steady_clock;
  using time_point = std::chrono::time_point<clock, duration>;

  StopWatch() = default;
protected:
  enum class State : unsigned char;

  static constexpr time_point current_time() noexcept
  {
    return std::chrono::time_point_cast<duration>(clock::now());
  }
public:
  virtual void reset() noexcept
  {
    clock_state = State::idle;
  }

  time_point go() noexcept
  {
    if (clock_state != State::stopped)
      start_point = current_time();

    clock_state = State::running;
    return start_point;
  }

  void stop() noexcept
  {
    if (clock_state == State::running)
    {
      stop_point = current_time();
      clock_state = State::stopped;
    }
  }

  duration elapsed_time() const noexcept
  {
    switch (clock_state)
    {
    case State::idle:
      return std::chrono::duration_cast<duration>(clock::duration::zero());

    case State::running:
      return std::chrono::duration_cast<duration>(current_time() - start_point);

    case State::stopped:
      return std::chrono::duration_cast<duration>(stop_point - start_point);

    default:
      return std::chrono::duration_cast<duration>(clock::duration::zero());
      break;
    }
  }

protected:
  enum class State : unsigned char { idle, running, stopped };

  time_point start_point;
  time_point stop_point;
  State      clock_state = State::idle;
};

lapwatch.h

#ifndef LAPWATCH_H_
#define LAPWATCH_H_
#include "stopwatch.h"
#include <vector>

template<typename duration = std::chrono::milliseconds>
class LapWatch : public StopWatch<duration>
{
  using clock      = typename StopWatch<duration>::clock;
  using time_point = typename StopWatch<duration>::clock;
  using StopWatch<duration>::State;

public:
  LapWatch() = default;
  struct Lap
  {
    duration total_time;
    duration split_time;
  };

  void lap()
  {
    if (this->clock_state != StopWatch<duration>::State::running)
      return;

    Lap current;
    if (laps.size() == 0)
      current.total_time = current.split_time = StopWatch<duration>::elapsed_time();
    else
    {
      current.total_time = StopWatch<duration>::elapsed_time();
      current.split_time = (current.total_time - laps[laps.size() - 1].total_time);
    }
    laps.push_back(static_cast<Lap&&>(current));
  }

  void reset() noexcept
  {
    laps.clear();
  }

  std::vector<Lap> laps;
};
#endif // !LAPWATCH_H_

usage example
#include "lapwatch.h"

int main()
{
  LapWatch<> watch;

  watch.go() // start the timer
  // Some time passes

  watch.lap() // Adds the total and split time, but doesn't stop it

  // Some more time passes
  watch.lap() // Adds another lap

  watch.stop() // stop the watch now

  // Laps are added to a vector in watch.laps

  for(auto const& lap : watch.laps) {
    lap.total_time // Total time passed since the start
    lap.split_time // Total time passed since the previous lap
  }
}

Concerns

Is this a good idea? Would you use it?

Is this a nice design?

I have a github repository for it too, if anyone prefers reading code that way.


texts: Measure size of repository as a function of time

texts:
In order to avoid having to make any real progress (at least for a short time), I wrote a script that measures how much progress I have made so far, instead. Specifically, this script sums up the file sizes of files in all commits of a git repository, filtering files either by their endings, a whitelist or not at all, and plots this size against the commit dates.

This script needs gitpython to work.

import argparse
import git
import matplotlib.pyplot as plt
import numpy as np
import os

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--dir", help="Directory of the git repository to analyze (default: '.')", default=os.curdir)
    parser.add_argument("--pattern", help="Count only files ending in pattern")
    parser.add_argument("--files", help="Only count these files", nargs='+')
    return parser.parse_args()

def filter_pattern(pattern):
    """Returns a function that returns True if the file name ends with pattern"""
    return lambda file: file.name.endswith(pattern)

def filter_whitelist(whitelist):
    """Returns a function that returns True if the file name is in whitelist"""
    whitelist = set(whitelist)
    return lambda file: file.name in whitelist

def get_file_sizes(commit, filter_func=None):
    """Return the sum of the file sizes in the commit.

    Counts only files passing filter_func.
    """
    return sum(file.size
               for file in filter(filter_func, commit.tree.traverse()))

def get_file_sizes_per_commit(repo, filter_func=None):
    """Get the filesizes in all commits of repo.

    Counts only files passing filter_func.
    Ordered from oldest to newest commit.
    """
    return np.array([get_file_sizes(commit, filter_func)
                     for commit in repo.iter_commits()])[::-1]

def get_commit_dates(repo):
    """Get the commit dates of all commits in repo.
    Ordered from oldest to newest.
    """
    return np.array([commit.committed_datetime
                     for commit in repo.iter_commits()])[::-1]

def plot_repo_size(repo, filter_func):
    sizes = get_file_sizes_per_commit(repo, filter_func)
    dates = get_commit_dates(repo)

    plt.plot(dates, sizes)
    plt.ylabel("Repository size")
    plt.xlabel("Commit date")
    plt.yscale("log")
    plt.show()

if __name__ == "__main__":
    args = parse_args()
    filter_func = filter_whitelist(args.files) if args.files else filter_pattern(args.pattern) if args.pattern else None

    repo = git.Repo(args.dir)
    plot_repo_size(repo, filter_func)

I am looking for general feedback as well as how to improve setting the filter function from the parsed arguments.

I am aware that it is not strictly necessary for the data I'm plotting to be numpy.arrays, but I wanted to be able to expand this script in the future and they are just easier to work with (I might even make it a pandas.DataFrame to be able to restrict the date range, interpolate to the future, etc).

With the repository I am using this on, this produces the following image when run with python plot_progress.py --pattern .tex:


texts: Parsing an IP address (Bit manipulation)

texts:
Given a string representing of an IP address, such as "127.43.23.59", return a 32 bit integer representation of this string. The 32 bit integer is separated into four bytes, where each byte is one of the numbers in the string, separated by dots. If you  & 0xFF with the returned integer, it should return 59. If you & 0xFF00 with the returned integer, it should return 23, etc.

public class IP{
    public static void main(String[] args)
    {
        IP address = new IP();
        int x = address.IPAddress("127.43.29.56");
    }
    public int IPAddress(String str)
    {
        int byte1 = 0;
        int numbers[] = new int[4];
        int index = 0;
        int finalByte = 0;
        for(int i = 0; i < str.length(); i++)
        {
            if(str.charAt(i) != '.')
                byte1 = 10*byte1 + (str.charAt(i) - 48);
            else
            {
                numbers[index++] = byte1;
                byte1 = 0;
            }
        }
        numbers[index] = byte1;
        return finalByte = (numbers[0]<<24) | (numbers[1]<<16)|
                    (numbers[2]<<8) | (numbers[3]);
    }
}


texts: Java Generics - Write a generic method to find the maximal element in the range [begin, end] of a list

texts:
I'm a Java beginner, going through the Generics Questions and Exercises in Oracle's The Java Tutorials.

Here's my solution to #8:

  Write a generic method to find the maximal element in the range [begin, end] of a list.

All suggestions for improvement are welcome. I'd especially like feedback on the following:

Java library usage
Algorithm performance
Exceptions

(imports omitted for brevity)

@SuppressWarnings("serial")
class MaximalElementList<E extends Comparable<E>> extends ArrayList<E> {

    /**
     * @param begin - list index to start iterating from (inclusive)
     * @param end - list index to iterate up to (exclusive)
     * @return max elem in list as determined by the compareTo of the element type.
     */
    public E getMaxInRange(int begin, int end) {
        E max;
        if (isEmpty())
            throw new IllegalStateException("Can't get a max element from an empty list.");
        else {
            max = this.get(begin);
            for (E elem : this.subList(begin, end)) {
                if (elem.compareTo(max) > 0) {
                    max = elem;
                }
            }
        }
        return max;
    }
}


texts:
This is the first piece of code I've written on my own since I started learning a couple of months ago. The code works and it takes an int as input and creates a linked list with each node representing a digit. I've added a function that sums two linked listed ints and returns a third list with the result. The rest of the code is also distributed in functions.

Before I move on, it would be greatly appreciated to know if I'm doing something wrong, if my code is properly structured or if I'm following a good/bad style.

#include <iostream>

using std::cout;
using std::cin;

struct intNode {
    int num;
    intNode *next;
};

int deallocateList(intNode *&s);
int intConversionHelper(int n);
int lenList(intNode *&s);
int sumListContent(intNode *&s);
intNode *sumLists(intNode *&s1, intNode *&s2);
int printNode(intNode *&s);
int intLen(int n);
intNode *intToList(int n);
void append(intNode *&s, int n);

int main() {
    int num1;
    int num2;
    cout << "Give me number 1: ";
    cin >> num1;

    cout << "Give me number 2: ";
    cin >> num2;

    intNode *list1 = intToList(num1);
    intNode *list2 = intToList(num2);
    cout << "\nPrinting ints as linked lists: \n";
    printNode(list1);
    printNode(list2);

    cout << "\nSum of the two lists (as a list too!)\n";
    intNode *sumList = sumLists(list1, list2);
    printNode(sumList);

    deallocateList(list1);
    deallocateList(list2);
    deallocateList(sumList);
}

int printNode(intNode *&s) {
    intNode *tmp = s;

    while (tmp != NULL) {
        cout << tmp->num;
        tmp = tmp->next;
    }
    cout << "\n";
}

int intLen(int n) {
    int len = 1;
    while (n > 9) {
        len++;
        n /= 10;
    }
    return len;
}

intNode *intToList(int n) {
    intNode *intList = NULL;
    int num;
    int dec = 10;

    num = n % 10;
    append(intList, num);
    int count = 1;
    while (count < intLen(n)) {
        num = n / dec % 10;
        dec = dec * 10;
        append(intList, num);
        count++;
    }
    return intList;
}

void append(intNode *&s, int n) {
    if (s == NULL) {
        s = new intNode;
        s->num = n;
        s->next = NULL;
    }
    else {
        intNode *nNode = new intNode;
        nNode->num = n;
        nNode->next = s;
        s = nNode;
    }
}

intNode *sumLists(intNode *&s1, intNode *&s2) {
    int sum1 = sumListContent(s1);
    int sum2 = sumListContent(s2);
    return intToList(sum1 + sum2);
}

int sumListContent(intNode *&s) {
    intNode *tmp = s;
    int sum = 0;
    int len = lenList(s);
    while (tmp != NULL) {
        sum += intConversionHelper(len) * tmp->num;
        len--;
        tmp = tmp->next;
    }
    return sum;
}

int lenList(intNode *&s) {
    intNode *tmp = s;
    int len = 0;
    while (tmp != NULL) {
        len++;
        tmp = tmp->next;
    }
    return len;
}

int intConversionHelper(int n) {
    float value = n;
    for (int i = 1; i < n; i++) {
    value = value * 10;
    }
    value = value / n;
    return value;
}

int deallocateList(intNode *&s) {
    intNode *tmp = s;
    while (s != NULL) {
        tmp = tmp->next;
        delete[] s;
        s = tmp;
    }
}


texts:
I like Node.js and typescript a lot, but i'm still pretty much a newbie with streams. I know how to use them, but I have trouble understanding how the work, what are the consequences of using them, etc.

I've made a wrapper (feel free to use it, it's on NPM) around the stream, using array like functions, while keeping types correct with TS (which, I think, event-stream doesn't do efficiently).

https://github.com/AGallouin/Node.ts-Streams

Thanks a lot for any advice !

import { Readable, Transform, Writable } from 'stream'

export class Stream<T> {
  private readonly underlying: Readable

  constructor(stream: Readable) {
    this.underlying = stream
  }

  static fromArray<T>(input: Array<T>): Stream<T> {
    const readable = new Readable({
      objectMode: true,
      read: () => {}
    })

    for (let i = 0; i < input.length; i++) {
      readable.push(input[i])
    }
    readable.push(null)

    return new Stream<T>(readable)
  }

  map<O>(map: (value: T) => O | Promise<O>): Stream<O> {
    const stream = new Transform({
      objectMode: true,
      transform: (data, encoding, callback) => {
        Promise.resolve(map(data))
          .then((v) => callback(undefined, v))
      }
    })

    this.underlying.pipe(stream)

    return new Stream<O>(stream)
  }

  reduce<O>(reducer: (acc: O, curr: T) => O, initialValue: O): Stream<O> {
    let acc = initialValue
    const wStream = new Writable({
      objectMode: true,
      write: (curr, encoding, next) => {
        acc = reducer(acc, curr)
        next()
      }
    })
    const rStream = new Readable({
      objectMode: true,
      read: () => {}
    })

    this.underlying
      .pipe(wStream)
      .on('finish', () => {
        rStream.push(acc)
        rStream.push(null)
      })

    return new Stream<O>(rStream)
  }

  filter(filter: (value: T) => boolean): Stream<T> {
    const stream = new Transform({
      objectMode: true,
      transform: (data, encoding, callback) => {
        if (filter(data)) {
          callback(undefined, data)
        } else {
          callback()
        }
      }
    })

    this.underlying.pipe(stream)

    return new Stream<T>(stream)
  }

  addWritingStream(write: (chunk: T, encoding: string, callback: (error?: Error | null) => void) => void): Promise<boolean> {
    return new Promise((resolve, reject) => {
      const stream = new Writable({ objectMode: true, write })

      this.underlying
        .pipe(stream)
        .on('finish', () => {
          resolve(true)
        })
        .on('error', () => {
          reject(false)
        })
    })
  }

  split(nbElements: number): Stream<Array<T>> {
    let acc: Array<T> = []
    const rStream = new Readable({
      objectMode: true,
      read: () => {}
    })
    const wStream = new Writable({
      objectMode: true,
      write: (curr, encoding, next) => {
        acc.push(curr)
        if (acc.length === nbElements) {
          rStream.push(acc)
          acc = []
        }
        next()
      }
    })

    this.underlying
      .pipe(wStream)
      .on('finish', () => {
        if (acc.length > 0) {
          rStream.push(acc)
        }
        rStream.push(null)
      })

    return new Stream<Array<T>>(rStream)
  }

  toArray(): Promise<Array<T>> {
    return new Promise((resolve) => {
      const acc: Array<T> = []
      const wStream = new Writable({
        objectMode: true,
        write: (curr, encoding, next) => {
          acc.push(curr)
          next()
        }
      })

      this.underlying
        .pipe(wStream)
        .on('finish', () => {
          resolve(acc)
        })
    })
  }
}


texts: Filtering what strategy to use in strategy pattern

texts:
I have a situation where I've used the strategy pattern but got many different strategies that are available to the client code that needs to select the appropriate strategy, this is because there's a lot of different usages to the strategy depending on the machine that's being calculated, because of the domain it's being used in.
My question is specifically about the filter part of the code, the part where a relevant strategy is picked, I decide to filter first on the location, then the main category of the machine object and then the MachineName (an enum). These can all influence what kind of calculation can be done.
A machine object looks like this (other parts removed for brevity):
public class Machine() {
  public Category MainCategory   { get; set; }
  public MachineName MachineName { get; set; }
  public Location MachineLocation {get; set; }
}

My filter code for the client part looks like this, note that there are around 30-35 options in total based on either the MachineName or the machine location (first in line for example).
public void BasicFilter(Machine Current_Machine)
{
  if(Current_Machine.MachineLocation == 1) { _strategyService.SetStrategy(new FirstMachineStrategy);}
  else if ( Current_Machine.MainCategory == MainCategory.Producer)
  {
    switch (Current_Machine.MachineName)
            {
                case MachineName.MultiRoller:
                  _strategyService.SetStrategy(new MultiRollerStrategy);
                // Other options removed for brevity
                default:
                 _strategyService.SetStrategy(new RollerStrategy);
            }
  }
  else if ( Current_Machine.MainCategory == MainCategory.Reciever)
  {
    _strategyService.SetStrategy(new RecieverStrategy);
  }
}

For completeness sake; I've also added a strategy as an example, again this differs on the location, name, or category. Where the strategy below is one of the default one(s)
public class RollerStrategy : ICalculationStrategy
{
    public object CalculateSteelValues(Machine Current_Machine, Machine Last_Machine)
    {
        Current_Machine.SteelAmount = Last_Machine.SteelAmount;

        if (Current_Machine.Reduction == 0)
        {
            // Can't divide through 0. So do nothing
        } else
        {
            Current_Machine.SteelThickness = Last_Machine.SteelThickness / Current_Machine.Reduction;
            Current_Machine.SteelWidth = Last_Machine.SteelWidth + Last_Machine.SteelThickness - Current_Machine.SteelThickness;
        }

        return Current_Machine;
    }

Is there a better implementation for filtering the different strategies, or something that would be cleaner to maintain, I didn't use a singular switch case statement on the name because I thought it would clutter and I'd need to find another solution for the location(s).
I've just recently started to use this pattern, so I was wondering if I was missing something.
EDIT:
The machine enums are nothing more than it's the exact name; here's a sample of the Enum's used:
    public enum MachineName
    {
         MultiRoller,
         TwoRoller,
         // Etc
    }

    public enum Category
    {
      Blank,
      Roller,
      Infeed,
    }

    public enum Location
    {
      Blank,
      FirstInLine,
      LastInLine,
    }


texts: Destructively appending one list to another

texts:
I am implementing a list structure in C. My current function I am working on is a destructive append function that takes two lists and appends the second one onto the end of the first. Right now, it appears to be working without runtime errors and memory leaks and I think I have all my cases covered, but when I submit it to my testing server, it says it is not correct. I was wondering if anyone could see any flaws that could cause it to not do what I expect it to do.

The append function:

ilist iappend_destroy(ilist il1, ilist il2){
   if(il1 == NULL && il2 == NULL){
      free(il1);
      free(il2);
      return NULL;
   }else if(il1 == NULL){
      free(il1);
      return(il2);
   }else if(il2 == NULL){
      free(il2);
      return(il1);
   }else{

   ilist tmp = iempty();
   ilist clone = il1;

   while(il1 != NULL){
      tmp = icons_destroy(il1->first, tmp);
      il1 = il1->rest;
   }

   ilist tmpclone = tmp;

   while(tmp != NULL){
      il2 = icons_destroy(tmp->first, il2);
      tmp = tmp->rest;
   }

   idelete(tmpclone);
   idelete(clone);
   return il2;
   }

The declaration of the ilist structure:

struct ilist_ADT{
    struct ilist_ADT *rest;
    int first;
};

The icons_destroy function:

ilist icons_destroy(int in, ilist il){
   if (il == NULL) {
      ilist anewlist = malloc(sizeof(struct ilist_ADT));
      anewlist->first = in;
      anewlist->rest = NULL;
      return (anewlist);
   } else {
      ilist previous = malloc(sizeof(struct ilist_ADT));
      previous->first = il->first;
      previous->rest = il->rest;
      il->first = in;
      il->rest = previous;
      return il;
   }
}


texts: Extracting Linux configuration information using Bash and Perl

texts:
For few days I'm thinking about making my code faster and using less CPU. This code is a statusbar that runs in a loop. I'm asking because there's a lot of perl and I'm wondering if it could be done better.

date=$( date +"%F %R" )

battery=$(acpi -b | perl -n -e '/(\S+),\s+([0-9]+\%),\s(\S*)\s/ && print $1," ",$2," [ ",$3," ]"')

RAM=$(free -m | perl -n -e '/Mem\:\s*([0-9]+)\s*([0-9]+).*/ && print "RAM: (",$2," / ",$1,")MB"')

VolumeLv=$(amixer get Master -c 1 | perl -n -e '/\[(.*)\%\]/ && print $1')

backLightLv=$(xbacklight | perl -n -e '/^([0-9]*)/ && print $1')
statusBacklight=$?
backLightBar=""
VolumeBar=""
Sign=":"
NoSign="."
for i in $(seq 1 2 100)
do
    if [ $i -gt $VolumeLv ]
    then
        VolumeBar=$(echo "$VolumeBar$NoSign")
    else
        VolumeBar=$(echo "$VolumeBar$Sign")
    fi
    if [ $statusBacklight -eq 0 ] && [ $i -gt $backLightLv ]
    then
        backLightBar=$(echo "$backLightBar$NoSign")
    else
        backLightBar=$(echo "$backLightBar$Sign")
    fi
done

ETHcards=""
for interface in $(iwconfig 2> /dev/null | perl -n -e '/^([a-zA-Z0-9]*)\s.*ESSID\:.*$/ && print $1,"\n"')
do
    IPANDMASK=$(ifconfig $interface | perl -n -e '/.*inet\ addr:([0-9\.]+).*Mask:([0-9\.]*)\s/ && print $1, "/", $2')
    MAC=$(ifconfig $interface | perl -n -e '/HWaddr\s+([a-f0-9\:]+)\s*/ && print $1')

    AP=$(iwconfig $interface 2>/dev/null | perl -n -e '/ESSID\:(\S*)/ && print $1')
    MODE=$(iwconfig $interface 2>/dev/null | perl -n -e '/Mode:(\S+)\s/ && print $1')

    ETHcards=$(echo "$ETHcards [ $interface ][ $MAC ][ $AP ][ $IPANDMASK ][ $MODE ]  //  ")
done
xsetroot -name "$date :: $battery;Volume: [$VolumeBar]$Mute $VolumeLv%    BackLight: [$backLightBar] $backLightLv%  //  $RAM  //  $ETHcards"


texts:
I've been trough a few css tutorials. I've also been using basic css for a while now.

My question, How do you decide witch css to use. For instance.
If you want a div box to show on the left. You can either use.

float: left;

or

position: absolute;

Another one would be, if you have a paragraph tag inside a div and you want to set its width or height. Do you use

width: auto;
height: auto;

or

width: 100%;
height: 100%;

or

padding: 5px;


texts: Calisthenics objects, and primitive wrapped in Objects

texts:
I m working on calisthenics objects and I'm actually having some troubles while trying to follow the calisthenic objects rules.

In fact, I m stuck with the one telling that we have to wrap all the primitives inside of objects.

Context

I'm having a Euro object that looks like :

public class Euro {

    private double amount;

    public Euro(double amount) {
        this.amount = amount;
    }

    @Override
    public boolean equals(Object obj) {
        Euro other = (Euro)obj;
        return other.amount == amount;
    }

    // Problems come here
    public Euro multiply(double priceValue) {
        Euro newAmount = new Euro(amount * priceValue);
        return newAmount;
    }

    public Euro add(Euro valueToAdd) {
        Euro newPrice = new Euro(amount + valueToAdd.amount);
        return newPrice;
    }
}

And I m having a Discount class. In fact, we can apply Discount on product, the the amount we obtain is a Euro :

public class Discount {

    private double value;

    public Discount(double theValue) {
        value = theValue;
    }

    public Euro apply(Euro price) {
        return price.multiply(value);
    }
}

Problem

My problems appear on the multiply method of the Euro object.

In fact, currently, I m accepting a double as parameter, and it doesn't follow the rule of wrapping all primitives in objects... Moreover, a "double" in a business context doesn't mean anything at all. I m a little bit stuck with this example and don't know how to bypass this.

Moreover, I don't want to use getter / setter on this implementation...

Any suggestions ?


texts:
I'm quite new to Laravel, and I'm not sure what am I doing is the best practice.

I'd like to return JSON if the request is Ajax, or return a view otherwise. This is the way I made it, and it works fine, but I'm not sure if this is the best way(it seems long winded). I'd really like to hear your suggestions.

public function store()
{
    $input = Input::all();

    if(!$this->settings->fill($input)->isValid())
    {
        if ( Request::ajax() ){
            return $this->jsonFailure(array(
                'errors' => $this->settings->errors
            ));
        }
        else{
            return Redirect::route('admin.settings.create')
                ->withInput()
                ->withErrors($this->settings->errors);
        }
    }

    $this->settings->save();

    if ( Request::ajax() )
        return $this->jsonSuccess('success');
    else
        Redirect::route('admin.settings.index');
}


texts: Efficient implementation of aggregating test/train data

texts:
Here is a short python snippet to ingest train data:

x_train = []
y_train = []

for x,y in train:
    x_train.append(x)
    y_train.append(y)

x_train = np.asarray(x_train)
y_train = np.asarray(y_train)

The variable train is a list of 60000 (x,y) tuples.


texts: Calculate mean, median, and mode from list of integers

texts:
I am trying to solve a problem put in The Rust Programming Language #2

  Given a list of integers, use a vector and return the mean (average), median (when sorted, the value in the middle position), and mode (the value that occurs most often; a hash map will be helpful here) of the list.

I decided to put the values in a simple struct and return a Result. I want to be sure I'm using all the language features within the calculations and I want to reduce the amount of casts if possible.

use std::collections::HashMap;

/// structure to represent the values after calculating the mean,
/// median, and mode of some integers.
/// the mode Vec holds each individual mode.
#[derive(Debug)]
pub struct Calculations {
    mean: f64,
    median: f64,
    mode: Vec<i32>,
}

/// calculates the mean, median, and mode of values.
/// returns a Result holding a Calculations or an error string
/// when given an empty slice
pub fn calculate_mmm(values: &[i32]) -> Result<Calculations, &str> {
    // if input is an empty slice, return an error message
    if values.is_empty() { return Err("Found empty slice") }

    // add all numbers together and divide by length
    let mean = values.iter().fold(0, |p, &q| p + q) as f64 / values.len() as f64;

    // sort all values and return middle element or average of middle 2 elements
    let median = {
        let mut sorted = values.to_vec();
        sorted.sort();

        if sorted.len() % 2 == 0 {
            (sorted[sorted.len() / 2] + sorted[(sorted.len() / 2) + 1]) as f64 / 2.0
        } else {
            sorted[(sorted.len() as f64 / 2.0) as usize] as f64
        }
    };

    // holds modes
    let mut mode: Vec<i32> = Vec::new();

    // holds each number and the number of times it occures
    let mut occurrences = HashMap::new();

    for i in values {
        let count = occurrences.entry(i).or_insert(0);
        *count += 1;
    }

    // the maximum times a value occurres
    let mut max_value = 0;

    for &value in occurrences.values() {
        if value > max_value {
            max_value = value;
        }
    }

    // find the numbers which occur the maximum number of times
    for (key, value) in occurrences {
        if value == max_value {
            mode.push(*key);
        }
    }

    // return all values
    Ok(
        Calculations { mean: mean as f64, median: median as f64, mode: mode }
    )
}


texts: Reuse the value of previous type instead of None

texts:
I've created a function in python to print some information through it. I'm trying to supply list of alphabets to the function along with the type those alphabets fall under.

When I execute the function, It checks whether the value of the type is None. If it is None, it executes the except block to fetch one.

I've tried with (working one):

def get_info(alpha,alpha_type):

    print("checking value of item:",alpha_type)

    try:
        if not alpha_type:raise
        return alpha,alpha_type
    except Exception:
        alpha_type = "vowel"
        return get_info(alpha,alpha_type)

if __name__ == '__main__':
    main_type = None
    for elem in ["a","e","o"]:
        result = get_info(elem, alpha_type=main_type)
        main_type = result[1]
        print(result)

Output it produces (as expected):

checking value of item: None
checking value of item: vowel
('a', 'vowel')
checking value of item: vowel
('e', 'vowel')
checking value of item: vowel
('o', 'vowel')

Although the value of the type is None when an alphabet is supplied to the function, ain't there already the value of previous type (when run twice) stored in the memory. However,
When I try like the following, I get messy output:

def get_info(alpha,alpha_type):

    print("checking value of item:",main_type)

    try:
        if not alpha_type:raise
        return alpha,alpha_type
    except Exception:
        alpha_type = "vowel"
        return get_info(alpha,alpha_type)

if __name__ == '__main__':
    for elem in ["a","e","o"]:
        print(get_info(elem,alpha_type=None))

Output the second function produces:

checking value of item: None
checking value of item: vowel
('a', 'vowel')
checking value of item: None
checking value of item: vowel
('e', 'vowel')
checking value of item: None
checking value of item: vowel
('o', 'vowel')

I would like to get the expected output (what the first function produces) following the design of the second function, so that I don't need to influence the result from outside of the function.


texts:
Question:

  Find the sum of multiples of 3 or 5 up to 1000

I have come up with this solution that is bit more generic than the first 1000 per se:

let multiplesSum = n => {

  let sum = 0

  for (let i = 0; i < n; i++) {
    if (i % 3 === 0 || i % 5 === 0) {
      sum += i
    }
  }
  return sum
}

Instead of pushing everything to an array use a variable and sum the numbers as they are looping.


texts: Optimizing and improving a username regex

texts:
I have created this regular expression to validate usernames which I need in my projects:

^(?=.{3,32}$)(?!.*[._-]{2})(?!.*[0-9]{5,})[a-z](?:[\w]*|[a-z\d\.]*|[a-z\d-]*)[a-z0-9]$

It works just fine. But I'm wondering if there is any improvement and optimization for it, since I'm not exactly a regex-guy.

The regex and tests are available here.

Rules are:

usernames should start with [a-z]
usernames should end with [a-z0-9]
usernames can have a length between 3 and 32
usernames can contain any of [a-z0-9\._-]
Numbers should not be in the vicinity of each other more than 4 times. I mean p1234 is a match and p12345 is not.
each username can contains only one of [\._-]. I mean a username can contain . or - or _
each ., -, and _ should be followed by an alpha-numeric. I mean a . can not be followed by another .. They should not be in the vicinity of each other.

Tests:

j1vad-amiry            match
j1vad-ami-ry           match
ja23d_am8ry            match
ja_23d_am8ry           match
jav5d2.am3y            match
jav.ad.amiry           match
jav.ad.ami.ry.2        match
ja3fd4                 match
page2491               match
page24915              not match
jav-ad_amiry           not match
javad_am-iry           not match
jav.ami-ry             not match
jav.ami_ry             not match
jav.ami__ry            not match
2jav                   not match
2jav_ad                not match
2jav_ad3               not match


texts:
I would like some feedback on my red black tree implementation. Anything is fine. I've debugged this and it seems to be working fine, however I may have missed something.

Basically, this is a red black tree that stores character strings as keys and the passage that contains those strings as values. Since these keys are able to be repeated, they form a linked list as well.

    TNODE *tree_add(TNODE *root, const KEY k, const VALUE v) {
        LNODE *lnode = NULL;
        if (root == NULL) {
                TNODE *node = talloc(k);
                lnode = lalloc(v);
                node->head = lnode;
                node->tail = lnode;
                node->is_red = true;
                return node;
        }
        if (strcmp(k, root->key) < 0) {
                root->left = tree_add(root->left, k, v);
        } else if (strcmp(k, root->key) > 0) {
                root->right = tree_add(root->right, k, v);
        } else {
                if (strcmp(k, root->key) == 0) {
                        lnode = lalloc(v);
                        root->tail->next = lnode;
                        root->tail = lnode;
                        root->tail->next = NULL;
                }
        }
        if (is_red(root->right) && !is_red(root->left)) {
                root = rotate_left(root);
        }
        if (is_red(root->left) && is_red(root->left->left)) {
                root = rotate_right(root);
        }
        if (is_red(root->left) && is_red(root->right)) {
                flip_colors(root);
        }
        return root;

}

Here are TNODE and LNODE:

    // LNODE is the data structure for a singly linked list.
typedef struct lnode {
  VALUE val;          // A pointer to the value stored in the linked list.
  struct lnode *next; // Pointer to the next item in the list; it should be NULL if there is no successor.
} LNODE;

typedef struct tnode {
  KEY key;             // Search key for this binary search tree node.
  struct tnode *right; // Right child.
  struct tnode *left;  // Left child.

  LNODE *head; // Head of the linked list storing the values for the search key.
  LNODE *tail; // Tail of the linked list storing the values for the search key.

  bool is_red; // Flag use only in red-black trees to denote redness.
} TNODE;

Here are some more functions: TALLOC, LALLOC, and rotate

    TNODE *talloc(const KEY k) {
        TNODE *tnode = malloc(sizeof(TNODE));
        if (tnode == NULL) {
                return NULL;
        }
        tnode->key = k;
        tnode->is_red = false;
        tnode->head = NULL;
        tnode->tail = NULL;
        tnode->right = NULL;
        tnode->left = NULL;
        return tnode;
}

LNODE *lalloc(const VALUE v) {
        LNODE *lnode = malloc(sizeof(LNODE));
        if (lnode == NULL) {
                return NULL;
        }
        lnode->val = v;
        lnode->next = NULL;
        return lnode;
}

TNODE *rotate_left(TNODE *h) {
        TNODE *x = h->right;
        h->right = x->left;
        x->left = h;
        x->is_red = h->is_red;
        h->is_red = true;
        return x;

}

TNODE *rotate_right(TNODE *h) {
        TNODE *x = h->left;
        h->left = x->right;
        x->right = h;
        x->is_red = h->is_red;
        h->is_red = true;
        return x;
}

void flip_colors(TNODE *h) {
        h->is_red = true;
        h->left->is_red = false;
        h->right->is_red = false;
}


texts: Get Image From Stream, TCP Stream without converting to MemoryStream first

texts:
IS it possible to read directly from the TCPStream to get an image if I know the size and all that, without first saving it to a memorystream?

My code currently works with putting the first 4 byte in the TCP stream as a length for the entire data, so first I send the length. And then I know the length so I recieve it.

But I am saving it to a MemoryStream first, and it would save time to get it directly from the Stream if possible.

  tempBytes = new byte[length];
  ms = new MemoryStream(tempBytes);

     int currentPosition = 0;
     while (currentPosition < length)
     {
     currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);
     }
     newImage = Image.FromStream(ms);

  currentPosition = 0;
  while (currentPosition < intsize)
   {
    currentPosition += tt1.GetStream().Read(lenArray, currentPosition, intsize - currentPosition);
   }

    length = BitConverter.ToInt32(lenArray, 0);

So this is in a while loop, so you can see, I get the length (well I get it at the end, but I have already got it before the while loop for the first run). Then I read the length of data into a memorystream, then get the image.

But as a NetworkStream is a Stream already, there should be possible to just read it directly.

So is there a way to do this to improve the performance?

EDIT:

Pseudo code of what I mean:

Read length from Stream:

tt1.GetStream().Read(lenArray,0,4);
length = BitConverter.ToInt32(lenArray, 0);

Read and get the Image

Image = tt1.GetStream().Read(data,0,length)

This of course doesn´t work, but it´s what I am trying to do.
I want to read directly from the stream, and as I know the length and all that, it should be possible I think, without having to save to a byte array inside a memorystream.


texts: Copying from sheet to sheet if column headings match

texts:
Basically, I have three sheets in my workbook where only the second and third worksheets are being used. I want to copy columns from the second sheet to the third sheet only if the column headings match. For example, the code will check the first row of sheet2 to check if it matches any of strings in an array and if it matches, it will copy the entire column to the third sheet under the same heading.

This code takes too long to process and I would like to make it faster.

Sub Standardization()

Dim myHeaders, e, x, wsImport As Worksheet, wsMain As Worksheet
Dim r As Range, c As Range

myHeaders = Array(
Array("Account_ID", "Account_ID"), Array("Claim_ID", "Claim_ID"), Array("Account_Name", "Account_Name"), _
Array("Claim_Type", "Claim_Type"), Array("Coverage", "Coverage"), Array("Claim_Level", "Claim_Level"), Array("Claim_Count", "Claim_Count"), _
Array("File_Date", "File_Date"), Array("File_Year", "File_Year"), Array("Resolution_Date", "Resolution_Date"), _
Array("Resolution_Year", "Resolution_Year"), Array("Claim_Status", "Claim_Status"), Array("Indemnity_Paid", "Indemnity_Paid"), _
Array("Disease_Category", "Disease_Category"), Array("State_Filed", "State_Filed"), Array("First_Exposure_Date", "First_Exposure_Date"), _
Array("Last_Exposure_Date", "Last_Exposure_Date"), Array("Claimant_Employee", "Claimant_Employee"), Array("Claimant_DOB", "Claimant_DOB"), _
Array("Claimant_Deceased", "Claimant_Deceased"), Array("Claimant_DOD", "Claimant_DOD"), Array("Claimant_Diagnosis_Date", "Claimant_Diagnosis_Date"), _
Array("Product_Type", "Product_Type"), Array("Product_Line", "Product_Line"), Array("Company/Entity/PC", "Company/Entity/PC"), _
Array("Plaintiff_Law_Firm", "Plaintiff_Law_Firm"), Array("Asbestos_Type", "Asbestos_Type"), Array("Evaluation_Date", "Evaluation_Date"), _
Array("Tier", "Tier"), Array("Data_Source", "Data_Source"), Array("Data_Source_Category", "Data_Source_Category"), _
Array("Jurisdiction/County", "Jurisdiction/County"), Array("Settlement_Demand", "Settlement_Demand"), Array("Jury_Verdict", "Jury_Verdict"), _
Array("Exposure_Site", "Exposure_Site"), Array("National_Defendant_Firm", "National_Defendant_Firm"), Array("Local_Defendant_Firm", "Local_Defendant_Firm"), _
Array("Expense_Amount", "Expense_Amount"), Array("NCC_Expense_Amount", "NCC_Expense_Amount"), Array("Non_NCC_Expense_Amount", "Non_NCC_Expense_Amount"))

Set wsImport = ThisWorkbook.Sheets(2)
Set wsMain = ThisWorkbook.Sheets(3)

Application.ScreenUpdating = False

For Each e In myHeaders
Set r = wsImport.Cells.Find(e(0), , , xlWhole)

If Not r Is Nothing Then
    Set c = wsMain.Cells.Find(e(1), , , xlWhole)

    If Not c Is Nothing Then
        wsImport.Range(r.Offset(1), wsImport.Cells(Rows.Count, r.Column).End(xlUp)).Copy _
        wsMain.Cells(Rows.Count, c.Column).End(xlUp)(2)
    Else
        msg = msg & vbLf & e(1) & " " & wsMain.Name
    End If
Else
    msg = msg & vbLf & e(0) & " " & wsImport.Name
End If

Next

Application.ScreenUpdating = False
wsMain.Columns("A:AO").Select
Selection.EntireColumn.AutoFit

Application.ScreenUpdating = False
Selection.ClearFormats

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium9"

Application.ScreenUpdating = True

End Sub


texts: Get character occurence count along with character in a string

texts:
I want to find character sequence count in a given string.

Sample Input: aaaabbbbaaacccbbb

Output: a4b4a3c3b3

My below function is working great and giving me the same result. but can this be optimized?

function getCharCount(str) {
    var result = str.charAt(0);
    var count = 1;
    if (str.length == 1) {
        result += count;
        return result;
    } else {
        for(var i=1;i<str.length;i++) {
            if(str.charAt(i) != str.charAt(i-1)) {
                result += count + str.charAt(i);
                count = 1;
            } else {
                count++;
            }
            if (i == str.length - 1) {
                result += count;
            }
        }
        return result;
    }
}


texts: My minesweeper implementation in Javascript

texts:
I'm beginner coder and I would like to request for critique review of my minesweeper implementation. Game was made using bootstrap 3 and game board itself is a simple html DOM table. Game is complete and working but I feel it could be written in more simple and elegant manner. What in my code can be improved/written in different/better way? In game page you can choose size of board, then you have to click "start" to generate board and start the game. Ctrl + click on cell to flag it and prevent accidental click.

Main function responsible for revealing cells:

function reveal(ev){
  var x = parseInt(this.getAttribute('x')),
      y = parseInt(this.getAttribute('y'));

  if(ev.ctrlKey == false){
    if(cells[getFieldId(x,y)].markedByPlayer == false){

      if(cells[getFieldId(x,y)].hasBomb == true){
        document.getElementById(x+'x'+y).innerHTML = '*';
        alert('Bomb! You have lost.');
        gameState = 'loss';
        revealMap();
      }else if(cells[getFieldId(x,y)].neighbourNumber > 0 && cells[getFieldId(x,y)].hasBomb != true){
        document.getElementById(x + 'x' +y).innerHTML = cells[getFieldId(x,y)].neighbourNumber;
        cells[getFieldId(x,y)].hasBeenDiscovered = true;
        pointColor(x,y,'midnightblue');
        document.getElementById(x+'x'+y).style.color = 'silver';
        revealFields(x,y);
      }else{
        revealFields(x,y);
      }

      if(checkVictoryCondition() == bombsNumber){
        alert('You have won!');
        revealMap();
      }
    }
  }else if(ev.ctrlKey == true){

    if(cells[getFieldId(x,y)].markedByPlayer == false){
      document.getElementById(x+'x'+y).innerHTML = '!';
      cells[getFieldId(x,y)].markedByPlayer = true;
      document.getElementById(x+'x'+y).style.color = 'red';
    }else if(cells[getFieldId(x,y)].markedByPlayer == true){
      document.getElementById(x+'x'+y).innerHTML = '';
      cells[getFieldId(x,y)].markedByPlayer = false;
    }
  }
}

function revealFields(x,y){
  if(x<0 || y<0 || x>boardHeight - 1 || y>boardWidth - 1){
    return;
  }
  if(cells[getFieldId(x,y)].neighbourNumber > 0){
    document.getElementById(x+ 'x' +y).innerHTML = cells[getFieldId(x,y)].neighbourNumber;
    cells[getFieldId(x,y)].hasBeenDiscovered = true;
    pointColor(x,y,'midnightblue');
    document.getElementById(x+ 'x' +y).removeEventListener('click', reveal, true);
  }
  if(cells[getFieldId(x,y)].hasBeenDiscovered == true){
    return;
  }
  cells[getFieldId(x,y)].hasBeenDiscovered = true;
  pointColor(x,y,'midnightblue');
  document.getElementById(x+ 'x' +y).removeEventListener('click', reveal, true);

  setTimeout(function(){revealFields(x-1,y);}, 200);
  setTimeout(function(){revealFields(x+1,y);}, 200);
  setTimeout(function(){revealFields(x,y-1);}, 200);
  setTimeout(function(){revealFields(x,y+1);}, 200);
  setTimeout(function(){revealFields(x-1,y-1);}, 200);
  setTimeout(function(){revealFields(x-1,y+1);}, 200);
  setTimeout(function(){revealFields(x+1,y-1);}, 200);
  setTimeout(function(){revealFields(x+1,y+1);}, 200);
}

JS fiddle link: https://jsfiddle.net/pL1n8zwj/1/


texts: How to collect reference values from hashmap?

texts:
I have written a code snippet to use HashMap<String, Vec<&String>> as the main data structure, and finally, I want to return a collected Vec<Vec<String>>, I can archive it by a for-loop, it there any pure iterator way to do this? (I have tried several times, but got tons of
confused compiler errors)
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
    let mut map: HashMap<String, Vec<&String>> = HashMap::new();
    for s in &strs {
        let mut key = s.clone();
        unsafe {
            key.as_bytes_mut().sort();
        }
        (*map.entry(key).or_insert(vec![])).push(s);
    }
    let mut ans: Vec<Vec<String>> = Vec::new();
    // I don't like these 2 lines
    for v in map.values() {
        ans.push(v.iter().cloned().cloned().collect::<Vec<String>>())
    }
    ans
}

I also tried with this code:
    pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
        let mut map: HashMap<String, Vec<String>> = HashMap::new();
        for s in strs {
            let mut key = s.clone();
            unsafe {
                key.as_bytes_mut().sort();
            }
            (*map.entry(key).or_insert(vec![])).push(s);
        }
        map.values().cloned().collect::<Vec<Vec<String>>>()
    }

In the last line, I want to move all the values from hashmap into result vector but also failed because of the lifetime error(then I gave up with a cloned vector), I am wondering how to make it.


texts: Python xml schema parsing for simpleContent and simpleTypes

texts:
I am writing a few python functions to parse through an xml schema for reuse later to check and create xml docs in this same pattern. Below are two functions I wrote to parse out data from simpleContent and simpleType objects. After writing this, it looked pretty messy to me and I'm sure there is a much better (more pythonic) way to write these functions and am looking for any assistance. I am use lxml for assess to the etree library.

def get_simple_type(element):
    simple_type = {}
    ename = element.get("name")
    simple_type[ename] = {}
    simple_type[ename]["restriction"] = element.getchildren()[0].attrib
    elements = element.getchildren()[0].getchildren()
    simple_type[ename]["elements"] = []
    for elem in elements:
        simple_type[ename]["elements"].append(elem.get("value"))
    return simple_type

def get_simple_content(element):
    simple_content = {}
    simple_content["simpleContent"] = {}
    simple_content["simpleContent"]["extension"] = element.getchildren()[0].attrib
    simple_content["attributes"] = []
    attributes = element.getchildren()[0].getchildren()
    for attribute in attributes:
        simple_content["attributes"].append(attribute.attrib)
    return simple_content

Examples in the schema of simpleContent and simpleTypes (they will be consistently formatted so no need to make the code more extensible for the variety of ways these elements could be represented in a schema):

<xs:simpleContent>
    <xs:extension base="xs:integer">
        <xs:attribute name="sort_order" type="xs:integer" />
    </xs:extension>
</xs:simpleContent>

<xs:simpleType name="yesNoOption">
    <xs:restriction base="xs:string">
      <xs:enumeration value="yes"/>
      <xs:enumeration value="no"/>
      <xs:enumeration value="Yes"/>
      <xs:enumeration value="No"/>
    </xs:restriction>
</xs:simpleType>

The code currently creates dictionaries like those show below, and I would like to keep that consistent:

{'attributes': [{'type': 'xs:integer', 'name': 'sort_order'}], 'simpleContent': {'extension': {'base': 'xs:integer'}}}

{'yesNoOption': {'restriction': {'base': 'xs:string'}, 'elements': ['yes', 'no', 'Yes', 'No']}}


texts:
I've finished ADDREV challenge but I'm still not happy with my current solution. How can I still make my solution efficient without using the built-in std::reverse() function?

  The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.

  Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.

  ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).

  Input

  The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.

  Output

  For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.

#include<string>
#include<iostream>

int reverse(int num);
int main() {
int n, a, b;

scanf_s("%d", &n);
while (n--) {
    std::cin >> a;
    std::cin >> b;
    //reverse the two number
    int sum = reverse(a) + reverse(b);
    sum = reverse(sum);

   //convert sum to string in order to remove zeroes
    std::string sumString = std::to_string(sum);
    sumString.erase(0, sumString.find_first_not_of('0'));
    std::cout << sumString;
}
    system("PAUSE");
    return 0;
}

int reverse(int num) {
   std::string r = std::to_string(num);
   std::string tmp;
   for (int i = r.length(); i >= 0; i--)
     {
       tmp = tmp + r.substr(i, 1);
     }
  return std::stoi(tmp);
}


texts:
This is the C++ code of my implementation of Knuth's algorithm M that produces mixed-radix numbers:

#include "visit.h"

void algorithmM(vector<int>& m)
{
  m.insert(m.begin(),2);
  const int n=m.size();
  vector<int> a(n,0);
  M2:
  visit(false,a);
  int j=n-1;
  M4:
  if (a[j]==m[j]-1) {a[j]=0;--j;goto M4;}
  if (j==0) return;
  else {a[j]++;goto M2;}
  }
int main()
{
  vector<int> m;
  int i;
  while(std::cin>>i)
  {if(i<0) continue;
   m.push_back(i);
  }
algorithmM(m);
return 0;
}

This is the code of "visit.h":

#include <iostream>
#include <vector>

using std::vector;
using std::cout;

template<class T> void visit(bool first,vector<T>& l)
{
 size_t dt=first?0:1;
 for(typename vector<T>::iterator i=l.begin()+dt;i!=l.end();++i)
cout<<*i;
 cout<<'\n';
}

The C++ code is very close to the Knuth's pseudocode.
And now this is an imperative Haskell implementation using mutable arrays:

import Data.Array.IO
import Control.Monad.State
import Data.IORef

data CountList = CountList {intlist::[Int],count::Int}
lenarr arr = do
         b<-getBounds arr
         return (snd b)

takeInput :: State (String,Int) [Int]
takeInput = do
        (s,count)<-get
        let g=reads s
        if g==[] then return []
        else do
            put (snd(head g),count+1)
            l<-takeInput
            return $ (fst(head g)):l
takeInput2 :: String->CountList
takeInput2 s = let (l,ss)=runState (takeInput) (s,0)
        in CountList l (snd ss)

fillArray :: CountList->IO((IOArray Int Int),(IOArray Int Int))
fillArray l = do
        arr<-newArray (0,(count l)) 0
        x<-nowfill 1 (intlist l) arr
        y<-newArray (0,(count l)) 0
        writeArray x 0 2
        return (x,y)

 where nowfill i l arr = do
             if l==[] then return arr
             else do
                writeArray arr i (head l)
                nowfill (i+1) (tail l) arr
visit ::(IOArray Int Int)->Int->IO ()
visit x i = do
          c<-lenarr x
          if i>c then putStrLn ""
          else do
                a<-readArray x i
                putStr (show a)
                visit x (i+1)

maj :: (IOArray Int Int)->(IOArray Int Int)->Int->IO((IOArray Int Int),Int)
maj m a j = do
        valaj <- readArray a j
        valmj <- readArray m j
        if valaj==valmj-1 then
                  do
                      writeArray a j 0
                      maj m a (j-1)
        else
            return (a,j)
m5 :: (IOArray Int Int)->Int->IO((IOArray Int Int),Int)
m5 a j = if j==0 then
         return (a,j)
     else do
         valaj<-readArray a j
         writeArray a j (valaj+1)
         return (a,j)
algorithmM0 m a = do
    visit a 1
    n<-lenarr m
    (a',j)<-maj m a n
    (a'',j')<-m5 a' j
    if j'==0 then
          return ()
    else
        algorithmM0 m a''
algorithmM = do
    l<-getLine
    let mycountlist = takeInput2 l
    (m,a)<-fillArray mycountlist
    algorithmM0 m a
main :: IO ()
main = algorithmM

I also have and a more functional approach using lists in Haskell which is smaller but I don't want to enlarge the post.

Can you please give me some advice on how to shrink the Haskell code?

I think that the main reason of using a high-level language like Haskell is to write less code but I don't think this happens here so I suppose that I am doing something wrong.


texts: Find and replace String with a substring result

texts:
I was asked this recently, and I couldn't figure out the best way. We are trying to replicate Google's search results where the search terms are bolded (using a b tag) in the results.

Input                       Terms               Output
The search is cool          {sea}               The search is cool

Originally, I thought this was pretty easy:

String results(String input, String[] terms)
{
   for(String term : terms)
   {
      input = input.replace(term, "" + term + "");
   }

   return input;
}

However, this isn't correct. For example:

Input                       Terms               Output
The search is cool          {sea, search}       The search is cool

I struggled to figure out the best way to approach this. Obviously we can no longer find and replace immediately. I played around with using a Map<Integer,String> where the key is the index returned by input.indexOf(term) and the value is the term, but this seemed potentially unnecessary. Any improvements?

public String results(String input, String[] terms)
{
   Map<Integer, String> map = new HashMap<Integer,String>();
   for(String term : terms)
   {
      int index = input.indexOf(term);
      if(index >= 0)//if found
      {
          String value = map.get(index);
          if(value == null || value.length() < term.length())//use the longer term
              map.put(index, term);
      }

   }

   for(String term: map.values())
   {
       input = input.replace(term, "" + term + "");
   }

   return input;
}


texts:
Just to enjoy, I want to implement selection and bubble sorts algorithms without looking any implementation by my own efforts . Is there any redundant/lack part(s)? After improved their implementations, I think to try to write them down as recursive, can I ?, any hint?

class Sorts {

    public static void main(String[] args) {
        int[] arrSelection = { 8, 6, 3, 1 };
        selectionSort(arrSelection);
        for (int i : arrSelection ) {
            System.out.print(i + "  ");
        }

        System.out.print("\n");

        int[] arrBubble = { 8, 6, 3, 1 };
        bubbleSort(arrBubble);
        for (int i : arrBubble ) {
            System.out.print(i + "  ");
        }

    }

    // swap helper for java
    private static int returnFirst(int x, int y) {
        return x;
    }

    public static void selectionSort(int[] arr) {
        int lengthOfInputArray = arr.length;
        int min;
        int min_index;

        for (int i = 0; i < lengthOfInputArray - 1; i++) {
            min = arr[i];
            min_index = i;
            for (int j = i+1; j < lengthOfInputArray; j++) {
                if (min > arr[j]) {
                    min = arr[j];
                    min_index = j;
                }
            }
            if (min_index != i) {
                // swap(arr[i], arr[min_index])
                arr[i] = returnFirst(arr[min_index], arr[min_index] = arr[i]);
            }
        }
    }

    public static void bubbleSort(int[] arr) {
        int lengthOfInputArray = arr.length;

        for (int i = 0; i < lengthOfInputArray; i++)
            for (int j = 0; j < lengthOfInputArray - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // swap(arr[j], arr[j + 1])
                    arr[j] = returnFirst(arr[j + 1], arr[j + 1] = arr[j]);
                }
            }
    }

}


texts: Dynamically adding controls to a form in a WinForms project

texts:
I have created this function in my DetailsScreen.cs, but I have no idea if this is the correct file to put this kind of code in, or if coding it this way is the correct approach. I know that it works because I have tested it.

My application generates a questionnaire based on selected (cyber security) standards. I have a form DetailsScreen, which requires the user to fill in some details such as name, company, etc. They also need to select from a checkedlist (questionStandardInput), the question standard they wish to use in this interview. For each selected standard, two answer standards need to be selected from two drop down lists (maturity answer standard and compliance answers standard).

Therefore, I need to be able to dynamically add labels and comboxes for each question standard. I asked because most code concerning label font etc. is placed in .Designer.cs files instead of the .cs files. But I need certain logic from the .cs file in order to properly format the controls, which is why I put it in here.

// Load answer input according to the number of questions standards selected.
private void questionStandardInput_MouseUp(object sender, MouseEventArgs e)
{
    questionLabels.Clear();
    maturityInput.Clear();
    complianceInput.Clear();
    selectionPanel.Controls.Clear();

    foreach (var item in questionStandardInput.CheckedItems)
    {
        Label qs_label = new Label();
        qs_label.Location = new Point(0, 0 + (questionLabels.Count * 115));
        qs_label.Font = new Font("Arial", 12F, FontStyle.Regular);
        qs_label.Size = new Size(150, 18);
        qs_label.Text = item.ToString();
        questionLabels.Add(qs_label);
        this.selectionPanel.Controls.Add(qs_label);

        Label m_label = new Label();
        m_label.Location = new Point(0, 0 + (questionLabels.Count * 115 + 35));
        m_label.Font = new Font("Arial", 12F, FontStyle.Regular);
        m_label.Size = new Size(150, 18);
        m_label.Text = "Maturity standard";
        this.selectionPanel.Controls.Add(m_label);

        Label c_label = new Label();
        c_label.Location = new Point(0, 0 + (questionLabels.Count * 115 + 70));
        c_label.Font = new Font("Arial", 12F, FontStyle.Regular);
        c_label.Size = new Size(170, 18);
        c_label.Text = "Compliance standard";
        this.selectionPanel.Controls.Add(c_label);

        ComboBox m_input = new ComboBox();
        m_input.Location = new Point(170, 0 + (questionLabels.Count * 115 + 35));
        m_input.Font = new Font("Arial", 12F, FontStyle.Regular);
        m_input.Size = new Size(200, 22);
        m_input.DropDownStyle = ComboBoxStyle.DropDownList;
        maturityInput.Add(m_input);
        this.selectionPanel.Controls.Add(m_input);

        ComboBox c_input = new ComboBox();
        c_input.Location = new Point(170, 0 + (questionLabels.Count * 115 + 70));
        c_input.Font = new Font("Arial", 12F, FontStyle.Regular);
        c_input.Size = new Size(200, 22);
        c_input.DropDownStyle = ComboBoxStyle.DropDownList;
        complianceInput.Add(c_input);
        this.selectionPanel.Controls.Add(c_input);

        InitializeMaturityStandardInput(m_input);
        InitializeComplianceStandardInput(c_input);
    }
    this.saveAssessmentButton.Location = new Point(235, 0 + (questionLabels.Count * 115));
    this.selectionPanel.Controls.Add(saveAssessmentButton);
}


texts: Handling related generic type parameters

texts:
In answering a question on StackOverflow, it occurred to me that a more generic version of GroupBy for C# that delegated membership in each group to a class could be useful.

This is my attempt, but I am unsatisfied with a few things. I don't particularly like the need to constrain the element type to IOrderable - I feel like it should be possible to delegate ordering to the group type somehow (I really wanted a static method constraint in the IGGrouping interface).

public interface IOrderable<T> {
    double ordering();
}

public interface IGGrouping<T> : IEnumerable<T> where T : IOrderable<T> {
    bool BelongsToGroup(T aT);
    IGGrouping<T> Add(T aT);
}

public static class IEnumerableExt {
    public static IEnumerable<IGGrouping<T>> GroupBy<TG,T>(this IEnumerable<T> src) where TG : IGGrouping<T>, new() where T : IOrderable<T> {
        var groups = new List<IGGrouping<T>>();
        void Add(T aT) {
            var found = false;
            foreach (var g in groups) {
                found = g.BelongsToGroup(aT);
                if (found) {
                    g.Add(aT);
                    break;
                }
            }
            if (!found)
                groups.Add(new TG().Add(aT));
        }

        foreach (var s in src.OrderBy(s => s.ordering()))
            Add(s);

        return groups;
    }
}

Here's a sample class to group by distance from center of current groups:

public class gRectangleGroup : IGGrouping<Rectangle> {
    List<Rectangle> members;
    public Point center;

    public gRectangleGroup() {
        members = new List<Rectangle>();
    }

    public gRectangleGroup Add(Rectangle r) {
        members.Add(r);
        center = new Point(members.Average(m => m.Loc.X), members.Average(m => m.Loc.Y));
        return this;
    }

    public bool BelongsToGroup(Rectangle r) => center.Distance(r.Loc) <= 5;

    public Rectangle Middle() => members.OrderBy(m => m.Loc.Distance(center)).First();

    public IEnumerator<Rectangle> GetEnumerator() => members.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

    IGGrouping<Rectangle> IGGrouping<Rectangle>.Add(Rectangle aT) => Add(aT);
}

You use gRectangleGroup like so:

List<Rectangle> list;

var ans2 = list.GroupBy<gRectangleGroup, Rectangle>().Cast<gRectangleGroup>().Select(rg => rg.Middle());

I don't like having to list the group type and the element type explicitly in the call to GroupBy. I don't like the Cast to gRectangleGroup when the type is passed to the GroupBy, but if GroupBy returns TG then I have to give up the fluent Add call for new groups.

I also don't like how a class that implements IGGrouping (like gRectangleGroup) and has a fluent Add that returns this, must also have another Add to return IGGrouping<T> because of the interface.

Can anyone suggest how this might be improved, or what they would change to solve the same issue?


texts: C++ class for disjoint-set/union-find on integers

texts:
I have implemented the disjoint-set data structure. The purpose is to group integers together. For example, if I want to find out the groups of integers where each adjacent neighbors are same:

vector<vector<int>> test = {
{1,0,0,1},
{0,0,0,1},
{0,3,3,1}};

There are 4 groups of integers, namely:

Group 1: 1 at (0,0)
Group 2: 0's at (0,1), (0,2), (1,0), (1,1), (1,2), (2,0)
Group 3: 1's at (0,3), (1,3), (2,3)
Group 4: 3's at (2,1), (2,3)

Here is the code in C++:

//This union-find class implements two optimization ideas:
//1)path compression
//2)union by rank

class DisjointSet {
    public:
    DisjointSet(int num_nodes);
    int find(int element);
    void do_union(int elment_a, int element_b);
    void dup(vector<int> &v);
    private:
    vector<int> parent_, rank_;
};

DisjointSet::DisjointSet(int num_nodes):
    parent_(num_nodes),rank_(num_nodes, 0)
{
    for(int i=0; i<num_nodes; ++i) parent_[i] = i;
}

int DisjointSet::find(int element)
{
    if(parent_[element] == element) return element;
    //1)path compression
    return parent_[element] = find(parent_[element]);
}

void DisjointSet::do_union(int a, int b)
{
    if(parent_[a] == parent_[b]) return;
    int fa = find(a), fb = find(b);
    //2)union by rank
    if(rank_[fa] < rank_[fb]) {
    parent_[fa] = fb;
    } else {
    parent_[fb] = fa;
    if(rank_[fa] == rank_[fb]) rank_[fa]++;
    }
}


texts: Improving a priority queue sketch in Racket/Scheme

texts:
I just put together the skeletons for a priority queue using a binary heap in racket/scheme. Using racket/scheme is all about the educational experience and I was wondering if anyone  wants to critique and improve the code. Bug reports are welcome

;; priority queues operations on integer values

(define (heap)
  (let ((the-heap (make-vector 10)) (next-free 1))

(define (swim val)
  (begin
    (vector-set! the-heap next-free val)
    (set! next-free (+ next-free 1))
    (let loop ((i (- next-free 1)))
      (if (and (< (vector-ref the-heap (quotient i 2)) (vector-ref the-heap i)) (> (quotient i 2) 0))
          (begin
            (exch the-heap i (floor (/ i 2)))
            (loop (floor (/ i 2))))
        the-heap))))

(define (sink index)
  ;; a call to this method is used to re-establish order within the
  ;; heap by 'sinking' the value rooted at index to its right position
  ;; within the whole heap
  (let loop ((node index) (kid (* 2 index)))
    (if (<= kid next-free)
        (let ((larger-kid (if (> (vector-ref the-heap kid) (vector-ref the-heap (+ kid 1)))
                                 kid
                                 (+ kid 1))))
          (if (> (vector-ref the-heap larger-kid) (vector-ref the-heap node))
              (begin
                (exch the-heap node larger-kid)
                (loop larger-kid (* 2 larger-kid)))
              the-heap))
          (newline))))

(define (delete-max)
  ;; delete and return the maximum value in the heap.
  ;; add the last item on the heap to the root position
  ;; sink to re-establish order within the heap of the heap and call
  ;;
  (begin
    (let ((val (vector-ref the-heap 1)))
      (vector-set! the-heap 1 (vector-ref the-heap (- next-free 1)))
      (set! next-free (- next-free 1))
      (vector-set! the-heap next-free 0)
      (sink 1)
      val)))

(define (put value)
  (swim value))

(define (size)
  (vector-length the-heap))

(define (empty?)
  (= next-free 1))

(define (exch vec lo j)
  (let ((lo-val (vector-ref vec lo)) (j-val (vector-ref vec j)))
    (begin
      (vector-set! vec lo j-val)
      (vector-set! vec j lo-val))))

(define (dispatch message . arg)
  (cond
    ((eq? message 'delete-max) (delete-max))
    ((eq? message 'put) (put (car arg)))
    ((eq? message 'size) size)
    ((eq? message 'heap) the-heap)
    ((eq? message 'empty?) empty?)))
dispatch))


texts: Initializing entity framework context in constructor

texts:
We use the architecture shown in the code below to initialize the DB context for our MVC 5 project using entity framework 6

We have the following questions related to it:

Is it safe to initialize the Context in the constructor and use it throughout the class?
What are the disadvantages of the given approach?

Constructor:

public class HomeController : Controller
{
    public DBEntities Context { get; set; }
    public HomeController()
    {
        Context = new DBEntities();
    }

    ...
}

We have a single point of entry to the controller using the Perform method (This method is invoked from the client using ajax):

[HttpPost]
public async Task<ContentResult> Perform(string operation, string entity, FormCollection form = null)
{
    var json = string.Empty;
    var returnTuple = new Tuple<string, int, string>(string.Empty, (int)HttpStatusCode.InternalServerError, "Default return value");

    switch (operation)
    {
        case "GET":
            switch (entity)
            {
                case ("ALLSCHOOLS"):
                    returnTuple = await GetSchools(form);
                break;

                ...
            }
        break;

        case "POST":
            switch (entity)
            {
                case "SCHOOL":
                    returnTuple = await SaveSchool(form);
                break;

                ...
            }
        break;
    }

    ...

    if (!string.IsNullOrEmpty(returnTuple.Item1))
    {
        json = returnTuple.Item1;
        Response.StatusCode = (int)HttpStatusCode.OK;
    }
    else
    {
        Response.StatusCode = returnTuple.Item2;
        Response.StatusDescription = returnTuple.Item3;
    }
    return Content(json, "application/json");
}

GetSchools method:

private async Task<Tuple<string, int, string>> GetSchools(FormCollection form)
{
    var json = string.Empty;
    var statusCode = int.MinValue;
    var statusDescription = string.Empty;

    var academicYear = Convert.ToInt32(form["academicyear"]);

    var schoolsObj = await Context.schools.Where(s => s.AcademicYear == academicYear).ToListAsync(); //Context is initialized in constructor shown above

    json = JsonConvert.SerializeObject(new
    {
        EntityObject = schoolsObj,
        Message = string.Empty,
        Formatting.None
    }, new JsonSerializerSettings
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    });
    return Tuple.Create(json, statusCode, statusDescription);
}

SaveSchool method:

private async Task<Tuple<string, int, string>> SaveSchool(FormCollection form)
{
    var json = string.Empty;
    var statusCode = int.MinValue;
    var statusDescription = string.Empty;
    var schoolObj = new school();
    var message = string.Empty;

    if (TryUpdateModel(schoolObj, form))
    {
        Context.schools.Add(schoolObj);
        var saveChanges = await Context.SaveChangesAsync();
        if (saveChanges == 0)
        {
            json = string.Empty;
            statusCode = (int)HttpStatusCode.InternalServerError;
            statusDescription = "Unable to save the data. Please try again later.";
            return Tuple.Create(json, statusCode, statusDescription);
        }
        else
        {
            json = JsonConvert.SerializeObject(new
            {
                EntityObject = schoolObj,
                Message = "Data saved successfully."
            }, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
        }
    }
    else
    {
        message = ModelStateValidationErrors(); //ModelStateValidationErrors() returns all modelstate errors
        statusCode = (int)HttpStatusCode.BadRequest;
        statusDescription = "Please check the error(s) below and resubmit the form.<br/>" + message;
    }
    return Tuple.Create(json, statusCode, statusDescription);
}


texts:
My objective is to make an array of unique keys from a list of objects.

Example:

Input:

var input = [{"a":1, "b":2}, {"a":3, "c":4}, {"a":5}]

Output:

[ "a", "b", "c" ]

Current approach:

var outputObj={};
input.map( function( obj ) {
    Object.keys( obj ).map( function(key) {
        outputObj[key] = 1;
    })
});
// output obj is now { a : 1, b: 1, c: 1 }
var output = Object.keys( outputObj );

This works, but it just smells funny, partly because the map function is relying on side-effects. Is there a better way to do this?

In Java, I would create a java.util.Set and simply add all keys to it.


texts:
I have a situation in which I need to get the closest road to a DbGeography point.

This takes 5 - 8 seconds to run in some cases.

I have a Spatial_Index on the column and I re-organised it, so it is not fragmented.

This query is quite heavy, sometimes the CPU usage raises to 100% because of this.

This is what the table looks like:

Here is the spatial result (in case it helps):

    public string GetRoad(DbGeography point)
    {
        var name = "";
        try
        {
            using (var gisEntities = new GISSpatialEntities())
            {
                var query = String.Format(@"
                            DECLARE @point geography;
                            SET @point = geography::STPointFromText('POINT({0} {1})', 4326);

                            SELECT TOP 10 * FROM GeographyLine
                            WHERE GeoLine.STIsValid() =1 AND  @point.STBuffer(200).STIntersects(GeoLine) = 1
                            ORDER BY GeoLine.STDistance(@point)", point.Longitude, point.Latitude);
                var firstOrDefault = gisEntities.GeographyLines.SqlQuery(query).FirstOrDefault();
                if (firstOrDefault != null)
                {
                    name = firstOrDefault.LineName;
                }
            }
        }
        catch (Exception ex)
        {
            var msg = string.Format("Exception in GetRoad() - {0} - Inner [{1}] \r\n", ex.Message, ex.InnerException);
            _logger.LogMessage(MessageType.Error, msg);
        }
        return name;
    }


texts: jQuery dynamic elements like TR and TD, add to HTML table

texts:
Is it possible to create dynamic TR and TD elements in an HTML table?  Something similar but better than this:

jQuery(document).ready(function() {
  $('button[name="new-title"]').on('click', function(){
    var table = $('table[name="errortitle"]');
    var tr = $('<tr />');
    var td = $('<td />');
    var input = $('<input />').attr({'class' : 'form-control'})
    var button = $('<button />').attr({'class' : 'btn'});
    var checkbox = input.clone().attr({'type' : 'checkbox', 'name' : 'check'});

    var tdId = td.clone().html('-');
    var tdTitle = td.clone().append(input.addClass('formInput').attr({'type': 'text'}));
    var tdCheckBox = td.clone().append(checkbox);
    var tdAction = td.clone().html(button.addClass('btn-danger').html('Usuń'));

    tr.append(tdCheckBox);
    tr.append(tdId);
    tr.append(tdTitle);
    tr.append(tdAction);

    table.append(tr);
  });
});

Is it possible to make this code nicer or more efficient?


texts: Filter out date records which don't fall within or span a date range

texts:
I have records which have specific time spans. The need is to select records which adhere to the following three rules (read them as or conditions) concerning a target time span:

Record's Begin date can begin within the target time span and end date does not matter.
Record's End date falls with the target time span and the start date is inconsequential.
Record's dates actually span the target time.

So basically a query should return all records which start, end or span a target time frame.

Is there a more efficient way in Oracle 11g of doing the above rules than what I currently have stated in the SQL below?

I have created a test SQL Fiddle Test for the below schema and SQL

Schema

CREATE TABLE dates_test (
  id         NUMBER,
  hint       VarChar(20),
  BEGIN_DATE DATE,
  END_DATE DATE
);
-- If the span is Mar 6 to April 6 then 2, 3 and 4 are valid -
INSERT INTO dates_test VALUES (1, 'exclude before', TO_DATE('01-JAN-2014','DD-MON-YYYY'), TO_DATE('05-JAN-2014','DD-MON-YYYY'));
INSERT INTO dates_test VALUES (2, 'spans',          TO_DATE('05-MAR-2014','DD-MON-YYYY'), TO_DATE('08-SEP-2014','DD-MON-YYYY'));
INSERT INTO dates_test VALUES (3, 'Starts within',  TO_DATE('07-MAR-2014','DD-MON-YYYY'), TO_DATE('07-SEP-2014','DD-MON-YYYY'));
INSERT INTO dates_test VALUES (4, 'Ends within',    TO_DATE('01-JAN-2014','DD-MON-YYYY'), TO_DATE('07-MAR-2014','DD-MON-YYYY'));
INSERT INTO dates_test VALUES (5, 'exclude after',  TO_DATE('06-JUN-2014','DD-MON-YYYY'), TO_DATE('07-SEP-2014','DD-MON-YYYY'));
INSERT INTO dates_test VALUES (6, 'within OK',  TO_DATE('08-MAR-2014','DD-MON-YYYY'), TO_DATE('09-MAR-2014','DD-MON-YYYY'));

Here is the SQL which returns what I need but can it be improved?

select * from
dates_test t0
where
(  -- Starts Within range
  ( t0.BEGIN_DATE
    BETWEEN TO_DATE('03-06-2014', 'mm-dd-yyyy')
    AND     TO_DATE('04-06-2014', 'mm-dd-yyyy')
  )
OR  -- Ends within range
  (
    t0.END_DATE
    BETWEEN TO_DATE('03-06-2014', 'mm-dd-yyyy')
    AND     TO_DATE('04-06-2014', 'mm-dd-yyyy')
   )
OR    -- SPANS Range
   (
     t0.BEGIN_DATE < TO_DATE('03-06-2014', 'mm-dd-yyyy')
     AND
     t0.END_DATE > TO_DATE('04-06-2014', 'mm-dd-yyyy')
    )
);

Result:

| ID |          HINT |                     BEGIN_DATE |                         END_DATE |
|----|---------------|--------------------------------|----------------------------------|
|  2 |         spans |   March, 05 2014 00:00:00+0000 | September, 08 2014 00:00:00+0000 |
|  3 | Starts within |   March, 07 2014 00:00:00+0000 | September, 07 2014 00:00:00+0000 |
|  4 |   Ends within | January, 01 2014 00:00:00+0000 |     March, 07 2014 00:00:00+0000 |
|  5 |     within OK |   March, 08 2014 00:00:00+0000 |     March, 09 2014 00:00:00+0000 |


texts: Minimalist accordion implementation using vanilla JavaScript

texts:
The following example is an accordion script in JavaScript that does not use jQuery. When I started looking for a simple solution to this requirement I did not accept the idea of having to use a powerful and robust library for a simple implementation. I didn't like the idea of use a machine gun when what I really need is a slingshot. So as a jQuery detox process I decide create my own solution. So far the code is simple enough and I’m planning using it in production as a custom widget in my blog running Wordpress. I’m very enthusiast of minimalist development and I have some concerns with this code.

Any suggestions about how I can achieve a simpler and elegant solution? I was thinking in implementing the element.classList properties.

Here is a live demo of the accordion script.

HTML

Archivos

2015
      <a href="#"

febrero 2015

enero 2015

2014
      <a href="#"

diciembre 2014

noviembre 2014

marzo 2014

febrero 2014

enero 2014

2013
      <a href="#"

diciembre 2013

septiembre 2013

CSS

.widget
{
  width:60%;
  margin:50px auto 0 auto;
  border:4px solid rgba(10,10,10,0.05);
  padding:10px;
  border-radius:10px;
  -webkit-box-shadow: 10px 10px 45px -20px rgba(0,0,0,0.75);
  -moz-box-shadow: 10px 10px 45px -20px rgba(0,0,0,0.75);
  box-shadow: 10px 10px 45px -20px rgba(0,0,0,0.75);
}

.widget-title
{
  font-weight:bold;
  text-transform:uppercase;
  color:#636363;
  padding-bottom:10px
}

.widget a
{
  color:#9b9b9b;
  text-decoration:none;
  padding:10px 0 10px 10px;
  display:inline-block;
}

.widget a + a
{
  padding:10px 16px;
  float:right;
  line-height:1.5;
}

.widget a + a:hover
{
  background-color:#ddd;
  color:#fff;
}

.widget a:hover
{
  color:#444
}

.widget ul
{
  list-style-type:none;
  margin:0;
  padding:0;
  background-color:#eee;
}

.widget ul
{
  line-height:1.5;
}

.widget li
{
  border-top:1px solid #ccc;
}

.widget li li
{
  line-height:1.5;
  border-top:1px solid #eaeaea;
  background-color:#fff;
}

.widget > ul li:first-child
li a:first-child {
  display:inline-block;
}

.hide {
  display:none;
}

JS

"use strict";

var elementum = document.querySelector(".widget_archive");
var gestus = elementum.getElementsByClassName("fa");

for (var i = 0; i < gestus.length; i++) {
  gestus[i].addEventListener("click", toogle);
}

function toogle()
{
  if (this.nextElementSibling.className === "")
  {
    this.nextElementSibling.className = "hide";
  }
  else
  {
    this.nextElementSibling.className = ""
  }
}


texts: Tagging the directories and switching between them by tags - follow-up (Part 2/2: business logic)

texts:
This is the bash script responsible for changing the directories via textual tags. (See here the entire project.)

dt_script

~/.dt/dt $@ > ~/.dt/dt_tmp
COMMAND_TYPE=$(head -n 1 ~/.dt/dt_tmp)
if [ $# -eq 0 ]; then
    NEXT_PATH=$(~/.dt/dt prev | tail -n 1) # Let dt return pwd if no prev tag.
    ~/.dt/dt --update-prev $(pwd)
    if [ "$COMMAND_TYPE" == "message" ]; then
        tail -n 1 ~/.dt/dt_tmp
    else
        cd $NEXT_PATH
    fi
else
    if [ "$COMMAND_TYPE" == "switch_directory" ]; then
        NEXT_PATH=$(tail -n 1 ~/.dt/dt_tmp)
        ~/.dt/dt --update-prev $(pwd)
        cd $NEXT_PATH
    elif [ "$COMMAND_TYPE" == "show_tag_entry_list" ]; then
        tail -n +2 ~/.dt/dt_tmp
    elif [ "$COMMAND_TYPE" == "message" ]; then
        tail -n 1 ~/.dt/dt_tmp
        #echo $(cut -d " " -f 2)
    else
        echo "Unknown command: $COMMAND_TYPE"
    fi
fi
rm ~/.dt/dt_tmp

Any further suggestions for improvement are welcomed.


texts:
I got this out of an article on interviews / code challenges. The challenge text goes like this:

  A palindrome is a word, phrase, number, or other sequence of
  characters which reads the same backward or forward. Allowances may be
  made for adjustments to capital letters, punctuation, and word
  dividers. Examples in English include “A man, a plan, a canal,
  Panama!”, “Amor, Roma”, “race car”, “stack cats”, “step on no pets”,
  “taco cat”, “put it up”, “Was it a car or a cat I saw?” and “No ‘x’ in
  Nixon”.

  Write the most efficient function you can that determines whether a
  given string is a palindrome.

  Your function should accept a string as a parameter and return a
  boolean (true if the string is a palindrome, false if it is not).

  Assume that this code will be put into a real production system and
  write accordingly.

Article in question: https://blog.devmastery.com/how-to-win-the-coding-interview-71ae7102d685

My Implementation:

Even though the article provides a way to solve it, my implementation is different in a few ways, so I would like your reasoning on it.

/*
 * Reverses a given string of characters
 *
 * @param {string} string - the string to reverse
 * @returns {string} - the reversed string
 *
 */
const reverseString = string => string.split('').reverse().join('');

/*
 * Function to test if a given string is a palindrome
 *
 * @param {string} string - the string to test
 * @returns {boolean | string} - returns true/false based on the string, being a palindrome,
 *                               or string if there is an error
 *
 */
const isPalindrome = string => {
    if (string) {
      let regexReplacer = /\.|\,| |\!|\?|\'|\"|\/|\\|\-|\_|\+|\‘|\’/g;
      let cleanString = string.replace(regexReplacer, '');
      return (cleanString.toLowerCase() === reverseString(cleanString).toLowerCase());
    }
    return '[isPalindrome]: string not supplied, exiting!';
};

/*
 * Basic function to test equality, poor-man's unit test
 *
 * @param {string} test - the string to test
 * @param {string | boolean} reponse - the expected result
 * @param {function} [func = isPalindrome] - the function to test, defaults to isPalindrome
 *
 */
const expectToEqual = (test, reponse, func = isPalindrome) => {
    if (func(test) === reponse) { console.info('Test for "' + test + '" passed!'); }
    else { console.error('Test for "' + test + '" failed!'); }
};

expectToEqual('A man, a plan, a canal, Panama!', true);

expectToEqual('raceca', false);

expectToEqual('No \‘x\’ in Nixon', true);

expectToEqual('', '[isPalindrome]: string not supplied, exiting!');

Link to jsbin: https://jsbin.com/hilatev/edit?js,console

Questions:

Regex - I'm using /\.|\,| |\!|\?|\'|\"|\/|\\|\-|\_|\+|\‘|\’/g to replace non word characters versus this /[^a-z0–9]/ig which is kind of obvious. But would still like your input.
String testing - The implementation provided in the article goes though the string in a while loop and tests each character. Is this favorable vs how I just compared the strings ? Why ?
Returns - The palindrome function returns true/false based on the string, but also returns a string if there is no string supplied. Is this favorable or I should of just thrown an error ?
Edge cases - In hindsight I'm missing and obvious big case, after the regex replace, what if you end up with an empty string? Besides this did I miss anything else major ? Or minor ?
Tests - I've written my own small test function vs in the article it just prints out the expected result (Ex: console.log(isPalindrome("racecar") + " = true");). Is this favorable? Why?
Other - Things that I may have missed ?


texts: Rails 5 helpers to fetch tasks with different filters

texts:
I moved a lot of the loading/logic from my view to my controller, and it's working great but after I did this I now have several very similar helper methods in my controller.

What is a more efficient way of doing this? Is there? I assume get_last_task_owed and get_first_task_owed I would be able to do in the view by finding the .first and .last of the record respectively.

  def get_projects_owed
    current_user.projects.where('end_date > ?', Date.today).order(:start_date).pluck(:name, :start_date, :end_date)

  end

  def get_all_projects
    current_user.projects.order(:start_date).pluck(:name, :start_date, :end_date)
  end

  def get_all_tasks
    @project.tasks.order(:product, :task_start_date).pluck(:product, :task_name, :task_start_date, :task_end_date).to_json
  end

  def get_last_task_owed
    tasks = @project.tasks
    tasks.where('task_end_date >= ?', Date.today).order('task_end_date DESC').first.task_end_date.strftime("%B %d, %Y")
  end

  def get_first_task_owed
    tasks = @project.tasks
    tasks.where('task_end_date >= ?', Date.today).order('task_end_date ASC').first.task_end_date.strftime("%B %d, %Y")
  end

  helper_method :get_projects_owed
  helper_method :get_all_projects
  helper_method :get_clients_with_projects
  helper_method :get_all_tasks
  helper_method :get_last_task_owed
  helper_method :get_first_task_owed


texts:
I think that the slice() is a bit hacky, and prone to breaking if I change my mind about the id names, but I wanted this to be generic so I could add types easily.

Is there maybe another / better way to do this just using CSS nesting the 'panels' inside the li elements?

Markup:

1

2

    ...

blah

blah

   ...

JavaScript:

function switchType(type){
    $("#type-select li a").removeClass("selected-type");
    $("#type-"+type).addClass("selected-type");
    $(".panel").removeClass("selected-panel");
    $("#panel-"+type).addClass("selected-panel");
}

// initial state
$("#no-results").hide();
switchType("1");
$("#type-select li a").click(function(){switchType(this.id.slice(5))});


texts: Check for pixel spacing between two folder images

texts:
Im trying to match the pixel spacing between two folders, here matches has 994 keys and it shows that i may take more than a day to compute this. Is there any way i can speed up this operation.

the load series function looks like this

import SimpleITK as sitk
def load_series(path):
    reader = sitk.ImageSeriesReader()
    dicom_names = reader.GetGDCMSeriesFileNames(path)
    reader.SetFileNames(dicom_names)
    return reader.Execute()

import csv
bar = ProgressBar()
file = open('BenignTest.csv', 'w')
writer = csv.writer(file)
for item in bar(matches.keys()):
    for case in matches[item]:
        load_case = load_series(case)
        if load_case.GetSpacing() == load_series(item).GetSpacing():
            writer.writerow((item , case))
            break

The matches dictionary looks like this,

{'/mnt/sdd1/DSB2017/stage1/0030a160d58723ff36d73f41b170ec21': ['/mnt/sde1/Cancer/128443/01-02-1999-LSS-59120/2-0OPAGELSPLUSD3602.512060.00.11.5-98506',
  '/mnt/sde1/Cancer/213485/01-02-1999-ACRIN-13247/3-0OPAGELSPLUSLUNG3502.51204026.71.5-85097',
  '/mnt/sde1/Cancer/206342/01-02-1999-ACRIN-68321/3-0OPAGELSPLUSLUNG3702.51205033.31.5-72233',
  '/mnt/sde1/Cancer/200209/01-02-2000-CRIN-10216/3-1OPAGELSPLUSLUNG4002.51204026.71.5-42354']...........}

Thanks in advance


texts: Edit one table from another table in a Windows Form DataGridView

texts:
I have a Sales Order Program that allows each customer to have their own Part Number for one of our Stock Items. The Customer Part Numbers are stored in a separate table. I need to make this as low impact on the User/UI as possible.
As a working model I have come up with a related demo using Person for the Order Table and a Table called NickNames that should represent the Customer Part Number Table.

public class Person
{
    private string _sobriquet;

    public Person()
    {
        NickName = new NickName(Id);
    }

    [Key]
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int NickNameId { get; set; }

    [ForeignKey("NickNameId")]
    public virtual NickName NickName { get; set; }

    public string Sobriquet
    {
        get { return _sobriquet; }
        set
        {
            _sobriquet = value;
            NickName.PersonId = Id;
            NickName.Sobriquet = _sobriquet;
        }
    }
}

public class NickName
{
    public NickName(int personId)
    {
        PersonId = personId;
    }

    protected NickName()
    {

    }

    [Key]
    public int PersonId { get; set; }

    public string Sobriquet { get; set; }
}

This does what I wanted... by Changing the Sobriquet property on the Person table the NickName Table is updated, but I am sure there is a better or cleaner way.


texts: TodoItem component type checking for optional prop

texts:
I have a TodoItem component that looks like this:
type Todo = {
  id: string;
  text: string;
  isCompleted: boolean;
  createdAt: string;
};

type TodoProps = {
  todo: Todo;
  removeTodo: (id: string) => void;
  markCompletedTodo?: (id: string) => void;
};

const TodoItem = ({ todo, removeTodo, markCompletedTodo }: TodoProps) => {
  return (

{todo.text}

      <button type="button" onClick={() => removeTodo(todo.id)}>
        Remove
      </button>
      {typeof markCompletedTodo === 'undefined' ? null : (
        <button type="button" onClick={() => markCompletedTodo(todo.id)}>
          Mark completed
        </button>
      )}

  );
};

export default TodoItem;

As you can see, it gets a todo with a isCompleted property. I want to render the 'Mark completed' button only is the isCompleted property is false, but currently I'm checking for the optional markCompletedTodo prop. That works but I have the feeling this can be done in a better way.
I'm using it to create two lists of TODOS, one for incomplete TODOS and one for complete TODOS, so I'm using it like this in another component:
return (

Incomplete TODOS

  {incompleteTodos.map((todo) => (
    <TodoItem
    key={todo.text}
    todo={todo}
    removeTodo={removeTodoRequest}
    markCompletedTodo={markCompletedTodoRequest}
    />
  ))}

Complete TODOS

  {completeTodos.map((todo) => (
    <TodoItem
      key={todo.text}
      todo={todo}
      removeTodo={removeTodoRequest}
    />
  ))}
)

Is there a better approach to this regarding the type checking and the prop types in the TodoItem component, or any other aspect?


texts: Binning whilst avoiding the need for for-loops in Python?

texts:
I am working on a relatively simple binning program, where I take a 5D array and bin it based on two 3D arrays to create a contour plot. See the sample code below. In actuality, my arrays are of size [27, 150, 20, 144, 288], so running a 4-nested for loop as shown below takes a LONG time.

Is there any way to speed up this loop and ideally avoid the need for all these loops? Apologies in advance if this isn't clear - I am new to all this!

S_mean = np.random.rand(5,10,10,10)
T_mean = np.random.rand(5,10,10,10)
Volume_mean = np.random.rand(2,5,10,10,10)

T_bins = np.linspace(0,1,36)
S_bins = np.linspace(0,1,100)

int_temp = []
int_sal = []

for i in range(5):
    int_temp.append(np.digitize(np.ndarray.flatten(T_mean[i,:,:,:]), T_bins))
    int_sal.append(np.digitize(np.ndarray.flatten(S_mean[i,:,:,:]), S_bins))

volume_sum = np.zeros((2,5,S_bins.size,T_bins.size))

# This is the problem loop

for k in range(2):
    for l in range(5):
        for i in range(T_bins.size):
            for j in range(S_bins.size):
                volume_sum[k,l,j,i]=(np.nansum(np.ndarray.flatten(Volume_mean[k,l,:,:,:])
                                    [np.argwhere(np.logical_and(int_temp[l] == i, int_sal[l] == j))]))

# The output I am trying to get

plt.pcolormesh(T_bins, S_bins, volume_sum[0,0,:,:])
plt.show()


texts:
Is this kind of vectorized operations the most efficient way to do this in matlab? Any critics about my code? Am I doing something wrong (i tested several times, I think it works). Notice that I use J to store the history of the cost function so I can see how well it is converging (by plotting a graph for instance).

main function

function [theta, J_history] = logRegGradientDescent(X, y, theta, alpha, num_iters)
% Given a matrix X where the columns are features and a matrix Y of targets
% we apply the gradientDescent to minimize the cost function and find its
% local optimum. Alpha is the learning rate on which we look for a local
% minimum and num_iters is the amount of times we repeat the learning step.

J_history = zeros(num_iters);

for iter = 1:num_iters

    % Derivative of the cost function used, the square error in that case.
    dLogisticCostFunction = (1/m) * X' * (logisticFunction(X,theta) - y);

    % Learning step
    theta = theta - alpha * dLogisticCostFunction;

    % Save the cost function for convergence analysis
    J_history(iter) = logRegCostFunction(X,y,theta);
end
end

logistic function

function h = logisticFunction(X,theta)
% Compute the logistic function.
% If X is a matrix such as:
%
%    x1_ x2_ x3_ .. xn_;
%  [ x11 x12 x13 .. x1n;
%    x21 x22 x23 .. x2n;
%    ..  ..  ..  .. .. ;
%    xn1 xn2 xn3 .. xnn; ]
%
% and thetha' is a vector:
%  [ t0, t1, t3 .. tn ]
%
% We calculate the logistic function:
% 1/ ( 1 + e^(-sum(x*theta)))

h = 1 ./ ( 1  + exp(-X*theta) );
end

logistic cost function

function J = logRegCostFunction(X,y,theta)
% Compute a convex cost function to the Logistical Regression where
% if y = 1 and the logistic function predicts y = 0, cost -> inf
% and if y = 0 and the logistic fucntion predicts y = 1, cost -> inf

% Calculates number of Features
m = length(y);

% Calculates the case where if y = 1, Cost = -log(h(x))
ify1 =  log(logisticFunction(X,theta)).*y;

% Calculates the case where if y = 0, Cost = -log(1-h(x))
ify0 =  log(1 - logisticFunction(X,theta)).*(y-1);

% Calculates the cost function
J = - (ify1 + ify0) / m;
end


texts: Ruby Fibonacci(n) recursive computation optimized with reflection

texts:
The idea is to take the common-known (and awfully bad performing) Fibonacci(n) recursive method:

# recursively computate fibonacci(n)
def fib(n)
  n <= 2 ? 1 : fib(n-2) + fib(n-1)
end

and to optimize it with some Ruby reflection:

require 'benchmark'

def fib(n)
    # if n<= 2 fib(n) = 1
    return 1 if n <= 2
    # if @fib_n is defined it means that another instance of this method
    # has already computed it, so I just return its value
    return instance_variable_get("@fib_#{n}") if instance_variable_get("@fib_#{n}")
    # else I have to set fib_n and return its value
    instance_variable_set("@fib_#{n}", ( fib(n-2) + fib(n-1) ) )
end

Benchmark.bm(30) do |x|
    x.report("fibonacci(#{ARGV[0]}) computation time:") {$fib = fib(ARGV[0].to_i)}
end

puts "fib(#{ARGV[0]}) = #{$fib}"

Since the execution time for fib(36) drops from about 4 sec to 0.000234 sec, I guess it's working! But since I'm a Ruby novice (and since this is my first attempt with reflection), I'd still like to have my code peer-reviewed.

Is my choice to use '@fib_n' instance variables correct or there is a better choice?
Does anyone know a better Ruby optimization for the recursive computation of Fibonacci members? (I know, the most efficient computation for Fibonacci is the iterative one, but here I'm strictly interested in the recursive one).