<commit_before>var keystone = require('keystone');
var engines = require('consolidate');

keystone.init({

	'name': 'Keystone Demo',
	'brand': 'Demo',

	'favicon': 'public/favicon.ico',
	'less': 'public',
	'static': 'public',

	'views': 'templates/views',
	'view engine': 'jade',

	'auto update': true,
	'mongo': process.env.MONGO_URI || process.env.MONGOLAB_URI || 'mongodb://localhost/keystone-demo',
	'cloudinary config': 'cloudinary://333779167276662:_8jbSi9FB3sWYrfimcl8VKh34rI@keystone-demo',

	'session': true,
	'auth': true,
	'user model': 'User',
	'cookie secret': process.env.COOKIE_SECRET || 'demo',

	'ga property': process.env.GA_PROPERTY,
	'ga domain': process.env.GA_DOMAIN,

	'chartbeat property': process.env.CHARTBEAT_PROPERTY,
	'chartbeat domain': process.env.CHARTBEAT_DOMAIN

});

keystone.import('models');

keystone.set('locals', {
	_: require('lodash'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable,
	ga_property: keystone.get('ga property'),
	ga_domain: keystone.get('ga domain'),
	chartbeat_property: keystone.get('chartbeat property'),
	chartbeat_domain: keystone.get('chartbeat domain')
});

keystone.set('routes', require('./routes'));

keystone.set('nav', {
	'posts': ['posts', 'post-comments', 'post-categories'],
	'galleries': 'galleries',
	'enquiries': 'enquiries',
	'users': 'users',
	'field-tests': 'things'
});

keystone.start();
<commit_msg>deleted<commit_after><|endoftext|>


<commit_before>define(function (require) {

  return {
    create: require('./project/create').create,
    destroy: require('./project/destroy').destroy,
    explainProjectDeleteConditions: require('./project/explainProjectDeleteConditions').explainProjectDeleteConditions,
    moveResources: require('./project/moveResources').moveResources

  };

});
<commit_msg>added removeResources to ProjectModals<commit_after>define(function (require) {

  return {
    create: require('./project/create').create,
    destroy: require('./project/destroy').destroy,
    explainProjectDeleteConditions: require('./project/explainProjectDeleteConditions').explainProjectDeleteConditions,
    moveResources: require('./project/moveResources').moveResources,
    removeResources: require('./project/removeResources').removeResources

  };

});
<|endoftext|>


<commit_before>/**
 * Created by michael on 07/09/15.
 */

var Promise = require('bluebird');

function FightController(app,player1,player2){
    this.app = app;
    this.player1 = player1;
    this.player2 = player2;

    this.readyCount = 0;

    this.activePlayer = player1;
    this.pausedPlayer = player2;
}

FightController.prototype.start = function(){
    return Promise.all([
        this.initPlayer(this.player1,this.player2),
        this.initPlayer(this.player2,this.player1)
    ]);
};

FightController.prototype.stop = function(){
    return Promise.all([
        this.deInitPlayer(this.player1),
        this.deInitPlayer(this.player2)
    ]);
};

FightController.prototype.deInitPlayer = function(player){
    return player.stopFight();
};

FightController.prototype.initPlayer = function(player,enemy) {
    player.fight = this;

    return enemy.user.robot().fetch({require: true}).then(function(robot){
        return player.socket.emit('requestFightResult',{
            status: 'ACCEPT',
            username: enemy.user.get('username'),
            robot: robot.toJSON({shallow: true})
        });
    });
};

FightController.prototype.onPlayerReady = function(){
    this.readyCount++;

    if(this.readyCount >= 2){
        this.activePlayer.emit('fightCommand',{
            command: 'active'
        })
    }
};

FightController.prototype.parseCommand = function(data){
    var player = this.app.getUserConnection(data.who);

    switch(data.command){
        case 'ready':
            this.onPlayerReady();
            break;
        case 'abort':
            this.app.stopFight(player);
            return;
    }

    if(!this.currentPlayer == player || this.readyCount < 2){
        return;
    }

    switch(data.command){
        case 'attack':
            this.attack();
            break;
    }

    var pause = this.currentPlayer;
    this.currentPlayer = this.pausedPlayer;
    this.pausedPlayer = pause;

    this.pausedPlayer.emit('fightCommand',{
        command: 'wait'
    });
};

FightController.prototype.attack = function(){
    this.pausedPlayer.socket.emit('fightCommand',{
        command: 'enemyAttack'
    });
};

module.exports = FightController;<commit_msg>zu früh auf emit zugegriffen<commit_after>/**
 * Created by michael on 07/09/15.
 */

var Promise = require('bluebird');

function FightController(app,player1,player2){
    this.app = app;
    this.player1 = player1;
    this.player2 = player2;

    this.readyCount = 0;

    this.activePlayer = player1;
    this.pausedPlayer = player2;
}

FightController.prototype.start = function(){
    return Promise.all([
        this.initPlayer(this.player1,this.player2),
        this.initPlayer(this.player2,this.player1)
    ]);
};

FightController.prototype.stop = function(){
    return Promise.all([
        this.deInitPlayer(this.player1),
        this.deInitPlayer(this.player2)
    ]);
};

FightController.prototype.deInitPlayer = function(player){
    return player.stopFight();
};

FightController.prototype.initPlayer = function(player,enemy) {
    player.fight = this;

    return enemy.user.robot().fetch({require: true}).then(function(robot){
        return player.socket.emit('requestFightResult',{
            status: 'ACCEPT',
            username: enemy.user.get('username'),
            robot: robot.toJSON({shallow: true})
        });
    });
};

FightController.prototype.onPlayerReady = function(){
    this.readyCount++;

    if(this.readyCount >= 2){
        this.activePlayer.socket.emit('fightCommand',{
            command: 'active'
        })
    }
};

FightController.prototype.parseCommand = function(data){
    var player = this.app.getUserConnection(data.who);

    switch(data.command){
        case 'ready':
            this.onPlayerReady();
            break;
        case 'abort':
            this.app.stopFight(player);
            return;
    }

    if(!this.currentPlayer == player || this.readyCount < 2){
        return;
    }

    switch(data.command){
        case 'attack':
            this.attack();
            break;
    }

    var pause = this.currentPlayer;
    this.currentPlayer = this.pausedPlayer;
    this.pausedPlayer = pause;

    this.pausedPlayer.socket.emit('fightCommand',{
        command: 'wait'
    });
};

FightController.prototype.attack = function(){
    this.pausedPlayer.socket.emit('fightCommand',{
        command: 'enemyAttack'
    });
};

module.exports = FightController;<|endoftext|>


<commit_before>'use strict';
const expect = require('chai').expect;
const Excel = require('exceljs');
const ExcelReader = require('../index').ExcelReader;
const fs = require('fs');

let testWorkbooks = {};
describe('Excel Reader', () => {
    before(() => {
        testWorkbooks.singleSheetFirstRowHeader = fs.createReadStream('./util/excels/1sheet-1header.xlsx');
    });
    describe('Sheets', () => {
        it('should error if different number of Sheets', (done) => {
            let workbook = testWorkbooks.singleSheetFirstRowHeader;
            let reader = new ExcelReader(testWorkbooks.singleSheetFirstRowHeader, {
                sheets: [{
                    name: 'Data',
                }, {
                    name: 'Test'
                }]
            })
            reader.eachRow()
            .then(() => {
                done('Reader must exit with an error');
            })
            .catch((err) => {
                expect(err).to.exist();
            });
        });
    });

    describe('Allowed Sheet Names', () => {
        it('should be an array', () => {
        });

        it('should only allow selected sheet names', () => {
        });

        it('should throw error if invalid sheet name is in excel', () => {
        });

        it('should allow any name if allowedNames is null', () => {
        });
    });

    describe('Rows', () => {
        it('should error if header row does not exist in excel', () => {
        });

        it('should assume default header row', () => {
        });

        it('should take header row from config', () => {
        });

        it('should only allow specified header rows', () => {
        });

        it('should return each row data based on header row keys', () => {
        });
    });
});<commit_msg>Written tests for excel reading<commit_after>'use strict';
const expect = require('chai').expect;
const Excel = require('exceljs');
const ExcelReader = require('../index').ExcelReader;
const fs = require('fs');

let testWorkbooks = {};
describe('Excel Reader', () => {
    before(() => {
        testWorkbooks.singleSheetFirstRowHeader = fs.createReadStream('./util/excels/1sheet-1header.xlsx');
        testWorkbooks.singleSheetNRowHeader = fs.createReadStream('./util/excels/1sheet-nheader.xlsx');
        testWorkbooks.multiSheetNRowHeader = fs.createReadStream('./util/excels/2sheet-nheader.xlsx');
    });
    describe('Sheets', () => {
        it('should error if different number of Sheets', (done) => {
            let reader = new ExcelReader(testWorkbooks.singleSheetFirstRowHeader, {
                sheets: [{
                    name: 'Data',
                }, {
                    name: 'Test'
                }]
            })
            reader.eachRow()
            .then(() => {
                done('Reader must exit with an error');
            })
            .catch((err) => {
                expect(err).to.exist();
                expect(err.message).to.match(/invalid number of sheets/i);
            });
        });
    });

    describe('Allowed Sheet Names', () => {
        it('should be an array or null', () => {
            let hasToThrow = ExcelReader.bind(null, testWorkbooks.singleSheetFirstRowHeader, {
                sheets: [{
                    allowedNames: 'dkfjkdj'
                }]
            });
            expect(hasToThrow).to.throw(/should be an array/);
        });

        it('should only allow selected sheet names', (done) => {
            let reader = new ExcelReader(testWorkbooks.singleSheetFirstRowHeader, {
                sheets: [{
                    allowedNames: ['Data']
                }]
            });
            reader.eachRow()
            .then(() => {
                done();
            })
            .catch(done);
        });

        it('should throw error if invalid sheet name is in excel', (done) => {
            let reader = new ExcelReader(testWorkbooks.singleSheetFirstRowHeader, {
                sheets: [{
                    allowedNames: ['Incorrect Sheet']
                }]
            });
            reader.eachRow()
            .then(() => {
                done('Reader must throw error');
            })
            .catch((err) => {
                expect(err).to.exist();
                expect(err.message).to.match(/invalid sheet name/i);
            });
        });

        it('should allow any name if allowedNames is null', (done) => {
            let reader = new ExcelReader(testWorkbooks.singleSheetFirstRowHeader, {
                sheets: [{
                    allowedNames: null
                }]
            });
            reader.eachRow()
            .then(() => {
                done();
            })
            .catch(done);
        });
    });

    describe('Rows', () => {
        it('should assume default header row', (done) => {
            let reader = new ExcelReader(testWorkbooks.singleSheetFirstRowHeader, {
                sheets: [{
                    name: 'Data',
                    rows: {
                        allowedHeaders: [{
                            name: 'Sr No',
                            key: 'index'
                        }, {
                            name: 'Name',
                            key: 'name'
                        }, {
                            name: 'X Value',
                            key: 'x'
                        }, {
                            name: 'Y Value',
                            key: 'y'
                        }, {
                            name: 'Z Value',
                            key: 'z'
                        }, {
                            name: 'Total',
                            key: 'total'
                        }]
                    }
                }]
            });
            let output = [{
                index: '1',
                name: 'First Entry',
                x: '25',
                y: '30',
                z: '45',
                total: '100'
                }, {
                    index: '2',
                    name: 'Second Entry',
                    x: '20',
                    y: '20',
                    z: '20',
                    total: '60'
                }, {
                    index: '3',
                    name: 'Third Entry',
                    x: '15',
                    y: '10',
                    z: '8',
                    total: '33'
                }, {
                    index: '4',
                    name: 'Fourth Entry',
                    x: '22',
                    y: '39',
                    z: '65',
                    total: '126'
                }, {
                    index: '5',
                    name: 'Fifth Entry',
                    x: '42',
                    y: '8',
                    z: 'invalid num',
                    total: '50'
                }];

            reader.eachRow((rowData, rowNum) => {
                expect(rowData).to.eql(output[rowNum - 1]);
            })
            .then(() => {
                done();
            })
            .catch(done);
        });

        it('should take header row from config', () => {
            let reader = new ExcelReader(testWorkbooks.singleSheetNRowHeader, {
                sheets: [{
                    name: 'Data',
                    rows: {
                        headerRow: 6,
                        allowedHeaders: [{
                            name: 'Sr No',
                            key: 'index'
                        }, {
                            name: 'Name',
                            key: 'name'
                        }, {
                            name: 'X Value',
                            key: 'x'
                        }, {
                            name: 'Y Value',
                            key: 'y'
                        }]
                    }
                }]
            });
            let output = [{
                    index: '1',
                    name: 'First Entry',
                    x: '6',
                    y: '68'
                }, {
                    index: '2',
                    name: 'Second Entry',
                    x: '34',
                    y: '57'
            }];

            reader.eachRow((rowData, rowNum) => {
                expect(rowData).to.eql(output[rowNum - 1]);
            })
            .then(() => {
                done();
            })
            .catch(done);
        });

        it('should return each row data for multiple sheets', () => {
            let reader = new ExcelReader(testWorkbooks.multiSheetNRowHeader, {
                sheets: [{
                    name: 'First Sheet',
                    key: 'sheet1',
                    rows: {
                        headerRow: 4,
                        allowedHeaders: [{
                            name: 'Sr No',
                            key: 'index'
                        }, {
                            name: 'Name',
                            key: 'name'
                        }, {
                            name: 'X Value',
                            key: 'x'
                        }, {
                            name: 'Y Value',
                            key: 'y'
                        }, {
                            name: 'Total',
                            key: 'total'
                        }]
                    }
                }, {
                    name: 'Second Sheet',
                    key: 'sheet2',
                    rows: {
                        headerRow: 3,
                        allowedHeaders: [{
                            name: 'Name',
                            key: 'name'
                        }, {
                            name: 'Z Value',
                            key: 'x'
                        }, {
                            name: 'Total',
                            key: 'total'
                        }]
                    }
                }]
            });
            let output = {
                sheet1: [{
                        index: '1',
                        name: 'First Entry',
                        x: '25',
                        y: '5',
                        total: '30'
                    }, {
                        index: '2',
                        name: 'Second Entry',
                        x: '20',
                        y: '20',
                        total: '40'
                    }, {
                        index: '3',
                        name: 'Third Entry',
                        x: '15',
                        y: '10',
                        total: '25'
                    }, {
                        index: '4',
                        name: 'Fourth Entry',
                        x: '22',
                        y: 'error',
                        total: '22'
                }],
                sheet2: [{
                        name: 'First Entry',
                        z: '43',
                        total: '73'
                    }, {
                        name: 'Second Entry',
                        z: '77',
                        total: '117'
                    }, {
                        name: 'Second Entry',
                        z: '51',
                        total: '76'
                }]
            };;

            reader.eachRow((rowData, rowNum, sheetKey) => {
                expect(rowData).to.eql(output[sheetKey][rowNum - 1]);
            })
            .then(() => {
                done();
            })
            .catch(done);
        });
    });
});<|endoftext|>


<commit_before>// NOTE: The usage of user objects instead of userids is to deal with situations
//       such as where users change names and/or attempt to register multiple times.
//       This causes some operations to be O(N) instead of O(log N) or O(N*N) instead
//       of O(N*log N), until node.js implements the Map and Set objects.

var RoundRobin = (function () {
	function RoundRobin(isDoubles) {
		this.isDoubles = !!isDoubles;
		this.isBracketFrozen = false;
		this.users = [];
		this.isUsersBusy = null;
		this.matches = null;
		this.userScores = null;
		this.pendingMatches = 0;
	};
	RoundRobin.prototype.addUser = function (user) {
		if (this.isBracketFrozen)
			return 'BracketFrozen';

		if (this.users.indexOf(user) >= 0)
			return 'UserAlreadyAdded';

		this.users.push(user);
	};
	RoundRobin.prototype.removeUser = function (user) {
		if (this.isBracketFrozen)
			return 'BracketFrozen';

		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';

		this.users.splice(userIndex, 1);
	};
	RoundRobin.prototype.replaceUser = function (user, replacementUser) {
		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';

		if (this.users.indexOf(replacementUser) >= 0)
			return 'UserAlreadyAdded';

		this.users[userIndex] = replacementUser;
	};
	RoundRobin.prototype.getUserCount = function () {
		return this.users.length;
	};

	RoundRobin.prototype.getBracketData = function () {
		var data = {};
		data.type = 'table';
		data.tableHeaders = {
			cols: this.users.slice(0),
			rows: this.users.slice(0)
		};
		data.tableContents = this.users.map(function (userA, row) {
			return this.users.map(function (userB, col) {
				if (!this.isDoubles && col >= row)
					return null;
				if (userA === userB)
					return null;

				var cell = {};
				cell.teams = [userA, userB];
				if (!this.isBracketFrozen)
					cell.state = 'unavailable';
				else {
					var match = this.matches[row][col];
					cell.state = match.state;
					if (match.state === 'finished') {
						cell.result = match.result;
						cell.score = match.score.slice(0);
					}
				}
				return cell;
			}, this);
		}, this);
		data.scores = this.users.map(function (user, u) {
			var score = {};
			score.team = user;
			if (!this.isBracketFrozen)
				score.score = 0;
			else
				score.score = this.userScores[u];
			return score;
		}, this);
		return data;
	};
	RoundRobin.prototype.freezeBracket = function () {
		this.isBracketFrozen = true;
		this.isUsersBusy = this.users.map(function () { return false; });
		this.matches = this.users.map(function (userA, row) {
			return this.users.map(function (userB, col) {
				if (!this.isDoubles && col >= row)
					return null;
				if (userA === userB)
					return null;
				++this.pendingMatches;
				return {state: 'available'};
			}, this);
		}, this);
		this.userScores = this.users.map(function () { return 0; });
	};

	RoundRobin.prototype.disqualifyUser = function (user) {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';

		this.matches[userIndex].forEach(function (match, col) {
			if (!match || match.state !== 'available')
				return;
			match.state = 'finished';
			match.result = 'loss';
			match.score = [0, 1];
			++this.userScores[col];
			--this.pendingMatches;
		}, this);

		this.matches.forEach(function (challenges, row) {
			var match = challenges[userIndex];
			if (!match || match.state !== 'available')
				return;
			match.state = 'finished';
			match.result = 'win';
			match.score = [1, 0];
			++this.userScores[row];
			--this.pendingMatches;
		}, this);
	};
	RoundRobin.prototype.getUserBusy = function (user) {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';
		return this.isUsersBusy[userIndex];
	};
	RoundRobin.prototype.setUserBusy = function (user, isBusy) {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';
		this.isUsersBusy[userIndex] = isBusy;
	};

	RoundRobin.prototype.getAvailableMatches = function () {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		var matches = [];
		this.matches.forEach(function (challenges, row) {
			challenges.forEach(function (match, col) {
				if (!match)
					return;
				if (match.state === 'available' &&
					!this.isUsersBusy[row] && !this.isUsersBusy[col])
					matches.push([this.users[row], this.users[col]]);
			}, this);
		}, this);
		return matches;
	};
	RoundRobin.prototype.setMatchResult = function (match, result, score) {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		if (!(result in {win:1, loss:1, draw:1}))
			return 'InvalidResult';

		var userIndexA = this.users.indexOf(match[0]);
		var userIndexB = this.users.indexOf(match[1]);
		if (userIndexA < 0 || userIndexB < 0)
			return 'UserNotAdded';

		var match = this.matches[userIndexA][userIndexB];
		if (!match || match.state !== 'available')
			return 'InvalidMatch';

		var virtualScore;
		if (result === 'win')
			virtualScore = [1, 0];
		else if (result === 'loss')
			virtualScore = [0, 1];
		else
			virtualScore = [0.5, 0.5];
		if (!score)
			score = virtualScore;

		match.state = 'finished';
		match.result = result;
		match.score = score.slice(0);
		this.userScores[userIndexA] += virtualScore[0];
		this.userScores[userIndexB] += virtualScore[1];
		--this.pendingMatches;

		if (this.pendingMatches === 0)
			return true;
	};

	RoundRobin.prototype.getResults = function () {
		if (!this.isBracketFrozen || this.pendingMatches !== 0)
			return 'TournamentNotEnded';

		var sortedScores = this.userScores.map(function (score, userIndex) {
			return {userIndex: userIndex, score: score};
		}).sort(function (a, b) { return b.score - a.score; });

		var results = [];
		var currentScore = sortedScores[0].score;
		var currentRank = [];
		results.push(currentRank);
		sortedScores.forEach(function (score) {
			if (score.score < currentScore) {
				currentScore = score.score;
				currentRank = [];
				results.push(currentRank);
			}
			currentRank.push(this.users[score.userIndex]);
		}, this);
		return results;
	};

	return RoundRobin;
})();
exports.RoundRobin = RoundRobin;
<commit_msg>Whitespace<commit_after>// NOTE: The usage of user objects instead of userids is to deal with situations
//       such as where users change names and/or attempt to register multiple times.
//       This causes some operations to be O(N) instead of O(log N) or O(N*N) instead
//       of O(N*log N), until node.js implements the Map and Set objects.

var RoundRobin = (function () {
	function RoundRobin(isDoubles) {
		this.isDoubles = !!isDoubles;
		this.isBracketFrozen = false;
		this.users = [];
		this.isUsersBusy = null;
		this.matches = null;
		this.userScores = null;
		this.pendingMatches = 0;
	};

	RoundRobin.prototype.addUser = function (user) {
		if (this.isBracketFrozen)
			return 'BracketFrozen';

		if (this.users.indexOf(user) >= 0)
			return 'UserAlreadyAdded';

		this.users.push(user);
	};
	RoundRobin.prototype.removeUser = function (user) {
		if (this.isBracketFrozen)
			return 'BracketFrozen';

		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';

		this.users.splice(userIndex, 1);
	};
	RoundRobin.prototype.replaceUser = function (user, replacementUser) {
		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';

		if (this.users.indexOf(replacementUser) >= 0)
			return 'UserAlreadyAdded';

		this.users[userIndex] = replacementUser;
	};
	RoundRobin.prototype.getUserCount = function () {
		return this.users.length;
	};

	RoundRobin.prototype.getBracketData = function () {
		var data = {};
		data.type = 'table';
		data.tableHeaders = {
			cols: this.users.slice(0),
			rows: this.users.slice(0)
		};
		data.tableContents = this.users.map(function (userA, row) {
			return this.users.map(function (userB, col) {
				if (!this.isDoubles && col >= row)
					return null;
				if (userA === userB)
					return null;

				var cell = {};
				cell.teams = [userA, userB];
				if (!this.isBracketFrozen)
					cell.state = 'unavailable';
				else {
					var match = this.matches[row][col];
					cell.state = match.state;
					if (match.state === 'finished') {
						cell.result = match.result;
						cell.score = match.score.slice(0);
					}
				}
				return cell;
			}, this);
		}, this);
		data.scores = this.users.map(function (user, u) {
			var score = {};
			score.team = user;
			if (!this.isBracketFrozen)
				score.score = 0;
			else
				score.score = this.userScores[u];
			return score;
		}, this);
		return data;
	};
	RoundRobin.prototype.freezeBracket = function () {
		this.isBracketFrozen = true;
		this.isUsersBusy = this.users.map(function () { return false; });
		this.matches = this.users.map(function (userA, row) {
			return this.users.map(function (userB, col) {
				if (!this.isDoubles && col >= row)
					return null;
				if (userA === userB)
					return null;
				++this.pendingMatches;
				return {state: 'available'};
			}, this);
		}, this);
		this.userScores = this.users.map(function () { return 0; });
	};

	RoundRobin.prototype.disqualifyUser = function (user) {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';

		this.matches[userIndex].forEach(function (match, col) {
			if (!match || match.state !== 'available')
				return;
			match.state = 'finished';
			match.result = 'loss';
			match.score = [0, 1];
			++this.userScores[col];
			--this.pendingMatches;
		}, this);

		this.matches.forEach(function (challenges, row) {
			var match = challenges[userIndex];
			if (!match || match.state !== 'available')
				return;
			match.state = 'finished';
			match.result = 'win';
			match.score = [1, 0];
			++this.userScores[row];
			--this.pendingMatches;
		}, this);
	};
	RoundRobin.prototype.getUserBusy = function (user) {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';
		return this.isUsersBusy[userIndex];
	};
	RoundRobin.prototype.setUserBusy = function (user, isBusy) {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		var userIndex = this.users.indexOf(user);
		if (userIndex < 0)
			return 'UserNotAdded';
		this.isUsersBusy[userIndex] = isBusy;
	};

	RoundRobin.prototype.getAvailableMatches = function () {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		var matches = [];
		this.matches.forEach(function (challenges, row) {
			challenges.forEach(function (match, col) {
				if (!match)
					return;
				if (match.state === 'available' &&
					!this.isUsersBusy[row] && !this.isUsersBusy[col])
					matches.push([this.users[row], this.users[col]]);
			}, this);
		}, this);
		return matches;
	};
	RoundRobin.prototype.setMatchResult = function (match, result, score) {
		if (!this.isBracketFrozen)
			return 'BracketNotFrozen';

		if (!(result in {win:1, loss:1, draw:1}))
			return 'InvalidResult';

		var userIndexA = this.users.indexOf(match[0]);
		var userIndexB = this.users.indexOf(match[1]);
		if (userIndexA < 0 || userIndexB < 0)
			return 'UserNotAdded';

		var match = this.matches[userIndexA][userIndexB];
		if (!match || match.state !== 'available')
			return 'InvalidMatch';

		var virtualScore;
		if (result === 'win')
			virtualScore = [1, 0];
		else if (result === 'loss')
			virtualScore = [0, 1];
		else
			virtualScore = [0.5, 0.5];
		if (!score)
			score = virtualScore;

		match.state = 'finished';
		match.result = result;
		match.score = score.slice(0);
		this.userScores[userIndexA] += virtualScore[0];
		this.userScores[userIndexB] += virtualScore[1];
		--this.pendingMatches;

		if (this.pendingMatches === 0)
			return true;
	};

	RoundRobin.prototype.getResults = function () {
		if (!this.isBracketFrozen || this.pendingMatches !== 0)
			return 'TournamentNotEnded';

		var sortedScores = this.userScores.map(function (score, userIndex) {
			return {userIndex: userIndex, score: score};
		}).sort(function (a, b) { return b.score - a.score; });

		var results = [];
		var currentScore = sortedScores[0].score;
		var currentRank = [];
		results.push(currentRank);
		sortedScores.forEach(function (score) {
			if (score.score < currentScore) {
				currentScore = score.score;
				currentRank = [];
				results.push(currentRank);
			}
			currentRank.push(this.users[score.userIndex]);
		}, this);
		return results;
	};

	return RoundRobin;
})();

exports.RoundRobin = RoundRobin;
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import config from '../../config';
var Chart = require('../Charts/Chart');
import * as utils from '../Utils';
import ReactDOM from 'react-dom';
import moment from "moment";
var Highcharts = require('highcharts');
var $ = require('jquery');
var DateTimeField = require('react-bootstrap-datetimepicker');
if (typeof document !== 'undefined') {
  require("jquery-ui");
}

var callback = function (data) {
  console.log("entered callback");
  // console.log(this.chart);
  // console.log("DATA");
  // console.log(data);
  var chart_id = this.chart;

  if (chart_id == "17") {
    utils.setup_chart_special(data);
  }
  else {
    $("#chart-config").hide();
    var opts = utils.charts[chart_id];
    var series = utils.chart_series[chart_id];
    // console.log("SERIES:");
    // console.log(series);
    var queryResult = data;
    var opts_series = [];
    for (var i = 0; i < series.length; i++) {
      if (!series[i]["not-in-chart"]) {
        var attr = series[i]["attribute"];
        var qr = queryResult[attr];
        if (qr != null) {
          series[i]["data"] = [];
          for (var j = 0; j < qr.length; j++) {
            var num = Number(qr[j]);
            if (num != 0) {
              series[i]["data"].push([j, num]);
            }
          }
          opts_series.push(series[i]);
        }
      }
    }
    // console.log("OPTS SERIES");
    console.log(opts_series);

    opts.series = opts_series;
    // console.log("options");
    // console.log(opts);
    var element = React.createElement(Chart, {container: 'chart', options: opts});

    if (typeof window !== 'undefined') {
      ReactDOM.render(element, document.getElementById('chart'));
    }
  }
  if (typeof window != 'undefined') {
    $.get(config.server_url + '/index.php/jobs/UserList', {
        user: "",
        application: "null"
      },
      function (data) {
        var users = data;
        $.get(config.server_url + '/index.php/jobs/ApplicationList', {
            application: "",
            user: "null"
          },
          function (data) {
            var apps = data;
            // $("#user-typeahead").typeahead({source:users});
            // $("#application-typeahead").typeahead({source: apps});

            $("#user-typeahead").autocomplete(
              {
                source: users,
                messages: {
                  noResults: '',
                  results: function () {
                  }
                }
              }
            );
            $("#application-typeahead").autocomplete({
              source: apps,
              messages: {
                noResults: '',
                results: function () {
                }
              }
            });
          });
      });
  }

  // var element = React.createElement(Chart, {container: 'chart', options: opts});

  // if (typeof window !== 'undefined') {
  //   ReactDOM.render(element, document.getElementById('chart'));
  // }
};

function Filter({children}) {
  var numapp_placeholder = "Apps#";
  var user_placeholder = "User";
  var app_placeholder = "Application"
  var start_date = moment().subtract(5, 'years');
  var end_date = moment();
  var end_date_min = start_date;
  console.log("in the sorting >>>>>>>>>>>>>");
  var chart = utils.charts["12"];
  var series_ = utils.chart_series["12"];
  var options = chart.sorting;
  var labels = [];
  for (var i = 0; i < series_.length; i++) {
    labels[series_[i].attribute] = series_[i].name;
  }
  populateDropdown(".sortpicker", options, labels);

  return (

            <input type="text" name="user" className="form-control cust_autocomplete" id="user-typeahead"
                   data-provide="typeahead"
                   placeholder={user_placeholder} autocomplete="off"/>

            <input type="text" name="application" className="form-control cust_autocomplete" id="application-typeahead"
                   data-provide="typeahead" placeholder={app_placeholder} autocomplete="off"/>

          <DateTimeField
            dateTime={start_date}
            onChange={startDateChanged}
          />

          <DateTimeField
            dateTime={end_date}
            minDate={end_date_min}
            onChange={endDateChanged}
          />

          <button onClick={updateChart} type="button" className="btn btn-inverse tiny-button">Update</button>

          <button type="button" id="sort_button_top" className="btn tiny-button"
                  data-toggle="modal"
                  href="#sorting_modal">

            Sort
          </button>

          <button onClick={toggleChart} type="button" id="toggle-percentage"
                  className="btn tiny-button">
            %
          </button>

      <input type="hidden" id="chart_id_storage"/>
      <input type="hidden" id="start_date_storage"/>
      <input type="hidden" id="end_date_storage"/>

  );
}

function startDateChanged(e) {
  end_date_min = e;
  console.log(e);
  $("#start_date_storage").val(e);
}

function endDateChanged(e) {
  console.log(e);
  $("#end_date_storage").val(e);
}

function sortChart(e) {

}
var stacking = false;
if (typeof document !== 'undefined') {
  var index = $("#chart").data('highchartsChart');
  var chart = Highcharts.charts[index];
}
function toggleChart(e) {
  if (typeof document !== 'undefined') {
    console.log("starting toggle");
    // var chart = $("#chart").highcharts();
    for (var i = 0; i < 5; i++) {
      chart.series[i].update({
        stacking: stacking ? "normal" : "percent"
      });
    }

    chart.yAxis[0].axisTitle.attr({
      text: stacking ? "Distribution of time (s)" : "Percentage of time (%)"
    });

    if (!stacking) {
      chart.yAxis[0].setExtremes(0, 100);
    } else {
      chart.yAxis[0].setExtremes(null, null);
    }
    stacking = !stacking;
    chart.redraw();
    console.log("toggle done");
  }
}

function updateChart(e) {
  console.log(e);
  // get parameters
  var numapp = $("#numapp-typeahead").val();
  var user = $("#user-typeahead").val();
  var app = $("#application-typeahead").val();
  var start = $("#start_date_storage").val();
  var end = $("#start_date_storage").val();

  var chart_id = $("#chart_id_storage").val();
  $("#chart").html("
Loading...
");

  var data = {
    url: "test",
    chart: chart_id,
    start_date: start,
    end_date: end,
    application: app,
    numapp: numapp,
    user: user
  }
  console.log(data);
  if (typeof window !== 'undefined') {
    $.ajax({
      url: config.server_url + '/index.php/jobs/filter',
      // url: "http://localhost/index.php/jobs/filter",
      dataType: 'json',
      type: 'POST',
      data: JSON.stringify(data),
      chart: chart_id,
      success: callback,
      error: function (xhr, status, err) {
        console.log("ERROR");
        console.log(xhr);
        console.log(status);
        console.log(err);
      }
    });
  }
}

function populateDropdown(selector, options, labels) {
  if (typeof document !== 'undefined') {
    var str = "";
    if (typeof options != 'undefined') {
      for (var i = 0; i < options.length; i++) {
        str += '<option value="' + options[i] + '">' + labels[options[i]] + '</option>';
      }

      $(selector).append(str);
      // $(selector).selectpicker('refresh');
    }
  }
}

Filter.propTypes = {
  // children: PropTypes.element.isRequired,
};

export default Filter;
<commit_msg>modify default for users/apps placeholders, fix #11<commit_after>import React, {PropTypes} from 'react';
import config from '../../config';
var Chart = require('../Charts/Chart');
import * as utils from '../Utils';
import ReactDOM from 'react-dom';
import moment from "moment";
var Highcharts = require('highcharts');
var $ = require('jquery');
var DateTimeField = require('react-bootstrap-datetimepicker');
if (typeof document !== 'undefined') {
  require("jquery-ui");
}

var callback = function (data) {
  console.log("entered callback");
  // console.log(this.chart);
  // console.log("DATA");
  // console.log(data);
  var chart_id = this.chart;

  if (chart_id == "17") {
    utils.setup_chart_special(data);
  }
  else {
    $("#chart-config").hide();
    var opts = utils.charts[chart_id];
    var series = utils.chart_series[chart_id];
    // console.log("SERIES:");
    // console.log(series);
    var queryResult = data;
    var opts_series = [];
    for (var i = 0; i < series.length; i++) {
      if (!series[i]["not-in-chart"]) {
        var attr = series[i]["attribute"];
        var qr = queryResult[attr];
        if (qr != null) {
          series[i]["data"] = [];
          for (var j = 0; j < qr.length; j++) {
            var num = Number(qr[j]);
            if (num != 0) {
              series[i]["data"].push([j, num]);
            }
          }
          opts_series.push(series[i]);
        }
      }
    }
    // console.log("OPTS SERIES");
    console.log(opts_series);

    opts.series = opts_series;
    // console.log("options");
    // console.log(opts);
    var element = React.createElement(Chart, {container: 'chart', options: opts});

    if (typeof window !== 'undefined') {
      ReactDOM.render(element, document.getElementById('chart'));
    }
  }
  if (typeof window != 'undefined') {
    $.get(config.server_url + '/index.php/jobs/UserList', {
        user: "",
        application: "null"
      },
      function (data) {
        var users = data;
        $.get(config.server_url + '/index.php/jobs/ApplicationList', {
            application: "",
            user: "null"
          },
          function (data) {
            var apps = data;
            // $("#user-typeahead").typeahead({source:users});
            // $("#application-typeahead").typeahead({source: apps});

            $("#user-typeahead").autocomplete(
              {
                source: users,
                messages: {
                  noResults: '',
                  results: function () {
                  }
                }
              }
            );
            $("#application-typeahead").autocomplete({
              source: apps,
              messages: {
                noResults: '',
                results: function () {
                }
              }
            });
          });
      });
  }

  // var element = React.createElement(Chart, {container: 'chart', options: opts});

  // if (typeof window !== 'undefined') {
  //   ReactDOM.render(element, document.getElementById('chart'));
  // }
};

function Filter({children}) {
  var numapp_placeholder = "Apps#";
  var user_placeholder = "All users";
  var app_placeholder = "All apps"
  var start_date = moment().subtract(5, 'years');
  var end_date = moment();
  var end_date_min = start_date;
  console.log("in the sorting >>>>>>>>>>>>>");
  var chart = utils.charts["12"];
  var series_ = utils.chart_series["12"];
  var options = chart.sorting;
  var labels = [];
  for (var i = 0; i < series_.length; i++) {
    labels[series_[i].attribute] = series_[i].name;
  }
  populateDropdown(".sortpicker", options, labels);

  return (

            <input type="text" name="user" className="form-control cust_autocomplete" id="user-typeahead"
                   data-provide="typeahead"
                   placeholder={user_placeholder} autocomplete="off"/>

            <input type="text" name="application" className="form-control cust_autocomplete" id="application-typeahead"
                   data-provide="typeahead" placeholder={app_placeholder} autocomplete="off"/>

          <DateTimeField
            dateTime={start_date}
            onChange={startDateChanged}
          />

          <DateTimeField
            dateTime={end_date}
            minDate={end_date_min}
            onChange={endDateChanged}
          />

          <button onClick={updateChart} type="button" className="btn btn-inverse tiny-button">Update</button>

          <button type="button" id="sort_button_top" className="btn tiny-button"
                  data-toggle="modal"
                  href="#sorting_modal">

            Sort
          </button>

          <button onClick={toggleChart} type="button" id="toggle-percentage"
                  className="btn tiny-button">
            %
          </button>

      <input type="hidden" id="chart_id_storage"/>
      <input type="hidden" id="start_date_storage"/>
      <input type="hidden" id="end_date_storage"/>

  );
}

function startDateChanged(e) {
  end_date_min = e;
  console.log(e);
  $("#start_date_storage").val(e);
}

function endDateChanged(e) {
  console.log(e);
  $("#end_date_storage").val(e);
}

function sortChart(e) {

}
var stacking = false;
if (typeof document !== 'undefined') {
  var index = $("#chart").data('highchartsChart');
  var chart = Highcharts.charts[index];
}
function toggleChart(e) {
  if (typeof document !== 'undefined') {
    console.log("starting toggle");
    // var chart = $("#chart").highcharts();
    for (var i = 0; i < 5; i++) {
      chart.series[i].update({
        stacking: stacking ? "normal" : "percent"
      });
    }

    chart.yAxis[0].axisTitle.attr({
      text: stacking ? "Distribution of time (s)" : "Percentage of time (%)"
    });

    if (!stacking) {
      chart.yAxis[0].setExtremes(0, 100);
    } else {
      chart.yAxis[0].setExtremes(null, null);
    }
    stacking = !stacking;
    chart.redraw();
    console.log("toggle done");
  }
}

function updateChart(e) {
  console.log(e);
  // get parameters
  var numapp = $("#numapp-typeahead").val();
  var user = $("#user-typeahead").val();
  var app = $("#application-typeahead").val();
  var start = $("#start_date_storage").val();
  var end = $("#start_date_storage").val();

  var chart_id = $("#chart_id_storage").val();
  $("#chart").html("
Loading...
");

  var data = {
    url: "test",
    chart: chart_id,
    start_date: start,
    end_date: end,
    application: app,
    numapp: numapp,
    user: user
  }
  console.log(data);
  if (typeof window !== 'undefined') {
    $.ajax({
      url: config.server_url + '/index.php/jobs/filter',
      // url: "http://localhost/index.php/jobs/filter",
      dataType: 'json',
      type: 'POST',
      data: JSON.stringify(data),
      chart: chart_id,
      success: callback,
      error: function (xhr, status, err) {
        console.log("ERROR");
        console.log(xhr);
        console.log(status);
        console.log(err);
      }
    });
  }
}

function populateDropdown(selector, options, labels) {
  if (typeof document !== 'undefined') {
    var str = "";
    if (typeof options != 'undefined') {
      for (var i = 0; i < options.length; i++) {
        str += '<option value="' + options[i] + '">' + labels[options[i]] + '</option>';
      }

      $(selector).append(str);
      // $(selector).selectpicker('refresh');
    }
  }
}

Filter.propTypes = {
  // children: PropTypes.element.isRequired,
};

export default Filter;
<|endoftext|>


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

'use strict';

// MODULES //

var Readable = require( 'readable-stream' ).Readable;
var isError = require( '@stdlib/assert/is-error' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isUint8Array = require( '@stdlib/assert/is-uint8array' );
var arraybuffer2buffer = require( '@stdlib/buffer/from-arraybuffer' );
var string2buffer = require( '@stdlib/buffer/from-string' );
var Buffer = require( '@stdlib/buffer/ctor' ); // TODO: replace Buffer.concat usage with stdlib pkg
var copy = require( '@stdlib/utils/copy' );
var inherit = require( '@stdlib/utils/inherit' );
var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var debug = require( './debug.js' );

// FUNCTIONS //

/**
* Implements the `_read` method.
*
* @private
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
function read() {
	/* eslint-disable no-invalid-this */
	var FLG;
	if ( this._destroyed ) {
		return;
	}
	FLG = true;
	while ( FLG ) {
		this._i += 1;
		if ( this._i > this._iter ) {
			debug( 'Finished iteration.' );
			return this.push( null );
		}
		debug( 'Value: %s. Iter: %d.', this._value, this._i );
		if ( this._objectMode === false && this._i > 1 ) {
			FLG = this.push( Buffer.concat( [ this._sep, this._value ] ) );
		} else {
			FLG = this.push( this._value );
		}
	}

	/* eslint-enable no-invalid-this */
}

/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {(string|Object|Error)} [error] - error
* @returns {ConstantStream} Stream instance
*/
function destroy( error ) {
	/* eslint-disable no-invalid-this */
	var self;
	if ( this._destroyed ) {
		debug( 'Attempted to destroy an already destroyed stream.' );
		return this;
	}
	self = this;
	this._destroyed = true;

	// TODO: replace with polyfill
	process.nextTick( close );

	return this;

	/**
	* Closes a stream.
	*
	* @private
	*/
	function close() {
		if ( error ) {
			debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) );
			self.emit( 'error', error );
		}
		debug( 'Closing the stream...' );
		self.emit( 'close' );
	}

	/* eslint-enable no-invalid-this */
}

// MAIN //

/**
* Stream constructor for generating a stream which always streams the same value.
*
* @constructor
* @param {(string|Buffer|Uint8Array)} value - value to stream
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before pausing streaming
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @throws {TypeError} in binary mode, value to stream must be a string, `Buffer`, or `Uint8Array`
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {ConstantStream} Stream instance
*
* @example
* var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
*
* function log( chunk ) {
*    console.log( chunk.toString() );
* }
*
* var opts = {
*     'iter': 10
* };
*
* var stream = new ConstantStream( 'beep', opts );
*
* stream.pipe( inspectStream( log )  );
*/
function ConstantStream( value, options ) {
	var opts;
	var err;
	if ( !( this instanceof ConstantStream ) ) {
		if ( arguments.length > 1 ) {
			return new ConstantStream( value, options );
		}
		return new ConstantStream( value );
	}
	opts = copy( DEFAULTS );
	if ( arguments.length > 1 ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	if ( opts.objectMode === false ) {
		if ( isString( value ) ) {
			value = string2buffer( value );
		} else if ( isBuffer( value ) ) {
			// Nothing to do, as value is already a buffer...
		} else if ( isUint8Array( value ) ) {
			// Convert to a `Buffer` object to provide backward compatibility with older Node.js versions...
			value = arraybuffer2buffer( value.buffer, value.byteOffset, value.length ); // eslint-disable-line max-len
		} else {
			throw new TypeError( 'invalid argument. In binary mode, a provided value must be a string, Buffer, or Uint8Array. Value: `' + value + '`.' );
		}
	}
	// Make the stream a readable stream:
	debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
	Readable.call( this, opts );

	// Destruction state:
	setNonEnumerable( this, '_destroyed', false );

	// Cache whether the stream is operating in object mode:
	setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode );

	// Cache the separator:
	setNonEnumerableReadOnly( this, '_sep', string2buffer( opts.sep ) );

	// Cache the total number of iterations:
	setNonEnumerableReadOnly( this, '_iter', opts.iter );

	// Cache the value to stream:
	setNonEnumerableReadOnly( this, '_value', value );

	// Initialize an iteration counter:
	setNonEnumerable( this, '_i', 0 );

	return this;
}

/*
* Inherit from the `Readable` prototype.
*/
inherit( ConstantStream, Readable );

/**
* Implements the `_read` method.
*
* @private
* @name _read
* @memberof ConstantStream.prototype
* @type {Function}
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
setNonEnumerableReadOnly( ConstantStream.prototype, '_read', read );

/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof ConstantStream.prototype
* @type {Function}
* @param {(string|Object|Error)} [error] - error
* @returns {ConstantStream} Stream instance
*/
setNonEnumerableReadOnly( ConstantStream.prototype, 'destroy', destroy );

// EXPORTS //

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

'use strict';

// MODULES //

var Readable = require( 'readable-stream' ).Readable;
var isError = require( '@stdlib/assert/is-error' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isUint8Array = require( '@stdlib/assert/is-uint8array' );
var arraybuffer2buffer = require( '@stdlib/buffer/from-arraybuffer' );
var string2buffer = require( '@stdlib/buffer/from-string' );
var Buffer = require( '@stdlib/buffer/ctor' ); // TODO: replace Buffer.concat usage with stdlib pkg
var copy = require( '@stdlib/utils/copy' );
var inherit = require( '@stdlib/utils/inherit' );
var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var debug = require( './debug.js' );

// FUNCTIONS //

/**
* Implements the `_read` method.
*
* @private
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
function read() {
	/* eslint-disable no-invalid-this */
	var FLG;
	if ( this._destroyed ) {
		return;
	}
	FLG = true;
	while ( FLG ) {
		this._i += 1;
		if ( this._i > this._iter ) {
			debug( 'Finished iteration.' );
			return this.push( null );
		}
		debug( 'Value: %s. Iter: %d.', this._value, this._i );
		if ( this._objectMode === false && this._i > 1 ) {
			FLG = this.push( Buffer.concat( [ this._sep, this._value ] ) );
		} else {
			FLG = this.push( this._value );
		}
	}

	/* eslint-enable no-invalid-this */
}

/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {(string|Object|Error)} [error] - error
* @returns {ConstantStream} Stream instance
*/
function destroy( error ) {
	/* eslint-disable no-invalid-this */
	var self;
	if ( this._destroyed ) {
		debug( 'Attempted to destroy an already destroyed stream.' );
		return this;
	}
	self = this;
	this._destroyed = true;

	// TODO: replace with polyfill
	process.nextTick( close );

	return this;

	/**
	* Closes a stream.
	*
	* @private
	*/
	function close() {
		if ( error ) {
			debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) );
			self.emit( 'error', error );
		}
		debug( 'Closing the stream...' );
		self.emit( 'close' );
	}

	/* eslint-enable no-invalid-this */
}

// MAIN //

/**
* Stream constructor for generating a stream which always streams the same value.
*
* @constructor
* @param {(string|Buffer|Uint8Array)} value - value to stream
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before pausing streaming
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @throws {TypeError} in binary mode, value to stream must be a string, `Buffer`, or `Uint8Array`
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {ConstantStream} Stream instance
*
* @example
* var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
*
* function log( chunk ) {
*    console.log( chunk.toString() );
* }
*
* var opts = {
*     'iter': 10
* };
*
* var stream = new ConstantStream( 'beep', opts );
*
* stream.pipe( inspectStream( log )  );
*/
function ConstantStream( value, options ) {
	var opts;
	var err;
	if ( !( this instanceof ConstantStream ) ) {
		if ( arguments.length > 1 ) {
			return new ConstantStream( value, options );
		}
		return new ConstantStream( value );
	}
	opts = copy( DEFAULTS );
	if ( arguments.length > 1 ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	if ( opts.objectMode === false ) {
		if ( isString( value ) ) {
			value = string2buffer( value );
		} else if ( isBuffer( value ) ) { // NOTE: order matters here. We want the `isBuffer` check BEFORE the `isUint8Array` check!!
			// Nothing to do, as value is already a buffer...
		} else if ( isUint8Array( value ) ) {
			// Convert to a `Buffer` object to provide backward compatibility with older Node.js versions...
			value = arraybuffer2buffer( value.buffer, value.byteOffset, value.length ); // eslint-disable-line max-len
		} else {
			throw new TypeError( 'invalid argument. In binary mode, a provided value must be a string, Buffer, or Uint8Array. Value: `' + value + '`.' );
		}
	}
	// Make the stream a readable stream:
	debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
	Readable.call( this, opts );

	// Destruction state:
	setNonEnumerable( this, '_destroyed', false );

	// Cache whether the stream is operating in object mode:
	setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode );

	// Cache the separator:
	setNonEnumerableReadOnly( this, '_sep', string2buffer( opts.sep ) );

	// Cache the total number of iterations:
	setNonEnumerableReadOnly( this, '_iter', opts.iter );

	// Cache the value to stream:
	setNonEnumerableReadOnly( this, '_value', value );

	// Initialize an iteration counter:
	setNonEnumerable( this, '_i', 0 );

	return this;
}

/*
* Inherit from the `Readable` prototype.
*/
inherit( ConstantStream, Readable );

/**
* Implements the `_read` method.
*
* @private
* @name _read
* @memberof ConstantStream.prototype
* @type {Function}
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
setNonEnumerableReadOnly( ConstantStream.prototype, '_read', read );

/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof ConstantStream.prototype
* @type {Function}
* @param {(string|Object|Error)} [error] - error
* @returns {ConstantStream} Stream instance
*/
setNonEnumerableReadOnly( ConstantStream.prototype, 'destroy', destroy );

// EXPORTS //

module.exports = ConstantStream;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular
    .module('users')
    .run(menuConfig);

  menuConfig.$inject = ['menuService', 'Authentication', '$rootScope', 'AUTH_EVENTS'];

  function menuConfig(menuService, Authentication, $rootScope, AUTH_EVENTS) {

    menuService.toolbar.addItem({
      title: 'Sign In',
      icon: 'login',
      type: 'button',
      state: 'authentication.signin',
      aria: 'User Sign In',
      show: true
    });

    menuService.toolbar.addItem({
      title: 'Sign Up',
      icon: 'timer_auto',
      type: 'button',
      state: 'authentication.signup',
      aria: 'User Sign Up',
      show: true
    });

    $rootScope.$on(AUTH_EVENTS.loginSuccess, function () {
      console.log('User::Run::Login::Event', Authentication);
      if (Authentication.user) {
        menuService.toolbar.addItem({
          id: 'usermenu',
          title: Authentication.user.displayName,
          icon: 'more_vert',
          type: 'menu',
          aria: 'User Menu',
          flex: 15,
          show: true,
          items: [{
            title: 'Edit Profile',
            icon: 'create',
            state: 'settings.profile'
          },
          {
            title: 'Change Profile Picture',
            icon: 'photo_camera',
            state: 'settings.picture'
          },
          {
            title: 'Change Password',
            icon: 'vpn_key',
            state: 'settings.password'
          },
          {
            title: 'Manage Social Accounts',
            icon: 'logout',
            state: 'settings.accounts'
          },
          {
            title: 'Signout',
            icon: 'people',
            state: 'signout'
          }]
        });
      }

      menuService.toolbar.getItem({ state: 'authentication.signup' }).show = false;
      menuService.toolbar.getItem({ state: 'authentication.signin' }).show = false;

    });

    $rootScope.$on(AUTH_EVENTS.logoutSuccess, function () {
      console.log('User::Run::Logout::Event', menuService.toolbar);

      menuService.toolbar.getItem({ state: 'authentication.signup' }).show = true;
      menuService.toolbar.getItem({ state: 'authentication.signin' }).show = true;

      menuService.toolbar.removeItem({ id: 'usermenu' });

    });

  }

})();
<commit_msg>fix(user) Remove flex toolbar item<commit_after>(function() {
  'use strict';

  angular
    .module('users')
    .run(menuConfig);

  menuConfig.$inject = ['menuService', 'Authentication', '$rootScope', 'AUTH_EVENTS'];

  function menuConfig(menuService, Authentication, $rootScope, AUTH_EVENTS) {

    menuService.toolbar.addItem({
      title: 'Sign In',
      icon: 'login',
      type: 'button',
      state: 'authentication.signin',
      aria: 'User Sign In',
      show: true
    });

    menuService.toolbar.addItem({
      title: 'Sign Up',
      icon: 'timer_auto',
      type: 'button',
      state: 'authentication.signup',
      aria: 'User Sign Up',
      show: true
    });

    $rootScope.$on(AUTH_EVENTS.loginSuccess, function () {
      console.log('User::Run::Login::Event', Authentication);
      if (Authentication.user) {
        menuService.toolbar.addItem({
          id: 'usermenu',
          title: Authentication.user.displayName,
          icon: 'more_vert',
          type: 'menu',
          aria: 'User Menu',
          show: true,
          items: [{
            title: 'Edit Profile',
            icon: 'create',
            state: 'settings.profile'
          },
          {
            title: 'Change Profile Picture',
            icon: 'photo_camera',
            state: 'settings.picture'
          },
          {
            title: 'Change Password',
            icon: 'vpn_key',
            state: 'settings.password'
          },
          {
            title: 'Manage Social Accounts',
            icon: 'logout',
            state: 'settings.accounts'
          },
          {
            title: 'Signout',
            icon: 'people',
            state: 'signout'
          }]
        });
      }

      menuService.toolbar.getItem({ state: 'authentication.signup' }).show = false;
      menuService.toolbar.getItem({ state: 'authentication.signin' }).show = false;

    });

    $rootScope.$on(AUTH_EVENTS.logoutSuccess, function () {
      console.log('User::Run::Logout::Event', menuService.toolbar);

      menuService.toolbar.getItem({ state: 'authentication.signup' }).show = true;
      menuService.toolbar.getItem({ state: 'authentication.signin' }).show = true;

      menuService.toolbar.removeItem({ id: 'usermenu' });

    });

  }

})();
<|endoftext|>


<commit_before>
/**
 * For the database connection
 */

var mongoose = require('mongoose'),
    config = require('../config').config,
    EventProxy = require('eventproxy').EventProxy,
    utils = require('../utils');

exports.initialize = function() {
    var db = mongoose.createConnection(config.db.DB_HOST, config.db.DB_NAME);
    global.db = db;

    var menuSchema = mongoose.Schema({title: String, url: String});
    db.model('Menu', menuSchema);

    var postSchema = mongoose.Schema({date: Date, author: String, title: String, content: String});
    db.model('Post', postSchema);

    var linkSchema = mongoose.Schema({title: String, url: String});
    db.model('Link', linkSchema);

    var categorySchema = mongoose.Schema({pid: String, title: String});
    db.model('Category', categorySchema);

    var tagSchema = mongoose.Schema({pid: String, title: String});
    db.model('Tag', tagSchema);

    var commentSchema = mongoose.Schema({pid: String, name: String, email: String, content: String});
    db.model('Comment', commentSchema);

    var self = this;
    return function initialize(req, resp, next) {
        req.dbEvt = self;
        next();
    }
}

var dbMenu = require('./db.menu'), dbPost = require('./db.post'), dbLink = require('./db.link');
for(var i in dbMenu)
    exports[i] = dbMenu[i];
for(var i in dbPost)
    exports[i] = dbPost[i];
for(var i in dbLink)
    exports[i] = dbLink[i];<commit_msg>SorryÀ²£¬»¹ÊÇÔÚ²âÊÔÅ¶¡£<commit_after>/**
 * For the database connection
 */

var mongoose = require('mongoose'),
    config = require('../config').config,
    EventProxy = require('eventproxy').EventProxy,
    utils = require('../utils');

exports.initialize = function() {
    var db = mongoose.createConnection(config.db.DB_HOST, config.db.DB_NAME);
    global.db = db;

    var menuSchema = mongoose.Schema({title: String, url: String});
    db.model('Menu', menuSchema);

    var postSchema = mongoose.Schema({date: Date, author: String, title: String, content: String});
    db.model('Post', postSchema);

    var linkSchema = mongoose.Schema({title: String, url: String});
    db.model('Link', linkSchema);

    var categorySchema = mongoose.Schema({pid: String, title: String});
    db.model('Category', categorySchema);

    var tagSchema = mongoose.Schema({pid: String, title: String});
    db.model('Tag', tagSchema);

    var commentSchema = mongoose.Schema({pid: String, name: String, email: String, content: String});
    db.model('Comment', commentSchema);

    var self = this;
    return function initialize(req, resp, next) {
        req.dbEvt = self;
        next();
    }
}

var dbMenu = require('./db.menu'), dbPost = require('./db.post'), dbLink = require('./db.link');
for(var i in dbMenu)
    exports[i] = dbMenu[i];
for(var i in dbPost)
    exports[i] = dbPost[i];
for(var i in dbLink)
    exports[i] = dbLink[i];<|endoftext|>


<commit_before>'use strict';

var fs      = require('fs'),
    path    = require('path'),
    express = require('express');

var routes = function () {

    var startDir = null,

    //Called once during initial server startup
    load = function(app, folderName) {

        //folder that acts as the container for convention-based routes (for example "controllers")
        if (!startDir) startDir = path.basename(folderName);
        fs.readdirSync(folderName).forEach(function(file) {

            var fullName = path.join(folderName, file);
            var stat = fs.lstatSync(fullName);

            if (stat.isDirectory()) {
                //Recursively walk-through folders
                load(app, fullName);
            }
            else if (file.toLowerCase().indexOf('.js')) {
                //Grab path to JavaScript file and use it to construct the route
                var dirs = path.dirname(fullName).split(path.sep);

                //Filter out all folder paths up to the startDir (and including the startDir) originally passed in.
                //For example, if startDir is "controllers" then we find it and remove everything to it
                //That means that mybasepath/subfolder/controllers/api/auth becomes /api/auth
                //This allows for server.js to be started from different paths
                var startDirIndex = dirs.indexOf(startDir),
                    startDirLastIndex = dirs.lastIndexOf(startDir);
                //Ensure startDir only exists once in the overall path of directories. If it's found more than once we
                //can't make this work (as is) so throw an error
                if (startDirIndex === startDirLastIndex) {
                    dirs.splice(0, startDirIndex + 1);
                }
                else {
                    throw new Error(startDir + ' directory may only appear once in the directory path.')
                }

                var router = express.Router();
                //Generate the base route used by the Express router
                var baseRoute = '/' + dirs.join('/');
                if (app.settings.env === 'development') {
                    console.log('Created route: ' + baseRoute + ' for ' + fullName + '\n');
                }

                //Load the JavaScript file ("controller") and pass the router to it
                require(fullName)(router);
                //Associate the route with the router
                app.use(baseRoute, router);
            }
        });

    };

    return {
        load: load
    };

}();

module.exports = routes;

<commit_msg>Validate index position is greater than -1<commit_after>'use strict';

var fs      = require('fs'),
    path    = require('path'),
    express = require('express');

var routes = function () {

    var startDir = null,

    //Called once during initial server startup
    load = function(app, folderName) {

        //folder that acts as the container for convention-based routes (for example "controllers")
        if (!startDir) startDir = path.basename(folderName);
        fs.readdirSync(folderName).forEach(function(file) {

            var fullName = path.join(folderName, file);
            var stat = fs.lstatSync(fullName);

            if (stat.isDirectory()) {
                //Recursively walk-through folders
                load(app, fullName);
            }
            else if (file.toLowerCase().indexOf('.js') > -1) {
                //Grab path to JavaScript file and use it to construct the route
                var dirs = path.dirname(fullName).split(path.sep);

                //Filter out all folder paths up to the startDir (and including the startDir) originally passed in.
                //For example, if startDir is "controllers" then we find it and remove everything to it
                //That means that mybasepath/subfolder/controllers/api/auth becomes /api/auth
                //This allows for server.js to be started from different paths
                var startDirIndex = dirs.indexOf(startDir),
                    startDirLastIndex = dirs.lastIndexOf(startDir);
                //Ensure startDir only exists once in the overall path of directories. If it's found more than once we
                //can't make this work (as is) so throw an error
                if (startDirIndex === startDirLastIndex) {
                    dirs.splice(0, startDirIndex + 1);
                }
                else {
                    throw new Error(startDir + ' directory may only appear once in the directory path.')
                }

                var router = express.Router();
                //Generate the base route used by the Express router
                var baseRoute = '/' + dirs.join('/');
                if (app.settings.env === 'development') {
                    console.log('Created route: ' + baseRoute + ' for ' + fullName + '\n');
                }

                //Load the JavaScript file ("controller") and pass the router to it
                require(fullName)(router);
                //Associate the route with the router
                app.use(baseRoute, router);
            }
        });

    };

    return {
        load: load
    };

}();

module.exports = routes;

<|endoftext|>


<commit_before>module.exports.register = function (context) {

  var TheGraph = context.TheGraph;

  TheGraph.config.group = {
    container: {
      className: "group"
    },
    boxRect: {
      ref: "box",
      rx: TheGraph.config.nodeRadius,
      ry: TheGraph.config.nodeRadius
    },
    labelText: {
      ref: "label",
      className: "group-label drag"
    },
    descriptionText: {
      className: "group-description"
    }
  };

  TheGraph.factories.group = {
    createGroupGroup: TheGraph.factories.createGroup,
    createGroupBoxRect: TheGraph.factories.createRect,
    createGroupLabelText: TheGraph.factories.createText,
    createGroupDescriptionText: TheGraph.factories.createText
  };

  // Group view

  TheGraph.Group = React.createFactory( React.createClass({
    displayName: "TheGraphGroup",
    componentDidMount: function () {

      // Move group
      // either by label or by box
      var dragRefName = (this.props.isSelectionGroup) ? 'box' : 'label';
      var dragNode = ReactDOM.findDOMNode(this.refs[dragRefName]);
      dragNode.addEventListener('panstart', this.onTrackStart);

      // Context menu
      var domNode = ReactDOM.findDOMNode(this);
      if (this.props.showContext) {
        domNode.addEventListener("contextmenu", this.showContext);
        domNode.addEventListener("press", this.showContext);
      }

    },
    showContext: function (event) {
      // Don't show native context menu
      event.preventDefault();

      // Don't tap graph on hold event
      if (event.stopPropagation) { event.stopPropagation(); }
      if (event.preventTap) { event.preventTap(); }

      // Get mouse position
      if (event.gesture) {
        event = event.gesture.srcEvent; // unpack hammer.js gesture event
      }
      var x = event.x || event.clientX || 0;
      var y = event.y || event.clientY || 0;

      // App.showContext
      this.props.showContext({
        element: this,
        type: (this.props.isSelectionGroup ? "selection" : "group"),
        x: x,
        y: y,
        graph: this.props.graph,
        itemKey: this.props.label,
        item: this.props.item
      });
    },
    getContext: function (menu, options, hide) {
      return TheGraph.Menu({
        menu: menu,
        options: options,
        label: this.props.label,
        triggerHideContext: hide
      });
    },
    onTrackStart: function (event) {
      // Don't pan graph
      event.stopPropagation();

      var dragRefName = (this.props.isSelectionGroup) ? 'box' : 'label';
      var dragNode = ReactDOM.findDOMNode(this.refs[dragRefName]);
      dragNode.addEventListener("panmove", this.onTrack);
      dragNode.addEventListener("panend", this.onTrackEnd);

      this.props.graph.startTransaction('movegroup');
    },
    onTrack: function (event) {
      // Don't pan graph
      event.stopPropagation();

      var deltaX = Math.round( event.gesture.srcEvent.movementX / this.props.scale );
      var deltaY = Math.round( event.gesture.srcEvent.movementY / this.props.scale );

      this.props.triggerMoveGroup(this.props.item.nodes, deltaX, deltaY);
    },
    onTrackEnd: function (event) {
      // Don't pan graph
      event.stopPropagation();

      // Snap to grid
      this.props.triggerMoveGroup(this.props.item.nodes);

      var dragRefName = (this.props.isSelectionGroup) ? 'box' : 'label';
      var dragNode = ReactDOM.findDOMNode(this.refs[dragRefName]);
      dragNode.addEventListener("panmove", this.onTrack);
      dragNode.addEventListener("panend", this.onTrackEnd);

      this.props.graph.endTransaction('movegroup');
    },
    render: function() {
      var x = this.props.minX - TheGraph.config.nodeWidth / 2;
      var y = this.props.minY - TheGraph.config.nodeHeight / 2;
      var color = (this.props.color ? this.props.color : 0);
      var selection = (this.props.isSelectionGroup ? ' selection drag' : '');
      var boxRectOptions = {
        x: x,
        y: y,
        width: this.props.maxX - x + TheGraph.config.nodeWidth*0.5,
        height: this.props.maxY - y + TheGraph.config.nodeHeight*0.75,
        className: "group-box color"+color + selection
      };
      boxRectOptions = TheGraph.merge(TheGraph.config.group.boxRect, boxRectOptions);
      var boxRect =  TheGraph.factories.group.createGroupBoxRect.call(this, boxRectOptions);

      var labelTextOptions = {
        x: x + TheGraph.config.nodeRadius,
        y: y + 9,
        children: this.props.label
      };
      labelTextOptions = TheGraph.merge(TheGraph.config.group.labelText, labelTextOptions);
      var labelText = TheGraph.factories.group.createGroupLabelText.call(this, labelTextOptions);

      var descriptionTextOptions = {
        x: x + TheGraph.config.nodeRadius,
        y: y + 24,
        children: this.props.description
      };
      descriptionTextOptions = TheGraph.merge(TheGraph.config.group.descriptionText, descriptionTextOptions);
      var descriptionText = TheGraph.factories.group.createGroupDescriptionText.call(this, descriptionTextOptions);

      var groupContents = [
        boxRect,
        labelText,
        descriptionText
      ];

      var containerOptions = TheGraph.merge(TheGraph.config.group.container, {});
      return TheGraph.factories.group.createGroupGroup.call(this, containerOptions, groupContents);

    }
  }));

};
<commit_msg>the-graph-group: Extend element to catch events during pan<commit_after>module.exports.register = function (context) {

  var TheGraph = context.TheGraph;

  TheGraph.config.group = {
    container: {
      className: "group"
    },
    boxRect: {
      rx: TheGraph.config.nodeRadius,
      ry: TheGraph.config.nodeRadius
    },
    labelText: {
      className: "group-label"
    },
    descriptionText: {
      className: "group-description"
    }
  };

  TheGraph.factories.group = {
    createGroupGroup: TheGraph.factories.createGroup,
    createGroupBoxRect: TheGraph.factories.createRect,
    createGroupLabelText: TheGraph.factories.createText,
    createGroupDescriptionText: TheGraph.factories.createText
  };

  // Group view

  TheGraph.Group = React.createFactory( React.createClass({
    displayName: "TheGraphGroup",
    getInitialState: function () {
        return {
            moving: false,
        };
    },
    componentDidMount: function () {

      // Move group
      var dragNode = ReactDOM.findDOMNode(this.refs.events);
      dragNode.addEventListener('panstart', this.onTrackStart);

      // Context menu
      var domNode = ReactDOM.findDOMNode(this);
      if (this.props.showContext) {
        domNode.addEventListener("contextmenu", this.showContext);
        domNode.addEventListener("press", this.showContext);
      }

    },
    showContext: function (event) {
      // Don't show native context menu
      event.preventDefault();

      // Don't tap graph on hold event
      if (event.stopPropagation) { event.stopPropagation(); }
      if (event.preventTap) { event.preventTap(); }

      // Get mouse position
      if (event.gesture) {
        event = event.gesture.srcEvent; // unpack hammer.js gesture event
      }
      var x = event.x || event.clientX || 0;
      var y = event.y || event.clientY || 0;

      // App.showContext
      this.props.showContext({
        element: this,
        type: (this.props.isSelectionGroup ? "selection" : "group"),
        x: x,
        y: y,
        graph: this.props.graph,
        itemKey: this.props.label,
        item: this.props.item
      });
    },
    getContext: function (menu, options, hide) {
      return TheGraph.Menu({
        menu: menu,
        options: options,
        label: this.props.label,
        triggerHideContext: hide
      });
    },
    onTrackStart: function (event) {
      // Don't pan graph
      event.stopPropagation();
      this.setState({ moving: true });

      var dragNode = ReactDOM.findDOMNode(this.refs.events);
      dragNode.addEventListener("panmove", this.onTrack);
      dragNode.addEventListener("panend", this.onTrackEnd);

      this.props.graph.startTransaction('movegroup');
    },
    onTrack: function (event) {
      // Don't pan graph
      event.stopPropagation();

      var deltaX = Math.round( event.gesture.srcEvent.movementX / this.props.scale );
      var deltaY = Math.round( event.gesture.srcEvent.movementY / this.props.scale );

      this.props.triggerMoveGroup(this.props.item.nodes, deltaX, deltaY);
    },
    onTrackEnd: function (event) {
      this.setState({ moving: false });
      // Don't pan graph
      event.stopPropagation();

      // Snap to grid
      this.props.triggerMoveGroup(this.props.item.nodes);

      var dragNode = ReactDOM.findDOMNode(this.refs.events);
      dragNode.addEventListener("panmove", this.onTrack);
      dragNode.addEventListener("panend", this.onTrackEnd);

      this.props.graph.endTransaction('movegroup');
    },
    render: function() {
      var x = this.props.minX - TheGraph.config.nodeWidth / 2;
      var y = this.props.minY - TheGraph.config.nodeHeight / 2;
      var color = (this.props.color ? this.props.color : 0);
      var selection = (this.props.isSelectionGroup ? ' selection drag' : '');

      var boxRectOptions = {
        x: x,
        y: y,
        width: this.props.maxX - x + TheGraph.config.nodeWidth*0.5,
        height: this.props.maxY - y + TheGraph.config.nodeHeight*0.75,
        className: "group-box color"+color + selection,
      };
      boxRectOptions = TheGraph.merge(TheGraph.config.group.boxRect, boxRectOptions);
      var boxRect =  TheGraph.factories.group.createGroupBoxRect.call(this, boxRectOptions);

      var labelTextOptions = {
        x: x + TheGraph.config.nodeRadius,
        y: y + 9,
        children: this.props.label,
      };
      labelTextOptions = TheGraph.merge(TheGraph.config.group.labelText, labelTextOptions);
      var labelText = TheGraph.factories.group.createGroupLabelText.call(this, labelTextOptions);

      var descriptionTextOptions = {
        x: x + TheGraph.config.nodeRadius,
        y: y + 24,
        children: this.props.description
      };
      descriptionTextOptions = TheGraph.merge(TheGraph.config.group.descriptionText, descriptionTextOptions);
      var descriptionText = TheGraph.factories.group.createGroupDescriptionText.call(this, descriptionTextOptions);

      // When moving, expand bounding box of element
      // to catch events when pointer moves faster than we can move the element
      var eventOptions = {
        className: 'eventcatcher drag',
        ref: 'events',
      };
      if (this.props.isSelectionGroup) {
        eventOptions.x = boxRectOptions.x;
        eventOptions.y = boxRectOptions.y;
        eventOptions.width = boxRectOptions.width;
        eventOptions.height = boxRectOptions.height;
      } else {
        eventOptions.x = boxRectOptions.x;
        eventOptions.y = boxRectOptions.y;
        eventOptions.width = 24 * this.props.label.length * 0.75;
        eventOptions.height = 24 * 2;
      }
      if (this.state.moving) {
        var extend = 1000;
        eventOptions.width += extend*2;
        eventOptions.height += extend*2;
        eventOptions.x -= extend;
        eventOptions.y -= extend;
      }
      var eventCatcher = TheGraph.factories.createRect(eventOptions);

      var groupContents = [
        boxRect,
        labelText,
        descriptionText,
        eventCatcher,
      ];

      var containerOptions = TheGraph.merge(TheGraph.config.group.container, {});
      return TheGraph.factories.group.createGroupGroup.call(this, containerOptions, groupContents);

    }
  }));

};
<|endoftext|>


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

var fs = require( "fs" );
var path = require( "path" );
var uuid = require( "uuid" );
var configurationDirectory = require( "../../lib/configurationDirectory" );
var produceClientContent = require( "./produceClientContent" );
var produceServerContent = require( "./produceServerContent" );
var spawnSync = require( "child_process" ).spawnSync;
var assignin = require( "lodash.assignin" );

function produceDataItem( fileName ) {
	return {
		fileName: fileName,
		deviceUuid: uuid.v4(),
		configPath: configurationDirectory( fileName )
	};
}

function clientCred( item, index ) {
	return {
		credid: index + 1,
		subjectuuid: item.deviceUuid,
		credtype: 1,
		privatedata: {
			data: "AAAAAAAAAAAAAAAA",
			encoding: "oic.sec.encoding.raw"
		}
	};
}

function serverCred( item, index ) {
	return assignin( clientCred( item, index ), {
		period: "20150630T060000/20990920T220000"
	} );
}

module.exports = function provision( options ) {
	var index;

	// Establish paths for json2cbor and its libraries.
	var toolPath = path.join( options.location, "iotivity-installed", "bin" );
	var libPath = path.join( options.location, "iotivity-installed", "lib" );

	// Generate device UUIDs and configuration paths.
	var clientData = options.clientPaths.map( produceDataItem );
	var serverData = options.serverPaths.map( produceDataItem );

	// Cross-link server and client credentials. This means any client can access any resource on
	// any server.
	for ( index in clientData ) {
		clientData[ index ].fileContents =
			produceClientContent( clientData[ index ], serverData.map( clientCred ) );
	}
	for ( index in serverData ) {
		serverData[ index ].fileContents =
			produceServerContent( serverData[ index ], clientData.map( serverCred ), options.uuid );
	}

	// Write out the .json and .dat files
	clientData.concat( serverData ).map( function( item ) {

		// The .json file is not used but it's good to have it side-by-side with the .dat file.
		fs.writeFileSync( path.join( item.configPath, "oic_svr_db.json" ),
			JSON.stringify( item.fileContents, null, "\t" ) );

		// json2cbor creates the .dat file. We let node search the PATH, after having added the
		// iotivity-node path where we know json2cbor should be. So, if it's installed globally
		// then node will find it there (like, /usr/bin or something like that), otherwise it will
		// find it in the iotivity-node/iotivity-installed/bin directory.
		var toolResult = spawnSync( "json2cbor", [
			path.join( item.configPath, "oic_svr_db.json" ),
			path.join( item.configPath, "oic_svr_db.dat" ) ], {
				env: assignin( {}, process.env, {
					PATH: ( process.env.PATH || "" )
						.split( path.delimiter )
						.concat( [ toolPath ] )
						.join( path.delimiter ),
					LD_LIBRARY_PATH: libPath,
					stdio: [ process.stdin, process.stdout, process.stderr ]
				} )
			} );

		if ( toolResult.status !== 0 ) {
			console.log( JSON.stringify( { info: true, message:
				"Warning: Failed to run json2cbor: " + toolResult.stderr
			} ) );
		}

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

var fs = require( "fs" );
var path = require( "path" );
var uuid = require( "uuid" );
var configurationDirectory = require( "../../lib/configurationDirectory" );
var produceClientContent = require( "./produceClientContent" );
var produceServerContent = require( "./produceServerContent" );
var spawnSync = require( "child_process" ).spawnSync;
var assignin = require( "lodash.assignin" );

function produceDataItem( fileName ) {
	return {
		fileName: fileName,
		deviceUuid: uuid.v4(),
		configPath: configurationDirectory( fileName )
	};
}

function clientCred( item, index ) {
	return {
		credid: index + 1,
		subjectuuid: item.deviceUuid,
		credtype: 1,
		privatedata: {
			data: "AAAAAAAAAAAAAAAA",
			encoding: "oic.sec.encoding.raw"
		}
	};
}

function serverCred( item, index ) {
	return assignin( clientCred( item, index ), {
		period: "20150630T060000/20990920T220000"
	} );
}

// Create provisioning information for a set of clients and a set of servers such
// that any of the clients may connect to any of the servers.
// options:
//   location: string - absolute path to iotivity-node package root
//   clientPaths: array of strings - absolute paths of clients
//   serverPaths: array of strings - absolute paths of servers
//   uuid: - string - UUID that will be used for the recognition resource
//         - array of objects - entries to add to the ACL of all servers
module.exports = function provision( options ) {
	var index;

	// Establish paths for json2cbor and its libraries.
	var toolPath = path.join( options.location, "iotivity-installed", "bin" );
	var libPath = path.join( options.location, "iotivity-installed", "lib" );

	// Generate device UUIDs and configuration paths.
	var clientData = options.clientPaths.map( produceDataItem );
	var serverData = options.serverPaths.map( produceDataItem );

	// Cross-link server and client credentials. This means any client can access any resource on
	// any server.
	for ( index in clientData ) {
		clientData[ index ].fileContents =
			produceClientContent( clientData[ index ], serverData.map( clientCred ) );
	}
	for ( index in serverData ) {
		serverData[ index ].fileContents =
			produceServerContent( serverData[ index ], clientData.map( serverCred ), options.uuid );
	}

	// Write out the .json and .dat files
	clientData.concat( serverData ).map( function( item ) {

		// The .json file is not used but it's good to have it side-by-side with the .dat file.
		fs.writeFileSync( path.join( item.configPath, "oic_svr_db.json" ),
			JSON.stringify( item.fileContents, null, "\t" ) );

		// json2cbor creates the .dat file. We let node search the PATH, after having added the
		// iotivity-node path where we know json2cbor should be. So, if it's installed globally
		// then node will find it there (like, /usr/bin or something like that), otherwise it will
		// find it in the iotivity-node/iotivity-installed/bin directory.
		var toolResult = spawnSync( "json2cbor", [
			path.join( item.configPath, "oic_svr_db.json" ),
			path.join( item.configPath, "oic_svr_db.dat" ) ], {
				env: assignin( {}, process.env, {
					PATH: ( process.env.PATH || "" )
						.split( path.delimiter )
						.concat( [ toolPath ] )
						.join( path.delimiter ),
					LD_LIBRARY_PATH: libPath,
					stdio: [ process.stdin, process.stdout, process.stderr ]
				} )
			} );

		if ( toolResult.status !== 0 ) {
			console.log( JSON.stringify( { info: true, message:
				"Warning: Failed to run json2cbor: " + toolResult.stderr
			} ) );
		}

	} );
};
<|endoftext|>


<commit_before>import FilterModule from "../FilterModule";
import { singleton as Singleton } from "needlepoint";

@Singleton
export default class TrimmingFilter extends FilterModule {
    filter(msg) {
        msg.body = msg.body.trim();

        return msg;
    }
}<commit_msg>Fix TrimmingFilter breaking for messages with no body<commit_after>import FilterModule from "../FilterModule";
import { singleton as Singleton } from "needlepoint";

@Singleton
export default class TrimmingFilter extends FilterModule {
    filter(msg) {
        if (msg.body) {
            msg.body = msg.body.trim();
        }

        return msg;
    }
}<|endoftext|>


<commit_before>var orm = require('../../../dbbs');
orm.setup();
var Subscriber = orm.model("subscriber");
var assert = require('assert');
var adapter = require('../adapter');

var testEmail ='ash.1382@gmail.com';
var subscriber;
describe('===> Testing insertSubscriber adapter function:\n',function() {
  it('User registered successfully',function(done) {
    adapter.insertSubscriber(testEmail,'My Password',function (result) {
      assert(result.value,"User not registered successfully")
      subscriber = result.value;
      done();
    });
  });
  it('Email in Use',function(done) {
    adapter.insertSubscriber(testEmail,'My Password',function (result) {
      assert.equal(result.error.type,"emailInUse")
      done();
    });
  });
});

describe('===> Testing fetchSubscriber adapter function:\n',function() {
  it('User fetched successfully',function(done) {
    adapter.fetchSubscriber({email:testEmail},function (result) {
      assert(result.value,"Unable to fetch user")
      done();
    });
  });
  it('Subscriber not found',function(done) {
    adapter.fetchSubscriber({email:"SOmething@gmail.com"},function (result) {
      assert.equal(result.error.type,"subscriberNotFound")
      done();
    });
  });
});

describe('===> Testing verifySubscriber adapter function:\n',function() {
  it('User verified successfully',function(done) {
    adapter.verifySubscriber(subscriber,function (result) {
      assert(result.value,"Unable to verify user")
      done();
    });
  });
  it('Subscriber Already verified',function(done) {
    adapter.verifySubscriber(subscriber,function (result) {
      assert.equal(result.error.type,"subscriberAlreadyVerified")
      done();
    });
  });
});

describe('===> Testing sendVerificationEmail adapter function:\n',function() {
  it('Verification Email sent successfully',function(done) {
    adapter.sendVerificationEmail(subscriber,function (result) {
      assert(result.value,"Unable to verify user")
      done();
    });
  });
});
/*
describe('===> Testing comparePassword adapter function:\n',function() {
  it('Passwords Matched successfully ',function(done) {
    adapter.comparePassword(subscriber,function (result) {
      assert(result.value,"Passwords mismatch")
      done();
    });
  });
});
*/
<commit_msg>Adding more tests<commit_after>var orm = require('../../../dbbs');
orm.setup();
var Subscriber = orm.model("subscriber");
var assert = require('assert');
var adapter = require('../adapter');

var testEmail ='ash.1382@gmail.com';
var subscriber;
describe('===> Testing insertSubscriber adapter function:\n',function() {
  it('User registered successfully',function(done) {
    adapter.insertSubscriber(testEmail,'My Password',function (result) {
      assert(result.value,"User not registered successfully")
      subscriber = result.value;
      done();
    });
  });
  it('Email in Use',function(done) {
    adapter.insertSubscriber(testEmail,'My Password',function (result) {
      assert.equal(result.error.type,"emailInUse")
      done();
    });
  });
});

describe('===> Testing fetchSubscriber adapter function:\n',function() {
  it('User fetched successfully',function(done) {
    adapter.fetchSubscriber({email:testEmail},function (result) {
      assert(result.value,"Unable to fetch user")
      done();
    });
  });
  it('Subscriber not found',function(done) {
    adapter.fetchSubscriber({email:"SOmething@gmail.com"},function (result) {
      assert.equal(result.error.type,"subscriberNotFound")
      done();
    });
  });
});

describe('===> Testing verifySubscriber adapter function:\n',function() {
  it('User verified successfully',function(done) {
    adapter.verifySubscriber(subscriber,function (result) {
      assert(result.value,"Unable to verify user")
      done();
    });
  });
  it('Subscriber Already verified',function(done) {
    adapter.verifySubscriber(subscriber,function (result) {
      assert.equal(result.error.type,"subscriberAlreadyVerified")
      done();
    });
  });
});

describe('===> Testing sendVerificationEmail adapter function:\n',function() {
  it('Verification Email sent successfully',function(done) {
    adapter.sendVerificationEmail(subscriber,function (result) {
      assert(result.value,"Unable to verify user")
      done();
    });
  });
});

describe('===> Testing generateAuthToken adapter function:\n',function() {
  it('AuthToken generated successfully',function(done) {
    adapter.generateAuthToken(subscriber,function (result) {
      assert(result.value,"Unable to generate authToken")
      done();
    });
  });
});

describe('===> Testing authenticateSubscriber adapter function:\n',function() {
  it('Subscriber authenticated successfully',function(done) {
    adapter.authenticateSubscriber('My Password',subscriber,function (result) {
      assert(result.value,"Unable to authenticate subscriber")
      done();
    });
  });
  it('Incorrect Password',function(done) {
    adapter.authenticateSubscriber('NOt Password',subscriber,function (result) {
      assert.equal(result.error.type,"incorrectPwd")
      done();
    });
  });
});

<|endoftext|>