<commit_before>'use strict';

/**
 * Testing library: runner for tests.
 * (C) 2013 Alex Fernández.
 */

// requires
var Log = require('log');
var util = require('util');

// globals
var log = new Log('info');
var next;

// constants
var GREEN = '\u001b[32m';
var RED = '\u001b[1;31m';
var PURPLE = '\u001b[1;35m';
var BLACK = '\u001b[0m';
var SUCCESS_START = GREEN + '✓ ';
var END = BLACK;
var FAILURE_START = RED + '✕ ';
var UNKNOWN_START = PURPLE + '? ';
var INVALID_START = PURPLE + '??? ';
var SEPARATOR = ': ';

/**
 * A test result.
 */
var TestResult = function(key)
{
	// self-reference
	var self = this;

	// attributes
	self.key = key;
	self.success = false;
	self.failure = false;
	self.message = null;
	var finished = false;

	/**
	 * Callback for the test result.
	 * Can only be called once.
	 */
	self.callback = function(error, result)
	{
		if (error)
		{
			// only report the first failure
			if (!self.failure)
			{
				fail(error);
			}
		}
		else
		{
			if (!result)
			{
				return fail('Empty result');
			}
			if (result.failure)
			{
				return fail(result);
			}
			return succeed(result);
		}
	}

	/**
	 * Report a failure.
	 */
	function fail(message)
	{
		self.failure = true;
		self.success = false;
		self.message = message;
		finished = true;
	}

	/**
	 * Report a success.
	 */
	function succeed(message)
	{
		if (finished)
		{
			// only one success allowed
			self.failure = true;
			self.success = false;
			self.message = 'Duplicated call to callback';
			return;
		}
		self.success = true;
		self.message = message;
		finished = true;
	}

	/**
	 * Return a printable representation.
	 */
	self.toString = function(indent)
	{
		var message = self.key;
		if (self.message)
		{
			message += SEPARATOR + self.message;
		}
		return getPrintable(self, message, indent);
	}
}

/**
 * A result that contains other results.
 */
var CompositeResult = function(key)
{
	// self-reference
	var self = this;

	// attributes
	self.key = key;
	self.success = false;
	self.failure = false;
	self.failures = 0;
	self.results = {};

	/**
	 * Add a sub-result.
	 */
	self.add = function(result)
	{
		self.results[result.key] = result;
		if (result.success && !self.failure)
		{
			self.success = true;
		}
		if (result.failure)
		{
			self.success = false;
			self.failure = true;
		}
	}

	/**
	 * Return a printable representation.
	 */
	self.toString = function(indent)
	{
		indent = indent || 0;
		var message = getPrintable(self, self.key + SEPARATOR, indent) + '\n';
		message += getIndented(indent) + '{\n';
		for (var key in self.results)
		{
			var result = self.results[key];
			message += result.toString(indent + 1) + ',\n';
		}
		message += getIndented(indent) + '}';
		return message
	}
}

/**
 * Get the printable representation for a result, like this:
 * START message END.
 * An optional indent is applied as an equivalent number of tabs.
 */
function getPrintable(result, message, indent)
{
	var start;
	if (!result.failure && !result.success)
	{
		start = UNKNOWN_START;
	}
	else if (result.success && result.failure)
	{
		start = INVALID_START;
	}
	else if (result.success)
	{
		start = SUCCESS_START;
	}
	else
	{
		start = FAILURE_START;
	}
	return getIndented(indent) + start + message + END;
}

/**
 * Get an indented string, with an equivalent number of tabs.
 */
function getIndented(indent)
{
	var indented = '';
	if (indent)
	{
		for (var i = 0; i < indent; i++)
		{
			indented += '\t';
		}
	}
	return indented;
}

/**
 * Run a series of functions sequentially. Parameters:
 *	- param: an indexed object with functions, or with nested indexed objects.
 *	- callback: a function(error, result) to pass an indexed object with the results.
 */
exports.run = function(param, callback)
{
	var series = clone(param);
	// uncaught exceptions
	process.on('uncaughtException', function(error)
	{
		uncaughtException(error);
	});
	var runner = new Runner('success', series);
	runner.runAll(function(error, result)
	{
		if (result.failure)
		{
			result.key = 'failure';
		}
		callback(error, result);
	});
}

/**
 * Process an uncaught exception.
 */
function uncaughtException(error)
{
	if (!next)
	{
		return log.error('Exception without next text');
	}
	next('Uncaught exception: ' + error.stack);
}

/**
 * A runner for a series of tests.
 */
var Runner = function(key, series)
{
	// self-reference
	var self = this;

	// attributes
	self.result = new CompositeResult(key);
	var finished = false;

	/**
	 * Run all functions in the series, one by one.
	 */
	self.runAll = function(callback)
	{
		runOne(function(error, result)
		{
			if (finished)
			{
				return;
			}
			finished = true;
			callback(error, result);
		});
	}

	/**
	 * Run one function in the given series, go to the next.
	 */
	function runOne(callback)
	{
		if (isEmpty(series))
		{
			return callback(null, self.result);
		}
		for (var key in series)
		{
			var value = series[key];
			if (typeof value == 'object')
			{
				var runner = new Runner(key, value);
				runner.runAll(function(error, result)
				{
					if (error)
					{
						log.error('Could not run all functions');
						return;
					}
					self.result.add(runner.result);
					deleteAndRunNext(key, callback);
				});
			}
			else if (typeof value == 'function')
			{
				var subResult = new TestResult(key);
				// it is a function to run
				next = getNext(key, subResult, callback);
				value(next);
			}
			else
			{
				log.error('Invalid value %s', value);
				self.result.callback('Key %s has an invalid value %s');
				deleteAndRunNext(key, callback);
			}
			// only the first element in series is used;
			// the rest are called by recursion in deleteAndRunNext()
			return;
		}
	}

	/**
	 * Get a function to call after a test.
	 */
	function getNext(key, testResult, callback)
	{
		return function(error, result)
		{
			testResult.callback(error, result);
			self.result.add(testResult);
			deleteAndRunNext(key, callback);
		};
	}

	/**
	 * Delete the current function, run the next.
	 */
	function deleteAndRunNext(key, callback)
	{
		if (!(key in series))
		{
			// already run
			return;
		}
		delete series[key];
		return process.nextTick(function()
		{
			runOne(callback);
		});
	}
}

/**
 * Test to run some functions.
 */
function testRun()
{
	var series = {
		a: function(callback) {
			callback(null, 'a');
		},
		b: {
			e: function(callback) {
				callback('e');
			},
			c: function(callback) {
				callback(null, 'c');
			},
			f: function(callback) {
				throw new Error('exception');
			},
		},
	};
	exports.run(series, function(error, result)
	{
		console.assert(result.failure, 'Root should be failure');
		console.assert(result.results.a, 'Should have result for a');
		console.assert(result.results.a.success, 'Should have success for a');
		console.assert(result.results.a.message == 'a', 'Should have an a for a');
		console.assert(result.results.b, 'Should have result for b');
		console.assert(result.results.b.failure, 'Should have failure for b');
		console.assert(result.results.b.results.c, 'Should have result for b.c');
		console.assert(result.results.b.results.c.success, 'Should have success for b.c');
		console.assert(result.results.b.results.c.message == 'c', 'Should have a c for b.c');
		console.assert(result.results.b.results.e, 'Should have result for b.e');
		console.assert(result.results.b.results.e.failure, 'Should have failure for b.e');
		console.assert(result.results.b.results.e.message == 'e', 'Should have a e for b.e');
		log.info('Test run successful with 2 failures: %s', result);
	});
}

/**
 * Clone a series of functions. Performs a sanity check.
 */
function clone(series)
{
	if (typeof series != 'object')
	{
		log.error('Invalid series %s', JSON.stringify(series));
		return;
	}
	var copy = {};
	for (var key in series)
	{
		var value = series[key];
		if (typeof value == 'function')
		{
			copy[key] = value;
		}
		else
		{
			copy[key] = clone(value);
		}
	}
	return copy;
}

/**
 * Test the clone function.
 */
function testClone()
{
	var original = {
		a: function(parameter) {},
		b: {
			c: function(parameter) {},
		},
	};
	var cloned = clone(original);
	console.assert(cloned.a, 'Cloned object should have function property');
	console.assert(typeof cloned.a == 'function', 'Cloned object should have function');
	console.assert(cloned.b, 'Cloned object should have object property');
	console.assert(typeof cloned.b == 'object', 'Cloned object should have object');
	console.assert(cloned.b.c, 'Cloned object should have sub-object property');
	console.assert(typeof cloned.b.c == 'function', 'Cloned object should have sub-object');
}

/**
 * Find out if the object is empty.
 */
function isEmpty(object)
{
	for (var key in object)
	{
		if (object[key])
		{
			return false;
		}
	}
	return true;
}

/**
 * Test the empty function.
 */
function testEmpty()
{
	console.assert(isEmpty({}), 'Empty should be empty');
	console.assert(!isEmpty({a: 'a'}), 'Not empty is empty');
}

/**
 * Run all module tests.
 * Cannot use testing since it is not defined yet.
 */
function test()
{
	testEmpty();
	testClone();
	testRun();
}

// run tests if invoked directly
if (__filename == process.argv[1])
{
	test();
}

<commit_msg>Do not report failure on empty result, it is a valid result.<commit_after>'use strict';

/**
 * Testing library: runner for tests.
 * (C) 2013 Alex Fernández.
 */

// requires
var Log = require('log');
var util = require('util');

// globals
var log = new Log('info');
var next;

// constants
var GREEN = '\u001b[32m';
var RED = '\u001b[1;31m';
var PURPLE = '\u001b[1;35m';
var BLACK = '\u001b[0m';
var SUCCESS_START = GREEN + '✓ ';
var END = BLACK;
var FAILURE_START = RED + '✕ ';
var UNKNOWN_START = PURPLE + '? ';
var INVALID_START = PURPLE + '??? ';
var SEPARATOR = ': ';

/**
 * A test result.
 */
var TestResult = function(key)
{
	// self-reference
	var self = this;

	// attributes
	self.key = key;
	self.success = false;
	self.failure = false;
	self.message = null;
	var finished = false;

	/**
	 * Callback for the test result.
	 * Can only be called once.
	 */
	self.callback = function(error, result)
	{
		if (error)
		{
			// only report the first failure
			if (!self.failure)
			{
				fail(error);
			}
		}
		else
		{
			if (result && result.failure)
			{
				return fail(result);
			}
			return succeed(result);
		}
	}

	/**
	 * Report a failure.
	 */
	function fail(message)
	{
		self.failure = true;
		self.success = false;
		self.message = message;
		finished = true;
	}

	/**
	 * Report a success.
	 */
	function succeed(message)
	{
		if (finished)
		{
			// only one success allowed
			self.failure = true;
			self.success = false;
			self.message = 'Duplicated call to callback';
			return;
		}
		self.success = true;
		self.message = message;
		finished = true;
	}

	/**
	 * Return a printable representation.
	 */
	self.toString = function(indent)
	{
		var message = self.key;
		if (self.message)
		{
			message += SEPARATOR + self.message;
		}
		return getPrintable(self, message, indent);
	}
}

/**
 * A result that contains other results.
 */
var CompositeResult = function(key)
{
	// self-reference
	var self = this;

	// attributes
	self.key = key;
	self.success = false;
	self.failure = false;
	self.failures = 0;
	self.results = {};

	/**
	 * Add a sub-result.
	 */
	self.add = function(result)
	{
		self.results[result.key] = result;
		if (result.success && !self.failure)
		{
			self.success = true;
		}
		if (result.failure)
		{
			self.success = false;
			self.failure = true;
		}
	}

	/**
	 * Return a printable representation.
	 */
	self.toString = function(indent)
	{
		indent = indent || 0;
		var message = getPrintable(self, self.key + SEPARATOR, indent) + '\n';
		message += getIndented(indent) + '{\n';
		for (var key in self.results)
		{
			var result = self.results[key];
			message += result.toString(indent + 1) + ',\n';
		}
		message += getIndented(indent) + '}';
		return message
	}
}

/**
 * Get the printable representation for a result, like this:
 * START message END.
 * An optional indent is applied as an equivalent number of tabs.
 */
function getPrintable(result, message, indent)
{
	var start;
	if (!result.failure && !result.success)
	{
		start = UNKNOWN_START;
	}
	else if (result.success && result.failure)
	{
		start = INVALID_START;
	}
	else if (result.success)
	{
		start = SUCCESS_START;
	}
	else
	{
		start = FAILURE_START;
	}
	return getIndented(indent) + start + message + END;
}

/**
 * Get an indented string, with an equivalent number of tabs.
 */
function getIndented(indent)
{
	var indented = '';
	if (indent)
	{
		for (var i = 0; i < indent; i++)
		{
			indented += '\t';
		}
	}
	return indented;
}

/**
 * Run a series of functions sequentially. Parameters:
 *	- param: an indexed object with functions, or with nested indexed objects.
 *	- callback: a function(error, result) to pass an indexed object with the results.
 */
exports.run = function(param, callback)
{
	var series = clone(param);
	// uncaught exceptions
	process.on('uncaughtException', function(error)
	{
		uncaughtException(error);
	});
	var runner = new Runner('success', series);
	runner.runAll(function(error, result)
	{
		if (result.failure)
		{
			result.key = 'failure';
		}
		callback(error, result);
	});
}

/**
 * Process an uncaught exception.
 */
function uncaughtException(error)
{
	if (!next)
	{
		return log.error('Exception without next text');
	}
	next('Uncaught exception: ' + error.stack);
}

/**
 * A runner for a series of tests.
 */
var Runner = function(key, series)
{
	// self-reference
	var self = this;

	// attributes
	self.result = new CompositeResult(key);
	var finished = false;

	/**
	 * Run all functions in the series, one by one.
	 */
	self.runAll = function(callback)
	{
		runOne(function(error, result)
		{
			if (finished)
			{
				return;
			}
			finished = true;
			callback(error, result);
		});
	}

	/**
	 * Run one function in the given series, go to the next.
	 */
	function runOne(callback)
	{
		if (isEmpty(series))
		{
			return callback(null, self.result);
		}
		for (var key in series)
		{
			var value = series[key];
			if (typeof value == 'object')
			{
				var runner = new Runner(key, value);
				runner.runAll(function(error, result)
				{
					if (error)
					{
						log.error('Could not run all functions');
						return;
					}
					self.result.add(runner.result);
					deleteAndRunNext(key, callback);
				});
			}
			else if (typeof value == 'function')
			{
				var subResult = new TestResult(key);
				// it is a function to run
				next = getNext(key, subResult, callback);
				value(next);
			}
			else
			{
				log.error('Invalid value %s', value);
				self.result.callback('Key %s has an invalid value %s');
				deleteAndRunNext(key, callback);
			}
			// only the first element in series is used;
			// the rest are called by recursion in deleteAndRunNext()
			return;
		}
	}

	/**
	 * Get a function to call after a test.
	 */
	function getNext(key, testResult, callback)
	{
		return function(error, result)
		{
			testResult.callback(error, result);
			self.result.add(testResult);
			deleteAndRunNext(key, callback);
		};
	}

	/**
	 * Delete the current function, run the next.
	 */
	function deleteAndRunNext(key, callback)
	{
		if (!(key in series))
		{
			// already run
			return;
		}
		delete series[key];
		return process.nextTick(function()
		{
			runOne(callback);
		});
	}
}

/**
 * Test to run some functions.
 */
function testRun()
{
	var series = {
		a: function(callback) {
			callback(null, 'a');
		},
		b: {
			e: function(callback) {
				callback('e');
			},
			c: function(callback) {
				callback(null, 'c');
			},
			f: function(callback) {
				throw new Error('exception');
			},
		},
	};
	exports.run(series, function(error, result)
	{
		console.assert(result.failure, 'Root should be failure');
		console.assert(result.results.a, 'Should have result for a');
		console.assert(result.results.a.success, 'Should have success for a');
		console.assert(result.results.a.message == 'a', 'Should have an a for a');
		console.assert(result.results.b, 'Should have result for b');
		console.assert(result.results.b.failure, 'Should have failure for b');
		console.assert(result.results.b.results.c, 'Should have result for b.c');
		console.assert(result.results.b.results.c.success, 'Should have success for b.c');
		console.assert(result.results.b.results.c.message == 'c', 'Should have a c for b.c');
		console.assert(result.results.b.results.e, 'Should have result for b.e');
		console.assert(result.results.b.results.e.failure, 'Should have failure for b.e');
		console.assert(result.results.b.results.e.message == 'e', 'Should have a e for b.e');
		log.info('Test run successful with 2 failures: %s', result);
	});
}

/**
 * Clone a series of functions. Performs a sanity check.
 */
function clone(series)
{
	if (typeof series != 'object')
	{
		log.error('Invalid series %s', JSON.stringify(series));
		return;
	}
	var copy = {};
	for (var key in series)
	{
		var value = series[key];
		if (typeof value == 'function')
		{
			copy[key] = value;
		}
		else
		{
			copy[key] = clone(value);
		}
	}
	return copy;
}

/**
 * Test the clone function.
 */
function testClone()
{
	var original = {
		a: function(parameter) {},
		b: {
			c: function(parameter) {},
		},
	};
	var cloned = clone(original);
	console.assert(cloned.a, 'Cloned object should have function property');
	console.assert(typeof cloned.a == 'function', 'Cloned object should have function');
	console.assert(cloned.b, 'Cloned object should have object property');
	console.assert(typeof cloned.b == 'object', 'Cloned object should have object');
	console.assert(cloned.b.c, 'Cloned object should have sub-object property');
	console.assert(typeof cloned.b.c == 'function', 'Cloned object should have sub-object');
}

/**
 * Find out if the object is empty.
 */
function isEmpty(object)
{
	for (var key in object)
	{
		if (object[key])
		{
			return false;
		}
	}
	return true;
}

/**
 * Test the empty function.
 */
function testEmpty()
{
	console.assert(isEmpty({}), 'Empty should be empty');
	console.assert(!isEmpty({a: 'a'}), 'Not empty is empty');
}

/**
 * Run all module tests.
 * Cannot use testing since it is not defined yet.
 */
function test()
{
	testEmpty();
	testClone();
	testRun();
}

// run tests if invoked directly
if (__filename == process.argv[1])
{
	test();
}

<|endoftext|>


<commit_before>/**
 * This plugin gives a 'close confirmation' when closing the IDE
 * @author Mostafa Eweda <mostafa@c9.io>
 * @copyright 2012, Cloud9 IDE, Inc.
 * @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
 */
"use strict";
define(function(require, exports, module) {
    main.consumes = [
        "plugin", "tabs", "settings", "preferences"
    ];
    main.provides = ["closeconfirmation"];
    return main;

    function main(options, imports, register) {
        var Plugin      = imports.plugin;
        var tabs        = imports.tabs;
        var settings    = imports.settings;
        var prefs       = imports.preferences;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit   = plugin.getEmitter();

        var loaded = false;
        function load(callback){
            if (loaded) return false;
            loaded = true;

            // when unloading the window
            window.onbeforeunload = onBeforeUnloadHandler;

            settings.on("read", function(){
                settings.setDefaults("user/general", [
                    ["confirmexit", "false"]
                ]);
            }, plugin);

            prefs.add({
                "General" : {
                    "General" : {
                        "Warn Before Exiting" : {
                            type     : "checkbox",
                            position : 8000,
                            path     : "user/general/@confirmexit"
                        }
                    }
                }
            }, plugin);
        }

        function unload() {
            if (window.onbeforeunload === onBeforeUnloadHandler)
                window.onbeforeunload = null;
        }

        /***** Methods *****/

        function onBeforeUnloadHandler() {
            var changed = false;
            tabs.getPages().forEach(function(page){
                changed = changed || (page.document.value && page.document.changed);
            });

            emit("exit", { changed: changed });

            if (changed)
                return "You have unsaved changes. Your changes will be lost if you don't save them";

            // see what's in the settings
            var confirmExit = settings.getBool("user/general/@confirmexit");
            if (confirmExit)
                return "You're about to leave Cloud9 IDE.";
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            unload();
            loaded = false;
        });

        /***** Register and define API *****/
        /**
         * Shows a 'close confirmation' popup when closing the IDE
         */
        plugin.freezePublicAPI({
        });

        register(null, {
            closeconfirmation: plugin
        });
    }
});
<commit_msg>Revert "Revert "Merge pull request +128 from c9/docs""<commit_after>/**
 * This plugin gives a 'close confirmation' when closing the IDE
 * @author Mostafa Eweda <mostafa@c9.io>
 * @copyright 2012, Cloud9 IDE, Inc.
 * @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
 */
"use strict";
define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "tabManager", "settings", "preferences"
    ];
    main.provides = ["closeconfirmation"];
    return main;

    function main(options, imports, register) {
        var Plugin      = imports.Plugin;
        var tabs        = imports.tabManager;
        var settings    = imports.settings;
        var prefs       = imports.preferences;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit   = plugin.getEmitter();

        var loaded = false;
        function load(callback){
            if (loaded) return false;
            loaded = true;

            // when unloading the window
            window.onbeforeunload = onBeforeUnloadHandler;

            settings.on("read", function(){
                settings.setDefaults("user/general", [
                    ["confirmexit", "false"]
                ]);
            }, plugin);

            prefs.add({
                "General" : {
                    "General" : {
                        "Warn Before Exiting" : {
                            type     : "checkbox",
                            position : 8000,
                            path     : "user/general/@confirmexit"
                        }
                    }
                }
            }, plugin);
        }

        function unload() {
            if (window.onbeforeunload === onBeforeUnloadHandler)
                window.onbeforeunload = null;
        }

        /***** Methods *****/

        function onBeforeUnloadHandler() {
            var changed = false;
            tabs.getTabs().forEach(function(tab){
                changed = changed || (tab.document.value && tab.document.changed);
            });

            emit("exit", { changed: changed });

            if (changed)
                return "You have unsaved changes. Your changes will be lost if you don't save them";

            // see what's in the settings
            var confirmExit = settings.getBool("user/general/@confirmexit");
            if (confirmExit)
                return "You're about to leave Cloud9 IDE.";
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            unload();
            loaded = false;
        });

        /***** Register and define API *****/
        /**
         * Shows a 'close confirmation' popup when closing the IDE
         */
        plugin.freezePublicAPI({
        });

        register(null, {
            closeconfirmation: plugin
        });
    }
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    "use strict";

    main.consumes = [
        "Plugin", "tabManager", "settings", "preferences", "auth"
    ];
    main.provides = ["closeconfirmation"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var tabs = imports.tabManager;
        var settings = imports.settings;
        var prefs = imports.preferences;
        var auth = imports.auth;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit = plugin.getEmitter();

        var defaultValue = options.defaultValue;

        var loaded = false;
        function load(callback) {
            if (loaded) return false;
            loaded = true;

            // when unloading the window
            window.onbeforeunload = onBeforeUnloadHandler;

            settings.on("read", function(){
                settings.setDefaults("user/general", [
                    ["confirmexit", defaultValue]
                ]);
            }, plugin);

            prefs.add({
                "General" : {
                    "General" : {
                        "Warn Before Exiting" : {
                            type: "checkbox",
                            position: 8000,
                            path: "user/general/@confirmexit"
                        }
                    }
                }
            }, plugin);
        }

        function unload() {
            if (window.onbeforeunload === onBeforeUnloadHandler)
                window.onbeforeunload = null;
        }

        /***** Methods *****/

        function onBeforeUnloadHandler() {
            var changed = tabs.getTabs().some(function(tab) {
                return tab.document.value && tab.document.changed;
            });

            emit("exit", { changed: changed });

            // see what's in the settings
            var confirmExit = settings.getBool("user/general/@confirmexit") && auth.loggedIn;
            if (confirmExit) {
                if (changed)
                    return "You have unsaved changes. Your changes will be lost if you don't save them";
                else
                    return "You're about to leave Cloud9.";
            }
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            unload();
            loaded = false;
        });

        /***** Register and define API *****/
        /**
         * Shows a 'close confirmation' popup when closing the IDE
         * @singleton
         */
        plugin.freezePublicAPI({
        });

        register(null, {
            closeconfirmation: plugin
        });
    }
});
<commit_msg>For SmartfaceCloud project added support for custom IDE provider name<commit_after>define(function(require, exports, module) {
    "use strict";

    main.consumes = [
        "Plugin", "tabManager", "settings", "preferences", "auth"
    ];
    main.provides = ["closeconfirmation"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var tabs = imports.tabManager;
        var settings = imports.settings;
        var prefs = imports.preferences;
        var auth = imports.auth;
        var ideProviderName = options.ideProviderName || "Cloud9";

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit = plugin.getEmitter();

        var defaultValue = options.defaultValue;

        var loaded = false;
        function load(callback) {
            if (loaded) return false;
            loaded = true;

            // when unloading the window
            window.onbeforeunload = onBeforeUnloadHandler;

            settings.on("read", function(){
                settings.setDefaults("user/general", [
                    ["confirmexit", defaultValue]
                ]);
            }, plugin);

            prefs.add({
                "General" : {
                    "General" : {
                        "Warn Before Exiting" : {
                            type: "checkbox",
                            position: 8000,
                            path: "user/general/@confirmexit"
                        }
                    }
                }
            }, plugin);
        }

        function unload() {
            if (window.onbeforeunload === onBeforeUnloadHandler)
                window.onbeforeunload = null;
        }

        /***** Methods *****/

        function onBeforeUnloadHandler() {
            var changed = tabs.getTabs().some(function(tab) {
                return tab.document.value && tab.document.changed;
            });

            emit("exit", { changed: changed });

            // see what's in the settings
            var confirmExit = settings.getBool("user/general/@confirmexit") && auth.loggedIn;
            if (confirmExit) {
                if (changed)
                    return "You have unsaved changes. Your changes will be lost if you don't save them";
                else
                    return "You're about to leave " + ideProviderName + ".";
            }
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            unload();
            loaded = false;
        });

        /***** Register and define API *****/
        /**
         * Shows a 'close confirmation' popup when closing the IDE
         * @singleton
         */
        plugin.freezePublicAPI({
        });

        register(null, {
            closeconfirmation: plugin
        });
    }
});
<|endoftext|>


<commit_before>//
// lib/runner.js
//
// Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>
// MIT Licensed
//
/*jshint asi: true, laxcomma: true*/
var utils = require('./utils')

// (fn) -> object
//
// Params:
//  fn: The function this runner will.. run.
//
// Returns:
//  A new instance of a runner.
//
// Desc:
//  Create a runner instance.
exports.create = function (fn, timeout) {
  var runner = {}

  utils.merge(runner, proto)
  runner.init(fn)
  return runner
}

// The 'prototype' for our object
var proto = exports.proto = {}

// (fn) -> undefined
//
// Params:
//  fn: The function this runner instance will run.
//
// Desc:
//  Initialize the data for this object instance.
proto.init = function (fn) {
  // The function this object will eventually run.
  this._fn = fn

  // An informative var. If function has defined the async 1st argument
  // callback, this will be true. Otherwise it will be false.
  this.sync = fn.length !== 1 ? true : false
}

// (callback) -> undefined
//
// Params:
//  callback: A callback which will called upon completion of this test. It
//    will be given a report object filled with information from the test.
//
// Desc:
//  Run this runner.
proto.run = function (callback) {
  var self = this

  // If the fn was not given, callback and return immediately.
  if (this._fn === undefined) {
    callback({
        'description': this.description
      , 'success': true
    })
    return undefined
  }

  // Our `this._fn` callback
  var done = function () {
    callback({
        'description': this.description
      , 'success': true
    })
  }

  try {
    this._fn(done)
  } catch (error) {
    callback({
        'description': this.description
      , 'error': error
      , 'stack': error.stack
      , 'success': false
    })
    return undefined
  }

  // This is commented out because for now, we are not supporting Async in
  // these tests yet.
  //if (this.fn.length === 0)
  done()
}<commit_msg>Added a little library description<commit_after>//
// lib/runner.js
//
// The runner is a generic object to wrap a function. It allows for
// async or sync functions via an optional callback in the function.
//
// Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>
// MIT Licensed
//
/*jshint asi: true, laxcomma: true*/
var utils = require('./utils')

// (fn) -> object
//
// Params:
//  fn: The function this runner will.. run.
//
// Returns:
//  A new instance of a runner.
//
// Desc:
//  Create a runner instance.
exports.create = function (fn, timeout) {
  var runner = {}

  utils.merge(runner, proto)
  runner.init(fn)
  return runner
}

// The 'prototype' for our object
var proto = exports.proto = {}

// (fn) -> undefined
//
// Params:
//  fn: The function this runner instance will run.
//
// Desc:
//  Initialize the data for this object instance.
proto.init = function (fn) {
  // The function this object will eventually run.
  this._fn = fn

  // An informative var. If function has defined the async 1st argument
  // callback, this will be true. Otherwise it will be false.
  this.sync = fn.length !== 1 ? true : false
}

// (callback) -> undefined
//
// Params:
//  callback: A callback which will called upon completion of this test. It
//    will be given a report object filled with information from the test.
//
// Desc:
//  Run this runner.
proto.run = function (callback) {
  var self = this

  // If the fn was not given, callback and return immediately.
  if (this._fn === undefined) {
    callback({
        'description': this.description
      , 'success': true
    })
    return undefined
  }

  // Our `this._fn` callback
  var done = function () {
    callback({
        'description': this.description
      , 'success': true
    })
  }

  try {
    this._fn(done)
  } catch (error) {
    callback({
        'description': this.description
      , 'error': error
      , 'stack': error.stack
      , 'success': false
    })
    return undefined
  }

  // This is commented out because for now, we are not supporting Async in
  // these tests yet.
  //if (this.fn.length === 0)
  done()
}<|endoftext|>


<commit_before>(function () {
'use strict';
var module = angular.module('fim.base');
module.run(function (modals, plugins, $q) {

  var config = {
    senderRS:           { type: String }
  };

  /* Register as plugin */
  plugins.register({
    id: 'issue-asset',
    extends: 'accounts',
    label: 'Issue Asset',
    create: function (args) {
      if (plugins.validate(args, config)) {
        var deferred = $q.defer();
        modals.open('issueAssetCreate', {
          resolve: {
            items: function () {
              return angular.copy(args);
            }
          },
          close: function (items) {
            deferred.resolve(items);
          },
          cancel: function () {
            deferred.resolve(null);
          }
        });
        return deferred.promise;
      }
    }
  });

  /* Register modal dialogs */
  modals.register('issueAssetCreate', {
    templateUrl: 'plugins/issue-asset/views/issue-asset-modal.html',
    controller: 'IssueAssetPluginModalController'
  });
});

})();<commit_msg>Removing moved plugins<commit_after><|endoftext|>


<commit_before>// ... is missing some documentation.

var _ = require('underscore'),
    Class = require('clah'),
    fs = require('fs'),
    glob = require('glob'),
    path = require('path'),
    commander = require('commander');

var Central = require('./central'),
    pkg = require(path.join(__dirname, '..', 'package.json'));

module.exports = Class.extend({

  init: function(args) {

    this.program = commander
      .version(this.getVersion())
      .usage('[options] <file>...')
      .option('-o, --output <path>', 'change the output directory ("docs" by default)', String, 'docs')
      .option('-q, --quiet', 'silence console logs')
      .parse(process.argv);

    this.rootDir = path.resolve('.');
    this.srcFiles = _.flatten(_.map(this.program.args, function(file) {
      var files = glob.sync(file);
      return files.length ? files : [ file ];
    }));
  },

  run : function() {
    new Central(this.rootDir, this.srcFiles, this.program.output, this.getOptions()).run(function(err) {
      if (err) console.log(err);
    });
  },

  getOptions : function() {
    return {
      logger: {
        quiet: this.program.quiet
      }
    };
  },

  getVersion : function() {
    return pkg.version;
  }
});

<commit_msg>Fixed globs.<commit_after>// ... is missing some documentation.

var _ = require('underscore'),
    Class = require('clah'),
    fs = require('fs'),
    glob = require('glob'),
    path = require('path'),
    commander = require('commander');

var Central = require('./central'),
    pkg = require(path.join(__dirname, '..', 'package.json'));

module.exports = Class.extend({

  init: function(args) {

    this.program = commander
      .version(this.getVersion())
      .usage('[options] <file>...')
      .option('-o, --output <path>', 'change the output directory ("docs" by default)', String, 'docs')
      .option('-q, --quiet', 'silence console logs')
      .parse(process.argv);

    this.rootDir = path.resolve('.');
    this.srcFiles = _.uniq(_.flatten(_.map(this.program.args, function(file) {
      var files = glob.sync(file);
      return files.length ? files : [ file ];
    })));
  },

  run : function() {
    new Central(this.rootDir, this.srcFiles, this.program.output, this.getOptions()).run(function(err) {
      if (err) console.log(err);
    });
  },

  getOptions : function() {
    return {
      logger: {
        quiet: this.program.quiet
      }
    };
  },

  getVersion : function() {
    return pkg.version;
  }
});

<|endoftext|>


<commit_before>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
'use strict';

var gulp = require('gulp'),
    prefix = require('gulp-autoprefixer'),
    minifyCss = require('gulp-minify-css'),
    usemin = require('gulp-usemin'),
    uglify = require('gulp-uglify'),<% if(useCompass) { %>
    compass = require('gulp-compass'),<% } %>
    minifyHtml = require('gulp-minify-html'),
    livereload = require('gulp-livereload'),
    imagemin = require('gulp-imagemin'),
    ngAnnotate = require('gulp-ng-annotate'),
    jshint = require('gulp-jshint'),
    rev = require('gulp-rev'),
    connect = require('gulp-connect'),
    proxy = require('proxy-middleware'),
    es = require('event-stream'),
    flatten = require('gulp-flatten'),
    clean = require('gulp-clean'),
    replace = require('gulp-replace');

var karma = require('gulp-karma')({configFile: 'src/test/javascript/karma.conf.js'});

var yeoman = {
    app: 'src/main/webapp/',//require('./bower.json').appPath || 'app',
    dist: 'src/main/webapp/dist/',
    test: 'src/test/javascript/spec/',
    tmp: '.tmp/'<% if(useCompass) { %>,
    scss: 'src/main/scss/'<% } %>
}

gulp.task('clean', function(){
    return gulp.src(yeoman.dist, {read: false}).
        pipe(clean());
});

gulp.task('clean:tmp', function(){
    return gulp.src(yeoman.tmp, {read: false}).
        pipe(clean());
});

gulp.task('test', function(){
    karma.once();
});

gulp.task('copy', ['clean'], function(){
    return es.merge(gulp.src(yeoman.app + 'i18n/**').
              pipe(gulp.dest(yeoman.dist + 'i18n/')),
              gulp.src(yeoman.app + '**/*.{woff,svg,ttf,eot}').
              pipe(flatten()).
              pipe(gulp.dest(yeoman.dist + 'fonts/')));
});

gulp.task('images', function(){
        return gulp.src(yeoman.app + 'images/**').
            pipe(imagemin({optimizationLevel: 5})).
            pipe(gulp.dest(yeoman.dist + 'images'));
});

<% if(useCompass) { %>
gulp.task('compass', function() {
    return gulp.src(yeoman.scss + '{,*/}*.scss').
        pipe(compass({
                project: __dirname,
                sass: 'src/main/scss',
                css: 'src/main/webapp/styles',
                generated_images: '.tmp/images/generated',
                image: 'src/main/webapp/images',
                javascript: 'src/main/webapp/scripts',
                font: 'src/main/webapp/styles/fonts',
                import_path: 'src/main/webapp/bower_components',
                relative: false
        })).
        pipe(gulp.dest(yeoman.tmp + 'styles'));
});
<% } %>

gulp.task('styles', [<% if(useCompass) { %> 'compass'<% } %>], function() {
    return gulp.src(yeoman.app + '{,*/}*.css').
        pipe(gulp.dest(yeoman.tmp));
});

gulp.task('server', ['watch'<% if(useCompass) { %>, 'compass'<% } %>], function() {
    connect.server(
        {
            root: [yeoman.app, yeoman.tmp],
            port: 9000,
            livereload: true,
            middleware: function(connect, o) {
                return [
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/api');
                        options.route = '/api';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/health');
                        options.route = '/api-docs';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/configprops');
                        options.route = '/api-docs';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/beans');
                        options.route = '/api-docs';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/api-docs');
                        options.route = '/api-docs';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/metrics');
                        options.route = '/metrics';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/dump');
                        options.route = '/dump';
                        return proxy(options);
                    })()<% if (authenticationType == 'token') { %>,
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/oauth/token');
                        options.route = '/oauth/token';
                        return proxy(options);
                    })()<% } %><% if (devDatabaseType == 'h2Memory') { %>,
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/console');
                        options.route = '/console';
                        return proxy(options);
                    })()<% } %>
                ];
            }
        }
    );
});

gulp.task('watch', function() {
    gulp.watch(yeoman.app + 'scripts/**');<% if(useCompass) { %>
    gulp.watch(yeoman.scss, ['compass']); <% } %>
    gulp.watch('src/images/**', ['images']);
    livereload();
});

gulp.task('server:dist', ['build'], function() {
    connect.server(
        {
            root: [yeoman.dist],
            port: 9000,
            //livereload: true,
            middleware: function(connect, o) {
                return [
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/api');
                        options.route = '/api';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/metrics');
                        options.route = '/metrics';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/dump');
                        options.route = '/dump';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/api-docs');
                        options.route = '/api-docs';
                        return proxy(options);
                    })()<% if (authenticationType == 'token') { %>,
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/oauth/token');
                        options.route = '/oauth/token';
                        return proxy(options);
                    })()<% } %><% if (devDatabaseType == 'h2Memory') { %>,
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/console');
                        options.route = '/console';
                        return proxy(options);
                    })()<% } %>
                ];
            }
        }
    );
});

gulp.task('build', ['clean', 'copy'], function() {
    gulp.run('usemin');
});

gulp.task('usemin', ['images', 'styles'], function(){
    return gulp.src(yeoman.app + '{,views/}*.html').
        pipe(usemin({
            css: [
                prefix.apply(),
                replace(/[0-9a-zA-Z\-_\s\.\/]*\/([a-zA-Z\-_\.0-9]*\.(woff|eot|ttf|svg))/g, '/fonts/$1'),
                //minifyCss(),
                'concat',
                rev()
            ],
            html: [
                minifyHtml({empty: true, conditionals:true})
            ],
            js: [
                ngAnnotate(),
                uglify(),
                'concat',
                rev()
            ]
        })).
        pipe(gulp.dest(yeoman.dist));
});

gulp.task('default', function() {
    gulp.run('test');
    gulp.run('build');
});
<commit_msg>fix glup errors<commit_after>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
'use strict';

var gulp = require('gulp'),
    prefix = require('gulp-autoprefixer'),
    minifyCss = require('gulp-minify-css'),
    usemin = require('gulp-usemin'),
    uglify = require('gulp-uglify'),<% if(useCompass) { %>
    compass = require('gulp-compass'),<% } %>
    minifyHtml = require('gulp-minify-html'),
    livereload = require('gulp-livereload'),
    imagemin = require('gulp-imagemin'),
    ngAnnotate = require('gulp-ng-annotate'),
    jshint = require('gulp-jshint'),
    rev = require('gulp-rev'),
    connect = require('gulp-connect'),
    proxy = require('proxy-middleware'),
    es = require('event-stream'),
    flatten = require('gulp-flatten'),
    clean = require('gulp-clean'),
    replace = require('gulp-replace');

var karma = require('gulp-karma')({configFile: 'src/test/javascript/karma.conf.js'});

var yeoman = {
    app: 'src/main/webapp/',//require('./bower.json').appPath || 'app',
    dist: 'src/main/webapp/dist/',
    test: 'src/test/javascript/spec/',
    tmp: '.tmp/'<% if(useCompass) { %>,
    scss: 'src/main/scss/'<% } %>
}

gulp.task('clean', function(){
    return gulp.src(yeoman.dist, {read: false}).
        pipe(clean());
});

gulp.task('clean:tmp', function(){
    return gulp.src(yeoman.tmp, {read: false}).
        pipe(clean());
});

gulp.task('test', function(){
    karma.once();
});

gulp.task('copy', ['clean'], function(){
    return es.merge(gulp.src(yeoman.app + 'i18n/**').
              pipe(gulp.dest(yeoman.dist + 'i18n/')),
              gulp.src(yeoman.app + '**/*.{woff,svg,ttf,eot}').
              pipe(flatten()).
              pipe(gulp.dest(yeoman.dist + 'fonts/')));
});

gulp.task('images', function(){
        return gulp.src(yeoman.app + 'images/**').
            pipe(imagemin({optimizationLevel: 5})).
            pipe(gulp.dest(yeoman.dist + 'images'));
});

<% if(useCompass) { %>
gulp.task('compass', function() {
    return gulp.src(yeoman.scss + '{,*/}*.scss').
        pipe(compass({
                project: __dirname,
                sass: 'src/main/scss',
                css: 'src/main/webapp/styles',
                generated_images: '.tmp/images/generated',
                image: 'src/main/webapp/images',
                javascript: 'src/main/webapp/',
                font: 'src/main/webapp/styles/fonts',
                import_path: 'src/main/webapp/bower_components',
                relative: false
        })).
        pipe(gulp.dest(yeoman.tmp + 'styles'));
});
<% } %>

gulp.task('styles', [<% if(useCompass) { %> 'compass'<% } %>], function() {
    return gulp.src(yeoman.app + '{,*/}*.css').
        pipe(gulp.dest(yeoman.tmp));
});

gulp.task('server', ['watch'<% if(useCompass) { %>, 'compass'<% } %>], function() {
    connect.server(
        {
            root: [yeoman.app, yeoman.tmp],
            port: 9000,
            livereload: true,
            middleware: function(connect, o) {
                return [
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/api');
                        options.route = '/api';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/health');
                        options.route = '/api-docs';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/configprops');
                        options.route = '/api-docs';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/beans');
                        options.route = '/api-docs';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/api-docs');
                        options.route = '/api-docs';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/metrics');
                        options.route = '/metrics';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/dump');
                        options.route = '/dump';
                        return proxy(options);
                    })()<% if (authenticationType == 'token') { %>,
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/oauth/token');
                        options.route = '/oauth/token';
                        return proxy(options);
                    })()<% } %><% if (devDatabaseType == 'h2Memory') { %>,
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/console');
                        options.route = '/console';
                        return proxy(options);
                    })()<% } %>
                ];
            }
        }
    );
});

gulp.task('watch', function() {
    gulp.watch(yeoman.app + 'scripts/**');<% if(useCompass) { %>
    gulp.watch(yeoman.scss, ['compass']); <% } %>
    gulp.watch('src/images/**', ['images']);
    livereload();
});

gulp.task('server:dist', ['build'], function() {
    connect.server(
        {
            root: [yeoman.dist],
            port: 9000,
            //livereload: true,
            middleware: function(connect, o) {
                return [
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/api');
                        options.route = '/api';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/metrics');
                        options.route = '/metrics';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/dump');
                        options.route = '/dump';
                        return proxy(options);
                    })(),
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/api-docs');
                        options.route = '/api-docs';
                        return proxy(options);
                    })()<% if (authenticationType == 'token') { %>,
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/oauth/token');
                        options.route = '/oauth/token';
                        return proxy(options);
                    })()<% } %><% if (devDatabaseType == 'h2Memory') { %>,
                    (function() {
                        var url = require('url');
                        var proxy = require('proxy-middleware');
                        var options = url.parse('http://localhost:8080/console');
                        options.route = '/console';
                        return proxy(options);
                    })()<% } %>
                ];
            }
        }
    );
});

gulp.task('build', ['clean', 'copy'], function() {
    gulp.run('usemin');
});

gulp.task('usemin', ['images', 'styles'], function(){
    return gulp.src(yeoman.app + '{,views/}*.html').
        pipe(usemin({
            css: [
                prefix.apply(),
                replace(/[0-9a-zA-Z\-_\s\.\/]*\/([a-zA-Z\-_\.0-9]*\.(woff|eot|ttf|svg))/g, '/fonts/$1'),
                //minifyCss(),
                'concat',
                rev()
            ],
            html: [
                minifyHtml({empty: true, conditionals:true})
            ],
            js: [
                ngAnnotate(),
                uglify(),
                'concat',
                rev()
            ]
        })).
        pipe(gulp.dest(yeoman.dist));
});

gulp.task('default', function() {
    gulp.run('test');
    gulp.run('build');
});
<|endoftext|>


<commit_before>'use strict';
var Agenda = require('agenda');
var config = require('config');
var _ = require('lodash');
var ApplicationEvent = require('broker/lib/event_types/application_event');
var EventBroker = require('broker/lib/event_broker');
var BBPromise = require('bluebird');
var logger = require('hoist-logger');

function Runner() {
  _.bindAll(this);
}

Runner.prototype = {
  processEvents: function (job, done) {
    logger.info({
      job: job
    }, 'processing schedule job');
    BBPromise.all(_.map(job.data.events, function (eventName) {
      return this.createEvent(job, eventName).catch(function (err) {
        logger.info(err);
        logger.error(err);
        throw err;
      });
    }, this)).catch(function (err) {
      logger.info(err);
      logger.error(err);
      throw err;
    }).nodeify(done);
  },
  createEvent: function (job, eventName) {
    var applicationEvent = new ApplicationEvent({
      applicationId: job.data.application,
      environment: job.data.environment,
      eventName: eventName
    });
    logger.info({
      eventId: applicationEvent.messageId,
      applicationId: applicationEvent.applicationId,
      correlationId: applicationEvent.correlationId,
      eventName: eventName
    }, 'raising scheduled event');
    return EventBroker.publish(applicationEvent);
  },
  start: function () {

    this.agenda = new Agenda({
      db: {
        address: config.get('Hoist.mongo.db')
      }
    });
    this.agenda.define('create:event', this.processEvents);
    this.agenda.start();
    logger.info('waiting on schedule');
  },
  stop: function (cb) {
    this.agenda.stop(cb || /* istanbul ignore next */ function () {});
  }
};

module.exports = new Runner();
<commit_msg>ignore logging lines from coverage<commit_after>'use strict';
var Agenda = require('agenda');
var config = require('config');
var _ = require('lodash');
var ApplicationEvent = require('broker/lib/event_types/application_event');
var EventBroker = require('broker/lib/event_broker');
var BBPromise = require('bluebird');
var logger = require('hoist-logger');

function Runner() {
  _.bindAll(this);
}

Runner.prototype = {
  processEvents: function (job, done) {
    logger.info({
      job: job
    }, 'processing schedule job');
    BBPromise.all(_.map(job.data.events, function (eventName) {
      return this.createEvent(job, eventName).catch(
        /* istanbul ignore next */
        function (err) {
          logger.info(err);
          logger.error(err);
          throw err;
        });
    }, this)).catch(
      /* istanbul ignore next */
      function (err) {
        logger.info(err);
        logger.error(err);
        throw err;
      }).nodeify(done);
  },
  createEvent: function (job, eventName) {
    var applicationEvent = new ApplicationEvent({
      applicationId: job.data.application,
      environment: job.data.environment,
      eventName: eventName
    });
    logger.info({
      eventId: applicationEvent.messageId,
      applicationId: applicationEvent.applicationId,
      correlationId: applicationEvent.correlationId,
      eventName: eventName
    }, 'raising scheduled event');
    return EventBroker.publish(applicationEvent);
  },
  start: function () {

    this.agenda = new Agenda({
      db: {
        address: config.get('Hoist.mongo.db')
      }
    });
    this.agenda.define('create:event', this.processEvents);
    this.agenda.start();
    logger.info('waiting on schedule');
  },
  stop: function (cb) {
    this.agenda.stop(cb || /* istanbul ignore next */ function () {});
  }
};

module.exports = new Runner();
<|endoftext|>


<commit_before>var clicked = false;
var eggCount = 0;
var chosenNums = [];
var easterImgClass = "text-center";
var easterImgStyle = "width: 100%; height: auto;";
var easterImgSrcBase = "../img/easter-eggs/";
var easterImg = "some HTML string -> use setImg()";

function setImg(newSrc) {
    easterImg = "" +
                    "You found an Easter Egg!";
    preloadEggs();
}

function pictureBox(imgName, titleText) {
    setImg(imgName);
    bootbox.alert({
        size: 'large',
        title: titleText,
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
}

function rasengan() {
    console.log("rasengan!");

    var narutoEggs = [
        "../img/sharingan/msharingan.png",
        "../img/sharingan/msharingan-color.png",
        "../img/sharingan/sharingan.png",
        "../img/easter-eggs/rasengan.png"
    ];
    var geassEggs = [
        "../img/easter-eggs/geass.png"
    ];
    var otherEggs = [
        "../img/easter-eggs/dragonball.png",
        "../img/easter-eggs/fairytail.png",
        "../img/easter-eggs/steins-gate.png",
        "../img/easter-eggs/white-beard.png",
        "../img/sharingan/msharingan.png",
        "../img/sharingan/msharingan-color.png",
        "../img/sharingan/sharingan.png",
        "../img/easter-eggs/rasengan.png",
        "../img/easter-eggs/pokeball-pixels.png",
        "../img/easter-eggs/pokeball-cyndaquil.png"
    ];

    var geassQuotes = [ "If I grant you power, could you go on? I propose a deal - in exchange for this power, you must agree to make my one wish come true. Accept this contract, and you accept its conditions. While living in the world of humans, you will live unlike any other: a different providence, a different time, a different life. The Power of the King will condemn you to a life of solitude. Are you prepared for this?",
                        "You appear to have a reason for living.",
                        "You don't want it to end here, do you?"
    ];

    // create image
    var img = document.createElement("img");
    img.className = "img-circle img-responsive";
    img.alt = "Easter Egg Special";
    img.onclick = rasengan;

    // egg picking
    if (eggCount++ < narutoEggs.length)     setEgg(narutoEggs, true);
    else if (eggCount === 13)               makeGeassBox();
    else                                    setEgg(otherEggs, false);

    // create div
    var div = document.createElement("div");
    div.className = "timeline-image";

    // create li
    var li = document.createElement("li");
    li.className = "timeline-inverted wow rotateIn";

    div.appendChild(img);
    li.appendChild(div);
    $("#timeline-list").append(li);

    function setEgg(eggs, naruto) {

        // find a new picture
        var randNum = Math.floor(Math.random() * eggs.length);
        while (naruto && $.inArray(randNum, chosenNums) != -1)
            randNum = Math.floor(Math.random() * eggs.length);
        chosenNums.push(randNum);

        img.src = eggs[randNum];
    }

    function makeGeassBox() {
        bootbox.dialog({
            size: 'small',
            title: 'Contract',
            message: geassQuotes.pop(),
            buttons: {
                success: {
                    label: "Accept",
                    className: "btn-success",
                    callback: function () {
                        console.log("accepted");

                        if (geassQuotes.length !== 0)
                            makeGeassBox();
                        else {
                            console.log("Geass activated.");
                            setEgg(geassEggs, false);
                        }

                    }
                },
                danger: {
                    label: "Reject",
                    className: "btn-danger",
                    callback: function () {
                        console.log("rejected");
                        setEgg(otherEggs, false);
                    }
                }
            }
        });
    }
}

// GISD - Infinite Circles
$("#gisd-image").click(function () {

    if (clicked) return;
    else clicked = true;

    rasengan();
    preloadEggs();
});

// Android
$("#android-image").click(function () {
    pictureBox("android-doughnut.jpg", "My kind of doughnut! (me at Google HQ)");
});

// Bizler
$("#bizler-image").click(function () {
    pictureBox("banana.jpg", "It's still a secret so here's a funny banana I made :p");
});

// PayPal
$("#paypal-image").click(function () {
    pictureBox("paypal-ceo.jpg", "Me and Dan Schulman (CEO of PayPal)");
});

// IBM
$("#ibm-image").click(function () {
    pictureBox("floppy-disk.jpg", "The oldest of companies");
});

// Interests
$("#interests-image").click(function () {
    pictureBox("eyepatch.jpg", "Why so serious?");
});

// Details
$("#details-image").click(function () {
    pictureBox("daisy-straw.jpg", "She helped make this site");
});

// Creative Easter Egg
$("#creative-egg").click(function () {
    pictureBox("ralph.gif", "Keep going, there are more to be found!");
});

// IE
$("#ie-egg").click(function () {
    pictureBox("ie-pokemon.jpg", "But it's pre-installed!");
});

// IE Face
$("#ie-face-egg").click(function () {
    pictureBox( "ie-graph.jpg", "Consumers think they know the pain");
});<commit_msg>updated messages<commit_after>var clicked = false;
var eggCount = 0;
var chosenNums = [];
var easterImgClass = "text-center";
var easterImgStyle = "width: 100%; height: auto;";
var easterImgSrcBase = "../img/easter-eggs/";
var easterImg = "some HTML string -> use setImg()";

function setImg(newSrc) {
    easterImg = "" +
                    "You found an Easter Egg!";
    preloadEggs();
}

function pictureBox(imgName, titleText) {
    setImg(imgName);
    bootbox.alert({
        size: 'large',
        title: titleText,
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
}

function rasengan() {
    console.log("rasengan!");

    var narutoEggs = [
        "../img/sharingan/msharingan.png",
        "../img/sharingan/msharingan-color.png",
        "../img/sharingan/sharingan.png",
        "../img/easter-eggs/rasengan.png"
    ];
    var geassEggs = [
        "../img/easter-eggs/geass.png"
    ];
    var otherEggs = [
        "../img/easter-eggs/dragonball.png",
        "../img/easter-eggs/fairytail.png",
        "../img/easter-eggs/steins-gate.png",
        "../img/easter-eggs/white-beard.png",
        "../img/sharingan/msharingan.png",
        "../img/sharingan/msharingan-color.png",
        "../img/sharingan/sharingan.png",
        "../img/easter-eggs/rasengan.png",
        "../img/easter-eggs/pokeball-pixels.png",
        "../img/easter-eggs/pokeball-cyndaquil.png"
    ];

    var geassQuotes = [ "If I grant you power, could you go on? I propose a deal - in exchange for this power, you must agree to make my one wish come true. Accept this contract, and you accept its conditions. While living in the world of humans, you will live unlike any other: a different providence, a different time, a different life. The Power of the King will condemn you to a life of solitude. Are you prepared for this?",
                        "You appear to have a reason for living.",
                        "You don't want it to end here, do you?"
    ];

    // create image
    var img = document.createElement("img");
    img.className = "img-circle img-responsive";
    img.alt = "Easter Egg Special";
    img.onclick = rasengan;

    // egg picking
    if (eggCount++ < narutoEggs.length)     setEgg(narutoEggs, true);
    else if (eggCount === 13)               makeGeassBox();
    else                                    setEgg(otherEggs, false);

    // create div
    var div = document.createElement("div");
    div.className = "timeline-image";

    // create li
    var li = document.createElement("li");
    li.className = "timeline-inverted wow rotateIn";

    div.appendChild(img);
    li.appendChild(div);
    $("#timeline-list").append(li);

    function setEgg(eggs, naruto) {

        // find a new picture
        var randNum = Math.floor(Math.random() * eggs.length);
        while (naruto && $.inArray(randNum, chosenNums) != -1)
            randNum = Math.floor(Math.random() * eggs.length);
        chosenNums.push(randNum);

        img.src = eggs[randNum];
    }

    function makeGeassBox() {
        bootbox.dialog({
            size: 'small',
            title: 'Contract',
            message: geassQuotes.pop(),
            buttons: {
                success: {
                    label: "Accept",
                    className: "btn-success",
                    callback: function () {
                        console.log("accepted");

                        if (geassQuotes.length !== 0)
                            makeGeassBox();
                        else {
                            console.log("Geass activated.");
                            setEgg(geassEggs, false);
                        }

                    }
                },
                danger: {
                    label: "Reject",
                    className: "btn-danger",
                    callback: function () {
                        console.log("rejected");
                        setEgg(otherEggs, false);
                    }
                }
            }
        });
    }
}

// GISD - Infinite Circles
$("#gisd-image").click(function () {

    if (clicked) return;
    else clicked = true;

    rasengan();
    preloadEggs();
});

// Android
$("#android-image").click(function () {
    pictureBox("android-doughnut.jpg", "My kind of doughnut! (me at Google HQ)");
});

// Bizler
$("#bizler-image").click(function () {
    pictureBox("banana.jpg", "It's still a secret so here's a banana I made");
});

// PayPal
$("#paypal-image").click(function () {
    pictureBox("paypal-ceo.jpg", "Me and Dan Schulman (CEO of PayPal)");
});

// IBM
$("#ibm-image").click(function () {
    pictureBox("floppy-disk.jpg", "The oldest of companies");
});

// Interests
$("#interests-image").click(function () {
    pictureBox("eyepatch.jpg", "Why so serious?");
});

// Details
$("#details-image").click(function () {
    pictureBox("daisy-straw.jpg", "She helped make this site");
});

// Creative Easter Egg
$("#creative-egg").click(function () {
    pictureBox("ralph.gif", "Keep going, there are more to be found!");
});

// IE
$("#ie-egg").click(function () {
    pictureBox("ie-pokemon.jpg", "But it's pre-installed!");
});

// IE Face
$("#ie-face-egg").click(function () {
    pictureBox( "ie-graph.jpg", "Consumers think they know the pain");
});<|endoftext|>


<commit_before>enyo.kind({
	name: "SimpleTabBar",
	fit: true,
	components: [
		{name:"bar",kind: "onyx.TabBar"},
		{
			style: "border: 2px solid grey; ",
			components: [
				{
					content: 'Only the content of this kind is changed',
					style: 'padding: 1em'
				},
				{name: 'stuff', content: 'empty', style: 'padding: 1em'}
			]
		}
	],

	handlers: {
		onTabChanged: "switchStuff"
	},

	rendered: function() {
		this.inherited(arguments);
		this.$.bar.addTab(
			{
				'caption': 'English',
				'tooltipMsg': 'English/Anglais',
				'data' : { 'msg': 'Hello World !' } // arbitrary user data
			}
		) ;
		this.$.bar.addTab(
			{
				'caption': 'Français',
				'tooltipMsg': 'Frech/Français',
				'data' : { 'msg': 'Bonjour tout le monde !' } // arbitrary user data
			}
		) ;
	},

	switchStuff: function(inSender,inEvent) {
		this.log("Tapped tab with caption "+ inEvent.caption
			+ " and message " + inEvent.data.msg );
		this.$.stuff.setContent( inEvent.data.msg);
	}
});

enyo.kind(
	{
		name: "DynamicTabBar",
		fit: true,
		components: [
			{name:"bar",kind: "onyx.TabBar", maxMenuHeight: 200},
			{
				style: "border: 2px solid grey; ",
				components: [
					{
						content: 'create many tabs and reduce the width of the browser'
					},
					{name: 'stuff', content: 'empty', style: 'padding: 1em'},
					{
						kind: 'onyx.Button',
						content: 'create tab',
						ontap: 'addATab',
						style: 'margin: 0.5em'
					},
					{
						kind: 'onyx.Button',
						content: 'kill last tab',
						ontap: 'killTab'
					}
				]
			}
		],

		handlers: {
			onTabChanged: "switchStuff"
		},

		number: 1,
		rendered: function() {
			this.inherited(arguments);
			var date = new Date();
			this.creationTime = date.getTime();
			this.addATab() ;
		},

		addATab: function(inSender,inEvent) {
			this.log("adding a tab");
			var date = new Date();
			var delta = ( date.getTime() - this.creationTime ) / 1000 ;
			this.$.bar.addTab(
				{
					'caption': 'Tab label ' + this.number ,
					data: { msg: "tab " + this.number++ + " created after " + delta + " seconds" }
				}
			) ;
		},

		switchStuff: function(inSender,inEvent) {
			this.log("Tapped tab with caption "+ inEvent.caption
				+ " and message " + inEvent.data.msg );
			this.$.stuff.setContent( inEvent.data.msg);
		},
		killTab: function(inSender,inEvent) {
			this.log("killing tab");
			this.$.bar.removeTab({index: this.number-- - 2});
		}

	}
);

enyo.kind({
	name: "onyx.sample.TabBarSample",
	classes: "onyx onyx-sample",
	components: [
		{
			classes: "onyx-sample-divider",
			content: "Simple Tab Bar"
		},
		{
			kind:"SimpleTabBar"
		},
		{
			classes: "onyx-sample-divider",
			content: "Dynamic Tab Bar",
			style: 'padding-top: 4em;'
		},
		{
			kind:"DynamicTabBar"
		}

	]
});
<commit_msg>ENYO-2577: fixed typo<commit_after>enyo.kind({
	name: "SimpleTabBar",
	fit: true,
	components: [
		{name:"bar",kind: "onyx.TabBar"},
		{
			style: "border: 2px solid grey; ",
			components: [
				{
					content: 'Only the content of this kind is changed',
					style: 'padding: 1em'
				},
				{name: 'stuff', content: 'empty', style: 'padding: 1em'}
			]
		}
	],

	handlers: {
		onTabChanged: "switchStuff"
	},

	rendered: function() {
		this.inherited(arguments);
		this.$.bar.addTab(
			{
				'caption': 'English',
				'tooltipMsg': 'English/Anglais',
				'data' : { 'msg': 'Hello World !' } // arbitrary user data
			}
		) ;
		this.$.bar.addTab(
			{
				'caption': 'Français',
				'tooltipMsg': 'French/Français',
				'data' : { 'msg': 'Bonjour tout le monde !' } // arbitrary user data
			}
		) ;
	},

	switchStuff: function(inSender,inEvent) {
		this.log("Tapped tab with caption "+ inEvent.caption
			+ " and message " + inEvent.data.msg );
		this.$.stuff.setContent( inEvent.data.msg);
	}
});

enyo.kind(
	{
		name: "DynamicTabBar",
		fit: true,
		components: [
			{name:"bar",kind: "onyx.TabBar", maxMenuHeight: 200},
			{
				style: "border: 2px solid grey; ",
				components: [
					{
						content: 'create many tabs and reduce the width of the browser'
					},
					{name: 'stuff', content: 'empty', style: 'padding: 1em'},
					{
						kind: 'onyx.Button',
						content: 'create tab',
						ontap: 'addATab',
						style: 'margin: 0.5em'
					},
					{
						kind: 'onyx.Button',
						content: 'kill last tab',
						ontap: 'killTab'
					}
				]
			}
		],

		handlers: {
			onTabChanged: "switchStuff"
		},

		number: 1,
		rendered: function() {
			this.inherited(arguments);
			var date = new Date();
			this.creationTime = date.getTime();
			this.addATab() ;
		},

		addATab: function(inSender,inEvent) {
			this.log("adding a tab");
			var date = new Date();
			var delta = ( date.getTime() - this.creationTime ) / 1000 ;
			this.$.bar.addTab(
				{
					'caption': 'Tab label ' + this.number ,
					data: { msg: "tab " + this.number++ + " created after " + delta + " seconds" }
				}
			) ;
		},

		switchStuff: function(inSender,inEvent) {
			this.log("Tapped tab with caption "+ inEvent.caption
				+ " and message " + inEvent.data.msg );
			this.$.stuff.setContent( inEvent.data.msg);
		},
		killTab: function(inSender,inEvent) {
			this.log("killing tab");
			this.$.bar.removeTab({index: this.number-- - 2});
		}

	}
);

enyo.kind({
	name: "onyx.sample.TabBarSample",
	classes: "onyx onyx-sample",
	components: [
		{
			classes: "onyx-sample-divider",
			content: "Simple Tab Bar"
		},
		{
			kind:"SimpleTabBar"
		},
		{
			classes: "onyx-sample-divider",
			content: "Dynamic Tab Bar",
			style: 'padding-top: 4em;'
		},
		{
			kind:"DynamicTabBar"
		}

	]
});
<|endoftext|>


<commit_before>
module.exports = [
  'last 2 versions',
  'Firefox ESR',
  '> 1%',
  'ie >= 9',
  'iOS >= 8',
  'Android >= 4',
];
<commit_msg>fix: ios8 compatibility<commit_after>
module.exports = [
  'last 2 versions',
  'Firefox ESR',
  '> 1%',
  'ie >= 9',
  'iOS >= 7',
  'Android >= 4',
];
<|endoftext|>


<commit_before>var benchmarkUtils = require('./benchmark-utils');
var EventsHandler = require('./events-handler');
var giveMe = require('give-me');
var Timer = require('./timer.js');
var _ = require('underscore');

module.exports = function(options){

  this.steps = [];
  this.results = [];
  this.options = options;

  this.add = function(stepName, href, func){
    var self = this;

    var step = {
      name: stepName,
      func: func,
      href: href,
      stats: {
        sample: []
      }
    };

    step.run = function(callback){

      var isSequence = !self.options.runMode || self.options.runMode == 'sequence',
          maxConcurrent = isSequence ? 1 : self.options.maxConcurrentRequests,
          totalRequests = self.options.minSamples,
          cycleLength = (maxConcurrent && totalRequests > maxConcurrent) ? maxConcurrent : totalRequests,
          cycleDelay = isSequence ? self.options.delay : 0;
          callbackDone = false,
          globalTimer = new Timer(),
          sampled = 0,
          i = 0;

      var runNextSample = function(){
        if(isSequence)
          globalTimer.start();
        self.runSample(step.func, sampleDone, i);
        i++;
      };

      var sampleDone = function(sample, pos){

        var currentGlobalTime = self.getCurrentTime(globalTimer, isSequence),
            maxTime = self.options.maxTime;

        step.stats.sample[pos] = sample;
        sampled++;

        if(!callbackDone && totalRequests > i && currentGlobalTime < maxTime){
          setTimeout(runNextSample, cycleDelay);
        } else if(!callbackDone && (sampled == totalRequests || currentGlobalTime >= maxTime)) {
          callbackDone = true;
          callback(self.addResult(step));
        }
      };

      globalTimer.start();

      for(i = 0; i < cycleLength; i++)
        (self.runSample)(step.func, sampleDone, i);

    };
    this.steps.push(step);
  };

  this.runSample = function(func, c, i){
    var timer = new Timer();
    timer.start();
    func(function(){
      c(timer.get(), i);
    });
  };

  this.getCurrentTime = function(timer, isSequence){
    if(isSequence){
      timer.stop();
      return timer.time;
    }
    return timer.get();
  };

  this.addResult = function(step){
    step.stats.sample = _.compact(step.stats.sample);
    var result = benchmarkUtils.getRelevantFields(_.pick(step, 'name', 'href', 'stats'));
    this.results.push(result);
    this.emit('cycle', benchmarkUtils.cycleMessage(result));
    return step;
  };

  this.run = function(){
    var self = this;

    giveMe.sequence(_.map(this.steps, function(step){ return _.bind(step.run, step); }), function(callbacks){

      var results = {};
      _.forEach(self.results, function(result, i){ results[i] = result; });

      var sorted = _.compose(benchmarkUtils.sort, benchmarkUtils.getSuccessful)(results);

      if(sorted.length > 1){
        _.find(results, function(result){ return result.name == sorted[0].name}).isFastest = true;
        _.find(results, function(result){ return result.name == sorted[sorted.length - 1].name}).isSlowest = true;
      }

      self.emit('complete', results);
    });
  };

  return _.extend(this, new EventsHandler());
};<commit_msg>console.log to understand what's happening with node 0.6<commit_after>var benchmarkUtils = require('./benchmark-utils');
var EventsHandler = require('./events-handler');
var giveMe = require('give-me');
var Timer = require('./timer.js');
var _ = require('underscore');

module.exports = function(options){

  this.steps = [];
  this.results = [];
  this.options = options;

  this.add = function(stepName, href, func){
    var self = this;

    var step = {
      name: stepName,
      func: func,
      href: href,
      stats: {
        sample: []
      }
    };

    step.run = function(callback){

      var isSequence = !self.options.runMode || self.options.runMode == 'sequence',
          maxConcurrent = isSequence ? 1 : self.options.maxConcurrentRequests,
          totalRequests = self.options.minSamples,
          cycleLength = (maxConcurrent && totalRequests > maxConcurrent) ? maxConcurrent : totalRequests,
          cycleDelay = isSequence ? self.options.delay : 0;
          callbackDone = false,
          globalTimer = new Timer(),
          sampled = 0,
          i = 0;

      var runNextSample = function(){
        if(isSequence)
          globalTimer.start();
        self.runSample(step.func, sampleDone, i);
        i++;
      };

      var sampleDone = function(sample, pos){

        var currentGlobalTime = self.getCurrentTime(globalTimer, isSequence),
            maxTime = self.options.maxTime;

        step.stats.sample[pos] = sample;
        sampled++;

        if(!callbackDone && totalRequests > i && currentGlobalTime < maxTime){
          setTimeout(runNextSample, cycleDelay);
        } else if(!callbackDone && (sampled == totalRequests || currentGlobalTime >= maxTime)) { console.log('global time:' + currentGlobalTime)
          callbackDone = true;
          callback(self.addResult(step));
        }
      };

      globalTimer.start();

      for(i = 0; i < cycleLength; i++)
        (self.runSample)(step.func, sampleDone, i);

    };
    this.steps.push(step);
  };

  this.runSample = function(func, c, i){
    var timer = new Timer();
    timer.start();
    func(function(){
      c(timer.get(), i);
    });
  };

  this.getCurrentTime = function(timer, isSequence){
    if(isSequence){
      timer.stop();
      return timer.time;
    }
    return timer.get();
  };

  this.addResult = function(step){
    step.stats.sample = _.compact(step.stats.sample);
    var result = benchmarkUtils.getRelevantFields(_.pick(step, 'name', 'href', 'stats'));
    this.results.push(result);
    this.emit('cycle', benchmarkUtils.cycleMessage(result));
    return step;
  };

  this.run = function(){
    var self = this;

    giveMe.sequence(_.map(this.steps, function(step){ return _.bind(step.run, step); }), function(callbacks){

      var results = {};
      _.forEach(self.results, function(result, i){ results[i] = result; });

      var sorted = _.compose(benchmarkUtils.sort, benchmarkUtils.getSuccessful)(results);

      if(sorted.length > 1){
        _.find(results, function(result){ return result.name == sorted[0].name}).isFastest = true;
        _.find(results, function(result){ return result.name == sorted[sorted.length - 1].name}).isSlowest = true;
      }

      self.emit('complete', results);
    });
  };

  return _.extend(this, new EventsHandler());
};<|endoftext|>


<commit_before>'use strict';
// generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>

var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gutil = require('gulp-util');

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {
    return gulp.src('app/styles/main.scss')
        .pipe($.sass({errLogToConsole: true}))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('app/styles'))
        .pipe(reload({stream:true}))
        .pipe($.size())
        .pipe($.notify("Compilation complete."));;
});

gulp.task('scripts', function () {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.jshint())
        .pipe($.jshint.reporter(require('jshint-stylish')))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe(reload({stream:true, once:true}))
        .pipe($.size());
});

gulp.task('fonts', function () {
    var streamqueue = require('streamqueue');
    return streamqueue({objectMode: true},
        $.bowerFiles(),
        gulp.src('app/fonts/**/*')
    )
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('dist/fonts'))
        .pipe($.size());
});

gulp.task('clean', function () {
    return gulp.src(['app/styles/main.css', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['html', 'images', 'fonts']);

gulp.task('default', ['clean'], function () {
    gulp.start('build');
});

gulp.task('serve', ['styles'], function () {
    browserSync.init(null, {
        server: {
            baseDir: 'app',
            directory: true
        },
        debugInfo: false,
        open: false,
        hostnameSuffix: ".xip.io"
    }, function (err, bs) {
        require('opn')(bs.options.url);
        console.log('Started connect web server on ' + bs.options.url);
    });
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;
    gulp.src('app/styles/*.scss')
        .pipe(wiredep({
            directory: 'app/bower_components'
        }))
        .pipe(gulp.dest('app/styles'));
    gulp.src('app/*.html')
        .pipe(wiredep({
            directory: 'app/bower_components',
            exclude: ['bootstrap-sass-official']
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('watch', ['serve'], function () {

    // watch for changes
    gulp.watch(['app/*.html'], reload);

    gulp.watch('app/styles/**/*.scss', ['styles']);
    gulp.watch('app/scripts/**/*.js', ['scripts']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('bower.json', ['wiredep']);
});
<commit_msg>Removes bootstrap-related code from gulpfile<commit_after>'use strict';
// generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>

var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gutil = require('gulp-util');

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {
    return gulp.src('app/styles/main.scss')
        .pipe($.sass({errLogToConsole: true}))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('app/styles'))
        .pipe(reload({stream:true}))
        .pipe($.size())
        .pipe($.notify("Compilation complete."));;
});

gulp.task('scripts', function () {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.jshint())
        .pipe($.jshint.reporter(require('jshint-stylish')))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe(reload({stream:true, once:true}))
        .pipe($.size());
});

gulp.task('fonts', function () {
    var streamqueue = require('streamqueue');
    return streamqueue({objectMode: true},
        $.bowerFiles(),
        gulp.src('app/fonts/**/*')
    )
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('dist/fonts'))
        .pipe($.size());
});

gulp.task('clean', function () {
    return gulp.src(['app/styles/main.css', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['html', 'images', 'fonts']);

gulp.task('default', ['clean'], function () {
    gulp.start('build');
});

gulp.task('serve', ['styles'], function () {
    browserSync.init(null, {
        server: {
            baseDir: 'app',
            directory: true
        },
        debugInfo: false,
        open: false,
        hostnameSuffix: ".xip.io"
    }, function (err, bs) {
        require('opn')(bs.options.url);
        console.log('Started connect web server on ' + bs.options.url);
    });
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;
    gulp.src('app/styles/*.scss')
        .pipe(wiredep({
            directory: 'app/bower_components'
        }))
        .pipe(gulp.dest('app/styles'));
    gulp.src('app/*.html')
        .pipe(wiredep({
            directory: 'app/bower_components'
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('watch', ['serve'], function () {

    // watch for changes
    gulp.watch(['app/*.html'], reload);

    gulp.watch('app/styles/**/*.scss', ['styles']);
    gulp.watch('app/scripts/**/*.js', ['scripts']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('bower.json', ['wiredep']);
});
<|endoftext|>