texts: Value Object encapsulating different units of measure

texts:
I have a situation where I need to use person's height in different units. Some parts of the system use Inches/Feet some Meters/Centimeters.

I was thinking of a Height value object which would encapsulate different measurement untis, and upon creation calculate and store all supported measurement units and provide accessors to get each.

I end up with this

public class Height : IEquatable<Height>
    {
        private Height()
        { }

        public double InMeters { get; private set; }
        public double InFeet { get; private set; }
        public double InInches { get; private set; }

        public static Height FromCMeters(double heightInCms) => new Height
        {
            InMeters = (double) heightInCms / 100,
            InFeet = heightInCms * 30.48,
            InInches = heightInCms * 2.54
        };

        public static Height FromFoots(double feet) => new Height
        {
            InFeet = feet,
            InMeters = (feet * 30.48) / 100,
            InInches = feet * 12
        };

        public static Height FromInches(double inches) => new Height
        {
            InInches = inches,
            InFeet = inches / 12,
            InMeters = (inches * 2.54) / 100
        };

        public bool Equals(Height other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return InMeters.Equals(other.InMeters);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((Height) obj);
        }

        public override int GetHashCode() => InMeters.GetHashCode();
    }

I intentionally omitted addition/subsctraction to keep code small.
The usage of Height value object:

var height = Height.FromCMeters(191);
// height.InMeters
// height.InInches
// height.InFeet

I have few doubts:

If I need to support new unit of measure I would have to change the value object which I don't think is a good idea
I tend to keep my value objects very small, this one seems to be doing too much for a value object (all those conversion logics)
I think it keeps track of many values instead of a one, and it feels that all this conversion logic belongs to somewhere else

This Height VO is mostly going to be used to represent height. All operations are going to be creating height from different units (m/cm/feet/inch) and pass it around. Whoever receives it is going to use it just to retrieve height value in the unit it needs.

This simple usage makes me think I don't really need more involved design, where I would have simply Height VO (with single metric) and let another component do the necessary conversion.

What do you think ?


texts: Extended Laravel Eloquent models to add filters to model setters

texts:
One of the tasks I find myself doing repeatedly is to filter the incoming inputs that will be stored in models. Examples of this include trimming, removing repeated or unnecessary pre/suffixes, commas or dashes in numbers, etc. This is similar to validation, but Laravel's built-in Validator does not appear to have this capability.

Mutators in Eloquent models does support this, but for large models creating one for each property will result in a lot of repeated code. I considered extending Validator to add this to the validation step, or adding a middleware to filter form requests, but it seems the easiest way would be to override the Model class' setAttribute function

use Illuminate\Database\Eloquent\Model;
use Log;

class BaseModel extends Model
{
    protected $filters = [];

    public function setAttribute($key, $value)
    {
        if ($this->hasFilter($key)) {
            $value = $this->executeFilter($key, $value);
        }

        return parent::setAttribute($key, $value);
    }

    protected function hasFilter($key)
    {
        return array_key_exists($key, $this->filters);
    }

    protected function getFilter($key)
    {
        return $this->filters[$key];
    }

    protected function executeFilter($key, $value)
    {
        $filter = $this->getFilter($key);
        $rules = is_string($filter) ? explode('|', $filter) : [$filter];

        foreach ($rules as $rule) {
            if (is_callable($rule)) {
                $value = call_user_func($rule, $value);
            } elseif (method_exists($this, 'filter'.ucfirst($rule))) {
                $ruleMethod = 'filter'.ucfirst($rule);
                $value = $this->$ruleMethod($value);
            } else {
                Log::warning("Unknown filter method $filter called on $key",
                    ['model' => '', 'value' => $value]);
            }
        }

        return $value;
    }
}

Example usage:

class Listing extends BaseModel
{
    protected $filters = [
        'name'           => 'trim',
        'description'    => 'trim',
        'price'          => 'price',
    ];

    protected function filterPrice($value)
    {
        return (float) ltrim(trim($value), '$');
    }
}

The $filters property contains the rules needed for each property. Each rule is separated by |, and the rule has to be a function that either exist globally (ie. built-in functions or helpers), or as a method on the model prefixed with the word 'filter'.

My questions are:

Is there a better way to accomplish the same functionality (ie. running some functions on all inputs), at a middleware, controller or model level?
This implementation works (I've written a few simple tests for them to verify this), but is this good design, and can it be improved? For instance, I'm curious if this can be rewritten into a trait, which I think is preferable - I don't think it is possible, but I might have missed something


texts: What are best practices of creating database importer in Rails?

texts:
I have sample database in GES files and I wrote importer in Ruby.

Sample file: WAR_APO.GES: https://gist.github.com/regedarek/cd0ce73c5d1e14ff9818

I will have several of GES files which I want to move to my data folder in app and I want to process them manually.

For most of them logic is the same but the difference are filename, model and attributes hash.
I want to also and new cases like: Update when type is U or Delete if is D

How should I refactor that:

class PrototypePharmaceuticImporter
  ID = '00'
  K  = "#{ID}K"
  F  = "#{ID}F"
  FB  = "#{ID}FB"
  D  = "#{ID}D"
  I  = "#{ID}I"
  U  = "#{ID}U"
  E  = "#{ID}E"

  TYPES = [K, F, FB, D, I, U, E]

  ARTICLE_TYPE = 57
  BARCODE = 15
  GROUP_CODE = 1
  GROUP_KEY = 40
  GROUP_NAME = 2
  FORM_CODE = 1
  FORM_KEY = 38
  FORM_NAME = 2
  FORM_SHORT_NAME = 3
  LONGNAME = 28
  PACKAGE_TYPE = 46
  PHARMACY_ONLY = 3
  PRESCRIPTION_ONLY = 47
  PRICE = 2
  WEIGHT = 14

  attr_accessor :file, :k, :f

  def initialize
    @pharmaceutics_file = File.open 'data/PAC_APO.GES', 'r'
    @forms_file = File.open 'data/DAR_APO.GES', 'r'
    @groups_file = File.open 'data/WAR_APO.GES', 'r'
    @k    = []
    @f    = []

    extract_groups_to_database
  end

  def extract_pharmaceutics_to_database
    add       = true
    tmp       = []
    type      = K

    @pharmaceutics_file.each_with_index do |line, i|
      break if (i > 96 * 1000 + 760 + 9)

      _type    = line.strip
      _changed = TYPES.include? _type

      if _changed && i > 0
        case type
        when K then @k << tmp
        when F then @f << tmp
        when FB then @f << tmp
        when I, U, D
          hash = {
            article_type: tmp[ARTICLE_TYPE],
            price: tmp[PRICE],
            weight: tmp[WEIGHT],
            package_type: tmp[PACKAGE_TYPE],
            group_code: tmp[GROUP_KEY],
            form_code: tmp[FORM_KEY],
            name: tmp[LONGNAME],
            barcode: tmp[BARCODE],
            pharmacy_only: tmp[PHARMACY_ONLY],
            prescription_only: tmp[PRESCRIPTION_ONLY]
          }
          Pharmaceutic.create(hash)
        end

        tmp  = []
        type = _type
      end

      tmp << clean(line)
    end
  end

  def extract_forms_to_database
    add       = true
    tmp       = []
    type      = K

    @forms_file.each_with_index do |line, i|
      break if (i > 96 * 1000 + 760 + 9)

      _type    = line.strip
      _changed = TYPES.include? _type

      if _changed && i > 0
        case type
        when K then @k << tmp
        when F then @f << tmp
        when FB then @f << tmp
        when I, U, D
          hash = {
            code: tmp[FORM_CODE],
            name: tmp[FORM_NAME],
            short_name: tmp[FORM_SHORT_NAME]
          }
          PharmaceuticForm.create(hash)
        end

        tmp  = []
        type = _type
      end

      tmp << clean(line)
    end
  end

  def extract_groups_to_database
    add       = true
    tmp       = []
    type      = K

    @groups_file.each_with_index do |line, i|
      break if (i > 96 * 1000 + 760 + 9)

      _type    = line.strip
      _changed = TYPES.include? _type

      if _changed && i > 0
        case type
        when K then @k << tmp
        when F then @f << tmp
        when FB then @f << tmp
        when I, U, D
          hash = {
            code: tmp[GROUP_CODE],
            name: tmp[GROUP_NAME]
          }
          PharmaceuticGroup.create(hash)
        end

        tmp  = []
        type = _type
      end

      tmp << clean(line)
    end
  end

  private

  def clean line
    line.strip
    .gsub(/^[\d]{2}/, '')
    .gsub(/\\[s|S]39/, 'ß')
    .gsub(/\\a25/, 'ä')
    .gsub(/\\A25/, 'Ä')
    .gsub(/\\o25/, 'ö')
    .gsub(/\\O25/, 'Ö')
    .gsub(/\\u25/, 'ü')
    .gsub(/\\U25/, 'Ü')
  end
end

Basically, I want to get rid of duplications in these methods.


texts: Mutually exclusive expandable panels (needs to work in IE9 and above)

texts:
I have a function which essentially opens and closes content associated to a panel. Only one panel can be open at any time.

Here is my JavaScript, along with a typical HTML sample that it could work with:

ts = {};

// Panels
ts.panel = (function() {

  function panels() {

    'use strict';

      var panel   = document.querySelectorAll('.panels-item');
      var button  = document.querySelectorAll('.panels-button');
      var content = document.querySelectorAll('.panels-content');

      // Reset all states
      function reset() {

        for (var i = 0; i < panel.length; i++) {
          button[i].setAttribute('aria-expanded', false);
          content[i].setAttribute('aria-hidden', true);
          content[i].className = 'panels-content js-hidden';
        }

      }

      Array.prototype.forEach.call(panel, function(el, i) {

        var button  = el.querySelector('.panels-button');
        var content = el.querySelector('.panels-content');

        // Buttons
        button.setAttribute('aria-expanded', false);
        button.setAttribute('aria-controls', content.getAttribute('id'));

        // Content
        content.setAttribute('aria-hidden', true);

        function togglePanel() {

          if (content.getAttribute('aria-hidden') === 'true') {

            reset();

            button.setAttribute('aria-expanded', true);
            content.setAttribute('aria-hidden', false);
            content.className = 'panels-content';

          } else {

            button.setAttribute('aria-expanded', false);
            content.setAttribute('aria-hidden', true);
            content.className = 'panels-content js-hidden';

          }

        }

        // Hook up the event listener
        button.addEventListener('click', togglePanel);

      });

    }

    return {
      panels: panels
    };

})();

ts.panel.panels();
* {
  margin: 0;
  padding: 0;
}

.panels {
  display: flex;
  flex-wrap: wrap;
}

.panels-item {
  border-radius: 24px;
  display: flex;
  flex-basis: 25%;
  flex-direction: column;
}

.panels-button {
  background-color: blue;
  border-radius: 24px;
  color: white;
  padding: 24px;
}

.panels-content {
  background-color: #ccc;
  padding: 24px;

}

.panels-title {
  color: blue;
  text-decoration: underline;
}

.js-hidden {
  display: none;
}

  <button class="panels-button">1</button>

1

  <button class="panels-button">2</button>

2

  <button class="panels-button">3</button>

3

  <button class="panels-button">4</button>

4

It does work, but I'm not confident with it. It would be good to have some suggestions.


texts: Find permutation of a specified lexicographic rank

texts:
This is one result of my work on Project Euler to learn Java.  I'm interested in how well this conforms to best practices as well as any recommendations on efficiency.  (I'm pretty sure this code is a lot more efficient than it is readable, but it's not deliberately obfuscated, I swear! :) )

import java.util.ArrayList;
import java.util.Arrays;

public class Combinatorics {
    private static ArrayList<Long> factorialList = new ArrayList<Long>(Arrays.asList(1L,1L));

    public static long factorial(int n) {
        if (n < 0) {
            return -1L;
        } else if (n < factorialList.size()) {
            return factorialList.get(n);
        } else {
            int currSize = factorialList.size();
            long currNum = factorialList.get(currSize - 1);
            while (currSize <= n) {
                currNum *= currSize;
                factorialList.add(currNum);
                currSize++;
            }
            return currNum;
        }
    }

    public static boolean factNisLessThanK(int n, long k) {
        if (n < 0) return false;
        if (n < factorialList.size()) return (factorialList.get(n) < k);

        int currSize = factorialList.size();
        long currNum = factorialList.get(currSize - 1);
        while (currSize <= n) {
            currNum *= currSize;
            factorialList.add(currNum);
            currSize++;
            if (currNum >= k) return false;
        }
        return true;
    }

    public static int[] lexicographicPermutation(int digits, long rank) {
        if ((rank < 1) || factNisLessThanK(digits, rank)) {
            int result[] = {-1};
            return result;
            //return "Error";
        }
        rank--;        //using 0 based ranking makes the math easier.
        int result[] = new int[digits];
        int index = 0;
        while (index < result.length) {
            result[index] = (int) (rank / factorial(digits - 1));
            rank %= factorial(digits - 1);
            index++;
            digits--;
        }
        for (int i = result.length - 1; i >= 0; i--) {
            for (int j = i + 1; j < result.length; j++) {
                if (result[j] >= result[i]) result[j]++;
            }
        }
        //return Arrays.toString(result);
        return result;
    }
}

The key to this whole program (actually, class) is the last method: lexicographicPermutation, which returns an int array containing the rankth permutation of a set of digits numbers—the numbers 0 through digits-1, in fact.

So, for example

System.out.println(Arrays.toString(Combinatorics.lexicographicPermutation(4, 11L)));

Prints [1, 3, 0, 2] because:

permutation 1: 0123
permutation 2: 0132
permutation 3: 0213
permutation 4: 0231
permutation 5: 0312
permutation 6: 0321
permutation 7: 1023
permutation 8: 1032
permutation 9: 1203
permutation 10: 1230
permutation 11: 1302

The code also includes a memoized factorial method and a factNisLessThanK method which lazily extends the factorial list only as much as needed to give the answer.  So a call like factNisLessThanK(17, 100L) would only compute up to 5! before returning false (since 5! = 120) instead of computing up to 17!

(I used it to solve Project Euler problem 24, calling lexicographicPermutation(10, 1000000L).)

https://projecteuler.net/problem=24


texts: Calculate future date based on business days (using Objects)

texts:
I realize there is already a review about this here, but it's using strings and stuff rather than date objects.

I'm trying to make a simple function to calculate days from a point in time and return object(s). The days have to follow an ignore list (like weekends and holidays) to calculate a range of days, then consider itself landing on any of those ignore days/dates in the end range, then compensate to skoot the final range if needed.

After trial and error with different methods of doing this (++ iterations mostly), I settled on this function. It seems too heavy though considering (mostly) all it's doing is skipping certain ISO day numbers to do some adds.

Are there some PHP date hidden secrets that I am missing? Or a way to boil this down? It seems like a feature such as this (skipping day codes) would be baked into PHP DatePeriod() or DateInterval() but sadly it's not. How would you approach this, pref without counters/strtotime stuff, and pref without extra classes or libs?

<?php

function getWorkingDaysFrom($from, $amtOfDays) {
    $globalDays = 0; // a global addition to $amtOfDays (such as a minimum shipping time of 3 days across all objects)
    $amtOfDays = $amtOfDays + $globalDays; // set base amount of days for initial range before calculations applied
    $ignore = array('6', '7'); // days of the week to ignore (weekends are 6 & 7) in ISO-8061
    $holidays = array('*-06-13', '*-11-23', '*-12-25', '*-01-01', '*-02-29'); // holiday dates (holidays are ignored if they fall into ignore list)
    $oneDay = new DateInterval('P1D');
    $from = new DateTime($from);
    $to = new DateTime();
    $to->add(new DateInterval('P' . $amtOfDays . 'D'));

    foreach(new DatePeriod($from, $oneDay, $to) as $day) {
        if (in_array($day->format('N'), $ignore)) {
            $to->modify('+1 day');
        } elseif (in_array($day->format('*-m-d'), $holidays)) {
            $to->modify('+1 day');
        }
        while (in_array($to->format('N'), $ignore) || (!in_array($to->format('N'), $ignore) && in_array($to->format('*-m-d'), $holidays))) {
            $to->modify('+1 day');
        }
    }
    return $to;
}

getWorkingDaysFrom('now', 20);

?>

Thanks for your time and insights.


texts:
I was working through another question here and have hacked up an answer:

def get_rows():
""" Get height of triangle from user"""

    while True:
        rows = input('Enter the number of rows:  ')
        if 3 <= rows <= 33:
            return rows

def triangle(rows, invert=True):
""" Print the outline of a triangle, of variable size.
    Print out a regular or inverted version of the triangle as necessary """

    if invert:
        height = -1 * rows
    else:
        height = 0

    # inner padding for min height (3)
    inner_buffer = [0, 1, 3]
    while len(inner_buffer) <= rows:
        inner_buffer.append(inner_buffer[-1]+2)

    level = 0
    while level <= rows:
        outer_padding = ' '*(rows - abs(height))

        if height == 0:
            print(outer_padding + '*')
        else:
            inner_padding = ' '*( inner_buffer[ abs(height) ] )
            print(outer_padding + '*' + inner_padding + '*')

        height += 1
        level += 1

At this stage I am working to re-implement this two ways using: recursion and itertools.

But I am looking at this and wonder if it would be a good place to use decorators. If someone is happy to implement one triangle (either regular or inverted, I don't mind) I would love to see the difference in the 3 implementations.


texts:
I've implemented the basic logic of a stack data structure. How can I make this code more generic? Is there any better way to display the stack contents?

StackMethods.java

import java.util.Arrays;

public class StackMethods {
    private int top;
    int size;
    int[] stack ;

    public StackMethods(int arraySize){
        size=arraySize;
        stack= new int[size];
        top=-1;
    }

    public void push(int value){
        if(top==size-1){
            System.out.println("Stack is full, can't push a value");
        }
        else{

            top=top+1;
            stack[top]=value;
        }
    }

    public void pop(){
        if(!isEmpty())
            top=top-1;
        else{
            System.out.println("Can't pop...stack is empty");
        }
    }

    public boolean isEmpty(){
        return top==-1;
    }

    public void display(){

        for(int i=0;i<=top;i++){
            System.out.print(stack[i]+ " ");
        }
        System.out.println();
    }
}

StackReviseDemo.java

public class StackReviseDemo {

    public static void main(String[] args) {
        StackMethods newStack = new StackMethods(5);
        newStack.push(10);
        newStack.push(1);
        newStack.push(50);
        newStack.push(20);
        newStack.push(90);

        newStack.display();
        newStack.pop();
        newStack.pop();
        newStack.pop();
        newStack.pop();
        newStack.display();
    }
}


texts:
I am new to PHP so this is largely compiled from examples around the web. It seems to work fine. Are there any ways in which it can be improved upon? Is it secure?

<?php
    mysql_connect("localhost", "myusername", "mypassword");
    mysql_select_db("companyDB");

    function user_login($username, $password)

{
    ob_start();

    $username = mysql_real_escape_string($username);
    $password = md5($password);

    $sql = "select * from users where username='$username' and password ='$password' LIMIT 1";
    $result = mysql_query($sql) or die('Please change your mysql query !');

    if(mysql_num_rows($result) > 0)
    {
        $_SESSION['username'] = $username;
        $_SESSION['loggedin'] = true;

        $row = mysql_fetch_row($result);
        $access_level = $row[4];
        $_SESSION['accessLevel'] = $access_level;

        while (ob_get_status())
        {
            ob_end_clean();
        }

        header("Location: /index.php");

    }
    else
    {

    }
}
?>


texts:
Note that this code is not going to be used for anything, it's more of a thought experiment. I've been seeing a lot of NumPy code lately and noticed that they use a custom indexing process, presumably by defining an object's __getitem__ method. I wrote the following class that allows for a multi-dimensional array to be indexed as ls[1,2] instead of ls[1][2].

Is there a better way to write this method? It seems unnecessary to be keeping track of current as the item look-up is descended, but I can't think of a way to avoid it.

class Array(list):
    def __getitem__(self, indices):
        current = super(self.__class__, self)
        for index in indices:
            current = current.__getitem__(index)
        return current

a = Array([[[1,2,3],[4,5,6]],
           [[0,1,2],[9,8,7]]])
print a[1,0,2] # 2


texts: A matrix with square diagonals and transpose being increments of other

texts:
Construct a matrix with the following property:

North-west to South East diagonals are squares.

Matrix[i][j] + 1 = Matrix[j][i] for each i less than j.

Example of such m a matrix is here. Also, since it appears this matrix does not have a name, I have named my class "Sqaure Diagonal, Transpose Increment".
Looking for code review, best practices, clever optimzations etc.
public final class SquareDiagonalTransposeIncrement {

    private SquareDiagonalTransposeIncrement() {}

    public static int[][] getSqaureDiagonalTransposeIncrementMatrix (int dimension) {
        if (dimension < 1) {
            throw new IllegalArgumentException("dimension: " + dimension + " should be greater than 0");
        }

        final int[][] m = new int[dimension][dimension];

        // set the diagonal
        for (int i = 0; i < dimension; i++) {
            m[i][i] = (i + 1) * (i + 1);
        }

        /*
         * Definition of the quadrant.
         *
         * - 0th quadrant means a quadrant square matrix from (0,0) to (0,0)
         * - 1st quadrant means a quadrant square matrix from (0,0) to (1,1)
         * - 2nd quadrant means a quadrant square matrix from (0,0) to (2,2)
         *
         */
        for (int quadrant = 0; quadrant < dimension - 1; quadrant++) {
            besiegeQuadrant(m, quadrant);
        }

        return m;
    }

    private static void besiegeQuadrant(int[][] m, int quadrant) {
        int value = m[quadrant][quadrant];

       // besiege the quadrant from the eastern and southern boundaries.
        for (int i = 0; i <= quadrant; i++) {
            m[i][quadrant + 1] = ++value; // eastern
            m[quadrant + 1][i] = ++value; // southern
        }
    }

    public static void main(String[] args) {
        int[][] m =  SquareDiagonalTransposeIncrement.getSqaureDiagonalTransposeIncrementMatrix (4);
        assertArrayEquals(new int[]{ 1, 2, 5, 10}, m[0]);
        assertArrayEquals(new int[]{ 3, 4, 7, 12}, m[1]);
        assertArrayEquals(new int[]{ 6, 8, 9, 14}, m[2]);
        assertArrayEquals(new int[]{11,13,15, 16}, m[3]);
    }
}


texts:
I wrote a function that dynamically stores statistical data. I tried to clone the functionality of how I had originally written my solution in Bash. Is there perhaps something I could improve, or do better?

Bash Solution

#!/bin/bash

data_set=()
while IFS= read -r -p 'Enter statistical data (empty line to quit):' input; do
  [[ $input ]] || break
  data_set+=("$input")
done

C Solution

double* get_data(int* data_size)
{
    double input;
    char line[4096];
    double* data_set = NULL;
    double* new_data = NULL;
    int size = 0;

    puts("Enter data (end w/empty line): ");
    while(fgets(line, sizeof(line), stdin))
    {
        if(line[0] == '\n') break;

        new_data = realloc(data_set, (size+1) * sizeof(double));

        if(sscanf(line, "%lf", &input))
        {
            if(new_data == NULL)
            {
                free(data_set);
                puts("Error (re)allocating memory");
                exit(1);
            }
           data_set = new_data;
           data_set[size++] = input;
       }
    }

    *data_size = size;

    return data_set;
}


texts: 2-opt algorithm for the Traveling Salesman and/or SRO

texts:
In this question I present a method to solve the Traveling Salesman Problem and/or the Single Route Optimization problem.

I am extracting 100 lat/long points from Google Maps and placing these into a text file. The program should be able to read in the text file, calculate the haversine distance between each point, and store in an adjacency matrix. The adjacency matrix will eventually be fed to a 2-opt algorithm.

Extracting an adjaceny matrix containing haversine distance from points on map has already been dealt with. This question tackles the 2-opt algorithm.

The 2-opt function is called from main as follows. route is a randomly generated list of 100 numbers, which is the path the 2-opt should follow.

def main():
    best = two_opt(connect_mat, route)  #connectivity/adjacency matrix

And here is the 2-opt function and a cost function that it utilizes. Can they be optimized in any way?

def cost(cost_mat, route):
    return cost_mat[np.roll(route, 1), route].sum()  # shifts route array by 1 in order to look at pairs of cities

def two_opt(cost_mat, route):
    best = route
    improved = True
    while improved:
        improved = False
        for i in range(1, len(route) - 2):
            for j in range(i + 1, len(route)):
                if j - i == 1: continue  # changes nothing, skip then
                new_route = route[:]  # Creates a copy of route
                new_route[i:j] = route[j - 1:i - 1:-1]  # this is the 2-optSwap since j >= i we use -1
                if cost(cost_mat, new_route) < cost(cost_mat, best):
                    best = new_route
                    improved = True
                    route = best
    return best

Sample Input:

35.905333, 14.471970
35.896389, 14.477780
35.901281, 14.518173
35.860491, 14.572245
35.807607, 14.535320
35.832267, 14.455894
35.882414, 14.373217
35.983794, 14.336096
35.974463, 14.351006
35.930951, 14.401137
.
.
.

Sample Output

I would like to be able to scale up the points being read to 5000. With the code above it would be painfully slow.

Timer Test:

Starting a timer at the beginning of the function and ending before the return statement gives an average of 1.5s per 100 points. If simple proportion can be used to test algorithm scaling performance, then:

100 points:  1.5s
1000 points: 15s
5000 points: 75s

Please correct me if my above assumption is wrong.

I was wondering whether it could be improved in any way. More information can be added if requested.

EDIT:

I noticed that I was using an extra variable best. This can be removed as such:

def two_opt(connect_mat, route):
    improved = True
    while improved:
        improved = False
        for i in range(1, len(route) - 2):
            for j in range(i + 1, len(route)):
                if j - i == 1:
                    continue  # changes nothing, skip then
                new_route = route[:]    # Creates a copy of route
                new_route[i:j] = route[j - 1:i - 1:-1]  # this is the 2-optSwap since j >= i we use -1
                if cost(connect_mat, new_route) < cost(connect_mat, route):
                    route = new_route    # change current route to best
                    improved = True

    return route

I doubt how much (if any) this increases efficiency, however it does sacrifice readability to some extent.


texts: Checking whether an array contains a value or another array

texts:
I'm designing an isIn method that takes a value:any and checks whether it exists in an array. It's working, but I'm wondering whether I missed any edge cases:

/**
 * Checks if given value is in the target array of allowed values.
 *
 * @param value The value being checked.
 * @param target The target value to perform the check against.
 * @return True if the value is in the target array, false otherwise.
 */
export function isIn(value: any, target: any[]): boolean {
  if (!isArray(value)) {
    return !isArray(target) || target.indexOf(value)>-1;
  }
  else {
    return (JSON.stringify(target)).indexOf(JSON.stringify(value)) != -1;
  }
}

describe("isIn", () => {

  it(`should return true when the value is in the array`, () => {
    expect(isIn(2, [2])).to.be.true;
    expect(isIn('a', ['a', 'b'])).to.be.true;
    expect(isIn('a', ['a'])).to.be.true;
    expect(isIn([2,3], [[2,3]])).to.be.true;
  });
  it(`should return false when the value is not in the array`, () => {
    expect(isIn('a', ['b'])).to.be.false;
    expect(isIn([2,4], [[2,3]])).to.be.false;
  });
});


texts:
Below is my try.

 //DAL
 //This is my interface
 namespace iPublisher.DAL.Interfaces
 {
   public interface IReportHandler
   {
       IEnumerable<DocumentMapper> FetchDocuments(int clientId, int pager);
    }
 }

//my concrete class
public class ReportHandler : IReportHandler
{
   public IEnumerable<DocumentMapper> FetchDocuments(int clientId, int pager)
   {
       //LINQ
   }
}

//Factory Interface
namespace iPublisher.DAL.Interfaces
{
public interface IReportFactory
{
    IReportHandler Create(int factoryId);
}
}

//Factory class
namespace iPublisher.DAL.Factory
{
public class ReportFactory : IReportFactory
{
    private IReportHandler reportObj;

    public IReportHandler Create(int factoryId)
    {
        switch (factoryId)
        {
            case 1:
                reportObj = new ReportHandler();
                return reportObj;
            default:
                throw new ArgumentException("");
        }

     }
 }
}

//UI Layer

namespace iPublisher.Controllers
{
[Authorize]
[SessionExpire]
public class ReportsController : Controller
{
      ReportFactory factObj = new ReportFactory();

    public string GetAllDocuments(string url,int pager =0)
    {
        if (SessionInfo.IsAdmin)
        {
            var documentsDataJSON = GetDocumentIntoJson(SessionInfo.ClientID, pager);

            return documentsDataJSON;
        }
        else
        {
            return "Sorry!! You are not authorized to perform this action";
        }
    }

    private string GetDocumentIntoJson(int clientId, int pager)
    {

        IReportHandler reportObj = factObj.Create(1);

        var documents = reportObj.FetchDocumentsList(clientId, pager);

        string documentsDataJSON = JsonConvert.SerializeObject(documents);

        return documentsDataJSON;
    }

 }

}

Code Metrics still showing Maintainability Index to 60.

What I am missing here or how can I improve my implementation?


texts: Laravel controller to update appointment requests

texts:
My question/refactor is similar to what is found here:
Laravel controller for form validation skinny

However, I feel that the answer is for 5.0 and not 5.2. This question does not pertain only to one controller but considering that I am making a RESTful API I believe 1 example is sufficient so I can propagate this:

class UpdateAppointmentRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'id' => 'required|integer',
            'user_id' => 'required|integer',
            'status' => 'integer',
            'note' => 'alpha'
        ];
    }
}

public function update(UpdateAppointmentRequest $request)
{
    $appointment = $this->appointment->find($request->get('id'));
    if ($appointment === null) {
        return $this->notFound('Appointment Not Found');
    }
    if($request->has('user_id') === true) {
        $appointment->user_id = $request->get('user_id');
    }
    if($request->has('status') === true) {
        $appointment->status = $request->get('status');
    }
    if($request->has('note') === true) {
        $appointment->note = $request->get('note');
    }
    try {
        return response()->json(['created' => $appointment->save()]);
    } catch(\PDOException $e) {
        return $this->internalIssues($e->getMessage());
    }
}

My issue is the if statements. Now considering that only 2 items from the validation are required and the rest are not - I have to validate if the present of the variable is there in order to update. It works well, but it will eventually make controllers very bloated (depending on which restful resources might have more parameters).

Does anyone know of a better way to refactor this within Laravel 5.2+?


texts: JSON storage of data for a to-do list application

texts:
I am making a to-do list application in Python that will show tasks/subtasks/sub-sub-tasks in a tree view, but with higher-level clades of tasks grouped into blocks (e.g., Work block, Home block). So something like:

To Do List
|--Home Tasks
|  |--Clean room
|  |--Get storage unit
|
|--Work Tasks
  |--Analysis
  |--Sorting
     |--Save Files
     |  |--Pull from computer 1
     |  |--Walk to computer 2
     |  |--Save on computer 2
     |--Sort files
     |--Plot data

My goal is to store the data as JSON, but I am totally new to this format. I am curious about the quality of the following, and any improvements I could make:

{
    "todoList":
    [
    {
    "taskBlock": "Home", "tasks":
        [
        {"task": "Clean room", "done": false},
        {"task": "Get storage unit", "done": false}
        ]
    },
    {
    "taskBlock": "Work", "tasks":
        [
        {"task": "Analysis", "done": false},
        {"task": "Sorting", "done": false, "subtasks":
            [
            {"task": "Save files", "done": false, "subtasks":
                [
                {"task": "Pull from computer 1", "done": false},
                {"task": "Walk to computer 2", "done": false},
                {"task": "Save on computer 2", "done": false}
                ]
            },
            {"task": "Sort files", "done": false},
            {"task": "Plot data", "done": false}
            ]
        }
        ]
    }
    ]
}

I am used to XML, and defining a root item, but frankly I wonder if my "root" item here is superfluous (the 'todoList' parent item).


texts: Speed up large calculation of intersections

texts:
I have the following data:

trains is a dictionary with 1700 elements. The keys are the IDs of trains and the value for each train is an array with every station ID where that train stops.
departures is a dictionary with the same keys as trains, so also 1700 elements. Each value is the departure time of the train.

Now, I would like to compute intersections between trains. When train A and train B have overlapping stops, I look at the departure time of both trains. When train A departs before train B, then (A, B) is put in the resulting set, otherwise (B, A).

trains = {90: [240, 76, 18, ...], 91: [2, 17, 98, 76, ...], ...}
departures = {90: 1418732160, 91: 1418711580, ...}
intersections = []

for i in trains:
    trA = trains[i]
    for j in trains:
        if i != j:
            trB = trains[j]
            intersect = [val for val in trA if val in trB]
            if intersect:
                if departures[i] < departures[j]:
                    if (i, j) not in intersections:
                        intersections.append((i, j))
                else:
                    if (j, i) not in intersections:
                        intersections.append((j, i))

When finished, the intersections list contains 500.000 elements.

This however takes very long to compute! I'm guessing it is because of the (i, j) not in intersections and (j, i) not in intersections statements.

Is there any way I could alter my code to speed up this calculation?


texts: Clicking child view and preventing parent view from running dblclick event

texts:
I have a parent view which has a dblclick event handler bound to it. I also have a view which is a descendant of the parent. This child view has a click event handler bound to it.

Currently, my code works as intended, but looks like this:

var ParentView = Backbone.Marionette.ItemView.extend({
    events: {
        'dblclick': '_playInStream'
    },

    _playInStream: function () {
        console.log("ParentView _playInStream");
    }
});

var ChildView = Backbone.Marionette.ItemView.extend({
    events: {
        'click': '_addToStream',
        'dblclick': '_addToStream'
    },

    _addToStream: _.debounce(function () {
        console.log("ChildView _addToStream");

        //  Don't allow dblclick to bubble up to the list item and cause a play.
        return false;
    }, 100, true)
});

The end result of this logic is:

Single-click on child view runs _addToStream (once)
Double-click on child view runs _addToStream (once)
Double-click on parent view runs _playInStream (once)

However, I feel like the way I am expressing this code is overly convoluted, but I also don't see a better way.

The debounce is necessary because double-clicking on ChildView will execute both the click and dblclick event handlers -- but I only want a single event to run.

If I remove the dblclick event handler from the child then a dblclick will propagate up to the parent which is not desireable.

Does anyone see a better way to achieve what I want?


texts: Getting a list of outdated versions with Python

texts:
I have a list of boxes and need to list only the outdated ones.

For example, input will look something like this:

maier/alpine-3.1.3-x86_64 (virtualbox, 1.2.0)
maier/alpine-3.1.3-x86_64 (virtualbox, 1.3.0)
ubuntu/precise64          (virtualbox, 20151202.0.0)
ubuntu/vivid64            (virtualbox, 20150821.0.0)
ubuntu/vivid64            (virtualbox, 20150903.0.0)
ubuntu/vivid64            (virtualbox, 20151113.0.0)
ubuntu/vivid64            (virtualbox, 20151127.0.0)
ubuntu/vivid64            (virtualbox, 20151211.0.0)
ubuntu/wily64             (virtualbox, 20151203.0.0)

Output will look roughly like this:

maier/alpine-3.1.3-x86_64 (virtualbox, 1.2.0)
ubuntu/vivid64            (virtualbox, 20150821.0.0)
ubuntu/vivid64            (virtualbox, 20150903.0.0)
ubuntu/vivid64            (virtualbox, 20151113.0.0)
ubuntu/vivid64            (virtualbox, 20151127.0.0)

Note the format consists of: name, provider, version

It seems like there would be an easy way to do this from Bash scripting alone, e.g. I can version sort a particular column with sort, but I wasn't quite able to figure it out so I roughed it out in Python instead.

Is there are better way to do this?

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""Attempt to remove outdated Vagrant boxes"""

import os
import re
import subprocess

from distutils.version import StrictVersion

def search(text):
    """Return a dictionary containing all the named subgroups of the match."""

    patt = r'^(?P<name>[^ ]+) +\((?P<provider>[^ ]+), +(?P<version>[^ ]+)\)$'
    return re.search(patt, text).groupdict()

output = subprocess.check_output(['vagrant', 'box', 'list'],
                                 stderr=subprocess.DEVNULL).decode().rstrip()

box_list = (search(line) for line in output.splitlines())

box_dict = {}

for box in box_list:
    name = box.get('name')
    version = box.get('version')
    box_dict[name] = box_dict.get(name, []) + [version]

outdated_boxes = {}

for box in box_dict:
    versions = box_dict[box]
    # remove the most recent version
    if len(versions) > 1:
        outdated_boxes[box] = sorted(versions, key=StrictVersion)[:-1]

for box in outdated_boxes:
    versions = outdated_boxes[box]
    for version in versions:
        command = ['vagrant', 'box', 'remove', box, '--box-version', version]
        print(*command)
        os.system(' '.join(command))
        # process = subprocess.Popen(command)
        # process.wait()
        print()


texts: Replace nested property for an interview

texts:
During an interview I was given this interesting JavaScript task:

Given the code:
const testStr = "bar.baz.foo:111222",
      testObj = {
        bar: {
          baz: {
            foo: 333444,
            foo2: 674654
          },
          boo: {
            faa: 11
          }
        },
        fee: 333
      };

function replaceInObj(obj, str) {
  // your code
}

write the implementation of the replaceInObj function

I was not allowed to use a 3rd-party library. I kinda solved the task, but I'm not satisfied with my solution and I'm struggling with my complex implementation. At the same time I cannot find another solution by myself.
My implementation of the replaceInObj function

const testStr = 'bar.baz.foo:111222';
const testObj = {
  bar: {
    baz: {
      foo: 333444,
      foo2: 674654,
    },
    boo: {
      faa: 11,
    },
  },
  fee: 333,
};

console.log('[before] testObj.bar.baz =', testObj.bar.baz);

// run
replaceInObj(testObj, testStr);

console.log('[after] testObj.bar.baz =', testObj.bar.baz);

function replaceInObj(obj, str) {
  const [path, valueToChange] = str.split(':');

  path.split('.').reduce((acc, prop, index, arr) => {
    const isLastProp = arr.length === index + 1;
    if (isLastProp) {
      acc[prop] = valueToChange;
    }

    return acc[prop];
  }, obj);
}


texts:
I have written another program in C++. Excluding the point that the class definition should be in a separate header file, is there anything that needs to be improved?

/*
    Date:5th January 2011
    Programmer:Fahad
*/
#include <iostream>
#include <string>
using namespace std;
class Persons     //A class that will store the name,addresses and id numbers of the users
{
    private:
        string name_;
        string address_;
        int id_number_;

    public:
        static int count;    //This is the count of the objects created
        Persons();
        void getData(int n);
        void displayData(int n);
        ~Persons();
};

int Persons count;//initializing the static member

int main()
{
    cout << "Enter Number Of Persons:";
    int n;     //This is the number of objects that the user wants to make.
    cin >> n;
    Persons *ptr;    //A pointer that will be used for the dynamic memory allocation.

    /*Exception Handling*/
    ////////////////////////////////////////////////////////////////////
    try
    {
        //ptr=new [sizeof(Persons) * n];
        ptr=new Persons[n];
    }
    catch(bad_alloc xa)
    {
        cout<<"Sorry,Program Can Not Continue";
        cin.get();
        exit(1);
    }
    /////////////////////////////////////////////////////////////////////
    for(int i = 0; i< n; i++)
    {
        ptr[i].getData(n);
    }
    for(int j = 0; j< n; j++)
    {
        ptr[j].displayData( n );
    }
    cin.get();
    delete[] ptr;
    return 0;
}

/*Function Definitions*/

Persons::Persons()
{
    name_="";
    address_="";
    id_number_=0;
    count++;
}
void Persons::getData(int n)
{

        cout<<"Enter Name (Press '$' To Exit):";
        getline(cin,name_,'$');
        cout<<endl<<"Enter Address (Press '$' To Exit):";
        getline(cin,address_,'$');
        cout<<endl<<"Enter Identitiy Card Number:";
        cin>>id_number_;

}
void Persons::displayData(int n)
{

        cout<<"Name:"<<name_;
        cout<<endl<<"Address:"<<address_;
        cout<<endl<<"Identitiy Card Number:"<<id_number_;

}


texts: PageObject implementation (CoffeeScript, CasperJS)

texts:
I'm using CasperJS and CoffeeScript for integration testing of a hobby project. Page Objects seem to be a useful abstraction. I had two major requirements:

Support for node.js style callbacks - mainly because tests can then be written using async.waterfall
Support extending (subclassing) to encapsulate common functionality, like a sidebar or a navbar

Here's the code, followed by a brief example of how I use it. It's a bit long, but that's about the shortest meaningful example I can give.

class PO # Base PO
  @casper: null

  # name: The name of the page object. Used to access it as PO[name], which is kind of like a forward declaration
  # selector: The page represented by this PO is considered to be ready for usage once this is visible
  # mixin: An object; properties of this will be mixed into the new instance
  constructor: (@name, @selector, mixin) ->
    if PO[@name] isnt undefined
      throw "Failed creating PO #{@name}: a PO instance or class method with this name already exists"
    PO[@name] = this
    @__defineGetter__ 'casper', -> PO.casper
    this[key] = val for key, val of mixin

  waitUntilVisible: (cb) -> @casper.waitUntilVisible @selector, cb

  # Switch to po, and call the callback cb with err and the po as parameters
  next: (cb, po, err=null) ->
    t0 = Date.now()
    msg = "Switching to PO #{po.name}"
    @casper.log msg, 'debug'
    po.waitUntilVisible =>
      @casper.log "#{msg}: done in #{Date.now() - t0}ms", 'debug'
      cb err, po
    po

new PO 'navbar', '',
  tabs: {}
  logout: (cb) ->
    @casper.click '#logout'
    @casper.waitFor (=> not @haveLogin()), (=> cb null, PO['login'])

  haveLogin: (cb) ->
    result = nick == @casper.evaluate -> $('#current-user-nick').text()
    cb? result
    result

  addTab: ({name, switchSelector, readySelector, po}) ->
    @tabs[name] = arguments[0]

  toTab: (name, cb) ->
    cb "Navbar tab #{name} not known", null unless name of @tabs
    tab = @tabs[name]
    @casper.click tab.switchSelector
    @casper.waitUntilVisible tab.readySelector, => cb null, PO[tab.po]

class PON extends PO # PO with navbar
  constructor: (name, selector, mixin) ->
    super name, selector, mixin
    @navbar = PO['navbar']

new PON 'login', '.login-form',
  # ...

module.exports = (casper) ->
  PO.casper = casper
  PO['login']


texts: Showing a spinner over content - fade out some elements and disable clicking on some elements

texts:
I am displaying a loading spinner inside of various elements. There are four potential states an element could be in:

Reduced opacity; unresponsive to pointer events.
Reduced opacity; responsive to pointer events.
Maintain opacity; unresponsive to pointer events.
Maintain opacity; responsive to pointer events.

I'm trying to write some CSS which is elegant, but also allows for enough flexibility to achieve the above goals.

I've attached a code-snippet to this post showing my implementation. Please note that it is intended only for modern browsers.

My concerns are:

I feel like this is the sort of thing which should be done using an overlay element and clever usage of z-index, but I also feel like my scenarios are too dynamic to support this sort of approach.
I am using the * selector with some filters applied to it in order to properly select elements. It is generally frowned upon to use the * selector. However, I don't believe that inverting my logic and applying .is-belowFadeout and .is-unclickableWhenSpinning classes is more appropriate.

How should I be approaching this problem?

.content {
    width: 180px;
    height: 180px;
    position: relative;
    background-color: lightGray;
    padding: 10px;
}

.content-subContent {
    width: 40px;
    height: 40px;
    background-color: red;
    cursor: pointer;
    display: inline-block;
}

@-webkit-keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(359deg);
  }
}

.spinner {
    border: 1px solid #4ea6ea;
    border-left-color: transparent;
    border-top-color: transparent;
    border-radius: 50%;
    -webkit-animation: spin 600ms infinite linear;
    display: none;
    vertical-align: middle;
}

.spinner--large {
    width: 32px;
    height: 32px;
    border-width: 4px;
}

/* TODO: This seems like a poor way of doing this. What would be more robust? */
.is-showingSpinner > *:not(.is-aboveFadeout):not(.spinner) {
    opacity: .2;
}

.is-showingSpinner > *:not(.is-alwaysClickable) {
    pointer-events: none;
}

.is-showingSpinner > .spinner {
    display: inline-block;
}

.u-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
}

.u-marginAuto {
    margin: auto;
}

.is-alwaysClickable:hover {
    background-color: #8b0000;
}


texts:
I'm trying to implement a deque data structure with an iterator in Java using array. Please help to review and point out things that I can improve on.

public class Deque<Item> implements Iterable<Item> {

  private Item[] a; // the array.
  private int itemCount; // number of objects the array holds at any given point in time.
  private int head; //last filled position from Front
  private int tail; //last filled position from END
  private int size; // size of array.

   public Deque() {
      // construct an empty deque
      size = 2;
      a = (Item[])new Object[size];
      itemCount = 0;
      head = 0;
      tail = 0;
   }

   public boolean isEmpty()  {
                   // is the deque empty?
     return (itemCount == 0);
   }
   public int size()                        {
      // return the number of items on the deque
    return itemCount;
   }
   public void addFirst(Item item) {
     try {
       if (item == null) {
       throw new IllegalArgumentException("item cannot be null");
     }
   }
   catch (NullPointerException ex) {
     throw new IllegalArgumentException("item cannot be null");
   }
      if (isEmpty()) {
        addLast(item);
        //return;
      } else if (head == 0) {
        resize(size);
        head--;
        a[head] = item;
        itemCount++;
        //return;
      } else {
        head--;
        a[head] = item;
        itemCount++;
        //return;
      }
      return;
   }

   private void resize (int currentSize) {
     //resize array to squared of current size.
     int newSize = currentSize * currentSize;
     int newStart = (currentSize * (currentSize - 1))/2;
     int newHead = newStart;
     Item[] newA = (Item[]) new Object[newSize];
     for (int j = itemCount; j > 0; j--) {
       newA[newStart++] = a[head++];
     }
     head = newHead;
     tail = newStart - 1;
     size = newSize;
     a = newA;
     return;
   }

   public void addLast(Item item)   {

      if (isEmpty()) {
        tail++;
        a[tail] = item;
        head = tail;
        itemCount++;
        //return;
      }
      else if ( tail == (size -1)) {
        resize(size);
        tail++;
        a[tail] = item;
        itemCount++;
      }
      return;
   }
   public Item removeFirst()  {
      // remove and return the item from the front
      Item k;
      if (isEmpty()) throw new java.util.NoSuchElementException("Empty Deque");
      else {
        k = a[head];
        a[head] = null;
        head --;
        //start --;
        itemCount--;
      }
      return k;
   }
   public Item removeLast()  {
     // remove and return the item from the end
     Item k;
     if (isEmpty()) throw new java.util.NoSuchElementException("Empty Deque");
     else {
       k = a[tail];
       a[tail] = null;
       tail --;
       //end --;
       itemCount--;
     }
     return k;
   }
   public Iterator<Item> iterator() {
    // return an iterator over items in order from front to end
    return new DequeIterator();
   }
   private class DequeIterator implements Iterator<Item> {
     private int startpos;
     private int size;
     public DequeIterator () {
       startpos = head;
       size = itemCount;
     }
     public boolean hasNext() {
       return (size != 0);
     }
     public void remove() {
       throw new UnsupportedOperationException();
     }
     public Item next() {
       if (hasNext()) {
         size--;
         return a[startpos++];
       }
       throw new NoSuchElementException();
     }
   }
}


texts: Validating that all strings in an array match a condition

texts:
I want to validate a list of objects for example strings. and if one of the objects fails to pass the condition return false as validation result . this is the code I use :

    public static bool AreValid(string[] strs)
    {
        foreach (string str in strs)
        {
            if (str != condition )
            {
                return false; // does this breaks the for loop ?
                // break;     // no need to this
            }
        }

        return true;
    }

is this a correct approach ?


texts:
Here is one of the possible solutions:

  public static int getNextPowerOfTwo(int value) {
    int result = value;
    result -= 1;
    result |= result >> 16;
    result |= result >> 8;
    result |= result >> 4;
    result |= result >> 2;
    result |= result >> 1;
    return result + 1;
}

As in your opinion is it good enough or may you suggest better one?


texts:
I have recently gotten into Java in a Computer Science class at my high school and I am trying to learn more than just the basics I have learned in school. Yesterday, I designed a very simple text editor I named Aqua that is written with Swing. For some reason, my computer drags a little bit when I run these methods. Is it because I have a crappy computer or did I write something wrong? Thanks!

private void save(String content, String name) throws IOException{
    System.out.println(dir.toString());
    if(firstRun<1){
        dirCreation();
        firstRun++;
    }
    try{
            String savedText = content;
            System.out.println(savedText);
            File newTextFile = new File(newDir.toString() + File + name + ".aqua");
            System.out.println(newDir.toString() + File.seperator + name + ".aqua");
            if (!newTextFile.exists()) {
                System.out.println("Created new File");
                newTextFile.createNewFile();
            }
        try (FileWriter fw = new FileWriter(newTextFile)) {
            fw.write(savedText);
        }

    }
    catch(IOException x){
                System.err.format("IOException: %s%n", x);
    }
}
private void load(String name) throws FileNotFoundException, IOException{
    if(firstRun<1){
        dirCreation();
        i++;
    }

    File loadingFile = new File(newDir + "\\" + name + ".aqua");
    Scanner scan = new Scanner(loadingFile);
    StringBuilder loadedText = new StringBuilder("");
    while (scan.hasNextLine()) {
            loadedText.append(scan.nextLine() + "\n");
            //Is this correct usage of StringBuilder?
    }
    jTextArea1.setText(out);
    }


texts: Extension methods to save and load form size, position, and state

texts:
I wrote these extension methods to provide a generic/re-usable method for saving a form's size, position, and window state. What I would primarily like to know is if there is a better way to handle storing the WindowState property. I would also like to know if there are any bugs I might have overlooked, unnecessary code, or ways to make it more readable.

public static void SaveFormSizeAndLocation( this Form form )
{
    try
    {
        using( RegistryKey key = Application.UserAppDataRegistry.CreateSubKey(form.Name) )
        {
            if( key != null )
            {
                if( form.WindowState == FormWindowState.Normal )
                {
                    key.SetValue("Left",form.Left);
                    key.SetValue("Top",form.Top);
                    key.SetValue("Width",form.Width);
                    key.SetValue("Height",form.Height);
                }
                if( form.ShowInTaskbar )
                {
                    string windowState = Enum.GetName(typeof(FormWindowState),form.WindowState);
                    key.SetValue("WindowState",form.WindowState);
                }
            }
        }
    }
    catch
    {
        // Party on, Garth!
    }
}
public static void LoadFormSizeAndLocation( this Form form )
{
    try
    {
        using( RegistryKey key = Application.UserAppDataRegistry.OpenSubKey(form.Name) )
        {
            if( key != null )
            {
                form.Left = (int)key.GetValue("Left",form.Left);
                form.Top = (int)key.GetValue("Top",form.Top);
                form.Width = (int)key.GetValue("Width",form.Width);
                form.Height = (int)key.GetValue("Height",form.Height);
                // Move window into visible screen bounds if outside screen bounds (prevent off-screen hidden windows)
                Rectangle screenRect = SystemInformation.VirtualScreen;
                if( form.Left < screenRect.Left )
                    form.Left = screenRect.Left;
                if( form.Top < screenRect.Top )
                    form.Top = screenRect.Top;
                if( form.Right > screenRect.Right )
                    form.Left = screenRect.Right - form.Width;
                if( form.Bottom > screenRect.Bottom )
                    form.Top = screenRect.Bottom - form.Height;
                if( form.ShowInTaskbar )
                {
                    string windowState = Enum.GetName(typeof(FormWindowState),form.WindowState);
                    windowState = key.GetValue("WindowState",windowState).ToString();
                    form.WindowState = (FormWindowState)Enum.Parse(typeof(FormWindowState),windowState);
                }
            }
        }
    }
    catch
    {
        // Party on, Wayne!
    }
}


texts: Destructure array and use object shorthand assignment

texts:
I have the following code:

let id = '';
let text = '';

// Note: `match` = [full match, id (first group), text (second group)]
if (match.length > 1) {
  [, id] = match;
}
if (match.length > 2) {
  [, id, text] = match;
}
return { id, text };

match could be null, or lengths between 1-3.

id and text need to be empty strings by default and only set if match is not null and of certain length.

How can I shorten this up?

Possibly avoiding the if statements.


texts:
This takes a dataframe as an argument, looks at all pairs of two columns in that data frame (country and year) and returns a column value of that pair in another data frame (the gini number).

get_gini <- function(year, country){
    GINI = 0
    SUBSETTED_WITH_COUNTRY_NAME_NOW_WITH_YEAR <- inequality[inequality$Code== country & inequality$Year== year,]
    GINI <- mean(as.numeric(SUBSETTED_WITH_COUNTRY_NAME_NOW_WITH_YEAR$Gini))

    country_and_year<- totes_data[totes_data$totes_data == country & totes_data$year == year,]
    country_and_year$GiniState1<-GINI
    output<-country_and_year$GiniState1
    output<-output[1]
    if (is.na(output)){
      output=0
    }
    else {
      output = output
    }
    assign("ginilist",output, envir=globalenv())
    rbind(output,ginilist)
}


texts: Homebrew std::string for use with kernel

texts:
I've ported some standard library facilities like vector, algorithm, etc. to my kernel so I can code in C++ instead of C. This is one of them. I'm looking for concerns regarding:

Performance
Safety
Friendly interface

Perhaps there are more idiomatic ways to accomplish what I'm going for?

#ifndef _LIBCPP_STRING_H_
#define _LIBCPP_STRING_H_

#include <prefix.h>
#include <libc/stddef.h>
#include <libc/string.h>
#include <libc/stdint.h>

#include "algorithm.h"

namespace std
{
    template<size_t Size>
    class fixed_string
    {
    public:
        static constexpr size_t npos = static_cast<size_t>(UINT32_MAX);

        fixed_string() :
            _length(0)
        {
            _buffer[0] = '\0';
        }
        fixed_string(const char *string)
        {
            assign(string, strlen(string));
        }
        fixed_string(const fixed_string &other)
        {
            assign(other._buffer, other._length);
        }

        fixed_string &operator =(const fixed_string &other)
        {
            assign(other._buffer, other._length);
            return *this;
        }
        fixed_string &operator =(const char *string)
        {
            assign(string, strlen(string));
            return *this;
        }

        bool operator ==(const fixed_string &other) const
        {
            if(_length != other._length)
                return false;

            return (strcmp(other._buffer, _buffer) == 0);
        }
        bool operator ==(const char *string) const
        {
            return (strcmp(string, _buffer) == 0);
        }

        bool operator !=(const fixed_string &other) const
        {
            return !(*this == other);
        }
        bool operator !=(const char *string) const
        {
            return !(*this == string);
        }

        size_t find(const fixed_string &other) const
        {
            return find(other._buffer, _length);
        }
        size_t find(const char *other) const
        {
            return find(other, strlen(other));
        }
        size_t find(const char *other, size_t length) const
        {
            size_t found  = 0;

            char *buffer = _buffer;
            while(*buffer)
            {
                if(found >= length)
                {
                    size_t diff = ((buffer - found) - _buffer);
                    return diff;
                }

                found = (*buffer == other[found]) ? found + 1 : 0;
                buffer ++;
            }

            return npos;
        }

        const char *c_str() const { return _buffer; }
        size_t length() const { return _length; }

    private:
        void assign(const char *string, size_t length)
        {
            if(!string)
            {
                _buffer[0] = '\0';
                _length = 0;

                return;
            }

            _length = std::min(length, Size);
            strlcpy(_buffer, string, _length);
        }

        char _buffer[Size + 1];
        size_t _length;
    };
}

#endif /* _LIBCPP_STRING_H_ */


texts:
Suppose each node of a tree has maximum n children. I want to serialize and de-serialize for a tree. My current solution is doing pre-order traverse, and using # to represent None child.

I'm wondering if there are any better implementation method. My current concern for my code is if the tree has too many None node (kinds of sparse tree), there will be a lot # in the serialized string output. But I have not figured out a way to represent serialized tree better, since I think for None node, we still need some kinds of information to represent there is an empty node there.

I'm looking forward to any smart ideas on existing code and smart ideas to represent serialized tree in a better (more compact and more efficient -- for both serialize and de-serialize).

My print tree method is just for the purpose of verification. deserialize is correctly re-constructing the tree, so we can skip code review for this part.

number_of_children = 3
index = 0
class Node:
    def __init__(self, value):
        self.value = value
        self.children = [] # a list of Node

    def serialize(self, result): # serialzie a tree into a string
        result.append(str(self.value))
        for child in self.children:
            if child:
                child.serialize(result)
            else:
                result.append('#')

    def printTree(self): # print tree layer by layer
        current_level_buffer=[]
        current_level_buffer.append(self)
        current_level_count = 1
        next_level_count=0
        next_level_buffer=[]
        print_buffer=[]
        next_level_valid = 1
        while True:
            node = current_level_buffer.pop(0)
            if not node:
                print_buffer.append('#')
                current_level_count -= 1
            else:
                print_buffer.append(str(node.value))
                current_level_count -= 1
                for child in node.children:
                    next_level_buffer.append(child)
                    next_level_count += 1
                    if child:
                        next_level_valid += 1
            if current_level_count == 0:
                print ' '.join(print_buffer)
                current_level_count = next_level_count
                current_level_buffer = next_level_buffer
                next_level_count = 0
                next_level_buffer=[]
                print_buffer=[]
                if next_level_valid == 0:
                    return
                next_level_valid = 0

def deserialize(source):  # deserialize a string into a tree
    global index
    current_node = None
    if source[index] != '#':
        current_node = Node(source[index])
        for i in range(number_of_children):
            index += 1
            current_node.children.append(deserialize(source))
    return current_node

if __name__ == "__main__":
    root = Node(0)
    child11 = Node(1)
    child12 = Node(2)
    root.children.append(child11)
    root.children.append(child12)
    root.children.append(None)
    child21 = Node(3)
    child22 = Node(4)
    child23 = Node(5)
    child11.children.append(child21)
    child11.children.append(child22)
    child11.children.append(child23)
    child24=Node(6)
    child25=Node(7)
    child26=Node(8)
    child12.children.append(child24)
    child12.children.append(child25)
    child12.children.append(child26)

    leafnodes = [child21, child22, child23, child24, child25, child26]
    for leaf in leafnodes:
        leaf.children.append(None)
        leaf.children.append(None)
        leaf.children.append(None)

    root.printTree()
    result = []
    root.serialize(result)
    print result
    print ''.join(result)

    new_root = deserialize(''.join(result))
    new_root.printTree()


texts: Sorting software version list using Python 2.7 (no modules)

texts:
I am participating in a challenge and one of the challenges was to write a script to sort a list of software versions (ex: 1.0, 1.3.2, 12, 1.3.0). Here is the my solution:

def answer(l):
     return sorted(l, key=lambda s: [int(i) for i in s.split('.')])
print(answer(eval(raw_input())))

In this code, I am essentially taking the list, and splitting each element by '.', converting them to integers, and then sorting the list. One thought is to use list comprehension to remove lambda altogether, but unsure how to achieve it.


texts:
Is this code correct?

This code was adapted from this alphabeta pseudocode.  AlphaBeta search is often mentioned but getting the code 100% correct is tricky.

IGame is an interface with two methods:
getScore() - evaluates the current game state from the viewpoint of the AI
generateMoves() - creates possible moves from the current game state.

class Search
{
    Move bestMove;

    Move findBestMove(int ply, IGame g)
    {
        bestMove = null;
        alpha_beta(ply, g, Integer.MINIMUM, Integer.MAXIMUM);
        return bestMove;
    }

    int alpha_beta(int depth, IGame g, int alpha, int beta)
    {
        if (depth == 0 || g.isGameFinished()) return g.getScore();

        Move[] gameMove = g.generateMoves();

        for (int i = 0; i < gameMove.length; i++)
        {
            g.execute(gameMove[i]);
            int score = -alpha_beta(depth - 1, -beta, -alpha);
            g.undo(gameMove[i]);

            if (alpha < score)
            {
                alpha = score;
                bestMove = gameMove[i];
            }
            if (beta <= alpha) return alpha;
        }
        return alpha;
    }
}


texts:
I've created a program that can send & receive a screenshot. However, I feel like my method is a little bit...inefficient. I have to write to the stream twice, because from what I've observed, in order for the image to form properly, I must know the exact file size aka. the length. So, what I do is write the length to the the stream, than write the image to the stream. Is there a way to combine this into one step, or optimize it more?

Here's my code for the client

 else if (plainText.Contains("screenshot")) //check if received command is asking for screenshot
        {
            MemoryStream ms = new MemoryStream();
            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//save bitmap to MemoryStream so I can read length
            writeToStream(ms.ToArray().Length.ToString()); //Write the length to the NetWorkStream
            writeToStream(ms.ToArray()); //Write the actual image to the NetworkStream
            ms.Close(); //close the MemoryStream when done
        }

And for my server:

private void screenShotBTN_Click(object sender, EventArgs e)
    {
        screenShotBTN.Enabled = false;

        NetworkStream stream = getSelectedClient().GetStream();

        writeBuffer = Encoding.ASCII.GetBytes("screenshot");

        stream.Write(writeBuffer, 0, writeBuffer.Length); // send screenshot request

        int data = 0;

        byte[] readBuffer = new byte[getSelectedClient().ReceiveBufferSize];

        data = stream.Read(readBuffer, 0, readBuffer.Length);

        string pictureSize = Encoding.ASCII.GetString(readBuffer, 0, data);

        Console.WriteLine(pictureSize); //for debugging purposes so I can see the length

        string x = new Random().Next().ToString();

        FileStream f = new FileStream(x + ".bmp", FileMode.Create, FileAccess.Write);

        while (new FileInfo(x + ".bmp").Length != Convert.ToInt32(pictureSize))
        {
            data = stream.Read(readBuffer, 0, readBuffer.Length);
            f.Write(readBuffer, 0, data);
        }

        f.Close();

        Process.Start(x + ".bmp");

        screenShotBTN.Enabled = true;
    }


texts: Standardizes Rows of a Pandas.DataFrame Object

texts:
Please take a look at this little snippet of code and explicate on whether there are an efficiency enhancements that you'd make for it. It standards a row of a pandas.DataFrame by adding zeros to it so that the total length of the datum is the same as the longest datum in the column

Sample "solubility.csv" file for testing

SMILES,Solubility
[Br-].CCCCCCCCCCCCCCCCCC[N+](C)(C)C,-3.6161271205000003
O=C1Nc2cccc3cccc1c23,-3.2547670983
[Zn++].CC(c1ccccc1)c2cc(C(C)c3ccccc3)c(O)c(c2)C([O-])=O.CC(c4ccccc4)c5cc(C(C)c6ccccc6)c(O)c(c5)C([O-])=O,-3.9244090954
C1OC1CN(CC2CO2)c3ccc(Cc4ccc(cc4)N(CC5CO5)CC6CO6)cc3,-4.6620645831

def generate_standard():
    dataframe = pd.read_csv('solubility.csv', usecols = ['SMILES','Solubility'])
    dataframe['standard'],longest = '',''
    for _ in dataframe['SMILES']:
        if len(str(_)) > len(longest):
            longest = str(_)
        continue
    # index,row in dataframe
    for index,row in dataframe.iterrows():
        # datum from column called 'SMILES'
        smi = row['SMILES']
        # zeros = to difference between longest datum and current datum
        zeros = (0 for x in range(len(longest) - len(str(smi))))
        # makes the zeros into type str
        zeros_as_str = ''.join(str(x) for x in zeros)
        # concatenate the two str
        std = str(smi) + zeros_as_str
        # and place it in a new column called standard at the current index
        dataframe.at[index,'standard'] = std
    return dataframe,longest


texts: ActiveAdmin: Hide a whole panel in a smart way

texts:
In order to only show relevant information to my users I want to disable the whole panel when all fields inside that panel are empty.

Currently I do this hacky method to get to this result:

if resource.phone.present? or
    resource.fax.present? or
    resource.email.present? or
    resource.website.present?
  panel I18n.t('contact_details') do
    attributes_table_for resource do
      row :phone if resource.phone.present?
      row :fax if resource.fax.present?
      row :email if resource.email.present?
      row :website if resource.website.present?
    end
  end
end

So I need to check all fields in order to know if I display the panel.
Then once I display the panel I need to check all the fields again in order to display the given row or not.

Now the user sees only what is relevant but my admin code is cluttered and no longer as maintainable.


texts:
I made a database for my Android app using SQLite and it works fine. However, as I understood, SQLite calls shouldn't be made on UI thread.

Is the below okay or not?

/**
     * @param howMany Amount of Stations returned, passing null returns all.
     *                Sorted after last time searched.
     * @return
     */
    public ArrayList<Station> getRecentStations(final int howMany) {
        final ArrayList<Station> stations = new ArrayList<Station>(howMany);

        new AsyncTask<Void, Void, Cursor>() {

            @Override
            protected Cursor doInBackground(Void... params) {
                SQLiteDatabase db = getReadableDatabase();

                Cursor cursor = db.query(TABLE_NAME_RECENT, COLUMNS_RECENT, null, null, null, null, COLUMN_TIME_SEARCHED + " DESC", Integer.toString(howMany));

            if (cursor != null) {
                    cursor.moveToFirst();
                }
                while (!cursor.isAfterLast()) {

                    Station s = new Station();
                    s.setStationId(cursor.getInt(0));
                    s.setStationName(cursor.getString(1));
                    s.setLatitude(Double.parseDouble(cursor.getString(2)));
                    s.setLongitude(Double.parseDouble(cursor.getString(3)));
                    s.setType(cursor.getString(4));
                    s.setTimeSearched(cursor.getString(5));
                    cursor.moveToNext();
                    stations.add(s);

                }

                db.close();
            }

        }.execute();
        return stations;

    }


texts: Adding support to Busybox vi for reading file from stdin

texts:
I am writing a patch for Busybox's implementation of vi, the classical command line code editor and predecessor of vim. It can open up a files through filenames given as command line arguments. My patch allows initial text to be loaded in to the buffer through a pipe on standard input too.

# normal usage
vi file.txt
# with my patch ('-' tells vi to read from stdin)
ls -l | vi -

The Busybox project is a minimal implementation of many Unix commands, meant to be run on embedded devices and has a very small executable size. The project has a script to measure the executable size delta of two versions. Below is the output for my current implementation.

function                                             old     new   delta
fd_insert                                              -     292    +292
edit_file                                           1299    1370     +71
init_text_buffer                                     333     398     +65
.rodata                                            88972   89004     +32
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 3/0 up/down: 460/0)             Total: 460 bytes

init_text_buffer does some initialisation and then calls  file_insert to read from the given filename. If it fails, the buffer will be left empty (spare a newline). text is a global pointer to the actual char buffer of the document.

I've modified this function to read from standard input if the filename argument is "-". LONE_DASH is a macro also used in other parts of Busybox.

if (fn && LONE_DASH(fn)) {
    rc = fd_insert(STDIN_FILENO, text);
} else {
    rc = file_insert(fn, text, 1);
}

file_insert was originally the only function to fill the text buffer with initial data. I haven't made any modifications to this function, but I used it as a template for fd_insert.

text_hole_make resizes the buffer if it's too small and returns the pointer delta.

full_read reads characters from a file descriptor into a buffer. The third argument is the maximum characters to read. It returns the number of characters read.

I wrote fd_insert from scratch to mimic the behaviour of file_insert, but to be able to read from file descriptors like STDIN_FILENO.

static int fd_insert(int fd, char *p)
{
    int size = BUFSIZ;
    int cnt = 0;
    int total = 0;

    do {
        total += cnt;
        p += text_hole_make(p + total, size);
        cnt = full_read(fd, p + total, size);
    } while (cnt == size);

    if (cnt < 0) {
        status_line_bold_errno("can't read from fd");
        if (total)  // un-do buffer insert
            p = text_hole_delete(p, p + total - 1, NO_UNDO);
        total = cnt;
    } else {
        total += cnt;
        // shrink unused space
        p = text_hole_delete(p + total, p + total + size - cnt - 1, NO_UNDO);
    }

    return total;
}

I've tried to remove the fd argument to reduce size, but this actually increased the size by 2 bytes (+7 to fd_insert and -5 to init_text_buffer).

There is some duplicated file reading logic in file_insert and fd_insert, but I'm not sure how to extract it. My goal is to reduce the executable size and to make my logic as clear as possible for others to read and maintain.


texts:
Question

Any way I can optimize this further using new C++11 or C++17 features? Would also like feedback on my variable naming, memory management, and style (notice my placement of varible_name++ in some areas), and how I've abstracted the sort into a recursive_merge_sort function and a merge function.

Code

#include <iostream>

void merge(int* data, int low, int mid, int high)
{
    int low_copy = low;
    int mid_copy = mid;

    int size = high - low;
    int* sorted = new int[size];
    int i = 0;

    while(low_copy < mid && mid_copy < high) {
        if(data[low_copy] < data[mid_copy]) {
            sorted[i] = data[low_copy++];
        }
        else {
            sorted[i] = data[mid_copy++];
        }
        ++i;
    }

    while(low_copy < mid) {
        sorted[i++] = data[low_copy++];
    }
    while(mid_copy < high) {
        sorted[i++] = data[mid_copy++];
    }

    for(i = 0; i < size; ++i) {
        data[low + i] = sorted[i];
    }
}

void recursive_merge_sort(int* data, int low, int high) {
    if(low >= high - 1) { return; }

    int mid = (high + low) / 2;
    recursive_merge_sort(data, low, mid);
    recursive_merge_sort(data, mid, high);

    merge(data, low, mid, high);
}

void merge_sort(int* data, int num_elements) {
    recursive_merge_sort(data, 0, num_elements);
}

int main()
{
    int data[] = { 5, 1, 4, 3, 65, 6, 128, 9, 0 };
    int num_elements = 9;

    std::cout << "unsorted\n";
    for(int i=0; i < num_elements; ++i) {
        std::cout << data[i] << " ";
    }

    merge_sort(data, num_elements);

    std::cout << "\nsorted\n";
    for(int i=0; i < num_elements; ++i) {
        std::cout << data[i] << " ";
    }

    return 0;
}


texts:
In an effort to learn more about AngularJS directives, I decided to create a simple, edit-in-place directive. I built a simple directive that would display a value, along with an edit link and the edit link would toggle visibility of an input and the save/cancel links. From there, I wanted a setup where I could make multiple properties of an object editable, and I wanted to share the link controls and trigger updates to each property together.

I decided to create a wrapper directive to handle the links and ended up with a working version in which I ended up broadcasting events from the parent(wrapper) directive and taking action in the nested directives based on that. I feel like there is probably a better approach, but this is what I was able to make work.

The HTML:

    <link rel="stylesheet" href="style.css" />

          <wrap-in-place>
            <value-in-place value="p.fname"></value-in-place>
            <value-in-place value="p.lname"></value-in-place>
          </wrap-in-place>

The JavaScript:

  var app = angular.module('editInPlaceApp',['myDirectives']);
  app.controller('MainController', ['$scope', 'PersonService', function($scope, PersonService){
    $scope.people = PersonService.loadPeople();
  }])
  .factory('PersonService', function(){
    var factory = {};

    factory.loadPeople = function(){
      var peeps = [{"id":"abc0", fname:"John", lname:"Doe"},
        {"id":"abc1", fname:"Jane", lname:"Smith"},
        {"id":"abc2", fname:"Bob", lname:"Jones"}];

      return peeps;
    };

    return factory;
  });

  angular.module('myDirectives',[])
  .directive('wrapInPlace', function(){
    return {
      restrict: 'E',
      transclude: true,
      scope:true,
      template: ' edit save cancel',
      link: function($scope, element, attrs){
        $scope.edit = function(){
          $scope.editChildren = true;
          $scope.$broadcast('editChildren',{"val":$scope.editChildren});
        };

        $scope.cancel = function(){
          $scope.editChildren = false;
          $scope.$broadcast('editChildren',{"val":$scope.editChildren});
        };

        $scope.saveChildren = function(){
          $scope.editChildren = false;
          $scope.$broadcast('saveChildren');
        };
      }
    };
  })
  .directive('valueInPlace', function(){
    return {
      restrict: 'E',
      scope: {
        value: '='
      },
      template: '{{value}}<input type="text" ng-model="updatedValue" ng-show="editing">',
      link: function ( $scope, element, attrs ) {
        $scope.editing = false;
        $scope.updatedValue = $scope.value;

        $scope.$on('editChildren', function(event, args){
          $scope.editing = args.val;
          if(!args.val){
            $scope.updatedValue = $scope.value;
          }
        });

        $scope.$on('saveChildren', function(event, args){
          $scope.editing = false;
          $scope.value = $scope.updatedValue;
        });

      }
    };
  });

The full working example can be found here.


texts:
I made this bit of code that uses jQuery in a simple HTML file to see if my son would think it is fun/interesting and to help me with my jQuery skills. The thing that was hard was the selectors towards the bottom of the script block.  I am wondering if there is a better way to do this.  Warning: it auto-refreshes to 're-pixel' the screen (for lack of a better word).

Also I am building tables but I am sure they are not right, it was my intention to grab the innerwidth and innerheight and create a table that is divided into fractional squares that perfectly fill the view-able browser screen.  I had trouble getting the logic right.

Also, I had to place a span tag in side the  blocks so the wouldn't collapse on me.  I wanted to do this in divs but I wasn't sure how to get the same effect.

$(document).ready(function () {
// find random colors
function colorMe() {
    var newColor = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6);
    return newColor;
}
// not sure about this but i got it to work in some wierd way.
var wb = Math.floor(window.innerWidth / 200);
var hb = Math.floor(window.innerHeight / 200);

// table buildout append cells and rows to the table.
// Note the yucky span tag to prevent td collapse
var table = $('

');
for (i = 0; i < 100; i++) {
    row = $('

');
    for (j = 0; j < 200; j++) {
        var row1 = $('	').html('

');
        table.append(row);
        row.append(row1);
    }
}
// table to body append
$('body').append(table);

// mouse event to emulate a pen commenting out the last two give it a fun calligraphy look
$("td").hover(function () {
    var whoIsMe = $(this).index();

    $(this).stop()
        .animate({
        "opacity": "0"
    }, "fast");

    $(this).next("td")
        .stop()
        .animate({
        "opacity": "0"
    }, "fast");

    $(this).prev("td")
        .stop()
        .animate({
        "opacity": "0"
    }, "fast");

    $(this).parent()
        .next()
        .children("td")
        .eq(whoIsMe)
        .stop()
        .animate({
        "opacity": "0"
    }, "fast");

    $(this).parent()
        .prev()
        .children("td")
        .eq(whoIsMe)
        .stop()
        .animate({
        "opacity": "0"
    }, "fast");
});
// eventually reload for a fresh palette of colored squares
setTimeout(function () {
    window.location.reload(1);
}, 50000);
});

Here is a link to a jsfiddle.


texts: Check for palindrome in singly linked list

texts:
Looking for code review, optimizations and best practices.

Node.java

 class Node {
    Node next;
    int data;

    public Node(int value) {
        data = value;
    }
}

Palindrome.java

 public class Palindrome {

        static Node reverse(Node head) {

            Node prev = null;
            Node current = head;
            Node next;
            while (current != null) {
                next = current.next;
                current.next = prev;
                prev = current;
                current = next;
            }
            head = prev;
            return head;
        }

        static public boolean isPalindrome(Node head) {

            Node current = head;
            int length = 0;

            // Get the length of the LinkedList
            while (current != null) {
                current = current.next;
                length++;
            }
            // Find position of next to mid element
            int mid = length % 2 == 0 ? length / 2 + 1 : length / 2 + 2;

            int idx = mid;
            current = head;

            // Traverse to next to mid element
            while (idx > 1) {
                current = current.next;
                idx--;
            }
            // Reverse right side of the List and return head of the reversed list
            Node head1 = reverse(current);

            boolean isPalindrome = true;
            idx = length / 2;
            current = head;

            // Check reversed list(second half) matches with first half
            while (idx > 0) {

                if (current.data != head1.data) {
                    isPalindrome = false;
                    break;
                }
                current = current.next;
                head1 = head1.next;
                idx--;
            }

            return isPalindrome;
        }

        public static void main(String[] args) {

            Node head = new Node(1);
            head.next = new Node(2);
            head.next.next = new Node(3);
            head.next.next.next = new Node(2);
            head.next.next.next.next = new Node(1);

            System.out.println(isPalindrome(head));
        }
    }


texts: Mixing function parameters, commands and command arguments in Bash functions

texts:
I'm trying to write a bash function that will take a command such as xcode-select -v or brew -v that outputs a lot of extra text, and format it to my liking.  Just to further the example, say I run xcode-select -v, it will output xcode-select version 2333..  I want to be able to split this string up and only take the 2333 part so I can put it in an echo statement.  I want the same function to be able to handle the various outputs of stuff like brew -v, or git --version, etc.

get_version_number() {
    # set local variable to executed arguments that is passed in
    local command="$($@)"
    # set up temp variable and assign to global IFS variable
    OIFS=$IFS
    # set up IFS to split the string on empty space
    IFS=" "
    # read commands output into an array and store it in $array variable
    read -a array <<< "$command"
    # clear out IFS back to what it original was for further use
    IFS=$OIFS
    # echo out array at a particular indices that should be passed in
    echo ${array[@]}
}

# store output of this command into variable for further usage
version=$(get_version_number xcode-select -v)
echo $version

Edit 1:
Originally the idea came from me having to copy/paste these same lines within different conditional blocks...

command=$(git -v)
OIFS=$IFS
IFS=" "
read -a output_array <<< "$command"
IFS=$OIFS
printf "Git version ${output_array[2]} is installed."

command=$(brew -v)
OIFS=$IFS
IFS=" "
read -a output_array <<< "$command"
IFS=$OIFS
printf "Homebrew version ${output_array[1]} is installed."


texts:
I am writing C code that has some dynamic arrays/list that are represented with a struct that contains the number of elements and a pointer to the elements.

I have some functions that are doing some similar work with that structs, for example printing the elements. To use the same code I decided to create a struct to that holes an abstract data type and the printing function receives a pointer to that struct.

A specific struct looks like that:

typedef struct {
    int numOfElements;
    int *element;

} LIST_INT, *PLIST_INT;

The generic struct look like that:

typedef struct {
    int numOfElements;
    void *element;

} LIST_GEN, *PLIST_GEN;

Is that the right approach?

This is the code example:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int numOfElements;
    char *element;

} LIST_CHAR, *PLIST_CHAR;

typedef struct {
    int numOfElements;
    int *element;

} LIST_INT, *PLIST_INT;

typedef struct {
    int numOfElements;
    void *element;

} LIST_GEN, *PLIST_GEN;

typedef void(*fpPrintElement)(void *element);

void print_list(PLIST_GEN list, int elementSize, fpPrintElement printElement) {
    int i = 0;
    int num = list->numOfElements;

    for (i = 0; i < num; ++i) {
        printElement(((char *)(list->element) + i * elementSize));
    }

    return;
}

void print_int(int * element) {
    printf("%d ", *element);
}

void print_char(char * element) {
    printf("%c ", *element);
}

void main() {
    LIST_INT list_int;
    list_int.numOfElements = 10;

    list_int.element = malloc(sizeof(list_int.element) * list_int.numOfElements);
    for (int i = 0; i < list_int.numOfElements; ++i) {
        list_int.element[i] = i * 1000;
    }

    LIST_INT list_char;
    list_char.numOfElements = 7;

    list_char.element = malloc(sizeof(list_char.element) * list_char.numOfElements);
    for (int i = 0; i < list_char.numOfElements; ++i) {
        list_char.element[i] = i + 35;
    }
    print_list((PLIST_GEN)&list_int, sizeof(*list_int.element), print_int);
    print_list((PLIST_GEN)&list_char, sizeof(*list_char.element), print_char);
    return;
}


texts: Adding a link on page with current URL (including hash) in a querystring

texts:
I'm trying to add a link to a page. The link should contain the current URL in a querystring (to be used as a ReturnUrl) and it can contain a hash.

Middle-clicking, right-clicking and ctrl+clicking should be supported. For example, middle-clicking will open the link in a new tab with (or without) the querystring.

Is this completely off-track, or how can I improve it?

<a href="@Url.Action(MVC.Links.ThereAndBackAgain())?ReturnUrl=" onclick="this.href += encodeURIComponent(location.href)">


texts: Ruby command to edit a field in a SAM file

texts:
Inspired by a bioinformatics question on Stack Overflow, I wanted to brush up on my Ruby knowledge, since I’ve been meaning to replace my command-line use of Perl by Ruby.

Briefly, the problem description is as follows:

  Given is a SAM file. This is a whitespace-delimited file with at least 11 columns. After the 11th column, there can be further optional columns in a specific format1. If there is an optional column starting with RX:Z: then remove all dashes in that column.

Here’s my Ruby “one-liner”:

ruby -ane '
  $F[11..].grep(/^RX:Z:/).map! {|x| x.gsub!(/-/, "")}
  puts $F.join("\t")
' file.sam

This works but I’m wondering if there’s a way of making this more idiomatic and/or more concise. For instance, I’m puzzled by the apparent necessity to manually join the modified $F back together. There doesn’t seem to be a way of using the -p flag instead of -n, and getting the in-place changes to $F to propagate to $_. perl -ae has the same limitation as far as I know.

1 This isn’t relevant to the question but each optional column is roughly described by the regular expression [a-zA-Z][a-zA-Z0-9]:[AifZHB]:\S*. The actual description is more complicated (for instance, if the character between the two colons is Z then the field after the second colon is a zero-terminated C-string of printable characters, and notably can include space).


texts: Command-line search for web-scraped TV Guide listings

texts:
This is a project that I am looking to clean up.  The code is fully functioning and it has already been turned in, so I figured I can let Code Review help me.  The git repository can be found here: https://github.com/TylerP33/sports_today

Here is my user input handler for my Command Line interface:

def user_input

    input = nil
    input = gets.strip.downcase

    case input

    when  "football"
        info = SportsToday::Schedule.football
        show_info(info)
        post_search_options

    when "baseball"
        info = SportsToday::Schedule.baseball
        show_info(info)
        post_search_options

    when "college basketball"
        info = SportsToday::Schedule.college_basketball
        show_info(info)
        post_search_options

    when "nba basketball"
        info = SportsToday::Schedule.nba_basketball
        show_info(info)
        post_search_options

    …

The code above calls these methods in the SportsToday::Schedule class, which search for specific strings in attributes (derived from scraped HTML):

def self.select_by(sport)
    all.select do |object|
        ATTRIBUTES.any? { |attr| object.public_send(attr).include?(sport) }
    end
end

def self.football
    select_by("Football")
end

def self.baseball
    select_by("Baseball")
end

def self.college_basketball
    select_by("College Basketball")
end

def self.nba_basketball
    select_by("NBA")
end

…

And then, the results are displayed using this:

def show_info(info)
    info.collect {|info|
        puts""
        puts""
        puts "\nEvent: #{info.sport}"
        puts "\nTime: #{info.time}"
        puts "\nDescription: #{info.description}"
        puts "\nMatchup: #{info.matchup}"
        puts ""
        puts ""
    }
end

I have some nasty code repetition going on — 10 similar methods in my CLI and Schedule classes — and I have no idea how to get around it.  There HAS to be a way for me to make some type of container for keywords, and be able to access them through my select_by method.


texts: License key generation & verification algorithm

texts:
I've made this for generating license keys & later checking if they're OK and valid.

A key is generated per-user and has an expiration time. That works fine.

Could anyone please check if it looks secure - as in, hard to crack without tampering with the verification code?

class LicenseException extends Exception{}

/**
 * Fix non-ascii characters and normalize name
 */
function sanitizeName($name)
{
    $translit = Array(
        'ä' => 'a', 'Ä' => 'A', 'á' => 'a', 'Á' => 'A', 'à' => 'a', 'À' => 'A',
        'ã' => 'a', 'Ã' => 'A', 'â' => 'a', 'Â' => 'A', 'č' => 'c', 'Č' => 'C',
        'ć' => 'c', 'Ć' => 'C', 'ď' => 'd', 'Ď' => 'D', 'ě' => 'e', 'Ě' => 'E',
        'é' => 'e', 'É' => 'E', 'ë' => 'e', 'Ë' => 'E', 'è' => 'e', 'È' => 'E',
        'ê' => 'e', 'Ê' => 'E', 'í' => 'i', 'Í' => 'I', 'ï' => 'i', 'Ï' => 'I',
        'ì' => 'i', 'Ì' => 'I', 'î' => 'i', 'Î' => 'I', 'ľ' => 'l', 'Ľ' => 'L',
        'ĺ' => 'l', 'Ĺ' => 'L', 'ń' => 'n', 'Ń' => 'N', 'ň' => 'n', 'Ň' => 'N',
        'ñ' => 'n', 'Ñ' => 'N', 'ó' => 'o', 'Ó' => 'O', 'ö' => 'o', 'Ö' => 'O',
        'ô' => 'o', 'Ô' => 'O', 'ò' => 'o', 'Ò' => 'O', 'õ' => 'o', 'Õ' => 'O',
        'ő' => 'o', 'Ő' => 'O', 'ř' => 'r', 'Ř' => 'R', 'ŕ' => 'r', 'Ŕ' => 'R',
        'š' => 's', 'Š' => 'S', 'ś' => 's', 'Ś' => 'S', 'ť' => 't', 'Ť' => 'T',
        'ú' => 'u', 'Ú' => 'U', 'ů' => 'u', 'Ů' => 'U', 'ü' => 'u', 'Ü' => 'U',
        'ù' => 'u', 'Ù' => 'U', 'ũ' => 'u', 'Ũ' => 'U', 'û' => 'u', 'Û' => 'U',
        'ý' => 'y', 'Ý' => 'Y', 'ž' => 'z', 'Ž' => 'Z', 'ź' => 'z', 'Ź' => 'Z'
    );

    return ucwords(
        strtolower(
            strtr(
                trim($name),
                $translit
            )
        )
    );
}

/**
 * Generate a license key for user's real name and expiration timestamp.
 *
 * $name ... real user's name
 * $expires ... unix timestamp when the key expires
 */
function generate_license_key($name, $expires)
{
    $name = sanitizeName($name);

    $key_plain = dechex($expires) . $name;

    // Get private key from a file
    $fp = fopen("private-key.pem", "r");
    $priv_key = fread($fp, 8192);
    fclose($fp);

    $res = openssl_get_privatekey($priv_key);
    openssl_private_encrypt($key_plain, $crypttext, $res);

    $base = base64_encode($crypttext);

    return $base;
}

/**
 * Veryfy if a license key is valid for the user
 */
function verify_license_key($key_base, $name)
{
    $name = sanitizeName($name);
    //echo "Verifying license key for $name: $key_base\n";

    $key_rsa = base64_decode(trim($key_base));

$pub_key = <<<RSA
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcExAHctl38IIUw+byiMt+X7Pe
jewWPzocUQNJN/apI55J3PV0Ri2UeZBJNT8AZy4FP31xpEpXfYNlK4N8gaZ3B6jO
4XgjaSwuFvSuXc9TUlelG4doAUbxD3lNF45oZ7tUvZ5+E0g1u0udMidkCq6cPsap
kgro0rKgHXNMQjxTeQIDAQAB
-----END PUBLIC KEY-----
RSA;

    $res = openssl_get_publickey($pub_key);

    openssl_public_decrypt($key_rsa, $key_plain, $res);

    $date = dechex(time());
    $datelen = strlen($date);

    if(substr($key_plain, 0, $datelen) < $date)
        throw new LicenseException('Expired license key!');

    $name_from_key = substr($key_plain, $datelen);

    if($name_from_key != $name)
        throw new LicenseException("Authorised name mismatch!");

    return true;
}

Here I'm testing it:

$key = generate_license_key('Pepíček Novák', time() + 3);

echo "LICENSE KEY: $key\n";

// OK
verify_license_key($key, 'Pepíček Novák');

sleep(5);

// FAIL - EXPIRED
verify_license_key($key, 'Pepíček Novák');