<commit_before>/*!
 * dir-info
 * 2015 Codenautas
 * GNU Licensed
 */

/**
 * Module dependencies.
 */

var Promise = require('promise');
var Path = require('path');
var fs = require('fs-promise');
var exec = require('child-process-promise').exec;

var dirInfo = {}; // this module

dirInfo.summaryTexts = {
    is:{
        github:'h',
        git:'g',
        svn:'s',
        multilang:'m',
        "package.json":'p',
        json:'j',
        other:''
    },
    status:{
        error:'E', // for json & package.json
        changed:'C',
        unstaged:'U',
        ignored:'i',
        outdated:'O', // only for multilang
        ok:''
    },
    server:{
        outdated:'O',
        ok:''
    }
};

dirInfo.config = { gitDir:false };

/*
    This function will search for the directory containing the git executable
    in this order:
    - dirInfo.config.gitDir
    - config.gitDir in packaje.json
    - GITDIR environment variable
    - A set of predefinded paths
*/
dirInfo.findGitDir = function findGitDir() {
    var paths;
    return Promise.resolve().then(function() {
        paths=[
            'c:\\Git\\bin',
            'c:\\Archivos de programa\\Git\\bin',
            'c:\\Program Files\\Git\\bin',
            'c:\\Program Files (x86)\\Git\\bin',
            '/usr/bin',
            '/usr/local/bin',
            '/bin'
        ];
        if(dirInfo.config.gitDir) {
            paths.unshift(dirInfo.config.gitDir);
        }
        return fs.readJson('./package.json');
    }).then(function(json){
        if(json.config && json.config.gitDir) {
            paths.unshift(json.config.gitDir);
        }
        if(process.env.GITDIR) {
            paths.unshift(process.env.GITDIR);
        }
        //console.log("paths", paths);
        return paths.reduce(function(promiseChain, path){
            return promiseChain.catch(function(){
                return fs.stat(path).then(function(stat){
                    if(stat.isDirectory()){
                        return path;
                    }else{
                        return Promise.reject('not dir');
                    }
                });
            });
        },Promise.reject());
    });
};

dirInfo.getInfo = function getInfo(path, opts){
    opts = opts || {};
    var info={
        name:Path.basename(path), // BAD! only the last dirname
        is:'other',
        status:null,
        server:null,
        origin:null
    };
    var gitDir='';
    var execOptions = {};
    return Promise.resolve(path).then(function(path){
        if(!path) { throw new Error('null path'); }
        return fs.exists(path);
    }).then(function(exists) {
        if(!exists) { throw new Error("'"+path+"' does not exists"); }
        return fs.stat(path);
    }).then(function(stat) {
        if(false == stat.isDirectory()) { throw new Error("'"+path+"' is not a directory"); }
        gitDir = path+Path.sep+".git";
        return fs.stat(gitDir);
    }).then(function(stat) {
        if(false == stat.isDirectory()) {
            return Promise.resolve(info);
        }
    }).then(function() {
        return dirInfo.findGitDir();
    }).then(function(gitDir) {
        if(""===gitDir) {
            console.log("sin .git in '"+path+"'");
            throw new Error("Could not find git");
        }
        execOptions.cwd = path;
        execOptions.env = {PATH: gitDir};
        return exec('git status', execOptions);
    }).then(function(res) {
        info.is = 'git';
        var isUntracked=res.stdout.match(/untracked files:/i);
        var isChanged=res.stdout.match(/modified:/i);
        if(opts.net) {
            //info.server = '';
            if(isChanged) { info.status = 'changed'; }
            if(isUntracked) { info.server = 'outdated'; }
        }
        if(opts.cmd) {
            info.status = 'ok';
            if(isChanged) { info.status = 'changed'; }
            else if(isUntracked) { info.status = 'unstaged'; }
        }
        if(opts.cmd || opts.net) {
            return exec('git config --get remote.origin.url', execOptions);
        }
        return Promise.resolve(info);
    }).catch(function (err) {
        // is not github, continuing
    }).then(function(res) {
        if(res.stdout.match(/github/)) { info.is = 'github'; }
    }).catch(function (err) {
        if(info.is==='other') { info.status = 'ok'; }
        // last git command returns 1 if remote.origin.url is not defined, but that is not an error!
    }).then(function() {
        return Promise.resolve(info);
    });
};

exports = module.exports = dirInfo;<commit_msg>removed console.log()<commit_after>/*!
 * dir-info
 * 2015 Codenautas
 * GNU Licensed
 */

/**
 * Module dependencies.
 */

var Promise = require('promise');
var Path = require('path');
var fs = require('fs-promise');
var exec = require('child-process-promise').exec;

var dirInfo = {}; // this module

dirInfo.summaryTexts = {
    is:{
        github:'h',
        git:'g',
        svn:'s',
        multilang:'m',
        "package.json":'p',
        json:'j',
        other:''
    },
    status:{
        error:'E', // for json & package.json
        changed:'C',
        unstaged:'U',
        ignored:'i',
        outdated:'O', // only for multilang
        ok:''
    },
    server:{
        outdated:'O',
        ok:''
    }
};

dirInfo.config = { gitDir:false };

/*
    This function will search for the directory containing the git executable
    in this order:
    - dirInfo.config.gitDir
    - config.gitDir in packaje.json
    - GITDIR environment variable
    - A set of predefinded paths
*/
dirInfo.findGitDir = function findGitDir() {
    var paths;
    return Promise.resolve().then(function() {
        paths=[
            'c:\\Git\\bin',
            'c:\\Archivos de programa\\Git\\bin',
            'c:\\Program Files\\Git\\bin',
            'c:\\Program Files (x86)\\Git\\bin',
            '/usr/bin',
            '/usr/local/bin',
            '/bin'
        ];
        if(dirInfo.config.gitDir) {
            paths.unshift(dirInfo.config.gitDir);
        }
        return fs.readJson('./package.json');
    }).then(function(json){
        if(json.config && json.config.gitDir) {
            paths.unshift(json.config.gitDir);
        }
        if(process.env.GITDIR) {
            paths.unshift(process.env.GITDIR);
        }
        return paths.reduce(function(promiseChain, path){
            return promiseChain.catch(function(){
                return fs.stat(path).then(function(stat){
                    if(stat.isDirectory()){
                        return path;
                    }else{
                        return Promise.reject('not dir');
                    }
                });
            });
        },Promise.reject());
    });
};

dirInfo.getInfo = function getInfo(path, opts){
    opts = opts || {};
    var info={
        name:Path.basename(path), // BAD! only the last dirname
        is:'other',
        status:null,
        server:null,
        origin:null
    };
    var gitDir='';
    var execOptions = {};
    return Promise.resolve(path).then(function(path){
        if(!path) { throw new Error('null path'); }
        return fs.exists(path);
    }).then(function(exists) {
        if(!exists) { throw new Error("'"+path+"' does not exists"); }
        return fs.stat(path);
    }).then(function(stat) {
        if(false == stat.isDirectory()) { throw new Error("'"+path+"' is not a directory"); }
        gitDir = path+Path.sep+".git";
        return fs.stat(gitDir);
    }).then(function(stat) {
        if(false == stat.isDirectory()) {
            return Promise.resolve(info);
        }
    }).then(function() {
        return dirInfo.findGitDir();
    }).then(function(gitDir) {
        if(""===gitDir) { throw new Error("Could not find git"); }
        execOptions.cwd = path;
        execOptions.env = {PATH: gitDir};
        return exec('git status', execOptions);
    }).then(function(res) {
        info.is = 'git';
        var isUntracked=res.stdout.match(/untracked files:/i);
        var isChanged=res.stdout.match(/modified:/i);
        if(opts.net) {
            //info.server = '';
            if(isChanged) { info.status = 'changed'; }
            if(isUntracked) { info.server = 'outdated'; }
        }
        if(opts.cmd) {
            info.status = 'ok';
            if(isChanged) { info.status = 'changed'; }
            else if(isUntracked) { info.status = 'unstaged'; }
        }
        if(opts.cmd || opts.net) {
            return exec('git config --get remote.origin.url', execOptions);
        }
        return Promise.resolve(info);
    }).catch(function (err) {
        // is not github, continuing
    }).then(function(res) {
        if(res.stdout.match(/github/)) { info.is = 'github'; }
    }).catch(function (err) {
        if(info.is==='other') { info.status = 'ok'; }
        // last git command returns 1 if remote.origin.url is not defined, but that is not an error!
    }).then(function() {
        return Promise.resolve(info);
    });
};

exports = module.exports = dirInfo;<|endoftext|>


<commit_before>Elm.Native.Task = {};
Elm.Native.Task.make = function(localRuntime) {

	localRuntime.Native = localRuntime.Native || {};
	localRuntime.Native.Task = localRuntime.Native.Task || {};
	if (localRuntime.Native.Task.values)
	{
		return localRuntime.Native.Task.values;
	}

	var Result = Elm.Result.make(localRuntime);
	var Signal = Elm.Native.Signal.make(localRuntime);
	var Utils = Elm.Native.Utils.make(localRuntime);

	// CONSTRUCTORS

	function succeed(value)
	{
		return {
			tag: 'Succeed',
			value: value
		};
	}

	function fail(error)
	{
		return {
			tag: 'Fail',
			value: error
		};
	}

	function asyncFunction(func)
	{
		return {
			tag: 'Async',
			asyncFunction: func
		};
	}

	function andThen(task, callback)
	{
		return {
			tag: 'AndThen',
			task: task,
			callback: callback
		};
	}

	function catch_(task, callback)
	{
		return {
			tag: 'Catch',
			task: task,
			callback: callback
		};
	}

	// RUNNER

	function perform(task) {
		runTask({ task: task }, function() {});
	}

	function performSignal(name, signal)
	{
		var workQueue = [];

		function onComplete()
		{
			workQueue.shift();

			setTimeout(function() {
				if (workQueue.length > 0)
				{
					runTask(workQueue[0], onComplete);
				}
			}, 0);
		}

		function register(task)
		{
			var root = { task: task };
			workQueue.push(root);
			if (workQueue.length === 1)
			{
				runTask(root, onComplete);
			}
		}

		Signal.output('perform-tasks-' + name, register, stream);

		return succeed(Utils.Tuple0);
	}

	function mark(status, task)
	{
		return { status: status, task: task };
	}

	function runTask(root, onComplete)
	{
		var result = mark('runnable', root.task);
		while (result.status === 'runnable')
		{
			result = stepTask(onComplete, root, result.task);
		}

		if (result.status === 'done')
		{
			root.task = result.task;
			onComplete();
		}

		if (result.status === 'blocked')
		{
			root.task = result.task;
		}
	}

	function stepTask(onComplete, root, task)
	{
		var tag = task.tag;

		if (tag === 'Succeed' || tag === 'Fail')
		{
			return mark('done', task);
		}

		if (tag === 'Async')
		{
			var placeHolder = {};
			var couldBeSync = true;
			var wasSync = false;

			task.asyncFunction(function(result) {
				placeHolder.tag = result.tag;
				placeHolder.value = result.value;
				if (couldBeSync)
				{
					wasSync = true;
				}
				else
				{
					runTask(root, onComplete);
				}
			});
			couldBeSync = false;
			return mark(wasSync ? 'done' : 'blocked', placeHolder);
		}

		if (tag === 'AndThen' || tag === 'Catch')
		{
			var result = mark('runnable', task.task);
			while (result.status === 'runnable')
			{
				result = stepTask(onComplete, root, result.task);
			}

			if (result.status === 'done')
			{
				var activeTask = result.task;
				var activeTag = activeTask.tag;

				var succeedChain = activeTag === 'Succeed' && tag === 'AndThen';
				var failChain = activeTag === 'Fail' && tag === 'Catch';

				return (succeedChain || failChain)
					? mark('runnable', task.callback(activeTask.value))
					: mark('runnable', activeTask);
			}
			if (result.status === 'blocked')
			{
				return mark('blocked', {
					tag: tag,
					task: result.task,
					callback: task.callback
				});
			}
		}
	}

	// THREADS

	function sleep(time) {
		return asyncFunction(function(callback) {
			setTimeout(function() {
				callback(succeed(Utils.Tuple0));
			}, time);
		});
	}

	function spawn(task) {
		return asyncFunction(function(callback) {
			var id = setTimeout(function() {
				perform(task);
			}, 0);
			callback(succeed(id));
		});
	}

	return localRuntime.Native.Task.values = {
		succeed: succeed,
		fail: fail,
		asyncFunction: asyncFunction,
		andThen: F2(andThen),
		catch_: F2(catch_),
		perform: perform,
		performSignal: performSignal,
		spawn: spawn,
		sleep: sleep
	};
};
<commit_msg>Load Signal module lazily<commit_after>Elm.Native.Task = {};
Elm.Native.Task.make = function(localRuntime) {

	localRuntime.Native = localRuntime.Native || {};
	localRuntime.Native.Task = localRuntime.Native.Task || {};
	if (localRuntime.Native.Task.values)
	{
		return localRuntime.Native.Task.values;
	}

	var Result = Elm.Result.make(localRuntime);
	var Signal;
	var Utils = Elm.Native.Utils.make(localRuntime);

	// CONSTRUCTORS

	function succeed(value)
	{
		return {
			tag: 'Succeed',
			value: value
		};
	}

	function fail(error)
	{
		return {
			tag: 'Fail',
			value: error
		};
	}

	function asyncFunction(func)
	{
		return {
			tag: 'Async',
			asyncFunction: func
		};
	}

	function andThen(task, callback)
	{
		return {
			tag: 'AndThen',
			task: task,
			callback: callback
		};
	}

	function catch_(task, callback)
	{
		return {
			tag: 'Catch',
			task: task,
			callback: callback
		};
	}

	// RUNNER

	function perform(task) {
		runTask({ task: task }, function() {});
	}

	function performSignal(name, signal)
	{
		var workQueue = [];

		function onComplete()
		{
			workQueue.shift();

			setTimeout(function() {
				if (workQueue.length > 0)
				{
					runTask(workQueue[0], onComplete);
				}
			}, 0);
		}

		function register(task)
		{
			var root = { task: task };
			workQueue.push(root);
			if (workQueue.length === 1)
			{
				runTask(root, onComplete);
			}
		}

		if (!Signal)
		{
			Signal = Elm.Native.Signal.make(localRuntime);
		}
		Signal.output('perform-tasks-' + name, register, stream);

		return signal;
	}

	function mark(status, task)
	{
		return { status: status, task: task };
	}

	function runTask(root, onComplete)
	{
		var result = mark('runnable', root.task);
		while (result.status === 'runnable')
		{
			result = stepTask(onComplete, root, result.task);
		}

		if (result.status === 'done')
		{
			root.task = result.task;
			onComplete();
		}

		if (result.status === 'blocked')
		{
			root.task = result.task;
		}
	}

	function stepTask(onComplete, root, task)
	{
		var tag = task.tag;

		if (tag === 'Succeed' || tag === 'Fail')
		{
			return mark('done', task);
		}

		if (tag === 'Async')
		{
			var placeHolder = {};
			var couldBeSync = true;
			var wasSync = false;

			task.asyncFunction(function(result) {
				placeHolder.tag = result.tag;
				placeHolder.value = result.value;
				if (couldBeSync)
				{
					wasSync = true;
				}
				else
				{
					runTask(root, onComplete);
				}
			});
			couldBeSync = false;
			return mark(wasSync ? 'done' : 'blocked', placeHolder);
		}

		if (tag === 'AndThen' || tag === 'Catch')
		{
			var result = mark('runnable', task.task);
			while (result.status === 'runnable')
			{
				result = stepTask(onComplete, root, result.task);
			}

			if (result.status === 'done')
			{
				var activeTask = result.task;
				var activeTag = activeTask.tag;

				var succeedChain = activeTag === 'Succeed' && tag === 'AndThen';
				var failChain = activeTag === 'Fail' && tag === 'Catch';

				return (succeedChain || failChain)
					? mark('runnable', task.callback(activeTask.value))
					: mark('runnable', activeTask);
			}
			if (result.status === 'blocked')
			{
				return mark('blocked', {
					tag: tag,
					task: result.task,
					callback: task.callback
				});
			}
		}
	}

	// THREADS

	function sleep(time) {
		return asyncFunction(function(callback) {
			setTimeout(function() {
				callback(succeed(Utils.Tuple0));
			}, time);
		});
	}

	function spawn(task) {
		return asyncFunction(function(callback) {
			var id = setTimeout(function() {
				perform(task);
			}, 0);
			callback(succeed(id));
		});
	}

	return localRuntime.Native.Task.values = {
		succeed: succeed,
		fail: fail,
		asyncFunction: asyncFunction,
		andThen: F2(andThen),
		catch_: F2(catch_),
		perform: perform,
		performSignal: performSignal,
		spawn: spawn,
		sleep: sleep
	};
};
<|endoftext|>


<commit_before>'use strict';

/* Directives */

angular.module('swiftBrowser.directives', []).
    directive('sbVersion', ['version', function(version) {
        return function(scope, elm, attrs) {
            elm.text(version);
        };
    }]).
    directive('sbFormatBytes', ['bytesFilter', function(bytesFilter) {
        return {
            restrict: 'AE',
            scope: {
                count: '=',
            },
            link: function (scope, element, attrs) {
                var formatted = bytesFilter(scope.count);
                var parts = formatted.split(' ');

                element.text(parts[0] + ' ');
                element.append($('').addClass('unit').text(parts[1]));
            },
        };
    }]);
<commit_msg>Simplify sbFormatBytes by using template over jQuery<commit_after>'use strict';

/* Directives */

angular.module('swiftBrowser.directives', []).
    directive('sbVersion', ['version', function(version) {
        return function(scope, elm, attrs) {
            elm.text(version);
        };
    }]).
    directive('sbFormatBytes', ['bytesFilter', function(bytesFilter) {
        return {
            restrict: 'AE',
            scope: {
                count: '=',
            },
            link: function (scope, element, attrs) {
                var formatted = bytesFilter(scope.count);
                var parts = formatted.split(' ');
                scope.number = parts[0];
                scope.unit = parts[1];
            },
            template: '{{number}} {{unit}}',
        };
    }]);
<|endoftext|>


<commit_before>// import path from 'path';
// import {isCI} from '../lib/ci';

module.exports = {
// 	// - - - - CHIMP - - - -
// 	watch: false,
// 	watchTags: '@watch,@focus',
// 	domainSteps: null,
// 	e2eSteps: null,
// 	fullDomain: false,
// 	domainOnly: false,
// 	e2eTags: '@e2e',
// 	watchWithPolling: false,
// 	server: false,
// 	serverPort: 8060,
// 	serverHost: 'localhost',
// 	sync: true,
// 	offline: false,
// 	showXolvioMessages: true,

// 	// - - - - CUCUMBER - - - -
	path: 'tests/end-to-end/ui',
	// 	format: 'pretty',
	// 	tags: '~@ignore',
	// 	singleSnippetPerFile: true,
	// 	recommendedFilenameSeparator: '_',
	// 	chai: false,
	screenshotsOnError: true,
	screenshotsPath: '.screenshots',
	captureAllStepScreenshots: false,
	saveScreenshotsToDisk: true,
	// 	// Note: With a large viewport size and captureAllStepScreenshots enabled,
	// 	// you may run out of memory. Use browser.setViewportSize to make the
	// 	// viewport size smaller.
	// 	saveScreenshotsToReport: false,
	// 	jsonOutput: null,
	// 	compiler: 'js:' + path.resolve(__dirname, '../lib/babel-register.js'),
	// 	conditionOutput: true,

	// 	// - - - - SELENIUM  - - - -
	// 	browser: null,
	// 	platform: 'ANY',
	// 	name: '',
	// 	user: '',
	// 	key: '',
	// 	port: null,
	// 	host: null,
	// 	// deviceName: null,

	// 	// - - - - WEBDRIVER-IO  - - - -
	// 	webdriverio: {
	// 		desiredCapabilities: {},
	// 		logLevel: 'silent',
	// 		// logOutput: null,
	// 		host: '127.0.0.1',
	// 		port: 4444,
	// 		path: '/wd/hub',
	// 		baseUrl: null,
	// 		coloredLogs: true,
	// 		screenshotPath: null,
	// 		waitforTimeout: 500,
	// 		waitforInterval: 250,
	// 	},

	// 	// - - - - SELENIUM-STANDALONE
	// 	seleniumStandaloneOptions: {
	// 		// check for more recent versions of selenium here:
	// 		// http://selenium-release.storage.googleapis.com/index.html
	// 		version: '2.53.1',
	// 		baseURL: 'https://selenium-release.storage.googleapis.com',
	// 		drivers: {
	// 			chrome: {
	// 				// check for more recent versions of chrome driver here:
	// 				// http://chromedriver.storage.googleapis.com/index.html
	// 				version: '2.25',
	// 				arch: process.arch,
	// 				baseURL: 'https://chromedriver.storage.googleapis.com'
	// 			},
	// 			ie: {
	// 				// check for more recent versions of internet explorer driver here:
	// 				// http://selenium-release.storage.googleapis.com/index.html
	// 				version: '2.50.0',
	// 				arch: 'ia32',
	// 				baseURL: 'https://selenium-release.storage.googleapis.com'
	// 			},
	// 			firefox: {
	// 				// check for more recent versions of gecko  driver here:
	// 				// https://github.com/mozilla/geckodriver/releases
	// 				version: '0.11.1',
	// 				arch: process.arch,
	// 				baseURL: 'https://github.com/mozilla/geckodriver/releases/download'
	// 			}
	// 		}
	// 	},

	// 	// - - - - SESSION-MANAGER  - - - -
	// 	noSessionReuse: false,

	// 	// - - - - SIMIAN  - - - -
	// 	simianResultEndPoint: 'api.simian.io/v1.0/result',
	// 	simianAccessToken: false,
	// 	simianResultBranch: null,
	// 	simianRepositoryId: null,

	// 	// - - - - MOCHA  - - - -
	mocha: true,
	mochaCommandLineOptions: ['--color'],
	mochaConfig: {
		// tags and grep only work when watch mode is false
		tags: '',
		grep: null,
		timeout: 40000,
		reporter: 'spec',
		slow: 100,
		//retries: 3,
		bail: true // bail after first test failure
	},

	// 	// - - - - JASMINE  - - - -
	// 	jasmine: false,
	// 	jasmineConfig: {
	// 		specDir: '.',
	// 		specFiles: [
	// 			'**/*@(_spec|-spec|Spec).@(js|jsx)',
	// 		],
	// 		helpers: [
	// 			'support/**/*.@(js|jsx)',
	// 		],
	// 		stopSpecOnExpectationFailure: false,
	// 		random: false,
	// 	},
	// 	jasmineReporterConfig: {
	// 		// This options are passed to jasmine.configureDefaultReporter(...)
	// 		// See: http://jasmine.github.io/2.4/node.html#section-Reporters
	// 	},

	// 	// - - - - METEOR  - - - -
	ddp: 'http://localhost:3000'
// 	serverExecuteTimeout: 10000,

// 	// - - - - PHANTOM  - - - -
// 	phantom_w: 1280,
// 	phantom_h: 1024,
// 	phantom_ignoreSSLErrors: false,

// 	// - - - - DEBUGGING  - - - -
// 	log: 'info',
// 	debug: false,
// 	seleniumDebug: null,
// 	debugCucumber: null,
// 	debugBrkCucumber: null,
// 	debugMocha: null,
// 	debugBrkMocha: null,
};
<commit_msg>Reactivate API tests<commit_after>// import path from 'path';
// import {isCI} from '../lib/ci';

module.exports = {
// 	// - - - - CHIMP - - - -
// 	watch: false,
// 	watchTags: '@watch,@focus',
// 	domainSteps: null,
// 	e2eSteps: null,
// 	fullDomain: false,
// 	domainOnly: false,
// 	e2eTags: '@e2e',
// 	watchWithPolling: false,
// 	server: false,
// 	serverPort: 8060,
// 	serverHost: 'localhost',
// 	sync: true,
// 	offline: false,
// 	showXolvioMessages: true,

// 	// - - - - CUCUMBER - - - -
	path: 'tests/end-to-end',
	// 	format: 'pretty',
	// 	tags: '~@ignore',
	// 	singleSnippetPerFile: true,
	// 	recommendedFilenameSeparator: '_',
	// 	chai: false,
	screenshotsOnError: true,
	screenshotsPath: '.screenshots',
	captureAllStepScreenshots: false,
	saveScreenshotsToDisk: true,
	// 	// Note: With a large viewport size and captureAllStepScreenshots enabled,
	// 	// you may run out of memory. Use browser.setViewportSize to make the
	// 	// viewport size smaller.
	// 	saveScreenshotsToReport: false,
	// 	jsonOutput: null,
	// 	compiler: 'js:' + path.resolve(__dirname, '../lib/babel-register.js'),
	// 	conditionOutput: true,

	// 	// - - - - SELENIUM  - - - -
	// 	browser: null,
	// 	platform: 'ANY',
	// 	name: '',
	// 	user: '',
	// 	key: '',
	// 	port: null,
	// 	host: null,
	// 	// deviceName: null,

	// 	// - - - - WEBDRIVER-IO  - - - -
	// 	webdriverio: {
	// 		desiredCapabilities: {},
	// 		logLevel: 'silent',
	// 		// logOutput: null,
	// 		host: '127.0.0.1',
	// 		port: 4444,
	// 		path: '/wd/hub',
	// 		baseUrl: null,
	// 		coloredLogs: true,
	// 		screenshotPath: null,
	// 		waitforTimeout: 500,
	// 		waitforInterval: 250,
	// 	},

	// 	// - - - - SELENIUM-STANDALONE
	// 	seleniumStandaloneOptions: {
	// 		// check for more recent versions of selenium here:
	// 		// http://selenium-release.storage.googleapis.com/index.html
	// 		version: '2.53.1',
	// 		baseURL: 'https://selenium-release.storage.googleapis.com',
	// 		drivers: {
	// 			chrome: {
	// 				// check for more recent versions of chrome driver here:
	// 				// http://chromedriver.storage.googleapis.com/index.html
	// 				version: '2.25',
	// 				arch: process.arch,
	// 				baseURL: 'https://chromedriver.storage.googleapis.com'
	// 			},
	// 			ie: {
	// 				// check for more recent versions of internet explorer driver here:
	// 				// http://selenium-release.storage.googleapis.com/index.html
	// 				version: '2.50.0',
	// 				arch: 'ia32',
	// 				baseURL: 'https://selenium-release.storage.googleapis.com'
	// 			},
	// 			firefox: {
	// 				// check for more recent versions of gecko  driver here:
	// 				// https://github.com/mozilla/geckodriver/releases
	// 				version: '0.11.1',
	// 				arch: process.arch,
	// 				baseURL: 'https://github.com/mozilla/geckodriver/releases/download'
	// 			}
	// 		}
	// 	},

	// 	// - - - - SESSION-MANAGER  - - - -
	// 	noSessionReuse: false,

	// 	// - - - - SIMIAN  - - - -
	// 	simianResultEndPoint: 'api.simian.io/v1.0/result',
	// 	simianAccessToken: false,
	// 	simianResultBranch: null,
	// 	simianRepositoryId: null,

	// 	// - - - - MOCHA  - - - -
	mocha: true,
	mochaCommandLineOptions: ['--color'],
	mochaConfig: {
		// tags and grep only work when watch mode is false
		tags: '',
		grep: null,
		timeout: 40000,
		reporter: 'spec',
		slow: 100,
		//retries: 3,
		bail: true // bail after first test failure
	},

	// 	// - - - - JASMINE  - - - -
	// 	jasmine: false,
	// 	jasmineConfig: {
	// 		specDir: '.',
	// 		specFiles: [
	// 			'**/*@(_spec|-spec|Spec).@(js|jsx)',
	// 		],
	// 		helpers: [
	// 			'support/**/*.@(js|jsx)',
	// 		],
	// 		stopSpecOnExpectationFailure: false,
	// 		random: false,
	// 	},
	// 	jasmineReporterConfig: {
	// 		// This options are passed to jasmine.configureDefaultReporter(...)
	// 		// See: http://jasmine.github.io/2.4/node.html#section-Reporters
	// 	},

	// 	// - - - - METEOR  - - - -
	ddp: 'http://localhost:3000'
// 	serverExecuteTimeout: 10000,

// 	// - - - - PHANTOM  - - - -
// 	phantom_w: 1280,
// 	phantom_h: 1024,
// 	phantom_ignoreSSLErrors: false,

// 	// - - - - DEBUGGING  - - - -
// 	log: 'info',
// 	debug: false,
// 	seleniumDebug: null,
// 	debugCucumber: null,
// 	debugBrkCucumber: null,
// 	debugMocha: null,
// 	debugBrkMocha: null,
};
<|endoftext|>


<commit_before>
Tinytest.add(
  'Client Side - Error Manager - Utils - stackFramesFilter()',
  function (test) {
    test.equal(typeof stackFramesFilter, 'function');
    test.equal(stackFramesFilter('/packages/zones/assets/zone.js'), false);
    test.equal(stackFramesFilter('/packages/foo/bar.js'), true);
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getCurrentOrigin()',
  function (test) {
    test.equal(typeof getCurrentOrigin, 'function');
    // Simple regex to catch origin part of the url
    // (may not work for all cases but sufficient for tests)
    var regex = /^https?:\/\/[a-zA-Z0-9\.]+:?[0-9]*$/;
    var origin = getCurrentOrigin();
    test.equal(typeof origin, 'string');
    test.equal(!!origin.match(regex), true);
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - formatTraceLine()',
  function (test) {
    test.equal(typeof formatTraceLine, 'function');
    var lines = [
      '{anonymous}()@'+getCurrentOrigin()+'/foo/bar.js:12:34',
      'funName@'+getCurrentOrigin()+'/foo/bar.js:12:34'
    ];
    var expected = [
      '    at foo/bar.js:12:34',
      '    at funName (foo/bar.js:12:34)',
    ];
    for(var i=lines.length; i-->0;) {
      test.equal(expected[i], formatTraceLine(lines[i]));
    }
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getNormalizedStacktrace()',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    test.equal(typeof getNormalizedStacktrace, 'function');
    var expected = [
      '    at foo/bar.js:12:34',
      '    at funName (foo/bar.js:12:34)',
    ].join('\n');
    test.equal(expected, getNormalizedStacktrace());
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack()',
  function (test) {
    test.equal(typeof getErrorStack, 'function');
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack() errored stack',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    var zone = {
      erroredStack: {_e: new Error()}
    };
    var trace = getErrorStack(zone);
    test.equal(1, trace.length);
    test.equal('number', typeof trace[0].at);
    test.equal('string', typeof trace[0].stack);
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack() without events',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    var stack = '    at foo/bar.js:12:34\n    at funName (foo/bar.js:12:34)';

    var zone = {
      id: 'foo',
      createdAt: 100,
      runAt: 200,
      owner: '_owner',
      currentStack: {_e: new Error()},
      erroredStack: {_e: new Error()},
      // eventMap: {}
    };

    var expected = {
      createdAt: 100,
      runAt: 200,
      stack: stack,
      owner: '_owner',
      ownerArgs: [],
      events: undefined,
      zoneId: 'foo'
    };

    var trace = getErrorStack(zone);
    test.equal(2, trace.length);
    test.equal('number', typeof trace[0].at);
    test.equal(stack, trace[0].stack);
    test.equal(expected, trace[1]);
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack() with stack',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    var stack = '    at foo/bar.js:12:34\n    at funName (foo/bar.js:12:34)';

    var eventMap = {foo: [
      {type: 'owner-args', args: ['foo', 'bar'], at: 300},
      {type: '_type', args: ['bar', 'baz']},
    ]};

    var zone = {
      id: 'foo',
      createdAt: 100,
      runAt: 200,
      owner: '_owner',
      currentStack: {_e: new Error()},
      erroredStack: {_e: new Error()},
      eventMap: eventMap
    };

    var expected = {
      createdAt: 100,
      runAt: 300,
      stack: stack,
      owner: '_owner',
      ownerArgs: ['foo', 'bar'],
      events: [{type: '_type', args: ['bar', 'baz']}],
      zoneId: 'foo'
    };

    var trace = getErrorStack(zone);
    test.equal(2, trace.length);
    test.equal('number', typeof trace[0].at);
    test.equal(stack, trace[0].stack);
    test.equal(expected, trace[1]);
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack() with parent zone',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    var stack = '    at foo/bar.js:12:34\n    at funName (foo/bar.js:12:34)';

    var eventMap = {
      foo: [
        {type: 'owner-args', args: ['foo', 'bar'], at: 300},
        {type: '_type', args: ['bar', 'baz']},
      ],
      bar: [
        {type: 'owner-args', args: ['foo2', 'bar2'], at: 310},
        {type: '_type2', args: ['bar2', 'baz2']},
      ]
    };

    var zone2 = {
      id: 'bar',
      createdAt: 110,
      runAt: 210,
      owner: '_owner2',
      currentStack: {_e: new Error()},
      erroredStack: {_e: new Error()},
    };

    var zone = {
      id: 'foo',
      createdAt: 100,
      runAt: 200,
      owner: '_owner',
      parent: zone2,
      currentStack: {_e: new Error()},
      erroredStack: {_e: new Error()},
      eventMap: eventMap
    };

    var expected = {
      createdAt: 100,
      runAt: 300,
      stack: stack,
      owner: '_owner',
      ownerArgs: ['foo', 'bar'],
      events: [{type: '_type', args: ['bar', 'baz']}],
      zoneId: 'foo'
    };

    var expected2 = {
      createdAt: 110,
      runAt: 310,
      stack: stack,
      owner: '_owner2',
      ownerArgs: ['foo2', 'bar2'],
      events: [{type: '_type2', args: ['bar2', 'baz2']}],
      zoneId: 'bar'
    };

    var trace = getErrorStack(zone);
    test.equal(3, trace.length);
    test.equal('number', typeof trace[0].at);
    test.equal(stack, trace[0].stack);
    test.equal(expected, trace[1]);
    test.equal(expected2, trace[2]);
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getBrowserInfo() for guest',
  function (test) {
    test.equal(typeof getBrowserInfo, 'function');
    var info = getBrowserInfo();
    test.equal('string', typeof info.browser);
    test.equal('string', typeof info.url);
    test.equal(undefined, info.userId);
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getBrowserInfo() for users',
  function (test) {
    hijackMeteorUserId(mock_MeteorUserId);
    test.equal(typeof getBrowserInfo, 'function');
    var info = getBrowserInfo();
    test.equal('string', typeof info.browser);
    test.equal('string', typeof info.url);
    test.equal('string', typeof info.userId);
    restoreMeteorUserId();
  }
);

//--------------------------------------------------------------------------\\

var original_printStackTrace = printStackTrace;

function hijackPrintStackTrace(mock) {
  printStackTrace = mock;
}

function restorePrintStackTrace() {
  printStackTrace = original_printStackTrace;
}

function mock_printStackTrace() {
  var o = getCurrentOrigin();
  return [
    '{anonymous}()@'+o+'/packages/zones/assets/bar.js:12:34',
    'funName@'+o+'/packages/zones/assets/bar.js:12:34',
    '{anonymous}()@'+o+'/foo/bar.js:12:34',
    'funName@'+o+'/foo/bar.js:12:34'
  ];
}

var original_MeteorUserId = Meteor.userId;

function hijackMeteorUserId(mock) {
  Meteor.userId = mock;
}

function restoreMeteorUserId() {
  Meteor.userId = original_MeteorUserId;
}

function mock_MeteorUserId() {
  return Random.id();
}
<commit_msg>Fix assert arguments order to (expected, actual)<commit_after>
Tinytest.add(
  'Client Side - Error Manager - Utils - stackFramesFilter()',
  function (test) {
    test.equal('function', typeof stackFramesFilter);
    test.equal(false, stackFramesFilter('/packages/zones/assets/zone.js'));
    test.equal(true, stackFramesFilter('/packages/foo/bar.js'));
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getCurrentOrigin()',
  function (test) {
    test.equal('function', typeof getCurrentOrigin);
    // Simple regex to catch origin part of the url
    // (may not work for all cases but sufficient for tests)
    var regex = /^https?:\/\/[a-zA-Z0-9\.]+:?[0-9]*$/;
    var origin = getCurrentOrigin();
    test.equal('string', typeof origin);
    test.equal(true, !!origin.match(regex));
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - formatTraceLine()',
  function (test) {
    test.equal('function', typeof formatTraceLine);
    var lines = [
      '{anonymous}()@'+getCurrentOrigin()+'/foo/bar.js:12:34',
      'funName@'+getCurrentOrigin()+'/foo/bar.js:12:34'
    ];
    var expected = [
      '    at foo/bar.js:12:34',
      '    at funName (foo/bar.js:12:34)',
    ];
    for(var i=lines.length; i-->0;) {
      test.equal(expected[i], formatTraceLine(lines[i]));
    }
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getNormalizedStacktrace()',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    test.equal('function', typeof getNormalizedStacktrace);
    var expected = [
      '    at foo/bar.js:12:34',
      '    at funName (foo/bar.js:12:34)',
    ].join('\n');
    test.equal(expected, getNormalizedStacktrace());
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack()',
  function (test) {
    test.equal('function', typeof getErrorStack);
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack() errored stack',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    var zone = {
      erroredStack: {_e: new Error()}
    };
    var trace = getErrorStack(zone);
    test.equal(1, trace.length);
    test.equal('number', typeof trace[0].at);
    test.equal('string', typeof trace[0].stack);
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack() without events',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    var stack = '    at foo/bar.js:12:34\n    at funName (foo/bar.js:12:34)';

    var zone = {
      id: 'foo',
      createdAt: 100,
      runAt: 200,
      owner: '_owner',
      currentStack: {_e: new Error()},
      erroredStack: {_e: new Error()},
      // eventMap: {}
    };

    var expected = {
      createdAt: 100,
      runAt: 200,
      stack: stack,
      owner: '_owner',
      ownerArgs: [],
      events: undefined,
      zoneId: 'foo'
    };

    var trace = getErrorStack(zone);
    test.equal(2, trace.length);
    test.equal('number', typeof trace[0].at);
    test.equal(stack, trace[0].stack);
    test.equal(expected, trace[1]);
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack() with stack',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    var stack = '    at foo/bar.js:12:34\n    at funName (foo/bar.js:12:34)';

    var eventMap = {foo: [
      {type: 'owner-args', args: ['foo', 'bar'], at: 300},
      {type: '_type', args: ['bar', 'baz']},
    ]};

    var zone = {
      id: 'foo',
      createdAt: 100,
      runAt: 200,
      owner: '_owner',
      currentStack: {_e: new Error()},
      erroredStack: {_e: new Error()},
      eventMap: eventMap
    };

    var expected = {
      createdAt: 100,
      runAt: 300,
      stack: stack,
      owner: '_owner',
      ownerArgs: ['foo', 'bar'],
      events: [{type: '_type', args: ['bar', 'baz']}],
      zoneId: 'foo'
    };

    var trace = getErrorStack(zone);
    test.equal(2, trace.length);
    test.equal('number', typeof trace[0].at);
    test.equal(stack, trace[0].stack);
    test.equal(expected, trace[1]);
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getErrorStack() with parent zone',
  function (test) {
    hijackPrintStackTrace(mock_printStackTrace);
    var stack = '    at foo/bar.js:12:34\n    at funName (foo/bar.js:12:34)';

    var eventMap = {
      foo: [
        {type: 'owner-args', args: ['foo', 'bar'], at: 300},
        {type: '_type', args: ['bar', 'baz']},
      ],
      bar: [
        {type: 'owner-args', args: ['foo2', 'bar2'], at: 310},
        {type: '_type2', args: ['bar2', 'baz2']},
      ]
    };

    var zone2 = {
      id: 'bar',
      createdAt: 110,
      runAt: 210,
      owner: '_owner2',
      currentStack: {_e: new Error()},
      erroredStack: {_e: new Error()},
    };

    var zone = {
      id: 'foo',
      createdAt: 100,
      runAt: 200,
      owner: '_owner',
      parent: zone2,
      currentStack: {_e: new Error()},
      erroredStack: {_e: new Error()},
      eventMap: eventMap
    };

    var expected = {
      createdAt: 100,
      runAt: 300,
      stack: stack,
      owner: '_owner',
      ownerArgs: ['foo', 'bar'],
      events: [{type: '_type', args: ['bar', 'baz']}],
      zoneId: 'foo'
    };

    var expected2 = {
      createdAt: 110,
      runAt: 310,
      stack: stack,
      owner: '_owner2',
      ownerArgs: ['foo2', 'bar2'],
      events: [{type: '_type2', args: ['bar2', 'baz2']}],
      zoneId: 'bar'
    };

    var trace = getErrorStack(zone);
    test.equal(3, trace.length);
    test.equal('number', typeof trace[0].at);
    test.equal(stack, trace[0].stack);
    test.equal(expected, trace[1]);
    test.equal(expected2, trace[2]);
    restorePrintStackTrace();
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getBrowserInfo() for guest',
  function (test) {
    test.equal(typeof getBrowserInfo, 'function');
    var info = getBrowserInfo();
    test.equal('string', typeof info.browser);
    test.equal('string', typeof info.url);
    test.equal(undefined, info.userId);
  }
);

Tinytest.add(
  'Client Side - Error Manager - Utils - getBrowserInfo() for users',
  function (test) {
    hijackMeteorUserId(mock_MeteorUserId);
    test.equal(typeof getBrowserInfo, 'function');
    var info = getBrowserInfo();
    test.equal('string', typeof info.browser);
    test.equal('string', typeof info.url);
    test.equal('string', typeof info.userId);
    restoreMeteorUserId();
  }
);

//--------------------------------------------------------------------------\\

var original_printStackTrace = printStackTrace;

function hijackPrintStackTrace(mock) {
  printStackTrace = mock;
}

function restorePrintStackTrace() {
  printStackTrace = original_printStackTrace;
}

function mock_printStackTrace() {
  var o = getCurrentOrigin();
  return [
    '{anonymous}()@'+o+'/packages/zones/assets/bar.js:12:34',
    'funName@'+o+'/packages/zones/assets/bar.js:12:34',
    '{anonymous}()@'+o+'/foo/bar.js:12:34',
    'funName@'+o+'/foo/bar.js:12:34'
  ];
}

var original_MeteorUserId = Meteor.userId;

function hijackMeteorUserId(mock) {
  Meteor.userId = mock;
}

function restoreMeteorUserId() {
  Meteor.userId = original_MeteorUserId;
}

function mock_MeteorUserId() {
  return Random.id();
}
<|endoftext|>


<commit_before>module.exports = [
    {action: '\\sqrt', label: '\\sqrt{X}'},
    {action: '^', label: 'x^{X}'},
    {action: '\\frac', label: '\\frac{X}{X}'},
    {action: '\\int', label: '\\int_{X}^{X}'},
    {action: '\\lim_', label: '\\lim_{X}'},
    {action: '\\overrightarrow', label: '\\overrightarrow{X}'},
    {action: '_', label: 'x_X'},
    {action: '\\nthroot', label: '\\sqrt[X]{X}'},
    {action: '\\sum', label: '\\sum_{X}^{X}'},
    {action: '\\binom', label: '\\binom{X}{X}'},
    {action: '\\sin'},
    {action: '\\cos'},
    {action: '\\tan'},
    {action: '\\vec', label: '\\vec{X}'},
    {action: '\\bar', label: '\\bar{X}'},
    {action: '\\underline', label: '\\underline{X}'},
    {action: '\\overleftarrow', label: '\\overleftarrow{X}'},
    {action: '|', label: '|X|'},
    {action: '(', label: '(X)'},
    {action: '_{ }^{ } ', label: '_{X}^{X}X', useWrite: true},
    {action: '\\text', label: '\\text{text}'}
]
<commit_msg>Add vectors<commit_after>module.exports = [
    {action: '\\sqrt', label: '\\sqrt{X}'},
    {action: '^', label: 'x^{X}'},
    {action: '\\frac', label: '\\frac{X}{X}'},
    {action: '\\int', label: '\\int_{X}^{X}'},
    {action: '\\lim_', label: '\\lim_{X}'},
    {action: '\\lim_{x\\rightarrow\\infty}', label: '\\lim_{x\\rightarrow\\infty}', useWrite:true},
    {action: '\\overrightarrow', label: '\\overrightarrow{X}'},
    {action: '_', label: 'x_X'},
    {action: '\\nthroot', label: '\\sqrt[X]{X}'},
    {action: '\\sum', label: '\\sum_{X}^{X}'},
    {action: '\\binom', label: '\\binom{X}{X}'},
    {action: '\\sin'},
    {action: '\\cos'},
    {action: '\\tan'},
    {action: '\\vec', label: '\\vec{X}'},
    {action: '\\bar', label: '\\bar{X}'},
    {action: '\\overline{\\text{i}}', useWrite: true},
    {action: '\\overline{\\text{j}}', useWrite: true},
    {action: '\\overline{\\text{k}}', useWrite: true},
    {action: '\\overleftarrow', label: '\\overleftarrow{X}'},
    {action: '|', label: '|X|'},
    {action: '(', label: '(X)'},
    {action: '_{ }^{ } ', label: '_{X}^{X}X', useWrite: true},
    {action: '\\text', label: '\\text{text}'},
]
<|endoftext|>


<commit_before>var KA_LAT  = 49.00921;
var KA_LNG  = 8.45003951;
var elemSvg = null;

var GEOJSON = null;
var Party = ["CDU","SPD","FDP","GRÜNE","DIE LINKE","PIRATEN","NPD","REP","Tierschutzpartei","ÖDP","PBC","Volksabstimmung","MLPD ","BüSo","AfD","BIG","pro Deutschland","FREIE WÄHLER","PARTEI DER VERNUNFT","RENTNER"];

const PartyColors = ["000","f40502","feed01","42a62a","8b1b62","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","009de0","ffffff","ffffff","ffffff","ffffff","ffffff"];

const PARTIES = {
    CDU: {
        "name": "CDU",
        "color": "#000",
    },
    SPD:{
        "color": "#f40502",
        "name": "SPD"
    },

    AFD:{
        "color": "#f40502",
        "name": "AfD"
    },
    FDP:{
        "color": "#feed01",
        "name": "FDP"
    },
    GRUENE:{
        "color": "#42a62a",
        "name": "Grüne"
    },
    LINKE:{
        "color": "#8b1b62",
        "name": "Die Linke"
    },
    PIRATEN:{
        "color": "#ff8800",
        "name": "Piraten"
    },
    NPD:{
        "name": "NPD"
    },
    REP:{
        "name": "Die Republikaner"
    },
    TIERSCHUTZPARTEI:{
        "name": "Tierschutzpartei"
    },
    OEDP:{
        "name": "ÖDP"
    },
    VOLKSABSTIMMUNG:{
        "name": "Volksabstimmung"
    },
    MLPD:{
        "name": "MLPD"
    },
    BUESO:{
        "name": "BüSo"
    },
    BIG:{
        "name": "BIG"
    },
    PRODEUTSCHLAND:{
        "name": "pro Deutschland"
    },
    FREIEWAEHLER:{
        "name": "Freie Wähler"
    },
    PARTEIDERVERNUNFT:{
        "name": "Partei der Vernunft"
    },
    RENTNER:{
        "name": "Rentner"
    }
}
var TILES_URL = 'http://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';

var MAP_ATTRIBUTION = 'Map data © ' +
                      'OpenStreetMap contributors | Tiles © ' +
                      'Carto';

var map = new L.Map("map", {center: [KA_LAT, KA_LNG], zoom: 12})
    .addLayer(new L.TileLayer(TILES_URL, {attribution: MAP_ATTRIBUTION}));

var svg = d3.select(map.getPanes().overlayPane).append("svg"),
    g = svg.append("g").attr("class", "leaflet-zoom-hide");

// SVG ID
svg.attr("id", "karte")

var stadtteile = g.append('g')
    .classed('stadtteile', true);

var wahlbezirke = g.append('g')
    .classed('wahlbezirke', true);

/**
 * Adapter to use Leaflet's projection in D3.
 */
function projectPoint(x, y) {
    var point = map.latLngToLayerPoint(new L.LatLng(y, x));
    this.stream.point(point.x, point.y);
}
var transform = d3.geo.transform({ point: projectPoint }),
    path = d3.geo.path().projection(transform);

/**
 * Create SVG paths from a GeoJSON file.
 */
function pathsFromGeoJSON(filename, group, setGeoJson, callback) {

    d3.json(filename, function (error, collection) {
        if (error) return callback(error, null);

        if (GEOJSON === null && setGeoJson){
            GEOJSON = collection
        }
        var feature = group.selectAll("path")
            .data(collection.features)
            .enter().append("path");

        map.on("viewreset", reset);
        reset();

        return callback(null, feature);

        // Reposition the SVG to cover the features.
        function reset() {
            var bounds = path.bounds(collection);
            var topLeft = bounds[0];
            var bottomRight = bounds[1];

            svg.attr("width", bottomRight[0] - topLeft[0])
                .attr("height", bottomRight[1] - topLeft[1])
                .style("left", topLeft[0] + "px")
                .style("top", topLeft[1] + "px");

            group.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");

            feature.attr("d", path);
        }
    });
}

pathsFromGeoJSON("ka_stadtteile.geojson", stadtteile,false, function (error, paths) {
    paths
        .attr("id", function (d) { return d.properties.Stadtteilnummer })
        .attr('class', 'district')
        .style('fill', 'rgba(255, 255, 255, 0.7)')
        .style('stroke', '#000')
        .style('stroke-width', 2);
});

pathsFromGeoJSON("bundestagswahl_2013_wahlbezirke.geojson", wahlbezirke, true, function (error, paths) {
    paths
        .attr("id", function (d) { return d.properties.Wahlbezirksnummer })
        .attr('class', 'wahlbezirk')
        .on('mousemove', onMouseOverWahlbezirk)
        .on('mouseleave', onMouseLeaveWahlbezirk)
        .style('fill', '#fff')
        .style('stroke', '#000')
        .style('stroke-width', 1)
        .on('click', selectDistrict);
});

function colorMap() {

    // Karte Reference setzten wenn nicht vorhanden
    if(elemSvg === null){
        getSVGMap();
    } // end if

    if (GEOJSON !== null){
        for(var item of GEOJSON.features){
            var win = maxPartie(item)
            var color = winnerColor(win[0])
            if (typeof color !== 'undefined'){
                color = "#" + color;
                elemSvg.getElementById(item.properties.Wahlbezirksnummer).style.fill = color
            }
        }
    } else {
        console.error("GEOJSON null!")
    }
}

function winnerColor(partyName){
    var index = Party.indexOf(partyName)
    if (index >= 0 && PartyColors.length >= index){
        return PartyColors[index]
    } else {
        console.error("Party not found! ", partyName)
    }
}

function maxPartie(data){
    if (data !== 'undefined'){
        var max = 0;
        var partyName = null;
        Object.keys(data.properties).forEach(function(k, v){
            var value = data.properties[k]
           if (max < value && Party.indexOf(k) >= 0) {
               max = value;
               partyName = k;
           }
        })
        return [partyName, max]
    } else {
        console.error("No data")
    }
}

function getSVGMap() {
    return elemSvg = document.getElementById("karte");
}
<commit_msg>Partei ergaenzt<commit_after>var KA_LAT  = 49.00921;
var KA_LNG  = 8.45003951;
var elemSvg = null;

var GEOJSON = null;
var Party = ["CDU","SPD","FDP","GRÜNE","DIE LINKE","PIRATEN","NPD","REP","Tierschutzpartei","ÖDP","PBC","Volksabstimmung","MLPD ","BüSo","AfD","BIG","pro Deutschland","FREIE WÄHLER","PARTEI DER VERNUNFT","RENTNER"];

const PartyColors = ["000","f40502","feed01","42a62a","8b1b62","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","009de0","ffffff","ffffff","ffffff","ffffff","ffffff"];

const PARTIES = {
    CDU: {
        "name": "CDU",
        "color": "#000",
    },
    SPD:{
        "color": "#f40502",
        "name": "SPD"
    },

    AFD:{
        "color": "#f40502",
        "name": "AfD"
    },
    FDP:{
        "color": "#feed01",
        "name": "FDP"
    },
    GRUENE:{
        "color": "#42a62a",
        "name": "Grüne"
    },
    LINKE:{
        "color": "#8b1b62",
        "name": "Die Linke"
    },
    PIRATEN:{
        "color": "#ff8800",
        "name": "Piraten"
    },
    NPD:{
        "name": "NPD"
    },
    REP:{
        "name": "REP"
    },
    TIERSCHUTZPARTEI:{
        "name": "Tierschutzpartei"
    },
    OEDP:{
        "name": "ÖDP"
    },
    VOLKSABSTIMMUNG:{
        "name": "Volksabstimmung"
    },
    MLPD:{
        "name": "MLPD"
    },
    BUESO:{
        "name": "BüSo"
    },
    BIG:{
        "name": "BIG"
    },
    PBC: {
        "name": "PBC"
    },
    PRODEUTSCHLAND:{
        "name": "pro Deutschland"
    },
    FREIEWAEHLER:{
        "name": "Freie Wähler"
    },
    PARTEIDERVERNUNFT:{
        "name": "Partei der Vernunft"
    },
    RENTNER:{
        "name": "Rentner"
    }
}
var TILES_URL = 'http://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';

var MAP_ATTRIBUTION = 'Map data © ' +
                      'OpenStreetMap contributors | Tiles © ' +
                      'Carto';

var map = new L.Map("map", {center: [KA_LAT, KA_LNG], zoom: 12})
    .addLayer(new L.TileLayer(TILES_URL, {attribution: MAP_ATTRIBUTION}));

var svg = d3.select(map.getPanes().overlayPane).append("svg"),
    g = svg.append("g").attr("class", "leaflet-zoom-hide");

// SVG ID
svg.attr("id", "karte")

var stadtteile = g.append('g')
    .classed('stadtteile', true);

var wahlbezirke = g.append('g')
    .classed('wahlbezirke', true);

/**
 * Adapter to use Leaflet's projection in D3.
 */
function projectPoint(x, y) {
    var point = map.latLngToLayerPoint(new L.LatLng(y, x));
    this.stream.point(point.x, point.y);
}
var transform = d3.geo.transform({ point: projectPoint }),
    path = d3.geo.path().projection(transform);

/**
 * Create SVG paths from a GeoJSON file.
 */
function pathsFromGeoJSON(filename, group, setGeoJson, callback) {

    d3.json(filename, function (error, collection) {
        if (error) return callback(error, null);

        if (GEOJSON === null && setGeoJson){
            GEOJSON = collection
        }
        var feature = group.selectAll("path")
            .data(collection.features)
            .enter().append("path");

        map.on("viewreset", reset);
        reset();

        return callback(null, feature);

        // Reposition the SVG to cover the features.
        function reset() {
            var bounds = path.bounds(collection);
            var topLeft = bounds[0];
            var bottomRight = bounds[1];

            svg.attr("width", bottomRight[0] - topLeft[0])
                .attr("height", bottomRight[1] - topLeft[1])
                .style("left", topLeft[0] + "px")
                .style("top", topLeft[1] + "px");

            group.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");

            feature.attr("d", path);
        }
    });
}

pathsFromGeoJSON("ka_stadtteile.geojson", stadtteile,false, function (error, paths) {
    paths
        .attr("id", function (d) { return d.properties.Stadtteilnummer })
        .attr('class', 'district')
        .style('fill', 'rgba(255, 255, 255, 0.7)')
        .style('stroke', '#000')
        .style('stroke-width', 2);
});

pathsFromGeoJSON("bundestagswahl_2013_wahlbezirke.geojson", wahlbezirke, true, function (error, paths) {
    paths
        .attr("id", function (d) { return d.properties.Wahlbezirksnummer })
        .attr('class', 'wahlbezirk')
        .on('mousemove', onMouseOverWahlbezirk)
        .on('mouseleave', onMouseLeaveWahlbezirk)
        .style('fill', '#fff')
        .style('stroke', '#000')
        .style('stroke-width', 1)
        .on('click', selectDistrict);
});

function colorMap() {

    // Karte Reference setzten wenn nicht vorhanden
    if(elemSvg === null){
        getSVGMap();
    } // end if

    if (GEOJSON !== null){
        for(var item of GEOJSON.features){
            var win = maxPartie(item)
            var color = winnerColor(win[0])
            if (typeof color !== 'undefined'){
                color = "#" + color;
                elemSvg.getElementById(item.properties.Wahlbezirksnummer).style.fill = color
            }
        }
    } else {
        console.error("GEOJSON null!")
    }
}

function winnerColor(partyName){
    var index = Party.indexOf(partyName)
    if (index >= 0 && PartyColors.length >= index){
        return PartyColors[index]
    } else {
        console.error("Party not found! ", partyName)
    }
}

function maxPartie(data){
    if (data !== 'undefined'){
        var max = 0;
        var partyName = null;
        Object.keys(data.properties).forEach(function(k, v){
            var value = data.properties[k]
           if (max < value && Party.indexOf(k) >= 0) {
               max = value;
               partyName = k;
           }
        })
        return [partyName, max]
    } else {
        console.error("No data")
    }
}

function getSVGMap() {
    return elemSvg = document.getElementById("karte");
}
<|endoftext|>


<commit_before>/* jslint node: true */
/* global BOT_DIR, LIBS_DIR, MODULES_DIR */
'use strict';

//check main entry point path
if (!global.BOT_DIR) throw new Error('Wrong entry point! No \'BOT_DIR\' defined!');
if (!global.LIBS_DIR) throw new Error('Wrong entry point! No \'LIBS_DIR\' defined!');
if (!global.MODULES_DIR) throw new Error('Wrong entry point! No \'MODULES_DIR\' defined!');

var logger = require(LIBS_DIR + '/logger');
var EventEmitter = require('events').EventEmitter;

function Module(name) {
	if (typeof name !== 'string' || name === '') {
		throw new Error('You need to specifify module name!');
	}

	Object.defineProperty(this, 'name', {
		writable: false,
		configurable: false,
		enumerable: true,
		value: name.replace(/[^a-zA-Z0-9_\-]+/g, '')
	});

	try {
		Object.defineProperty(this, 'filename', {
			writable: false,
			configurable: false,
			enumerable: true,
			value: require.resolve(MODULES_DIR + '/' + this.name)
		});
	} catch (e) {
		throw new Error('Module \'' + this.name + '\' does not exists!');
	}

	this.loaded = false;
	this.reloading = false;
	this.context = null;

	//empty require - MM will inject own method on load
	this.require = function() {
		return null;
	};
}

//called on load
Module.prototype.init = function init() {
	var error = null;

	if (this.loaded) {
		error = new Error('Module \'' + this.name + '\' is already loaded!');
	}

	if (!error && typeof this.dispatcher !== 'object' && this.dispatcher !== null) error = new Error('No dispatcher given!');
	if (!error && typeof this.config !== 'object' && this.config !== null) error = new Error('No config given!');

	if (!error) {
		try {
			this.__load(); //load context
			if (typeof this.context.init === 'function') this.context.init.call(this, false);
		} catch (e) {
			this.__unload(); //unload if needed
			error = new Error('Failed loading context of \'' + this.name + '\' module! ' + e.message);
		}
	}

	logger.debug('Init of \'' + this.name + '\' module' + (error ? ' failed' : ' is success') + '.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

//called on unload
Module.prototype.halt = function halt() {
	var error = null;

	if (this.loaded) {
		try {
			if (typeof this.context.halt === 'function') this.context.halt.call(this, false);
			this.__unload();
			if (this.dispatcher && this.dispatcher.clearEvents) this.dispatcher.clearEvents();
		} catch (e) {
			error = new Error('Failed unloading context of \'' + this.name + '\' module! ' + e.message);
		}
	} else {
		error = new Error('Module \'' + this.name + '\' is not loaded!');
	}

	logger.debug('Halt of \'' + this.name + '\' module.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

Module.prototype.reload = function reload() {
	var error = null;
	if (this.loaded) {
		this.reloading = true;

		try {
			if (typeof this.context.halt === 'function') this.context.halt.call(this, true);
			this.__unload();
			if (this.dispatcher && this.dispatcher.clearEvents) this.dispatcher.clearEvents();

			this.__load();
			if (typeof this.context.init === 'function') this.context.init.call(this, true);
		} catch (e) {
			error = e;
		}

		this.reloading = false;
	} else {
		error = new Error('Module \'' + this.name + '\' is not loaded!');
	}

	logger.debug('Reload of \'' + this.name + '\' module.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

Module.prototype.injectConfig = function injectConfig(config) {
	var error = null;
	if (!(config instanceof Object)) {
		error = new Error('Config needs to be object!');
	} else {
		if (typeof config[this.name] !== 'object') config[this.name] = {};

		Object.defineProperty(this, 'config', {
			writable: false,
			configurable: false,
			enumerable: true,
			value: config[this.name]
		});
	}

	logger.debug('Module \'' + this.name + '\' Config inject.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

Module.prototype.injectDispatcher = function injectDispatcher(dispatchBase) {
	var error = null;
	if (!(dispatchBase instanceof EventEmitter)) {
		error = new Error('Wrong dispatcher type for \'' + this.name + '\' module injected!');
	} else {
		var events = [];
		var eventTest = new RegExp('^' + this.name + '/');
		var module = this;
		this.dispatcher = {
			on: function(event, listener) {
				events.push({
					event: event,
					listener: listener
				});
				dispatchBase.on(event, listener);
				return this;
			},
			once: function(event, listener) {
				events.push({
					event: event,
					listener: listener
				});
				dispatchBase.once(event, listener);
				return this;
			},
			off: function(event, listener) {
				return this.removeListener(event, listener);
			},
			addListener: function(event, listener) {
				events.push({
					event: event,
					listener: listener
				});
				dispatchBase.addListener(event, listener);
				return this;
			},
			removeListener: function(event, listener) {
				events.some(function(obj, i) {
					if (obj.event === event && obj.listener === listener) {
						events.splice(i, 1);
						return true;
					}
					return false;
				});
				dispatchBase.removeListener(event, listener);
				return this;
			},
			emit: function(event) {
				var args;
				//all emited events needs to be prefixed by module name
				if (!(eventTest.test(event))) {
					event = module.name + '/' + event;
					args = Array.prototype.slice.call(arguments, 1); //convert arguments to Array and remove first argument
					args.unshift(event); //put new event as first argument
				}
				try {
					dispatchBase.emit.apply(dispatchBase, args || arguments);
				} catch (e) {
					dispatchBase.emit.call(dispatchBase, 'dispatchError', e, event, module);
				}
				return this;
			},
			clearEvents: function() {
				events.forEach(function(event) {
					dispatchBase.removeListener(event.event, event.listener);
				});
				events = [];
				return this;
			}
		};
	}

	logger.debug('Module \'' + this.name + '\' dispatcher inject.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

/**
 * unload helper
 * @internal
 * @return void
 */
Module.prototype.__unload = function __unload() {
	if (this.loaded) {
		//remove from node require cache
		var module = require.cache[this.filename];
		module.children.forEach(function(m) {
			delete require.cache[m.filename];
		});
		delete require.cache[this.filename];

		this.loaded = false;
		this.context = null;
	}
};

/**
 * load helper
 * @internal
 * @throws Error
 * @return void
 */
Module.prototype.__load = function __load() {
	if (!this.loaded) {
		try {
			this.context = require(this.filename);
		} catch (e) {
			this.context = null;
			throw e;
		}

		if (typeof this.context === 'object' && this.context !== null) {
			this.loaded = true;
		} else {
			this.context = null;
		}
	}
};

Module.prototype.valueOf = Module.prototype.toString = function toString() {
	return this.name;
};

module.exports.Module = Module;
module.exports.create = function createModule(name, module_dir) {
	return new Module(name, module_dir);
};<commit_msg>better wording here<commit_after>/* jslint node: true */
/* global BOT_DIR, LIBS_DIR, MODULES_DIR */
'use strict';

//check main entry point path
if (!global.BOT_DIR) throw new Error('Wrong entry point! No \'BOT_DIR\' defined!');
if (!global.LIBS_DIR) throw new Error('Wrong entry point! No \'LIBS_DIR\' defined!');
if (!global.MODULES_DIR) throw new Error('Wrong entry point! No \'MODULES_DIR\' defined!');

var logger = require(LIBS_DIR + '/logger');
var EventEmitter = require('events').EventEmitter;

function Module(name) {
	if (typeof name !== 'string' || name === '') {
		throw new Error('You need to specifify module name!');
	}

	Object.defineProperty(this, 'name', {
		writable: false,
		configurable: false,
		enumerable: true,
		value: name.replace(/[^a-zA-Z0-9_\-]+/g, '')
	});

	try {
		Object.defineProperty(this, 'filename', {
			writable: false,
			configurable: false,
			enumerable: true,
			value: require.resolve(MODULES_DIR + '/' + this.name)
		});
	} catch (e) {
		throw new Error('Module \'' + this.name + '\' does not exists!');
	}

	this.loaded = false;
	this.reloading = false;
	this.context = null;

	//empty require - MM will inject own method on load
	this.require = function() {
		return null;
	};
}

//called on load
Module.prototype.init = function init() {
	var error = null;

	if (this.loaded) {
		error = new Error('Module \'' + this.name + '\' is already loaded!');
	}

	if (!error && typeof this.dispatcher !== 'object' && this.dispatcher !== null) error = new Error('No dispatcher given!');
	if (!error && typeof this.config !== 'object' && this.config !== null) error = new Error('No config given!');

	if (!error) {
		try {
			this.__load(); //load context
			if (typeof this.context.init === 'function') this.context.init.call(this, false);
		} catch (e) {
			this.__unload(); //unload if needed
			error = new Error('Failed loading context of \'' + this.name + '\' module! ' + e.message);
		}
	}

	logger.debug('Init of \'' + this.name + '\' module' + (error ? ' failed' : ' is success') + '.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

//called on unload
Module.prototype.halt = function halt() {
	var error = null;

	if (this.loaded) {
		try {
			if (typeof this.context.halt === 'function') this.context.halt.call(this, false);
			this.__unload();
			if (this.dispatcher && this.dispatcher.clearEvents) this.dispatcher.clearEvents();
		} catch (e) {
			error = new Error('Failed unloading context of \'' + this.name + '\' module! ' + e.message);
		}
	} else {
		error = new Error('Module \'' + this.name + '\' is not loaded!');
	}

	logger.debug('Halt of \'' + this.name + '\' module.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

Module.prototype.reload = function reload() {
	var error = null;
	if (this.loaded) {
		this.reloading = true;

		try {
			if (typeof this.context.halt === 'function') this.context.halt.call(this, true);
			this.__unload();
			if (this.dispatcher && this.dispatcher.clearEvents) this.dispatcher.clearEvents();

			this.__load();
			if (typeof this.context.init === 'function') this.context.init.call(this, true);
		} catch (e) {
			error = e;
		}

		this.reloading = false;
	} else {
		error = new Error('Module \'' + this.name + '\' is not loaded!');
	}

	logger.debug('Context reload of \'' + this.name + '\' module.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

Module.prototype.injectConfig = function injectConfig(config) {
	var error = null;
	if (!(config instanceof Object)) {
		error = new Error('Config needs to be object!');
	} else {
		if (typeof config[this.name] !== 'object') config[this.name] = {};

		Object.defineProperty(this, 'config', {
			writable: false,
			configurable: false,
			enumerable: true,
			value: config[this.name]
		});
	}

	logger.debug('Module \'' + this.name + '\' Config inject.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

Module.prototype.injectDispatcher = function injectDispatcher(dispatchBase) {
	var error = null;
	if (!(dispatchBase instanceof EventEmitter)) {
		error = new Error('Wrong dispatcher type for \'' + this.name + '\' module injected!');
	} else {
		var events = [];
		var eventTest = new RegExp('^' + this.name + '/');
		var module = this;
		this.dispatcher = {
			on: function(event, listener) {
				events.push({
					event: event,
					listener: listener
				});
				dispatchBase.on(event, listener);
				return this;
			},
			once: function(event, listener) {
				events.push({
					event: event,
					listener: listener
				});
				dispatchBase.once(event, listener);
				return this;
			},
			off: function(event, listener) {
				return this.removeListener(event, listener);
			},
			addListener: function(event, listener) {
				events.push({
					event: event,
					listener: listener
				});
				dispatchBase.addListener(event, listener);
				return this;
			},
			removeListener: function(event, listener) {
				events.some(function(obj, i) {
					if (obj.event === event && obj.listener === listener) {
						events.splice(i, 1);
						return true;
					}
					return false;
				});
				dispatchBase.removeListener(event, listener);
				return this;
			},
			emit: function(event) {
				var args;
				//all emited events needs to be prefixed by module name
				if (!(eventTest.test(event))) {
					event = module.name + '/' + event;
					args = Array.prototype.slice.call(arguments, 1); //convert arguments to Array and remove first argument
					args.unshift(event); //put new event as first argument
				}
				try {
					dispatchBase.emit.apply(dispatchBase, args || arguments);
				} catch (e) {
					dispatchBase.emit.call(dispatchBase, 'dispatchError', e, event, module);
				}
				return this;
			},
			clearEvents: function() {
				events.forEach(function(event) {
					dispatchBase.removeListener(event.event, event.listener);
				});
				events = [];
				return this;
			}
		};
	}

	logger.debug('Module \'' + this.name + '\' dispatcher inject.' + (error ? ' With error: ' + error.message : ''));

	if (error) throw error;

	return this;
};

/**
 * unload helper
 * @internal
 * @return void
 */
Module.prototype.__unload = function __unload() {
	if (this.loaded) {
		//remove from node require cache
		var module = require.cache[this.filename];
		module.children.forEach(function(m) {
			delete require.cache[m.filename];
		});
		delete require.cache[this.filename];

		this.loaded = false;
		this.context = null;
	}
};

/**
 * load helper
 * @internal
 * @throws Error
 * @return void
 */
Module.prototype.__load = function __load() {
	if (!this.loaded) {
		try {
			this.context = require(this.filename);
		} catch (e) {
			this.context = null;
			throw e;
		}

		if (typeof this.context === 'object' && this.context !== null) {
			this.loaded = true;
		} else {
			this.context = null;
		}
	}
};

Module.prototype.valueOf = Module.prototype.toString = function toString() {
	return this.name;
};

module.exports.Module = Module;
module.exports.create = function createModule(name, module_dir) {
	return new Module(name, module_dir);
};<|endoftext|>


<commit_before>//
// load projects when manage projects is clicked
//
var TFS = Titanium.Filesystem;
var TiDeveloper  = {};
TiDeveloper.currentPage = 1;
TiDeveloper.init = false;

// holder var for all projects
TiDeveloper.ProjectArray = [];
var db = openDatabase("TiDeveloper","1.0");
var highestId = 0;

// State Machine for UI tab state
TiDeveloper.stateMachine = new App.StateMachine('ui_state');
TiDeveloper.stateMachine.addState('manage','l:menu[val=manage]',false);
TiDeveloper.stateMachine.addState('create','l:menu[val=create]',false);
TiDeveloper.stateMachine.addState('api','l:menu[val=api]',false);
TiDeveloper.stateMachine.addState('interact','l:menu[val=interact]',true);
TiDeveloper.currentState = null;
TiDeveloper.stateMachine.addListener(function()
{
	var state = this.getActiveState();
	if (state != 'interact')
	{
		TiDeveloper.startIRCTrack();
	}
	else
	{
		TiDeveloper.stopIRCTrack();

	}
});
TiDeveloper.ircMessageCount = 0;
TiDeveloper.startIRCTrack = function()
{
	// TiDeveloper.ircMessageCount = 0;
	// $('#irc_message_count').html('');
	$('#irc_message_count').css('display','inline');

};
TiDeveloper.stopIRCTrack = function()
{
	TiDeveloper.ircMessageCount = 0;
	$('#irc_message_count').css('display','none');
	$('#irc_message_count').html('');

};

function createRecord(name,dir)
{
	var record = {
		name: name,
		dir: dir,
		id: highestId++,
		date: new Date().getTime()
	};
	TiDeveloper.ProjectArray.push(record);
    db.transaction(function (tx)
    {
        tx.executeSql("INSERT INTO Projects (id, timestamp, name, directory) VALUES (?, ?, ?, ?)", [record.id, record.date, record.name, record.dir]);
    });
}

function loadProjects()
{
	db.transaction(function(tx)
	{
        tx.executeSql("SELECT id, timestamp, name, directory FROM Projects", [], function(tx, result)
		{
            for (var i = 0; i < result.rows.length; ++i) {
                var row = result.rows.item(i);
				TiDeveloper.ProjectArray.push({
					id: row['id'],
					date: row['timestamp'],
					name: row['name'],
					dir: row['directory']
				});
				if (highestId < row['id'])
				{
					highestId = row['id'];
				}
            }
        }, function(tx, error) {
            alert('Failed to retrieve projects from database - ' + error.message);
            return;
        });
	});
}

db.transaction(function(tx)
{
   tx.executeSql("SELECT COUNT(*) FROM Projects", [], function(result)
   {
       loadProjects();
   }, function(tx, error)
   {
       tx.executeSql("CREATE TABLE Projects (id REAL UNIQUE, timestamp REAL, name TEXT, directory TEXT)", [], function(result)
	   {
          loadProjects();
       });
   });
});

//
//  create.project service
//
$MQL('l:create.project.request',function(msg)
{
	try
	{
		var result = Titanium.Project.create(msg.payload.project_name,msg.payload.project_location);
		if (result.success)
		{
			createRecord(result.name,result.basedir);
			$MQ('l:create.project.response',{result:'success'});
			$MQ('l:project.list.response',{page:1,totalRecords:TiDeveloper.ProjectArray.length,'rows':TiDeveloper.ProjectArray})
		}
		else
		{
			$MQ('l:create.project.response',{result:'error',message:result.message});
		}
	}
	catch(E)
	{
		alert('Exception = '+E);
	}
});

//
// Handling paging requests
//
$MQL('l:page.data.request',function(msg)
{
	var state =msg.payload
	var rowsPerPage = state.rowsPerPage
	var page = state.page
	TiDeveloper.currentPage = page;
	var data = TiDeveloper.getProjectPage(rowsPerPage,page);
	$MQ('l:project.list.response',{page:page,totalRecords:TiDeveloper.ProjectArray.length,'rows':data})
});

TiDeveloper.formatDirectory =function(dir)
{
	var dirStr = dir
	if (dir.length > 40)
	{
		dirStr = dir.substring(0,40) + '...';
		$('#project_detail_dir_a').css('display','block');
		$('#project_detail_dir_span').css('display','none');
		$('#project_detail_dir_a').html(dirStr);
	}
	else
	{
		$('#project_detail_dir_span').css('display','block');
		$('#project_detail_dir_a').css('display','none');
		$('#project_detail_dir_span').html(dirStr);
	}
}
//
// Get a page of data
//
TiDeveloper.getProjectPage = function(pageSize,page)
{
	var pageData = [];
	var start = (page==0)?0:(pageSize * page) - pageSize;
	var end = ((pageSize * page) > TiDeveloper.ProjectArray.length)?TiDeveloper.ProjectArray.length:(pageSize * page);
	for (var i=start;i<end;i++)
	{
		pageData.push(TiDeveloper.ProjectArray[i])
	}
	return pageData
};

//
// Load initial projects
//
$MQL('l:menu',function(msg)
{
	if (msg.payload.val == 'manage' && TiDeveloper.init == false)
	{
		var data = TiDeveloper.getProjectPage(10,0)
		$MQ('l:project.list.response',{totalRecords:TiDeveloper.ProjectArray.length,'rows':data});
		TiDeveloper.init=true;
	}
});
//
//  Project Package Request - get details about modules, etc
//
$MQL('l:package.project.request',function(msg)
{
	$MQ('l:package.project.data',{rows:[
	{name:'Titanium Runtime'},
	{name:'Ruby Language Module'},
	{name:'Python'},
	{name:'network'},
	{name:'file'},
	{name:'chat'},
	{name:'java'},
	{name:'php'},
	{name:'desktop_core'},
	{name:'custom_module_1'},
	{name:'custom_module_2'},
	{name:'custom_module_3'},
	{name:'custom_module_4'}

	]})
});

function findProject(name)
{
	for (var i=0;i<TiDeveloper.ProjectArray.length;i++)
	{
		if (TiDeveloper.ProjectArray[i].name == name)
		{
			return TiDeveloper.ProjectArray[i];
		}
	}
	return null;
}

//
// Create Package Request
//
$MQL('l:create.package.request',function(msg)
{
	// elements that are included for network bundle
	var network = $("div[state='network']").length;

	// elements that are included (bundled)
	var bundled = $("div[state='bundled']").length;

	// project name
	var project = $('#package_project_name').html();

	var launch = msg.payload.launch;

	if (msg.payload.launch ==true)
	{
		// do  launch
		var dest = Titanium.Process.getEnv('KR_RUNTIME');
		var runtimeDir = TFS.getFile(dest);
		var ext = (Titanium.platform == 'win32') ? '.exe' : '';
		var exec = TFS.getFile(runtimeDir,'template','kboot'+ext);
		var proj = findProject(project);
		// try
		// 		{
		// 			Titanium.Process.launch(String(exec),'--start="'+proj.dir+'"');
		// 		}
		// 		catch (E)
		// 		{
		// 			alert("Error: "+E);
		// 		}
	}
	else
	{

	}
})

//
//  Delete a project
//
$MQL('l:delete.project.request',function(msg)
{
	var name = msg.payload.name;
	var id = msg.payload.id
	if (confirm('Are you sure you want to delete project: ' + name + '?')==true)
	{
		for (var i=0;i<TiDeveloper.ProjectArray.length;i++)
		{
			if (TiDeveloper.ProjectArray[i].id == id)
			{
				TiDeveloper.ProjectArray.splice(i,1);
				break;
			}
		}
	}
	var data = TiDeveloper.getProjectPage(10,TiDeveloper.currentPage);
	$MQ('l:project.list.response',{page:TiDeveloper.currentPage,totalRecords:TiDeveloper.ProjectArray.length,'rows':data})
})
//
// project search request
//
$MQL('l:project.search.request',function(msg)
{
	var q = msg.payload.search_value;

	db.transaction(function(tx)
	{
		try
		{
	        tx.executeSql("SELECT id, timestamp, name, directory FROM Projects where name LIKE 'foobar'", [], function(tx, result)
			{
				try
				{
					var results = [];
		            for (var i = 0; i < result.rows.length; ++i) {
		                var row = result.rows.item(i);
						results.push({
							id: row['id'],
							date: row['timestamp'],
							name: row['name'],
							dir: row['directory']
						});
					}
					$MQ('l:project.search.response',{totalRecords:results.length,'rows':results});
				}
				catch (EX)
				{
					alert("EXCEPTION = "+EX);
				}
			});
		}
		catch (E)
		{
			alert("E="+e);
		}
	});
})

//
// Show file dialog and send value
//
$MQL('l:show.filedialog',function()
{
	var files = Titanium.UI.openFiles({directories:true});
	var val = files.length ? files[0] : '';
	$MQ('l:file.selected',{value:val});
})

setTimeout(function()
{
	try
	{
		var myNick = Titanium.Platform.username+'1';
		var myName = Titanium.Platform.username+'1';
		var myNameStr = Titanium.Platform.username+'1';

		$('#irc').append('
you are joining the room. one moment...
');

		var irc = Titanium.Network.createIRCClient();
		irc.connect("irc.freenode.net",6667,myNick,myName,myNameStr,String(new Date().getTime()),function(cmd,channel,data,nick)
		{
			// switch on command
			switch(cmd)
			{
				case 'PRIVMSG':
				{
					TiDeveloper.ircMessageCount ++;
					$('#irc_message_count').html(TiDeveloper.ircMessageCount);

					$('#irc').append('
' + nick + ': ' + channel.substring(1,channel.length) + '
');
					break;
				}
				case '366':
				{
					var users = irc.getUsers('#titanium_dev')
					$MQ('l:online.count',{count:users.length})
					for (var i=0;i<users.length;i++)
					{
						if (users[i].operator == true)
						{
							$('#irc_users').append('
(op) '+users[i].name+'
');
						}
						else if (users[i].voice==true)
						{
							$('#irc_users').append('
(v) '+users[i].name+'
');
						}
						else
						{
							$('#irc_users').append('
'+users[i].name+'
');
						}
					}
				}
				case 'JOIN':
				{
					if (nick.indexOf('freenode.net') != -1)
					{
						continue;
					}

					if (nick == myNick)
					{
						$('#irc').append('
 you are now in the room.
');
						break
					}
					$('#irc').append('
' + nick + ' has joined the room
');
					$('#irc_users').append('
'+nick+'
');
					break;

				}
				case 'PART':
				{
					$('#irc').append('
' + nick + ' has left the room
');
					$('.'+nick).html('');
					break;

				}
			}
//			$('#irc').append('
'+cmd+"=>"+channel+':'+data+ ' ' + nick + '
');
			$('#irc').get(0).scrollTop = $('#irc').get(0).scrollHeight;
		});

		irc.join("#titanium_dev");
		$('#irc_send').click(function()
		{
			irc.send('#titanium_dev',$('#irc_msg').val());
			$('#irc').append('
'+myNick + ': ' + $('#irc_msg').val() + '
');
			$('#irc_msg').val('');
			$('#irc').get(0).scrollTop = $('#irc').get(0).scrollHeight;

		})
	}
	catch(E)
	{
		alert("Exception: "+E);
	}
},1000);

<commit_msg>minor fixes<commit_after>//
// load projects when manage projects is clicked
//
var TFS = Titanium.Filesystem;
var TiDeveloper  = {};
TiDeveloper.currentPage = 1;
TiDeveloper.init = false;

// holder var for all projects
TiDeveloper.ProjectArray = [];
var db = openDatabase("TiDeveloper","1.0");
var highestId = 0;

// State Machine for UI tab state
TiDeveloper.stateMachine = new App.StateMachine('ui_state');
TiDeveloper.stateMachine.addState('manage','l:menu[val=manage]',false);
TiDeveloper.stateMachine.addState('create','l:menu[val=create]',false);
TiDeveloper.stateMachine.addState('api','l:menu[val=api]',false);
TiDeveloper.stateMachine.addState('interact','l:menu[val=interact]',true);
TiDeveloper.currentState = null;
TiDeveloper.stateMachine.addListener(function()
{
	var state = this.getActiveState();
	if (state != 'interact')
	{
		TiDeveloper.startIRCTrack();
	}
	else
	{
		TiDeveloper.stopIRCTrack();

	}
});
TiDeveloper.ircMessageCount = 0;
TiDeveloper.startIRCTrack = function()
{
	// TiDeveloper.ircMessageCount = 0;
	// $('#irc_message_count').html('');
	$('#irc_message_count').css('display','inline');

};
TiDeveloper.stopIRCTrack = function()
{
	TiDeveloper.ircMessageCount = 0;
	$('#irc_message_count').css('display','none');
	$('#irc_message_count').html('');

};

function createRecord(name,dir)
{
	var record = {
		name: name,
		dir: dir,
		id: highestId++,
		date: new Date().getTime()
	};
	TiDeveloper.ProjectArray.push(record);
    db.transaction(function (tx)
    {
        tx.executeSql("INSERT INTO Projects (id, timestamp, name, directory) VALUES (?, ?, ?, ?)", [record.id, record.date, record.name, record.dir]);
    });
}

function loadProjects()
{
	db.transaction(function(tx)
	{
        tx.executeSql("SELECT id, timestamp, name, directory FROM Projects", [], function(tx, result)
		{
            for (var i = 0; i < result.rows.length; ++i) {
                var row = result.rows.item(i);
				TiDeveloper.ProjectArray.push({
					id: row['id'],
					date: row['timestamp'],
					name: row['name'],
					dir: row['directory']
				});
				if (highestId < row['id'])
				{
					highestId = row['id'];
				}
            }
        }, function(tx, error) {
            alert('Failed to retrieve projects from database - ' + error.message);
            return;
        });
	});
}

db.transaction(function(tx)
{
   tx.executeSql("SELECT COUNT(*) FROM Projects", [], function(result)
   {
       loadProjects();
   }, function(tx, error)
   {
       tx.executeSql("CREATE TABLE Projects (id REAL UNIQUE, timestamp REAL, name TEXT, directory TEXT)", [], function(result)
	   {
          loadProjects();
       });
   });
});

//
//  create.project service
//
$MQL('l:create.project.request',function(msg)
{
	try
	{
		var result = Titanium.Project.create(msg.payload.project_name,msg.payload.project_location);
		if (result.success)
		{
			createRecord(result.name,result.basedir);
			$MQ('l:create.project.response',{result:'success'});
			$MQ('l:project.list.response',{page:1,totalRecords:TiDeveloper.ProjectArray.length,'rows':TiDeveloper.ProjectArray})
		}
		else
		{
			$MQ('l:create.project.response',{result:'error',message:result.message});
		}
	}
	catch(E)
	{
		alert('Exception = '+E);
	}
});

//
// Handling paging requests
//
$MQL('l:page.data.request',function(msg)
{
	var state =msg.payload
	var rowsPerPage = state.rowsPerPage
	var page = state.page
	TiDeveloper.currentPage = page;
	var data = TiDeveloper.getProjectPage(rowsPerPage,page);
	$MQ('l:project.list.response',{page:page,totalRecords:TiDeveloper.ProjectArray.length,'rows':data})
});

TiDeveloper.formatDirectory =function(dir)
{
	var dirStr = dir
	if (dir.length > 40)
	{
		dirStr = dir.substring(0,40) + '...';
		$('#project_detail_dir_a').css('display','block');
		$('#project_detail_dir_span').css('display','none');
		$('#project_detail_dir_a').html(dirStr);
	}
	else
	{
		$('#project_detail_dir_span').css('display','block');
		$('#project_detail_dir_a').css('display','none');
		$('#project_detail_dir_span').html(dirStr);
	}
}
//
// Get a page of data
//
TiDeveloper.getProjectPage = function(pageSize,page)
{
	var pageData = [];
	var start = (page==0)?0:(pageSize * page) - pageSize;
	var end = ((pageSize * page) > TiDeveloper.ProjectArray.length)?TiDeveloper.ProjectArray.length:(pageSize * page);
	for (var i=start;i<end;i++)
	{
		pageData.push(TiDeveloper.ProjectArray[i])
	}
	return pageData
};

//
// Load initial projects
//
$MQL('l:menu',function(msg)
{
	if (msg.payload.val == 'manage' && TiDeveloper.init == false)
	{
		var data = TiDeveloper.getProjectPage(10,0)
		$MQ('l:project.list.response',{totalRecords:TiDeveloper.ProjectArray.length,'rows':data});
		TiDeveloper.init=true;
	}
});
//
//  Project Package Request - get details about modules, etc
//
$MQL('l:package.project.request',function(msg)
{
	$MQ('l:package.project.data',{rows:[
	{name:'Titanium Runtime'},
	{name:'Ruby Language Module'},
	{name:'Python'},
	{name:'network'},
	{name:'file'},
	{name:'chat'},
	{name:'java'},
	{name:'php'},
	{name:'desktop_core'},
	{name:'custom_module_1'},
	{name:'custom_module_2'},
	{name:'custom_module_3'},
	{name:'custom_module_4'}

	]})
});

function findProject(name)
{
	for (var i=0;i<TiDeveloper.ProjectArray.length;i++)
	{
		if (TiDeveloper.ProjectArray[i].name == name)
		{
			return TiDeveloper.ProjectArray[i];
		}
	}
	return null;
}

//
// Create Package Request
//
$MQL('l:create.package.request',function(msg)
{
	// elements that are included for network bundle
	var network = $("div[state='network']").length;

	// elements that are included (bundled)
	var bundled = $("div[state='bundled']").length;

	// project name
	var project = $('#package_project_name').html();

	var launch = msg.payload.launch;

	if (msg.payload.launch ==true)
	{
		// do  launch
		var dest = Titanium.Process.getEnv('KR_RUNTIME');
		var runtimeDir = TFS.getFile(dest);
		var ext = (Titanium.platform == 'win32') ? '.exe' : '';
		var exec = TFS.getFile(runtimeDir,'template','kboot'+ext);
		var proj = findProject(project);
		// try
		// 		{
		// 			Titanium.Process.launch(String(exec),'--start="'+proj.dir+'"');
		// 		}
		// 		catch (E)
		// 		{
		// 			alert("Error: "+E);
		// 		}
	}
	else
	{

	}
})

//
//  Delete a project
//
$MQL('l:delete.project.request',function(msg)
{
	var name = msg.payload.name;
	var id = msg.payload.id
	if (confirm('Are you sure you want to delete project: ' + name + '?')==true)
	{
		for (var i=0;i<TiDeveloper.ProjectArray.length;i++)
		{
			if (TiDeveloper.ProjectArray[i].id == id)
			{
				TiDeveloper.ProjectArray.splice(i,1);
				break;
			}
		}
	}
	var data = TiDeveloper.getProjectPage(10,TiDeveloper.currentPage);
	$MQ('l:project.list.response',{page:TiDeveloper.currentPage,totalRecords:TiDeveloper.ProjectArray.length,'rows':data})
})
//
// project search request
//
$MQL('l:project.search.request',function(msg)
{
	var q = msg.payload.search_value;

	db.transaction(function(tx)
	{
		try
		{
	        tx.executeSql("SELECT id, timestamp, name, directory FROM Projects where name LIKE 'foobar'", [], function(tx, result)
			{
				try
				{
					var results = [];
		            for (var i = 0; i < result.rows.length; ++i) {
		                var row = result.rows.item(i);
						results.push({
							id: row['id'],
							date: row['timestamp'],
							name: row['name'],
							dir: row['directory']
						});
					}
					$MQ('l:project.search.response',{totalRecords:results.length,'rows':results});
				}
				catch (EX)
				{
					alert("EXCEPTION = "+EX);
				}
			});
		}
		catch (E)
		{
			alert("E="+e);
		}
	});
})

//
// Show file dialog and send value
//
$MQL('l:show.filedialog',function()
{
	var files = Titanium.UI.openFiles({directories:true});
	var val = files.length ? files[0] : '';
	$MQ('l:file.selected',{value:val});
})

var irc_count = 0;

setTimeout(function()
{
	try
	{
		var myNick = Titanium.Platform.username+'1';
		var myName = Titanium.Platform.username+'1';
		var myNameStr = Titanium.Platform.username+'1';

		$('#irc').append('
you are joining the room. one moment...
');

		var irc = Titanium.Network.createIRCClient();
		irc.connect("irc.freenode.net",6667,myNick,myName,myNameStr,String(new Date().getTime()),function(cmd,channel,data,nick)
		{
			// switch on command
			switch(cmd)
			{
				case 'NOTICE':
				case 'PRIVMSG':
				{
					if (nick)
					{
						TiDeveloper.ircMessageCount ++;
						$('#irc_message_count').html(TiDeveloper.ircMessageCount);
						$('#irc').append('
' + nick + ': ' + channel.substring(1,channel.length) + '
');
					}
					break;
				}
				case '366':
				{
					var users = irc.getUsers('#titanium_dev');
					$MQ('l:online.count',{count:users.length});
					irc_count = users.length;
					for (var i=0;i<users.length;i++)
					{
						if (users[i].operator == true)
						{
							$('#irc_users').append('
'+users[i].name+'(op)
');
						}
						else if (users[i].voice==true)
						{
							$('#irc_users').append('
'+users[i].name+'(v)
');
						}
						else
						{
							$('#irc_users').append('
'+users[i].name+'
');
						}
					}
				}
				case 'JOIN':
				{
					if (nick.indexOf('freenode.net') != -1)
					{
						continue;
					}

					if (nick == myNick)
					{
						$('#irc').append('
 you are now in the room.
');
						break
					}
					else
					{
						irc_count++;
					}
					$('#irc').append('
' + nick + ' has joined the room
');
					$('#irc_users').append('
'+nick+'
');
					$MQ('l:online.count',{count:irc_count});
					break;

				}
				case 'PART':
				{
					$('#irc').append('
' + nick + ' has left the room
');
					$('.'+nick).html('');
					irc_count--;
					$MQ('l:online.count',{count:irc_count});
					break;

				}
			}
			$('#irc').get(0).scrollTop = $('#irc').get(0).scrollHeight;
		});

		irc.join("#titanium_dev");
		$('#irc_send').click(function()
		{
			irc.send('#titanium_dev',$('#irc_msg').val());
			$('#irc').append('
'+myNick + ': ' + $('#irc_msg').val() + '
');
			$('#irc_msg').val('');
			$('#irc').get(0).scrollTop = $('#irc').get(0).scrollHeight;

		})
	}
	catch(E)
	{
		alert("Exception: "+E);
	}
},1000);

<|endoftext|>


<commit_before>import Ajv from 'ajv';

/**
 * Schema validation middleware and helper functions
 */
let schema = {

    compileJsonSchema(inputSchema) {
        let ajv = new Ajv();
        return ajv.compile(inputSchema);
    },

    validateJson(compiledSchema, jsonBody) {
        return compiledSchema(jsonBody);
    },

    getSchemaError(compiledSchema) {
        let ajv = new Ajv();
        return ajv.errorsText(compiledSchema.errors);
    },

    validateBody(inputSchema) {
        return function (req, res, next) {
            let compiledSchema = compileJsonSchema(inputSchema);
            let valid = validateJson(compiledSchema, req.body);
            if (!valid) {
                return res.status(400).send({error: getValidateError(valid)});
            } else {
                return next();
            }
        };
    }

};

export default schema;
<commit_msg>Fix libs/schema ambiguous/wrong references.<commit_after>import Ajv from 'ajv';

/**
 * Schema validation middleware and helper functions
 */
let schema = {

    compileJsonSchema(inputSchema) {
        let ajv = new Ajv();
        return ajv.compile(inputSchema);
    },

    validateJson(compiledSchema, jsonBody) {
        return compiledSchema(jsonBody);
    },

    getSchemaError(compiledSchema) {
        let ajv = new Ajv();
        return ajv.errorsText(compiledSchema.errors);
    },

    validateBody(inputSchema) {
        return function (req, res, next) {
            let compiledSchema = schema.compileJsonSchema(inputSchema);
            let valid = schema.validateJson(compiledSchema, req.body);
            if (!valid) {
                return res.status(400).send({error: schema.getSchemaError(valid)});
            } else {
                return next();
            }
        };
    }

};

export default schema;
<|endoftext|>


<commit_before>import R from "ramda";
import log from "./log";

const delay = (msecs, func) => global.setTimeout(func, msecs);

/**
 * Manages actions that change the state of the service.
 *
 * @param {Object} settings:
 *                  - apps:     Collection of apps to start.
 *                  - mainApi:  The main API.
 *
 */
export default (settings = {}) => {
  const { apps, mainApi } = settings;

  const getApp = (req, res) => {
        const id = req.params.app;
        const app = R.find(item => item.id === id, apps);
        if (app) {
          return app;
        } else {
          res.status(404).send({ message: `The app '${ id }' does not exist.` });
        }
      };

  // API.
  return {
    /**
     * Restarts the gateway and all apps.
     */
    restart(req, res) {
      log.info(`API: Restarting the gateway and all apps.`);
      res.send({ message: "Restarting..." });
      delay(200, () => {
        mainApi
          .restart()
          .catch(err => res.status(500).send({ message: err.message }));
      });
    },

    /**
     * Restarts the app on all containers.
     */
    restartApp(req, res) {
      const app = getApp(req, res);
      if (app) {
        log.info(`API: Restarting app '${ app.id }'...`);
        app.restart()
          .then(result => {
              res.send({ app: app.id, restarted: true, version: result.version });
              log.info(`API:...Restarted app '${ app.id }'.`);
          })
          .catch(err => res.status(500).send({ message: err.message }));
      }
    },

    /**
     * Checks for updates for the app.
     */
    update(req, res) {
      const app = getApp(req, res);
      if (app) {
        log.info(`API: Updating app '${ app.id }'...`);
        app.update()
          .then(result => {
              res.send({ app: app.id, updated: result.updated, version: result.version });
              log.info(`API:...Updated app '${ app.id }'.`);
          })
          .catch(err => res.status(500).send({ message: err.message }));
      }
    }
  };
};
<commit_msg>Improve output log message for app/update<commit_after>import R from "ramda";
import log from "./log";

const delay = (msecs, func) => global.setTimeout(func, msecs);

/**
 * Manages actions that change the state of the service.
 *
 * @param {Object} settings:
 *                  - apps:     Collection of apps to start.
 *                  - mainApi:  The main API.
 *
 */
export default (settings = {}) => {
  const { apps, mainApi } = settings;

  const getApp = (req, res) => {
        const id = req.params.app;
        const app = R.find(item => item.id === id, apps);
        if (app) {
          return app;
        } else {
          res.status(404).send({ message: `The app '${ id }' does not exist.` });
        }
      };

  // API.
  return {
    /**
     * Restarts the gateway and all apps.
     */
    restart(req, res) {
      log.info(`API: Restarting the gateway and all apps.`);
      res.send({ message: "Restarting..." });
      delay(200, () => {
        mainApi
          .restart()
          .catch(err => res.status(500).send({ message: err.message }));
      });
    },

    /**
     * Restarts the app on all containers.
     */
    restartApp(req, res) {
      const app = getApp(req, res);
      if (app) {
        log.info(`API: Restarting app '${ app.id }'...`);
        app.restart()
          .then(result => {
              res.send({ app: app.id, restarted: true, version: result.version });
              log.info(`API:...Restarted app '${ app.id }'.`);
          })
          .catch(err => res.status(500).send({ message: err.message }));
      }
    },

    /**
     * Checks for updates for the app.
     */
    update(req, res) {
      const app = getApp(req, res);
      if (app) {
        log.info(`API: Updating app '${ app.id }'...`);
        app.update()
          .then(result => {
              res.send({ app: app.id, updated: result.updated, version: result.version });
              const msg = result.updated
                ? `API: ...updated app '${ app.id }' to version ${ result.version }.`
                : `API: ...did not update app '${ app.id }', latest version ${ result.version } already running.`
              log.info(msg);
          })
          .catch(err => res.status(500).send({ message: err.message }));
      }
    }
  };
};
<|endoftext|>