<commit_before>import assert from 'assert'
import * as get from '../src/utils/get'
import R from 'ramda'

describe('getSliceYear', () => {
    it('gets the year from the specified term', () => {
        assert.deepEqual(get.sliceYear('2016W1'), 2016)
        assert.deepEqual(get.sliceYear('2017W1'), 2017)
    })
})

describe('getSliceTerm', () => {
    it('gets the year from the specified term', () => {
        assert.deepEqual(get.sliceTerm('2016W1'), 'W1')
        assert.deepEqual(get.sliceTerm('2017W2'), 'W2')
    })
})

describe('getarrayOfUMI', () => {
    it('takes an array of objects and returns the UMI values of the specified UMI', () => {
        const input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017W2', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Alice Bob', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 }
        ]
        const outputUMI6 = [6,6,6,6,6,6]
        const getUMI6 = get.arrayOfUMI('UMI6')
        assert.deepEqual(getUMI6(input), outputUMI6)
        const outputUMI5 = [5,5,5,5,5,5]
        const getUMI5 = get.arrayOfUMI('UMI5')
        assert.deepEqual(getUMI5(input), outputUMI5)
    })
})

describe('getArrayOfGender', () => {
    it('takes an array of objects and returns the genders', () => {
        const input = [
            { gender: 'Male', UMI6: 5 },
            { gender: 'Male', UMI6: 2 },
            { gender: 'Female', UMI6: 5 },
            { gender: 'Male', UMI6: 5 },
            { gender: 'Female', UMI6: 5 },
            { gender: 'Female', UMI6: 3 },
            { gender: 'Male', UMI6: 1 },
        ]
        const output = ['Male', 'Male', 'Female', 'Male', 'Female', 'Female', 'Male']
        assert.deepEqual(get.arrayOfGender()(input), output)
    })
})

describe('getPercentFromDecimal', () => {
    it('takes a decimal and converts to percent', () => {
        assert.deepEqual(get.percentFromDecimal(0.5), '50%')
        assert.deepEqual(get.percentFromDecimal(0.12345), '12.345%')
    })
})

describe('getInstructorFirstName', () => {
    it('takes a name and returns the first name', () => {
        assert.deepEqual(get.instructorFirstName('Doe, John'), 'John')
        assert.deepEqual(get.instructorFirstName('Doe, John A'), 'John')
    })
})

describe('getInstructorLastName', () => {
    it('takes a name and returns the first name', () => {
        assert.deepEqual(get.instructorLastName('Doe, John'), 'Doe')
        assert.deepEqual(get.instructorLastName('Doe, John A'), 'Doe')
    })
})

describe('getCourseLevel', () => {
    it('takes a courseNUm and returns the level of the course', () => {
        assert.deepEqual(get.courseLevel('LFSLC 100 001'), 100)
        assert.deepEqual(get.courseLevel('LFSLC 168 001'), 100)
        assert.deepEqual(get.courseLevel('LFSLC 199.98 001'), 100)
        assert.deepEqual(get.courseLevel('LFSLC 289 001'), 200)
    })
})

describe('getUniqYears', () => {
    it('takes an array of courseObj and returns the uniq years', () => {
        let input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017W2', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Alice Bob', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 }
        ]
        assert.deepEqual(get.uniqYears(input), [2016, 2017, 2019])
        input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
        ]
        assert.deepEqual(get.uniqYears(input), [2016])
        input = []
        assert.deepEqual(get.uniqYears(input), [])
    })
})

describe('getUniqTerms', () => {
    it('takes an array of courseObj and returns the uniq terms', () => {
        let input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017W2', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Alice Bob', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 }
        ]
        assert.deepEqual(get.uniqTerms(input), ['W1', 'W2', 'S1', 'S2'])
        input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
        ]
        assert.deepEqual(get.uniqTerms(input), ['W1'])
        input = []
        assert.deepEqual(get.uniqTerms(input), [])
    })
})<commit_msg>Added tests for getUniqCourseLevls<commit_after>import assert from 'assert'
import * as get from '../src/utils/get'
import R from 'ramda'

describe('getSliceYear', () => {
    it('gets the year from the specified term', () => {
        assert.deepEqual(get.sliceYear('2016W1'), 2016)
        assert.deepEqual(get.sliceYear('2017W1'), 2017)
    })
})

describe('getSliceTerm', () => {
    it('gets the year from the specified term', () => {
        assert.deepEqual(get.sliceTerm('2016W1'), 'W1')
        assert.deepEqual(get.sliceTerm('2017W2'), 'W2')
    })
})

describe('getarrayOfUMI', () => {
    it('takes an array of objects and returns the UMI values of the specified UMI', () => {
        const input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017W2', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Alice Bob', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 }
        ]
        const outputUMI6 = [6,6,6,6,6,6]
        const getUMI6 = get.arrayOfUMI('UMI6')
        assert.deepEqual(getUMI6(input), outputUMI6)
        const outputUMI5 = [5,5,5,5,5,5]
        const getUMI5 = get.arrayOfUMI('UMI5')
        assert.deepEqual(getUMI5(input), outputUMI5)
    })
})

describe('getArrayOfGender', () => {
    it('takes an array of objects and returns the genders', () => {
        const input = [
            { gender: 'Male', UMI6: 5 },
            { gender: 'Male', UMI6: 2 },
            { gender: 'Female', UMI6: 5 },
            { gender: 'Male', UMI6: 5 },
            { gender: 'Female', UMI6: 5 },
            { gender: 'Female', UMI6: 3 },
            { gender: 'Male', UMI6: 1 },
        ]
        const output = ['Male', 'Male', 'Female', 'Male', 'Female', 'Female', 'Male']
        assert.deepEqual(get.arrayOfGender()(input), output)
    })
})

describe('getPercentFromDecimal', () => {
    it('takes a decimal and converts to percent', () => {
        assert.deepEqual(get.percentFromDecimal(0.5), '50%')
        assert.deepEqual(get.percentFromDecimal(0.12345), '12.345%')
    })
})

describe('getInstructorFirstName', () => {
    it('takes a name and returns the first name', () => {
        assert.deepEqual(get.instructorFirstName('Doe, John'), 'John')
        assert.deepEqual(get.instructorFirstName('Doe, John A'), 'John')
    })
})

describe('getInstructorLastName', () => {
    it('takes a name and returns the first name', () => {
        assert.deepEqual(get.instructorLastName('Doe, John'), 'Doe')
        assert.deepEqual(get.instructorLastName('Doe, John A'), 'Doe')
    })
})

describe('getCourseLevel', () => {
    it('takes a courseNUm and returns the level of the course', () => {
        assert.deepEqual(get.courseLevel('LFSLC 100 001'), 100)
        assert.deepEqual(get.courseLevel('LFSLC 168 001'), 100)
        assert.deepEqual(get.courseLevel('LFSLC 199.98 001'), 100)
        assert.deepEqual(get.courseLevel('LFSLC 289 001'), 200)
    })
})

describe('getUniqYears', () => {
    it('takes an array of courseObj and returns the uniq years', () => {
        let input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017W2', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Alice Bob', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 }
        ]
        assert.deepEqual(get.uniqYears(input), [2016, 2017, 2019])
        input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
        ]
        assert.deepEqual(get.uniqYears(input), [2016])
        input = []
        assert.deepEqual(get.uniqYears(input), [])
    })
})

describe('getUniqTerms', () => {
    it('takes an array of courseObj and returns the uniq terms', () => {
        let input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017W2', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 100 001', instructor: 'Alice Bob', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 }
        ]
        assert.deepEqual(get.uniqTerms(input), ['W1', 'W2', 'S1', 'S2'])
        input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
        ]
        assert.deepEqual(get.uniqTerms(input), ['W1'])
        input = []
        assert.deepEqual(get.uniqTerms(input), [])
    })
})

describe('getUniqCourseLevels', () => {
    it('takes an array of courseObj and returns the uniq course levels', () => {
        let input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017W2', courseNum: 'LFSLC 220 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 420 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2017S1', courseNum: 'LFSLC 570 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 123 001', instructor: 'Doe John', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
            {term: '2019S2', courseNum: 'LFSLC 300 001', instructor: 'Alice Bob', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 }
        ]
        assert.deepEqual(get.uniqCourseLevels(input), [100,200,300,400,500])
        input = [
            {term: '2016W1', courseNum: 'LFSLC 100 001', instructor: 'John Doe', UMI1: 1, UMI2: 2, UMI3: 3, UMI4: 4, UMI5: 5, UMI6: 6 },
        ]
        assert.deepEqual(get.uniqCourseLevels(input), [100])
        input = []
        assert.deepEqual(get.uniqCourseLevels(input), [])
    })
})<|endoftext|>


<commit_before>import d3 from "d3"

var i,j,k,l;

var width = 960,
    height = 500;

var color = d3.scale.category20c();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

    //以下計算中
/*
    var b = ["酒","借金"];
    var c = ["借りる","過食"];
     var a = [b,c];

*/

     /*var k_danraku = {    //形態素解析段落
       "danraku1":[
         "私",
         "生きる",
         "いる"
       ],
       "danraku2":[
         "ここ",
         "生きる"
       ]
     }
    */

    var danraku0 = ["A","B","C"];
    var danraku1 = ["B","D"];
    var keitaisokaiseki = [["あ","い","う"],["い","え"]];

console.log(keitaisokaiseki[0][0]);

    /*danraku1.add()

    var danraku = ["段落あ","段落い"];
    var A =
    */

//for
//    tangoset.add(danraku.tango);

    var jaccard

/*
    var miserables = {
      "nodes":[
        {"id":0,"name":"1","group":1},
        {"id":1,"name":"2","group":2},
        {"id":2,"name":"3","group":3},
        {"id":3,"name":"4","group":4},
        {"id":4,"name":"8","group":8},
        {"id":5,"name":"7","group":7},
        {"id":6,"name":"6","group":6},
        {"id":7,"name":"5","group":5},
        {"id":8,"name":"結局","group":1},
        {"id":9,"name":"思う","group":6},
        {"id":10,"name":"関係","group":6},
        {"id":11,"name":"入る","group":2},
        {"id":12,"name":"仕事","group":5},
        {"id":13,"name":"人","group":4},
        {"id":14,"name":"嘔吐","group":8},
        {"id":15,"name":"見える","group":2},
        {"id":16,"name":"分かる","group":3},
        {"id":17,"name":"過食","group":7},
        {"id":18,"name":"嫌い","group":1},
        {"id":19,"name":"悪い","group":2},
        {"id":20,"name":"2つ","group":7},
        {"id":21,"name":"対人","group":1},
        {"id":22,"name":"ストレス","group":8},
        {"id":23,"name":"風","group":3},
        {"id":24,"name":"信頼","group":2},
        {"id":25,"name":"一つ","group":5},
        {"id":26,"name":"行動","group":1},
        {"id":27,"name":"調子","group":4},
        {"id":28,"name":"考える","group":4},
        {"id":29,"name":"気持ち","group":2},
        {"id":30,"name":"言う","group":2},
        {"id":31,"name":"ま","group":3},
        {"id":32,"name":"自分","group":2},
        {"id":33,"name":"B","group":1}
      ],
      "links":[
        {"source":11,"target":8,"value":0},
        {"source":13,"target":11,"value":0},
        {"source":13,"target":12,"value":0},
        {"source":12,"target":9,"value":0},
        {"source":10,"target":9,"value":0},
        {"source":14,"target":10,"value":0},
        {"source":15,"target":13,"value":0},
        {"source":16,"target":14,"value":0},
        {"source":17,"target":14,"value":0},
        {"source":18,"target":15,"value":0},
        {"source":19,"target":16,"value":0},
        {"source":20,"target":17,"value":0},
        {"source":21,"target":19,"value":0},
        {"source":22,"target":20,"value":0},
        {"source":25,"target":23,"value":0},
        {"source":24,"target":23,"value":0},
        {"source":26,"target":24,"value":0},
        {"source":27,"target":22,"value":0},
        {"source":25,"target":22,"value":0},
        {"source":28,"target":27,"value":0},
        {"source":29,"target":25,"value":0},
        {"source":31,"target":28,"value":0},
        {"source":30,"target":29,"value":0},
        {"source":32,"target":31,"value":0},
        {"source":33,"target":32,"value":0}
      ]
    };
    */

var tangoset = new Set();

//var tangoset = miserables.nodes;

//nodes書き換え。nodesはオブジェクトmiserables内にある配列
//keitaisokaiseki.length は段落数
//keitaisokaiseki[i].lengthは段落[i]内の単語数
console.log(keitaisokaiseki.length);
for(i=0;i<keitaisokaiseki.length;++i){
  console.log(keitaisokaiseki[i].length);
  for(j=0;j<keitaisokaiseki[i].length;++j){
    tangoset.add(keitaisokaiseki[i][j]);
  }
}
var miserables={"nodes":new Array,"links":new Array};

console.log(tangoset);

miserables.nodes = Array.from(tangoset).map(function(t) {
  return {nodes:t};
  // body...
});

console.log(miserables.nodes[0]);

for(k=0;k<tangoset.length;++k){
  miserables.nodes[k].name =miserables.nodes[k];

  miserables.nodes[k].group =1;//ゆくゆくはjaccard係数に
}
//node作成終了。miserables.nodes.lengthがtangosetになってるはず
  console.log(miserables.nodes);
  console.log(miserables.nodes.size);

var danrakusuu = keitaisokaiseki.length;

console.log(danrakusuu);
//あとはlinksの作成だけ
//まずはlistをつくる
var list;
//list作成
//keitaisokaisekiとnodesを照らしあわせる
for(i=0;i<keitaisokaiseki.length;++i){//danrakusuuはkeitaisokaisekiとlistで共通
  for(j=0;j<keitaisokaiseki[i].length;++j){
    for(k=0;k<tangoset.size;++k){
      if(keitaisokaiseki[i][j]==tangoset[k].name){
        list[i][k]=1;
      } else{
        list[i][k]=0;
      }
    }
  }
}
console.log(list);
//listはi*k
var list3//どの段落でどれとどれが共起されてるか
//listからmiserables.linksとlist3をつくる
for(i=0;i<keitaisokaiseki.length;++i){

    for(k=0;k<tangoset.size;++k){
      for(l=k+1;l<tangoset.size;++l){//別の単語を見る
      if(list[i][k]==1 && list[i][l]==1){
        miserables.links.add({"source":l,"target":k,"value":0});
        list3[i][k][l]=1;
      }else{
        list3[i][k][l]=0;

      }
      }
    }
  }

//list3[段落][単語k][単語l]

//value太さをつける
var edges = miserables.links;

for(i=0;i<keitaisokaiseki.length;++i){

    for(k=0;k<tangoset.size;++k){
      for(l=k+1;l<tangoset.size;++l){//別の単語を見る

for(j=0;k<edges.size;++k){  //edgesをjで見ていく
  if(list3[i][k][l]==1 && edges[j].source==l && edges[j].target==k){
  edges[j].value++;
}
}
}
}
}

/*
for(i=0;i<keitaisokaiseki.length;++i){
  for(j=0;j<keitaisokaiseki[i].length;++j){
    miserables.nodes.add();
    miserables.nodes[].name =;
    miserables.nodes[].group =1;//ゆくゆくはjaccard係数に
  }
}
*/
/*    for(i=0; i<tangoset.length; ++i){
    for(j=i+1; j<tangoset.length; ++j){
    for(k=0; k<k_danraku.length; ++k){
      for(l=0; l<k_danraku.length; ++l){
        if(keitaisokaiseki[i][k]==1&&keitaisokaiseki[j][l]==1){
          miserables.nodes[i].value=1;
        }
      }
    }
    }
  }*/

//以上計算中

var graph = miserables;
//d3.json("miserables.json", function(error, graph) {

//  if (error) throw error;

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

  var link = svg.selectAll(".link")
      .data(graph.links)
    .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("text")
      .attr("class", "node")
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag)
      .text(function(d) { return d.name.substring(0,4); });

  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; });
  });
//});
<commit_msg>やっとなんか出た[objectObject]<commit_after>import d3 from "d3"

var i,j,k,l;

var width = 960,
    height = 500;

var color = d3.scale.category20c();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

    //以下計算中
/*
    var b = ["酒","借金"];
    var c = ["借りる","過食"];
     var a = [b,c];

*/

     /*var k_danraku = {    //形態素解析段落
       "danraku1":[
         "私",
         "生きる",
         "いる"
       ],
       "danraku2":[
         "ここ",
         "生きる"
       ]
     }
    */

    var danraku0 = ["A","B","C"];
    var danraku1 = ["B","D"];
    var keitaisokaiseki = [["あ","い","う"],["い","え"]];

console.log(keitaisokaiseki[0][0]);

    /*danraku1.add()

    var danraku = ["段落あ","段落い"];
    var A =
    */

//for
//    tangoset.add(danraku.tango);

    var jaccard

/*
    var miserables = {
      "nodes":[
        {"id":0,"name":"1","group":1},
        {"id":1,"name":"2","group":2},
        {"id":2,"name":"3","group":3},
        {"id":3,"name":"4","group":4},
        {"id":4,"name":"8","group":8},
        {"id":5,"name":"7","group":7},
        {"id":6,"name":"6","group":6},
        {"id":7,"name":"5","group":5},
        {"id":8,"name":"結局","group":1},
        {"id":9,"name":"思う","group":6},
        {"id":10,"name":"関係","group":6},
        {"id":11,"name":"入る","group":2},
        {"id":12,"name":"仕事","group":5},
        {"id":13,"name":"人","group":4},
        {"id":14,"name":"嘔吐","group":8},
        {"id":15,"name":"見える","group":2},
        {"id":16,"name":"分かる","group":3},
        {"id":17,"name":"過食","group":7},
        {"id":18,"name":"嫌い","group":1},
        {"id":19,"name":"悪い","group":2},
        {"id":20,"name":"2つ","group":7},
        {"id":21,"name":"対人","group":1},
        {"id":22,"name":"ストレス","group":8},
        {"id":23,"name":"風","group":3},
        {"id":24,"name":"信頼","group":2},
        {"id":25,"name":"一つ","group":5},
        {"id":26,"name":"行動","group":1},
        {"id":27,"name":"調子","group":4},
        {"id":28,"name":"考える","group":4},
        {"id":29,"name":"気持ち","group":2},
        {"id":30,"name":"言う","group":2},
        {"id":31,"name":"ま","group":3},
        {"id":32,"name":"自分","group":2},
        {"id":33,"name":"B","group":1}
      ],
      "links":[
        {"source":11,"target":8,"value":0},
        {"source":13,"target":11,"value":0},
        {"source":13,"target":12,"value":0},
        {"source":12,"target":9,"value":0},
        {"source":10,"target":9,"value":0},
        {"source":14,"target":10,"value":0},
        {"source":15,"target":13,"value":0},
        {"source":16,"target":14,"value":0},
        {"source":17,"target":14,"value":0},
        {"source":18,"target":15,"value":0},
        {"source":19,"target":16,"value":0},
        {"source":20,"target":17,"value":0},
        {"source":21,"target":19,"value":0},
        {"source":22,"target":20,"value":0},
        {"source":25,"target":23,"value":0},
        {"source":24,"target":23,"value":0},
        {"source":26,"target":24,"value":0},
        {"source":27,"target":22,"value":0},
        {"source":25,"target":22,"value":0},
        {"source":28,"target":27,"value":0},
        {"source":29,"target":25,"value":0},
        {"source":31,"target":28,"value":0},
        {"source":30,"target":29,"value":0},
        {"source":32,"target":31,"value":0},
        {"source":33,"target":32,"value":0}
      ]
    };
    */

var tangoset = new Set();

//var tangoset = miserables.nodes;

//nodes書き換え。nodesはオブジェクトmiserables内にある配列
//keitaisokaiseki.length は段落数
//keitaisokaiseki[i].lengthは段落[i]内の単語数
console.log(keitaisokaiseki.length);
for(i=0;i<keitaisokaiseki.length;++i){
  console.log(keitaisokaiseki[i].length);
  for(j=0;j<keitaisokaiseki[i].length;++j){
    tangoset.add(keitaisokaiseki[i][j]);
  }
}
var miserables={"nodes":new Array,"links":new Array};

console.log(tangoset);

miserables.nodes = Array.from(tangoset).map(function(t) {
  return {name:t};
  // body...
});

console.log(miserables.nodes[0]);

for(k=0;k<miserables.nodes.length;++k){
  miserables.nodes[k].name =miserables.nodes[k];

  miserables.nodes[k].group =1;//ゆくゆくはjaccard係数に
}
//node作成終了。miserables.nodes.lengthがtangosetになってるはず
  console.log(miserables.nodes);
  console.log(miserables.nodes.size);

var danrakusuu = keitaisokaiseki.length;

console.log(danrakusuu);
//あとはlinksの作成だけ
//まずはlistをつくる
var list;
//list作成
//keitaisokaisekiとnodesを照らしあわせる
for(i=0;i<keitaisokaiseki.length;++i){//danrakusuuはkeitaisokaisekiとlistで共通
  for(j=0;j<keitaisokaiseki[i].length;++j){
    for(k=0;k<miserables.nodes.size;++k){
      if(keitaisokaiseki[i][j]==miserables.nodes[k].name){
        list[i][k]=1;
      } else{
        list[i][k]=0;
      }
    }
  }
}
console.log(list);
//listはi*k
var list3//どの段落でどれとどれが共起されてるか
//listからmiserables.linksとlist3をつくる
for(i=0;i<keitaisokaiseki.length;++i){

    for(k=0;k<miserables.nodes.size;++k){
      for(l=k+1;l<miserables.nodes.size;++l){//別の単語を見る
      if(list[i][k]==1 && list[i][l]==1){
        miserables.links.add({"source":l,"target":k,"value":0});
        list3[i][k][l]=1;
      }else{
        list3[i][k][l]=0;

      }
      }
    }
  }

//list3[段落][単語k][単語l]

//value太さをつける
var edges = miserables.links;

for(i=0;i<keitaisokaiseki.length;++i){

    for(k=0;k<miserables.nodes.size;++k){
      for(l=k+1;l<miserables.nodes.size;++l){//別の単語を見る

for(j=0;k<edges.size;++k){  //edgesをjで見ていく
  if(list3[i][k][l]==1 && edges[j].source==l && edges[j].target==k){
  edges[j].value++;
}
}
}
}
}

/*
for(i=0;i<keitaisokaiseki.length;++i){
  for(j=0;j<keitaisokaiseki[i].length;++j){
    miserables.nodes.add();
    miserables.nodes[].name =;
    miserables.nodes[].group =1;//ゆくゆくはjaccard係数に
  }
}
*/
/*    for(i=0; i<miserables.nodes.length; ++i){
    for(j=i+1; j<miserables.nodes.length; ++j){
    for(k=0; k<k_danraku.length; ++k){
      for(l=0; l<k_danraku.length; ++l){
        if(keitaisokaiseki[i][k]==1&&keitaisokaiseki[j][l]==1){
          miserables.nodes[i].value=1;
        }
      }
    }
    }
  }*/

//以上計算中

var graph = miserables;
//d3.json("miserables.json", function(error, graph) {

//  if (error) throw error;

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

  var link = svg.selectAll(".link")
      .data(graph.links)
    .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("text")
      .attr("class", "node")
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag)
      .text(function(d) { return d.name; });

  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; });
  });
//});
<|endoftext|>


<commit_before>var mathf = require("mathf"),
    vec2 = require("vec2");

var mat32 = module.exports;

mat32.create = function(m11, m12, m13, m21, m22, m23) {
    return mat32.set(
        new mathf.ArrayType(4),
        m11, m12, m13,
        m21, m22, m23
    );
};

mat32.copy = function(a, b) {
    a[0] = b[0];
    a[1] = b[1];
    a[2] = b[2];
    a[3] = b[3];
    a[4] = b[4];
    a[5] = b[5];

    return a;
};

mat32.set = function(a, m11, m12, m13, m21, m22, m23) {

    a[0] = m11 !== undefined ? m11 : 1;
    a[2] = m12 !== undefined ? m12 : 0;
    a[1] = m21 !== undefined ? m21 : 0;
    a[3] = m22 !== undefined ? m22 : 1;
    a[4] = m13 !== undefined ? m13 : 0;
    a[5] = m23 !== undefined ? m23 : 0;

    return a;
};

mat32.identity = function(a) {
    a[0] = 1;
    a[1] = 0;
    a[2] = 0;
    a[3] = 1;
    a[4] = 0;
    a[5] = 0;

    return a;
};

mat32.zero = function(a) {
    a[0] = 0;
    a[1] = 0;
    a[2] = 0;
    a[3] = 0;
    a[4] = 0;
    a[5] = 0;

    return a;
};

mat32.mul = function(a, b, out) {
    var a11 = a[0],
        a12 = a[2],
        a13 = a[4],
        a21 = a[1],
        a22 = a[3],
        a23 = a[5],

        b11 = b[0],
        b12 = b[2],
        b13 = b[4],
        b21 = b[1],
        b22 = b[3],
        b23 = b[5];

    out = out || a;

    out[0] = a11 * b11 + a21 * b12;
    out[2] = a12 * b11 + a22 * b12;

    out[1] = a11 * b21 + a21 * b22;
    out[3] = a12 * b21 + a22 * b22;

    out[4] = a11 * b13 + a12 * b23 + a13;
    out[5] = a21 * b13 + a22 * b23 + a23;

    return out;
};

mat32.smul = function(a, s, out) {
    out = out || a;

    out[0] = a[0] * s;
    out[1] = a[1] * s;
    out[2] = a[2] * s;
    out[3] = a[3] * s;
    out[4] = a[4] * s;
    out[5] = a[5] * s;

    return out;
};

mat32.sdiv = function(a, s, out) {
    s = s !== 0 ? 1 / s : s;

    out = out || a;

    out[0] = a[0] * s;
    out[1] = a[1] * s;
    out[2] = a[2] * s;
    out[3] = a[3] * s;
    out[4] = a[4] * s;
    out[5] = a[5] * s;

    return out;
};

mat32.determinant = function(a) {

    return a[0] * a[3] - a[2] * a[1];
};

mat32.inverse = function(a, out) {
    var m11 = a[0],
        m12 = a[2],
        m13 = a[4],
        m21 = a[1],
        m22 = a[3],
        m23 = a[5],

        det = m11 * m22 - m12 * m21;

    out = out || a;

    if (det === 0) {
        return mat32.identity(out);
    }
    det = 1 / det;

    out[0] = m22 * det;
    out[1] = -m12 * det;
    out[2] = -m21 * det;
    out[3] = m11 * det;

    out[4] = (m21 * m23 - m22 * m13) * det;
    out[5] = -(m11 * m23 - m12 * m13) * det;

    return out;
};

mat32.transpose = function(a, out) {
    var tmp;

    out = out || a;

    if (out === a) {
        tmp = a[1];
        out[1] = a[2];
        out[2] = tmp;
    } else {
        out[0] = a[0];
        out[1] = a[2];
        out[2] = a[1];
        out[3] = a[3];
    }

    return out;
};

mat32.lookAt = function(out, eye, target) {
    var x = target[0] - eye[0],
        y = target[1] - eye[1],
        a = mathf.atan2(y, x) - mathf.HALF_PI,
        c = mathf.cos(a),
        s = mathf.sin(a);

    out[0] = c;
    out[1] = s;
    out[2] = -s;
    out[3] = c;

    return out;
};

mat32.compose = function(out, position, scale, angle) {
    var sx = scale[0],
        sy = scale[1],
        c = mathf.cos(angle),
        s = mathf.sin(angle);

    out[0] = c * sx;
    out[1] = s * sx;
    out[2] = -s * sy;
    out[3] = c * sy;

    out[4] = position[0];
    out[5] = position[1];

    return out;
};

mat32.decompose = function(a, position, scale) {
    var m11 = a[0],
        m12 = a[1],
        sx = vec2.lengthValues(m11, m12),
        sy = vec2.lengthValues(a[2], a[3]);

    position[0] = a[4];
    position[1] = a[5];

    scale[0] = sx;
    scale[1] = sy;

    return mathf.atan2(m12, m11);
};

mat32.setRotation = function(a, angle) {
    var c = mathf.cos(angle),
        s = mathf.sin(angle);

    a[0] = c;
    a[1] = s;
    a[2] = -s;
    a[3] = c;

    return a;
};

mat32.getRotation = function(a) {

    return mathf.atan2(a[1], a[0]);
};

mat32.setPosition = function(a, v) {

    a[4] = v[0];
    a[5] = v[1];

    return a;
};

mat32.getPosition = function(a, v) {

    v[0] = a[4];
    v[1] = a[5];

    return v;
};

mat32.extractPosition = function(a, out) {

    out[4] = a[4];
    out[5] = a[5];

    return out;
};

mat32.extractRotation = function(a, out) {
    var m11 = a[0],
        m12 = a[2],
        m21 = a[1],
        m22 = a[3],

        x = m11 * m11 + m21 * m21,
        y = m12 * m12 + m22 * m22,

        sx = x !== 0 ? 1 / mathf.sqrt(x) : 0,
        sy = y !== 0 ? 1 / mathf.sqrt(y) : 0;

    out[0] = m11 * sx;
    out[1] = m21 * sx;

    out[2] = m12 * sy;
    out[3] = m22 * sy;

    return out;
};

mat32.translate = function(a, v, out) {
    var x = v[0],
        y = v[1];

    out = out || a;

    out[4] = a[0] * x + a[2] * y + a[4];
    out[5] = a[1] * x + a[3] * y + a[5];

    return out;
};

mat32.rotate = function(a, angle, out) {
    var m11 = a[0],
        m12 = a[2],
        m21 = a[1],
        m22 = a[3],

        s = mathf.sin(angle),
        c = mathf.cos(angle);

    out = out || a;

    out[0] = m11 * c + m12 * s;
    out[1] = m11 * -s + m12 * c;
    out[2] = m21 * c + m22 * s;
    out[3] = m21 * -s + m22 * c;

    return out;
};

mat32.scale = function(a, v, out) {
    var x = v[0],
        y = v[1];

    out = out || a;

    out[0] = a[0] * x;
    out[1] = a[1] * x;
    out[4] = a[4] * x;

    out[2] = a[2] * y;
    out[3] = a[3] * y;
    out[5] = a[5] * y;

    return out;
};

mat32.orthographic = function(out, left, right, top, bottom) {
    var w = right - left,
        h = top - bottom,

        x = (right + left) / w,
        y = (top + bottom) / h;

    out[0] = 2 / w;
    out[1] = 0;
    out[2] = 0;
    out[3] = 2 / h;
    out[4] = -x;
    out[5] = -y;

    return out;
};

mat32.equal = function(a, b) {
    return !(
        a[0] !== b[0] ||
        a[1] !== b[1] ||
        a[2] !== b[2] ||
        a[3] !== b[3] ||
        a[4] !== b[4] ||
        a[5] !== b[5]
    );
};

mat32.notEqual = function(a, b) {
    return (
        a[0] !== b[0] ||
        a[1] !== b[1] ||
        a[2] !== b[2] ||
        a[3] !== b[3] ||
        a[4] !== b[4] ||
        a[5] !== b[5]
    );
};
<commit_msg>updates<commit_after>var mathf = require("mathf"),
    vec2 = require("vec2");

var mat32 = module.exports;

mat32.create = function(m11, m12, m13, m21, m22, m23) {
    return mat32.set(
        new mathf.ArrayType(6),
        m11, m12, m13,
        m21, m22, m23
    );
};

mat32.copy = function(a, b) {
    a[0] = b[0];
    a[1] = b[1];
    a[2] = b[2];
    a[3] = b[3];
    a[4] = b[4];
    a[5] = b[5];

    return a;
};

mat32.set = function(a, m11, m12, m13, m21, m22, m23) {

    a[0] = m11 !== undefined ? m11 : 1;
    a[2] = m12 !== undefined ? m12 : 0;
    a[1] = m21 !== undefined ? m21 : 0;
    a[3] = m22 !== undefined ? m22 : 1;
    a[4] = m13 !== undefined ? m13 : 0;
    a[5] = m23 !== undefined ? m23 : 0;

    return a;
};

mat32.identity = function(a) {
    a[0] = 1;
    a[1] = 0;
    a[2] = 0;
    a[3] = 1;
    a[4] = 0;
    a[5] = 0;

    return a;
};

mat32.zero = function(a) {
    a[0] = 0;
    a[1] = 0;
    a[2] = 0;
    a[3] = 0;
    a[4] = 0;
    a[5] = 0;

    return a;
};

mat32.mul = function(a, b, out) {
    var a11 = a[0],
        a12 = a[2],
        a13 = a[4],
        a21 = a[1],
        a22 = a[3],
        a23 = a[5],

        b11 = b[0],
        b12 = b[2],
        b13 = b[4],
        b21 = b[1],
        b22 = b[3],
        b23 = b[5];

    out = out || a;

    out[0] = a11 * b11 + a21 * b12;
    out[2] = a12 * b11 + a22 * b12;

    out[1] = a11 * b21 + a21 * b22;
    out[3] = a12 * b21 + a22 * b22;

    out[4] = a11 * b13 + a12 * b23 + a13;
    out[5] = a21 * b13 + a22 * b23 + a23;

    return out;
};

mat32.smul = function(a, s, out) {
    out = out || a;

    out[0] = a[0] * s;
    out[1] = a[1] * s;
    out[2] = a[2] * s;
    out[3] = a[3] * s;
    out[4] = a[4] * s;
    out[5] = a[5] * s;

    return out;
};

mat32.sdiv = function(a, s, out) {
    s = s !== 0 ? 1 / s : s;

    out = out || a;

    out[0] = a[0] * s;
    out[1] = a[1] * s;
    out[2] = a[2] * s;
    out[3] = a[3] * s;
    out[4] = a[4] * s;
    out[5] = a[5] * s;

    return out;
};

mat32.determinant = function(a) {

    return a[0] * a[3] - a[2] * a[1];
};

mat32.inverse = function(a, out) {
    var m11 = a[0],
        m12 = a[2],
        m13 = a[4],
        m21 = a[1],
        m22 = a[3],
        m23 = a[5],

        det = m11 * m22 - m12 * m21;

    out = out || a;

    if (det === 0) {
        return mat32.identity(out);
    }
    det = 1 / det;

    out[0] = m22 * det;
    out[1] = -m12 * det;
    out[2] = -m21 * det;
    out[3] = m11 * det;

    out[4] = (m21 * m23 - m22 * m13) * det;
    out[5] = -(m11 * m23 - m12 * m13) * det;

    return out;
};

mat32.transpose = function(a, out) {
    var tmp;

    out = out || a;

    if (out === a) {
        tmp = a[1];
        out[1] = a[2];
        out[2] = tmp;
    } else {
        out[0] = a[0];
        out[1] = a[2];
        out[2] = a[1];
        out[3] = a[3];
    }

    return out;
};

mat32.lookAt = function(out, eye, target) {
    var x = target[0] - eye[0],
        y = target[1] - eye[1],
        a = mathf.atan2(y, x) - mathf.HALF_PI,
        c = mathf.cos(a),
        s = mathf.sin(a);

    out[0] = c;
    out[1] = s;
    out[2] = -s;
    out[3] = c;

    return out;
};

mat32.compose = function(out, position, scale, angle) {
    var sx = scale[0],
        sy = scale[1],
        c = mathf.cos(angle),
        s = mathf.sin(angle);

    out[0] = c * sx;
    out[1] = s * sx;
    out[2] = -s * sy;
    out[3] = c * sy;

    out[4] = position[0];
    out[5] = position[1];

    return out;
};

mat32.decompose = function(a, position, scale) {
    var m11 = a[0],
        m12 = a[1],
        sx = vec2.lengthValues(m11, m12),
        sy = vec2.lengthValues(a[2], a[3]);

    position[0] = a[4];
    position[1] = a[5];

    scale[0] = sx;
    scale[1] = sy;

    return mathf.atan2(m12, m11);
};

mat32.setRotation = function(a, angle) {
    var c = mathf.cos(angle),
        s = mathf.sin(angle);

    a[0] = c;
    a[1] = s;
    a[2] = -s;
    a[3] = c;

    return a;
};

mat32.getRotation = function(a) {

    return mathf.atan2(a[1], a[0]);
};

mat32.setPosition = function(a, v) {

    a[4] = v[0];
    a[5] = v[1];

    return a;
};

mat32.getPosition = function(a, v) {

    v[0] = a[4];
    v[1] = a[5];

    return v;
};

mat32.extractPosition = function(a, out) {

    out[4] = a[4];
    out[5] = a[5];

    return out;
};

mat32.extractRotation = function(a, out) {
    var m11 = a[0],
        m12 = a[2],
        m21 = a[1],
        m22 = a[3],

        x = m11 * m11 + m21 * m21,
        y = m12 * m12 + m22 * m22,

        sx = x !== 0 ? 1 / mathf.sqrt(x) : 0,
        sy = y !== 0 ? 1 / mathf.sqrt(y) : 0;

    out[0] = m11 * sx;
    out[1] = m21 * sx;

    out[2] = m12 * sy;
    out[3] = m22 * sy;

    return out;
};

mat32.translate = function(a, v, out) {
    var x = v[0],
        y = v[1];

    out = out || a;

    out[4] = a[0] * x + a[2] * y + a[4];
    out[5] = a[1] * x + a[3] * y + a[5];

    return out;
};

mat32.rotate = function(a, angle, out) {
    var m11 = a[0],
        m12 = a[2],
        m21 = a[1],
        m22 = a[3],

        s = mathf.sin(angle),
        c = mathf.cos(angle);

    out = out || a;

    out[0] = m11 * c + m12 * s;
    out[1] = m11 * -s + m12 * c;
    out[2] = m21 * c + m22 * s;
    out[3] = m21 * -s + m22 * c;

    return out;
};

mat32.scale = function(a, v, out) {
    var x = v[0],
        y = v[1];

    out = out || a;

    out[0] = a[0] * x;
    out[1] = a[1] * x;
    out[4] = a[4] * x;

    out[2] = a[2] * y;
    out[3] = a[3] * y;
    out[5] = a[5] * y;

    return out;
};

mat32.orthographic = function(out, left, right, top, bottom) {
    var w = right - left,
        h = top - bottom,

        x = (right + left) / w,
        y = (top + bottom) / h;

    out[0] = 2 / w;
    out[1] = 0;
    out[2] = 0;
    out[3] = 2 / h;
    out[4] = -x;
    out[5] = -y;

    return out;
};

mat32.equal = function(a, b) {
    return !(
        a[0] !== b[0] ||
        a[1] !== b[1] ||
        a[2] !== b[2] ||
        a[3] !== b[3] ||
        a[4] !== b[4] ||
        a[5] !== b[5]
    );
};

mat32.notEqual = function(a, b) {
    return (
        a[0] !== b[0] ||
        a[1] !== b[1] ||
        a[2] !== b[2] ||
        a[3] !== b[3] ||
        a[4] !== b[4] ||
        a[5] !== b[5]
    );
};
<|endoftext|>


<commit_before>import ParseCSS from 'css-parse';
import toCamelCase from 'to-camel-case';
import fs from 'fs';

export default {

	parse (input, output = './style.js', prettyPrint = false) {

		if (input.indexOf('.scss') > 1) {

			let {css} = require('node-sass').renderSync({
				file: input,
				outputStyle: 'compressed'
			});

			let styleSheet = this.handleRulesAndReturnCSSJSON(css.toString());
			return helpers.outputReactFriendlyStyle(styleSheet, output, prettyPrint)

		} else {

			helpers.readFile(input, (err, data) => {
        if (err) {
          console.error(err);
          process.exit();
        }
				let styleSheet = this.handleRulesAndReturnCSSJSON(data);
				helpers.outputReactFriendlyStyle(styleSheet, output, prettyPrint)
			});
		}

	},

	handleRulesAndReturnCSSJSON(stylesheetString) {

		const changeArr = ['margin', 'padding'];

		let {stylesheet} = ParseCSS(helpers.clean(stylesheetString));

		let JSONResult = {};

		for (let rule of stylesheet.rules) {
			if (rule.type !== 'rule') return;

			for (let selector of rule.selectors) {
				selector = selector.replace(/\.|#/g, '');
				let styles = (JSONResult[selector] = JSONResult[selector] || {});

				let declarationsToAdd = [];

				for (let declaration of rule.declarations) {
					if (declaration.type !== 'declaration') return;

					let value = declaration.value;
					let property = declaration.property;

					if (helpers.indexOf(property, changeArr)) {
						var baseDeclaration = {
							type: 'description'
						};

						var values = value.replace(/px|\s*/g, '').split(',');

						values.forEach(function (value, index, arr) {
							arr[index] = parseInt(value);
						});

						var length = values.length;

						if (length === 1) {

							for (let prop of ['Top', 'Bottom', 'Right', 'Left']) {
								styles[property + prop] = values[0];
							}

						}

						if (length === 2) {

							for (let prop of ['Top', 'Bottom']) {
								styles[property + prop] = values[0];
							}

							for (let prop of ['Top', 'Bottom']) {
								styles[property + prop] = values[1];
							}
						}

						if (length === 3) {

							for (let prop of ['Left', 'Right']) {
								styles[property + prop] = values[1];
							}

							styles[`${property}Top`] = values[0];
							styles[`${property}Bottom`] = values[2];
						}

						if (length === 4) {
							['Top', 'Right', 'Bottom', 'Left'].forEach(function (prop, index) {
								styles[property + prop] = values[index];
							});
						}
					}
					else {

						if (!isNaN(declaration.value)) {
							declaration.value = parseInt(declaration.value);
							styles[toCamelCase(property)] = declaration.value;
						} else {
							styles[toCamelCase(property)] = declaration.value;
						}
					}

				}
			}
		}

		return JSONResult;

	}
}

let helpers = {

	indexOf(value, arr) {
		var flag = false;
		for (var i = 0; i < arr.length; i++) {
			if (value === arr[i]) {
				return true
			}
		}
		return flag;
	},

	clean(string) {
		return string.replace(/\r?\n|\r/g, "");
	},

	readFile(file, cb) {
		fs.readFile(file, "utf8", cb);
	},

	outputReactFriendlyStyle(style, outputFile, prettyPrint) {
		var indentation = prettyPrint ? 4 : 0;
		var wstream = fs.createWriteStream(outputFile);
		wstream.write(`module.exports = require('react-native').StyleSheet.create(${JSON.stringify(style, null, indentation)});`);
		wstream.end();
		return style;
	}
};
<commit_msg>beautify code<commit_after>import ParseCSS from 'css-parse';
import toCamelCase from 'to-camel-case';
import fs from 'fs';

export default {

	parse (input, output = './style.js', prettyPrint = false) {

		if (input.indexOf('.scss') > 1) {

			let {css} = require('node-sass').renderSync({
				file: input,
				outputStyle: 'compressed'
			});

			let styleSheet = this.handleRulesAndReturnCSSJSON(css.toString());
			return helpers.outputReactFriendlyStyle(styleSheet, output, prettyPrint)

		} else {

			helpers.readFile(input, (err, data) => {
				if (err) {
					console.error(err);
					process.exit();
				}
				let styleSheet = this.handleRulesAndReturnCSSJSON(data);
				helpers.outputReactFriendlyStyle(styleSheet, output, prettyPrint)
			});
		}

	},

	handleRulesAndReturnCSSJSON(stylesheetString) {

		const changeArr = ['margin', 'padding'];

		let {stylesheet} = ParseCSS(helpers.clean(stylesheetString));

		let JSONResult = {};

		for (let rule of stylesheet.rules) {
			if (rule.type !== 'rule') return;

			for (let selector of rule.selectors) {
				selector = selector.replace(/\.|#/g, '');
				let styles = (JSONResult[selector] = JSONResult[selector] || {});

				let declarationsToAdd = [];

				for (let declaration of rule.declarations) {
					if (declaration.type !== 'declaration') return;

					let value = declaration.value;
					let property = declaration.property;

					if (helpers.indexOf(property, changeArr)) {
						var baseDeclaration = {
							type: 'description'
						};

						var values = value.replace(/px|\s*/g, '').split(',');

						values.forEach(function (value, index, arr) {
							arr[index] = parseInt(value);
						});

						var length = values.length;

						if (length === 1) {

							for (let prop of ['Top', 'Bottom', 'Right', 'Left']) {
								styles[property + prop] = values[0];
							}

						}

						if (length === 2) {

							for (let prop of ['Top', 'Bottom']) {
								styles[property + prop] = values[0];
							}

							for (let prop of ['Top', 'Bottom']) {
								styles[property + prop] = values[1];
							}
						}

						if (length === 3) {

							for (let prop of ['Left', 'Right']) {
								styles[property + prop] = values[1];
							}

							styles[`${property}Top`] = values[0];
							styles[`${property}Bottom`] = values[2];
						}

						if (length === 4) {
							['Top', 'Right', 'Bottom', 'Left'].forEach(function (prop, index) {
								styles[property + prop] = values[index];
							});
						}
					}
					else {

						if (!isNaN(declaration.value)) {
							declaration.value = parseInt(declaration.value);
							styles[toCamelCase(property)] = declaration.value;
						} else {
							styles[toCamelCase(property)] = declaration.value;
						}
					}

				}
			}
		}

		return JSONResult;

	}
}

let helpers = {

	indexOf(value, arr) {
		var flag = false;
		for (var i = 0; i < arr.length; i++) {
			if (value === arr[i]) {
				return true
			}
		}
		return flag;
	},

	clean(string) {
		return string.replace(/\r?\n|\r/g, "");
	},

	readFile(file, cb) {
		fs.readFile(file, "utf8", cb);
	},

	outputReactFriendlyStyle(style, outputFile, prettyPrint) {
		var indentation = prettyPrint ? 4 : 0;
		var wstream = fs.createWriteStream(outputFile);
		wstream.write(`module.exports = require('react-native').StyleSheet.create(${JSON.stringify(style, null, indentation)});`);
		wstream.end();
		return style;
	}
};
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import {defineAggregate, Event, Repository, EventBus, Flow} from 'qubits'
import App from './components/App'
import * as BundleStore from './bundle-store'
import * as BundleEventStore from './event-store'
import BundleCommandHandlers from './command-handlers'
import BundleEventListeners from './event-listeners'
import * as Commands from './commands'

(() => {
  // taken from: https://gist.github.com/jed/982883
  const idGenerator = (a) => a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,idGenerator)

  const Bundle = defineAggregate({
    idGenerator,
    name: 'Bundle',
    state: {
      links: [],
      name: null
    },
    methods: {
      addLink(link) {
        this.state.links.push(link)
        return Event({name: 'LinkAddedToBundleEvent', aggregateId: this.id, payload: link, state: this.state})
      },
      edit(name) {
        this.state.name = name
        return Event({name: 'BundleEditedEvent', aggregateId: this.id, payload: {name}, state: this.state})
      }
    }
  })

  const BundleRepository = Repository(Bundle, BundleEventStore)

  const BundleFlow = Flow({
    eventBus: EventBus(BundleEventListeners(BundleStore)),
    eventStore: BundleEventStore,
    commandHandlers: BundleCommandHandlers(BundleRepository)
  })

  ReactDOM.render(<App dispatch={BundleFlow.dispatch}/>, document.querySelector('.main'))
})()
<commit_msg>Update aggregate to follow qubits<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import {defineAggregate, Event, Repository, EventBus, Flow} from 'qubits'
import App from './components/App'
import * as BundleStore from './bundle-store'
import * as BundleEventStore from './event-store'
import BundleCommandHandlers from './command-handlers'
import BundleEventListeners from './event-listeners'
import * as Commands from './commands'

(() => {
  // taken from: https://gist.github.com/jed/982883
  const idGenerator = (a) => a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,idGenerator)

  const Bundle = defineAggregate({
    idGenerator,
    name: 'Bundle',
    state: {
      links: [],
      name: null
    },
    methods: {
      addLink(link) {
        this.state.links.push(link)
        return Event({name: 'LinkAddedToBundleEvent', aggregateId: this.id, payload: link, state: this.state})
      },
      edit(name) {
        this.state.name = name
        return Event({name: 'BundleEditedEvent', aggregateId: this.id, payload: {name}, state: this.state})
      }
    },
    sourcing: {
      LinkAddedToBundleEvent: (payload, bundle) => bundle.addLink(payload),
      BundleEditedEvent: (payload, bundle) => bundle.edit(payload.name)
    }
  })

  const BundleRepository = Repository(Bundle, BundleEventStore)

  const BundleFlow = Flow({
    eventBus: EventBus(BundleEventListeners(BundleStore)),
    eventStore: BundleEventStore,
    commandHandlers: BundleCommandHandlers(BundleRepository)
  })

  ReactDOM.render(<App dispatch={BundleFlow.dispatch}/>, document.querySelector('.main'))
})()
<|endoftext|>


<commit_before>// Define module using Universal Module Definition pattern
// https://github.com/umdjs/umd/blob/master/returnExports.js

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['d3', 'vega', 'vegalite', 'lodash', 'visgen', 'visrank'],factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(
      require('d3'),
      require('vega'),
      require('vegalite'),
      require('lodash'),
      require('visgen'),
      require('visrank')
    );
  } else {
    // Browser globals (root is window)
    factory(root.d3, root.vg, root.vl, root._, root.vgn, root.visrank);
  }
}(this, function(d3, vg, vl, _, vgn, visrank){
  var schema, col_indices;

  var HEIGHT_OFFSET = 60, MAX_HEIGHT = 500, MAX_WIDTH = 500;

  var CONFIG = {
    showTable: false,

    genAggr: true,
    genBin: true,
    genTypeCasting: true,

    omitTranpose: true,
    omitDotPlotWithExtraEncoding: true,
    omitAggrWithAllDimsOnFacets: true
  }

  var keys = vg.keys;

  function getVLType(data_type){
    // return vegalite's data type
    var typeMap = {
      "categorical": "O",
      "geographic": "G",
      "quantitative": "Q",
      "datetime": "T",
      "count": "Q"
    };
    return typeMap[data_type];
  }

  // ----- load schema -----
  function loadSchema(){
    //TODO: use amd-plugin to load json, csv
    d3.json("data/birdstrikes/birdstrikes-schema.json", function(_schema) {
      //TODO: remove this line after updating csv.
      schema = _(_schema).filter(function(d){ return !d.disabled;})
        .sortBy('field_name')
        .sortBy(function(col){
          return getVLType(col.data_type) !== "Q" ? 0 :
            col.data_type === "count" ? 2 : 1 ;
        })
        .map(function(col, i){
          col.key = col['field_name'].replace(/(: )/g, "__").replace(/[\/ ]/g,"_").replace(/[()]/g, "");
          col.index = i; //add index
          return col;
        })
        .value();

      col_indices = _.reduce(schema, function(result, col, i){ result[col] = i; return result;}, {});

      console.log('schema keys', _.pluck(schema,'key').sort());
      console.log('data_types', _(schema).pluck('data_type').uniq().value());
      loadData();
    });
  }

  function updateSelectedFields(){
    var selectedColIndices = [];

    d3.selectAll("#datacols input.datacol").each(function(d, i){
      var selected = d3.select(this).node().checked;
      if(selected){
        selectedColIndices.push(d.index);
      }
    });

    renderMain(selectedColIndices);
  }

  function loadData(){
    // TODO: use other lib to load csv as columns?
    // TODO: regenerate csv with all columns
    d3.json("data/birdstrikes.json", function(data) {
      self.data = data;
      console.log("keys", vg.keys(data[0]));
      init();
    });
  }

  function init(){
    var datacols = d3.select("#datacols").selectAll("div")
      .data(schema).enter().append("div").append("label");

    datacols.append("input").attr("type","checkbox").attr("class","datacol")
      .on("change", updateSelectedFields);

    datacols.append("span").attr("class","type").text(function(d){
      return "["+getVLType(d.data_type)+"] ";
    });

    datacols.append("span").attr("class","name").html(function(d){
      return d.field_name;
    });

    // -----  Assume User Selection here -----

    // 0:O "Aircraft: Airline/Operator"
    // 1:O "Aircraft: Make/Model"
    // 2:O "Airport: Name"
    // 3:Q "Cost: Other"
    // 4:Q "Cost: Repair"
    // 5:Q "Cost: Total $"
    // 6:O "Effect: Amount of damage"
    // 7:T "Flight Date"
    // 8:# "Number of Strikes"
    // 9:G "Origin State"
    // 10:Q "Speed (IAS) in knots"
    // 11:O "When: Phase of flight"
    // 12:O "When: Time of day"
    // 13:O "Wildlife: Size"
    // 14:O "Wildlife: Species"

    // var colIndicesSet = [
    //   [6,5,4], //CxQxQ -- good except some bar + size
    //   [6,11,5], //CxCxQ
    //   [6,8], //Cx#
    //   [2,3], //C(Big)xQ
    //   [6, 10], //CxQ
    //   [6,8,5], //Cx#xG
    //   [10], //Q
    //   // [4,5], //QxQ
    //   // [7,8], //Dx#
    //   // [11,12,13], //OxOxO //FIXME
    //   //// [6,5,10] //CxQxQ //TODO: speed might be problematic
    // ];

    // var control = d3.select("#control");

    // var dsel = control.append("select")
    //   .attr("class", "data")
    //   .style("width", "300px")
    //   .on("change", function(){
    //     var index = this.options[this.selectedIndex].value;
    //     render(colIndicesSet[index])
    //   })
    //   .selectAll("option").data(colIndicesSet)
    //   .enter().append("option")
    //     .attr("value", function(d, i){ return i;})
    //     .attr("selected", function(d,i){ return i==0? true : undefined;})
    //     .text(function(d, i){ return getTitle(d);});

    // render(colIndicesSet[0])
  }

  function fieldDetailHtml(v, type){
    return "" +
      "" +
      (v.aggr ? v.aggr : "") +
      (v.bin ? " bin " : "") +
      "" +
      "" +
      (v.name || "") +
      "" +
      " ("+ (type || v.type) + ")";
  }

  function encodingDetails(enc, div){
    div.append("div").html("marktype: "+enc.marktype()+"");
    enc.forEach(function(k, v){
      div.append("div").html(k+": "+fieldDetailHtml(v, vl.dataTypeNames[v.type]))
    });
  }

  function getTitle(colIndices){
    var cols = colIndices.map(function(i){ return schema[i];});

    return cols.map(function(col){
      return col['field_name'] + " [" + col['data_type'][0] +"]";
    }).join(",");
  }

  function getChartsByFieldSet(fields) {
    var aggr = vgn.genAggregate([], fields);
    var chartsByFieldset = aggr.map(function (fields) {
      var encodings = vgn.generateCharts(fields,
        {
          genAggr: false
        },
        {
          dataUrl: "data/birdstrikes.json",
          viewport: [460, 460]
        },
        true
      ).map(function (e) { //add score
          var score = visrank.encodingScore(e);
          e.score = score.score;
          e.scoreFeatures = score.features;
          return e;
        });

      var diff = vgn.getDistanceTable(encodings),
        clusters = vgn.cluster(encodings, 2.5)
          .map(function (cluster) {
            return cluster.sort(function (i, j) {
              return encodings[j].score - encodings[i].score;
            });
          })
          .sort(function (c1, c2) {
            return encodings[c2[0]].score - encodings[c1[0]].score;
          });

      //console.log("clusters", clusters);

      return {
        fields: fields,
        encodings: encodings,
        diff: diff,
        clusters: clusters
      };

    })
    return chartsByFieldset;
  }

  function renderMain(selectedColIndices){
    if(selectedColIndices.length === 0) return;

    var selectedCols = selectedColIndices.map(function(i){ return schema[i];}),
      selectedColNames = _.pluck(selectedCols, 'field_name'),
      selectedColTypes = _.pluck(selectedCols, 'data_type');

    // ----- Generate Charts -----
    //TODO(kanitw): change schema format to match
    var fields = selectedCols.map(function(col){
      if(col.data_type == "count"){
        return {aggr: "count", type:"Q"};
      }
      var type = getVLType(col.data_type), f;
      switch(type){

        case "Q":
          f = {name: col.key, type: "Q", _aggr:"*"}
          return f;
        case "O":
        default:
          return {name: col.key, type:"O"};
      }
    });

    console.log('fields', JSON.stringify(fields));

    var chartsByFieldSet = getChartsByFieldSet(fields);

    d3.select("#aggr").selectAll("*").remove();
    d3.select("#vis").selectAll("*").remove();
    d3.select("#selected-fields").selectAll("*").remove();

    var aggrTable = d3.select("#aggr").selectAll("div.fieldset");

    var enter = aggrTable.data(chartsByFieldSet).enter()
      .append("div").attr("class", "fieldset");

    // data fields
    enter.append("div").attr("class", "datafields")
      .selectAll("div.datafield").data(function(d){return d.fields;})
      .enter().append("div").attr("class", "datafield")
      .html(fieldDetailHtml);

    // top vis
    enter.append("div").attr("class","topvis")
      .each(renderTopVis);

    enter.append("div").attr("class", "select")
      .append("a").attr("href","#").text("expand")
        .on('click', function(d){
          renderEncodingVariations(d)
        });

    // console.log("chartsByFieldset", chartsByFieldset);
    // chartsByFieldset.forEach(renderCharts);
  }

  var topVisId = 0; //HACK

  function renderTopVis(charts){
    var container = d3.select(this),
      clusters = charts.clusters,
      encodings = charts.encodings;

    if(clusters.length == 0 || clusters[0].length===0) return;

    var id = "topvis-" + (topVisId++);

    var topIdx = clusters[0][0],
      encoding = vl.Encoding.parseJSON(encodings[topIdx]),
      spec = vl.toVegaSpec(encoding, data);

    appendVis(container, encoding, spec, id);
  }

  function appendVis(container, encoding, spec, id){
    container.append("div").attr("id", id)
      .style({
        "height": Math.min(+spec.height + HEIGHT_OFFSET, MAX_HEIGHT) + "px",
        "max-width": MAX_WIDTH+"px",
        "overflow": "scroll"
      });

    if (spec){
      vg.parse.spec(spec, function (vgChart) {
        var vis = vgChart({el: '#' + id});
        vis.update();
      });
    }

    container.append("input").attr({"readonly":1, value: encoding.toShorthand(), class:"shorthand"})
      .style("font-size", "12px");
  }

  function renderEncodingVariations(charts, groupId) {
    var encodings = charts.encodings,
      diff = charts.diff,
      clusters = charts.clusters;

    var dataFields = d3.select("#selected-fields"),
      content = d3.select("#vis");

    content.selectAll("*").remove();
    dataFields.selectAll("*").remove();

    dataFields.selectAll("div.datafield").data(charts.fields)
      .enter().append("div").attr("class", "datafield")
      .html(fieldDetailHtml);

    var visIdCounter=0;

    if(CONFIG.showTable){
      renderDistanceTable(content, diff);
    }

    clusters.forEach(function (clusterIndices) {
      var cluster = clusterIndices.map(function (i) {
        var e = encodings[i],
          encoding = vl.Encoding.parseJSON(e),
          spec = vl.toVegaSpec(encoding, data);
        return {
          encodingJson: e,
          encoding: encoding,
          spec: spec,
          i: i
        };
      });

      var clusterHeight = cluster.reduce(function (h, c) {
        var nh = +c.spec.height + HEIGHT_OFFSET + 120;
        return nh > h ? nh : h;
      }, 0)

      var chartGroupDiv = content.append("div")
        .attr("id", "group")
        .attr("class", "row")
        .style({
          "background-color": "#fcfcfc",
          "overflow-x": "scroll",
          "overflow-y": "hidden",
          "margin-bottom": "20px",
          "white-space": "nowrap",
          "height": clusterHeight + "px"
        });

      cluster.forEach(function (o, i) {
        if(CONFIG.showOnlyClusterTop && i>0) return;
        // console.log('chart', chart, chart.toShorthand());
        var encodingJson = o.encodingJson,
          i = o.i,
          id = 'vis-' + groupId + "-" + (visIdCounter++),
          encoding = o.encoding,
          spec = o.spec;

        var chartDiv = chartGroupDiv.append("div")
          .style({
            "display": "inline-block",
            "margin-right": "10px",
            "vertical-align": "top"
          })
        var detail = chartDiv.append("div").text("id:"+i+", score:"+encodingJson.score).append("div");
        encodingDetails(encoding, detail);

        appendVis(chartDiv, encoding, spec, id);
      });
    })
  }

  function renderDistanceTable(content, diff) {
    var table = content.append("table");
    var headerRow = table.append("tr").attr("class", "header-row");
    headerRow.append("th");
    headerRow.selectAll("th.item-col").data(diff)
      .enter().append("th").attr("class", "item-col")
      .append("b").text(function (d, i) {
        return "" + i;
      });

    var rows = table.selectAll("tr.item-row")
      .data(diff)
      .enter().append("tr").attr("class", "item-row");

    rows.append("td").append("b").text(function (d, i) {
      return i;
    });
    rows.selectAll("td.item-cell")
      .data(_.identity)
      .enter().append("td").attr("class", "item-cell")
      .style("text-align", "center")
      .style("border", "1px solid #ddd")
      .text(function (d) {
        return d ? d3.format('.2')(d) : "-";
      });
  }

  loadSchema();
}));<commit_msg>fix group header bug<commit_after>// Define module using Universal Module Definition pattern
// https://github.com/umdjs/umd/blob/master/returnExports.js

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['d3', 'vega', 'vegalite', 'lodash', 'visgen', 'visrank'],factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(
      require('d3'),
      require('vega'),
      require('vegalite'),
      require('lodash'),
      require('visgen'),
      require('visrank')
    );
  } else {
    // Browser globals (root is window)
    factory(root.d3, root.vg, root.vl, root._, root.vgn, root.visrank);
  }
}(this, function(d3, vg, vl, _, vgn, visrank){
  var schema, col_indices;

  var HEIGHT_OFFSET = 60, MAX_HEIGHT = 500, MAX_WIDTH = 500;

  var CONFIG = {
    showTable: false,

    genAggr: true,
    genBin: true,
    genTypeCasting: true,

    omitTranpose: true,
    omitDotPlotWithExtraEncoding: true,
    omitAggrWithAllDimsOnFacets: true
  }

  var keys = vg.keys;

  function getVLType(data_type){
    // return vegalite's data type
    var typeMap = {
      "categorical": "O",
      "geographic": "G",
      "quantitative": "Q",
      "datetime": "T",
      "count": "Q"
    };
    return typeMap[data_type];
  }

  // ----- load schema -----
  function loadSchema(){
    //TODO: use amd-plugin to load json, csv
    d3.json("data/birdstrikes/birdstrikes-schema.json", function(_schema) {
      //TODO: remove this line after updating csv.
      schema = _(_schema).filter(function(d){ return !d.disabled;})
        .sortBy('field_name')
        .sortBy(function(col){
          return getVLType(col.data_type) !== "Q" ? 0 :
            col.data_type === "count" ? 2 : 1 ;
        })
        .map(function(col, i){
          col.key = col['field_name'].replace(/(: )/g, "__").replace(/[\/ ]/g,"_").replace(/[()]/g, "");
          col.index = i; //add index
          return col;
        })
        .value();

      col_indices = _.reduce(schema, function(result, col, i){ result[col] = i; return result;}, {});

      console.log('schema keys', _.pluck(schema,'key').sort());
      console.log('data_types', _(schema).pluck('data_type').uniq().value());
      loadData();
    });
  }

  function updateSelectedFields(){
    var selectedColIndices = [];

    d3.selectAll("#datacols input.datacol").each(function(d, i){
      var selected = d3.select(this).node().checked;
      if(selected){
        selectedColIndices.push(d.index);
      }
    });

    renderMain(selectedColIndices);
  }

  function loadData(){
    // TODO: use other lib to load csv as columns?
    // TODO: regenerate csv with all columns
    d3.json("data/birdstrikes.json", function(data) {
      self.data = data;
      console.log("keys", vg.keys(data[0]));
      init();
    });
  }

  function init(){
    var datacols = d3.select("#datacols").selectAll("div")
      .data(schema).enter().append("div").append("label");

    datacols.append("input").attr("type","checkbox").attr("class","datacol")
      .on("change", updateSelectedFields);

    datacols.append("span").attr("class","type").text(function(d){
      return "["+getVLType(d.data_type)+"] ";
    });

    datacols.append("span").attr("class","name").html(function(d){
      return d.field_name;
    });

    // -----  Assume User Selection here -----

    // 0:O "Aircraft: Airline/Operator"
    // 1:O "Aircraft: Make/Model"
    // 2:O "Airport: Name"
    // 3:Q "Cost: Other"
    // 4:Q "Cost: Repair"
    // 5:Q "Cost: Total $"
    // 6:O "Effect: Amount of damage"
    // 7:T "Flight Date"
    // 8:# "Number of Strikes"
    // 9:G "Origin State"
    // 10:Q "Speed (IAS) in knots"
    // 11:O "When: Phase of flight"
    // 12:O "When: Time of day"
    // 13:O "Wildlife: Size"
    // 14:O "Wildlife: Species"

    // var colIndicesSet = [
    //   [6,5,4], //CxQxQ -- good except some bar + size
    //   [6,11,5], //CxCxQ
    //   [6,8], //Cx#
    //   [2,3], //C(Big)xQ
    //   [6, 10], //CxQ
    //   [6,8,5], //Cx#xG
    //   [10], //Q
    //   // [4,5], //QxQ
    //   // [7,8], //Dx#
    //   // [11,12,13], //OxOxO //FIXME
    //   //// [6,5,10] //CxQxQ //TODO: speed might be problematic
    // ];

    // var control = d3.select("#control");

    // var dsel = control.append("select")
    //   .attr("class", "data")
    //   .style("width", "300px")
    //   .on("change", function(){
    //     var index = this.options[this.selectedIndex].value;
    //     render(colIndicesSet[index])
    //   })
    //   .selectAll("option").data(colIndicesSet)
    //   .enter().append("option")
    //     .attr("value", function(d, i){ return i;})
    //     .attr("selected", function(d,i){ return i==0? true : undefined;})
    //     .text(function(d, i){ return getTitle(d);});

    // render(colIndicesSet[0])
  }

  function fieldDetailHtml(v){
    return "" +
      "" +
      (v.aggr ? v.aggr : "") +
      (v.bin ? " bin " : "") +
      "" +
      "" +
      (v.name || "") +
      "" +
      " ("+ v.type + ")";
  }

  function encodingDetails(enc, div){
    div.append("div").html("marktype: "+enc.marktype()+"");
    enc.forEach(function(k, v){
      div.append("div").html(k+": "+fieldDetailHtml(v, vl.dataTypeNames[v.type]))
    });
  }

  function getTitle(colIndices){
    var cols = colIndices.map(function(i){ return schema[i];});

    return cols.map(function(col){
      return col['field_name'] + " [" + col['data_type'][0] +"]";
    }).join(",");
  }

  function getChartsByFieldSet(fields) {
    var aggr = vgn.genAggregate([], fields);
    var chartsByFieldset = aggr.map(function (fields) {
      var encodings = vgn.generateCharts(fields,
        {
          genAggr: false
        },
        {
          dataUrl: "data/birdstrikes.json",
          viewport: [460, 460]
        },
        true
      ).map(function (e) { //add score
          var score = visrank.encodingScore(e);
          e.score = score.score;
          e.scoreFeatures = score.features;
          return e;
        });

      var diff = vgn.getDistanceTable(encodings),
        clusters = vgn.cluster(encodings, 2.5)
          .map(function (cluster) {
            return cluster.sort(function (i, j) {
              return encodings[j].score - encodings[i].score;
            });
          })
          .sort(function (c1, c2) {
            return encodings[c2[0]].score - encodings[c1[0]].score;
          });

      //console.log("clusters", clusters);

      return {
        fields: fields,
        encodings: encodings,
        diff: diff,
        clusters: clusters
      };

    })
    return chartsByFieldset;
  }

  function renderMain(selectedColIndices){
    if(selectedColIndices.length === 0) return;

    var selectedCols = selectedColIndices.map(function(i){ return schema[i];}),
      selectedColNames = _.pluck(selectedCols, 'field_name'),
      selectedColTypes = _.pluck(selectedCols, 'data_type');

    // ----- Generate Charts -----
    //TODO(kanitw): change schema format to match
    var fields = selectedCols.map(function(col){
      if(col.data_type == "count"){
        return {aggr: "count", type:"Q"};
      }
      var type = getVLType(col.data_type), f;
      switch(type){

        case "Q":
          f = {name: col.key, type: "Q", _aggr:"*"}
          return f;
        case "O":
        default:
          return {name: col.key, type:"O"};
      }
    });

    console.log('fields', JSON.stringify(fields));

    var chartsByFieldSet = getChartsByFieldSet(fields);

    d3.select("#aggr").selectAll("*").remove();
    d3.select("#vis").selectAll("*").remove();
    d3.select("#selected-fields").selectAll("*").remove();

    var aggrTable = d3.select("#aggr").selectAll("div.fieldset");

    var enter = aggrTable.data(chartsByFieldSet).enter()
      .append("div").attr("class", "fieldset");

    // data fields
    enter.append("div").attr("class", "datafields")
      .selectAll("div.datafield").data(function(d){return d.fields;})
      .enter().append("div").attr("class", "datafield")
      .html(fieldDetailHtml);

    // top vis
    enter.append("div").attr("class","topvis")
      .each(renderTopVis);

    enter.append("div").attr("class", "select")
      .append("a").attr("href","#").text("expand")
        .on('click', function(d){
          renderEncodingVariations(d)
        });

    // console.log("chartsByFieldset", chartsByFieldset);
    // chartsByFieldset.forEach(renderCharts);
  }

  var topVisId = 0; //HACK

  function renderTopVis(charts){
    var container = d3.select(this),
      clusters = charts.clusters,
      encodings = charts.encodings;

    if(clusters.length == 0 || clusters[0].length===0) return;

    var id = "topvis-" + (topVisId++);

    var topIdx = clusters[0][0],
      encoding = vl.Encoding.parseJSON(encodings[topIdx]),
      spec = vl.toVegaSpec(encoding, data);

    appendVis(container, encoding, spec, id);
  }

  function appendVis(container, encoding, spec, id){
    container.append("div").attr("id", id)
      .style({
        "height": Math.min(+spec.height + HEIGHT_OFFSET, MAX_HEIGHT) + "px",
        "max-width": MAX_WIDTH+"px",
        "overflow": "scroll"
      });

    if (spec){
      vg.parse.spec(spec, function (vgChart) {
        var vis = vgChart({el: '#' + id});
        vis.update();
      });
    }

    container.append("input").attr({"readonly":1, value: encoding.toShorthand(), class:"shorthand"})
      .style("font-size", "12px");
  }

  function renderEncodingVariations(charts, groupId) {
    var encodings = charts.encodings,
      diff = charts.diff,
      clusters = charts.clusters;

    var dataFields = d3.select("#selected-fields"),
      content = d3.select("#vis");

    content.selectAll("*").remove();
    dataFields.selectAll("*").remove();

    dataFields.selectAll("div.datafield").data(charts.fields)
      .enter().append("div").attr("class", "datafield")
      .html(fieldDetailHtml);

    var visIdCounter=0;

    if(CONFIG.showTable){
      renderDistanceTable(content, diff);
    }

    clusters.forEach(function (clusterIndices) {
      var cluster = clusterIndices.map(function (i) {
        var e = encodings[i],
          encoding = vl.Encoding.parseJSON(e),
          spec = vl.toVegaSpec(encoding, data);
        return {
          encodingJson: e,
          encoding: encoding,
          spec: spec,
          i: i
        };
      });

      var clusterHeight = cluster.reduce(function (h, c) {
        var nh = +c.spec.height + HEIGHT_OFFSET + 120;
        return nh > h ? nh : h;
      }, 0)

      var chartGroupDiv = content.append("div")
        .attr("id", "group")
        .attr("class", "row")
        .style({
          "background-color": "#fcfcfc",
          "overflow-x": "scroll",
          "overflow-y": "hidden",
          "margin-bottom": "20px",
          "white-space": "nowrap",
          "height": clusterHeight + "px"
        });

      cluster.forEach(function (o, i) {
        if(CONFIG.showOnlyClusterTop && i>0) return;
        // console.log('chart', chart, chart.toShorthand());
        var encodingJson = o.encodingJson,
          i = o.i,
          id = 'vis-' + groupId + "-" + (visIdCounter++),
          encoding = o.encoding,
          spec = o.spec;

        var chartDiv = chartGroupDiv.append("div")
          .style({
            "display": "inline-block",
            "margin-right": "10px",
            "vertical-align": "top"
          })
        var detail = chartDiv.append("div").text("id:"+i+", score:"+encodingJson.score).append("div");
        encodingDetails(encoding, detail);

        appendVis(chartDiv, encoding, spec, id);
      });
    })
  }

  function renderDistanceTable(content, diff) {
    var table = content.append("table");
    var headerRow = table.append("tr").attr("class", "header-row");
    headerRow.append("th");
    headerRow.selectAll("th.item-col").data(diff)
      .enter().append("th").attr("class", "item-col")
      .append("b").text(function (d, i) {
        return "" + i;
      });

    var rows = table.selectAll("tr.item-row")
      .data(diff)
      .enter().append("tr").attr("class", "item-row");

    rows.append("td").append("b").text(function (d, i) {
      return i;
    });
    rows.selectAll("td.item-cell")
      .data(_.identity)
      .enter().append("td").attr("class", "item-cell")
      .style("text-align", "center")
      .style("border", "1px solid #ddd")
      .text(function (d) {
        return d ? d3.format('.2')(d) : "-";
      });
  }

  loadSchema();
}));<|endoftext|>


<commit_before>var mathf = require("mathf"),
    vec3 = require("vec3"),
    vec4 = require("vec4"),
    isNumber = require("is_number");

var color = exports;

color.ArrayType = typeof(Float32Array) !== "undefined" ? Float32Array : mathf.ArrayType;

color.create = function(r, g, b, a) {
    var out = new color.ArrayType(4);

    out[0] = r !== undefined ? r : 0;
    out[1] = g !== undefined ? g : 0;
    out[2] = b !== undefined ? b : 0;
    out[3] = a !== undefined ? a : 1;

    return out;
};

color.copy = vec4.copy;

color.clone = function(a) {
    var out = new color.ArrayType(4);

    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];

    return out;
};

color.setRGB = vec3.set;
color.setRGBA = vec4.set;

color.add = vec4.add;
color.sub = vec4.sub;

color.mul = vec4.mul;
color.div = vec4.div;

color.sadd = vec4.sadd;
color.ssub = vec4.ssub;

color.smul = vec4.smul;
color.sdiv = vec4.sdiv;

color.lengthSqValues = vec4.lengthSqValues;
color.lengthValues = vec4.lengthValues;
color.invLengthValues = vec4.invLengthValues;

color.dot = vec4.dot;

color.lengthSq = vec4.lengthSq;

color.length = vec4.length;

color.invLength = vec4.invLength;

color.setLength = vec4.setLength;

color.normalize = vec4.normalize;

color.lerp = vec4.lerp;

color.min = vec4.min;

color.max = vec4.max;

color.clamp = vec4.clamp;

color.equal = vec4.equal;

color.notEqual = vec4.notEqual;

var cmin = color.create(0, 0, 0, 0),
    cmax = color.create(1, 1, 1, 1);

color.cnormalize = function(out) {
    return color.clamp(out, out, cmin, cmax);
};

color.str = function(out) {
    return "Color(" + out[0] + ", " + out[1] + ", " + out[2] + ", " + out[3] + ")";
};

color.set = function(out, r, g, b) {
    var type = typeof(r);

    if (type === "number") {
        out[0] = r !== undefined ? r : 0;
        out[1] = g !== undefined ? g : 0;
        out[2] = b !== undefined ? b : 0;
    } else if (type === "string") {
        color.setStyle(out, r);
    } else if (r.length === +r.length) {
        out[0] = r[0] || 0;
        out[1] = r[1] || 0;
        out[2] = r[2] || 0;
    }

    return out;
};

function to256(value) {
    return (value * 255) | 0;
}

color.toRGB = function(out, alpha) {
    if (isNumber(alpha)) {
        return "rgba(" + to256(out[0]) + "," + to256(out[1]) + "," + to256(out[2]) + "," + mathf.clamp01(alpha) + ")";
    } else {
        return "rgb(" + to256(out[0]) + "," + to256(out[1]) + "," + to256(out[2]) + ")";
    }
};

color.toRGBA = function(out) {
    return "rgba(" + to256(out[0]) + "," + to256(out[1]) + "," + to256(out[2]) + "," + mathf.clamp01(out[3]) + ")";
};

function toHEX(value) {
    if (value < 16) {
        return "0" + value.toString(16);
    } else {
        return value.toString(16);
    }
}

color.toHEX = function(out) {
    return "#" + toHEX(out[0]) + toHEX(out[1]) + toHEX(out[2]);
};

var rgb255 = /^rgb\((\d+),(\s+)?(\d+),(\s+)?(\d+)\)$/i,
    inv255 = 1 / 255;
color.fromRGB = function(out, style) {
    var values = rgb255.exec(style);
    out[0] = mathf.min(255, Number(values[1])) * inv255;
    out[1] = mathf.min(255, Number(values[2])) * inv255;
    out[2] = mathf.min(255, Number(values[3])) * inv255;
    return out;
};

var rgba255 = /^rgba\((\d+),(\s+)?(\d+),(\s+)?(\d+),(\s+)?(\d+)\)$/i;
color.fromRGBA = function(out, style) {
    var values = rgba255.exec(style);
    out[0] = mathf.min(255, Number(values[1])) * inv255;
    out[1] = mathf.min(255, Number(values[2])) * inv255;
    out[2] = mathf.min(255, Number(values[3])) * inv255;
    out[3] = mathf.min(1, Number(values[4]));
    return out;
};

var rgb100 = /^rgb\((\d+)\%,(\s+)?(\d+)\%,(\s+)?(\d+)\%\)$/i,
    inv100 = 1 / 100;
color.fromRGB100 = function(out, style) {
    var values = rgb100.exec(style);
    out[0] = mathf.min(100, Number(values[1])) * inv100;
    out[1] = mathf.min(100, Number(values[2])) * inv100;
    out[2] = mathf.min(100, Number(values[3])) * inv100;
    return out;
};

color.fromHEX = function(out, style) {
    out[0] = parseInt(style.substr(1, 2), 16) * inv255;
    out[1] = parseInt(style.substr(3, 2), 16) * inv255;
    out[2] = parseInt(style.substr(5, 2), 16) * inv255;
    return out;
};

var hex3to6 = /#(.)(.)(.)/,
    hex3to6String = "#$1$1$2$2$3$3";
color.fromHEX3 = function(out, style) {
    style = style.replace(hex3to6, hex3to6String);
    out[0] = parseInt(style.substr(1, 2), 16) * inv255;
    out[1] = parseInt(style.substr(3, 2), 16) * inv255;
    out[2] = parseInt(style.substr(5, 2), 16) * inv255;
    return out;
};

color.fromColorName = function(out, style) {
    return color.fromHEX(out, colorNames[style.toLowerCase()]);
};

var hex6 = /^\#([0.0-9a-f]{6})$/i,
    hex3 = /^\#([0.0-9a-f])([0.0-9a-f])([0.0-9a-f])$/i,
    colorName = /^(\w+)$/i;
color.setStyle = function(out, style) {
    if (rgb255.test(style)) {
        return color.fromRGB(out, style);
    } else if (rgb100.test(style)) {
        return color.fromRGB100(out, style);
    } else if (hex6.test(style)) {
        return color.fromHEX(out, style);
    } else if (hex3.test(style)) {
        return color.fromHEX3(out, style);
    } else if (colorName.test(style)) {
        return color.fromColorName(out, style);
    } else {
        return out;
    }
};

var colorNames = color.colorNames = {
    aliceblue: "#f0f8ff",
    antiquewhite: "#faebd7",
    aqua: "#00ffff",
    aquamarine: "#7fffd4",
    azure: "#f0ffff",
    beige: "#f5f5dc",
    bisque: "#ffe4c4",
    black: "#000000",
    blanchedalmond: "#ffebcd",
    blue: "#0000ff",
    blueviolet: "#8a2be2",
    brown: "#a52a2a",
    burlywood: "#deb887",
    cadetblue: "#5f9ea0",
    chartreuse: "#7fff00",
    chocolate: "#d2691e",
    coral: "#ff7f50",
    cornflowerblue: "#6495ed",
    cornsilk: "#fff8dc",
    crimson: "#dc143c",
    cyan: "#00ffff",
    darkblue: "#00008b",
    darkcyan: "#008b8b",
    darkgoldenrod: "#b8860b",
    darkgray: "#a9a9a9",
    darkgreen: "#006400",
    darkkhaki: "#bdb76b",
    darkmagenta: "#8b008b",
    darkolivegreen: "#556b2f",
    darkorange: "#ff8c00",
    darkorchid: "#9932cc",
    darkred: "#8b0000",
    darksalmon: "#e9967a",
    darkseagreen: "#8fbc8f",
    darkslateblue: "#483d8b",
    darkslategray: "#2f4f4f",
    darkturquoise: "#00ced1",
    darkviolet: "#9400d3",
    deeppink: "#ff1493",
    deepskyblue: "#00bfff",
    dimgray: "#696969",
    dodgerblue: "#1e90ff",
    firebrick: "#b22222",
    floralwhite: "#fffaf0",
    forestgreen: "#228b22",
    fuchsia: "#ff00ff",
    gainsboro: "#dcdcdc",
    ghostwhite: "#f8f8ff",
    gold: "#ffd700",
    goldenrod: "#daa520",
    gray: "#808080",
    green: "#008000",
    greenyellow: "#adff2f",
    grey: "#808080",
    honeydew: "#f0fff0",
    hotpink: "#ff69b4",
    indianred: "#cd5c5c",
    indigo: "#4b0082",
    ivory: "#fffff0",
    khaki: "#f0e68c",
    lavender: "#e6e6fa",
    lavenderblush: "#fff0f5",
    lawngreen: "#7cfc00",
    lemonchiffon: "#fffacd",
    lightblue: "#add8e6",
    lightcoral: "#f08080",
    lightcyan: "#e0ffff",
    lightgoldenrodyellow: "#fafad2",
    lightgrey: "#d3d3d3",
    lightgreen: "#90ee90",
    lightpink: "#ffb6c1",
    lightsalmon: "#ffa07a",
    lightseagreen: "#20b2aa",
    lightskyblue: "#87cefa",
    lightslategray: "#778899",
    lightsteelblue: "#b0c4de",
    lightyellow: "#ffffe0",
    lime: "#00ff00",
    limegreen: "#32cd32",
    linen: "#faf0e6",
    magenta: "#ff00ff",
    maroon: "#800000",
    mediumaquamarine: "#66cdaa",
    mediumblue: "#0000cd",
    mediumorchid: "#ba55d3",
    mediumpurple: "#9370d8",
    mediumseagreen: "#3cb371",
    mediumslateblue: "#7b68ee",
    mediumspringgreen: "#00fa9a",
    mediumturquoise: "#48d1cc",
    mediumvioletred: "#c71585",
    midnightblue: "#191970",
    mintcream: "#f5fffa",
    mistyrose: "#ffe4e1",
    moccasin: "#ffe4b5",
    navajowhite: "#ffdead",
    navy: "#000080",
    oldlace: "#fdf5e6",
    olive: "#808000",
    olivedrab: "#6b8e23",
    orange: "#ffa500",
    orangered: "#ff4500",
    orchid: "#da70d6",
    palegoldenrod: "#eee8aa",
    palegreen: "#98fb98",
    paleturquoise: "#afeeee",
    palevioletred: "#d87093",
    papayawhip: "#ffefd5",
    peachpuff: "#ffdab9",
    peru: "#cd853f",
    pink: "#ffc0cb",
    plum: "#dda0dd",
    powderblue: "#b0e0e6",
    purple: "#800080",
    red: "#ff0000",
    rosybrown: "#bc8f8f",
    royalblue: "#4169e1",
    saddlebrown: "#8b4513",
    salmon: "#fa8072",
    sandybrown: "#f4a460",
    seagreen: "#2e8b57",
    seashell: "#fff5ee",
    sienna: "#a0522d",
    silver: "#c0c0c0",
    skyblue: "#87ceeb",
    slateblue: "#6a5acd",
    slategray: "#708090",
    snow: "#fffafa",
    springgreen: "#00ff7f",
    steelblue: "#4682b4",
    tan: "#d2b48c",
    teal: "#008080",
    thistle: "#d8bfd8",
    tomato: "#ff6347",
    turquoise: "#40e0d0",
    violet: "#ee82ee",
    wheat: "#f5deb3",
    white: "#ffffff",
    whitesmoke: "#f5f5f5",
    yellow: "#ffff00",
    yellowgreen: "#9acd32"
};
<commit_msg>updates<commit_after>var mathf = require("mathf"),
    vec3 = require("vec3"),
    vec4 = require("vec4"),
    isNumber = require("is_number");

var color = exports;

color.ArrayType = typeof(Float32Array) !== "undefined" ? Float32Array : mathf.ArrayType;

color.create = function(r, g, b, a) {
    var out = new color.ArrayType(4);

    out[0] = r !== undefined ? r : 0;
    out[1] = g !== undefined ? g : 0;
    out[2] = b !== undefined ? b : 0;
    out[3] = a !== undefined ? a : 1;

    return out;
};

color.copy = vec4.copy;

color.clone = function(a) {
    var out = new color.ArrayType(4);

    out[0] = a[0];
    out[1] = a[1];
    out[2] = a[2];
    out[3] = a[3];

    return out;
};

color.setRGB = vec3.set;
color.setRGBA = vec4.set;

color.add = vec4.add;
color.sub = vec4.sub;

color.mul = vec4.mul;
color.div = vec4.div;

color.sadd = vec4.sadd;
color.ssub = vec4.ssub;

color.smul = vec4.smul;
color.sdiv = vec4.sdiv;

color.lengthSqValues = vec4.lengthSqValues;
color.lengthValues = vec4.lengthValues;
color.invLengthValues = vec4.invLengthValues;

color.dot = vec4.dot;

color.lengthSq = vec4.lengthSq;

color.length = vec4.length;

color.invLength = vec4.invLength;

color.setLength = vec4.setLength;

color.normalize = vec4.normalize;

color.lerp = vec4.lerp;

color.min = vec4.min;

color.max = vec4.max;

color.clamp = vec4.clamp;

color.equal = vec4.equal;

color.notEqual = vec4.notEqual;

var cmin = color.create(0, 0, 0, 0),
    cmax = color.create(1, 1, 1, 1);

color.cnormalize = function(out) {
    return color.clamp(out, out, cmin, cmax);
};

color.str = function(out) {
    return "Color(" + out[0] + ", " + out[1] + ", " + out[2] + ", " + out[3] + ")";
};

color.set = function(out, r, g, b) {
    var type = typeof(r);

    if (type === "number") {
        out[0] = r !== undefined ? r : 0;
        out[1] = g !== undefined ? g : 0;
        out[2] = b !== undefined ? b : 0;
    } else if (type === "string") {
        color.setStyle(out, r);
    } else if (r.length === +r.length) {
        out[0] = r[0] || 0;
        out[1] = r[1] || 0;
        out[2] = r[2] || 0;
    }

    return out;
};

function to256(value) {
    return (value * 255) | 0;
}

color.toRGB = function(out, alpha) {
    if (isNumber(alpha)) {
        return "rgba(" + to256(out[0]) + "," + to256(out[1]) + "," + to256(out[2]) + "," + mathf.clamp01(alpha) + ")";
    } else {
        return "rgb(" + to256(out[0]) + "," + to256(out[1]) + "," + to256(out[2]) + ")";
    }
};

color.toRGBA = function(out) {
    return "rgba(" + to256(out[0]) + "," + to256(out[1]) + "," + to256(out[2]) + "," + mathf.clamp01(out[3]) + ")";
};

function toHEX(value) {
    if (value < 16) {
        return "0" + value.toString(16);
    } else {
        return value.toString(16);
    }
}

color.toHEX = function(out) {
    return "#" + toHEX(out[0]) + toHEX(out[1]) + toHEX(out[2]);
};

var rgb255 = /^rgb\((\d+),(\s+)?(\d+),(\s+)?(\d+)\)$/i,
    inv255 = 1 / 255;
color.fromRGB = function(out, style) {
    var values = rgb255.exec(style);
    out[0] = mathf.min(255, Number(values[1])) * inv255;
    out[1] = mathf.min(255, Number(values[2])) * inv255;
    out[2] = mathf.min(255, Number(values[3])) * inv255;
    return out;
};

var rgba255 = /^rgba\((\d+),(\s+)?(\d+),(\s+)?(\d+),(\s+)?(\d+)\)$/i;
color.fromRGBA = function(out, style) {
    var values = rgba255.exec(style);
    out[0] = mathf.min(255, Number(values[1])) * inv255;
    out[1] = mathf.min(255, Number(values[2])) * inv255;
    out[2] = mathf.min(255, Number(values[3])) * inv255;
    out[3] = mathf.min(1, Number(values[4]));
    return out;
};

var rgb100 = /^rgb\((\d+)\%,(\s+)?(\d+)\%,(\s+)?(\d+)\%\)$/i,
    inv100 = 1 / 100;
color.fromRGB100 = function(out, style) {
    var values = rgb100.exec(style);
    out[0] = mathf.min(100, Number(values[1])) * inv100;
    out[1] = mathf.min(100, Number(values[2])) * inv100;
    out[2] = mathf.min(100, Number(values[3])) * inv100;
    return out;
};

color.fromHEX = function(out, style) {
    out[0] = parseInt(style.substr(1, 2), 16) * inv255;
    out[1] = parseInt(style.substr(3, 2), 16) * inv255;
    out[2] = parseInt(style.substr(5, 2), 16) * inv255;
    return out;
};

var hex3to6 = /#(.)(.)(.)/,
    hex3to6String = "#$1$1$2$2$3$3";
color.fromHEX3 = function(out, style) {
    style = style.replace(hex3to6, hex3to6String);
    out[0] = parseInt(style.substr(1, 2), 16) * inv255;
    out[1] = parseInt(style.substr(3, 2), 16) * inv255;
    out[2] = parseInt(style.substr(5, 2), 16) * inv255;
    return out;
};

color.fromColorName = function(out, style) {
    return color.fromHEX(out, colorNames[style.toLowerCase()]);
};

var hex6 = /^\#([0.0-9a-f]{6})$/i,
    hex3 = /^\#([0.0-9a-f])([0.0-9a-f])([0.0-9a-f])$/i,
    colorName = /^(\w+)$/i;
color.fromStyle = function(out, style) {
    if (rgb255.test(style)) {
        return color.fromRGB(out, style);
    } else if (rgb100.test(style)) {
        return color.fromRGB100(out, style);
    } else if (hex6.test(style)) {
        return color.fromHEX(out, style);
    } else if (hex3.test(style)) {
        return color.fromHEX3(out, style);
    } else if (colorName.test(style)) {
        return color.fromColorName(out, style);
    } else {
        return out;
    }
};

var colorNames = color.colorNames = {
    aliceblue: "#f0f8ff",
    antiquewhite: "#faebd7",
    aqua: "#00ffff",
    aquamarine: "#7fffd4",
    azure: "#f0ffff",
    beige: "#f5f5dc",
    bisque: "#ffe4c4",
    black: "#000000",
    blanchedalmond: "#ffebcd",
    blue: "#0000ff",
    blueviolet: "#8a2be2",
    brown: "#a52a2a",
    burlywood: "#deb887",
    cadetblue: "#5f9ea0",
    chartreuse: "#7fff00",
    chocolate: "#d2691e",
    coral: "#ff7f50",
    cornflowerblue: "#6495ed",
    cornsilk: "#fff8dc",
    crimson: "#dc143c",
    cyan: "#00ffff",
    darkblue: "#00008b",
    darkcyan: "#008b8b",
    darkgoldenrod: "#b8860b",
    darkgray: "#a9a9a9",
    darkgreen: "#006400",
    darkkhaki: "#bdb76b",
    darkmagenta: "#8b008b",
    darkolivegreen: "#556b2f",
    darkorange: "#ff8c00",
    darkorchid: "#9932cc",
    darkred: "#8b0000",
    darksalmon: "#e9967a",
    darkseagreen: "#8fbc8f",
    darkslateblue: "#483d8b",
    darkslategray: "#2f4f4f",
    darkturquoise: "#00ced1",
    darkviolet: "#9400d3",
    deeppink: "#ff1493",
    deepskyblue: "#00bfff",
    dimgray: "#696969",
    dodgerblue: "#1e90ff",
    firebrick: "#b22222",
    floralwhite: "#fffaf0",
    forestgreen: "#228b22",
    fuchsia: "#ff00ff",
    gainsboro: "#dcdcdc",
    ghostwhite: "#f8f8ff",
    gold: "#ffd700",
    goldenrod: "#daa520",
    gray: "#808080",
    green: "#008000",
    greenyellow: "#adff2f",
    grey: "#808080",
    honeydew: "#f0fff0",
    hotpink: "#ff69b4",
    indianred: "#cd5c5c",
    indigo: "#4b0082",
    ivory: "#fffff0",
    khaki: "#f0e68c",
    lavender: "#e6e6fa",
    lavenderblush: "#fff0f5",
    lawngreen: "#7cfc00",
    lemonchiffon: "#fffacd",
    lightblue: "#add8e6",
    lightcoral: "#f08080",
    lightcyan: "#e0ffff",
    lightgoldenrodyellow: "#fafad2",
    lightgrey: "#d3d3d3",
    lightgreen: "#90ee90",
    lightpink: "#ffb6c1",
    lightsalmon: "#ffa07a",
    lightseagreen: "#20b2aa",
    lightskyblue: "#87cefa",
    lightslategray: "#778899",
    lightsteelblue: "#b0c4de",
    lightyellow: "#ffffe0",
    lime: "#00ff00",
    limegreen: "#32cd32",
    linen: "#faf0e6",
    magenta: "#ff00ff",
    maroon: "#800000",
    mediumaquamarine: "#66cdaa",
    mediumblue: "#0000cd",
    mediumorchid: "#ba55d3",
    mediumpurple: "#9370d8",
    mediumseagreen: "#3cb371",
    mediumslateblue: "#7b68ee",
    mediumspringgreen: "#00fa9a",
    mediumturquoise: "#48d1cc",
    mediumvioletred: "#c71585",
    midnightblue: "#191970",
    mintcream: "#f5fffa",
    mistyrose: "#ffe4e1",
    moccasin: "#ffe4b5",
    navajowhite: "#ffdead",
    navy: "#000080",
    oldlace: "#fdf5e6",
    olive: "#808000",
    olivedrab: "#6b8e23",
    orange: "#ffa500",
    orangered: "#ff4500",
    orchid: "#da70d6",
    palegoldenrod: "#eee8aa",
    palegreen: "#98fb98",
    paleturquoise: "#afeeee",
    palevioletred: "#d87093",
    papayawhip: "#ffefd5",
    peachpuff: "#ffdab9",
    peru: "#cd853f",
    pink: "#ffc0cb",
    plum: "#dda0dd",
    powderblue: "#b0e0e6",
    purple: "#800080",
    red: "#ff0000",
    rosybrown: "#bc8f8f",
    royalblue: "#4169e1",
    saddlebrown: "#8b4513",
    salmon: "#fa8072",
    sandybrown: "#f4a460",
    seagreen: "#2e8b57",
    seashell: "#fff5ee",
    sienna: "#a0522d",
    silver: "#c0c0c0",
    skyblue: "#87ceeb",
    slateblue: "#6a5acd",
    slategray: "#708090",
    snow: "#fffafa",
    springgreen: "#00ff7f",
    steelblue: "#4682b4",
    tan: "#d2b48c",
    teal: "#008080",
    thistle: "#d8bfd8",
    tomato: "#ff6347",
    turquoise: "#40e0d0",
    violet: "#ee82ee",
    wheat: "#f5deb3",
    white: "#ffffff",
    whitesmoke: "#f5f5f5",
    yellow: "#ffff00",
    yellowgreen: "#9acd32"
};
<|endoftext|>


<commit_before>import Koa from 'koa';
import Router from 'koa-router';
import { handle } from './controller';
import JsonBody from 'koa-json-body';
import ErrorMiddleware from './middleware/error';
import TokenMiddleware from './middleware/token';
import CorsMiddleware from '@koa/cors';
import setup from 'avanti-core/dist/setup';

setup().then(() => {
    const app = new Koa();
    const router = new Router();

    app.use(CorsMiddleware())
    app.use(ErrorMiddleware());
    app.use(TokenMiddleware());
    app.use(JsonBody({
        strict: true
    }));

    router.get('/client/list', handle('client@list'));
    router.post('/client/create', handle('client@create'));
    router.post('/client/remove', handle('client@remove'));

    router.get('/host/list', handle('host@list'));
    router.post('/host/info', handle('host@info'));
    router.post('/host/create', handle('host@create'));
    router.post('/host/remove', handle('host@remove'));
    router.post('/host/alias/create', handle('host@createAlias'));
    router.post('/host/alias/remove', handle('host@removeAlias'));
    router.post('/host/php', handle('host@php'));
    router.post('/host/refresh', handle('host@refresh'));
    router.post('/host/option', handle('host@setOption'));
    router.delete('/host/option', handle('host@removeOption'));

    app
        .use(router.routes())
        .use(router.allowedMethods());

    app.listen(3000);
});
<commit_msg>update routes to work properly<commit_after>import Koa from 'koa';
import Router from 'koa-router';
import { handle } from './controller';
import JsonBody from 'koa-json-body';
import ErrorMiddleware from './middleware/error';
import TokenMiddleware from './middleware/token';
import CorsMiddleware from '@koa/cors';
import setup from 'avanti-core/dist/setup';

setup().then(() => {
    const app = new Koa();
    const router = new Router();

    app.use(CorsMiddleware())
    app.use(ErrorMiddleware());
    app.use(TokenMiddleware());
    app.use(JsonBody({
        strict: true
    }));

    router.get('/client/list', handle('client@list'));
    router.post('/client/create', handle('client@create'));
    router.post('/client/remove', handle('client@remove'));

    router.get('/host/list', handle('host@list'));
    router.post('/host/info', handle('host@info'));
    router.post('/host/create', handle('host@create'));
    router.post('/host/remove', handle('host@remove'));
    router.post('/host/alias/create', handle('host@createAlias'));
    router.post('/host/alias/remove', handle('host@removeAlias'));
    router.post('/host/php', handle('host@php'));
    router.post('/host/refresh', handle('host@refresh'));
    router.post('/host/option/set', handle('host@setOption'));
    router.post('/host/option/remove', handle('host@removeOption'));

    app
        .use(router.routes())
        .use(router.allowedMethods());

    app.listen(3000);
});
<|endoftext|>