<commit_before>(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.lispish = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
 * Returns the car of a cons
 * @param  {cons} cons cons to be car'd
 * @return {*}      car value of the given cons
 */
function car(cons) {
    return cons.car;
}

module.exports = car;
},{}],2:[function(require,module,exports){
/**
 * Returns the cdr of a cons
 * @param  {cons} cons cons to be cdr'd
 * @return {*}      cdr value of the given cons
 */
function cdr(cons) {
    return cons.cdr;
}

module.exports = cdr;
},{}],3:[function(require,module,exports){
var cdr = require('./cdr');
var car = require('./car');
var range = require('../list/range');
var compose = require('../fun/compose');

function permute(S) {

    function swap(s, x, y) {
        var min = Math.min(x, y);
        var max = Math.max(x, y);
        return s.slice(0, min) + s[max] + s.slice(min + 1, max) + s[min] + s.slice(max + 1);
    }

    // TODO: Make more funcctional
    function generate(n, S) {
        var result = [];
        if (n === 1) {
            return S;
        } else {
            for (var i = 0; i < n; i += 1) {
                result = result.concat(generate(n - 1, S));
                if (n % 2 === 0) {
                    S = swap(S, i, n - 1);
                } else {
                    S = swap(S, 0, n - 1);
                }
            }
        }
        return result;
    }
    return generate(S.length, S);
}

// In order to provide car/cdr composition shorthand
// (e.g. caaar, cadadr, etc.), we define properties
// on the cons prototype for many of these permutions.
// This is a bit of a hack, as default getters aren't
// supported in ES5. Proxies would allow us to achieve
// this much more elegantly, but unfortunately they are
// not well supported.
// TODO: Make more functional
for (var i = 0; i < 5; i++) {
    for (var j = 0; j < 5; j++) {
        var Ds = (new Array(i + 1).join('d'));
        var As = (new Array(j + 1).join('a'));
        var permutations = permute(As + Ds);
        for (var p = 0, len = permutations.length; p < len; p++) {
            var perm = permutations[p];
            if (perm !== 'a' && perm !== 'd' && perm.length < 5 && !exports.hasOwnProperty('c' + perm + 'r')) {
                exports[('c' + perm + 'r')] = (function(perm) {
                    function helper(perm) {
                        if (perm.length === 0) {
                            return function(i){return i;};
                        } else {
                            if (perm[0] === 'a') {
                                return compose(helper(perm.slice(1)), car);
                            } else if (perm[0] === 'd') {
                                return compose(helper(perm.slice(1)), cdr);
                            }
                        }
                    }
                    return helper(perm);
                })(perm);
            }
        }
    }
}
},{"../fun/compose":10,"../list/range":25,"./car":1,"./cdr":2}],4:[function(require,module,exports){
/**
 * Returns an immutable cons pair consisting
 * of a and b
 * @param  {*} a car value
 * @param  {*} b cdr value
 * @return {cons}
 */
function cons(a, b) {
    return Object.freeze(
        Object.defineProperty(
            Object.defineProperty(
                Object.create(null), 'car', {
                    value: a
                }
            ), 'cdr', {
                value: b
            }
        )
    );
}

module.exports = cons;
},{}],5:[function(require,module,exports){
var cons = require('./cons');
var pair = require('./pair');
var cdr = require('./cdr');
var car = require('./car');

/**
 * Returns a boolean indicating whether to two given parameters
 * are equal. If the paramters are cons pairs, equality is determined
 * by the equality of their members.
 * @param  {*} a
 * @param  {*} b
 * @return {boolean}
 */
function equal(a, b){
    // If a is a pair and b is not (or vice versa),
    // these cannot be equal.
    if (pair(a) !== pair(b)){
        return false;
    }
    // If car(a) is a pair and car(b) is not (or vice versa),
    // these cannot be equal.
    if (pair(a) && pair(car(a)) !== pair(b) && pair(car(b))){
        return false;
    }
    // If cdr(a) is a pair and cdr(b) is not (or vice versa),
    // these cannot be equal.
    if (pair(a) && pair(cdr(a)) !== pair(b) && pair(cdr(b))){
        return false;
    }
    // If a is a pair (which, if we have reached this point,
    // means that b must also be a pair), recurse.
    // Otherwise, test the equality of a and b directly.
    if (pair(a)){
        return equal(car(a), car(b)) && equal(cdr(a), cdr(b));
    } else {
        return a === b;
    }
}

module.exports = equal;
},{"./car":1,"./cdr":2,"./cons":4,"./pair":6}],6:[function(require,module,exports){
/**
 * Returns a boolean indicating whether the given parameter is a cons pair.
 * @param  {*} c
 * @return {boolean}
 */
function pair(c){
    return c !== null && typeof c === 'object' && 'car' in c && 'cdr' in c;
}

module.exports = pair;

},{}],7:[function(require,module,exports){
var cons = require('./cons');
var car = require('./car');
var cdr = require('./cdr');
var pair = require('./pair');

/**
 * Returns a string representation of a cons.
 * cons prefix, suffix, and separator can all
 * optionally be defined by the user.
 * @param  {cons} c    cons to be printed
 * @param  {(Object|undefined)} options Optional options object
 * @return {string}      String representation of the given cons
 */
// TODO: Make more functional
function print(c, options) {
    var opts = options || {};
    prefix = typeof opts.prefix !== 'undefined' ? opts.prefix : '(';
    suffix = typeof opts.suffix !== 'undefined' ? opts.suffix : ')';
    separator = typeof opts.separator !== 'undefined' ? opts.separator : ',';

    function printHelper(c, separator) {
        var cdrL = cdr(c);
        var carL = car(c);
        var cdrResult = '';
        var carResult = '';
        if (pair(carL)) {
            carResult = printHelper(carL, separator);
        } else if (carL !== null) {
            carResult = carL.toString();
        }
        if (pair(cdrL)) {
            cdrResult = printHelper(cdrL, separator);
        } else if (cdrL !== null) {
            cdrResult = cdrL.toString();
        }
        if (carResult === '' || cdrResult === '') {
            separator = '';
        }
        return prefix + carResult + separator + cdrResult + suffix;
    }
    return printHelper(c, separator);
}

module.exports = print;
},{"./car":1,"./cdr":2,"./cons":4,"./pair":6}],8:[function(require,module,exports){
var apply = require('./apply');
var args = require('../helpers/args');
var list = require('../list/list');

function Y(f) {
    return f((function(h) {
        return function() {
            return apply(f(h(h)), list(args(arguments)));
        };
    })(function(h) {
        return function() {
            return apply(f(h(h)), list(args(arguments)));
        };
    }));
}

module.exports = Y;
},{"../helpers/args":12,"../list/list":20,"./apply":9}],9:[function(require,module,exports){
var cdr = require('../cons/cdr');
var car = require('../cons/car');

/**
 * Call the given function with the list of arguments supplied.
 * @param  {Function} fn
 * @param  {cons}   args
 * @return {*}
 */
function apply(fn, args){
    function helper(fn, args){
        if (cdr(args) === null){
            return fn(car(args));
        } else {
            return apply(fn.bind(null, car(args)), cdr(args));
        }
    }
    return helper(fn, args);
}

module.exports = apply;
},{"../cons/car":1,"../cons/cdr":2}],10:[function(require,module,exports){
/**
 * Compose functions a and b
 * @param  {Function} a Outer function
 * @param  {Function} b Inner function
 * @return {Function}   Composed function
 */
function compose(a, b) {
    return function(c) {
        return a(b(c));
    };
}

module.exports = compose;
},{}],11:[function(require,module,exports){
var cons = require('../cons/cons');
var apply = require('./apply');

/**
 * Curry the given function. If the number of expected parameters
 * is passed explicitly, this will be used. Otherwise, the arity of the
 * function passed in will be used.
 * @param  {Function} fn
 * @param  {integer}   arity
 * @return {Function}
 */
function curry(fn, arity){
    function helper(fn, arity, args){
        if (arity === 0){
            return apply(fn, args);
        } else {
            return function(arg){
                return helper(fn, arity - 1, cons(arg, args));
            };
        }
    }
    if (typeof arity === 'undefined'){
        return helper(fn, fn.length, null);
    } else {
        return helper(fn, arity, null);
    }
}
module.exports = curry;
},{"../cons/cons":4,"./apply":9}],12:[function(require,module,exports){
/**
 * Given an array-like, returns a real array.
 * @param  {Array-like} args
 * @return {Arrau}
 */
function args(args){
    return Array.prototype.slice.call(args);
}

module.exports = args;
},{}],13:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Returns a new list that is the result
 * of concatenating L2 onto the end of L1;
 * @param  {cons} L1
 * @param  {cons} L2
 * @return {cons}
 */
function concat(L1, L2){
    if (L1 === null){
        return L2;
    } else {
        return cons(car(L1), concat(cdr(L1), L2));
    }
}

module.exports = concat;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],14:[function(require,module,exports){
var equal = require('../cons/equal');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Returns true if the specified value is equal to at least one element of the given list.
 * @param  {cons} L
 * @param  {*} a
 * @return {Boolean}
 */
function contains(L, a){
    if (L === null){
        return false;
    } else {
        if (equal(car(L), a)){
            return true;
        } else {
            return contains(cdr(L), a);
        }
    }
}

module.exports = contains;
},{"../cons/car":1,"../cons/cdr":2,"../cons/equal":5}],15:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Given a cons list, returns a new cons list
 * with the first item removed
 * @param  {cons} L
 * @return {cons}
 */
function dequeue (L) {
    return cdr(L);
}

module.exports = dequeue;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],16:[function(require,module,exports){
var cons = require('../cons/cons');

/**
 * Given a cons list and a value, returns a new cons list
 * with the value appended to the front of the list.
 * @param  {cons} L
 * @param  {*} val
 * @return {cons}
 */
function enqueue (L, val) {
    return cons(val, L);
}

module.exports = enqueue;
},{"../cons/cons":4}],17:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Returns true if every element in the list passes the
 * test implemented by the provided callback function.
 * The callback function is passed the current value
 * and the current index in the list.
 * @param  {cons}   L
 * @param  {Function} fn
 * @return {boolean}
 */
function every(L, fn){
    function helper(L, fn, idx){
        if (L === null){
            return true;
        } else {
            if (!fn(car(L), idx)){
                return false;
            } else {
                return helper(cdr(L), fn, idx + 1);
            }
        }
    }
    return helper(L, fn, 0);
}

module.exports = every;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],18:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Returns a new cons list consisting of the values
 * of the given cons list for which the the callback function,
 * called passing the value of each item in the list in turn,
 * evaluated to true.
 * @param  {cons}   L
 * @param  {Function} fn
 * @return {cons}
 */
function filter(L, fn){
    if (L === null){
        return L;
    } if (cdr(L) === null){
        if (fn(car(L))){
            return cons(car(L), null);
        } else {
            return null;
        }
    } else {
        if (fn(car(L))){
            return cons(car(L), filter(cdr(L), fn));
        } else {
            return filter(cdr(L), fn);
        }
    }
}

module.exports = filter;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],19:[function(require,module,exports){
var cdr = require('../cons/cdr');
var reduce = require('./reduce');

/**
 * Returns the length of the given list
 * @param  {cons} l list
 * @return {integer}   length of the given list.
 */
function length(L){
    return reduce(L, function(curr, acc){return acc + 1;}, 0);
}

module.exports = length;
},{"../cons/cdr":2,"./reduce":26}],20:[function(require,module,exports){
var cons = require('../cons/cons');
var args = require('../helpers/args');

/**
 * Returns a cons list constructed from the given parameters.
 * @return {cons}
 */
function list(){
    function helper(args){
        if (args.length === 0){
            return null;
        } else {
            if (Array.isArray(args[0])){
                return cons(helper(args[0]), helper(args.slice(1)));
            } else {
                return cons(args[0], helper(args.slice(1)));
            }
        }
    }
    if (arguments.length === 1 && Array.isArray(arguments[0])){
        return helper(arguments[0]);
    } else {
        return helper(args(arguments));
    }

}

module.exports = list;
},{"../cons/cons":4,"../helpers/args":12}],21:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Returns a new cons list with the results of calling the provided
 * function on every element.
 * @param  {cons}   L  cons list to be mapped
 * @param  {Function} fn callback function
 * @return {cons}
 */
function map(L, fn){
    if (L === null){
        return L;
    } else if (cdr(L) === null){
        return cons(fn(car(L)), null);
    } else {
        return cons(fn(car(L)), map(cdr(L), fn));
    }
}

module.exports = map;

},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],22:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Returns the value of the last item in a cons list.
 * @param  {cons} L
 * @return {*}
 */
function peek(L){
    if (L === null){
        return L;
    } if (cdr(L) === null){
        return car(L);
    } else {
        return peek(cdr(L));
    }
}

module.exports = peek;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],23:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');
var list = require('./list');

/**
 * Given a cons list, returns a new list with the last item removed.
 * @param  {cons} L
 * @return {cons}
 */
function pop(L){
    if (cdr(L) === null){
        return null;
    } else {
        return cons(car(L), pop(cdr(L)));
    }
}

module.exports = pop;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4,"./list":20}],24:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');
var list = require('./list');

/**
 * Given a cons list and a value, returns a new cons list
 * with the value appended to the end.
 * @param  {cons} L
 * @param  {*} val
 * @return {cons}
 */
function push(L, val){
    if (L === null){
        return cons(val, null);
    } else if (cdr(L) === null){
        return cons(car(L), cons(val, null));
    } else {
        return cons(car(L), push(cdr(L), val));
    }
}

module.exports = push;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4,"./list":20}],25:[function(require,module,exports){
var cons = require('../cons/cons');

/**
 * Returns a range list from n to m.
 * @param  {integer} n If m in not passed, the end of the range (exlusive),
 * otherwise the start of the range (inclusive).
 * @param  {(integer|undefined)} m If passed, the end of the range (exlusive).
 * @param {(integer|undefined)} step steps to take between each item in the range.
 * Defaults to 1.
 * @return {cons}   List from n to m.
 */
function range(m, n, step){
    function rangeHelper(m, n, step){
        if (m === n){
            return null;
        } else if (goodStep(m, n, step)) {
            return cons(m, rangeHelper(m+step, n, step));
        } else {
            return cons(m, null);
        }
    }
    function goodStep(start, stop, step){
        return (abs(stop - start) > abs(stop - (start + step)));
    }
    function stepHelper(m, n, step){
        if (typeof n === 'undefined'){
            if (goodStep(0, m, step)) {
                return rangeHelper(0, m, step);
            } else {
                return null;
            }
        } else {
            if (goodStep(m, n, step)) {
                return rangeHelper(m, n, step);
            } else {
                return null;
            }
        }
    }
    if (typeof step === 'undefined'){
        return stepHelper(m, n, 1);
    } else {
        return stepHelper(m, n, step);
    }
}

function abs(n){
    if (n < 0){
        return -n;
    } else {
        return n;
    }
}

module.exports = range;
},{"../cons/cons":4}],26:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Applies the given callback function against an accumulator
 * and each value of the cons list (from left-to-right) in order
 * to reduce it to a single value.
 * @param  {cons}   L
 * @param  {Function} fn
 * @param  {*}   acc
 * @return {cons}
 */
function reduce(L, fn, acc){
    function reduceHelper(L, fn, acc){
        if (L === null){
            return acc;
        } else if (cdr(L) === null){
            return fn(car(L), acc);
        } else {
            return reduce(cdr(L), fn, fn(car(L), acc));
        }
    }
    if (typeof acc === 'undefined'){
        return reduceHelper(L, fn, 0);
    } else {
        return reduceHelper(L, fn, acc);
    }
}

module.exports = reduce;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],27:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Returns a new list, which is a
 * reversed copy of the list passed in.
 * @param  {cons} L
 * @return {cons}
 */
function reverse(L){
    function helper(L, rev){
        if (L === null){
            return rev;
        } else {
            return helper(cdr(L), cons(car(L), rev));
        }
    }
    return helper(L, null);
}

module.exports = reverse;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],28:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

var length = require('../list/length');

/**
 * Given a list, returns a new list 'slice'.
 * If n is not passed in, the slice will be from m to
 * the end of the original list. If n is passed in,
 * then the slice will be from m to n. Invalid slices
 * (e.g. where m is larger than n) will return null.
 * @param  {cons} L
 * @param  {integer} m
 * @param  {(integer|undefined)} n
 * @return {cons}
 */
function slice(L, m, n){
    function sliceHelper(L, m, n, current){
        if (current === n || m >= n){
            return null;
        } else if (current >= m){
            return cons(car(L), sliceHelper(cdr(L), m, n, current + 1));
        } else {
            return sliceHelper(cdr(L), m, n, current + 1);
        }
    }
    if (typeof n === 'undefined'){
        return sliceHelper(L, m, length(L), 0);
    } else {
        return sliceHelper(L, m, n, 0);
    }
}

module.exports = slice;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4,"../list/length":19}],29:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Returns true if some element in the list passes the
 * test implemented by the provided callback function.
 * The callback function is passed the current value
 * and the current index in the list.
 * @param  {cons}   L
 * @param  {Function} fn
 * @return {boolean}
 */
function some(L, fn){
    function helper(L, fn, idx){
        if (L === null){
            return false;
        } else {
            if (fn(car(L), idx)){
                return true;
            } else {
                return helper(cdr(L), fn, idx + 1);
            }
        }
    }
    return helper(L, fn, 0);
}

module.exports = some;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],30:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

var length = require('../list/length');

/**
 * Given a list, returns a new, sorted list.
 * Optionally, a custom comparison function can be passed.
 * By default, ascending sort if performed.
 * @param  {cons}   L
 * @param  {Function} fn
 * @return {cons}
 */
function sort(L, fn){
    function merge(L1, L2, fn){
        if (L1 === null){
            return L2;
        } else if (L2 === null){
            return L1;
        } else if (fn(car(L1), car(L2))){
            return cons(car(L1), merge(cdr(L1), L2, fn));
        } else {
            return cons(car(L2), merge(L1, cdr(L2), fn));
        }
    }
    function split(L, lo, hi){
        function splitHelper(L, lo, hi, curr){
            if (curr < lo){
                return splitHelper(cdr(L), lo, hi, curr+1);
            } else if (curr === hi){
                return null;
            } else {
                return cons(car(L), splitHelper(cdr(L), lo, hi, curr+1));
            }
        }
        if (lo < hi && lo >= 0 && hi <= length(L)){
            return splitHelper(L, lo, hi, 0);
        } else {
            return null;
        }
    }
    function msort(L, fn, len){
        if (L === null || cdr(L) === null){
            return L;
        } else {
            return merge(
                msort(split(L, 0, Math.floor(len/2)), fn, Math.floor(len/2)),
                msort(split(L, Math.floor(len/2), len), fn, len - Math.floor(len/2)),
                fn
            );
        }
    }
    if (typeof fn === 'undefined'){
        return msort(L, function(a,b){return a < b;}, length(L));
    } else {
        return msort(L, fn, length(L));
    }
}

module.exports = sort;
},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4,"../list/length":19}],31:[function(require,module,exports){
var cons = require('../cons/cons');
var car = require('../cons/car');
var cdr = require('../cons/cdr');

/**
 * Given two cons lists, returns a new cons list composed of
 * cons pairs consisting of positionally determined elements
 * from each of the given lists. The resulting list will only contain
 * as many elements as contained in the shorter of the two lists.
 * @param  {cons} L1
 * @param  {cons} L2
 * @return {cons}
 */
function zip(L1, L2){
    if (L1 === null || L2 === null){
        return null;
    } else if (cdr(L1) === null || cdr(L2) === null){
        return null;
    } else {
        return cons(cons(car(L1), car(L2)), zip(cdr(L1), cdr(L2)));
    }
}

module.exports = zip;

},{"../cons/car":1,"../cons/cdr":2,"../cons/cons":4}],32:[function(require,module,exports){
// cons
exports.cons = Object.create(null);
exports.cons.cons = require('./cons/cons');
exports.cons.car = require('./cons/car');
exports.cons.cdr = require('./cons/cdr');
exports.cons.print = require('./cons/print');
exports.cons.equal = require('./cons/equal');
exports.cons.pair = require('./cons/pair');

var compositions = require('./cons/compositions');
Object.keys(compositions).forEach(function(key) {
    exports.cons[key] = compositions[key];
});

// helpers
exports.helpers = Object.create(null);
exports.helpers.args = require('./helpers/args');

// list
exports.list = Object.create(null);
exports.list.list = require('./list/list');
exports.list.length = require('./list/length');
exports.list.range = require('./list/range');
exports.list.map = require('./list/map');
exports.list.reduce = require('./list/reduce');
exports.list.filter = require('./list/filter');
exports.list.peek = require('./list/peek');
exports.list.push = require('./list/push');
exports.list.pop = require('./list/pop');
exports.list.zip = require('./list/zip');
exports.list.some = require('./list/some');
exports.list.every = require('./list/every');
exports.list.reverse = require('./list/reverse');
exports.list.concat = require('./list/concat');
exports.list.enqueue = require('./list/enqueue');
exports.list.dequeue = require('./list/dequeue');
exports.list.slice = require('./list/slice');
exports.list.sort = require('./list/sort');
exports.list.contains = require('./list/contains');

// fun
exports.fun = Object.create(null);
exports.fun.compose = require('./fun/compose');
exports.fun.apply = require('./fun/apply');
exports.fun.curry = require('./fun/curry');
exports.fun.Y = require('./fun/Y');
},{"./cons/car":1,"./cons/cdr":2,"./cons/compositions":3,"./cons/cons":4,"./cons/equal":5,"./cons/pair":6,"./cons/print":7,"./fun/Y":8,"./fun/apply":9,"./fun/compose":10,"./fun/curry":11,"./helpers/args":12,"./list/concat":13,"./list/contains":14,"./list/dequeue":15,"./list/enqueue":16,"./list/every":17,"./list/filter":18,"./list/length":19,"./list/list":20,"./list/map":21,"./list/peek":22,"./list/pop":23,"./list/push":24,"./list/range":25,"./list/reduce":26,"./list/reverse":27,"./list/slice":28,"./list/some":29,"./list/sort":30,"./list/zip":31}]},{},[32])(32)
});<commit_msg>Remove unneeded files<commit_after><|endoftext|>


<commit_before>import { countOccurences, runSSHCommand } from '../../../utils';
import { describe, it } from 'mocha';
import { expect } from 'chai';
import os from 'os';
import path from 'path';
import sh from 'shelljs';
const servers = require('../../../../tests/fixtures/servers');

sh.config.silent = false;

describe('module - mongo', function() {
  this.timeout(600000);

  describe('logs', () => {
    it('should pull logs from "meteor" vm', async () => {
      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));

      sh.exec('mup setup');
      const out = sh.exec('mup mongo logs');

      expect(out.code).to.be.equal(0);
      expect(countOccurences('MongoDB starting :', out.output)).to.be.equal(1);
      expect(countOccurences('db version', out.output)).to.be.equal(1);
    });
  });

  describe('setup', () => {
    it('should setup mongodb on "mongo" vm', async () => {
      const serverInfo = servers.mymongo;

      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));

      const out = sh.exec('mup mongo setup');

      expect(out.code).to.be.equal(0);

      expect(
        countOccurences('Setup Environment: SUCCESS', out.output)
      ).to.be.equal(1);
      expect(
        countOccurences('Copying Mongo Config: SUCCESS', out.output)
      ).to.be.equal(1);

      const sshOut = await runSSHCommand(serverInfo, 'tree -pufi /opt');

      expect(sshOut.code).to.be.equal(0);
      expect(countOccurences('mongodb.conf', sshOut.output)).to.be.equal(1);
    });
  });

  describe('start', () => {
    it('should start mongodb on "mongo" vm', async () => {
      const serverInfo = servers.mymongo;

      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));
      sh.exec('mup docker setup && mup mongo setup');

      const out = sh.exec('mup mongo start');
      expect(out.code).to.be.equal(0);

      expect(countOccurences('Start Mongo: SUCCESS', out.output)).to.be.equal(
        1
      );
      expect(
        (await runSSHCommand(serverInfo, 'nc -z -v -w5 localhost 27017')).code
      ).to.be.equal(0);
    });

    it('should allow configuring db name', async () => {
      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));
      const out = sh.exec('mup --config mup.db-name.js validate --show');

      expect(out.code).to.be.equal(0);

      expect(countOccurences('mongodb://mongodb:27017/test-db', out.output)).to.be.equal(
        1
      );
    });
  });

  describe('stop', () => {
    it('should stop mongodb on "mongo" vm', async () => {
      const serverInfo = servers.mymongo;

      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));
      sh.exec('mup docker setup && mup mongo setup && mup mongo start');

      const out = sh.exec('mup mongo stop');

      expect(out.code).to.be.equal(0);

      expect(countOccurences('Stop Mongo: SUCCESS', out.output)).to.be.equal(1);
      expect(
        (await runSSHCommand(serverInfo, 'nc -z -v -w5 localhost 27017')).code
      ).to.be.equal(1);
    });
  });
});
<commit_msg>Fix mongo test<commit_after>import { countOccurences, runSSHCommand } from '../../../utils';
import { describe, it } from 'mocha';
import { expect } from 'chai';
import os from 'os';
import path from 'path';
import sh from 'shelljs';
const servers = require('../../../../tests/fixtures/servers');

sh.config.silent = false;

describe('module - mongo', function() {
  this.timeout(600000);

  describe('logs', () => {
    it('should pull logs from "meteor" vm', async () => {
      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));

      sh.exec('mup setup');
      const out = sh.exec('mup mongo logs');

      expect(out.code).to.be.equal(0);
      expect(countOccurences('MongoDB starting :', out.output)).to.be.equal(1);
      expect(countOccurences('db version', out.output)).to.be.equal(1);
    });
  });

  describe('setup', () => {
    it('should setup mongodb on "mongo" vm', async () => {
      const serverInfo = servers.mymongo;

      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));

      const out = sh.exec('mup mongo setup');

      expect(out.code).to.be.equal(0);

      expect(
        countOccurences('Setup Environment: SUCCESS', out.output)
      ).to.be.equal(1);
      expect(
        countOccurences('Copying Mongo Config: SUCCESS', out.output)
      ).to.be.equal(1);

      const sshOut = await runSSHCommand(serverInfo, 'tree -pufi /opt');

      expect(sshOut.code).to.be.equal(0);
      expect(countOccurences('mongo-start-new.sh', sshOut.output)).to.be.equal(1);
    });
  });

  describe('start', () => {
    it('should start mongodb on "mongo" vm', async () => {
      const serverInfo = servers.mymongo;

      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));
      sh.exec('mup docker setup && mup mongo setup');

      const out = sh.exec('mup mongo start');
      expect(out.code).to.be.equal(0);

      expect(countOccurences('Start Mongo: SUCCESS', out.output)).to.be.equal(
        1
      );
      expect(
        (await runSSHCommand(serverInfo, 'nc -z -v -w5 localhost 27017')).code
      ).to.be.equal(0);
    });

    it('should allow configuring db name', async () => {
      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));
      const out = sh.exec('mup --config mup.db-name.js validate --show');

      expect(out.code).to.be.equal(0);

      expect(countOccurences('mongodb://mongodb:27017/test-db', out.output)).to.be.equal(
        1
      );
    });
  });

  describe('stop', () => {
    it('should stop mongodb on "mongo" vm', async () => {
      const serverInfo = servers.mymongo;

      sh.cd(path.resolve(os.tmpdir(), 'tests/project-1'));
      sh.exec('mup docker setup && mup mongo setup && mup mongo start');

      const out = sh.exec('mup mongo stop');

      expect(out.code).to.be.equal(0);

      expect(countOccurences('Stop Mongo: SUCCESS', out.output)).to.be.equal(1);
      expect(
        (await runSSHCommand(serverInfo, 'nc -z -v -w5 localhost 27017')).code
      ).to.be.equal(1);
    });
  });
});
<|endoftext|>


<commit_before>/* eslint-disable no-unused-expressions */

import sinon from 'sinon';

import { build } from '../../builder';
import { toIdMap, values } from '../../fp';
import { subscriber as plugin } from '.';

const createConfig = () => {
  const peter = { id: 'peter', name: 'peter' };
  const gernot = { id: 'gernot', name: 'gernot' };
  const robin = { id: 'robin', name: 'robin' };

  const users = toIdMap([peter, gernot, robin]);

  const getUser = (id) => Promise.resolve(users[id]);
  getUser.operation = 'READ';
  getUser.byId = true;
  const getUsers = () => Promise.resolve(values(users));
  getUser.operation = 'READ';

  const updateUser = (nextUser) => {
    const { id } = nextUser;
    const user = users[id];
    users[id] = { ...user, ...nextUser };
    return Promise.resolve(users[id]);
  };
  updateUser.operaton = 'UPDATE';

  const removeUser = (id) => {
    delete users[id];
    Promise.resolve();
  };
  removeUser.operation = 'DELETE';

  return {
    user: {
      api: { getUser, getUsers, updateUser, removeUser }
    }
  };
};

describe('subscriber', () => {
  it('patches fns so that a subscriber can be created on READ operations', () => {
    const api = build(createConfig(), [plugin()]);
    expect(api.user.getUsers.createSubscriber).to.be.a('function');
    expect(api.user.getUser.createSubscriber).to.be.a('function');
  });

  it('does not patch other operations than read', () => {
    const api = build(createConfig(), [plugin()]);
    expect(api.user.removeUser.createSubscriber).not.to.be;
    expect(api.user.updateUser.createSubscriber).not.to.be;
  });
});
<commit_msg>Add more subscriber specs and fix annotations<commit_after>/* eslint-disable no-unused-expressions */

import sinon from 'sinon';

import { build } from '../../builder';
import { toIdMap, values } from '../../fp';
import { subscriber as plugin } from '.';

const createConfig = () => {
  const peter = { id: 'peter', name: 'peter' };
  const gernot = { id: 'gernot', name: 'gernot' };
  const robin = { id: 'robin', name: 'robin' };

  const users = toIdMap([peter, gernot, robin]);

  const getUser = (id) => Promise.resolve(users[id]);
  getUser.operation = 'READ';
  getUser.byId = true;
  const getUsers = () => Promise.resolve(values(users));
  getUsers.operation = 'READ';

  const updateUser = (nextUser) => {
    const { id } = nextUser;
    const user = users[id];
    users[id] = { ...user, ...nextUser };
    return Promise.resolve(users[id]);
  };
  updateUser.operation = 'UPDATE';

  const removeUser = (id) => {
    delete users[id];
    Promise.resolve();
  };
  removeUser.operation = 'DELETE';

  return {
    user: {
      api: { getUser, getUsers, updateUser, removeUser }
    }
  };
};

describe('subscriber', () => {
  it('patches fns so that a subscriber can be created on READ operations', () => {
    const api = build(createConfig(), [plugin()]);
    expect(api.user.getUsers.createSubscriber).to.be.a('function');
    expect(api.user.getUser.createSubscriber).to.be.a('function');
  });

  it('does not patch other operations than read', () => {
    const api = build(createConfig(), [plugin()]);
    expect(api.user.removeUser.createSubscriber).not.to.be;
    expect(api.user.updateUser.createSubscriber).not.to.be;
  });

  describe('createSubscriber()', () => {
    it('returns a subscriber shape', () => {
      const api = build(createConfig(), [plugin()]);
      const subscriber = api.user.getUsers.createSubscriber();
      expect(subscriber.useArgs).to.be.a('function');
      expect(subscriber.destroy).to.be.a('function');
      expect(subscriber.subscribe).to.be.a('function');
    });
  });

  describe('subscriber', () => {
    describe('destroy', () => {
      fit('removes all subscriptions', () => {
        const spy1 = sinon.spy();
        const spy2 = sinon.spy();
        const api = build(createConfig(), [plugin()]);

        const subscriber = api.user.getUsers.createSubscriber();
        subscriber.subscribe(spy1);
        subscriber.subscribe(spy2);

        return api.user.updateUser({ id: 'peter', name: 'Peter' }).then(() => {
          expect(spy1).to.have.been.calledOnce;
          expect(spy2).to.have.been.calledOnce;
          subscriber.destroy();

          return api.user.updateUser({ id: 'peter', name: 'PEter' }).then(() => {
            expect(spy1).to.have.been.calledOnce;
            expect(spy2).to.have.been.calledOnce;
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>Added empty dependencies<commit_after>var dependencies = [];
<|endoftext|>


<commit_before>
/*
Copyright 2016 Resin.io

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 Promise, PubNub, _;

_ = require('lodash');

Promise = require('bluebird');

PubNub = require('pubnub');

/**
 * @summary Get a PubNub instance
 * @function
 * @protected
 *
 * @param {Object} options - PubNub options
 * @param {String} options.subscribe_key - subscribe key
 * @param {String} options.publish_key - publish key
 *
 * @returns {Object} PubNub instance
 */

exports.getInstance = function(options) {
  options.ssl = true;
  return PubNub.init(options);
};

/**
 * @summary Get logs history from an instance
 * @function
 * @protected
 *
 * @description
 * **BE CAREFUL!** This function reacts poorly to non valid channels.
 * It just returns an empty array as if it didn't have any history messages.
 *
 * @param {Object} instance - PubNub instance
 * @param {String} channel - channel
 *
 * @returns {Promise<String[]>} history messages
 */

exports.history = function(instance, channel) {
  return Promise.fromNode(function(callback) {
    return instance.history({
      channel: channel,
      callback: function(history) {
        return callback(null, _.first(history));
      },
      error: callback
    });
  });
};
<commit_msg>Remove accidentally put file<commit_after><|endoftext|>


<commit_before>import autoprefixer from 'autoprefixer';
import fs from 'fs';
import sass from 'node-sass';
import postcss from 'postcss';
import paths from '../mconfig.json';
import message from './utils/message.js';
import notification from './utils/notification.js';

/**
 * Compiles and minifies main Sass files to CSS.
 */
export function compileStyles() {
    [
        'critical',
        'main',
    ].forEach((name) => {
        const infile  = paths.styles.src  + name + '.scss';
        const outfile = paths.styles.dest + name + '.css';

        const timeLabel = `${name}.css compiled in`;
        console.time(timeLabel);

        sass.render({
            file: infile,
            omitSourceMapUrl: true,
            outFile: outfile,
            outputStyle: 'compressed',
            sourceMap: true,
            sourceMapContents: true
        }, (err, result) => {
            if (err) {
                message(`Error compiling ${name}.scss`, 'error');
                message(err.formatted);

                notification({
                    title:   `${name}.scss compilation failed 🚨`,
                    message: err.formatted
                });
                return;
            }

            fs.access(outfile, (err) => {
                if (err) {
                    message(`Error compiling ${name}.scss`, 'error');
                    message(err);

                    notification({
                        title:   `${name}.scss compilation failed 🚨`,
                        message: err
                    });
                    return;
                }

                postcss([ autoprefixer ]).process(result.css, {
                    from: outfile,
                    to: outfile,
                    map: {
                        annotation: false,
                        inline: false,
                        sourcesContent: true
                    }
                }).then((result) => {
                    result.warnings().forEach((warn) => {
                        message(`Error prefixing ${name}.css`, 'error');
                        message(warn.toString());
                    });

                    fs.writeFile(outfile, result.css, (err) => {
                        if (err) {
                            message(`Error compiling ${name}.scss`, 'error');
                            message(err);

                            notification({
                                title:   `${name}.scss compilation failed 🚨`,
                                message: `Could not save stylesheet to ${name}.css`
                            });
                            return;
                        }

                        message(`${name}.css compiled`, 'success', timeLabel);
                    });

                    if (result.map) {
                        fs.writeFile(outfile + '.map', result.map.toString(), (err) => {
                            if (err) {
                                message(`Error compiling ${name}.scss`, 'error');
                                message(err);

                                notification({
                                    title:   `${name}.scss compilation failed 🚨`,
                                    message: `Could not save sourcemap to ${name}.css.map`
                                });
                                return;
                            }
                        });
                    }
                });
            });
        });
    });
};
<commit_msg>Fix logic for PostCSS processing<commit_after>import autoprefixer from 'autoprefixer';
import fs from 'fs';
import sass from 'node-sass';
import postcss from 'postcss';
import paths from '../mconfig.json';
import message from './utils/message.js';
import notification from './utils/notification.js';

/**
 * Compiles and minifies main Sass files to CSS.
 */
export function compileStyles() {
    [
        'critical',
        'main',
    ].forEach((name) => {
        const infile  = paths.styles.src  + name + '.scss';
        const outfile = paths.styles.dest + name + '.css';

        const timeLabel = `${name}.css compiled in`;
        console.time(timeLabel);

        sass.render({
            file: infile,
            omitSourceMapUrl: true,
            outFile: outfile,
            outputStyle: 'compressed',
            sourceMap: true,
            sourceMapContents: true
        }, (err, result) => {
            if (err) {
                message(`Error compiling ${name}.scss`, 'error');
                message(err.formatted);

                notification({
                    title:   `${name}.scss compilation failed 🚨`,
                    message: err.formatted
                });
                return;
            }

            postcss([ autoprefixer ]).process(result.css, {
                from: outfile,
                to: outfile,
                map: {
                    annotation: false,
                    inline: false,
                    sourcesContent: true
                }
            }).then((result) => {
                result.warnings().forEach((warn) => {
                    message(`Error prefixing ${name}.css`, 'error');
                    message(warn.toString());
                });

                fs.writeFile(outfile, result.css, (err) => {
                    if (err) {
                        message(`Error compiling ${name}.scss`, 'error');
                        message(err);

                        notification({
                            title:   `${name}.scss compilation failed 🚨`,
                            message: `Could not save stylesheet to ${name}.css`
                        });
                        return;
                    }

                    message(`${name}.css compiled`, 'success', timeLabel);
                });

                if (result.map) {
                    fs.writeFile(outfile + '.map', result.map.toString(), (err) => {
                        if (err) {
                            message(`Error compiling ${name}.scss`, 'error');
                            message(err);

                            notification({
                                title:   `${name}.scss compilation failed 🚨`,
                                message: `Could not save sourcemap to ${name}.css.map`
                            });
                            return;
                        }
                    });
                }
            });
        });
    });
};
<|endoftext|>


<commit_before>//Assumes zopfli is installed
var glob = require('glob');
var fs = require('fs');
var execSync = require('execSync');

execSync.exec('git pull');

var exec=require('child_process').exec;
exec('git checkout zopfli | git merge master',function(err,stdout,stderr){
    glob("../ajax/libs/**/package.json", function (error, matches) {
        matches.forEach(function(element){
            var package = JSON.parse(fs.readFileSync(element, 'utf8'));
            package.assets = Array();
            var versions = glob.sync("../ajax/libs/"+package.name+"/!(package.json)");
            versions.forEach(function(version) {
                var temp = Object();
                temp.files = glob.sync(version + "/**/*.*");

                for (var i = 0; i < temp.files.length; i++){
                    var regex = /(?:^.+\/)?(.+?)?\.((?:js)|(?:css))([\.-](?:gz))?$/ig;
                    var result = regex.exec(temp.files[i]);
                    //result[0] Original Input
                    //result[1] Filename
                    //result[2] js|css
                    //result[3] gz

                    if (result == null) {
                        continue;
                    }

                    if (typeof result[3] == "undefined") { //
                        if (!fs.exists(temp.files[i] + ".gz")) {
                            console.log('zopfli', temp.files[i])
                            execSync.exec('zopfli ' + temp.files[i]);
                            console.log('zopfli ended')
                        }
                    }
                }
            });
        });
    });

    execSync.exec('git add ../.');
    execSync.exec('git commit -am "zopfli"');
    execSync.exec('git push');
    execSync.exec('git checkout master');

})
<commit_msg>fix zopfli script<commit_after>//Assumes zopfli is installed
var glob = require('glob');
var fs = require('fs');
var execSync = require('execSync');

execSync.exec('git pull');

var exec=require('child_process').exec;
exec('git checkout zopfli',function(err,stdout,stderr){
    execSync.exec('git merge master');
    glob("../ajax/libs/**/package.json", function (error, matches) {
        matches.forEach(function(element){
            var package = JSON.parse(fs.readFileSync(element, 'utf8'));
            package.assets = Array();
            var versions = glob.sync("../ajax/libs/"+package.name+"/!(package.json)");
            versions.forEach(function(version) {
                var temp = Object();
                temp.files = glob.sync(version + "/**/*.*");

                for (var i = 0; i < temp.files.length; i++){
                    var regex = /(?:^.+\/)?(.+?)?\.((?:js)|(?:css))([\.-](?:gz))?$/ig;
                    var result = regex.exec(temp.files[i]);
                    //result[0] Original Input
                    //result[1] Filename
                    //result[2] js|css
                    //result[3] gz

                    if (result == null) {
                        continue;
                    }

                    if (typeof result[3] == "undefined") { //
                        if (!fs.exists(temp.files[i] + ".gz")) {
                            console.log('zopfli', temp.files[i])
                            execSync.exec('zopfli ' + temp.files[i]);
                            console.log('zopfli ended')
                        }
                    }
                }
            });
        });
    });

    execSync.exec('git add ../.');
    execSync.exec('git commit -am "zopfli"');
    execSync.exec('git push');
    execSync.exec('git checkout master');

})
<|endoftext|>


<commit_before><commit_msg>Fixed usage of previous variable name<commit_after><|endoftext|>


<commit_before>/*
Copyright 2013 Martin Schnabel. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
define(["json2", "backbone"], function() {

if (!window["WebSocket"]) {
	return null;
}

var Conn = Backbone.Model.extend({
	constructor: function(data, opts) {
		this.wsconn = null;
		Backbone.Model.prototype.constructor.call(this, data, opts);
	},
	connect: function() {
		var c = this;
		if (c.urlRoot) {
			c.wsurl = c.url();
		}
		if (!c.wsurl) {
			c.wsurl = "ws://"+ location.host +"/ws";
		}
		console.log("connect", c.wsurl);
		c.trigger("connect", c.wsurl);
		var ws = c.wsconn = new WebSocket(c.wsurl);
		ws.onopen = function(e) {
			c.trigger("open", e);
		};
		ws.onclose = function(e) {
			c.wsconn = null;
			c.trigger("close", e);
		};
		ws.onmessage = function(e) {
			var msg = JSON.parse(e.data)
			console.log("msg", msg);
			c.trigger("msg", msg);
			c.trigger("msg:"+ msg.Head, msg.Data);
		};
		ws.onerror = function(e) {
			c.trigger("error", e.message);
		};
	},
	connected: function() {
		return this.wsconn != null;
	},

});

return new Conn();

});
<commit_msg>adds offline send queue for client connection.<commit_after>/*
Copyright 2013 Martin Schnabel. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
define(["json2", "backbone"], function() {

if (!window["WebSocket"]) {
	return null;
}

var Conn = Backbone.Model.extend({
	constructor: function(data, opts) {
		this.wsconn = null;
		this.queue = [];
		Backbone.Model.prototype.constructor.call(this, data, opts);
	},
	connect: function() {
		var c = this;
		if (c.urlRoot) {
			c.wsurl = c.url();
		}
		if (!c.wsurl) {
			c.wsurl = "ws://"+ location.host +"/ws";
		}
		console.log("connect", c.wsurl);
		c.trigger("connect", c.wsurl);
		var ws = c.wsconn = new WebSocket(c.wsurl);
		ws.onopen = function(e) {
			c.trigger("open", e);
			console.log("work", c.queue);
			_.each(c.queue, c.wsconn.send, c.wsconn);
			c.queue = [];
		};
		ws.onclose = function(e) {
			c.wsconn = null;
			c.trigger("close", e);
		};
		ws.onmessage = function(e) {
			var msg = JSON.parse(e.data)
			console.log("msg", msg);
			c.trigger("msg", msg);
			c.trigger("msg:"+ msg.Head, msg.Data);
		};
		ws.onerror = function(e) {
			c.trigger("error", e.message);
		};
	},
	connected: function() {
		return this.wsconn != null;
	},
	send: function(head, data) {
		var msg = JSON.stringify({"Head":head, "Data":data});
		if (this.wsconn != null) {
			console.log("send", msg);
			this.wsconn.send(msg);
		} else {
			console.log("push", msg);
			this.queue.push(msg);
		}
	},

});

return new Conn();

});
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
// GitOperations - main home for git related activities
//////////////////////////////////////////////////////////////////////////
//
// We interface with git using the command line.
/* ----------------------------------------------------------------------
													Object Structures
-------------------------------------------------------------------------

*/
var exec = require('child_process').exec;

//////////////////////////////////////////////////////////////////////////
// Push our current state to the server
exports.push = function( callback ) {
	console.log( "Pushing changes to git" );

	var commandString = "git push origin master";
	runCommand( commandString, callback );
} // end push()

//////////////////////////////////////////////////////////////////////////
// Pull the current state of the server down to our local repository
exports.pull = function( isRebase, callback ) {
	console.log( "Pulling changes " + isRebase ? "with rebase" : "without rebase" );

	var commandString = isRebase ? "git pull --rebase" : "git pull";
	exec( commandString, function( error, stdout, stderr ) {
		if( stderr.indexOf("Current branch master is up to date") ) {
			stdout = stderr;
			stderr = null;
		}

		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		console.log( commandString );
		callback( null, stdout );
	});
} // end pull()

//////////////////////////////////////////////////////////////////////////
// Return our local repository state back to the last time we pulled from the server
exports.checkout = function( filePath, branch, callback ) {
	console.log( "Checking out" );
	var pathString;
	if( typeof(filePath) != "undefined" && filePath != null ) {
		pathString = "-- " + filePath;
	} else if( typeof(branch) != "undefined" && branch != null ) {
		pathString = branch;
	} else {
		pathString = "-- .";
	}

	var commandString = "git checkout " + pathString;
	runCommand( commandString, callback );
} // end checkout()

//////////////////////////////////////////////////////////////////////////
// Push our current state to the server
exports.commit = function( commitMessage, location, callback ) {
	console.log( "Committing changes in " + location );

	if( location == null || typeof(location) == "undefined" )
		location = ".";

	var commandString = 'git commit -m "' + commitMessage + '" ' + location;
	runCommand( commandString, callback );
} // end commit()

//////////////////////////////////////////////////////////////////////////
// Create a new branch
exports.branch = function( branchName, TagOrSHA, callback ) {
	console.log( "Creating branch " + branchName );

	if( TagOrSHA == null || typeof(TagOrSHA) == "undefined" )
		TagOrSHA = "HEAD";

	var commandString = 'git branch ' + branchName + ' ' + TagOrSHA;
	runCommand( commandString, callback );
} // end branch()

//////////////////////////////////////////////////////////////////////////
// Merge the current branch with a specified branch
exports.merge = function( branchName, callback ) {
	console.log( "Committing changes in " + branchName );

	var commandString = "git merge " + branchName;
	runCommand( commandString, callback );
} // end merge()

//////////////////////////////////////////////////////////////////////////
// Returns the current SHA of the local HEAD
exports.getAsyncSHA = function( callback ) {
	var commandString = "git rev-parse --verify HEAD";
	exec( commandString, function( error, stdout, stderr ) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		console.log( commandString );
		callback( stdout );
	});
} // end getAsyncSHA()

//////////////////////////////////////////////////////////////////////////
// Returns the current SHA of the local HEAD
exports.getAsyncBranch = function( callback ) {
	var commandString = "git branch";
	exec( commandString, function( error, stdout, stderr ) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		console.log( commandString );
		callback( stdout );
	});
} // end getAsyncSHA()

function runCommand( commandString, callback ) {
	exec( commandString, function( error, stdout, stderr ) {
		console.log( commandString );
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		callback( null, stdout );
	});
} // runCommand()<commit_msg>Report an error only when it contains the word "fatal"<commit_after>//////////////////////////////////////////////////////////////////////////
// GitOperations - main home for git related activities
//////////////////////////////////////////////////////////////////////////
//
// We interface with git using the command line.
/* ----------------------------------------------------------------------
													Object Structures
-------------------------------------------------------------------------

*/
var exec = require('child_process').exec;

//////////////////////////////////////////////////////////////////////////
// Push our current state to the server
exports.push = function( callback ) {
	console.log( "Pushing changes to git" );

	var commandString = "git push origin master";
	runCommand( commandString, callback );
} // end push()

//////////////////////////////////////////////////////////////////////////
// Pull the current state of the server down to our local repository
exports.pull = function( isRebase, callback ) {
	console.log( "Pulling changes " + isRebase ? "with rebase" : "without rebase" );

	var commandString = isRebase ? "git pull --rebase" : "git pull";
	exec( commandString, function( error, stdout, stderr ) {
		if( stderr.indexOf("Current branch master is up to date") ) {
			stdout = stderr;
			stderr = null;
		}

		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		console.log( commandString );
		callback( null, stdout );
	});
} // end pull()

//////////////////////////////////////////////////////////////////////////
// Return our local repository state back to the last time we pulled from the server
exports.checkout = function( filePath, branch, callback ) {
	console.log( "Checking out" );
	var pathString;
	if( typeof(filePath) != "undefined" && filePath != null ) {
		pathString = "-- " + filePath;
	} else if( typeof(branch) != "undefined" && branch != null ) {
		pathString = branch;
	} else {
		pathString = "-- .";
	}

	var commandString = "git checkout " + pathString;
	runCommand( commandString, callback );
} // end checkout()

//////////////////////////////////////////////////////////////////////////
// Push our current state to the server
exports.commit = function( commitMessage, location, callback ) {
	console.log( "Committing changes in " + location );

	if( location == null || typeof(location) == "undefined" )
		location = ".";

	var commandString = 'git commit -m "' + commitMessage + '" ' + location;
	runCommand( commandString, callback );
} // end commit()

//////////////////////////////////////////////////////////////////////////
// Create a new branch
exports.branch = function( branchName, TagOrSHA, callback ) {
	console.log( "Creating branch " + branchName );

	if( TagOrSHA == null || typeof(TagOrSHA) == "undefined" )
		TagOrSHA = "HEAD";

	var commandString = 'git branch ' + branchName + ' ' + TagOrSHA;
	runCommand( commandString, callback );
} // end branch()

//////////////////////////////////////////////////////////////////////////
// Merge the current branch with a specified branch
exports.merge = function( branchName, callback ) {
	console.log( "Committing changes in " + branchName );

	var commandString = "git merge " + branchName;
	runCommand( commandString, callback );
} // end merge()

//////////////////////////////////////////////////////////////////////////
// Returns the current SHA of the local HEAD
exports.getAsyncSHA = function( callback ) {
	var commandString = "git rev-parse --verify HEAD";
	exec( commandString, function( error, stdout, stderr ) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		console.log( commandString );
		callback( stdout );
	});
} // end getAsyncSHA()

//////////////////////////////////////////////////////////////////////////
// Returns the current SHA of the local HEAD
exports.getAsyncBranch = function( callback ) {
	var commandString = "git branch";
	exec( commandString, function( error, stdout, stderr ) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		console.log( commandString );
		callback( stdout );
	});
} // end getAsyncSHA()

function runCommand( commandString, callback ) {
	exec( commandString, function( error, stdout, stderr ) {
		console.log( commandString );
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);

		var err = stderr.indexOf("fatal") > 0 ? stderr : null;

		callback( err, stdout );
	});
} // runCommand()<|endoftext|>


<commit_before>"use strict"

// MAP
$( document ).ready(function() {

    // INIT
    L.mapbox.accessToken = getMapboxAccessToken();
    var map = L.mapbox.map('map').setView([51.961298, 7.625849], 14);

    L.control.layers({
        'Streets': L.mapbox.tileLayer('mapbox.streets').addTo(map),
        'Satellite': L.mapbox.tileLayer('mapbox.satellite'),
        'Light': L.mapbox.tileLayer('mapbox.light')
    }).addTo(map);

    var boxes = [];
    var markers = [];
    requestData();

    // MAP-FUNCTION
    map.on('zoomend', function() {
        console.log(map.getZoom());
        if (map.getZoom() >= 14) {
            map.featureLayer.setFilter(function() { return true; });
        } else {
            map.featureLayer.setFilter(function() { return false; });
        }
    });

    // REQUEST DATA FROM API
    function requestData(){

        $.ajax({
            url: getURL() + "/boxes",
            global: false,
            type: 'GET',
            async: false,
            success: function(data) {
                boxes = data;
                boxes.forEach(function (box, key) {
                    $.ajax({
                        url: getURL() + "/boxes/" + box._id + "/tracks",
                        global: false,
                        type: 'GET',
                        async: false,
                        success: function(data) {
                            box.tracks = data;
                            box.tracks.forEach(function (track, key) {
                                $.ajax({
                                    url: getURL() + "/boxes/" + box._id + "/tracks/" + track._id + "/measurements",
                                    global: false,
                                    type: 'GET',
                                    async: false,
                                    success: function(data) {
                                        track.measurements = data;
                                    }
                                });
                            });
                        }
                    });
                });
                drawMarkers();
            }
        });
    }

    function drawMarkers() {

        var geoJsonFeatures = [];

        boxes.forEach(function (box, key) {
            box.tracks.forEach(function (track, key) {

                track.measurements.forEach(function (measurement, key) {

                    geoJsonFeatures.push(
                        {
                            type: 'Feature',
                            geometry: {
                                type: 'Point',
                                coordinates: [
                                    measurement.lng, measurement.lat,
                                ]
                            },
                            'properties': {
                                'title': '
' + box._id + ' BoxId
' +
                                    '
' + track._id + ' TrackId
',
                                'description': '

' +
                                    '
Longitude	' + measurement.lng + '
' +
                                    '
Latitude	' + measurement.lat + '
' +
                                    '
Altitude	' + measurement.altitude + '
' +
                                    '
Speed	' + measurement.speed + '
' +
                                    '
Vibration	' + measurement.vibration + '
' +
                                    '
Sound	' + measurement.sound + '
' +
                                    '
Brightness	' + measurement.brightness + '
' +
                                    '
IR	' + measurement.ir + '
' +
                                    '
UV	' + measurement.uv + '
' +
                                    '

',
                                'perfect': isPerfectCondition(measurement.speed, measurement.vibration),
                                'poor': isPoorCondition(measurement.speed, measurement.vibration),
                                'icon': {
                                    'iconUrl': calcRoadConditionIcon(measurement.speed, measurement.vibration),
                                    'iconSize': [12, 12], // size of the icon
                                    'iconAnchor': [6, 6], // point of the icon which will correspond to marker's location
                                    'popupAnchor': [0, -6], // point from which the popup should open relative to the iconAnchor
                                    'className': 'dot'
                                }
                            }
                        }
                    );
                });
            });
        });

        // Add markers to the map
        var markers = L.mapbox.featureLayer().addTo(map);
        markers.on('layeradd', function(e) {
            var marker = e.layer;
            var feature = marker.feature;
            marker.setIcon(L.icon(feature.properties.icon));
        });
        markers.setGeoJSON(geoJsonFeatures);

        $('.menu-ui a').on('click', function() {
            // For each filter link, get the 'data-filter' attribute value.
            var filter = $(this).data('filter');
            $(this).addClass('active').siblings().removeClass('active');
            markers.setFilter(function(f) {
                // If the data-filter attribute is set to "all", return
                // all (true). Otherwise, filter on markers that have
                // a value set to true based on the filter name.
                return (filter === 'all') ? true : f.properties[filter] === true;
            });
            return false;
        });
    };

    /*
        Function to calculate the condition of the road based on the measured parameters
        Returns the icon file path
    */
    function calcRoadConditionIcon(speed, vibration) {
        var icon;

        if (speed > 15 && vibration < 1.2 && vibration > 0.8) {
            // Perfect Cycling Road
            icon = '/img/circle_green.png';
        } else {
            // Poor Cycling Road
            icon = '/img/circle_red.png';
        }

        return icon;
    }

    /*
        Function to calculate whether the condition of the road is perfect
        Returns true or false
    */
    function isPerfectCondition(speed, vibration) {
        if (speed > 15 && vibration < 1.2 && vibration > 0.8) {
            // Perfect Cycling Road
            return true;
        } else {
            // Poor Cycling Road
            return false;
        }
    }

    /*
        Function to calculate whether the condition of the road is poor
        Returns true or false
    */
    function isPoorCondition(speed, vibration) {
        if (speed > 15 && vibration < 1.2 && vibration > 0.8) {
            // Perfect Cycling Road
            return false;
        } else {
            // Poor Cycling Road
            return true;
        }
    }

});
<commit_msg>First implementation of the data interpolation<commit_after>"use strict"

// MAP
$( document ).ready(function() {

    // INIT
    L.mapbox.accessToken = getMapboxAccessToken();
    var map = L.mapbox.map('map').setView([51.961298, 7.625849], 14);

    L.control.layers({
        'Streets': L.mapbox.tileLayer('mapbox.streets').addTo(map),
        'Satellite': L.mapbox.tileLayer('mapbox.satellite'),
        'Light': L.mapbox.tileLayer('mapbox.light')
    }).addTo(map);

    var boxes = [];
    var markers = [];
    requestData();

    // MAP-FUNCTION
    map.on('zoomend', function() {
        console.log(map.getZoom());
        if (map.getZoom() >= 14) {
            map.featureLayer.setFilter(function() { return true; });
        } else {
            map.featureLayer.setFilter(function() { return false; });
        }
    });

    // REQUEST DATA FROM API
    function requestData(){

        $.ajax({
            url: getURL() + "/boxes",
            global: false,
            type: 'GET',
            async: false,
            success: function(data) {
                boxes = data;
                boxes.forEach(function (box, key) {
                    $.ajax({
                        url: getURL() + "/boxes/" + box._id + "/tracks",
                        global: false,
                        type: 'GET',
                        async: false,
                        success: function(data) {
                            box.tracks = data;
                            box.tracks.forEach(function (track, key) {
                                $.ajax({
                                    url: getURL() + "/boxes/" + box._id + "/tracks/" + track._id + "/measurements",
                                    global: false,
                                    type: 'GET',
                                    async: false,
                                    success: function(data) {
                                        track.measurements = data;
                                    }
                                });
                            });
                        }
                    });
                });
                drawMarkers();
            }
        });
    }

    function drawMarkers() {

        var geoJsonFeatures = [];

        boxes.forEach(function (box, key) {
            box.tracks.forEach(function (track, key) {

                // Interpolate the data before the visualization
                track.measurements = interpolate(track.measurements);

                track.measurements.forEach(function (measurement, key) {

                    geoJsonFeatures.push(
                        {
                            type: 'Feature',
                            geometry: {
                                type: 'Point',
                                coordinates: [
                                    measurement.lng, measurement.lat,
                                ]
                            },
                            'properties': {
                                'title': '
' + box._id + ' BoxId
' +
                                    '
' + track._id + ' TrackId
',
                                'description': '

' +
                                    '
Longitude	' + measurement.lng + '
' +
                                    '
Latitude	' + measurement.lat + '
' +
                                    '
Altitude	' + measurement.altitude + '
' +
                                    '
Speed	' + measurement.speed + '
' +
                                    '
Vibration	' + measurement.vibration + '
' +
                                    '
Sound	' + measurement.sound + '
' +
                                    '
Brightness	' + measurement.brightness + '
' +
                                    '
IR	' + measurement.ir + '
' +
                                    '
UV	' + measurement.uv + '
' +
                                    '

',
                                'perfect': isPerfectCondition(measurement.speed, measurement.vibration),
                                'poor': isPoorCondition(measurement.speed, measurement.vibration),
                                'icon': {
                                    'iconUrl': calcRoadConditionIcon(measurement.speed, measurement.vibration),
                                    'iconSize': [12, 12], // size of the icon
                                    'iconAnchor': [6, 6], // point of the icon which will correspond to marker's location
                                    'popupAnchor': [0, -6], // point from which the popup should open relative to the iconAnchor
                                    'className': 'dot'
                                }
                            }
                        }
                    );
                });
            });
        });

        // Add markers to the map
        var markers = L.mapbox.featureLayer().addTo(map);
        markers.on('layeradd', function(e) {
            var marker = e.layer;
            var feature = marker.feature;
            marker.setIcon(L.icon(feature.properties.icon));
        });
        markers.setGeoJSON(geoJsonFeatures);

        $('.menu-ui a').on('click', function() {
            // For each filter link, get the 'data-filter' attribute value.
            var filter = $(this).data('filter');
            $(this).addClass('active').siblings().removeClass('active');
            markers.setFilter(function(f) {
                // If the data-filter attribute is set to "all", return
                // all (true). Otherwise, filter on markers that have
                // a value set to true based on the filter name.
                return (filter === 'all') ? true : f.properties[filter] === true;
            });
            return false;
        });
    };

    /*
        Function to interpolate the speed and vibration values
    */
    function interpolate(measurements) {
        for (var i = 2; i < measurements.length - 2; i++) {
            var m_2 = measurements[i-2],
                m_1 = measurements[i-1],
                m = measurements[i],
                m1 = measurements[i+1],
                m2 = measurements[i+2];
            measurements[i].speed = (m_2.speed + m_1.speed + m.speed + m1.speed + m2.speed) / 5;
            measurements[i].vibration = (m_2.vibration + m_1.vibration + m.vibration + m1.vibration + m2.vibration) / 5;
        }

        return measurements;
    }

    /*
        Function to calculate the condition of the road based on the measured parameters
        Returns the icon file path
    */
    function calcRoadConditionIcon(speed, vibration) {
        var icon;

        if (speed > 15 && vibration < 1.2 && vibration > 0.8) {
            // Perfect Cycling Road
            icon = '/img/circle_green.png';
        } else {
            // Poor Cycling Road
            icon = '/img/circle_red.png';
        }

        return icon;
    }

    /*
        Function to calculate whether the condition of the road is perfect
        Returns true or false
    */
    function isPerfectCondition(speed, vibration) {
        if (speed > 15 && vibration < 1.2 && vibration > 0.8) {
            // Perfect Cycling Road
            return true;
        } else {
            // Poor Cycling Road
            return false;
        }
    }

    /*
        Function to calculate whether the condition of the road is poor
        Returns true or false
    */
    function isPoorCondition(speed, vibration) {
        if (speed > 15 && vibration < 1.2 && vibration > 0.8) {
            // Perfect Cycling Road
            return false;
        } else {
            // Poor Cycling Road
            return true;
        }
    }

});
<|endoftext|>


<commit_before><commit_msg>Added Move actions and methods.<commit_after><|endoftext|>


<commit_before><commit_msg>added blank component did mount<commit_after><|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

import { BackSide, DoubleSide, CubeUVRefractionMapping, CubeUVReflectionMapping, GammaEncoding, LinearEncoding, ObjectSpaceNormalMap, TangentSpaceNormalMap, NoToneMapping } from '../../constants.js';
import { WebGLProgram } from './WebGLProgram.js';

function WebGLPrograms( renderer, extensions, capabilities ) {

	var programs = [];

	var isWebGL2 = capabilities.isWebGL2;
	var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
	var floatVertexTextures = capabilities.floatVertexTextures;
	var precision = capabilities.precision;
	var maxVertexUniforms = capabilities.maxVertexUniforms;
	var vertexTextures = capabilities.vertexTextures;

	var shaderIDs = {
		MeshDepthMaterial: 'depth',
		MeshDistanceMaterial: 'distanceRGBA',
		MeshNormalMaterial: 'normal',
		MeshBasicMaterial: 'basic',
		MeshLambertMaterial: 'lambert',
		MeshPhongMaterial: 'phong',
		MeshToonMaterial: 'phong',
		MeshStandardMaterial: 'physical',
		MeshPhysicalMaterial: 'physical',
		MeshMatcapMaterial: 'matcap',
		LineBasicMaterial: 'basic',
		LineDashedMaterial: 'dashed',
		PointsMaterial: 'points',
		ShadowMaterial: 'shadow',
		SpriteMaterial: 'sprite'
	};

	var parameterNames = [
		"precision", "supportsVertexTextures", "instancing",
		"map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding",
		"lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap",
		"roughnessMap", "metalnessMap", "gradientMap",
		"alphaMap", "combine", "vertexColors", "vertexTangents", "fog", "useFog", "fogExp2",
		"flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
		"maxBones", "useVertexTexture", "morphTargets", "morphNormals",
		"maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
		"numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
		"shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
		"alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
		"sheen"
	];

	function allocateBones( object ) {

		var skeleton = object.skeleton;
		var bones = skeleton.bones;

		if ( floatVertexTextures ) {

			return 1024;

		} else {

			// default for when object is not specified
			// ( for example when prebuilding shader to be used with multiple objects )
			//
			//  - leave some extra space for other uniforms
			//  - limit here is ANGLE's 254 max uniform vectors
			//    (up to 54 should be safe)

			var nVertexUniforms = maxVertexUniforms;
			var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );

			var maxBones = Math.min( nVertexMatrices, bones.length );

			if ( maxBones < bones.length ) {

				console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
				return 0;

			}

			return maxBones;

		}

	}

	function getTextureEncodingFromMap( map, gammaOverrideLinear ) {

		var encoding;

		if ( ! map ) {

			encoding = LinearEncoding;

		} else if ( map.isTexture ) {

			encoding = map.encoding;

		} else if ( map.isWebGLRenderTarget ) {

			console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
			encoding = map.texture.encoding;

		}

		// add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
		if ( encoding === LinearEncoding && gammaOverrideLinear ) {

			encoding = GammaEncoding;

		}

		return encoding;

	}

	this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {

		var shaderID = shaderIDs[ material.type ];

		// heuristics to create shader parameters according to lights in the scene
		// (not to blow over maxLights budget)

		var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;

		if ( material.precision !== null ) {

			precision = capabilities.getMaxPrecision( material.precision );

			if ( precision !== material.precision ) {

				console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );

			}

		}

		var currentRenderTarget = renderer.getRenderTarget();

		var parameters = {

			isWebGL2: isWebGL2,

			shaderID: shaderID,

			precision: precision,

			instancing: object.isInstancedMesh === true,

			supportsVertexTextures: vertexTextures,
			outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
			map: !! material.map,
			mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
			matcap: !! material.matcap,
			matcapEncoding: getTextureEncodingFromMap( material.matcap, renderer.gammaInput ),
			envMap: !! material.envMap,
			envMapMode: material.envMap && material.envMap.mapping,
			envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
			envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
			lightMap: !! material.lightMap,
			aoMap: !! material.aoMap,
			emissiveMap: !! material.emissiveMap,
			emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
			bumpMap: !! material.bumpMap,
			normalMap: !! material.normalMap,
			objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
			tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
			clearcoatNormalMap: !! material.clearcoatNormalMap,
			displacementMap: !! material.displacementMap,
			roughnessMap: !! material.roughnessMap,
			metalnessMap: !! material.metalnessMap,
			specularMap: !! material.specularMap,
			alphaMap: !! material.alphaMap,

			gradientMap: !! material.gradientMap,

			sheen: !! material.sheen,

			combine: material.combine,

			vertexTangents: ( material.normalMap && material.vertexTangents ),
			vertexColors: material.vertexColors,
			vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap,

			fog: !! fog,
			useFog: material.fog,
			fogExp2: ( fog && fog.isFogExp2 ),

			flatShading: material.flatShading,

			sizeAttenuation: material.sizeAttenuation,
			logarithmicDepthBuffer: logarithmicDepthBuffer,

			skinning: material.skinning && maxBones > 0,
			maxBones: maxBones,
			useVertexTexture: floatVertexTextures,

			morphTargets: material.morphTargets,
			morphNormals: material.morphNormals,
			maxMorphTargets: renderer.maxMorphTargets,
			maxMorphNormals: renderer.maxMorphNormals,

			numDirLights: lights.directional.length,
			numPointLights: lights.point.length,
			numSpotLights: lights.spot.length,
			numRectAreaLights: lights.rectArea.length,
			numHemiLights: lights.hemi.length,

			numDirLightShadows: lights.directionalShadowMap.length,
			numPointLightShadows: lights.pointShadowMap.length,
			numSpotLightShadows: lights.spotShadowMap.length,

			numClippingPlanes: nClipPlanes,
			numClipIntersection: nClipIntersection,

			dithering: material.dithering,

			shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
			shadowMapType: renderer.shadowMap.type,

			toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
			physicallyCorrectLights: renderer.physicallyCorrectLights,

			premultipliedAlpha: material.premultipliedAlpha,

			alphaTest: material.alphaTest,
			doubleSided: material.side === DoubleSide,
			flipSided: material.side === BackSide,

			depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false

		};

		return parameters;

	};

	this.getProgramCode = function ( material, parameters ) {

		var array = [];

		if ( parameters.shaderID ) {

			array.push( parameters.shaderID );

		} else {

			array.push( material.fragmentShader );
			array.push( material.vertexShader );

		}

		if ( material.defines !== undefined ) {

			for ( var name in material.defines ) {

				array.push( name );
				array.push( material.defines[ name ] );

			}

		}

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

			array.push( parameters[ parameterNames[ i ] ] );

		}

		array.push( material.onBeforeCompile.toString() );

		array.push( renderer.gammaOutput );

		array.push( renderer.gammaFactor );

		return array.join();

	};

	this.acquireProgram = function ( material, shader, parameters, code ) {

		var program;

		// Check if code has been already compiled
		for ( var p = 0, pl = programs.length; p < pl; p ++ ) {

			var programInfo = programs[ p ];

			if ( programInfo.code === code ) {

				program = programInfo;
				++ program.usedTimes;

				break;

			}

		}

		if ( program === undefined ) {

			program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
			programs.push( program );

		}

		return program;

	};

	this.releaseProgram = function ( program ) {

		if ( -- program.usedTimes === 0 ) {

			// Remove from unordered set
			var i = programs.indexOf( program );
			programs[ i ] = programs[ programs.length - 1 ];
			programs.pop();

			// Free WebGL resources
			program.destroy();

		}

	};

	// Exposed for resource monitoring & error feedback via renderer.info:
	this.programs = programs;

}

export { WebGLPrograms };
<commit_msg>Add missing ParameterNames<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

import { BackSide, DoubleSide, CubeUVRefractionMapping, CubeUVReflectionMapping, GammaEncoding, LinearEncoding, ObjectSpaceNormalMap, TangentSpaceNormalMap, NoToneMapping } from '../../constants.js';
import { WebGLProgram } from './WebGLProgram.js';

function WebGLPrograms( renderer, extensions, capabilities ) {

	var programs = [];

	var isWebGL2 = capabilities.isWebGL2;
	var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
	var floatVertexTextures = capabilities.floatVertexTextures;
	var precision = capabilities.precision;
	var maxVertexUniforms = capabilities.maxVertexUniforms;
	var vertexTextures = capabilities.vertexTextures;

	var shaderIDs = {
		MeshDepthMaterial: 'depth',
		MeshDistanceMaterial: 'distanceRGBA',
		MeshNormalMaterial: 'normal',
		MeshBasicMaterial: 'basic',
		MeshLambertMaterial: 'lambert',
		MeshPhongMaterial: 'phong',
		MeshToonMaterial: 'phong',
		MeshStandardMaterial: 'physical',
		MeshPhysicalMaterial: 'physical',
		MeshMatcapMaterial: 'matcap',
		LineBasicMaterial: 'basic',
		LineDashedMaterial: 'dashed',
		PointsMaterial: 'points',
		ShadowMaterial: 'shadow',
		SpriteMaterial: 'sprite'
	};

	var parameterNames = [
		"precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing",
		"map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV",
		"lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap",
		"roughnessMap", "metalnessMap", "gradientMap",
		"alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "fog", "useFog", "fogExp2",
		"flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
		"maxBones", "useVertexTexture", "morphTargets", "morphNormals",
		"maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
		"numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
		"numDirLightShadows", "numPointLightShadows", "numSpotLightShadows",
		"shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
		"alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
		"sheen"
	];

	function allocateBones( object ) {

		var skeleton = object.skeleton;
		var bones = skeleton.bones;

		if ( floatVertexTextures ) {

			return 1024;

		} else {

			// default for when object is not specified
			// ( for example when prebuilding shader to be used with multiple objects )
			//
			//  - leave some extra space for other uniforms
			//  - limit here is ANGLE's 254 max uniform vectors
			//    (up to 54 should be safe)

			var nVertexUniforms = maxVertexUniforms;
			var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );

			var maxBones = Math.min( nVertexMatrices, bones.length );

			if ( maxBones < bones.length ) {

				console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
				return 0;

			}

			return maxBones;

		}

	}

	function getTextureEncodingFromMap( map, gammaOverrideLinear ) {

		var encoding;

		if ( ! map ) {

			encoding = LinearEncoding;

		} else if ( map.isTexture ) {

			encoding = map.encoding;

		} else if ( map.isWebGLRenderTarget ) {

			console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
			encoding = map.texture.encoding;

		}

		// add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
		if ( encoding === LinearEncoding && gammaOverrideLinear ) {

			encoding = GammaEncoding;

		}

		return encoding;

	}

	this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {

		var shaderID = shaderIDs[ material.type ];

		// heuristics to create shader parameters according to lights in the scene
		// (not to blow over maxLights budget)

		var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;

		if ( material.precision !== null ) {

			precision = capabilities.getMaxPrecision( material.precision );

			if ( precision !== material.precision ) {

				console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );

			}

		}

		var currentRenderTarget = renderer.getRenderTarget();

		var parameters = {

			isWebGL2: isWebGL2,

			shaderID: shaderID,

			precision: precision,

			instancing: object.isInstancedMesh === true,

			supportsVertexTextures: vertexTextures,
			outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
			map: !! material.map,
			mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
			matcap: !! material.matcap,
			matcapEncoding: getTextureEncodingFromMap( material.matcap, renderer.gammaInput ),
			envMap: !! material.envMap,
			envMapMode: material.envMap && material.envMap.mapping,
			envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
			envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
			lightMap: !! material.lightMap,
			aoMap: !! material.aoMap,
			emissiveMap: !! material.emissiveMap,
			emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
			bumpMap: !! material.bumpMap,
			normalMap: !! material.normalMap,
			objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
			tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
			clearcoatNormalMap: !! material.clearcoatNormalMap,
			displacementMap: !! material.displacementMap,
			roughnessMap: !! material.roughnessMap,
			metalnessMap: !! material.metalnessMap,
			specularMap: !! material.specularMap,
			alphaMap: !! material.alphaMap,

			gradientMap: !! material.gradientMap,

			sheen: !! material.sheen,

			combine: material.combine,

			vertexTangents: ( material.normalMap && material.vertexTangents ),
			vertexColors: material.vertexColors,
			vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap,

			fog: !! fog,
			useFog: material.fog,
			fogExp2: ( fog && fog.isFogExp2 ),

			flatShading: material.flatShading,

			sizeAttenuation: material.sizeAttenuation,
			logarithmicDepthBuffer: logarithmicDepthBuffer,

			skinning: material.skinning && maxBones > 0,
			maxBones: maxBones,
			useVertexTexture: floatVertexTextures,

			morphTargets: material.morphTargets,
			morphNormals: material.morphNormals,
			maxMorphTargets: renderer.maxMorphTargets,
			maxMorphNormals: renderer.maxMorphNormals,

			numDirLights: lights.directional.length,
			numPointLights: lights.point.length,
			numSpotLights: lights.spot.length,
			numRectAreaLights: lights.rectArea.length,
			numHemiLights: lights.hemi.length,

			numDirLightShadows: lights.directionalShadowMap.length,
			numPointLightShadows: lights.pointShadowMap.length,
			numSpotLightShadows: lights.spotShadowMap.length,

			numClippingPlanes: nClipPlanes,
			numClipIntersection: nClipIntersection,

			dithering: material.dithering,

			shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
			shadowMapType: renderer.shadowMap.type,

			toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
			physicallyCorrectLights: renderer.physicallyCorrectLights,

			premultipliedAlpha: material.premultipliedAlpha,

			alphaTest: material.alphaTest,
			doubleSided: material.side === DoubleSide,
			flipSided: material.side === BackSide,

			depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false

		};

		return parameters;

	};

	this.getProgramCode = function ( material, parameters ) {

		var array = [];

		if ( parameters.shaderID ) {

			array.push( parameters.shaderID );

		} else {

			array.push( material.fragmentShader );
			array.push( material.vertexShader );

		}

		if ( material.defines !== undefined ) {

			for ( var name in material.defines ) {

				array.push( name );
				array.push( material.defines[ name ] );

			}

		}

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

			array.push( parameters[ parameterNames[ i ] ] );

		}

		array.push( material.onBeforeCompile.toString() );

		array.push( renderer.gammaOutput );

		array.push( renderer.gammaFactor );

		return array.join();

	};

	this.acquireProgram = function ( material, shader, parameters, code ) {

		var program;

		// Check if code has been already compiled
		for ( var p = 0, pl = programs.length; p < pl; p ++ ) {

			var programInfo = programs[ p ];

			if ( programInfo.code === code ) {

				program = programInfo;
				++ program.usedTimes;

				break;

			}

		}

		if ( program === undefined ) {

			program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
			programs.push( program );

		}

		return program;

	};

	this.releaseProgram = function ( program ) {

		if ( -- program.usedTimes === 0 ) {

			// Remove from unordered set
			var i = programs.indexOf( program );
			programs[ i ] = programs[ programs.length - 1 ];
			programs.pop();

			// Free WebGL resources
			program.destroy();

		}

	};

	// Exposed for resource monitoring & error feedback via renderer.info:
	this.programs = programs;

}

export { WebGLPrograms };
<|endoftext|>