<commit_before>/* ========================================================================
 * DBH-PG: test
 * ========================================================================
 * Copyright 2014 Sapienlab
 * Licensed under MIT (https://github.com/sapienlab/dbh-pg/blob/master/LICENSE)
 * ======================================================================== */
'use strict';

describe('DBH', function() {

    var assert = require('assert'),
        DBH = require('../'),
        Promise = require('bluebird'),
        using = Promise.using,
        db = new DBH('postgres://postgres@localhost/db2test'),
        people = [
            {name: 'Aaron',    age: 10},
            {name: 'Brian',    age: 20},
            {name: 'Chris',    age: 30},
            {name: 'David',    age: 40},
            {name: 'Elvis',    age: 50},
            {name: 'Frank',    age: 60},
            {name: 'Grace',    age: 70},
            {name: 'Haley',    age: 80},
            {name: 'Irma',     age: 90},
            {name: 'Jenny',    age: 100},
            {name: 'Kevin',    age: 110},
            {name: 'Larry',    age: 120},
            {name: 'Michelle', age: 130},
            {name: 'Nancy',    age: 140},
            {name: 'Olivia',   age: 150},
            {name: 'Peter',    age: 160},
            {name: 'Quinn',    age: 170},
            {name: 'Ronda',    age: 180},
            {name: 'Shelley',  age: 190},
            {name: 'Tobias',   age: 200},
            {name: 'Uma',      age: 210},
            {name: 'Veena',    age: 220},
            {name: 'Wanda',    age: 230},
            {name: 'Xavier',   age: 240},
            {name: 'Yoyo',     age: 250},
            {name: 'Zanzabar', age: 260}
        ];

    before(function() {

        Promise.longStackTraces();

        db.verbose = true;

        return using(db.conn(), function (conn) {
            return conn.exec(
                'create table person(\
                    id serial primary key,\
                    name varchar(10),\
                    age integer\
                )'
            ).then(function () {
                var me = this,
                prepared = DBH.prepare('insert into person(name, age) values ($1, $2)');
                return Promise.all(people.map(function (person) {
                    return me.exec(prepared([person.name, person.age]));
                }));
            })
        });

    });

    describe('elemental', function() {

        it('db is instance of DBH', function() {
            assert.equal(db instanceof DBH, true);
        });

    });

    describe('#conn', function() {

        it('create connection', function() {
            return using(db.conn(), function (conn) {
                return true;
            });
        });

        it('exec "select count(age) from person" whith conn.exec', function() {
            return using(db.conn(), function (conn) {
                return conn.exec('select count(age) from person')
                    .then(function (result) {
                        assert.equal(result.rows[0].count, 26);
                    });
            });
        });

        it('exec "select count(age) from person" whith conn.count', function() {
            return using(db.conn(), function (conn) {
                return conn.count('person')
                    .then(function (count) {
                        assert.equal(count, 26);
                    });
            });
        });

        it('exec "select count(age) from person" whith conn.fetchScalar', function() {
            return using(db.conn(), function (conn) {
                return conn.fetchScalar('select count(age) from person')
                    .then(function (count) {
                        assert.equal(count, 26);
                    });
            });
        });

    });

    describe('transactions', function () {

        it('without commit', function() {
            var oldName = 'Old Name',
                newName = 'New Name',
                query = 'select name from person where id=1';
            return using(db.conn(), function (conn) {
                return conn.update('person', { name: oldName }, { id : 1})
                    .then(DBH.fetchScalar(query))
                    .then(function (name) {
                        assert.equal(name, oldName);
                    })
                    .then(DBH.begin) // start transaction
                    .then(DBH.update('person', { name: newName }, { id: 1 }));
                // because not commit is here, then auto rollback must be called
            }).then(function () {
                return using(db.conn(), function (conn) {
                    return conn.fetchScalar(query)
                        .then(function (name) {
                            assert.equal(oldName, name);
                            assert.notEqual(name, newName);
                        });
                });
            });
        });

        it('with commit', function() {
            var oldName = 'Old Name',
                newName = 'New Name',
                query = 'select name from person where id=1';
            return using(db.conn(), function (conn) {
                return conn.update('person', { name: oldName }, { id : 1})
                    .then(DBH.fetchScalar(query))
                    .then(function (name) {
                        assert.equal(name, oldName);
                    })
                    .then(DBH.begin) // start transaction
                    .then(DBH.update('person', { name: newName }, { id: 1 }))
                    .then(DBH.commit);
            }).then(function () {
                return using(db.conn(), function (conn) {
                    return conn.fetchScalar(query)
                        .then(function (name) {
                            assert.notEqual(oldName, name);
                            assert.equal(name, newName);
                        });
                });
            });
        });

    })

});
<commit_msg>Update db.js<commit_after>/* ========================================================================
 * DBH-PG: test
 * ========================================================================
 * Copyright 2014 Sapienlab
 * Licensed under MIT (https://github.com/sapienlab/dbh-pg/blob/master/LICENSE)
 * ======================================================================== */
'use strict';

describe('DBH', function() {

    var assert = require('assert'),
        DBH = require('../'),
        Promise = require('bluebird'),
        using = Promise.using,
        db = new DBH('postgres://postgres@localhost/db2test'),
        people = [
            {name: 'Aaron',    age: 10},
            {name: 'Brian',    age: 20},
            {name: 'Chris',    age: 30},
            {name: 'David',    age: 40},
            {name: 'Elvis',    age: 50},
            {name: 'Frank',    age: 60},
            {name: 'Grace',    age: 70},
            {name: 'Haley',    age: 80},
            {name: 'Irma',     age: 90},
            {name: 'Jenny',    age: 100},
            {name: 'Kevin',    age: 110},
            {name: 'Larry',    age: 120},
            {name: 'Michelle', age: 130},
            {name: 'Nancy',    age: 140},
            {name: 'Olivia',   age: 150},
            {name: 'Peter',    age: 160},
            {name: 'Quinn',    age: 170},
            {name: 'Ronda',    age: 180},
            {name: 'Shelley',  age: 190},
            {name: 'Tobias',   age: 200},
            {name: 'Uma',      age: 210},
            {name: 'Veena',    age: 220},
            {name: 'Wanda',    age: 230},
            {name: 'Xavier',   age: 240},
            {name: 'Yoyo',     age: 250},
            {name: 'Zanzabar', age: 260}
        ];

    before(function() {

        Promise.longStackTraces();

        db.verbose = true;

        return using(db.conn(), function (conn) {
            return conn.exec(
                'create table person(\
                    id serial primary key,\
                    name varchar(10),\
                    age integer\
                )'
            ).then(function () {
                var me = this,
                prepared = DBH.prepare('insert into person(name, age) values ($1, $2)');
                return Promise.all(people.map(function (person) {
                    return me.exec(prepared([person.name, person.age]));
                }));
            })
        });

    });

    describe('elemental', function() {

        it('db is instance of DBH', function() {
            assert.equal(db instanceof DBH, true);
        });

    });

    describe('#conn', function() {

        it('create connection', function() {
            return using(db.conn(), function (conn) {
                return true;
            });
        });

        it('exec "select count(age) from person" whith conn.exec', function() {
            return using(db.conn(), function (conn) {
                return conn.exec('select count(age) from person')
                    .then(function (result) {
                        assert.equal(result.rows[0].count, 26);
                    });
            });
        });

        it('exec "select count(age) from person" whith conn.count', function() {
            return using(db.conn(), function (conn) {
                return conn.count('person')
                    .then(function (count) {
                        assert.equal(count, 26);
                    });
            });
        });

        it('exec "select count(age) from person" whith conn.fetchScalar', function() {
            return using(db.conn(), function (conn) {
                return conn.fetchScalar('select count(age) from person')
                    .then(function (count) {
                        assert.equal(count, 26);
                    });
            });
        });

    });

    describe('transactions', function () {

        it('without commit', function() {
            var id = 1,
                oldName = 'Old Name',
                newName = 'New Name',
                query = 'select name from person where id=' + id;
            return using(db.conn(), function (conn) {
                return conn.update('person', { name: oldName }, { id : id })
                    .then(DBH.fetchScalar(query))
                    .then(function (name) {
                        assert.equal(name, oldName);
                    })
                    .then(DBH.begin) // start transaction
                    .then(DBH.update('person', { name: newName }, { id: id }));
                // because not commit is here, then auto rollback must be called
            }).then(function () {
                return using(db.conn(), function (conn) {
                    return conn.fetchScalar(query)
                        .then(function (name) {
                            assert.equal(oldName, name);
                            assert.notEqual(name, newName);
                        });
                });
            });
        });

        it('with commit', function() {
            var id = 2,
                oldName = 'Old Name',
                newName = 'New Name',
                query = 'select name from person where id=' + id;
            return using(db.conn(), function (conn) {
                return conn.update('person', { name: oldName }, { id : id })
                    .then(DBH.fetchScalar(query))
                    .then(function (name) {
                        assert.equal(name, oldName);
                    })
                    .then(DBH.begin) // start transaction
                    .then(DBH.update('person', { name: newName }, { id: id }))
                    .then(DBH.commit);
            }).then(function () {
                return using(db.conn(), function (conn) {
                    return conn.fetchScalar(query)
                        .then(function (name) {
                            assert.notEqual(oldName, name);
                            assert.equal(name, newName);
                        });
                });
            });
        });

    })

});
<|endoftext|>


<commit_before>'use strict';

module.exports = PLS;
var Matrix = require('ml-matrix');
var Stat = require('ml-stat');

/**
* Function that pow 2 each element of a Matrix or a Vector,
* used in the apply method of the Matrix object
* @param i - index i.
* @param j - index j.
* @return The Matrix object modified at the index i, j.
* */
function pow2array(i, j) {
    this[i][j] = this[i][j] * this[i][j];
    return this;
}

/**
 * Function that given vector, returns his norm
 * @param {Vector} X
 * @returns {number} Norm of the vector
 */
function norm(X) {
    return Math.sqrt(X.clone().apply(pow2array).sum());
}

/**
 * Function that returns the index where the sum of each
 * column vector is maximum.
 * @param {Matrix} X
 * @returns {number} index of the maximum
 */
function maxSumColIndex(X) {
    var maxIndex = 0;
    var maxSum = -Infinity;
    for(var i = 0; i < X.column; ++i) {
        var currentSum = X.getColumnVector(i).sum();
        if(currentSum > maxSum) {
            maxSum = currentSum;
            maxIndex = i;
        }
    }
    return i;
}

/**
 * Construction of the PLS model that takes
 * @param {Matrix} dataset - Dataset to be apply the model
 * @param {Matrix} predictions - Predictions over each case of the dataset
 * @param reload - used internally for load purposes.
 * @constructor
 * @throws RangeError - if the number of elements in predictions isn't be
 *                      the same to the dataset
 */
function PLS(dataset, predictions, reload) {
    if(reload) {
        this.ymean = dataset.ymean;
        this.ystd = dataset.ystd;
        this.PBQ = dataset.PBQ;
    } else {
        if(dataset.length !== predictions.length)
            throw new RangeError("The number of predictions and elements in the dataset must be the same");

        var tolerance = 1e-10;
        var X = featureNormalize(Matrix(dataset).clone()).result;
        var resultY = featureNormalize(Matrix(predictions).clone());
        this.ymean = resultY.means;
        this.ystd = resultY.std;
        var Y = resultY.result;

        var rx = X.rows;
        var cx = X.columns;
        var ry = Y.rows;
        var cy = Y.columns;

        if(rx != ry) {
            throw new Error("dataset cases is not the same as the predictions");
        }

        var n = Math.max(cx, cy);
        var T = Matrix.zeros(rx, n);
        var P = Matrix.zeros(cx, n);
        var U = Matrix.zeros(ry, n);
        var Q = Matrix.zeros(cy, n);
        var B = Matrix.zeros(n, n);
        var W = P.clone();
        var k = 0;

        while(norm(Y) > tolerance && k < n) {
            var transposeX = X.transpose();
            var transposeY = Y.transpose();

            var tIndex = maxSumColIndex(X.clone().mulM(X));
            var uIndex = maxSumColIndex(Y.clone().mulM(Y));

            var t1 = X.getColumnVector(tIndex);
            var u = Y.getColumnVector(uIndex);
            var t = Matrix.zeros(rx, 1);

            while(norm(t1.clone().sub(t)) > tolerance) {
                var w = transposeX.mmul(u);
                w.div(norm(w));
                t = t1;
                t1 = X.mmul(w);
                var q = transposeY.mmul(t1);
                q.div(norm(q));
                var u = Y.mmul(q);
            }

            t = t1;
            var num = transposeX.mmul(t);
            var den = (t.transpose().mmul(t))[0][0];
            var p = num.div(den);
            var pnorm = norm(p);
            p.div(pnorm);
            t.mul(pnorm);
            w.mul(pnorm);

            num = u.transpose().mmul(t);
            var b = (num.div(den))[0][0];
            X.sub(t.mmul(p.transpose()));
            Y.sub(t.mmul(q.transpose()).mul(b));

            T.addColumn(k, t);
            P.addColumn(k, p);
            U.addColumn(k, u);
            Q.addColumn(k, q);
            W.addColumn(k, w);
            B[k][k] = b;
            k++;
        }

        // NOTE: some variables commented because maybe it's needed
        // in the future

        k--;
        n--;
        //T = T.subMatrix(0, n, 0, k);
        P = P.subMatrix(0, n, 0, k);
        //U = U.subMatrix(0, n, 0, k);
        Q = Q.subMatrix(0, n, 0, k);
        //W = W.subMatrix(0, n, 0, k);
        B = B.subMatrix(0, k, 0, k);

        // this.T = T;
        // this.P = P;
        // this.U = U;
        // this.Q = Q;
        // this.W = W;
        // this.B = B;
        this.PBQ = P.mmul(B).mmul(Q.transpose());
    }
}
/**
 * Load a PLS model from an Object
 * @param model
 * @returns {PLS} - PLS object from the given model
 */
PLS.load = function (model) {
    if(model.modelName !== 'PLS')
        throw new RangeError("The current model is invalid!");

    return new PLS(model, null, true);
};

/**
 * Function that predict the behavior of the given dataset.
 * @param dataset - data to be predicted.
 * @returns {Matrix} - predictions of each element of the dataset.
 */
PLS.prototype.predict = function (dataset) {
    var X = Matrix(dataset).clone();
    var normalization = featureNormalize(X);
    X = normalization.result;
    var means = normalization.means;
    var std = normalization.std;
    var Y = X.mmul(this.PBQ);
    Y.mulRowVector(this.ystd);
    // be careful because its suposed to be a sumRowVector but the mean
    // is negative here in the case of the and
    Y.subRowVector(this.ymean);
    return Y;
};

/**
 * Function that normalize the dataset and return the means and
 * standard deviation of each feature.
 * @param dataset
 * @returns {{result: Matrix, means: (*|number), std: Matrix}}
 */
function featureNormalize(dataset) {
    var means = Stat.matrix.mean(dataset);
    var std = Matrix.rowVector(Stat.matrix.standardDeviation(dataset, means, true));
    means = Matrix.rowVector(means);

    var result = dataset.addRowVector(means.neg());
    return {result: result.divRowVector(std), means: means, std: std};
}
<commit_msg>Load function added.<commit_after>'use strict';

module.exports = PLS;
var Matrix = require('ml-matrix');
var Stat = require('ml-stat');

/**
* Function that pow 2 each element of a Matrix or a Vector,
* used in the apply method of the Matrix object
* @param i - index i.
* @param j - index j.
* @return The Matrix object modified at the index i, j.
* */
function pow2array(i, j) {
    this[i][j] = this[i][j] * this[i][j];
    return this;
}

/**
 * Function that given vector, returns his norm
 * @param {Vector} X
 * @returns {number} Norm of the vector
 */
function norm(X) {
    return Math.sqrt(X.clone().apply(pow2array).sum());
}

/**
 * Function that returns the index where the sum of each
 * column vector is maximum.
 * @param {Matrix} X
 * @returns {number} index of the maximum
 */
function maxSumColIndex(X) {
    var maxIndex = 0;
    var maxSum = -Infinity;
    for(var i = 0; i < X.column; ++i) {
        var currentSum = X.getColumnVector(i).sum();
        if(currentSum > maxSum) {
            maxSum = currentSum;
            maxIndex = i;
        }
    }
    return i;
}

/**
 * Construction of the PLS model that takes
 * @param {Matrix} dataset - Dataset to be apply the model
 * @param {Matrix} predictions - Predictions over each case of the dataset
 * @param reload - used internally for load purposes.
 * @constructor
 * @throws RangeError - if the number of elements in predictions isn't be
 *                      the same to the dataset
 */
function PLS(dataset, predictions, reload) {
    if(reload) {
        this.ymean = dataset.ymean;
        this.ystd = dataset.ystd;
        this.PBQ = dataset.PBQ;
    } else {
        if(dataset.length !== predictions.length)
            throw new RangeError("The number of predictions and elements in the dataset must be the same");

        var tolerance = 1e-10;
        var X = featureNormalize(Matrix(dataset).clone()).result;
        var resultY = featureNormalize(Matrix(predictions).clone());
        this.ymean = resultY.means;
        this.ystd = resultY.std;
        var Y = resultY.result;

        var rx = X.rows;
        var cx = X.columns;
        var ry = Y.rows;
        var cy = Y.columns;

        if(rx != ry) {
            throw new Error("dataset cases is not the same as the predictions");
        }

        var n = Math.max(cx, cy);
        var T = Matrix.zeros(rx, n);
        var P = Matrix.zeros(cx, n);
        var U = Matrix.zeros(ry, n);
        var Q = Matrix.zeros(cy, n);
        var B = Matrix.zeros(n, n);
        var W = P.clone();
        var k = 0;

        while(norm(Y) > tolerance && k < n) {
            var transposeX = X.transpose();
            var transposeY = Y.transpose();

            var tIndex = maxSumColIndex(X.clone().mulM(X));
            var uIndex = maxSumColIndex(Y.clone().mulM(Y));

            var t1 = X.getColumnVector(tIndex);
            var u = Y.getColumnVector(uIndex);
            var t = Matrix.zeros(rx, 1);

            while(norm(t1.clone().sub(t)) > tolerance) {
                var w = transposeX.mmul(u);
                w.div(norm(w));
                t = t1;
                t1 = X.mmul(w);
                var q = transposeY.mmul(t1);
                q.div(norm(q));
                var u = Y.mmul(q);
            }

            t = t1;
            var num = transposeX.mmul(t);
            var den = (t.transpose().mmul(t))[0][0];
            var p = num.div(den);
            var pnorm = norm(p);
            p.div(pnorm);
            t.mul(pnorm);
            w.mul(pnorm);

            num = u.transpose().mmul(t);
            var b = (num.div(den))[0][0];
            X.sub(t.mmul(p.transpose()));
            Y.sub(t.mmul(q.transpose()).mul(b));

            T.addColumn(k, t);
            P.addColumn(k, p);
            U.addColumn(k, u);
            Q.addColumn(k, q);
            W.addColumn(k, w);
            B[k][k] = b;
            k++;
        }

        // NOTE: some variables commented because maybe it's needed
        // in the future

        k--;
        n--;
        //T = T.subMatrix(0, n, 0, k);
        P = P.subMatrix(0, n, 0, k);
        //U = U.subMatrix(0, n, 0, k);
        Q = Q.subMatrix(0, n, 0, k);
        //W = W.subMatrix(0, n, 0, k);
        B = B.subMatrix(0, k, 0, k);

        // this.T = T;
        // this.P = P;
        // this.U = U;
        // this.Q = Q;
        // this.W = W;
        // this.B = B;
        this.PBQ = P.mmul(B).mmul(Q.transpose());
    }
}

/**
 * Load a PLS model from an Object
 * @param model
 * @returns {PLS} - PLS object from the given model
 */
PLS.load = function (model) {
    if(model.modelName !== 'PLS')
        throw new RangeError("The current model is invalid!");

    return new PLS(model, null, true);
};

/**
 * Function that predict the behavior of the given dataset.
 * @param dataset - data to be predicted.
 * @returns {Matrix} - predictions of each element of the dataset.
 */
PLS.prototype.predict = function (dataset) {
    var X = Matrix(dataset).clone();
    var normalization = featureNormalize(X);
    X = normalization.result;
    var means = normalization.means;
    var std = normalization.std;
    var Y = X.mmul(this.PBQ);
    Y.mulRowVector(this.ystd);
    // be careful because its suposed to be a sumRowVector but the mean
    // is negative here in the case of the and
    Y.subRowVector(this.ymean);
    return Y;
};

/**
 * Function that normalize the dataset and return the means and
 * standard deviation of each feature.
 * @param dataset
 * @returns {{result: Matrix, means: (*|number), std: Matrix}}
 */
function featureNormalize(dataset) {
    var means = Stat.matrix.mean(dataset);
    var std = Matrix.rowVector(Stat.matrix.standardDeviation(dataset, means, true));
    means = Matrix.rowVector(means);

    var result = dataset.addRowVector(means.neg());
    return {result: result.divRowVector(std), means: means, std: std};
}
<|endoftext|>


<commit_before>/* globals d3:false */

var pty = {
    version: '0.1.0'  // semver
};

// Charting Module
pty.chart = {};

// Network Chart
// -------------

pty.chart.network = function() {

    // Chart Attributes
    var me = {
        width: 400,
        height: 400,
        nodeRadius: 20,
        charge: function(d, i) { return -4e3; },
        friction: 0.5,
        linkStrength: 0.2,
        linkDistance: 120,
        // onClick: function(d, i) {},
        nodeClass: function(d, i) { return ''; },
        nodeBaseURL: function(d) { return ''; },
        chartURL: function(d) { return ''; },
        nodeLabel: function(d, i) { return ''; },
        fixCenter: true,
        initialData: {} //Implement 'DO NOTHING' if left undefined
    };

    // Charting Function
    function chart(selection) {
        selection.each(function(data) {

            var div = d3.select(this),
                svg = div.selectAll('svg').data([data]);

            // Data Preprocessing
            // ------------------

            var idx = {},
                dataNodes = [],
                k = 0;

            // Identify unique nodes and construct a dictionary of indices
            data.nodes.forEach(function(d) {
                if (!idx.hasOwnProperty(d.id)) {
                    idx[d.id] = k;
                    k += 1;
                    dataNodes.push(d);
                }
            });

            dataNodes.forEach( function(d) {
                d.internalcn = 0;
            });

            // Identify unique links and set the source and target of each one
            k = 0;
            var idxLinks = {}, dataLinks = [];

            data.links.forEach(function(d) {

                d.source = Math.min(idx[d.from], idx[d.to]);
                d.target = Math.max(idx[d.from], idx[d.to]);
                d.linkID = d.source + '-' + d.target;

                if (!idxLinks.hasOwnProperty(d.linkID)) {
                    idxLinks[d.linkID] = k;
                    dataLinks.push(d);
                    dataNodes[idx[d.from]].internalcn += 1;
                    dataNodes[idx[d.to]].internalcn += 1;
                    k += 1;
                }
            });

            dataNodes.forEach( function(d) {
                d.isclick = (d.internalcn < d.numcn);
            });

            // Fix the center node
            dataNodes.forEach(function(d) {
                if (d.id === data.root) {
                    d.x = me.width / 2;
                    d.y = me.height / 2;
                    d.fixed = me.fixCenter;
                }
            });

            function onClick(d, i) {
                d3.json(me.nodeBaseURL(d), function(error, data) {
                    var olddata;

                    if (!error) {
                        olddata = div.data()[0];
                        olddata.nodes = olddata.nodes.concat(data.nodes);
                        olddata.links = olddata.links.concat(data.links);

                        div.data([olddata]).call(chart);
                    }
                });
                d.isclick = false;
            }

            function printURL(d, i) {
                var myURL = me.chartURL(d);
                console.log(myURL);
                return myURL;
            }

            // Initialization
            // --------------

            // Initialize the SVG element
            var svgEnter = svg.enter().append('svg')
                .attr('width', me.width)
                .attr('height', me.height)
                .call(chart.init);

            var g = svg.select('g.network-chart'),
                glinks = g.select('g.links'),
                gnodes = g.select('g.nodes'),
                glabels = g.select('g.labels'),
                gbrand = g.select('g.brand'),
               // gnodeURL = g.select('g.nodeURL'),
                grefresh = g.select('g.button');

            // Force layout
            // ------------

            var force = d3.layout.force()
                .charge(me.charge)
                .friction(me.friction)
                .linkStrength(me.linkStrength)
                .size([me.width, me.height]);

            force.nodes(dataNodes)
                .links(dataLinks)
                .start();

            // Graphic Elements
            // ----------------

            // Links
            // -----

            var links = glinks.selectAll('line.link')
                .data(force.links(), function(d) { return d.linkID; });

            links.enter().append('line')
                .attr('class', 'link')
                .classed('center-link', function(d) {
                    return (d.from === data.root) || (d.to === data.root);
                });

            // Remove unused links
            links.exit().remove();

            // Nodes
            // -----

            var circles = gnodes.selectAll('circle.node')
                .data(force.nodes(), function(d) { return d.id; });

            // Update
            circles.classed('node-clickable', function(d) { return d.isclick; });

            circles.enter().append('circle')
                .attr('class', function(d, i) {
                    return me.nodeClass(d, i) + ' node';
                })
                .attr('r', me.nodeRadius)
                .classed('node', true)
                .classed('node-center', function(d) { return d.id === data.root; })
                .classed('node-clickable', function(d) { return (d.id !== data.root) && (d.isclick); })
                .on('mouseover', function(d) {
                    d3.select(this).classed('node-highlight', true);
                })
                .on('mouseout', function(d) {
                    d3.select(this).classed('node-highlight', false);
                })
                .on('click', function(d, i) {
                    if (d3.select(this).classed('node-clickable')) {
                        onClick(d, i);
                        gnodeurl.selectAll('text').remove();
                        gnodeurl.append('text').attr('text-anchor','start').text(printURL(d));
                    }
                    else {
                    gnodeurl.selectAll('text').remove();
                    gnodeurl.append('text').attr('text-anchor','start').text(printURL(d)); //URL does not update properly.
                }
                });

            circles.call(force.drag);

            circles.exit().remove();

            // Labels
            // ------

            var words = glabels.selectAll('text.node-label')
                .data(force.nodes(), function(d) { return d.id; });

            words.enter().append('text')
                .text(me.nodeLabel)
                .attr('x', function(d, i) { return d.x + me.nodeRadius; })
                .attr('y', function(d, i) { return d.y - me.nodeRadius; })
                .attr('class', 'node-label');

            words.exit().remove();

            // Force On Tick
            force.on('tick', function() {
                links
                    .attr("x1", function(d) { return d.source.x; })
                    .attr("y1", function(d) { return d.source.y; })
                    .attr("x2", function(d) { return d.target.x; })
                    .attr("y2", function(d) { return d.target.y; });

                circles
                    .attr('cx', function(d) { return d.x; })
                    .attr('cy', function(d) { return d.y; });

                words
                    .attr('x', function(d, i) { return d.x + me.nodeRadius; })
                    .attr('y', function(d, i) { return d.y - me.nodeRadius; });

            });

            //Other elements
            //--------------
            var gbutton = g.append('g')
               .attr('class','button')
               .attr('transform','translate(' +  [10,10] +')');

            //Refresh button
            var refreshButton = gbutton.append('circle')
                                   .attr('cx',10)
                                   .attr('cy',10)
                                   .attr('r',10)
                                   .attr('fill','white')
                                   .attr('stroke','black')
                                   .attr('stroke-width',2)
                                   .attr('cursor','pointer')
                                   .on('click', function() {

                                    d3.json(me.initialData, function(error,data) {
                                        div.data([data]).call(chart);
                                    })

                                   } );

             gbutton.append('text')
                .attr('x',4)
                .attr('y',15)
                .attr('cursor','pointer')
                .attr('font-family', 'FontAwesome')
                .text('\uf0e2' )
                .on('click', function() {

                                    d3.json(me.initialData, function(error,data) {
                                        div.data([data]).call(chart);
                                    })

                                   } );

            //Container for the url
            var gnodeurl = svgEnter.append('g')
                            .attr('class','urlcontainer')
                            .attr('transform','translate(' + [4, me.height -8 ] +')');

            gnodeurl.append('text').attr('text-anchor','start').text("Hi five!");

        });
    }

    chart.init = function(selection) {
        selection.each(function(data) {

            var initial = selection;

            var svgEnter = d3.select(this),
                gcont = svgEnter.append('g').attr('class', 'network-chart');

            // Add a background group and rectangle
            gcont.append('g')
                .attr('class', 'background')
                .append('rect')
                .attr('width', me.width)
                .attr('height', me.height)
                .attr('class', 'background');

            gcont.append('g').attr('class', 'links');
            gcont.append('g').attr('class', 'nodes');
            gcont.append('g').attr('class', 'labels');

            var gbrand = gcont.append('g')
                .attr('class', 'brand')
                .attr('transform', 'translate(' + [me.width - 4, me.height - 4] + ')');

            var brandLabel = gbrand.append('a')
                .attr('xlink:href', 'http://www.masega.co')
                .append('text')
                .attr('class', 'masega-brand')
                .attr('text-anchor', 'end')
                .text('masega.co');

            // var gnodeurl = gcont.append('g')
            //                 .attr('class','urlcontainer')
            //                 .attr('transform','translate(' + [4, me.height -8 ] +')');

            // var gprintnodeurl = gnodeurl.append('a')
            //                 .attr('xlink:href', me.chartURL(this))
            //                 .append('text')
            //                 .attr('text-anchor','start')
            //                 .text("hola");

            // var gbutton = gcont.append('g')
            //    .attr('class','button')
            //    .attr('transform','translate(' +  [10,10] +')');

            // var refreshButton = gbutton.append('rect')
            //                        .attr('width',20)
            //                        .attr('height',20)
            //                        .attr('fill','black')
            //                        .on('click', function() { gcont.data([initialData]).call(chart); } );

        });
    };

    // Accessor Methods

    // Generate Accessor Methods
    function createAccessor(attr) {
        return function(value) {
            if (!arguments.length) { return me[attr]; }
            me[attr] = value;
            return chart;
        };
    }

    for (var attr in me) {
        if ((!chart[attr]) && (me.hasOwnProperty(attr))) {
            chart[attr] = createAccessor(attr);
        }
    }

    return chart;
};<commit_msg>CHange the way the refresh button works. Now appeals to the json of the root.<commit_after>/* globals d3:false */

var pty = {
    version: '0.1.0'  // semver
};

// Charting Module
pty.chart = {};

// Network Chart
// -------------

pty.chart.network = function() {

    // Chart Attributes
    var me = {
        width: 400,
        height: 400,
        nodeRadius: 20,
        charge: function(d, i) { return -4e3; },
        friction: 0.5,
        linkStrength: 0.2,
        linkDistance: 120,
        // onClick: function(d, i) {},
        nodeClass: function(d, i) { return ''; },
        nodeBaseURL: function(d) { return ''; },
        chartURL: function(d) { return ''; },
        nodeLabel: function(d, i) { return ''; },
        fixCenter: true,
        initialData: {} //Implement 'DO NOTHING' if left undefined
    };

    // Charting Function
    function chart(selection) {
        selection.each(function(data) {

            var div = d3.select(this),
                svg = div.selectAll('svg').data([data]);

            // Data Preprocessing
            // ------------------

            var idx = {},
                dataNodes = [],
                k = 0;

            // Identify unique nodes and construct a dictionary of indices
            data.nodes.forEach(function(d) {
                if (!idx.hasOwnProperty(d.id)) {
                    idx[d.id] = k;
                    k += 1;
                    dataNodes.push(d);
                }
            });

            dataNodes.forEach( function(d) {
                d.internalcn = 0;
            });

            // Identify unique links and set the source and target of each one
            k = 0;
            var idxLinks = {}, dataLinks = [];

            data.links.forEach(function(d) {

                d.source = Math.min(idx[d.from], idx[d.to]);
                d.target = Math.max(idx[d.from], idx[d.to]);
                d.linkID = d.source + '-' + d.target;

                if (!idxLinks.hasOwnProperty(d.linkID)) {
                    idxLinks[d.linkID] = k;
                    dataLinks.push(d);
                    dataNodes[idx[d.from]].internalcn += 1;
                    dataNodes[idx[d.to]].internalcn += 1;
                    k += 1;
                }
            });

            dataNodes.forEach( function(d) {
                d.isclick = (d.internalcn < d.numcn);
            });

            // Fix the center node
            dataNodes.forEach(function(d) {
                if (d.id === data.root) {
                    d.x = me.width / 2;
                    d.y = me.height / 2;
                    d.fixed = me.fixCenter;
                }
            });

            function onClick(d, i) {
                d3.json(me.nodeBaseURL(d), function(error, data) {
                    var olddata;

                    if (!error) {
                        olddata = div.data()[0];
                        olddata.nodes = olddata.nodes.concat(data.nodes);
                        olddata.links = olddata.links.concat(data.links);

                        div.data([olddata]).call(chart);
                    }
                });
                d.isclick = false;
            }

            function printURL(d, i) {
                var myURL = me.chartURL(d);
                console.log(myURL);
                return myURL;
            }

            // Initialization
            // --------------

            // Initialize the SVG element
            var svgEnter = svg.enter().append('svg')
                .attr('width', me.width)
                .attr('height', me.height)
                .call(chart.init);

            var g = svg.select('g.network-chart'),
                glinks = g.select('g.links'),
                gnodes = g.select('g.nodes'),
                glabels = g.select('g.labels'),
                gbrand = g.select('g.brand'),
               // gnodeURL = g.select('g.nodeURL'),
                grefresh = g.select('g.button');

            // Force layout
            // ------------

            var force = d3.layout.force()
                .charge(me.charge)
                .friction(me.friction)
                .linkStrength(me.linkStrength)
                .size([me.width, me.height]);

            force.nodes(dataNodes)
                .links(dataLinks)
                .start();

            // Graphic Elements
            // ----------------

            // Links
            // -----

            var links = glinks.selectAll('line.link')
                .data(force.links(), function(d) { return d.linkID; });

            links.enter().append('line')
                .attr('class', 'link')
                .classed('center-link', function(d) {
                    return (d.from === data.root) || (d.to === data.root);
                });

            // Remove unused links
            links.exit().remove();

            // Nodes
            // -----

            var circles = gnodes.selectAll('circle.node')
                .data(force.nodes(), function(d) { return d.id; });

            // Update
            circles.classed('node-clickable', function(d) { return d.isclick; });

            circles.enter().append('circle')
                .attr('class', function(d, i) {
                    return me.nodeClass(d, i) + ' node';
                })
                .attr('r', me.nodeRadius)
                .classed('node', true)
                .classed('node-center', function(d) { return d.id === data.root; })
                .classed('node-clickable', function(d) { return (d.id !== data.root) && (d.isclick); })
                .on('mouseover', function(d) {
                    d3.select(this).classed('node-highlight', true);
                })
                .on('mouseout', function(d) {
                    d3.select(this).classed('node-highlight', false);
                })
                .on('click', function(d, i) {
                    if (d3.select(this).classed('node-clickable')) {
                        onClick(d, i);
                        gnodeurl.selectAll('text').remove();
                        gnodeurl.append('text').attr('text-anchor','start').text(printURL(d));
                    }
                    else {
                    gnodeurl.selectAll('text').remove();
                    gnodeurl.append('text').attr('text-anchor','start').text(printURL(d)); //URL does not update properly.
                }
                });

            circles.call(force.drag);

            circles.exit().remove();

            // Labels
            // ------

            var words = glabels.selectAll('text.node-label')
                .data(force.nodes(), function(d) { return d.id; });

            words.enter().append('text')
                .text(me.nodeLabel)
                .attr('x', function(d, i) { return d.x + me.nodeRadius; })
                .attr('y', function(d, i) { return d.y - me.nodeRadius; })
                .attr('class', 'node-label');

            words.exit().remove();

            // Force On Tick
            force.on('tick', function() {
                links
                    .attr("x1", function(d) { return d.source.x; })
                    .attr("y1", function(d) { return d.source.y; })
                    .attr("x2", function(d) { return d.target.x; })
                    .attr("y2", function(d) { return d.target.y; });

                circles
                    .attr('cx', function(d) { return d.x; })
                    .attr('cy', function(d) { return d.y; });

                words
                    .attr('x', function(d, i) { return d.x + me.nodeRadius; })
                    .attr('y', function(d, i) { return d.y - me.nodeRadius; });

            });

            //Other elements
            //--------------
            var gbutton = g.append('g')
               .attr('class','button')
               .attr('transform','translate(' +  [10,10] +')');

            //Refresh button
            var refreshButton = gbutton.append('circle')
                                   .attr('cx',10)
                                   .attr('cy',10)
                                   .attr('r',10)
                                   .attr('fill','white')
                                   .attr('stroke','black')
                                   .attr('stroke-width',2)
                                   .attr('cursor','pointer')
                                   .on('click', function() {

                                    d3.json(nodeBaseURL(me.root), function(error,data) {
                                        div.data([data]).call(chart);
                                    })

                                   } );

             gbutton.append('text')
                .attr('x',4)
                .attr('y',15)
                .attr('cursor','pointer')
                .attr('font-family', 'FontAwesome')
                .text('\uf0e2' )
                .on('click', function() {

                                    d3.json(me.initialData, function(error,data) {
                                        div.data([data]).call(chart);
                                    })

                                   } );

            //Container for the url
            var gnodeurl = svgEnter.append('g')
                            .attr('class','urlcontainer')
                            .attr('transform','translate(' + [4, me.height -8 ] +')');

            gnodeurl.append('text').attr('text-anchor','start').text("Hi five!");

        });
    }

    chart.init = function(selection) {
        selection.each(function(data) {

            var initial = selection;

            var svgEnter = d3.select(this),
                gcont = svgEnter.append('g').attr('class', 'network-chart');

            // Add a background group and rectangle
            gcont.append('g')
                .attr('class', 'background')
                .append('rect')
                .attr('width', me.width)
                .attr('height', me.height)
                .attr('class', 'background');

            gcont.append('g').attr('class', 'links');
            gcont.append('g').attr('class', 'nodes');
            gcont.append('g').attr('class', 'labels');

            var gbrand = gcont.append('g')
                .attr('class', 'brand')
                .attr('transform', 'translate(' + [me.width - 4, me.height - 4] + ')');

            var brandLabel = gbrand.append('a')
                .attr('xlink:href', 'http://www.masega.co')
                .append('text')
                .attr('class', 'masega-brand')
                .attr('text-anchor', 'end')
                .text('masega.co');

            // var gnodeurl = gcont.append('g')
            //                 .attr('class','urlcontainer')
            //                 .attr('transform','translate(' + [4, me.height -8 ] +')');

            // var gprintnodeurl = gnodeurl.append('a')
            //                 .attr('xlink:href', me.chartURL(this))
            //                 .append('text')
            //                 .attr('text-anchor','start')
            //                 .text("hola");

            // var gbutton = gcont.append('g')
            //    .attr('class','button')
            //    .attr('transform','translate(' +  [10,10] +')');

            // var refreshButton = gbutton.append('rect')
            //                        .attr('width',20)
            //                        .attr('height',20)
            //                        .attr('fill','black')
            //                        .on('click', function() { gcont.data([initialData]).call(chart); } );

        });
    };

    // Accessor Methods

    // Generate Accessor Methods
    function createAccessor(attr) {
        return function(value) {
            if (!arguments.length) { return me[attr]; }
            me[attr] = value;
            return chart;
        };
    }

    for (var attr in me) {
        if ((!chart[attr]) && (me.hasOwnProperty(attr))) {
            chart[attr] = createAccessor(attr);
        }
    }

    return chart;
};<|endoftext|>


<commit_before>var path = require('path');

module.exports = {
	entry: path.join(__dirname, "app.js"),
	output: {
		path: __dirname,
		filename: "build.js"
	},

	module: {
		loaders: [
			{ test: /\.jade$/, loader: 'html!jade' },
			{ test: /\.css$/, loader: 'style!css' }
		]
	}
};<commit_msg>[example] remove webpack config, use webpack CLI instead<commit_after><|endoftext|>


<commit_before>import Vue from 'vue'
import runtime from 'offline-plugin/runtime'
import { Notification, Button } from 'element-ui'

const createNotifier = () => new Vue({
  data: {
    updating: false
  },
  created() {
    const h = this.$createElement
    this.notification = Notification({
      title: 'Detected an update for CodePan, apply updates will reload the tab automatically!',
      type: 'info',
      message: h('el-button', {
        on: { click: this.update },
        props: {
          icon: 'check',
          type: 'success',
          loading: this.updating
        }
       }, [this.updating ? 'Updating' : 'Apply Updates']),
      duration: 0
    })
  },
  methods: {
    update() {
      this.updating = true
      runtime.applyUpdate()
    }
  },
  components: {
    'el-button': Button
  }
})

let notifier

runtime.install({
  // When an update is ready, tell ServiceWorker to take control immediately:
  onUpdateReady() {
    console.log('update ready')
    notifier = createNotifier()
  },

  // Reload to get the new version:
  onUpdated() {
    console.log('updated')
    notifier.updating = false
    notifier.notification.close()
    location.reload()
  }
})
<commit_msg>fix lint<commit_after>import Vue from 'vue'
import runtime from 'offline-plugin/runtime'
import { Notification, Button } from 'element-ui'

const createNotifier = () => new Vue({
  data: {
    updating: false
  },
  created() {
    const h = this.$createElement
    this.notification = Notification({ // eslint-disable-line new-cap
      title: 'Detected an update for CodePan, apply updates will reload the tab automatically!',
      type: 'info',
      message: h('el-button', {
        on: { click: this.update },
        props: {
          icon: 'check',
          type: 'success',
          loading: this.updating
        }
      }, [this.updating ? 'Updating' : 'Apply Updates']),
      duration: 0
    })
  },
  methods: {
    update() {
      this.updating = true
      runtime.applyUpdate()
    }
  },
  components: {
    'el-button': Button
  }
})

let notifier

runtime.install({
  // When an update is ready, tell ServiceWorker to take control immediately:
  onUpdateReady() {
    console.log('update ready')
    notifier = createNotifier()
  },

  // Reload to get the new version:
  onUpdated() {
    console.log('updated')
    notifier.updating = false
    notifier.notification.close()
    location.reload()
  }
})
<|endoftext|>


<commit_before>import { Observable, Scheduler, isObservable, of, from, range as rxRange, empty as rxEmpty, pipe } from "rxjs";
import {
	first as rxFirst,
	subscribeOn,
	map,
	mergeMap,
	concatMap,
	switchMap as rxSwitchMap,
	concatAll,
	reduce,
	filter as rxFilter,
	count as rxCount,
	pairwise
} from "rxjs/operators";

import { isPromise, isUndef, isUndefOrNull, isNull, id } from "./util";
import { boolean } from "./boolean/value";

export class Maybe extends Observable {
	toObservable() {
		return create($o => {
			this.subscribe($o);
		});
	}
}

export class Single extends Observable {
	toObservable() {
		return create($o => {
			this.subscribe($o);
		});
	}
}

export const isMaybe = x => !!(x && x instanceof Maybe);

export const isSingle = x => !!(x && x instanceof Single);

Observable.prototype.toSingle = function() {
	return new Single($o => {
		rxFirst()(this).subscribe($o);
	});
};

Observable.prototype.toMaybe = function() {
	return new Maybe($o => {
		rxFirst()(this).subscribe($o);
	});
};

// TODO check each arg for Observable
export const fromArgs = args => seq(args.map(x => seq(x))).pipe(concatAll());

export const isSeq = isObservable;

const wrap = fn => x => {
	const ret = fn(x);
	return isSeq(ret) || isPromise(ret) ? ret : subscribeOn(Scheduler.queue)(of(ret).toSingle());
};

export const forEachCurried = fn => $s => isSeq($s) ? mergeMap(wrap(fn))($s) : fn($s);

export function forEach($s, fn) {
	return !isUndef(fn) ? forEachCurried(fn)($s) : forEachCurried($s);
}

/**
 * curried filter
 * @param  {function} fn [description]
 * @return {function}     [description]
 */
export const filterCurried = fn => $s =>
	isSeq($s) ?
		pipe(mergeMap(x => pairwise()(seq(boolean(fn(x)),x))),rxFilter(([t]) => t),map(([,x]) => x))($s) :
		pipe(rxFilter(t => t),map(() => $s))(seq(fn($s)));

export function filter($s, fn) {
	return !isUndef(fn) ? filterCurried(fn)($s) : filterCurried($s);
}

export const foldLeftCurried = fn => $seed => $a =>
	isSeq($a) ?
		pipe(reduce((a,x) => fn(a,x),$seed),switchMap(id))($a) :
		fn($seed,$a);

export function foldLeft($a, $seed, fn) {
	return !isUndef(fn) ? foldLeftCurried(fn)($seed)($a) : foldLeftCurried($seed)($a);
}

export const scanCurried = fn => $seed => $a =>
	isSeq($a) ?
		pipe(scan((a,x) => fn(a,x),$seed),switchMap(x => x))($a) :
		fn($seed,$a);

export function scan($a,$seed,fn) {
	return !isUndef(fn) ? scanCurried(fn)($seed)($a) : scanCurried($seed)($a);
}

function fromType(x) {
	return isSeq(x) ? x : isUndefOrNull(x) ? rxEmpty() : of(x).toSingle();
}

export function seq(...a) {
	const len = a.length;
	if (len == 0) return fromType();
	if(len == 1) return fromType(a[0]);
	return concatMap(x => seq(x))(from(a));
}

export function just(a) {
	return (isSeq(a) ? a : of(a)).toSingle();
}

export function create(o){
	return Observable.create(o);
}

// TODO how to use f when not a seq?
export const first = (f,d) => s => isSeq(s) ? rxFirst(f,d)(s) : isNull(s) ? d : s;

export const count = s => isSeq(s) ? rxCount()(s) : 1;

export function range(n,s=0) {
	return subscribeOn(Scheduler.queue)(rxRange(s,n));
}

export const switchMapCurried = fn => $s => isSeq($s) ? pipe(
	rxSwitchMap(wrap(fn)),
	subscribeOn(Scheduler.queue),
	unsubscribeOn(Scheduler.queue))($s) : fn($s);

function unsubscribeOn(scheduler) {
	return source => create(observer => {
		const subscription = source.subscribe(observer);
		return () => scheduler.schedule(() => subscription.unsubscribe());
	});
}

export const switchMap = ($s,fn) => !isUndef(fn) ? switchMapCurried(fn)($s) : switchMapCurried($s);

export { pipe };
<commit_msg>added sort<commit_after>import { Observable, Scheduler, isObservable, of, from, range as rxRange, empty as rxEmpty, pipe } from "rxjs";
import {
	first as rxFirst,
	subscribeOn,
	map,
	mergeMap,
	concatMap,
	switchMap as rxSwitchMap,
	concatAll,
	reduce,
	filter as rxFilter,
	count as rxCount,
	pairwise
} from "rxjs/operators";

import { isPromise, isUndef, isUndefOrNull, isNull, id } from "./util";
import { boolean } from "./boolean/value";

export class Maybe extends Observable {
	toObservable() {
		return create($o => {
			this.subscribe($o);
		});
	}
}

export class Single extends Observable {
	toObservable() {
		return create($o => {
			this.subscribe($o);
		});
	}
}

export const isMaybe = x => !!(x && x instanceof Maybe);

export const isSingle = x => !!(x && x instanceof Single);

Observable.prototype.toSingle = function() {
	return new Single($o => {
		rxFirst()(this).subscribe($o);
	});
};

Observable.prototype.toMaybe = function() {
	return new Maybe($o => {
		rxFirst()(this).subscribe($o);
	});
};

// TODO check each arg for Observable
export const fromArgs = args => seq(args.map(x => seq(x))).pipe(concatAll());

export const isSeq = isObservable;

const wrap = fn => x => {
	const ret = fn(x);
	return isSeq(ret) || isPromise(ret) ? ret : subscribeOn(Scheduler.queue)(of(ret).toSingle());
};

export const forEachCurried = fn => $s => isSeq($s) ? mergeMap(wrap(fn))($s) : fn($s);

export function forEach($s, fn) {
	return !isUndef(fn) ? forEachCurried(fn)($s) : forEachCurried($s);
}

/**
 * curried filter
 * @param  {function} fn [description]
 * @return {function}     [description]
 */
export const filterCurried = fn => $s =>
	isSeq($s) ?
		pipe(mergeMap(x => pairwise()(seq(boolean(fn(x)),x))),rxFilter(([t]) => t),map(([,x]) => x))($s) :
		pipe(rxFilter(t => t),map(() => $s))(seq(fn($s)));

export function filter($s, fn) {
	return !isUndef(fn) ? filterCurried(fn)($s) : filterCurried($s);
}

export const foldLeftCurried = fn => $seed => $a =>
	isSeq($a) ?
		pipe(reduce((a,x) => fn(a,x),$seed),switchMap(id))($a) :
		fn($seed,$a);

export function foldLeft($a, $seed, fn) {
	return !isUndef(fn) ? foldLeftCurried(fn)($seed)($a) : foldLeftCurried($seed)($a);
}

export const scanCurried = fn => $seed => $a =>
	isSeq($a) ?
		pipe(scan((a,x) => fn(a,x),$seed),switchMap(x => x))($a) :
		fn($seed,$a);

export function scan($a,$seed,fn) {
	return !isUndef(fn) ? scanCurried(fn)($seed)($a) : scanCurried($seed)($a);
}

function fromType(x) {
	return isSeq(x) ? x : isUndefOrNull(x) ? rxEmpty() : of(x).toSingle();
}

export function seq(...a) {
	const len = a.length;
	if (len == 0) return fromType();
	if(len == 1) return fromType(a[0]);
	return concatMap(x => seq(x))(from(a));
}

export function just(a) {
	return (isSeq(a) ? a : of(a)).toSingle();
}

export function create(o){
	return Observable.create(o);
}

// TODO how to use f when not a seq?
export const first = (f,d) => s => isSeq(s) ? rxFirst(f,d)(s) : isNull(s) ? d : s;

export const count = s => isSeq(s) ? rxCount()(s) : 1;

export function range(n,s=0) {
	return subscribeOn(Scheduler.queue)(rxRange(s,n));
}

export const switchMapCurried = fn => $s => isSeq($s) ? pipe(
	rxSwitchMap(wrap(fn)),
	subscribeOn(Scheduler.queue),
	unsubscribeOn(Scheduler.queue))($s) : fn($s);

function unsubscribeOn(scheduler) {
	return source => create(observer => {
		const subscription = source.subscribe(observer);
		return () => scheduler.schedule(() => subscription.unsubscribe());
	});
}

export const switchMap = ($s,fn) => !isUndef(fn) ? switchMapCurried(fn)($s) : switchMapCurried($s);

// FIXME
export function sort($s,fn){
	return switchMap(seq($s).toArray(),a => seq(isUndef(fn) ? a.sort() : a.sort(fn)));
}

export { pipe };
<|endoftext|>


<commit_before>/**
 * Set factory function
 *
 * returns an object with the main Set operations
 *
 * @author Eyas Ranjous <eyas@eyasranjous.info>
 *
 */

function set() {

    'use strict';

    // local variables (private properties)
    var elements = [],
        currentIndex = null;

    // return an object with the Set operations
    return {

        add: function(el) {
            if (elements.indexOf(el) === -1) {
                elements.push(el);
            }
        },

        remove: function(el){
            var index = elements.indexOf(el);
            if (index !== -1) {
                elements.splice(index, 1);
            }
        },

        iterator: function() {
            return {
                current: function() {
                    return (currentIndex !== null ? elements[currentIndex] : null);
                },

                next: function() {
                    if (currentIndex === null && elements.length > 0) {
                        currentIndex = 0;
                        return true;
                    }
                    else if (currentIndex >= elements.length - 1) {
                        currentIndex = null;
                        return false;
                    }
                    else {
                        currentIndex++;
                        return true;
                    }
                }
            };
        },

        isEmpty: function() {
            return elements.length > 0 ? false : true;
        },

        size: function(){
            return elements.length;
        },

        contains: function(el) {
            return elements.indexOf(el) !== -1 ? true : false;
        },

        union: function(s) {
            var resultSet = s.clone();

            for (var i = 0; i < elements.length; i++) {
                resultSet.add(elements[i]);
            }

            return resultSet;
        },

        intersect: function(s) {
            var resultSet = set();

            for (var i = 0; i < elements.length; i++) {
                if (s.contains(elements[i])) {
                    resultSet.add(elements[i]);
                }
            }

            return resultSet;
        },

        difference: function(s) {
            var resultSet = set();

            for (var i = 0; i < elements.length; i++) {
                if (!s.contains(elements[i])) {
                    resultSet.add(elements[i]);
                }
            }

            return resultSet;
        },

        isSubset: function(s) {
            if (elements.length <= s.size()) {
                for (var i = 0; i < elements.length; i++) {
                    if (!s.contains(elements[i])) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        },

        clone: function() {
            var s = set();
            for (var i = 0; i < elements.length; i++) {
                s.add(elements[i]);
            }
            return s;
        }

    };
}

module.exports = set;<commit_msg>use iterator in set function<commit_after>/**
 * Set factory function
 *
 * returns an object with the main Set operations
 *
 * @author Eyas Ranjous <eyas@eyasranjous.info>
 *
 */

function set() {

    'use strict';

    // local variables (private properties)
    var elements = [],
        iterator = require('./iterators/iterator')(elements);

    // return an object with the Set operations
    return {

        add: function(el) {
            if (elements.indexOf(el) === -1) {
                elements.push(el);
            }
        },

        remove: function(el){
            var index = elements.indexOf(el);
            if (index !== -1) {
                elements.splice(index, 1);
            }
        },

        iterator: function() {
            return iterator.toReadOnly();
        },

        isEmpty: function() {
            return elements.length > 0 ? false : true;
        },

        size: function(){
            return elements.length;
        },

        contains: function(el) {
            return elements.indexOf(el) !== -1 ? true : false;
        },

        union: function(s) {
            var resultSet = s.clone();

            for (var i = 0; i < elements.length; i++) {
                resultSet.add(elements[i]);
            }

            return resultSet;
        },

        intersect: function(s) {
            var resultSet = set();

            for (var i = 0; i < elements.length; i++) {
                if (s.contains(elements[i])) {
                    resultSet.add(elements[i]);
                }
            }

            return resultSet;
        },

        difference: function(s) {
            var resultSet = set();

            for (var i = 0; i < elements.length; i++) {
                if (!s.contains(elements[i])) {
                    resultSet.add(elements[i]);
                }
            }

            return resultSet;
        },

        isSubset: function(s) {
            if (elements.length <= s.size()) {
                for (var i = 0; i < elements.length; i++) {
                    if (!s.contains(elements[i])) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        },

        clone: function() {
            var s = set();
            for (var i = 0; i < elements.length; i++) {
                s.add(elements[i]);
            }
            return s;
        }

    };
}

module.exports = set;<|endoftext|>


<commit_before>var x11 = require('./lib');
var Mocha = require('mocha');
var fs = require('fs');
var path = require('path');
var util = require('util');
var async = require('async');

var mocha = new Mocha({
    timeout : 80000,
    reporter : 'spec'
});

// To be able to perform the tests we need the server:
// 1 - to support the dpms extension.
// 2 - dpms version is 1.1.
// 3 - to be dpms capable.
var run_dpms_test = function(X, cb) {
    X.require('dpms', function(err, ext) {
        if (!util.isError(err)) {
            dpms = ext;
            dpms.GetVersion(undefined, undefined, function(err, version) {
                if (!err && version[0] === 1 && version[1] === 1) {
                    dpms.Capable(function(err, capable) {
                        if (!err && capable[0] == 1) cb(true);
                        else cb(false);
                    });
                } else {
                    cb(false);
                }
            });
        } else {
            cb(false);
        }
    });
};

var run_xtest_test = function(X, cb) {
    X.require('xtest', function(err) {
        if (!util.isError(err)) cb(true);
        else cb(false);
    });
};

var run_randr_test = function(X, cb) {
    X.require('randr', function(err, ext) {
        if (!util.isError(err)) {
            randr = ext;
            randr.QueryVersion(1, 2, function(err, version) {
                if (err) {
                    cb(false);
                } else {
                    cb((version[0] === 1) && (version[1] >= 2));
                }
            });
        } else {
            cb(false);
        }
    });
};

x11.createClient(function(err, display) {
    if (err) {
        console.log('Could not create X client');
        process.exit(-1);
    }

    var X = display.client;
    // Add all files from test root directory
    async.forEach(
        fs.readdirSync('./test'),
        function(file, cb) {
            if (file === 'dpms.js') {
                run_dpms_test(X, function(run) {
                    if (run) {
                        mocha.addFile(path.join('./test', file));
                    }

                    cb();
                });
            } else if (file === 'xtest.js') {
                run_xtest_test(X, function(run) {
                    if (run) {
                        mocha.addFile(path.join('./test', file));
                    }

                    cb();
                });
            } else if (file === 'randr.js') {
                run_randr_test(X, function(run) {
                    if (run) {
                        mocha.addFile(path.join('./test', file));
                    }

                    cb();
                });
            } else {
                mocha.addFile(path.join('./test', file));
                cb();
            }
        },
        function() {
            X.terminate();
            X.on('end', function() {
                mocha.run(function(failures) {
                    process.exit(failures);
                });
            });

        }
    );
});
<commit_msg>Assign to local vars instead of globals<commit_after>var x11 = require('./lib');
var Mocha = require('mocha');
var fs = require('fs');
var path = require('path');
var util = require('util');
var async = require('async');

var mocha = new Mocha({
    timeout : 80000,
    reporter : 'spec'
});

// To be able to perform the tests we need the server:
// 1 - to support the dpms extension.
// 2 - dpms version is 1.1.
// 3 - to be dpms capable.
var run_dpms_test = function(X, cb) {
    X.require('dpms', function(err, ext) {
        if (!util.isError(err)) {
            var dpms = ext;
            dpms.GetVersion(undefined, undefined, function(err, version) {
                if (!err && version[0] === 1 && version[1] === 1) {
                    dpms.Capable(function(err, capable) {
                        if (!err && capable[0] == 1) cb(true);
                        else cb(false);
                    });
                } else {
                    cb(false);
                }
            });
        } else {
            cb(false);
        }
    });
};

var run_xtest_test = function(X, cb) {
    X.require('xtest', function(err) {
        if (!util.isError(err)) cb(true);
        else cb(false);
    });
};

var run_randr_test = function(X, cb) {
    X.require('randr', function(err, ext) {
        if (!util.isError(err)) {
            var randr = ext;
            randr.QueryVersion(1, 2, function(err, version) {
                if (err) {
                    cb(false);
                } else {
                    cb((version[0] === 1) && (version[1] >= 2));
                }
            });
        } else {
            cb(false);
        }
    });
};

x11.createClient(function(err, display) {
    if (err) {
        console.log('Could not create X client');
        process.exit(-1);
    }

    var X = display.client;
    // Add all files from test root directory
    async.forEach(
        fs.readdirSync('./test'),
        function(file, cb) {
            if (file === 'dpms.js') {
                run_dpms_test(X, function(run) {
                    if (run) {
                        mocha.addFile(path.join('./test', file));
                    }

                    cb();
                });
            } else if (file === 'xtest.js') {
                run_xtest_test(X, function(run) {
                    if (run) {
                        mocha.addFile(path.join('./test', file));
                    }

                    cb();
                });
            } else if (file === 'randr.js') {
                run_randr_test(X, function(run) {
                    if (run) {
                        mocha.addFile(path.join('./test', file));
                    }

                    cb();
                });
            } else {
                mocha.addFile(path.join('./test', file));
                cb();
            }
        },
        function() {
            X.terminate();
            X.on('end', function() {
                mocha.run(function(failures) {
                    process.exit(failures);
                });
            });

        }
    );
});
<|endoftext|>


<commit_before>// app/controllers/MainCtrl.js

app.controller('MainController', ['$scope', '$state', '$log', '$sce', 'DataService',
    function($scope, $state, $log, $sce, DataService) {

      $scope.error;
      $scope.chapterText = "";
      $scope.annotatedChapterText = "";
      $scope.annotationArray;
      $scope.selectChapter;
      $scope.category;
      $scope.newAnnotation;

      $scope.loadChapter = function () {
        $scope.error = false;
        $scope.annotatedChapterText = "";
        loadChapterAndAnnotations($scope.selectChapter);
      };

      $scope.addAnnotation = function () {
        $scope.newAnnotation = getTextSelection();
        $log.log($scope.newAnnotation);
      };

      $scope.saveAnnotation = function () {
        var index = parseInt($scope.newAnnotation.prevIndex);
        var prevCharseqEnd = parseInt($scope.annotationArray[index].extent.charseq._END);
        var start = $scope.newAnnotation.start + prevCharseqEnd + 1;
        var end = $scope.newAnnotation.end + prevCharseqEnd + 1;
        var text = $scope.newAnnotation.text;
        var category = $scope.category;
        var annotationObj = {
                              _category: category,
                              extent: {
                                charseq: {
                                  _END: end.toString(),
                                  _START: start.toString(),
                                  __text: text
                                }
                              }
                            };

        if (category) {
          $scope.annotationArray.splice(index, 0, annotationObj);
        } else {
          $scope.error = { statusText: "Please choose a category" };
        }
        $scope.annotatedChapterText = $scope.chapterText;
        $scope.annotatedChapterText = createAnnotatedChapterText($scope.annotatedChapterText, $scope.annotationArray);
        $scope.newAnnotation = "";
        $scope.category = "";
      };

      $scope.delete = function (event) {
        var index = parseInt(event.target.attributes[0].value);
        if (event.target.attributes[0].name === "data-index") {
          $scope.annotatedChapterText = $scope.chapterText;
          $scope.annotationArray.splice(index, 1);
          $scope.annotatedChapterText =
          createAnnotatedChapterText($scope.annotatedChapterText, $scope.annotationArray);
        }
      };

      $scope.saveJSON = function () {
        var annotationsJSON = angular.toJson($scope.annotationArray.reverse(), true);
        if (annotationsJSON) {
          $log.info(annotationsJSON);
        } else {
          $log.warn('There are no annotations for the current selected chapter.')
        }
      };

      function loadChapterAndAnnotations (chapterNumber) {
        DataService.getChapterText(chapterNumber)
          .then(function(chapter) {

            $scope.chapterText = chapter.data;

            DataService.getChapterAnnotations(chapterNumber)
              .then(function (response) {
                $scope.annotatedChapterText = chapter.data;  //.replace(/\n/g,"
");
                $scope.annotationArray = response.data.document.span.reverse();
                $scope.annotatedChapterText =
                createAnnotatedChapterText($scope.annotatedChapterText, $scope.annotationArray);
              })
              .catch(function (error) {
                $scope.error = error;
                $log.error(error.status, error.statusText);
              });
          })
          .catch(function (error) {
             $scope.error = error;
             $log.error(error.status, error.statusText);
          });
      }; // end loadChapterAndAnnotations function

      function createAnnotatedChapterText (text, annotations) {
        angular.forEach(annotations, function (value, index) {
          var start = parseInt(value.extent.charseq._START) ;
          var end = parseInt(value.extent.charseq._END) + 1;
          var subText = text.substring(start, end);
          var category = value._category;
          var arrayIndex = index.toString();
          var preText = text.substring(0, start);
          var hiliteText =
          '' + subText + '';
          var postText = text.substring(end);
          text = preText + hiliteText + postText;
        });
        return text;
      };

      function getTextSelection (event) {
        var selection = document.getSelection();
        var previousSiblingIndex = selection.anchorNode.parentElement.previousSibling.attributes[0].value;
        var rangeContents = selection.getRangeAt(0).cloneContents();
        var start = selection.anchorOffset < selection.focusOffset ? selection.anchorOffset : selection.focusOffset;
        var end = selection.anchorOffset < selection.focusOffset ? selection.focusOffset - 1: selection.anchorOffset - 1;
        var span = document.createElement('span');
        span.appendChild(rangeContents);
        var rangeText = span.innerHTML;
        return {
          text: rangeText,
          end: end,
          start: start,
          prevIndex: previousSiblingIndex
        }
      };

}]);
<commit_msg>prevent textSelection function from completing on mouseclick<commit_after>// app/controllers/MainCtrl.js

app.controller('MainController', ['$scope', '$state', '$log', '$sce', 'DataService',
    function($scope, $state, $log, $sce, DataService) {

      $scope.error;
      $scope.chapterText = "";
      $scope.annotatedChapterText = "";
      $scope.annotationArray;
      $scope.selectChapter;
      $scope.category;
      $scope.newAnnotation;

      $scope.loadChapter = function () {
        $scope.error = false;
        $scope.annotatedChapterText = "";
        loadChapterAndAnnotations($scope.selectChapter);
      };

      $scope.addAnnotation = function () {
        $scope.newAnnotation = getTextSelection();
      };

      $scope.saveAnnotation = function () {
        var index = parseInt($scope.newAnnotation.prevIndex);
        var prevCharseqEnd = parseInt($scope.annotationArray[index].extent.charseq._END);
        var start = $scope.newAnnotation.start + prevCharseqEnd + 1;
        var end = $scope.newAnnotation.end + prevCharseqEnd + 1;
        var text = $scope.newAnnotation.text;
        var category = $scope.category;
        var annotationObj = {
                              _category: category,
                              extent: {
                                charseq: {
                                  _END: end.toString(),
                                  _START: start.toString(),
                                  __text: text
                                }
                              }
                            };

        if (category) {
          $scope.annotationArray.splice(index, 0, annotationObj);
        } else {
          $scope.error = { statusText: "Please choose a category" };
        }
        $scope.annotatedChapterText = $scope.chapterText;
        $scope.annotatedChapterText = createAnnotatedChapterText($scope.annotatedChapterText, $scope.annotationArray);
        $scope.newAnnotation = "";
        $scope.category = "";
      };

      $scope.delete = function (event) {
        var index = parseInt(event.target.attributes[0].value);
        if (event.target.attributes[0].name === "data-index") {
          $scope.annotatedChapterText = $scope.chapterText;
          $scope.annotationArray.splice(index, 1);
          $scope.annotatedChapterText =
          createAnnotatedChapterText($scope.annotatedChapterText, $scope.annotationArray);
        }
      };

      $scope.saveJSON = function () {
        var annotationsJSON = angular.toJson($scope.annotationArray.reverse(), true);
        if (annotationsJSON) {
          $log.info(annotationsJSON);
        } else {
          $log.warn('There are no annotations for the current selected chapter.')
        }
      };

      function loadChapterAndAnnotations (chapterNumber) {
        DataService.getChapterText(chapterNumber)
          .then(function(chapter) {

            $scope.chapterText = chapter.data;

            DataService.getChapterAnnotations(chapterNumber)
              .then(function (response) {
                $scope.annotatedChapterText = chapter.data;  //.replace(/\n/g,"
");
                $scope.annotationArray = response.data.document.span.reverse();
                $scope.annotatedChapterText =
                createAnnotatedChapterText($scope.annotatedChapterText, $scope.annotationArray);
              })
              .catch(function (error) {
                $scope.error = error;
                $log.error(error.status, error.statusText);
              });
          })
          .catch(function (error) {
             $scope.error = error;
             $log.error(error.status, error.statusText);
          });
      }; // end loadChapterAndAnnotations function

      function createAnnotatedChapterText (text, annotations) {
        angular.forEach(annotations, function (value, index) {
          var start = parseInt(value.extent.charseq._START) ;
          var end = parseInt(value.extent.charseq._END) + 1;
          var subText = text.substring(start, end);
          var category = value._category;
          var arrayIndex = index.toString();
          var preText = text.substring(0, start);
          var hiliteText =
          '' + subText + '';
          var postText = text.substring(end);
          text = preText + hiliteText + postText;
        });
        return text;
      };

      function getTextSelection (event) {
        var selection = document.getSelection();
        var previousSiblingIndex = selection.anchorNode.parentElement.previousSibling.attributes[0].value;
        var rangeContents = selection.getRangeAt(0).cloneContents();
        var start = selection.anchorOffset < selection.focusOffset ? selection.anchorOffset : selection.focusOffset;
        var end = selection.anchorOffset < selection.focusOffset ? selection.focusOffset - 1: selection.anchorOffset - 1;
        var span = document.createElement('span');
        span.appendChild(rangeContents);
        var rangeText = span.innerHTML;
        if (end < start) {
          return;
        };
        return {
          text: rangeText,
          end: end,
          start: start,
          prevIndex: previousSiblingIndex
        };
      };

}]);
<|endoftext|>


<commit_before>'use strict';

const	intercoms	= [],
	Intercom	= require(__dirname + '/../index.js'),
	assert	= require('assert'),
	lUtils	= require('larvitutils'),
	async	= require('async'),
	log	= require('winston'),
	fs	= require('fs');

let	confFile;

// Set up winston
log.remove(log.transports.Console);
/**/log.add(log.transports.Console, {
	'colorize':	true,
	'timestamp':	true,
	'level':	'debug',
	'json':	false
});
/**/

before(function(done) {
	this.timeout(20000);

	function instantiateIntercoms(config) {
		const	tasks	= [];

		for (let i = 0; i < 14; i ++) {
			tasks.push(function(cb) {
				const	intercom	= new Intercom(config);

				intercoms.push(intercom);
				intercom.on('ready', cb);
			});
		}

		// Wait until all is connected and ready
		async.parallel(tasks, done);
	}

	if (process.env.CONFFILE === undefined) {
		confFile = __dirname + '/../config/amqp_test.json';
	} else {
		confFile = process.env.CONFFILE;
	}

	log.verbose('Autobahn config file: "' + confFile + '"');

	// First look for absolute path
	fs.stat(confFile, function(err) {
		if (err) {

			// Then look for this string in the config folder
			confFile = __dirname + '/../config/' + confFile;
			fs.stat(confFile, function(err) {
				if (err) throw err;
				log.verbose('Autobahn config: ' + JSON.stringify(require(confFile)));
				instantiateIntercoms(require(confFile).default);
			});

			return;
		}

		log.verbose('Autobahn config: ' + JSON.stringify(require(confFile)));
		instantiateIntercoms(require(confFile).default);
	});
});

after(function(done) {
	const	tasks	= [];

	this.timeout(10000);

	for (let i = 0; intercoms[i] !== undefined; i ++) {
		const	intercom	= intercoms[i];
		tasks.push(function(cb) {
			intercom.close(cb);
		});
	}

	async.parallel(tasks, done);
});

describe('Send and receive', function() {
	it('check so the first intercom is up', function(done) {
		const	intercom	= intercoms[0];

		assert.notDeepEqual(intercom.handle,	undefined);
		assert.notDeepEqual(intercom.handle.channel,	undefined);
		done();
	});

	it('send and receive a message to the default exchange', function(done) {
		const	orgMsg	= {'foo': 'bar'},
			tasks	= [];

		this.timeout(2500);
		this.slow(2100); // > 1050 is shown in yellow, 1000ms is setTimeout()

		let	subscribed	= 0,
			consumed	= 0;

		function consume(intercom, cb) {
			intercom.consume(function(msg, ack, deliveryTag) {
				assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
				delete msg.uuid;
				assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
				assert(deliveryTag, 'deliveryTag shoult be non-empty');
				consumed ++;
				ack();
			}, cb);
		}

		function subscribe(intercom, cb) {
			intercom.subscribe(function(msg, ack, deliveryTag) {
				assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
				delete msg.uuid;
				assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
				assert(deliveryTag, 'deliveryTag shoult be non-empty');
				subscribed ++;
				ack();
			}, cb);
		}

		tasks.push(function(cb) { consume(intercoms[0],	cb); });
		tasks.push(function(cb) { consume(intercoms[1],	cb); });
		tasks.push(function(cb) { subscribe(intercoms[2],	cb); });
		tasks.push(function(cb) { subscribe(intercoms[3],	cb); });

		async.parallel(tasks, function(err) {
			if (err) throw err;

			intercoms[4].send(orgMsg, function(err) {
				if (err) throw err;

				// Wait for a while to make sure consume() is not ran multiple times.
				// This is not pretty, but I can not think of a better way
				setTimeout(function() {
					assert.deepEqual(consumed,	1);
					assert.deepEqual(subscribed,	2);
					done();
				}, 1000);
			});
		});
	});

	it('send and receive a message to a custom exchange', function(done) {
		const	exchange	= 'customeOne',
			orgMsg	= {'foo': 'bard'},
			tasks	= [];

		this.timeout(2500);
		this.slow(2100); // > 1050 is shown in yellow, 1000ms is setTimeout()

		let	subscribed	= 0,
			consumed	= 0;

		function consume(intercom, cb) {
			intercom.consume({'exchange': exchange}, function(msg, ack, deliveryTag) {
				assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
				delete msg.uuid;
				assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
				assert(deliveryTag, 'deliveryTag shoult be non-empty');
				consumed ++;
				ack();
			}, cb);
		}

		function subscribe(intercom, cb) {
			intercom.subscribe({'exchange': exchange}, function(msg, ack, deliveryTag) {
				assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
				delete msg.uuid;
				assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
				assert(deliveryTag, 'deliveryTag shoult be non-empty');
				subscribed ++;
				ack();
			}, cb);
		}

		tasks.push(function(cb) { consume(intercoms[5],	cb); });
		tasks.push(function(cb) { consume(intercoms[6],	cb); });
		tasks.push(function(cb) { subscribe(intercoms[7],	cb); });
		tasks.push(function(cb) { subscribe(intercoms[8],	cb); });

		async.parallel(tasks, function(err) {
			if (err) throw err;

			intercoms[9].send(orgMsg, {'exchange': exchange}, function(err) {
				if (err) throw err;

				// Wait for a while to make sure consume() is not ran multiple times.
				// This is not pretty, but I can not think of a better way
				setTimeout(function() {
					assert.deepEqual(consumed,	1);
					assert.deepEqual(subscribed,	2);
					done();
				}, 1000);
			});
		});
	});

	it('send and receive on the same Intercom', function(done) {
		const	exchange	= 'sameInstance',
			orgMsg	= {'bi': 'bu'};

		intercoms[10].subscribe({'exchange': exchange}, function(msg, ack, deliveryTag) {
			assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
			delete msg.uuid;
			assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
			assert(deliveryTag, 'deliveryTag shoult be non-empty');
			ack();
			done();
		}, function(err) {
			if (err) throw err;

			intercoms[10].send(orgMsg, {'exchange': exchange}, function(err) {
				if (err) throw err;
			});
		});
	});

	it('send and receive multiple messages on different Intercoms', function(done) {
		const	exchange	= 'anotherInstance',
			orgMsg1	= {'ba': 'bo'},
			orgMsg2	= {'waff': 'woff'};

		let	msg1Received = 0,
			msg2Received = 0;

		intercoms[11].subscribe({'exchange': exchange}, function(msg, ack) {
			if (JSON.stringify(msg.ba) === JSON.stringify(orgMsg1.ba)) {
				msg1Received ++;
				ack();
			} else if (JSON.stringify(msg.waff) === JSON.stringify(orgMsg2.waff)) {
				msg2Received ++;
				ack();
			}

			if (msg1Received === 1 && msg2Received === 1) {
				done();
			}
		}, function(err) {
			if (err) throw err;

			intercoms[11].send(orgMsg1, {'exchange': exchange}, function(err) {
				if (err) throw err;
			});

			intercoms[12].send(orgMsg2, {'exchange': exchange}, function(err) {
				if (err) throw err;
			});
		});
	});

	it('send and receive multiple messages on the same Intercom', function(done) {
		const	exchange	= 'yetAnotherInstance',
			orgMsg1	= {'bar': 'bor'},
			orgMsg2	= {'waffer': 'woffer'};

		let	msg1Received = 0,
			msg2Received = 0;

		intercoms[13].subscribe({'exchange': exchange}, function(msg, ack) {
			if (JSON.stringify(msg.bar) === JSON.stringify(orgMsg1.bar)) {
				msg1Received ++;
				ack();
			} else if (JSON.stringify(msg.waffer) === JSON.stringify(orgMsg2.waffer)) {
				msg2Received ++;
				ack();
			}

			if (msg1Received === 10 && msg2Received === 10) {
				done();
			}
		}, function(err) {
			if (err) throw err;

			for (let i = 0; i !== 10; i ++) {
				intercoms[13].send(orgMsg1, {'exchange': exchange}, function(err) {
					if (err) throw err;
				});

				intercoms[13].send(orgMsg2, {'exchange': exchange}, function(err) {
					if (err) throw err;
				});
			}
		});
	});

	it('send and receive messages on different exchanges', function(done) {
		const	exchange1	= 'differentExes1',
			exchange2	= 'differentExes2',
			orgMsg1	= {'bar': 'bor'},
			orgMsg2	= {'waffer': 'woffer'},
			tasks	= [];

		let	receivedMsg1	= 0,
			receivedMsg2	= 0;

		tasks.push(function(cb) {
			intercoms[0].subscribe({'exchange': exchange1}, function(msg, ack) {
				assert.deepEqual(msg.bar, orgMsg1.bar);
				receivedMsg1 ++;
				ack();
			}, cb);
		});

		tasks.push(function(cb) {
			intercoms[0].subscribe({'exchange': exchange2}, function(msg, ack) {
				assert.deepEqual(msg.waffer, orgMsg2.waffer);
				receivedMsg2 ++;
				ack();
			}, cb);
		});

		tasks.push(function(cb) {
			intercoms[0].send(orgMsg1, {'exchange': exchange1}, cb);
		});

		tasks.push(function(cb) {
			intercoms[0].send(orgMsg2, {'exchange': exchange2}, cb);
		});

		async.series(tasks, function(err) {
			let	interval;

			if (err) throw err;

			interval = setInterval(function() {
				if (receivedMsg1 === 1 && receivedMsg2 === 1) {
					clearInterval(interval);
					done();
				}
			}, 10);
		});
	});
});
<commit_msg>warn log level on tests<commit_after>'use strict';

const	intercoms	= [],
	Intercom	= require(__dirname + '/../index.js'),
	assert	= require('assert'),
	lUtils	= require('larvitutils'),
	async	= require('async'),
	log	= require('winston'),
	fs	= require('fs');

let	confFile;

// Set up winston
log.remove(log.transports.Console);
/**/log.add(log.transports.Console, {
	'colorize':	true,
	'timestamp':	true,
	'level':	'warn',
	'json':	false
});
/**/

before(function(done) {
	this.timeout(20000);

	function instantiateIntercoms(config) {
		const	tasks	= [];

		for (let i = 0; i < 14; i ++) {
			tasks.push(function(cb) {
				const	intercom	= new Intercom(config);

				intercoms.push(intercom);
				intercom.on('ready', cb);
			});
		}

		// Wait until all is connected and ready
		async.parallel(tasks, done);
	}

	if (process.env.CONFFILE === undefined) {
		confFile = __dirname + '/../config/amqp_test.json';
	} else {
		confFile = process.env.CONFFILE;
	}

	log.verbose('Autobahn config file: "' + confFile + '"');

	// First look for absolute path
	fs.stat(confFile, function(err) {
		if (err) {

			// Then look for this string in the config folder
			confFile = __dirname + '/../config/' + confFile;
			fs.stat(confFile, function(err) {
				if (err) throw err;
				log.verbose('Autobahn config: ' + JSON.stringify(require(confFile)));
				instantiateIntercoms(require(confFile).default);
			});

			return;
		}

		log.verbose('Autobahn config: ' + JSON.stringify(require(confFile)));
		instantiateIntercoms(require(confFile).default);
	});
});

after(function(done) {
	const	tasks	= [];

	this.timeout(10000);

	for (let i = 0; intercoms[i] !== undefined; i ++) {
		const	intercom	= intercoms[i];
		tasks.push(function(cb) {
			intercom.close(cb);
		});
	}

	async.parallel(tasks, done);
});

describe('Send and receive', function() {
	it('check so the first intercom is up', function(done) {
		const	intercom	= intercoms[0];

		assert.notDeepEqual(intercom.handle,	undefined);
		assert.notDeepEqual(intercom.handle.channel,	undefined);
		done();
	});

	it('send and receive a message to the default exchange', function(done) {
		const	orgMsg	= {'foo': 'bar'},
			tasks	= [];

		this.timeout(2500);
		this.slow(2100); // > 1050 is shown in yellow, 1000ms is setTimeout()

		let	subscribed	= 0,
			consumed	= 0;

		function consume(intercom, cb) {
			intercom.consume(function(msg, ack, deliveryTag) {
				assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
				delete msg.uuid;
				assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
				assert(deliveryTag, 'deliveryTag shoult be non-empty');
				consumed ++;
				ack();
			}, cb);
		}

		function subscribe(intercom, cb) {
			intercom.subscribe(function(msg, ack, deliveryTag) {
				assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
				delete msg.uuid;
				assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
				assert(deliveryTag, 'deliveryTag shoult be non-empty');
				subscribed ++;
				ack();
			}, cb);
		}

		tasks.push(function(cb) { consume(intercoms[0],	cb); });
		tasks.push(function(cb) { consume(intercoms[1],	cb); });
		tasks.push(function(cb) { subscribe(intercoms[2],	cb); });
		tasks.push(function(cb) { subscribe(intercoms[3],	cb); });

		async.parallel(tasks, function(err) {
			if (err) throw err;

			intercoms[4].send(orgMsg, function(err) {
				if (err) throw err;

				// Wait for a while to make sure consume() is not ran multiple times.
				// This is not pretty, but I can not think of a better way
				setTimeout(function() {
					assert.deepEqual(consumed,	1);
					assert.deepEqual(subscribed,	2);
					done();
				}, 1000);
			});
		});
	});

	it('send and receive a message to a custom exchange', function(done) {
		const	exchange	= 'customeOne',
			orgMsg	= {'foo': 'bard'},
			tasks	= [];

		this.timeout(2500);
		this.slow(2100); // > 1050 is shown in yellow, 1000ms is setTimeout()

		let	subscribed	= 0,
			consumed	= 0;

		function consume(intercom, cb) {
			intercom.consume({'exchange': exchange}, function(msg, ack, deliveryTag) {
				assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
				delete msg.uuid;
				assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
				assert(deliveryTag, 'deliveryTag shoult be non-empty');
				consumed ++;
				ack();
			}, cb);
		}

		function subscribe(intercom, cb) {
			intercom.subscribe({'exchange': exchange}, function(msg, ack, deliveryTag) {
				assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
				delete msg.uuid;
				assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
				assert(deliveryTag, 'deliveryTag shoult be non-empty');
				subscribed ++;
				ack();
			}, cb);
		}

		tasks.push(function(cb) { consume(intercoms[5],	cb); });
		tasks.push(function(cb) { consume(intercoms[6],	cb); });
		tasks.push(function(cb) { subscribe(intercoms[7],	cb); });
		tasks.push(function(cb) { subscribe(intercoms[8],	cb); });

		async.parallel(tasks, function(err) {
			if (err) throw err;

			intercoms[9].send(orgMsg, {'exchange': exchange}, function(err) {
				if (err) throw err;

				// Wait for a while to make sure consume() is not ran multiple times.
				// This is not pretty, but I can not think of a better way
				setTimeout(function() {
					assert.deepEqual(consumed,	1);
					assert.deepEqual(subscribed,	2);
					done();
				}, 1000);
			});
		});
	});

	it('send and receive on the same Intercom', function(done) {
		const	exchange	= 'sameInstance',
			orgMsg	= {'bi': 'bu'};

		intercoms[10].subscribe({'exchange': exchange}, function(msg, ack, deliveryTag) {
			assert.notDeepEqual(lUtils.formatUuid(msg.uuid), false);
			delete msg.uuid;
			assert.deepEqual(JSON.stringify(orgMsg), JSON.stringify(msg));
			assert(deliveryTag, 'deliveryTag shoult be non-empty');
			ack();
			done();
		}, function(err) {
			if (err) throw err;

			intercoms[10].send(orgMsg, {'exchange': exchange}, function(err) {
				if (err) throw err;
			});
		});
	});

	it('send and receive multiple messages on different Intercoms', function(done) {
		const	exchange	= 'anotherInstance',
			orgMsg1	= {'ba': 'bo'},
			orgMsg2	= {'waff': 'woff'};

		let	msg1Received = 0,
			msg2Received = 0;

		intercoms[11].subscribe({'exchange': exchange}, function(msg, ack) {
			if (JSON.stringify(msg.ba) === JSON.stringify(orgMsg1.ba)) {
				msg1Received ++;
				ack();
			} else if (JSON.stringify(msg.waff) === JSON.stringify(orgMsg2.waff)) {
				msg2Received ++;
				ack();
			}

			if (msg1Received === 1 && msg2Received === 1) {
				done();
			}
		}, function(err) {
			if (err) throw err;

			intercoms[11].send(orgMsg1, {'exchange': exchange}, function(err) {
				if (err) throw err;
			});

			intercoms[12].send(orgMsg2, {'exchange': exchange}, function(err) {
				if (err) throw err;
			});
		});
	});

	it('send and receive multiple messages on the same Intercom', function(done) {
		const	exchange	= 'yetAnotherInstance',
			orgMsg1	= {'bar': 'bor'},
			orgMsg2	= {'waffer': 'woffer'};

		let	msg1Received = 0,
			msg2Received = 0;

		intercoms[13].subscribe({'exchange': exchange}, function(msg, ack) {
			if (JSON.stringify(msg.bar) === JSON.stringify(orgMsg1.bar)) {
				msg1Received ++;
				ack();
			} else if (JSON.stringify(msg.waffer) === JSON.stringify(orgMsg2.waffer)) {
				msg2Received ++;
				ack();
			}

			if (msg1Received === 10 && msg2Received === 10) {
				done();
			}
		}, function(err) {
			if (err) throw err;

			for (let i = 0; i !== 10; i ++) {
				intercoms[13].send(orgMsg1, {'exchange': exchange}, function(err) {
					if (err) throw err;
				});

				intercoms[13].send(orgMsg2, {'exchange': exchange}, function(err) {
					if (err) throw err;
				});
			}
		});
	});

	it('send and receive messages on different exchanges', function(done) {
		const	exchange1	= 'differentExes1',
			exchange2	= 'differentExes2',
			orgMsg1	= {'bar': 'bor'},
			orgMsg2	= {'waffer': 'woffer'},
			tasks	= [];

		let	receivedMsg1	= 0,
			receivedMsg2	= 0;

		tasks.push(function(cb) {
			intercoms[0].subscribe({'exchange': exchange1}, function(msg, ack) {
				assert.deepEqual(msg.bar, orgMsg1.bar);
				receivedMsg1 ++;
				ack();
			}, cb);
		});

		tasks.push(function(cb) {
			intercoms[0].subscribe({'exchange': exchange2}, function(msg, ack) {
				assert.deepEqual(msg.waffer, orgMsg2.waffer);
				receivedMsg2 ++;
				ack();
			}, cb);
		});

		tasks.push(function(cb) {
			intercoms[0].send(orgMsg1, {'exchange': exchange1}, cb);
		});

		tasks.push(function(cb) {
			intercoms[0].send(orgMsg2, {'exchange': exchange2}, cb);
		});

		async.series(tasks, function(err) {
			let	interval;

			if (err) throw err;

			interval = setInterval(function() {
				if (receivedMsg1 === 1 && receivedMsg2 === 1) {
					clearInterval(interval);
					done();
				}
			}, 10);
		});
	});
});
<|endoftext|>