<commit_before>//	ryukyu.js JavaScript library
//	v 0.1.5
//	copyright July 2015 Dan McKeown
//      http://danmckeown.info/code/ryukyu
//	Released under MIT license:
//      https://github.com/pacificpelican/ryukyu/blob/master/LICENSE

"use strict";

var ryukyu_retArr = [];
var ryukyu_bigCount = 0;
var ryukyu_nodeRetObj = {};

                        //  class declarations require ES6/ES2015
var ryukyu_listItem = class linkedListItem {  // This class instantiates a single variable that contains an id, a value and a next reference
    constructor(place, next, value) {
        if (value === undefined) {
            this.value = null;
        }
        else {
            this.value = value;
        }
        this.id = place;  // Let place be undefined rather than null by default since it is the id and should have a value
        if (((next === undefined) || (next === "auto")) && (place != undefined)) {
            this.next = place+1;
        }
        else {
            this.next = next;
        }
    }
};

var ryukyu_list = class listNode {  //  This class generates a series of variables, each w/a next pointer to the next one's id
    constructor(theLength, baseName, defaultValue) {
        if (baseName === undefined) {
            console.log("basename automatically assigned as node");
            baseName = "node";
        }
        if (defaultValue === undefined) {
            console.log("setting default value to null");
            var defaultValue = null;
        }
        ryukyu_nodeRetObj = {}
        for (var i=1; i<theLength; i++) {
            var nodeName;
            nodeName = baseName + "_" + i;
            console.log("about to construct " + nodeName);
            var name0 = nodeName;
            window[name0] = new ryukyu_listItem(i, "auto", defaultValue);
            ryukyu_nodeRetObj[i] = window[name0];
        }
            var nodeName;
            var pos = i;
            nodeName = baseName + "_" + pos;
            console.log("about to construct " + nodeName);
            var name0 = nodeName;
            window[name0] = new ryukyu_listItem(pos, null, defaultValue);
            ryukyu_nodeRetObj[i] = window[name0];
            return ryukyu_nodeRetObj;
    }
}

function ryukyu_listToArray(head_id, nodeBaseName, arrName) { // This takes info about the head list variable, works along chain and returns an array
    if ((head_id === undefined) || (nodeBaseName === undefined)) {
        return false;
    }
    else {
        if ((arrName === undefined) || (arrName === "null")) {
            arrName = "array";
        }
        window[arrName] = [];
        var headNodeName = nodeBaseName + "_" + head_id;
        var name0 = headNodeName;
        var value1 = window[name0].value;
        console.log("looking to add value " + value1 + " to " + ryukyu_retArr);
        ryukyu_retArr[ryukyu_bigCount] = value1;
//        window[arrName][ryukyu_bigCount] = value1;
        ryukyu_bigCount++;
        var next = window[name0].next;
        console.log("next is " + next);
        if ((next != null) || (next != undefined)) {
            ryukyu_listToArray(next, nodeBaseName);
        }
    }
    var theRet = ryukyu_retArr;
    ryukyu_bigCount = 0;
    window[arrName] = theRet;
    console.log("resulting array " + arrName + " is " + window[arrName]);
    return theRet;  //  I don't know if it should return the array or true or another copy of the array as an object
}

function ryukyu_arrayToList(arr, nodeBaseName) {    // arr should be a variable not in quotes (or a literal in quotes)
                                                    // while nodeBaseName should be a name in quotes
    if ((arr === undefined) || (arr === "null")) {
        return false;
    }
    else {
        if ((nodeBaseName === undefined) || (nodeBaseName === "null") || (arr.length < 1)) {
            nodeBaseName = "node";
        }
        ryukyu_nodeRetObj = {}
        var node_num = 1;
        for (var i=0; i<arr.length; i++) {
            console.log("array is " + arr);
            var name0 = nodeBaseName + "_" + node_num;
            if (i<(arr.length - 1)) {
                window[name0] = new ryukyu_listItem(node_num, "auto", arr[i]);
                console.log("array item " + arr[i] + " at " + i + " converted into linked list item " + name0 + " with value " + arr[i]);
            }
            else{
                window[name0] = new ryukyu_listItem(node_num, "null", arr[i]);
                console.log("array item " + arr[i] + " at " + i + " converted into linked list item " + name0 + " with value " + arr[i]);
            }
        //    ryukyu_nodeRetObj.push(window[name0]);
            ryukyu_nodeRetObj[i] = window[name0];
            node_num++;
        }
        console.log("..return object is " + ryukyu_nodeRetObj);
        return ryukyu_nodeRetObj;
    }
}

var $ryukyu = function ryukyu(feature, payload) {  // This function can be called e.g. as $ryukyu("bubbleSort",[3,6,2,1]);
	function sortResultArr(set) {
		console.log("about to sort: " + set + "  using Ryukyu default sort");
		var x = 0;
		function bubbleOne(set0) {
		    if (set0[x+1] < set0[x]) {
		        console.log("inside swap (bubbleOne)...x=" + x + " " + set0);
		        var temp = set0[x+1];
		        set0[x+1] = set0[x];
		        set0[x] = temp;
		        console.log(set0);
		    }
		    return set0;
		}
		function bubbleSort() {
				zs1 = set;
		    console.log(zs1.length);
		    length1 = zs1.length
		    tmp = (zs1.length * length1);
		    for (i=0; i<tmp; i++) {
		        console.log("run " + i);
		        console.log("i=" + i + "  length1=" + length1 + "  x=" + x);
		        if (i % length1 == 0) {
		            x = 0;
		        }
		        else {
		            x = (i % length1);
		        }
		        bubbleOne(zs1);
		    }
		}
		bubbleSort();
		console.log("final order set: " + set);
		resultArr = set;
		return set;
	}
	if (feature == "crush") {
		var retStr = [];
		for (i=0; i<payload.length; i++) {
			if ((payload[i] != null) && (typeof payload[i] != 'undefined')) {
				retStr = retStr + payload[i];
			}
		}
		return retStr;
	}
	if (feature == "bubbleSort") {
		set = payload;
		console.log("about to sort: " + set + "  using Ryukyu Bubble Sort");
		zs1 = set;
		var x = 0;
		function bubbleOne(set) {
		    if (set[x+1] < set[x]) {
		        console.log("inside swap (bubbleOne)...x=" + x + " " + set);
		        var temp = set[x+1];
		        set[x+1] = set[x];
		        set[x] = temp;
		        console.log(set);
		    }
		    return set;
		}
		function bubbleSort() {
		    console.log(zs1.length);
		    length1 = zs1.length
		    tmp = (zs1.length * length1);
		    for (i=0; i<tmp; i++) {
		        console.log("run " + i);
		        console.log("i=" + i + "  length1=" + length1 + "  x=" + x);
		        if (i % length1 == 0) {
		            x = 0;
		        }
		        else {
		            x = (i % length1);
		        }
		        bubbleOne(zs1);
		    }
		}
		bubbleSort();
		console.log("final order set: " + set);
		return set;
	}
	if (feature == "selectionSort") {
		set = payload;
		console.log("about to sort: " + set + " using Ryukyu Selection Sort");
		var zs1 = set;
		var x = 0;
		resultArr = [];
		var bubbleCount = 0;
		arr = set;
		var sortedSize = 0;
		function selectionSort() {
		    console.log("running at " + size + " on the array: " + arr);
		    var x = arr[size];
		        for (i=0; i<set.length; i++) {
		            for (i=0; i<arr.length; i++) {
		                if (arr[i] > arr[i+1]) {
		                    console.log("swapping arr[size] and arr[size+i]: " + arr[size] + " "+ arr[size+i]);
		                    var t = arr[i];
		                    arr[i] = arr[1+i];
		                    arr[1+i] = t;
		                    size++;
		                    selectionSort();
		                }
		            }
		        }
		        return arr;
		}
		size = sortedSize;
		resultArr = selectionSort();
		console.log("final sort:" + resultArr);
		return resultArr;
	}
	if (feature == "insertionSort") {
		set = payload;
		console.log("about to sort: " + set + " using Ryukyu Insertion Sort");
		var zs1 = set;
		var x = 0;
		function swapLeft(z) {  //  Not used in this program but could be useful somewhere in a library (?)
		    if (set[z] > set[z+1]) {
		        console.log('attempting to swap ' + set[z] + " and " + set[z+1]);
		        var temp = set[z];
		        set[z] = set[z+1];
		        set[z+1] = temp;
		    }
		}
		function checkLeft(z) {
		    if (set[z-1] > set[z]) {
		        return true;
		    }
		    else {
		        return false;
		    }
		}
		function insertionSortSpotFinder(set, x) {  // find the position of the first value that needs to shift right
		    console.log('spot finder run ' + x);
		    while (x<set.length) {
		        if (((set[x] != 'undefined') && (set[x+1] != 'undefined')) && (set[x] <= set[x+1])) {
		            x++;
		        }
		        else {
		            console.log('spot is ' + x);
		            return x;
		        }
		    }
		    return false;
		}
		function insertionSortDepthFinder(set, x) {  //  find how far to the right the SpotFinder-flagged item needs to be moved
		    console.log('depth finder run ' + x);
		    var count = 0;
		    var basis = set[x];
		    while (x<set.length) {
		        console.log("set at x is " + x + " " + set[x]);
		        if (((set[x] != 'undefined') && (set[x+1] != 'undefined')) && (basis >= set[x+1])) {
		            count++;
		            x++;
		        }
		        else {
		            console.log('depth is ' + count);
		            return count;
		        }
		    }
		    return false;
		}
		function implementInsertionSort(zs1, place, distance) {
		    var tempe = zs1[place];
		    var dest = zs1[place+distance];
		    for (i=distance; i>0; i--) {
		        console.log("replacing " + zs1[i+place-1] + " with " + zs1[i+place]);
		        var t = zs1[i+place-1];
		        console.log("trailer is " + trailer + " and zs1[i+place-1] is " + zs1[i+place-1] +  " and zs1[i+place] is " + zs1[i+place]);
		        if (i == distance) {
		            console.log("run ZERO");
		            zs1[i+place-1] = zs1[i+place];
		            var trailer = t;
		        }
		        else if (i != distance - 0){
		            zs1[i+place-1] = trailer;
		            var trailer = t;
		        }
		    }
		    zs1[place+distance] = tempe;
		}
		function insertionSort() {
		    var xvar = 0;
		    var count = 0;
		    console.log("zs1.length is " + zs1.length);
		    while (count<zs1.length+10) {
		        console.log("sort tool run " + count);
		        var spot = insertionSortSpotFinder(zs1, xvar);
		        var depth = insertionSortDepthFinder(zs1, spot);
		        var result = implementInsertionSort(zs1, spot, depth);
		        console.log("current set at" + count + " is " + zs1);
		        count++;
		    }
		}
		insertionSort();
		console.log("final order set: " + zs1);
		return zs1;
	}
	if (feature == "quickSort") {
		set = payload;
		console.log("about to sort: " + set + " using Ryukyu Quick Sort");
		var zs1 = set;
		var x = 0;
		var resultArr = [];
		function swap(seti, z) {  //  Not used in this program but could be useful somewhere in a library (?)
		    console.log("seti is " + seti);
		    z = 1;
		    if (seti[z-1] != 'undefined') {
		        console.log("inside swap function with z at " + z + " and array at " + seti);
		        console.log("SWAP: about to compare if " + seti[z] + " is less than < " + seti[z-1]);
		        if (seti[z] < seti[z-1]) {
		            console.log('attempting to swap ' + seti[z] + " and " + seti[z-1]);
		            var temp = seti[z];
		            seti[z] = seti[z-1];
		            seti[z-1] = temp;
		            return seti;
		        }
		        else {
		            return seti;
		        }
		    }
		}
		function checkLeft(z) {
		    if (set[z-1] != 'undefined') {
		        if (set[z-1] > set[z]) {
		            return true;
		        }
		        else {
		            return false;
		        }
		    }
		}
		function quickOne(arr) {
		    console.log("running quickOne with array " + arr);
		    var pivotPosition = arr.length - 1;
		    var pivot = arr[pivotPosition];
		    for (i=0; i<arr.length; i++) {
		        var doTest = checkLeft(pivot+i);
		            arr = swap(arr, pivot+i);
		    }
		    return arr;
		}
		function quickSort(set) {
		    console.log("current result array: " + resultArr);
		    var ar2 = ar3 = [];
		    if (set.length > 1) {
		        var half = (set.length / 2);
		        half = Math.floor(half);
		        for (i=0; i<half; i++) {
		            ar2[i] = set[i];
		        }
		        quickSort(ar2);
		        var runner = 0;
		        for (i=half; i<set.length; i++) {
		            ar3[runner] = set[i];
		            runner++;
		        }
		        quickSort(ar3);
		    }
		    else {
		        var st = quickOne(set);
		        var middle = Math.floor(resultArr.length / 2);
		        console.log("SET IS " + set);
		        var pivot1 = resultArr[middle];
		        console.log("comparing " + st + " > " + pivot1);
		        st = parseInt(st);
		        pivot1 = parseInt(pivot1);
		        if (st > pivot1) {
		            console.log("TRUE: about to push " + st + " onto the result array");
		            resultArr.push(st);
		        }
		        else {
		            console.log("FALSE: about to unshift " + st + " onto the result array");
		            resultArr.unshift(st);
		        }
		        resultArr = sortResultArr(resultArr);
		    }
		}
		quickSort(set);
		zs2 = resultArr;
		console.log("final order set: " + zs2);
		return zs2;
	}
	else {
		return false;
	}
}
<commit_msg>ryukyu.js v0.1.6 fix ryukyu_arrayToList function to start numbering from 1 not zero: conversion now symmetrical<commit_after>//	ryukyu.js JavaScript library
//	v 0.1.6
//	copyright July 2015 Dan McKeown
//      http://danmckeown.info/code/ryukyu
//	Released under MIT license:
//      https://github.com/pacificpelican/ryukyu/blob/master/LICENSE

"use strict";

var ryukyu_retArr = [];
var ryukyu_bigCount = 0;
var ryukyu_nodeRetObj = {};

                        //  class declarations require ES6/ES2015
var ryukyu_listItem = class linkedListItem {  // This class instantiates a single variable that contains an id, a value and a next reference
    constructor(place, next, value) {
        if (value === undefined) {
            this.value = null;
        }
        else {
            this.value = value;
        }
        this.id = place;  // Let place be undefined rather than null by default since it is the id and should have a value
        if (((next === undefined) || (next === "auto")) && (place != undefined)) {
            this.next = place+1;
        }
        else {
            this.next = next;
        }
    }
};

var ryukyu_list = class listNode {  //  This class generates a series of variables, each w/a next pointer to the next one's id
    constructor(theLength, baseName, defaultValue) {
        if (baseName === undefined) {
            console.log("basename automatically assigned as node");
            baseName = "node";
        }
        if (defaultValue === undefined) {
            console.log("setting default value to null");
            var defaultValue = null;
        }
        ryukyu_nodeRetObj = {}
        for (var i=1; i<theLength; i++) {
            var nodeName;
            nodeName = baseName + "_" + i;
            console.log("about to construct " + nodeName);
            var name0 = nodeName;
            window[name0] = new ryukyu_listItem(i, "auto", defaultValue);
            ryukyu_nodeRetObj[i] = window[name0];
        }
            var nodeName;
            var pos = i;
            nodeName = baseName + "_" + pos;
            console.log("about to construct " + nodeName);
            var name0 = nodeName;
            window[name0] = new ryukyu_listItem(pos, null, defaultValue);
            ryukyu_nodeRetObj[i] = window[name0];
            return ryukyu_nodeRetObj;
    }
}

function ryukyu_listToArray(head_id, nodeBaseName, arrName) { // This takes info about the head list variable, works along chain and returns an array
    if ((head_id === undefined) || (nodeBaseName === undefined)) {
        return false;
    }
    else {
        if ((arrName === undefined) || (arrName === "null")) {
            arrName = "array";
        }
        window[arrName] = [];
        var headNodeName = nodeBaseName + "_" + head_id;
        var name0 = headNodeName;
        var value1 = window[name0].value;
        console.log("looking to add value " + value1 + " to " + ryukyu_retArr);
        ryukyu_retArr[ryukyu_bigCount] = value1;
//        window[arrName][ryukyu_bigCount] = value1;
        ryukyu_bigCount++;
        var next = window[name0].next;
        console.log("next is " + next);
        if ((next != null) || (next != undefined)) {
            ryukyu_listToArray(next, nodeBaseName);
        }
    }
    var theRet = ryukyu_retArr;
    ryukyu_bigCount = 0;
    window[arrName] = theRet;
    console.log("resulting array " + arrName + " is " + window[arrName]);
    return theRet;  //  I don't know if it should return the array or true or another copy of the array as an object
}

function ryukyu_arrayToList(arr, nodeBaseName) {    // arr should be a variable not in quotes (or a literal in quotes)
                                                    // while nodeBaseName should be a name in quotes
    if ((arr === undefined) || (arr === "null")) {
        return false;
    }
    else {
        if ((nodeBaseName === undefined) || (nodeBaseName === "null") || (arr.length < 1)) {
            nodeBaseName = "node";
        }
        ryukyu_nodeRetObj = {}
        var node_num = 1;
        for (var i=0; i<arr.length; i++) {
            console.log("array is " + arr);
            var name0 = nodeBaseName + "_" + node_num;
            if (i<(arr.length - 1)) {
                window[name0] = new ryukyu_listItem(node_num, "auto", arr[i]);
                console.log("array item " + arr[i] + " at " + i + " converted into linked list item " + name0 + " with value " + arr[i]);
            }
            else{
                window[name0] = new ryukyu_listItem(node_num, "null", arr[i]);
                console.log("array item " + arr[i] + " at " + i + " converted into linked list item " + name0 + " with value " + arr[i]);
            }
        //    ryukyu_nodeRetObj.push(window[name0]);
            ryukyu_nodeRetObj[node_num] = window[name0];
            node_num++;
        }
        console.log("..return object is " + ryukyu_nodeRetObj);
        return ryukyu_nodeRetObj;
    }
}

var $ryukyu = function ryukyu(feature, payload) {  // This function can be called e.g. as $ryukyu("bubbleSort",[3,6,2,1]);
	function sortResultArr(set) {
		console.log("about to sort: " + set + "  using Ryukyu default sort");
		var x = 0;
		function bubbleOne(set0) {
		    if (set0[x+1] < set0[x]) {
		        console.log("inside swap (bubbleOne)...x=" + x + " " + set0);
		        var temp = set0[x+1];
		        set0[x+1] = set0[x];
		        set0[x] = temp;
		        console.log(set0);
		    }
		    return set0;
		}
		function bubbleSort() {
				zs1 = set;
		    console.log(zs1.length);
		    length1 = zs1.length
		    tmp = (zs1.length * length1);
		    for (i=0; i<tmp; i++) {
		        console.log("run " + i);
		        console.log("i=" + i + "  length1=" + length1 + "  x=" + x);
		        if (i % length1 == 0) {
		            x = 0;
		        }
		        else {
		            x = (i % length1);
		        }
		        bubbleOne(zs1);
		    }
		}
		bubbleSort();
		console.log("final order set: " + set);
		resultArr = set;
		return set;
	}
	if (feature == "crush") {
		var retStr = [];
		for (i=0; i<payload.length; i++) {
			if ((payload[i] != null) && (typeof payload[i] != 'undefined')) {
				retStr = retStr + payload[i];
			}
		}
		return retStr;
	}
	if (feature == "bubbleSort") {
		set = payload;
		console.log("about to sort: " + set + "  using Ryukyu Bubble Sort");
		zs1 = set;
		var x = 0;
		function bubbleOne(set) {
		    if (set[x+1] < set[x]) {
		        console.log("inside swap (bubbleOne)...x=" + x + " " + set);
		        var temp = set[x+1];
		        set[x+1] = set[x];
		        set[x] = temp;
		        console.log(set);
		    }
		    return set;
		}
		function bubbleSort() {
		    console.log(zs1.length);
		    length1 = zs1.length
		    tmp = (zs1.length * length1);
		    for (i=0; i<tmp; i++) {
		        console.log("run " + i);
		        console.log("i=" + i + "  length1=" + length1 + "  x=" + x);
		        if (i % length1 == 0) {
		            x = 0;
		        }
		        else {
		            x = (i % length1);
		        }
		        bubbleOne(zs1);
		    }
		}
		bubbleSort();
		console.log("final order set: " + set);
		return set;
	}
	if (feature == "selectionSort") {
		set = payload;
		console.log("about to sort: " + set + " using Ryukyu Selection Sort");
		var zs1 = set;
		var x = 0;
		resultArr = [];
		var bubbleCount = 0;
		arr = set;
		var sortedSize = 0;
		function selectionSort() {
		    console.log("running at " + size + " on the array: " + arr);
		    var x = arr[size];
		        for (i=0; i<set.length; i++) {
		            for (i=0; i<arr.length; i++) {
		                if (arr[i] > arr[i+1]) {
		                    console.log("swapping arr[size] and arr[size+i]: " + arr[size] + " "+ arr[size+i]);
		                    var t = arr[i];
		                    arr[i] = arr[1+i];
		                    arr[1+i] = t;
		                    size++;
		                    selectionSort();
		                }
		            }
		        }
		        return arr;
		}
		size = sortedSize;
		resultArr = selectionSort();
		console.log("final sort:" + resultArr);
		return resultArr;
	}
	if (feature == "insertionSort") {
		set = payload;
		console.log("about to sort: " + set + " using Ryukyu Insertion Sort");
		var zs1 = set;
		var x = 0;
		function swapLeft(z) {  //  Not used in this program but could be useful somewhere in a library (?)
		    if (set[z] > set[z+1]) {
		        console.log('attempting to swap ' + set[z] + " and " + set[z+1]);
		        var temp = set[z];
		        set[z] = set[z+1];
		        set[z+1] = temp;
		    }
		}
		function checkLeft(z) {
		    if (set[z-1] > set[z]) {
		        return true;
		    }
		    else {
		        return false;
		    }
		}
		function insertionSortSpotFinder(set, x) {  // find the position of the first value that needs to shift right
		    console.log('spot finder run ' + x);
		    while (x<set.length) {
		        if (((set[x] != 'undefined') && (set[x+1] != 'undefined')) && (set[x] <= set[x+1])) {
		            x++;
		        }
		        else {
		            console.log('spot is ' + x);
		            return x;
		        }
		    }
		    return false;
		}
		function insertionSortDepthFinder(set, x) {  //  find how far to the right the SpotFinder-flagged item needs to be moved
		    console.log('depth finder run ' + x);
		    var count = 0;
		    var basis = set[x];
		    while (x<set.length) {
		        console.log("set at x is " + x + " " + set[x]);
		        if (((set[x] != 'undefined') && (set[x+1] != 'undefined')) && (basis >= set[x+1])) {
		            count++;
		            x++;
		        }
		        else {
		            console.log('depth is ' + count);
		            return count;
		        }
		    }
		    return false;
		}
		function implementInsertionSort(zs1, place, distance) {
		    var tempe = zs1[place];
		    var dest = zs1[place+distance];
		    for (i=distance; i>0; i--) {
		        console.log("replacing " + zs1[i+place-1] + " with " + zs1[i+place]);
		        var t = zs1[i+place-1];
		        console.log("trailer is " + trailer + " and zs1[i+place-1] is " + zs1[i+place-1] +  " and zs1[i+place] is " + zs1[i+place]);
		        if (i == distance) {
		            console.log("run ZERO");
		            zs1[i+place-1] = zs1[i+place];
		            var trailer = t;
		        }
		        else if (i != distance - 0){
		            zs1[i+place-1] = trailer;
		            var trailer = t;
		        }
		    }
		    zs1[place+distance] = tempe;
		}
		function insertionSort() {
		    var xvar = 0;
		    var count = 0;
		    console.log("zs1.length is " + zs1.length);
		    while (count<zs1.length+10) {
		        console.log("sort tool run " + count);
		        var spot = insertionSortSpotFinder(zs1, xvar);
		        var depth = insertionSortDepthFinder(zs1, spot);
		        var result = implementInsertionSort(zs1, spot, depth);
		        console.log("current set at" + count + " is " + zs1);
		        count++;
		    }
		}
		insertionSort();
		console.log("final order set: " + zs1);
		return zs1;
	}
	if (feature == "quickSort") {
		set = payload;
		console.log("about to sort: " + set + " using Ryukyu Quick Sort");
		var zs1 = set;
		var x = 0;
		var resultArr = [];
		function swap(seti, z) {  //  Not used in this program but could be useful somewhere in a library (?)
		    console.log("seti is " + seti);
		    z = 1;
		    if (seti[z-1] != 'undefined') {
		        console.log("inside swap function with z at " + z + " and array at " + seti);
		        console.log("SWAP: about to compare if " + seti[z] + " is less than < " + seti[z-1]);
		        if (seti[z] < seti[z-1]) {
		            console.log('attempting to swap ' + seti[z] + " and " + seti[z-1]);
		            var temp = seti[z];
		            seti[z] = seti[z-1];
		            seti[z-1] = temp;
		            return seti;
		        }
		        else {
		            return seti;
		        }
		    }
		}
		function checkLeft(z) {
		    if (set[z-1] != 'undefined') {
		        if (set[z-1] > set[z]) {
		            return true;
		        }
		        else {
		            return false;
		        }
		    }
		}
		function quickOne(arr) {
		    console.log("running quickOne with array " + arr);
		    var pivotPosition = arr.length - 1;
		    var pivot = arr[pivotPosition];
		    for (i=0; i<arr.length; i++) {
		        var doTest = checkLeft(pivot+i);
		            arr = swap(arr, pivot+i);
		    }
		    return arr;
		}
		function quickSort(set) {
		    console.log("current result array: " + resultArr);
		    var ar2 = ar3 = [];
		    if (set.length > 1) {
		        var half = (set.length / 2);
		        half = Math.floor(half);
		        for (i=0; i<half; i++) {
		            ar2[i] = set[i];
		        }
		        quickSort(ar2);
		        var runner = 0;
		        for (i=half; i<set.length; i++) {
		            ar3[runner] = set[i];
		            runner++;
		        }
		        quickSort(ar3);
		    }
		    else {
		        var st = quickOne(set);
		        var middle = Math.floor(resultArr.length / 2);
		        console.log("SET IS " + set);
		        var pivot1 = resultArr[middle];
		        console.log("comparing " + st + " > " + pivot1);
		        st = parseInt(st);
		        pivot1 = parseInt(pivot1);
		        if (st > pivot1) {
		            console.log("TRUE: about to push " + st + " onto the result array");
		            resultArr.push(st);
		        }
		        else {
		            console.log("FALSE: about to unshift " + st + " onto the result array");
		            resultArr.unshift(st);
		        }
		        resultArr = sortResultArr(resultArr);
		    }
		}
		quickSort(set);
		zs2 = resultArr;
		console.log("final order set: " + zs2);
		return zs2;
	}
	else {
		return false;
	}
}
<|endoftext|>


<commit_before>import anglicize from 'anglicize';

module.exports = function (exec, execmap) {
  const filters = {};

  /**
   * Anglicize the input, ie. deletes the diacritics
   * @param  {String} input
   * @return {String} input without diacritics
   */
  filters.anglicize = function (input, args) {
    return exec(args, () => anglicize(input), "anglicize");
  };

  /**
   * Tokenize the input
   * @param  {String} input
   * @param  {String|RegExp|Boolean} args  true: default tokenization
   *                                       string: predefined tokenization
   *                                       RegExp: tokenization with the given regexp
   * @return {Array} tokens
   */
  filters.tokenize = function (input, args) {
    return exec(args, arg => { return tokenize(input, arg); }, "tokenize");
  };

  /**
   * Count tokenized words
   * @param  {String} input
   * @param  {String|RegExp|Boolean} args  true: default tokenization
   *                                       string: predefined tokenization
   *                                       RegExp: tokenization with the given regexp
   * @return {Integer} number of words
   */
  filters.countWords = function (input, args) {
    return exec(args, function (arg) {
      return tokenize(input, arg).length;
    }, "countWords");
  };

  /**
   * Count characters
   * @param  {String} input
   * @param  {String|RegExp|Boolean} args  true: count every characters
   *                                       string: count using a predefined setting
   *                                       RegExp: count characters that match the regexp
   * @return {Integer} number of characters
   */
  filters.countCharacters = function (input, args) {
    return exec(args, function (arg) {
      if (arg === true) { return input.length; }
      if (arg === 'slug') { return input.replace(/-/g, '').length; }

      return Array.from(input).filter(c => c.match(arg)).length;
    }, "countWords");
  };

  return filters;
}

/**
 * Tokenize the input
 * @param  {String} input
 * @param  {String|RegExp|Boolean} args  true: default tokenization
 *                                       string: predefined tokenization
 *                                       RegExp: tokenization with the given regexp
 * @return {Array} tokens
 */
function tokenize(input, arg) {
  switch (arg) {
  case true:
    arg = /[^a-z0-9äâàéèëêïîöôùüûœç'\-]+/i;
    break;
  case 'slug':
    arg = /[^a-z0-9]+/i;
    break;
  }

  let words = input.split(arg);

  // Split quotes in words
  for (let i = 0; i <= words.length - 1; i++) {
    if (!words[i].includes("'")) { continue; }

    let splitted = words[i].split("'");

    for (let j = 0; j < splitted.length - 1; j++) {
      splitted[j] += "'";
    }

    words.splice(i, 1, ...splitted);
  }

  return words.filter(word => word);
}
<commit_msg>add next<commit_after>import anglicize from 'anglicize';

module.exports = function (exec, execmap) {
  const filters = {};

  /**
   * Anglicize the input, ie. deletes the diacritics
   * @param  {String} input
   * @return {String} input without diacritics
   */
  filters.anglicize = function (input, args, next) {
    return exec(args, () => next(null, anglicize(input)), "anglicize");
  };

  /**
   * Tokenize the input
   * @param  {String} input
   * @param  {String|RegExp|Boolean} args  true: default tokenization
   *                                       string: predefined tokenization
   *                                       RegExp: tokenization with the given regexp
   * @return {Array} tokens
   */
  filters.tokenize = function (input, args, next) {
    return exec(args, arg => next(null, tokenize(input, arg)), "tokenize");
  };

  /**
   * Count tokenized words
   * @param  {String} input
   * @param  {String|RegExp|Boolean} args  true: default tokenization
   *                                       string: predefined tokenization
   *                                       RegExp: tokenization with the given regexp
   * @return {Integer} number of words
   */
  filters.countWords = function (input, args, next) {
    return exec(args, arg => next(null, tokenize(input, arg).length), "countWords");
  };

  /**
   * Count characters
   * @param  {String} input
   * @param  {String|RegExp|Boolean} args  true: count every characters
   *                                       string: count using a predefined setting
   *                                       RegExp: count characters that match the regexp
   * @return {Integer} number of characters
   */
  filters.countCharacters = function (input, args, next) {
    return exec(args, function (arg) {
      if (arg === true) { return next(null, input.length); }
      if (arg === 'slug') { return next(null, input.replace(/-/g, '').length); }

      return next(null, Array.from(input).filter(c => c.match(arg)).length);
    }, "countWords");
  };

  return filters;
}

/**
 * Tokenize the input
 * @param  {String} input
 * @param  {String|RegExp|Boolean} args  true: default tokenization
 *                                       string: predefined tokenization
 *                                       RegExp: tokenization with the given regexp
 * @return {Array} tokens
 */
function tokenize(input, arg) {
  switch (arg) {
  case true:
    arg = /[^a-z0-9äâàéèëêïîöôùüûœç'\-]+/i;
    break;
  case 'slug':
    arg = /[^a-z0-9]+/i;
    break;
  }

  let words = input.split(arg);

  // Split quotes in words
  for (let i = 0; i <= words.length - 1; i++) {
    if (!words[i].includes("'")) { continue; }

    let splitted = words[i].split("'");

    for (let j = 0; j < splitted.length - 1; j++) {
      splitted[j] += "'";
    }

    words.splice(i, 1, ...splitted);
  }

  return words.filter(word => word);
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import './Harta.css';
import * as traseuLung from './constants/traseu_lung.json';
import { isActive, culoareParticipant } from './helpers'

export default class Harta extends Component {
  constructor(props) {
    super(props);
    this.state = {
      culoriParticipanti: []
    };
    this.schimbaStateHover = this.props.schimbaStateHover.bind(this);
  }

  static defaultProps = {
    center: {lat: 47.76, lng: 26.20},
    zoom: 13,
    participanti: {},
  };

  render() {
    const Participant = ({ idParticipant, numeParticipant, active, color }) => {
      return (

 {
            this.schimbaStateHover(idParticipant)
            e.target.closest('.avatar-participant').parentElement.classList.add('avatar-index')
          }}
          onMouseLeave={(e) => {
            this.schimbaStateHover(-1)
            e.target.closest('.avatar-participant').parentElement.classList.remove('avatar-index')
          }}
          style={{ borderColor: `${culoareParticipant(numeParticipant)}` }}
          className={`avatar-participant ${isActive(active)}`}>
          {idParticipant}

      );
    };

    const createMapOptions = maps => {
      return {
        mapTypeId: maps.MapTypeId.SATELLITE
      }
    }

    const participant = this.props.participanti.map((p, index) => {
      return <Participant key={index}
        lat={p.lastLocation.latitude}
        lng={p.lastLocation.longitude}
        idParticipant={p.id}
        numeParticipant={p.name}
        active={parseInt(p.id, 10) === this.props.participantHovered}
      />;
    });

    const loadedGMapsApi = ({map, maps}) => {
      const traseuLungPolyline = traseuLung.features["0"].geometry.coordinates["0"]
      .map((coord, index) => {
          return {lng: coord[0], lat: coord[1]}
      });

      const GMapsPolyline = new maps.Polyline({
        path: traseuLungPolyline,
        geodesic: true,
        strokeColor: '#00aaff',
        strokeOpacity: 0.7,
        strokeWeight: 4
      });

      GMapsPolyline.setMap(map);
    }

    return (
      <GoogleMapReact
        defaultCenter={this.props.center}
        defaultZoom={this.props.zoom}
        options={createMapOptions}
        onGoogleApiLoaded={loadedGMapsApi}
          yesIWantToUseGoogleMapApiInternals
      >
        {participant}
      </GoogleMapReact>
    );
  }
}
<commit_msg>Changed max/min values on map<commit_after>import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import './Harta.css';
import * as traseuLung from './constants/traseu_lung.json';
import { isActive, culoareParticipant } from './helpers'

export default class Harta extends Component {
  constructor(props) {
    super(props);
    this.state = {
      culoriParticipanti: []
    };
    this.schimbaStateHover = this.props.schimbaStateHover.bind(this);
  }

  static defaultProps = {
    center: {lat: 47.76, lng: 26.20},
    zoom: 13,
    participanti: {},
  };

  render() {
    const Participant = ({ idParticipant, numeParticipant, active, color }) => {
      return (

 {
            this.schimbaStateHover(idParticipant)
            e.target.closest('.avatar-participant').parentElement.classList.add('avatar-index')
          }}
          onMouseLeave={(e) => {
            this.schimbaStateHover(-1)
            e.target.closest('.avatar-participant').parentElement.classList.remove('avatar-index')
          }}
          style={{ borderColor: `${culoareParticipant(numeParticipant)}` }}
          className={`avatar-participant ${isActive(active)}`}>
          {idParticipant}

      );
    };

    const createMapOptions = maps => {
      return {
        mapTypeId: maps.MapTypeId.SATELLITE,
        minZoom: 12,
        maxZoom: 16,
      }
    }

    const participant = this.props.participanti.map((p, index) => {
      return <Participant key={index}
        lat={p.lastLocation.latitude}
        lng={p.lastLocation.longitude}
        idParticipant={p.id}
        numeParticipant={p.name}
        active={parseInt(p.id, 10) === this.props.participantHovered}
      />;
    });

    const loadedGMapsApi = ({map, maps}) => {
      const traseuLungPolyline = traseuLung.features["0"].geometry.coordinates["0"]
      .map((coord, index) => {
          return {lng: coord[0], lat: coord[1]}
      });

      const GMapsPolyline = new maps.Polyline({
        path: traseuLungPolyline,
        geodesic: true,
        strokeColor: '#00aaff',
        strokeOpacity: 0.7,
        strokeWeight: 4
      });

      GMapsPolyline.setMap(map);
    }

    return (
      <GoogleMapReact
        defaultCenter={this.props.center}
        defaultZoom={this.props.zoom}
        options={createMapOptions}
        onGoogleApiLoaded={loadedGMapsApi}
          yesIWantToUseGoogleMapApiInternals
      >
        {participant}
      </GoogleMapReact>
    );
  }
}
<|endoftext|>


<commit_before>var fs = require('fs'),
    xml = require('xml-object-stream'),
    enums = require('../shared/enums'),
    _ = require('lodash'),
    moment = require('moment'),
    utils = require('../shared/utils')

exports.readPrograms = function (body, callback) {
  var stream = xml.parse(body)
  var programs = []

  stream.each('KUVAOHJELMA', function(xml) {
    programs.push(validateProgram(xml))
  })

  stream.on('end', function() {
    return callback(null, programs)
  })
}

var format = flatMap(requiredAttr('TYPE', 'type'), function(p) {
  var cls = _.curry(node)('LUOKITTELU', 'classification')
  if (p.type == '08') {
    return map(cls([and(required('PELIFORMAATTI'), valueInList('PELIFORMAATTI', enums.gameFormat, 'gameFormat'))]), function(p) {
      return {gameFormat: p.classification.gameFormat}
    })
  } else {
    return cls([and(required('FORMAATTI'), valueInList('FORMAATTI', enums.format, 'format'))])
  }
})

var validateProgram = map(compose([
  and(requiredAttr('TYPE', 'type'), function(xml) {
    var type = xml.$.TYPE
    if (_.has(enums.legacyProgramTypes, type)) return ok({ programType: enums.legacyProgramTypes[type] })
    else return error("Virheellinen attribuutti: TYPE")
  }),
  required('ASIAKKAANTUNNISTE', 'externalId'),
  required('ALKUPERAINENNIMI', 'name'),
  flatMap(requiredAttr('TYPE', 'type'), function(p) {
    var allButTvOrOther = ['01','02','03','04','06','07','08','10','11']
    if (_.contains(allButTvOrOther, p.type)) return required('SUOMALAINENNIMI', 'nameFi')
    else return optional('SUOMALAINENNIMI', 'nameFi')
  }),
  optional('RUOTSALAINENNIMI', 'nameSv'),
  optional('MUUNIMI', 'nameOther'),
  optional('JULKAISUVUOSI', 'year'),
  optional('VALMISTUMISVUOSI', 'year'),
  flatMap(optional('MAAT'), function(p) {
    var countries = p.MAAT ? p.MAAT.split(' ') : []
    return function(xml) {
      if (_.all(countries, _.curry(_.has)(enums.countries))) return ok({country: countries})
      else return error('Virheellinen MAAT kenttä: ' + countries)
    }
  }),
  map(childrenByNameTo('TUOTANTOYHTIO', 'productionCompanies'), function(p) { return { productionCompanies: p.productionCompanies.map(text) } }),
  required('SYNOPSIS', 'synopsis'),
  optional('TUOTANTOKAUSI', 'season'),
  optional('OSA', 'episode'),
  flatMap(requiredAttr('TYPE', 'type'), function(p) {
    return p.type == '03' ? required('ISANTAOHJELMA', 'parentTvSeriesName') : optional('ISANTAOHJELMA', 'parentTvSeriesName')
  }),
  map(compose([
    valuesInEnum('LAJIT', enums.legacyGenres),
    valuesInEnum('TELEVISIO-OHJELMALAJIT', enums.legacyTvGenres),
    valuesInList('PELINLAJIT', enums.legacyGameGenres)
  ]), function(p) {
    return { legacyGenre: p.LAJIT.concat(p['TELEVISIO-OHJELMALAJIT']).concat(p.PELINLAJIT) }
  }),
  map(childrenByNameTo('OHJAAJA', 'directors'), function(p) { return {directors: p.directors.map(fullname) }}),
  map(childrenByNameTo('NAYTTELIJA', 'actors'), function(p) { return {actors: p.actors.map(fullname) }}),
  map(required('LUOKITTELIJA', 'author'), function(p) { return { classification: { author: { name: p.author } } }}),
  format,
  node('LUOKITTELU', 'classification', [
    and(requiredAttr('REKISTEROINTIPAIVA', 'registrationDate'), function(xml) {
      var d = moment(xml.$.REKISTEROINTIPAIVA, "DD.MM.YYYY HH:mm:ss")
      if (d.isValid()) return ok({ registrationDate: d.toDate() })
      else return error("Virheellinen aikaformaatti: " + 'REKISTEROINTIPAIVA')
    }),
    and(required('KESTO'), test('KESTO', utils.isValidDuration, "Virheellinen kesto", 'duration')),
    map(childrenByNameTo('VALITTUTERMI', 'criteria'), function(p) {
      var criteriaComments = _.object(p.criteria.map(function (c) {
        return [parseInt(c.$.KRITEERI), c.$.KOMMENTTI]
      }))
      return {safe: _.isEmpty(criteriaComments), criteria: _.keys(criteriaComments), criteriaComments: criteriaComments}
    })
  ])
]), function(p) { p.classifications = [p.classification]; delete p.classification; return p})

// validator = Xml -> Result
// validation = validator -> (program -> validator) -> validator
function flatMap(validator, f) {
  return function(xml) {
    var res = validator(xml)
    var res2 = f(res.program)(xml)
    var errors = _(res.errors.concat(res2.errors)).flatten().uniq().value()
    return {program: _.merge(_.cloneDeep(res.program), _.cloneDeep(res2.program)), errors: errors}
  }
}

function map(validator, f) {
  return function(xml) {
    var res = validator(xml)
    if (res.errors.length > 0) return res
    else return {program: f(res.program), errors: []}
  }
}

function mapError(v, f) {
  return function(xml) {
    var res = v(xml)
    if (res.errors.length > 0) return error([f(res.errors)])
    else return res
  }
}

function compose(xs) {
  return _.reduce(xs, function(acc, f) {
    return flatMap(acc, function(_) { return f })
  }, ret({}))
}

function and(v1, v2) {
  return function(xml) {
    var res = v1(xml)
    if (res.errors.length == 0) {
      return v2(xml)
    } else {
      return res
    }
  }
}

function or(v1, v2) {
  return function(xml) {
    var res = v1(xml)
    if (res.errors.length > 0) {
      return v2(xml)
    } else {
      return res
    }
  }
}

function ok(program) {
  return {program: program, errors: []}
}
function error(msg) {
  return {program: {}, errors: [msg]}
}

function ret(program) {
  return function(xml) {
    return {program: program, errors: []}
  }
}

function required(name, toField) {
  return function(xml) {
    toField = toField || name
    var val = xml[name]
    if (val && val.$text !== '' && val.$text !== undefined) return ok(utils.keyValue(toField, xml[name].$text))
    else return error(["Pakollinen kenttä puuttuu: " + name])
  }
}

function requiredNode(name, toField) {
  return function(xml) {
    toField = toField || name
    if (xml[name]) return ok(utils.keyValue(toField, xml[name].$text))
    else return error(["Pakollinen elementti puuttuu: " + name])
  }
}

function requiredAttr(name, toField) {
  return function(xml) {
    if (xml.$[name]) return ok(utils.keyValue(toField, xml.$[name]))
    else return error("Pakollinen attribuutti puuttuu: " + name)
  }
}

function optional(field, toField) {
  return function(xml) {
    toField = toField || field
    if (!xml[field] || !xml[field].$text || xml[field].$text.length == 0) return {program: utils.keyValue(toField, undefined), errors: []}
    else return {program: utils.keyValue(toField, xml[field].$text), errors: []}
  }
}

function childrenByNameTo(field, toField) {
  return function(xml) {
    return {
      program: utils.keyValue(toField, childrenByName(xml, field)),
      errors: []
    }
  }
}

function valuesInEnum(field, _enum) {
  return function(xml) {
    var values = optionListToArray(xml[field]).map(function(g) { return _enum[g] })
    if (_.all(values, function(v) { return v !== undefined })) return ok(utils.keyValue(field, values))
    else return error("Virheellinen kenttä " + field)
  }
}

function valuesInList(field, list) {
  return function(xml) {
    var values = optionListToArray(xml[field])
    var exists = values.map(_.curry(_.contains)(list))
    if (_.all(exists)) return ok(utils.keyValue(field, values))
    else return error("Virheellinen kenttä " + field)
  }
}

function valueInList(field, list, toField) {
  return function(xml) {
    toField = toField || field
    var value = xml[field].$text
    if (_.contains(list, value)) return ok(utils.keyValue(toField, value))
    else return error("Virheellinen kenttä " + field)
  }
}

function node(name, toField, validators) {
  return flatMap(requiredNode(name, toField), function(p) {
    return function (xml) {
      return _.reduce(validators, function(acc, f) {
        return flatMap(acc, function(_) { return map(f, function(p) { return utils.keyValue(toField, p)}) })
      }, ret(p))(xml[name])
    }
  })
}

function test(field, f, msg, toField) {
  return function(xml) {
    var text = xml[field].$text
    if (f(text)) return ok(utils.keyValue(toField || field, text))
    else return error(msg + " " + text)
  }
}
function text(node) {
  return node.$text
}
function fullname(node) {
  return node.ETUNIMI.$text + ' ' + node.SUKUNIMI.$text
}
function childrenByName(root, name) {
  return root.$children.filter(function(e) { return e.$name == name })
}

function optionListToArray(field, sep) {
  sep = sep || ' '
  if (!field || field.$text.length == 0) return []
  var arr = field.$text.split(sep).map(function(s) { return s.replace(/[\^\s]/g, '')} )
  return _(arr).compact().uniq().value()
}

<commit_msg>XML api: validate criteria codes<commit_after>var fs = require('fs'),
    xml = require('xml-object-stream'),
    enums = require('../shared/enums'),
    _ = require('lodash'),
    moment = require('moment'),
    utils = require('../shared/utils')

exports.readPrograms = function (body, callback) {
  var stream = xml.parse(body)
  var programs = []

  stream.each('KUVAOHJELMA', function(xml) {
    programs.push(validateProgram(xml))
  })

  stream.on('end', function() {
    return callback(null, programs)
  })
}

var format = flatMap(requiredAttr('TYPE', 'type'), function(p) {
  var cls = _.curry(node)('LUOKITTELU', 'classification')
  if (p.type == '08') {
    return map(cls([and(required('PELIFORMAATTI'), valueInList('PELIFORMAATTI', enums.gameFormat, 'gameFormat'))]), function(p) {
      return {gameFormat: p.classification.gameFormat}
    })
  } else {
    return cls([and(required('FORMAATTI'), valueInList('FORMAATTI', enums.format, 'format'))])
  }
})

var validateProgram = map(compose([
  and(requiredAttr('TYPE', 'type'), function(xml) {
    var type = xml.$.TYPE
    if (_.has(enums.legacyProgramTypes, type)) return ok({ programType: enums.legacyProgramTypes[type] })
    else return error("Virheellinen attribuutti: TYPE")
  }),
  required('ASIAKKAANTUNNISTE', 'externalId'),
  required('ALKUPERAINENNIMI', 'name'),
  flatMap(requiredAttr('TYPE', 'type'), function(p) {
    var allButTvOrOther = ['01','02','03','04','06','07','08','10','11']
    if (_.contains(allButTvOrOther, p.type)) return required('SUOMALAINENNIMI', 'nameFi')
    else return optional('SUOMALAINENNIMI', 'nameFi')
  }),
  optional('RUOTSALAINENNIMI', 'nameSv'),
  optional('MUUNIMI', 'nameOther'),
  optional('JULKAISUVUOSI', 'year'),
  optional('VALMISTUMISVUOSI', 'year'),
  flatMap(optional('MAAT'), function(p) {
    var countries = p.MAAT ? p.MAAT.split(' ') : []
    return function(xml) {
      if (_.all(countries, _.curry(_.has)(enums.countries))) return ok({country: countries})
      else return error('Virheellinen MAAT kenttä: ' + countries)
    }
  }),
  map(childrenByNameTo('TUOTANTOYHTIO', 'productionCompanies'), function(p) { return { productionCompanies: p.productionCompanies.map(text) } }),
  required('SYNOPSIS', 'synopsis'),
  optional('TUOTANTOKAUSI', 'season'),
  optional('OSA', 'episode'),
  flatMap(requiredAttr('TYPE', 'type'), function(p) {
    return p.type == '03' ? required('ISANTAOHJELMA', 'parentTvSeriesName') : optional('ISANTAOHJELMA', 'parentTvSeriesName')
  }),
  map(compose([
    valuesInEnum('LAJIT', enums.legacyGenres),
    valuesInEnum('TELEVISIO-OHJELMALAJIT', enums.legacyTvGenres),
    valuesInList('PELINLAJIT', enums.legacyGameGenres)
  ]), function(p) {
    return { legacyGenre: p.LAJIT.concat(p['TELEVISIO-OHJELMALAJIT']).concat(p.PELINLAJIT) }
  }),
  map(childrenByNameTo('OHJAAJA', 'directors'), function(p) { return {directors: p.directors.map(fullname) }}),
  map(childrenByNameTo('NAYTTELIJA', 'actors'), function(p) { return {actors: p.actors.map(fullname) }}),
  map(required('LUOKITTELIJA', 'author'), function(p) { return { classification: { author: { name: p.author } } }}),
  format,
  node('LUOKITTELU', 'classification', [
    and(requiredAttr('REKISTEROINTIPAIVA', 'registrationDate'), function(xml) {
      var d = moment(xml.$.REKISTEROINTIPAIVA, "DD.MM.YYYY HH:mm:ss")
      if (d.isValid()) return ok({ registrationDate: d.toDate() })
      else return error("Virheellinen aikaformaatti: " + 'REKISTEROINTIPAIVA')
    }),
    and(required('KESTO'), test('KESTO', utils.isValidDuration, "Virheellinen kesto", 'duration')),
    flatMap(childrenByNameTo('VALITTUTERMI', 'criteria'), function(p) {
      var validCriteria = enums.classificationCriteria.map(function(x) { return x.id })
      var errors = _.flatten(p.criteria.map(function(c) {
        return and(requiredAttr('KRITEERI'), attrInList('KRITEERI', validCriteria))(c).errors
      }))
      if (errors.length > 0) return function() { return {program: {}, errors: errors } }
      var criteriaComments = _.object(p.criteria.map(function (c) {
        return [parseInt(c.$.KRITEERI), c.$.KOMMENTTI]
      }))
      return function () { return ok({safe: _.isEmpty(criteriaComments), criteria: _.keys(criteriaComments), criteriaComments: criteriaComments}) }
    })
  ])
]), function(p) { p.classifications = [p.classification]; delete p.classification; return p})

// validator = Xml -> Result
// validation = validator -> (program -> validator) -> validator
function flatMap(validator, f) {
  return function(xml) {
    var res = validator(xml)
    var res2 = f(res.program)(xml)
    var errors = _(res.errors.concat(res2.errors)).flatten().uniq().value()
    return {program: _.merge(_.cloneDeep(res.program), _.cloneDeep(res2.program)), errors: errors}
  }
}

function map(validator, f) {
  return function(xml) {
    var res = validator(xml)
    if (res.errors.length > 0) return res
    else return {program: f(res.program), errors: []}
  }
}

function mapError(v, f) {
  return function(xml) {
    var res = v(xml)
    if (res.errors.length > 0) return error([f(res.errors)])
    else return res
  }
}

function compose(xs) {
  return _.reduce(xs, function(acc, f) {
    return flatMap(acc, function(_) { return f })
  }, ret({}))
}

function and(v1, v2) {
  return function(xml) {
    var res = v1(xml)
    if (res.errors.length == 0) {
      return v2(xml)
    } else {
      return res
    }
  }
}

function or(v1, v2) {
  return function(xml) {
    var res = v1(xml)
    if (res.errors.length > 0) {
      return v2(xml)
    } else {
      return res
    }
  }
}

function ok(program) {
  return {program: program, errors: []}
}
function error(msg) {
  return {program: {}, errors: [msg]}
}

function ret(program) {
  return function(xml) {
    return {program: program, errors: []}
  }
}

function required(name, toField) {
  return function(xml) {
    toField = toField || name
    var val = xml[name]
    if (val && val.$text !== '' && val.$text !== undefined) return ok(utils.keyValue(toField, xml[name].$text))
    else return error(["Pakollinen kenttä puuttuu: " + name])
  }
}

function requiredNode(name, toField) {
  return function(xml) {
    toField = toField || name
    if (xml[name]) return ok(utils.keyValue(toField, xml[name].$text))
    else return error(["Pakollinen elementti puuttuu: " + name])
  }
}

function requiredAttr(name, toField) {
  return function(xml) {
    if (xml.$[name]) return ok(utils.keyValue(toField, xml.$[name]))
    else return error("Pakollinen attribuutti puuttuu: " + name)
  }
}

function optional(field, toField) {
  return function(xml) {
    toField = toField || field
    if (!xml[field] || !xml[field].$text || xml[field].$text.length == 0) return {program: utils.keyValue(toField, undefined), errors: []}
    else return {program: utils.keyValue(toField, xml[field].$text), errors: []}
  }
}

function childrenByNameTo(field, toField) {
  return function(xml) {
    return {
      program: utils.keyValue(toField, childrenByName(xml, field)),
      errors: []
    }
  }
}

function valuesInEnum(field, _enum) {
  return function(xml) {
    var values = optionListToArray(xml[field]).map(function(g) { return _enum[g] })
    if (_.all(values, function(v) { return v !== undefined })) return ok(utils.keyValue(field, values))
    else return error("Virheellinen kenttä " + field)
  }
}

function valuesInList(field, list) {
  return function(xml) {
    var values = optionListToArray(xml[field])
    var exists = values.map(_.curry(_.contains)(list))
    if (_.all(exists)) return ok(utils.keyValue(field, values))
    else return error("Virheellinen kenttä " + field)
  }
}

function valueInList(field, list, toField) {
  return function(xml) {
    toField = toField || field
    var value = xml[field].$text
    if (_.contains(list, value)) return ok(utils.keyValue(toField, value))
    else return error("Virheellinen kenttä " + field)
  }
}

function attrInList(attr, list) {
  return function(xml) {
    var value = xml.$[attr]
    if (_.contains(list.map(function(x) { return x.toString() }), value)) return ok(utils.keyValue(attr, value))
    else return error("Virheellinen arvo atribuutille " + attr + ": " + value)
  }
}

function node(name, toField, validators) {
  return flatMap(requiredNode(name, toField), function(p) {
    return function (xml) {
      return _.reduce(validators, function(acc, f) {
        return flatMap(acc, function(_) { return map(f, function(p) { return utils.keyValue(toField, p)}) })
      }, ret(p))(xml[name])
    }
  })
}

function test(field, f, msg, toField) {
  return function(xml) {
    var text = xml[field].$text
    if (f(text)) return ok(utils.keyValue(toField || field, text))
    else return error(msg + " " + text)
  }
}
function text(node) {
  return node.$text
}
function fullname(node) {
  return node.ETUNIMI.$text + ' ' + node.SUKUNIMI.$text
}
function childrenByName(root, name) {
  return root.$children.filter(function(e) { return e.$name == name })
}

function optionListToArray(field, sep) {
  sep = sep || ' '
  if (!field || field.$text.length == 0) return []
  var arr = field.$text.split(sep).map(function(s) { return s.replace(/[\^\s]/g, '')} )
  return _(arr).compact().uniq().value()
}

<|endoftext|>


<commit_before>/**
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var async = require("async");
var Changeset = require("ep_etherpad-lite/static/js/Changeset");
var padManager = require("../db/PadManager");
var ERR = require("async-stacktrace");
var Security = require('ep_etherpad-lite/static/js/security');
var hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks');
var getPadPlainText = require('./ExportHelper').getPadPlainText;
var _processSpaces = require('./ExportHelper')._processSpaces;
var _analyzeLine = require('./ExportHelper')._analyzeLine;
var _encodeWhitespace = require('./ExportHelper')._encodeWhitespace;

// This is slightly different than the HTML method as it passes the output to getTXTFromAText
function getPadTXT(pad, revNum, callback)
{
  var atext = pad.atext;
  var html;
  async.waterfall([
  // fetch revision atext

  function (callback)
  {
    if (revNum != undefined)
    {
      pad.getInternalRevisionAText(revNum, function (err, revisionAtext)
      {
        if(ERR(err, callback)) return;
        atext = revisionAtext;
        callback();
      });
    }
    else
    {
      callback(null);
    }
  },

  // convert atext to html

  function (callback)
  {
    html = getTXTFromAtext(pad, atext); // only this line is different to the HTML function
    callback(null);
  }],
  // run final callback

  function (err)
  {
    if(ERR(err, callback)) return;
    callback(null, html);
  });
}

exports.getPadTXT = getPadTXT;

// This is different than the functionality provided in ExportHtml as it provides formatting
// functionality that is designed specifically for TXT exports
function getTXTFromAtext(pad, atext, authorColors)
{
  var apool = pad.apool();
  var textLines = atext.text.slice(0, -1).split('\n');
  var attribLines = Changeset.splitAttributionLines(atext.attribs, atext.text);

  var tags = ['h1', 'h2', 'strong', 'em', 'u', 's'];
  var props = ['heading1', 'heading2', 'bold', 'italic', 'underline', 'strikethrough'];
  var anumMap = {};
  var css = "";

  props.forEach(function (propName, i)
  {
    var propTrueNum = apool.putAttrib([propName, true], true);
    if (propTrueNum >= 0)
    {
      anumMap[propTrueNum] = i;
    }
  });

  function getLineTXT(text, attribs)
  {
    var propVals = [false, false, false];
    var ENTER = 1;
    var STAY = 2;
    var LEAVE = 0;

    // Use order of tags (b/i/u) as order of nesting, for simplicity
    // and decent nesting.  For example,
    // Just bold Bold and italics Just italics
    // becomes
    // Just bold Bold and italics Just italics
    var taker = Changeset.stringIterator(text);
    var assem = Changeset.stringAssembler();
    var openTags = [];

    var idx = 0;

    function processNextChars(numChars)
    {
      if (numChars <= 0)
      {
        return;
      }

      var iter = Changeset.opIterator(Changeset.subattribution(attribs, idx, idx + numChars));
      idx += numChars;

      while (iter.hasNext())
      {
        var o = iter.next();
        var propChanged = false;
        Changeset.eachAttribNumber(o.attribs, function (a)
        {
          if (a in anumMap)
          {
            var i = anumMap[a]; // i = 0 => bold, etc.
            if (!propVals[i])
            {
              propVals[i] = ENTER;
              propChanged = true;
            }
            else
            {
              propVals[i] = STAY;
            }
          }
        });
        for (var i = 0; i < propVals.length; i++)
        {
          if (propVals[i] === true)
          {
            propVals[i] = LEAVE;
            propChanged = true;
          }
          else if (propVals[i] === STAY)
          {
            propVals[i] = true; // set it back
          }
        }
        // now each member of propVal is in {false,LEAVE,ENTER,true}
        // according to what happens at start of span
        if (propChanged)
        {
          // leaving bold (e.g.) also leaves italics, etc.
          var left = false;
          for (var i = 0; i < propVals.length; i++)
          {
            var v = propVals[i];
            if (!left)
            {
              if (v === LEAVE)
              {
                left = true;
              }
            }
            else
            {
              if (v === true)
              {
                propVals[i] = STAY; // tag will be closed and re-opened
              }
            }
          }

          var tags2close = [];

          for (var i = propVals.length - 1; i >= 0; i--)
          {
            if (propVals[i] === LEAVE)
            {
              //emitCloseTag(i);
              tags2close.push(i);
              propVals[i] = false;
            }
            else if (propVals[i] === STAY)
            {
              //emitCloseTag(i);
              tags2close.push(i);
            }
          }

          for (var i = 0; i < propVals.length; i++)
          {
            if (propVals[i] === ENTER || propVals[i] === STAY)
            {
              emitOpenTag(i);
              propVals[i] = true;
            }
          }
          // propVals is now all {true,false} again
        } // end if (propChanged)
        var chars = o.chars;
        if (o.lines)
        {
          chars--; // exclude newline at end of line, if present
        }

        var s = taker.take(chars);

        //removes the characters with the code 12. Don't know where they come
        //from but they break the abiword parser and are completly useless
        s = s.replace(String.fromCharCode(12), "");

        // remove * from s, it's just not needed on a blank line..  This stops
        // plugins from being able to display * at the beginning of a line
        s = s.replace("*", "");

        // assem.append(_encodeWhitespace(Security.escapeHTML(s)));
        assem.append(_encodeWhitespace(s));
      } // end iteration over spans in line

      var tags2close = [];
      for (var i = propVals.length - 1; i >= 0; i--)
      {
        if (propVals[i])
        {
          tags2close.push(i);
          propVals[i] = false;
        }
      }

    } // end processNextChars
    processNextChars(text.length - idx);

    return _processSpaces(assem.toString());
  } // end getLineHTML
  var pieces = [css];

  // Need to deal with constraints imposed on HTML lists; can
  // only gain one level of nesting at once, can't change type
  // mid-list, etc.
  // People might use weird indenting, e.g. skip a level,
  // so we want to do something reasonable there.  We also
  // want to deal gracefully with blank lines.
  // => keeps track of the parents level of indentation
  var lists = []; // e.g. [[1,'bullet'], [3,'bullet'], ...]
  for (var i = 0; i < textLines.length; i++)
  {
    var line = _analyzeLine(textLines[i], attribLines[i], apool);
    var lineContent = getLineTXT(line.text, line.aline);
    if(line.listTypeName == "bullet"){
      lineContent = "* " + lineContent; // add a bullet
    }
    if(line.listLevel > 0){
      for (var j = line.listLevel - 1; j >= 0; j--){
        pieces.push('\t');
      }
      if(line.listTypeName == "number"){
        pieces.push(line.listLevel + ". ");
        // This is bad because it doesn't truly reflect what the user
        // sees because browsers do magic on nested

s
      }
      pieces.push(lineContent, '\n');
    }else{
      pieces.push(lineContent, '\n');
    }
  }

  return pieces.join('');
}
exports.getTXTFromAtext = getTXTFromAtext;

exports.getPadTXTDocument = function (padId, revNum, noDocType, callback)
{
  padManager.getPad(padId, function (err, pad)
  {
    if(ERR(err, callback)) return;

    getPadTXT(pad, revNum, function (err, html)
    {
      if(ERR(err, callback)) return;
      callback(null, html);
    });
  });
}

function _encodeWhitespace(s) {
  return s.replace(/[^\x21-\x7E\s\t\n\r]/g, function(c)
  {
    return "&#" +c.charCodeAt(0) + ";"
  });
}
<commit_msg>Correct license header<commit_after>/**
 * TXT export
 */

/*
 * 2013 John McLear
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var async = require("async");
var Changeset = require("ep_etherpad-lite/static/js/Changeset");
var padManager = require("../db/PadManager");
var ERR = require("async-stacktrace");
var Security = require('ep_etherpad-lite/static/js/security');
var hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks');
var getPadPlainText = require('./ExportHelper').getPadPlainText;
var _processSpaces = require('./ExportHelper')._processSpaces;
var _analyzeLine = require('./ExportHelper')._analyzeLine;
var _encodeWhitespace = require('./ExportHelper')._encodeWhitespace;

// This is slightly different than the HTML method as it passes the output to getTXTFromAText
function getPadTXT(pad, revNum, callback)
{
  var atext = pad.atext;
  var html;
  async.waterfall([
  // fetch revision atext

  function (callback)
  {
    if (revNum != undefined)
    {
      pad.getInternalRevisionAText(revNum, function (err, revisionAtext)
      {
        if(ERR(err, callback)) return;
        atext = revisionAtext;
        callback();
      });
    }
    else
    {
      callback(null);
    }
  },

  // convert atext to html

  function (callback)
  {
    html = getTXTFromAtext(pad, atext); // only this line is different to the HTML function
    callback(null);
  }],
  // run final callback

  function (err)
  {
    if(ERR(err, callback)) return;
    callback(null, html);
  });
}

exports.getPadTXT = getPadTXT;

// This is different than the functionality provided in ExportHtml as it provides formatting
// functionality that is designed specifically for TXT exports
function getTXTFromAtext(pad, atext, authorColors)
{
  var apool = pad.apool();
  var textLines = atext.text.slice(0, -1).split('\n');
  var attribLines = Changeset.splitAttributionLines(atext.attribs, atext.text);

  var tags = ['h1', 'h2', 'strong', 'em', 'u', 's'];
  var props = ['heading1', 'heading2', 'bold', 'italic', 'underline', 'strikethrough'];
  var anumMap = {};
  var css = "";

  props.forEach(function (propName, i)
  {
    var propTrueNum = apool.putAttrib([propName, true], true);
    if (propTrueNum >= 0)
    {
      anumMap[propTrueNum] = i;
    }
  });

  function getLineTXT(text, attribs)
  {
    var propVals = [false, false, false];
    var ENTER = 1;
    var STAY = 2;
    var LEAVE = 0;

    // Use order of tags (b/i/u) as order of nesting, for simplicity
    // and decent nesting.  For example,
    // Just bold Bold and italics Just italics
    // becomes
    // Just bold Bold and italics Just italics
    var taker = Changeset.stringIterator(text);
    var assem = Changeset.stringAssembler();
    var openTags = [];

    var idx = 0;

    function processNextChars(numChars)
    {
      if (numChars <= 0)
      {
        return;
      }

      var iter = Changeset.opIterator(Changeset.subattribution(attribs, idx, idx + numChars));
      idx += numChars;

      while (iter.hasNext())
      {
        var o = iter.next();
        var propChanged = false;
        Changeset.eachAttribNumber(o.attribs, function (a)
        {
          if (a in anumMap)
          {
            var i = anumMap[a]; // i = 0 => bold, etc.
            if (!propVals[i])
            {
              propVals[i] = ENTER;
              propChanged = true;
            }
            else
            {
              propVals[i] = STAY;
            }
          }
        });
        for (var i = 0; i < propVals.length; i++)
        {
          if (propVals[i] === true)
          {
            propVals[i] = LEAVE;
            propChanged = true;
          }
          else if (propVals[i] === STAY)
          {
            propVals[i] = true; // set it back
          }
        }
        // now each member of propVal is in {false,LEAVE,ENTER,true}
        // according to what happens at start of span
        if (propChanged)
        {
          // leaving bold (e.g.) also leaves italics, etc.
          var left = false;
          for (var i = 0; i < propVals.length; i++)
          {
            var v = propVals[i];
            if (!left)
            {
              if (v === LEAVE)
              {
                left = true;
              }
            }
            else
            {
              if (v === true)
              {
                propVals[i] = STAY; // tag will be closed and re-opened
              }
            }
          }

          var tags2close = [];

          for (var i = propVals.length - 1; i >= 0; i--)
          {
            if (propVals[i] === LEAVE)
            {
              //emitCloseTag(i);
              tags2close.push(i);
              propVals[i] = false;
            }
            else if (propVals[i] === STAY)
            {
              //emitCloseTag(i);
              tags2close.push(i);
            }
          }

          for (var i = 0; i < propVals.length; i++)
          {
            if (propVals[i] === ENTER || propVals[i] === STAY)
            {
              emitOpenTag(i);
              propVals[i] = true;
            }
          }
          // propVals is now all {true,false} again
        } // end if (propChanged)
        var chars = o.chars;
        if (o.lines)
        {
          chars--; // exclude newline at end of line, if present
        }

        var s = taker.take(chars);

        //removes the characters with the code 12. Don't know where they come
        //from but they break the abiword parser and are completly useless
        s = s.replace(String.fromCharCode(12), "");

        // remove * from s, it's just not needed on a blank line..  This stops
        // plugins from being able to display * at the beginning of a line
        s = s.replace("*", "");

        // assem.append(_encodeWhitespace(Security.escapeHTML(s)));
        assem.append(_encodeWhitespace(s));
      } // end iteration over spans in line

      var tags2close = [];
      for (var i = propVals.length - 1; i >= 0; i--)
      {
        if (propVals[i])
        {
          tags2close.push(i);
          propVals[i] = false;
        }
      }

    } // end processNextChars
    processNextChars(text.length - idx);

    return _processSpaces(assem.toString());
  } // end getLineHTML
  var pieces = [css];

  // Need to deal with constraints imposed on HTML lists; can
  // only gain one level of nesting at once, can't change type
  // mid-list, etc.
  // People might use weird indenting, e.g. skip a level,
  // so we want to do something reasonable there.  We also
  // want to deal gracefully with blank lines.
  // => keeps track of the parents level of indentation
  var lists = []; // e.g. [[1,'bullet'], [3,'bullet'], ...]
  for (var i = 0; i < textLines.length; i++)
  {
    var line = _analyzeLine(textLines[i], attribLines[i], apool);
    var lineContent = getLineTXT(line.text, line.aline);
    if(line.listTypeName == "bullet"){
      lineContent = "* " + lineContent; // add a bullet
    }
    if(line.listLevel > 0){
      for (var j = line.listLevel - 1; j >= 0; j--){
        pieces.push('\t');
      }
      if(line.listTypeName == "number"){
        pieces.push(line.listLevel + ". ");
        // This is bad because it doesn't truly reflect what the user
        // sees because browsers do magic on nested

s
      }
      pieces.push(lineContent, '\n');
    }else{
      pieces.push(lineContent, '\n');
    }
  }

  return pieces.join('');
}
exports.getTXTFromAtext = getTXTFromAtext;

exports.getPadTXTDocument = function (padId, revNum, noDocType, callback)
{
  padManager.getPad(padId, function (err, pad)
  {
    if(ERR(err, callback)) return;

    getPadTXT(pad, revNum, function (err, html)
    {
      if(ERR(err, callback)) return;
      callback(null, html);
    });
  });
}

function _encodeWhitespace(s) {
  return s.replace(/[^\x21-\x7E\s\t\n\r]/g, function(c)
  {
    return "&#" +c.charCodeAt(0) + ";"
  });
}
<|endoftext|>


<commit_before>applicantControllers.controller('GraphsCtrl', ['$scope', 'Graphs',
	function($scope, graphs) {

		$scope.queries = [$scope.languages, $scope.etl, $scope.web,
		$scope.mobile, $scope.db, $scope.bigData];

		var fields = ['languages', 'etl', 'web', 'mobile', 'db', 'bigData'];
		var ids = ['Language', 'ETL', 'Web', 'Mobile', 'Databases', 'Big'];

		$scope.queries.forEach(function(value, index) {
			$scope.queries[index] = graphs.query ({
				field: fields[index]
			});

			$scope.queries[index].$promise.then(function(data) {
				console.log(index);
				console.log(data);
				displayGraph(data, ids[index]);
			});
		});

		function displayGraph(data, id) {
			var labels = data.map(function(index) {
				return index.key;
			});

			var count = data.map(function(index) {
				return index.doc_count;
			});

			var ctx = document.getElementById(id);

			var blues = [
			'#E3F2FD',
			'#BBDEFB',
			'#90CAF9',
			'#64B5F6',
			'#42A5F5',
			'#2196F3',
			'#1E88E5',
			'#1976D2',
			'#1565C0',
			'#0D47A1'
			];

			var reds = [
			'#FFEBEE',
			'#FFCDD2',
			'#EF9A9A',
			'#E57373',
			'#EF5350',
			'#F44336',
			'#E53935',
			'#D32F2F',
			'#C62828',
			'#B71C1C'
			];

			var greens = [
			'#E8F5E9',
			'#C8E6C9',
			'#A5D6A7',
			'#81C784',
			'#66BB6A',
			'#4CAF50',
			'#43A047',
			'#388E3C',
			'#2E7D32',
			'#1B5E20'
			];

			var oranges = [
			'#FFF350',
			'#FFE0B2',
			'#FFCC80',
			'#FFB74D',
			'#FFA726',
			'#FF9800',
			'#FB8C00',
			'#F87C00',
			'#EF6C00',
			'#E65100'
			];

			var yellows = [
			'#FFFDE7',
			'#FFF9C4',
			'#FFF59D',
			'#FFF176',
			'#FFEE58',
			'#FFEB3B',
			'#FDD835',
			'#FBC02D',
			'#F9A825',
			'#F57F17'
			];

			var purples = [
			'#F3E5F5',
			'#E1BEE7',
			'#CE93D8',
			'#BA68C8',
			'#AB47BC',
			'#9C27B0',
			'#8E24AA',
			'#7B1FA2',
			'#6A1B9A',
			'#4A148C'
			];

			var pinks = [
			'#FCE4EC',
			'#F8BBD0',
			'#F48FB1',
			'#F06292',
			'#EC407A',
			'#E91E63',
			'#D81B60',
			'#C2185B',
			'#AD1457',
			'#880E4F'
			];

			var teals = [
			'#E0F2F1',
			'#B2DFDB',
			'#80CBC4',
			'#4DB6AC',
			'#26A69A',
			'#009688',
			'#00897B',
			'#00796B',
			'#00695C',
			'#004D40'
			];

			if( id == 'Language'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: reds,
							borderColor: reds,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'ETL'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: teals,
							borderColor: teals,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'Web'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: yellows,
							borderColor: yellows,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'Mobile'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: greens,
							borderColor: greens,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'Databases'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: blues,
							borderColor: blues,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'Big'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: purples,
							borderColor: purples,
							borderWidth: 1
						}]
					}
				});
			}

		}
	}
]);
<commit_msg>conflict<commit_after>applicantControllers.controller('GraphsCtrl', ['$scope', 'Graphs',
	function($scope, graphs) {

		$scope.queries = [$scope.languages, $scope.etl, $scope.web,
		$scope.mobile, $scope.db, $scope.bigData];

		var fields = ['languages', 'etl', 'web', 'mobile', 'db', 'bigData'];
		var ids = ['Language', 'ETL', 'Web', 'Mobile', 'Databases', 'Big'];

		$scope.queries.forEach(function(value, index) {
			$scope.queries[index] = graphs.query ({
				field: fields[index]
			});

			$scope.queries[index].$promise.then(function(data) {
				displayGraph(data, ids[index]);
			});
		});

		function displayGraph(data, id) {
			var labels = data.map(function(index) {
				return index.key;
			});

			var count = data.map(function(index) {
				return index.doc_count;
			});

			var ctx = document.getElementById(id);

			var blues = [
			'#E3F2FD',
			'#BBDEFB',
			'#90CAF9',
			'#64B5F6',
			'#42A5F5',
			'#2196F3',
			'#1E88E5',
			'#1976D2',
			'#1565C0',
			'#0D47A1'
			];

			var reds = [
			'#FFEBEE',
			'#FFCDD2',
			'#EF9A9A',
			'#E57373',
			'#EF5350',
			'#F44336',
			'#E53935',
			'#D32F2F',
			'#C62828',
			'#B71C1C'
			];

			var greens = [
			'#E8F5E9',
			'#C8E6C9',
			'#A5D6A7',
			'#81C784',
			'#66BB6A',
			'#4CAF50',
			'#43A047',
			'#388E3C',
			'#2E7D32',
			'#1B5E20'
			];

			var oranges = [
			'#FFF350',
			'#FFE0B2',
			'#FFCC80',
			'#FFB74D',
			'#FFA726',
			'#FF9800',
			'#FB8C00',
			'#F87C00',
			'#EF6C00',
			'#E65100'
			];

			var yellows = [
			'#FFFDE7',
			'#FFF9C4',
			'#FFF59D',
			'#FFF176',
			'#FFEE58',
			'#FFEB3B',
			'#FDD835',
			'#FBC02D',
			'#F9A825',
			'#F57F17'
			];

			var purples = [
			'#F3E5F5',
			'#E1BEE7',
			'#CE93D8',
			'#BA68C8',
			'#AB47BC',
			'#9C27B0',
			'#8E24AA',
			'#7B1FA2',
			'#6A1B9A',
			'#4A148C'
			];

			var pinks = [
			'#FCE4EC',
			'#F8BBD0',
			'#F48FB1',
			'#F06292',
			'#EC407A',
			'#E91E63',
			'#D81B60',
			'#C2185B',
			'#AD1457',
			'#880E4F'
			];

			var teals = [
			'#E0F2F1',
			'#B2DFDB',
			'#80CBC4',
			'#4DB6AC',
			'#26A69A',
			'#009688',
			'#00897B',
			'#00796B',
			'#00695C',
			'#004D40'
			];

			if( id == 'Language'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: reds,
							borderColor: reds,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'ETL'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: teals,
							borderColor: teals,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'Web'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: yellows,
							borderColor: yellows,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'Mobile'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: greens,
							borderColor: greens,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'Databases'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: blues,
							borderColor: blues,
							borderWidth: 1
						}]
					}
				});
			}

			if( id == 'Big'){
				var chart = new Chart(ctx, {
					type: 'pie',
					data: {
						labels: labels,
						datasets: [{
							label: '# of Votes',
							data: count,
							backgroundColor: purples,
							borderColor: purples,
							borderWidth: 1
						}]
					}
				});
			}

		}
	}
]);
<|endoftext|>


<commit_before>/* global require */

var $ = require('jquery'),
  pryv = require('pryv');

var defaultPermissions = [{
  streamId : 'diary',
  defaultName : 'Journal',
  level : 'read'
}];

window.onload = function () {
  var $permissionsArea = $('#permissionsArea'),
    $clearButton= $('#clearPermissionArea'),
    $addPermission = $('#addPermission'),
    $regUrlText = $('#registerUrlText'),
    $submitButton = $('#submitButton'),
    $masterToken = $('#masterToken');

  permissionsAreaState(false);
  $regUrlText.text(getRegisterURL());
  $masterToken.prop('checked', false);
  $permissionsArea.val(JSON.stringify(defaultPermissions, null, '  '));

  $masterToken.click(masterTokenManagement);
  $addPermission.click(addPermission);
  $submitButton.click(requestAccess);
  $clearButton.click(clearPermissions);

  // Toggle dev options
  toggleDevOptions();
  $('#toggleDev').click(toggleDevOptions);
};

/**
 * change view and permissions to fit a master token app access
 */
function masterTokenManagement() {
  var $permissionsViewInactive = $('#permissionsViewInactive'),
    $permissionsArea = $('#permissionsArea'),
    masterTokenPermissions = [{
      streamId: '*',
      level: 'manage'
    }];

  if ($('#masterToken:checked').length === 1) {
    try {
      defaultPermissions = JSON.parse($permissionsArea.val());
      $permissionsArea.val(JSON.stringify(masterTokenPermissions, null, '  '));
      permissionsAreaState(true);
      $permissionsViewInactive.css({'display': 'unset'});
    } catch (err) {
      logToConsole(err);
    }
  } else {
    $permissionsViewInactive.css({'display': 'none'});
    permissionsAreaState(false);
    $permissionsArea.val(JSON.stringify(defaultPermissions, null, '  '));
  }
}

/**
 * disable/activate inputs for permissions area
 * @param state {Boolean}
 */
function permissionsAreaState(state) {
  var $addPermission = $('#addPermission'),
    $permissionsArea = $('#permissionsArea'),
    $clearButton= $('#clearPermissionArea'),
    $streamId = $('#streamId'),
    $level = $('#level'),
    $name = $('#name');

  $permissionsArea.prop('disabled', state);
  $addPermission.prop('disabled', state);
  $clearButton.prop('disabled', state);
  $streamId.prop('disabled', state);
  $level.prop('disabled', state);
  $name.prop('disabled', state);
}

/**
 * manage the add permission button
 */
function addPermission() {
  var $permissionsArea = $('#permissionsArea'),
    $streamId = $('#streamId'),
    $level = $('#level option:selected'),
    $name = $('#name'),
    permission;

  if (!$streamId.val()) {
    return logToConsole('Error: A streamId is required to submit a permission.');
  }
  if (!$level.val()) {
    return logToConsole('Error: A level is required to submit a permission.');
  }

  if ($name.val()) {
    permission = [{
      streamId: $streamId.val(),
      defaultName: $name.val(),
      level: $level.val()
    }];
  } else {
    permission = [{
      streamId: $streamId.val(),
      level: $level.val()
    }];
  }

  if ($permissionsArea.val()) {
    $permissionsArea.val(
      $permissionsArea.val().addNewPermission(JSON.stringify(permission, null, '  '))
    );
  } else {
    $permissionsArea.val(JSON.stringify(permission, null, '  '));
  }

  if ($permissionsArea.length) {
    $permissionsArea.scrollTop($permissionsArea[0].scrollHeight - $permissionsArea.height());
  }
}

String.prototype.addNewPermission = function(newPermission) {
  return this.replace('\n]', ',\n' + newPermission.substring(2, newPermission.length ));
};

/**
 * manage the clear permissions button
 */
function clearPermissions() {
  var $permissionsArea = $('#permissionsArea');

  $permissionsArea.val('');
}

/**
 * prints to console a message/error
 * @param text {String}
 */
function logToConsole(text) {
  var $console = $('#console');

  $console.append(text + '\n');
  if($console.length) {
    $console.scrollTop($console[0].scrollHeight - $console.height());
  }
}

/**
 * retrieve the registerURL from URL parameters
 */
function getRegisterURL() {
  return pryv.utility.urls.parseClientURL().parseQuery()['pryv-reg'];
}

/**
 * process the form and request access
 */
function requestAccess() {
  var customRegisterUrl = getRegisterURL(),
    $username = $('#usernameArea'),
    $token = $('#tokenArea');

  if (customRegisterUrl) {
    pryv.Auth.config.registerURL = {host: customRegisterUrl, 'ssl': true};
  }

  // Rec-la config, only for dev
  if ($('#reclaDevel').val().length > 0) {
    pryv.Access.config.reclaDevel = $('#reclaDevel').val();
  } else {
    pryv.Access.config.reclaDevel = false;
  }
  pryv.Access._init(); //because we change the config

  var settings = {
    requestingAppId: false,
    languageCode: false,
    permissionsArea: false,
    returnURL: false,
    callbacks: {}
  };
  settings.requestingAppId = $('#requestingAppId').val();

  // Dev and advanced settings
  settings.languageCode = $('#languageCode option:selected').val();
  settings.returnURL = $('#returnURL').val();
  settings.oauthState = $('#oauthState').val();
  settings.forcePolling = $('#forcePolling').attr('checked') === 'checked';

  try {
    settings.requestedPermissions = JSON.parse($('#permissionsArea').val());
    settings.spanButtonID = 'pryvButton';

    settings.callbacks.initialization = function () {
      logToConsole('Access Requested.');
    };
    settings.callbacks.needSignin = function () {
      logToConsole('Access parameters validated, please sign in.');
    };
    settings.callbacks.accepted = function (username, appToken) {
      logToConsole(
        'Access generation successful, please copy the token to be used with ' +
        'the associated username.');
      $username.text(username);
      $token.text(appToken);
    };
    settings.callbacks.refused = function (reason) {
      logToConsole('Access refused by user' + reason);
    };
    settings.callbacks.error = function (code, message) {
      logToConsole('Error: code=' + code + ', message: ' + message);
    };

    pryv.Auth.setup(settings);
  } catch (e) {
    logToConsole('Error in Access params: ' + e);
  }
}

function toggleDevOptions() {
  $('#languageCode').parent().parent().toggle();
  $('#returnURL').parent().parent().toggle();
  $('#oauthState').parent().parent().toggle();
  $('#forcePolling').parent().parent().toggle();
  $('#reclaDevel').parent().parent().toggle();
  }<commit_msg>Adapt old code for new javascript lib<commit_after>/* global require */

var $ = require('jquery'),
  pryv = require('pryv');

var defaultPermissions = [{
  streamId : 'diary',
  defaultName : 'Journal',
  level : 'read'
}];

window.onload = function () {
  var $permissionsArea = $('#permissionsArea'),
    $clearButton= $('#clearPermissionArea'),
    $addPermission = $('#addPermission'),
    $regUrlText = $('#registerUrlText'),
    $submitButton = $('#submitButton'),
    $masterToken = $('#masterToken');

  permissionsAreaState(false);
  $regUrlText.text(getRegisterURL());
  $masterToken.prop('checked', false);
  $permissionsArea.val(JSON.stringify(defaultPermissions, null, '  '));

  $masterToken.click(masterTokenManagement);
  $addPermission.click(addPermission);
  $submitButton.click(requestAccess);
  $clearButton.click(clearPermissions);

  // Toggle dev options
  toggleDevOptions();
  $('#toggleDev').click(toggleDevOptions);
};

/**
 * change view and permissions to fit a master token app access
 */
function masterTokenManagement() {
  var $permissionsViewInactive = $('#permissionsViewInactive'),
    $permissionsArea = $('#permissionsArea'),
    masterTokenPermissions = [{
      streamId: '*',
      level: 'manage'
    }];

  if ($('#masterToken:checked').length === 1) {
    try {
      defaultPermissions = JSON.parse($permissionsArea.val());
      $permissionsArea.val(JSON.stringify(masterTokenPermissions, null, '  '));
      permissionsAreaState(true);
      $permissionsViewInactive.css({'display': 'unset'});
    } catch (err) {
      logToConsole(err);
    }
  } else {
    $permissionsViewInactive.css({'display': 'none'});
    permissionsAreaState(false);
    $permissionsArea.val(JSON.stringify(defaultPermissions, null, '  '));
  }
}

/**
 * disable/activate inputs for permissions area
 * @param state {Boolean}
 */
function permissionsAreaState(state) {
  var $addPermission = $('#addPermission'),
    $permissionsArea = $('#permissionsArea'),
    $clearButton= $('#clearPermissionArea'),
    $streamId = $('#streamId'),
    $level = $('#level'),
    $name = $('#name');

  $permissionsArea.prop('disabled', state);
  $addPermission.prop('disabled', state);
  $clearButton.prop('disabled', state);
  $streamId.prop('disabled', state);
  $level.prop('disabled', state);
  $name.prop('disabled', state);
}

/**
 * manage the add permission button
 */
function addPermission() {
  var $permissionsArea = $('#permissionsArea'),
    $streamId = $('#streamId'),
    $level = $('#level option:selected'),
    $name = $('#name'),
    permission;

  if (!$streamId.val()) {
    return logToConsole('Error: A streamId is required to submit a permission.');
  }
  if (!$level.val()) {
    return logToConsole('Error: A level is required to submit a permission.');
  }

  if ($name.val()) {
    permission = [{
      streamId: $streamId.val(),
      defaultName: $name.val(),
      level: $level.val()
    }];
  } else {
    permission = [{
      streamId: $streamId.val(),
      level: $level.val()
    }];
  }

  if ($permissionsArea.val()) {
    $permissionsArea.val(
      $permissionsArea.val().addNewPermission(JSON.stringify(permission, null, '  '))
    );
  } else {
    $permissionsArea.val(JSON.stringify(permission, null, '  '));
  }

  if ($permissionsArea.length) {
    $permissionsArea.scrollTop($permissionsArea[0].scrollHeight - $permissionsArea.height());
  }
}

String.prototype.addNewPermission = function(newPermission) {
  return this.replace('\n]', ',\n' + newPermission.substring(2, newPermission.length ));
};

/**
 * manage the clear permissions button
 */
function clearPermissions() {
  var $permissionsArea = $('#permissionsArea');

  $permissionsArea.val('');
}

/**
 * prints to console a message/error
 * @param text {String}
 */
function logToConsole(text) {
  var $console = $('#console');

  $console.append(text + '\n');
  if($console.length) {
    $console.scrollTop($console[0].scrollHeight - $console.height());
  }
}

/**
 * retrieve the registerURL from URL parameters
 */
function getRegisterURL() {
  return pryv.utility.urls.parseClientURL().parseQuery()['pryv-reg'];
}

/**
 * process the form and request access
 */
function requestAccess() {
  var customRegisterUrl = getRegisterURL(),
    $username = $('#usernameArea'),
    $token = $('#tokenArea');

  if (customRegisterUrl) {
    pryv.Auth.config.registerURL = {host: customRegisterUrl, 'ssl': true};
  }

  // Rec-la config, only for dev
  if ($('#reclaDevel').val().length > 0) {
    pryv.Auth.config.reclaDevel = $('#reclaDevel').val();
  } else {
    pryv.Auth.config.reclaDevel = false;
  }
  pryv.Auth._init(); //because we change the config

  var settings = {
    requestingAppId: false,
    languageCode: false,
    permissionsArea: false,
    returnURL: false,
    callbacks: {}
  };
  settings.requestingAppId = $('#requestingAppId').val();

  // Dev and advanced settings
  settings.languageCode = $('#languageCode option:selected').val();
  settings.returnURL = $('#returnURL').val();
  settings.oauthState = $('#oauthState').val();
  settings.forcePolling = $('#forcePolling').attr('checked') === 'checked';

  try {
    settings.requestedPermissions = JSON.parse($('#permissionsArea').val());
    settings.spanButtonID = 'pryvButton';

    settings.callbacks.initialization = function () {
      logToConsole('Access Requested.');
    };
    settings.callbacks.needSignin = function () {
      logToConsole('Access parameters validated, please sign in.');
    };
    settings.callbacks.accepted = function (username, appToken) {
      logToConsole(
        'Access generation successful, please copy the token to be used with ' +
        'the associated username.');
      $username.text(username);
      $token.text(appToken);
    };
    settings.callbacks.refused = function (reason) {
      logToConsole('Access refused by user' + reason);
    };
    settings.callbacks.error = function (code, message) {
      logToConsole('Error: code=' + code + ', message: ' + message);
    };

    pryv.Auth.setup(settings);
  } catch (e) {
    logToConsole('Error in Access params: ' + e);
  }
}

function toggleDevOptions() {
  $('#languageCode').parent().parent().toggle();
  $('#returnURL').parent().parent().toggle();
  $('#oauthState').parent().parent().toggle();
  $('#forcePolling').parent().parent().toggle();
  $('#reclaDevel').parent().parent().toggle();
  }<|endoftext|>


<commit_before>var config = require('../config'),
_ = require('underscore')._,
moment = require('moment'),
express = require('express'),
twilio = require('twilio'),
Cleverbot = require('cleverbot-node');

var cleverbot = new Cleverbot();
var express = require('express');
var app = express();
var twilioClient = new twilio.RestClient(config.accountSid, config.authToken);

app.use(express.urlencoded());
app.post('/cleverbot', function(req, res){

  var timestamp = moment().format("YYYY/MM/DD HH:mm:ss");
  if (!_.isUndefined(getQueryParam("To", req)) &&
  	  !_.isUndefined(getQueryParam("From", req)) &&
  	  !_.isUndefined(getQueryParam("Body", req))){

    text(getQueryParam("Body", req), getQueryParam("From", req));

    console.log(timestamp);
  	console.log("To: " + getQueryParam("To", req));
  	console.log("From: " + getQueryParam("From", req));
  	console.log("Text: " + getQueryParam("Body", req));
  	console.log();
  }

  res.send("Post ping recieved at " + timestamp);
});

var server = app.listen(config.port, function() {
    console.log('Listening on port %d', server.address().port);
});

function text(message, phoneNumber) {

	var min = 0.3; // in minutes.
	var max = 5;

	cleverbot.write(message, function(response){

		setTimeout( function(){

			twilioClient.sms.messages.create({
				To: phoneNumber,
				From: config.twilioNumber,
				Body: response,
			}, function(err, message) {
				if (err) throw err;
				console.log("Sent to " + phoneNumber + ": " + response);
			});

		}, 1);
		// }, _.random(min, max) * 1000 * 60);
	});
}

function getQueryParam(name, req) {
    return req.body[name];
}<commit_msg>TEST: Trying to get twilio to send a message back<commit_after>var config = require('../config'),
_ = require('underscore')._,
moment = require('moment'),
express = require('express'),
twilioClient = require('twilio')(config.accountSid, config.authToken),
Cleverbot = require('cleverbot-node');

var cleverbot = new Cleverbot();
var express = require('express');
var app = express();

app.use(express.urlencoded());
app.post('/cleverbot', function(req, res){

  var timestamp = moment().format("YYYY/MM/DD HH:mm:ss");
  if (!_.isUndefined(getQueryParam("To", req)) &&
  	  !_.isUndefined(getQueryParam("From", req)) &&
  	  !_.isUndefined(getQueryParam("Body", req))){

    text(getQueryParam("Body", req), getQueryParam("From", req));

    console.log(timestamp);
  	console.log("To: " + getQueryParam("To", req));
  	console.log("From: " + getQueryParam("From", req));
  	console.log("Text: " + getQueryParam("Body", req));
  	console.log();
  }

  res.send("Post ping recieved at " + timestamp);
});

var server = app.listen(config.port, function() {
    console.log('Listening on port %d', server.address().port);
});

function text(message, phoneNumber) {

	var min = 0.3; // in minutes.
	var max = 5;

	cleverbot.write(message, function(response){

		setTimeout( function(){
      console.log("should have sent");
			twilioClient.sendMessage({
				to: phoneNumber,
				from: config.twilioNumber,
				body: response,
			}, function(err, message) {
				if (err) throw err;
				console.log("Sent to " + phoneNumber + ": " + response);
			});

		}, 1);
		// }, _.random(min, max) * 1000 * 60);
	});
}

function getQueryParam(name, req) {
    return req.body[name];
}

<|endoftext|>