<commit_before>Package.describe({
    summary: 'Telescope custom package – use as template for your own packages',
    version: '0.1.0',
    name: 'my-custom-package'
});

Package.onUse(function (api) {

    // ---------------------------------- 1. Core dependency -----------------------------------

    api.use("telescope:core");

    // ---------------------------------- 2. Files to include ----------------------------------

    // i18n config (must come first)

    api.addFiles([
      'package-tap.i18n'
    ], ['client', 'server']);

    // client & server

    api.addFiles([
      'lib/custom_fields.js',
      'lib/template_modules.js',
      'lib/callbacks.js'
    ], ['client', 'server']);

    // client

    api.addFiles([
      'lib/client/templates/hello.html',
      'lib/client/templates/hello.js',
	  "lib/client/templates/custom_post_body.html",
	  "lib/client/templates/custom_post_body.js",
      'lib/client/templates/custom_post_title.html',
      'lib/client/templates/custom_post_title.js',
      'lib/client/stylesheets/custom.scss',
      'lib/client/custom_templates.js',
      'lib/client/templates/custom_main.html',
      'lib/client/templates/eduFooter.html',
      'lib/client/templates/eduFooter.js'
    ], ['client']);

    // server

    api.addFiles([
      'lib/server/templates/custom_emailPostItem.handlebars'
    ], ['server']);

    // i18n languages (must come last)

    api.addFiles([
      'i18n/en.i18n.json'
    ], ['client', 'server']);

});<commit_msg>Update package.js<commit_after>Package.describe({
    summary: 'Telescope custom package – use as template for your own packages',
    version: '0.1.0',
    name: 'my-custom-package'
});

Package.onUse(function (api) {

    // ---------------------------------- 1. Core dependency -----------------------------------

    api.use("telescope:core");

    // ---------------------------------- 2. Files to include ----------------------------------

    // i18n config (must come first)

    api.addFiles([
      'package-tap.i18n'
    ], ['client', 'server']);

    // client & server

    api.addFiles([
      'lib/custom_fields.js',
      'lib/template_modules.js',
      'lib/callbacks.js',
      'lib/custom_posts_view.js'
    ], ['client', 'server']);

    // client

    api.addFiles([
      'lib/client/templates/hello.html',
      'lib/client/templates/hello.js',
	  "lib/client/templates/custom_post_body.html",
	  "lib/client/templates/custom_post_body.js",
      'lib/client/templates/custom_post_title.html',
      'lib/client/templates/custom_post_title.js',
      'lib/client/stylesheets/custom.scss',
      'lib/client/custom_templates.js',
      'lib/client/templates/custom_main.html',
      'lib/client/templates/eduFooter.html',
      'lib/client/templates/eduFooter.js'
    ], ['client']);

    // server

    api.addFiles([
      'lib/server/templates/custom_emailPostItem.handlebars'
    ], ['server']);

    // i18n languages (must come last)

    api.addFiles([
      'i18n/en.i18n.json'
    ], ['client', 'server']);

});
<|endoftext|>


<commit_before>/**
 * ownCloud
 *
 * @author Vincent Petry
 * @copyright 2014 Vincent Petry <pvince81@owncloud.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * This node module is run by the karma executable to specify its configuration.
 *
 * The list of files from all needed JavaScript files including the ones from the
 * apps to test, and the test specs will be passed as configuration object.
 *
 * Note that it is possible to test a single app by setting the KARMA_TESTSUITE
 * environment variable to the apps name, for example "core" or "files_encryption".
 * Multiple apps can be specified by separating them with space.
 *
 * Setting the environment variable NOCOVERAGE to 1 will disable the coverage
 * preprocessor, which is needed to be able to debug tests properly in a browser.
 */

/* jshint node: true */
module.exports = function(config) {
	function findApps() {
		/*
		var fs = require('fs');
		var apps = fs.readdirSync('apps');
		return apps;
		*/
		// other apps tests don't run yet... needs further research / clean up
		return [
			'files',
			'files_trashbin',
			{
				name: 'files_sharing',
				srcFiles: [
					// only test these files, others are not ready and mess
					// up with the global namespace/classes/state
					'apps/files_sharing/js/app.js',
					'apps/files_sharing/js/sharedfilelist.js',
					'apps/files_sharing/js/share.js',
					'apps/files_sharing/js/sharebreadcrumbview.js',
					'apps/files_sharing/js/public.js',
					'apps/files_sharing/js/sharetabview.js',
					'apps/files_sharing/js/files_drop.js',
					'apps/files_sharing/js/templates.js',
				],
				testFiles: ['apps/files_sharing/tests/js/*.js']
			},
			{
				name: 'files_external',
				srcFiles: [
					// only test these files, others are not ready and mess
					// up with the global namespace/classes/state
					'apps/files_external/js/app.js',
					'apps/files_external/js/mountsfilelist.js',
					'apps/files_external/js/settings.js',
					'apps/files_external/js/statusmanager.js'
				],
				testFiles: ['apps/files_external/tests/js/*.js']
			},
			{
				name: 'files_versions',
				srcFiles: [
					// need to enforce loading order...
					'apps/files_versions/js/versionmodel.js',
					'apps/files_versions/js/templates.js',
					'apps/files_versions/js/versioncollection.js',
					'apps/files_versions/js/versionstabview.js'
				],
				testFiles: ['apps/files_versions/tests/js/**/*.js']
			},
			{
				name: 'comments',
				srcFiles: [
					// need to enforce loading order...
					'apps/comments/js/app.js',
					'apps/comments/js/templates.js',
					'apps/comments/js/vendor/Caret.js/dist/jquery.caret.min.js',
					'apps/comments/js/vendor/At.js/dist/js/jquery.atwho.min.js',
					'apps/comments/js/commentmodel.js',
					'apps/comments/js/commentcollection.js',
					'apps/comments/js/commentsummarymodel.js',
					'apps/comments/js/commentsmodifymenu.js',
					'apps/comments/js/commentstabview.js',
					'apps/comments/js/filesplugin.js'
				],
				testFiles: ['apps/comments/tests/js/**/*.js']
			},
			{
				name: 'systemtags',
				srcFiles: [
					// need to enforce loading order...
					'apps/systemtags/js/app.js',
					'apps/systemtags/js/systemtagsinfoview.js',
					'apps/systemtags/js/systemtagsinfoviewtoggleview.js',
					'apps/systemtags/js/systemtagsfilelist.js',
					'apps/systemtags/js/filesplugin.js'
				],
				testFiles: ['apps/systemtags/tests/js/**/*.js']
			},
			{
				name: 'settings',
				srcFiles: [
					'settings/js/apps.js',
					'core/vendor/marked/marked.min.js'
				]
			}
		];
	}

	// respect NOCOVERAGE env variable
	// it is useful to disable coverage for debugging
	// because the coverage preprocessor will wrap the JS files somehow
	var enableCoverage = !parseInt(process.env.NOCOVERAGE, 10);
	console.log(
		'Coverage preprocessor: ',
		enableCoverage ? 'enabled' : 'disabled'
	);

	// default apps to test when none is specified (TODO: read from filesystem ?)
	var appsToTest = process.env.KARMA_TESTSUITE;
	if (appsToTest) {
		appsToTest = appsToTest.split(' ');
	} else {
		appsToTest = ['core'].concat(findApps());
	}

	console.log('Apps to test: ', appsToTest);

	// read core files from core.json,
	// these are required by all apps so always need to be loaded
	// note that the loading order is important that's why they
	// are specified in a separate file
	var corePath = 'core/js/';
	var vendorPath = 'core/vendor/';
	var coreModule = require('../' + corePath + 'core.json');
	var testCore = false;
	var files = [];
	var index;
	var preprocessors = {};

	// find out what apps to test from appsToTest
	index = appsToTest.indexOf('core');
	if (index > -1) {
		appsToTest.splice(index, 1);
		testCore = true;
	}

	// core mocks
	files.push(corePath + 'tests/specHelper.js');

	var srcFile, i;
	// add vendor library files
	for (i = 0; i < coreModule.vendor.length; i++) {
		srcFile = vendorPath + coreModule.vendor[i];
		files.push(srcFile);
	}

	// add core library files
	for (i = 0; i < coreModule.libraries.length; i++) {
		srcFile = corePath + coreModule.libraries[i];
		files.push(srcFile);
	}

	// add core modules files
	for (i = 0; i < coreModule.modules.length; i++) {
		srcFile = corePath + coreModule.modules[i];
		files.push(srcFile);
		if (enableCoverage) {
			preprocessors[srcFile] = 'coverage';
		}
	}

	// TODO: settings pages

	// need to test the core app as well ?
	if (testCore) {
		// core tests
		files.push(corePath + 'tests/specs/**/*.js');
	}

	function addApp(app) {
		// if only a string was specified, expand to structure
		if (typeof app === 'string') {
			app = {
				srcFiles: 'apps/' + app + '/js/**/*.js',
				testFiles: 'apps/' + app + '/tests/js/**/*.js'
			};
		}

		// add source files/patterns
		files = files.concat(app.srcFiles || []);
		// add test files/patterns
		files = files.concat(app.testFiles || []);
		if (enableCoverage) {
			// add coverage entry for each file/pattern
			for (var i = 0; i < app.srcFiles.length; i++) {
				preprocessors[app.srcFiles[i]] = 'coverage';
			}
		}
	}

	// add source files for apps to test
	for (i = 0; i < appsToTest.length; i++) {
		addApp(appsToTest[i]);
	}

	// serve images to avoid warnings
	files.push({
		pattern: 'core/img/**/*',
		watched: false,
		included: false,
		served: true
	});
	files.push({
		pattern: 'core/css/images/*',
		watched: false,
		included: false,
		served: true
	});

	// include core CSS
	files.push({
		pattern: 'core/css/*.css',
		watched: true,
		included: true,
		served: true
	});
	files.push({
		pattern: 'tests/css/*.css',
		watched: true,
		included: true,
		served: true
	});

	// Allow fonts
	files.push({
		pattern: 'core/fonts/*',
		watched: false,
		included: false,
		served: true
	});

	config.set({
		// base path, that will be used to resolve files and exclude
		basePath: '..',

		// frameworks to use
		frameworks: ['jasmine', 'jasmine-sinon', 'viewport'],

		// list of files / patterns to load in the browser
		files: files,

		// list of files to exclude
		exclude: [],

		proxies: {
			// prevent warnings for images
			'/base/tests/img/': 'http://localhost:9876/base/core/img/',
			'/base/tests/css/': 'http://localhost:9876/base/core/css/',
			'/base/core/css/images/': 'http://localhost:9876/base/core/css/images/',
			'/actions/': 'http://localhost:9876/base/core/img/actions/',
			'/base/core/fonts/': 'http://localhost:9876/base/core/fonts/'
		},

		// test results reporter to use
		// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
		reporters: ['dots', 'junit', 'coverage'],

		junitReporter: {
			outputFile: 'tests/autotest-results-js.xml'
		},

		// web server port
		port: 9876,

		preprocessors: preprocessors,

		coverageReporter: {
			dir: 'tests/karma-coverage',
			reporters: [
				{ type: 'html' },
				{ type: 'cobertura' },
				{ type: 'lcovonly' }
			]
		},

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: true,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera (has to be installed with `npm install karma-opera-launcher`)
		// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
		// - PhantomJS
		// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
		// use PhantomJS_debug for extra local debug
		browsers: ['PhantomJS'],

		plugins: [
			'karma-phantomjs-launcher',
			'karma-coverage',
			'karma-jasmine',
			'karma-jasmine-sinon',
			'karma-viewport',
			'karma-junit-reporter'
		],
		// you can define custom flags
		customLaunchers: {
			PhantomJS_debug: {
				base: 'PhantomJS',
				debug: true
			}
		},

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000,

		// Continuous Integration mode
		// if true, it capture browsers, run tests and exit
		singleRun: false
	});
};
<commit_msg>Fix js unit tests<commit_after>/**
 * ownCloud
 *
 * @author Vincent Petry
 * @copyright 2014 Vincent Petry <pvince81@owncloud.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * This node module is run by the karma executable to specify its configuration.
 *
 * The list of files from all needed JavaScript files including the ones from the
 * apps to test, and the test specs will be passed as configuration object.
 *
 * Note that it is possible to test a single app by setting the KARMA_TESTSUITE
 * environment variable to the apps name, for example "core" or "files_encryption".
 * Multiple apps can be specified by separating them with space.
 *
 * Setting the environment variable NOCOVERAGE to 1 will disable the coverage
 * preprocessor, which is needed to be able to debug tests properly in a browser.
 */

/* jshint node: true */
module.exports = function(config) {
	function findApps() {
		/*
		var fs = require('fs');
		var apps = fs.readdirSync('apps');
		return apps;
		*/
		// other apps tests don't run yet... needs further research / clean up
		return [
			'files',
			'files_trashbin',
			{
				name: 'files_sharing',
				srcFiles: [
					// only test these files, others are not ready and mess
					// up with the global namespace/classes/state
					'apps/files_sharing/js/app.js',
					'apps/files_sharing/js/sharedfilelist.js',
					'apps/files_sharing/js/share.js',
					'apps/files_sharing/js/sharebreadcrumbview.js',
					'apps/files_sharing/js/public.js',
					'apps/files_sharing/js/sharetabview.js',
					'apps/files_sharing/js/files_drop.js',
					'apps/files_sharing/js/templates.js',
				],
				testFiles: ['apps/files_sharing/tests/js/*.js']
			},
			{
				name: 'files_external',
				srcFiles: [
					// only test these files, others are not ready and mess
					// up with the global namespace/classes/state
					'apps/files_external/js/app.js',
					'apps/files_external/js/templates.js',
					'apps/files_external/js/mountsfilelist.js',
					'apps/files_external/js/settings.js',
					'apps/files_external/js/statusmanager.js'
				],
				testFiles: ['apps/files_external/tests/js/*.js']
			},
			{
				name: 'files_versions',
				srcFiles: [
					// need to enforce loading order...
					'apps/files_versions/js/versionmodel.js',
					'apps/files_versions/js/templates.js',
					'apps/files_versions/js/versioncollection.js',
					'apps/files_versions/js/versionstabview.js'
				],
				testFiles: ['apps/files_versions/tests/js/**/*.js']
			},
			{
				name: 'comments',
				srcFiles: [
					// need to enforce loading order...
					'apps/comments/js/app.js',
					'apps/comments/js/templates.js',
					'apps/comments/js/vendor/Caret.js/dist/jquery.caret.min.js',
					'apps/comments/js/vendor/At.js/dist/js/jquery.atwho.min.js',
					'apps/comments/js/commentmodel.js',
					'apps/comments/js/commentcollection.js',
					'apps/comments/js/commentsummarymodel.js',
					'apps/comments/js/commentsmodifymenu.js',
					'apps/comments/js/commentstabview.js',
					'apps/comments/js/filesplugin.js'
				],
				testFiles: ['apps/comments/tests/js/**/*.js']
			},
			{
				name: 'systemtags',
				srcFiles: [
					// need to enforce loading order...
					'apps/systemtags/js/app.js',
					'apps/systemtags/js/systemtagsinfoview.js',
					'apps/systemtags/js/systemtagsinfoviewtoggleview.js',
					'apps/systemtags/js/systemtagsfilelist.js',
					'apps/systemtags/js/filesplugin.js'
				],
				testFiles: ['apps/systemtags/tests/js/**/*.js']
			},
			{
				name: 'settings',
				srcFiles: [
					'settings/js/apps.js',
					'core/vendor/marked/marked.min.js'
				]
			}
		];
	}

	// respect NOCOVERAGE env variable
	// it is useful to disable coverage for debugging
	// because the coverage preprocessor will wrap the JS files somehow
	var enableCoverage = !parseInt(process.env.NOCOVERAGE, 10);
	console.log(
		'Coverage preprocessor: ',
		enableCoverage ? 'enabled' : 'disabled'
	);

	// default apps to test when none is specified (TODO: read from filesystem ?)
	var appsToTest = process.env.KARMA_TESTSUITE;
	if (appsToTest) {
		appsToTest = appsToTest.split(' ');
	} else {
		appsToTest = ['core'].concat(findApps());
	}

	console.log('Apps to test: ', appsToTest);

	// read core files from core.json,
	// these are required by all apps so always need to be loaded
	// note that the loading order is important that's why they
	// are specified in a separate file
	var corePath = 'core/js/';
	var vendorPath = 'core/vendor/';
	var coreModule = require('../' + corePath + 'core.json');
	var testCore = false;
	var files = [];
	var index;
	var preprocessors = {};

	// find out what apps to test from appsToTest
	index = appsToTest.indexOf('core');
	if (index > -1) {
		appsToTest.splice(index, 1);
		testCore = true;
	}

	// core mocks
	files.push(corePath + 'tests/specHelper.js');

	var srcFile, i;
	// add vendor library files
	for (i = 0; i < coreModule.vendor.length; i++) {
		srcFile = vendorPath + coreModule.vendor[i];
		files.push(srcFile);
	}

	// add core library files
	for (i = 0; i < coreModule.libraries.length; i++) {
		srcFile = corePath + coreModule.libraries[i];
		files.push(srcFile);
	}

	// add core modules files
	for (i = 0; i < coreModule.modules.length; i++) {
		srcFile = corePath + coreModule.modules[i];
		files.push(srcFile);
		if (enableCoverage) {
			preprocessors[srcFile] = 'coverage';
		}
	}

	// TODO: settings pages

	// need to test the core app as well ?
	if (testCore) {
		// core tests
		files.push(corePath + 'tests/specs/**/*.js');
	}

	function addApp(app) {
		// if only a string was specified, expand to structure
		if (typeof app === 'string') {
			app = {
				srcFiles: 'apps/' + app + '/js/**/*.js',
				testFiles: 'apps/' + app + '/tests/js/**/*.js'
			};
		}

		// add source files/patterns
		files = files.concat(app.srcFiles || []);
		// add test files/patterns
		files = files.concat(app.testFiles || []);
		if (enableCoverage) {
			// add coverage entry for each file/pattern
			for (var i = 0; i < app.srcFiles.length; i++) {
				preprocessors[app.srcFiles[i]] = 'coverage';
			}
		}
	}

	// add source files for apps to test
	for (i = 0; i < appsToTest.length; i++) {
		addApp(appsToTest[i]);
	}

	// serve images to avoid warnings
	files.push({
		pattern: 'core/img/**/*',
		watched: false,
		included: false,
		served: true
	});
	files.push({
		pattern: 'core/css/images/*',
		watched: false,
		included: false,
		served: true
	});

	// include core CSS
	files.push({
		pattern: 'core/css/*.css',
		watched: true,
		included: true,
		served: true
	});
	files.push({
		pattern: 'tests/css/*.css',
		watched: true,
		included: true,
		served: true
	});

	// Allow fonts
	files.push({
		pattern: 'core/fonts/*',
		watched: false,
		included: false,
		served: true
	});

	config.set({
		// base path, that will be used to resolve files and exclude
		basePath: '..',

		// frameworks to use
		frameworks: ['jasmine', 'jasmine-sinon', 'viewport'],

		// list of files / patterns to load in the browser
		files: files,

		// list of files to exclude
		exclude: [],

		proxies: {
			// prevent warnings for images
			'/base/tests/img/': 'http://localhost:9876/base/core/img/',
			'/base/tests/css/': 'http://localhost:9876/base/core/css/',
			'/base/core/css/images/': 'http://localhost:9876/base/core/css/images/',
			'/actions/': 'http://localhost:9876/base/core/img/actions/',
			'/base/core/fonts/': 'http://localhost:9876/base/core/fonts/'
		},

		// test results reporter to use
		// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
		reporters: ['dots', 'junit', 'coverage'],

		junitReporter: {
			outputFile: 'tests/autotest-results-js.xml'
		},

		// web server port
		port: 9876,

		preprocessors: preprocessors,

		coverageReporter: {
			dir: 'tests/karma-coverage',
			reporters: [
				{ type: 'html' },
				{ type: 'cobertura' },
				{ type: 'lcovonly' }
			]
		},

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: true,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera (has to be installed with `npm install karma-opera-launcher`)
		// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
		// - PhantomJS
		// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
		// use PhantomJS_debug for extra local debug
		browsers: ['PhantomJS'],

		plugins: [
			'karma-phantomjs-launcher',
			'karma-coverage',
			'karma-jasmine',
			'karma-jasmine-sinon',
			'karma-viewport',
			'karma-junit-reporter'
		],
		// you can define custom flags
		customLaunchers: {
			PhantomJS_debug: {
				base: 'PhantomJS',
				debug: true
			}
		},

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000,

		// Continuous Integration mode
		// if true, it capture browsers, run tests and exit
		singleRun: false
	});
};
<|endoftext|>


<commit_before>/**
 * @desc	Creates a grid based on correlation values from a json file and highlights the top X amount from results.
 * @params	jsonLocation: location where the json file that defines the correlation values for the grid
 * 			results: the array that contains the nodes that need to be highlighted the grid
 * 			container: the HTML element that will contain the grid
 *			options: configurable options for the grid, possible options include:
 *				{
 *					canvasSize: 225,	// size of canvas in pixels
 *					highlightCount: 10,	// top x to highlight from results
 *					highlightValue: function(d) { return d[0]; },	// function used to select items from the results array to highlight
 					highlightTooltip: function(c) {},	// function performed on highlighted circles where c is the DOM path to them
 *				}
 * @author	Edward Y. Chen
 * @since	9/17/2012
 */

function createGrid(jsonLocation, results, container, options) {
	// Don't create grid if nowhere to put it
	if (d3.select(container).empty())
		return;

	// Grid actually goes in svg-container
	if (d3.select(container + ' div.svg-container').empty())
		d3.select(container).append('div').classed('svg-container', true);
	container += ' div.svg-container';

	// Grid attributes
	var gridAttr = {
		nodes: new Array(),
		canvasSize: 225,
		highlightCount: 10,
		highlightValue: function(d) { return d[0]; },
		highlightColor: '#FFFFFF',
		maxColor: '#FF6666',
		color: d3.scale.pow().exponent(5).interpolate(d3.interpolateRgb)
	}

	for (var key in options)
		gridAttr[key] = options[key];

	d3.json(jsonLocation, function(json) {
		var weights = json.weights;
		var texts = json.texts;

		gridAttr.width = Math.sqrt(weights.length),
		gridAttr.pixels = 225 / gridAttr.width;
		gridAttr.color.domain([0, d3.max(weights)])
			.range(['#000000', gridAttr.maxColor]);

		for (index in weights){
			var node = new GridNode(index, texts[index], weights[index]);
			gridAttr.nodes.push(node)
		}

		drawCanvas(container);
		var highlights = results.filter(function(d, i) { return i < gridAttr.highlightCount; });
		fill(highlights, container)
	});

	function GridNode(index, label, weight) {
		this.weight = weight;
		this.label = label;

		this.column = index % gridAttr.width;
		this.row = Math.floor(index / gridAttr.width);

		this.columnPixels = index % gridAttr.width * gridAttr.pixels;
		this.rowPixels = Math.floor(index / gridAttr.width) * gridAttr.pixels;
	}

	function drawCanvas(container) {
		var canvas = d3.select(container)
					.append('svg:svg')
					.attr('width', gridAttr.canvasSize)
					.attr('height', gridAttr.canvasSize);

		canvas.selectAll('rect')
			.data(gridAttr.nodes)
			.enter()
			.append('svg:rect')
			.attr('x', function(d,i) { return (d.columnPixels); })
			.attr('y', function(d,i) { return (d.rowPixels); })
			.attr('width', gridAttr.pixels)
			.attr('height', gridAttr.pixels)
			.attr('fill', function(d) { return gridAttr.color(d.weight); })
			.append('title')
			.text(function(d) { return d.label; });

		canvas.selectAll('circle')
			.data(gridAttr.nodes)
			.enter()
			.append('svg:circle')
			.attr('cx', function(d,i) { return (d.columnPixels) + gridAttr.pixels/2; })
			.attr('cy', function(d,i) { return (d.rowPixels) + gridAttr.pixels/2; })
			.attr('fill', gridAttr.highlightColor)
			.attr('fill-opacity', 0)
			.attr('r', Math.floor(gridAttr.pixels/3))
			.attr('label', function(d) { return d.label; })
			.append('title')
			.text(function(d) { return d.label; });
	}

	function fill(elementList, container) {
		for (e in elementList) {
			d3.selectAll(container + ' circle[label="' + gridAttr.highlightValue(elementList[e]) + '"]')
				.data(elementList, function(d) { return elementList[e]; })
				.attr('fill-opacity', 1)
				.classed('highlight', true);
		}

		if (typeof gridAttr.highlightTooltip != 'undefined') {
			gridAttr.highlightTooltip(container + ' circle.highlight');
		}
	}
}<commit_msg>Clean up variables and finish documentation<commit_after>/**
 * @desc	Creates a grid based on correlation values from a json file and highlights the top X amount from results.
 * @params	jsonLocation: location where the json file that defines the correlation values for the grid
 * 			results: the array that contains the nodes that need to be highlighted the grid
 * 			container: the HTML element that will contain the grid
 *			options: configurable options for the grid, possible options include:
 *				{
 *					canvasSize: 225,	// size of canvas in pixels
 *					highlightCount: 10,	// top x to highlight from results
 *					highlightValue: function(d) { return d[0]; },	// function used to select items from the results array to highlight
 					highlightTooltip: function(c) {},	// function performed on highlighted circles where c is the DOM path to them
 					highlightColor: #FFFFFF,	// Color of highlight circles
 					maxColor: #FF6666, 	// Grid ranges from black to this color using an exponential scale
 *				}
 * @author	Edward Y. Chen
 * @since	9/17/2012
 */

function createGrid(jsonLocation, results, container, options) {
	// Don't create grid if nowhere to put it
	if (d3.select(container).empty())
		return;

	// Grid actually goes in svg-container
	if (d3.select(container + ' div.svg-container').empty())
		d3.select(container).append('div').classed('svg-container', true);
	container += ' div.svg-container';

	// Grid attributes
	var gridAttr = {
		nodes: new Array(),
		canvasSize: 225,
		highlightCount: 10,
		highlightValue: function(d) { return d[0]; },
		highlightColor: '#FFFFFF',
		maxColor: '#FF6666',
		color: d3.scale.pow().exponent(5).interpolate(d3.interpolateRgb)
	}

	// Copy attributes from options to gridAttr
	for (var key in options)
		gridAttr[key] = options[key];

	d3.json(jsonLocation, function(json) {
		var weights = json.weights;
		var texts = json.texts;

		gridAttr.width = Math.sqrt(weights.length),
		gridAttr.pixels = 225 / gridAttr.width;
		gridAttr.color.domain([0, d3.max(weights)])
			.range(['#000000', gridAttr.maxColor]);

		for (index in weights){
			var node = new GridNode(index, texts[index], weights[index]);
			gridAttr.nodes.push(node)
		}

		drawCanvas(container);
		var highlights = results.filter(function(d, i) { return i < gridAttr.highlightCount; });
		fill(highlights, container)
	});

	function GridNode(index, label, weight) {
		this.weight = weight;
		this.label = label;

		this.columnPixels = index % gridAttr.width * gridAttr.pixels;
		this.rowPixels = Math.floor(index / gridAttr.width) * gridAttr.pixels;
	}

	function drawCanvas(container) {
		var canvas = d3.select(container)
					.append('svg:svg')
					.attr('width', gridAttr.canvasSize)
					.attr('height', gridAttr.canvasSize);

		canvas.selectAll('rect')
			.data(gridAttr.nodes)
			.enter()
			.append('svg:rect')
			.attr('x', function(d,i) { return (d.columnPixels); })
			.attr('y', function(d,i) { return (d.rowPixels); })
			.attr('width', gridAttr.pixels)
			.attr('height', gridAttr.pixels)
			.attr('fill', function(d) { return gridAttr.color(d.weight); })
			.append('title')
			.text(function(d) { return d.label; });

		canvas.selectAll('circle')
			.data(gridAttr.nodes)
			.enter()
			.append('svg:circle')
			.attr('cx', function(d,i) { return (d.columnPixels) + gridAttr.pixels/2; })
			.attr('cy', function(d,i) { return (d.rowPixels) + gridAttr.pixels/2; })
			.attr('fill', gridAttr.highlightColor)
			.attr('fill-opacity', 0)
			.attr('r', Math.floor(gridAttr.pixels/3))
			.attr('label', function(d) { return d.label; })
			.append('title')
			.text(function(d) { return d.label; });
	}

	function fill(elementList, container) {
		for (e in elementList) {
			d3.selectAll(container + ' circle[label="' + gridAttr.highlightValue(elementList[e]) + '"]')
				.data(elementList, function(d) { return elementList[e]; })
				.attr('fill-opacity', 1)
				.classed('highlight', true);
		}

		if (typeof gridAttr.highlightTooltip != 'undefined') {
			gridAttr.highlightTooltip(container + ' circle.highlight');
		}
	}
}<|endoftext|>


<commit_before>(function(){
    var resources = [
      "vendor/prismjs/prism.min.js",
    ];
    var head = document.head;
    var source = "https://sydjs.github.io/sydjs_zero/tutorial/"

    for (var resource in resources) {
      var element = document.createElement("script");
      element.href = source + resources[resource];
      head.appendChild(element);
    }
}());
<commit_msg>Logging the SCRIPT SRC value<commit_after>(function(){
    var resources = [
      "vendor/prismjs/prism.min.js",
    ];
    var head = document.head;
    var source = "https://sydjs.github.io/sydjs_zero/tutorial/"

    for (var resource in resources) {
      var element = document.createElement("script");
      element.src = source + resources[resource];

      console.log(element.src);
      head.appendChild(element);
    }
}());
<|endoftext|>


<commit_before>// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {

		// undefined is used here as the undefined global variable in ECMAScript 3 is
		// mutable (ie. it can be changed by someone else). undefined isn't really being
		// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
		// can no longer be modified.

		// window and document are passed through as local variable rather than global
		// as this (slightly) quickens the resolution process and can be more efficiently
		// minified (especially when both are regularly referenced in your plugin).

		// Create the defaults once
		var pluginName = "reveal",
				defaults = {
					revealElement: '.reveal',
					showWhenFromBottom: 100,
					unhideOnScrollUp: true,
					scrollUpUnhideSensitivity: 50
		};

		// The actual plugin constructor
		function Plugin ( element, options ) {
				this.element = element;
				// jQuery has an extend method which merges the contents of two or
				// more objects, storing the result in the first object. The first object
				// is generally empty as we don't want to alter the default options for
				// future instances of the plugin
				this.settings = $.extend( {}, defaults, options );
				this._defaults = defaults;
				this._name = pluginName;
				this.init();
		}

		Plugin.prototype = {
			init: function () {
				// Place initialization logic here
				// You already have access to the DOM element and
				// the options via the instance, e.g. this.element
				// and this.settings
				// you can add more functions like the one below and
				// call them like so: this.yourOtherFunction(this.element, this.settings).

				// get the viewport height
				this.documentHeight = $(document).height()-$(window).height();

				var _this = this;

				_this.totalElements = $(_this.settings.revealElement).length;

				var currentHeight = 0;
				var bodyPadding = 0;

				$(_this.settings.revealElement).each(function( index ) {
					currentHeight += $(this).outerHeight();

					if(currentHeight > $(window).height()) {
						$(this).css({'position': 'fixed','bottom': 0, 'zIndex': _this.totalElements - index}).addClass('stuck');
						bodyPadding += $(this).outerHeight();
					} else {
						$(this).css({'position': 'relative', 'zIndex': _this.totalElements - index}).addClass('flow');
					}
				});

				$('body').css('paddingBottom', bodyPadding);

				$(window).on('scroll', function() {
					_this.update(_this);
				});

				$(window).on('resize', function() {
					_this.update(_this);
				});
			},
			update: function (_this) {
				var s = $(window).scrollTop();
				var flowHeight = 0;

				var stuck = $('.stuck');
				var flow = $('.flow');

				$('.flow').each(function() {
					flowHeight += $(this).outerHeight();
				});

				if(stuck.length > 0) {
					if(stuck.first().offset().top >= flowHeight) {
						stuck.first().removeClass('stuck').addClass('flow').css({'position': 'relative', 'bottom': 'auto'});
						$('body').css('padding-bottom', parseInt($('body').css('padding-bottom')) - $('.flow').last().outerHeight());
					}
				}
				if(flowHeight >= $(window).height() + s) {
					$('.flow').last().removeClass('flow').addClass('stuck').css({'position': 'fixed', 'bottom': 0});
					$('body').css('padding-bottom', parseInt($('body').css('padding-bottom')) + $('.stuck').first().outerHeight());
				}
			}
		};

		// A really lightweight plugin wrapper around the constructor,
		// preventing against multiple instantiations
		$.fn[ pluginName ] = function ( options ) {
				return this.each(function() {
						if ( !$.data( this, "plugin_" + pluginName ) ) {
								$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
						}
				});
		};

})( jQuery, window, document );<commit_msg>No need to unstick last element<commit_after>// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {

		// undefined is used here as the undefined global variable in ECMAScript 3 is
		// mutable (ie. it can be changed by someone else). undefined isn't really being
		// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
		// can no longer be modified.

		// window and document are passed through as local variable rather than global
		// as this (slightly) quickens the resolution process and can be more efficiently
		// minified (especially when both are regularly referenced in your plugin).

		// Create the defaults once
		var pluginName = "reveal",
				defaults = {
					revealElement: '.reveal',
					showWhenFromBottom: 100,
					unhideOnScrollUp: true,
					scrollUpUnhideSensitivity: 50
		};

		// The actual plugin constructor
		function Plugin ( element, options ) {
				this.element = element;
				// jQuery has an extend method which merges the contents of two or
				// more objects, storing the result in the first object. The first object
				// is generally empty as we don't want to alter the default options for
				// future instances of the plugin
				this.settings = $.extend( {}, defaults, options );
				this._defaults = defaults;
				this._name = pluginName;
				this.init();
		}

		Plugin.prototype = {
			init: function () {
				// Place initialization logic here
				// You already have access to the DOM element and
				// the options via the instance, e.g. this.element
				// and this.settings
				// you can add more functions like the one below and
				// call them like so: this.yourOtherFunction(this.element, this.settings).

				// get the viewport height
				this.documentHeight = $(document).height()-$(window).height();

				var _this = this;

				_this.totalElements = $(_this.settings.revealElement).length;

				var currentHeight = 0;
				var bodyPadding = 0;

				$(_this.settings.revealElement).each(function( index ) {
					currentHeight += $(this).outerHeight();

					if(currentHeight > $(window).height()) {
						$(this).css({'position': 'fixed','bottom': 0, 'zIndex': _this.totalElements - index}).addClass('stuck');
						bodyPadding += $(this).outerHeight();
					} else {
						$(this).css({'position': 'relative', 'zIndex': _this.totalElements - index}).addClass('flow');
					}
				});

				$('body').css('paddingBottom', bodyPadding);

				$(window).on('scroll', function() {
					_this.update(_this);
				});

				$(window).on('resize', function() {
					_this.update(_this);
				});
			},
			update: function (_this) {
				var s = $(window).scrollTop();
				var flowHeight = 0;

				var stuck = $('.stuck');
				var flow = $('.flow');

				$('.flow').each(function() {
					flowHeight += $(this).outerHeight();
				});

				if(stuck.length > 0) {
					if(stuck.first().offset().top > flowHeight) {
						stuck.first().removeClass('stuck').addClass('flow').css({'position': 'relative', 'bottom': 'auto'});
						$('body').css('padding-bottom', parseInt($('body').css('padding-bottom')) - $('.flow').last().outerHeight());
					}
				}
				if(flowHeight >= $(window).height() + s) {
					$('.flow').last().removeClass('flow').addClass('stuck').css({'position': 'fixed', 'bottom': 0});
					$('body').css('padding-bottom', parseInt($('body').css('padding-bottom')) + $('.stuck').first().outerHeight());
				}
			}
		};

		// A really lightweight plugin wrapper around the constructor,
		// preventing against multiple instantiations
		$.fn[ pluginName ] = function ( options ) {
				return this.each(function() {
						if ( !$.data( this, "plugin_" + pluginName ) ) {
								$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
						}
				});
		};

})( jQuery, window, document );<|endoftext|>


<commit_before>/**
 * @fileOverview A wrapper for the Jetty HTTP server.
 */

export('Server');

var log = require('ringo/logging').getLogger(module.id);

/**
 * Create a Jetty HTTP server with the given options. The options may
 * either define properties to be used with the default jetty.xml, or define
 * a custom configuration file.
 *
 * @param {Object} options A javascript object with any of the following properties,
 * with the default value in parentheses:
 *

 *
jettyConfig ('config/jetty.xml')

 *
port (8080)

 *
host (undefined)

 *

 *
 * For convenience, the constructor supports the definition of a JSGI application
 * and static resource mapping in the config object using the following properties:
 *

 *
virtualHost (undefined)

 *
mountpoint ('/')

 *
staticDir ('static')

 *
staticMountpoint ('/static')

 *
config ('config')

 *
app ('app')

 *

 */
function Server(options) {

    if (!(this instanceof Server)) {
        return new Server(options);
    }

    // the jetty server instance
    var jetty;
    var defaultContext;
    var contextMap = {};
    var xmlconfig;

    /**
     * Get the server's default context. The default context is the
     * context that is created when the server is created.
     * @since: 0.6
     * @returns the default context
     */
    this.getDefaultContext = function() {
        return defaultContext;
    };

    /**
     * Get a servlet application context for the given path and virtual hosts, creating
     * it if it doesn't exist.
     * @param {string} path the context root path such as "/" or "/app"
     * @param {string|array} virtualHosts optional single or multiple virtual host names.
     *   A virtual host may start with a "*." wildcard.
     * @param {Object} options may have the following properties:
     *   sessions: true to enable sessions for this context, false otherwise
     *   security: true to enable security for this context, false otherwise
     * @since: 0.6
     * @returns a Context object
     */
    this.getContext = function(path, virtualHosts, options) {
        var idMap = xmlconfig.getIdMap();
        options = options || {};
        var contextKey = virtualHosts ? String(virtualHosts) + path : path;
        var cx = contextMap[contextKey];
        if (!cx) {
            var contexts = idMap.get("Contexts");
            var sessions = Boolean(options.sessions);
            var security = Boolean(options.security);
            cx = new org.eclipse.jetty.servlet.ServletContextHandler(contexts, path, sessions, security);
            if (virtualHosts) {
                cx.setVirtualHosts(Array.isArray(virtualHosts) ? virtualHosts : [String(virtualHosts)]);
            }
            contextMap[contextKey] = cx;
            if (jetty.isRunning()) {
                cx.start();
            }
        }

        return {
            /**
             * Map this context to a JSGI application.
             * @param {function|object} app a JSGI application, either as a function or an object
             *   with properties config and app defining
             *   the application.
             *
{ config: 'config', app: 'app' }

             * @param {RhinoEngine} engine optional RhinoEngine instance for multi-engine setups
             * @since: 0.6
             * @name Context.instance.serveApplication
             */
            serveApplication: function(app, engine) {
                log.debug("Adding JSGI application:", cx, "->", app);
                engine = engine || require('ringo/engine').getRhinoEngine();
                var isFunction = typeof app === "function";
                var servlet = isFunction ?
                              new JsgiServlet(engine, app) :
                              new JsgiServlet(engine);
                var jpkg = org.eclipse.jetty.servlet;
                var servletHolder = new jpkg.ServletHolder(servlet);
                if (!isFunction) {
                    servletHolder.setInitParameter('config', app.config || 'config');
                    servletHolder.setInitParameter('app', app.app || 'app');
                }
                cx.addServlet(servletHolder, "/*");
            },
            /**
             * Map this context to a directory containing static resources.
             * @param {string} dir the directory from which to serve static resources
             * @since: 0.6
             * @name Context.instance.serveStatic
             */
            serveStatic: function(dir) {
                log.debug("Adding static handler:", cx, "->", dir);
                var repo = getRepository(dir);
                cx.setResourceBase(repo.exists() ? repo.getPath() : dir);
                var jpkg = org.eclipse.jetty.servlet;
                var servletHolder = new jpkg.ServletHolder(jpkg.DefaultServlet);
                cx.addServlet(servletHolder, "/*");
            },
            /**
             * Map a request path within this context to the given servlet.
             * @param {string} servletPath the servlet path
             * @param {Servlet} servlet a java object implementing the javax.servlet.Servlet interface.
             * @param {Object} initParams optional object containing servlet init parameters
             * @since: 0.6
             * @name Context.instance.addServlet
             */
            addServlet: function(servletPath, servlet, initParams) {
                log.debug("Adding Servlet:", servletPath, "->", servlet);
                var jpkg = org.eclipse.jetty.servlet;
                var servletHolder = new jpkg.ServletHolder(servlet);
                for (var p in initParams) {
                    servletHolder.setInitParameter(p, initParams[p])
                }
                cx.addServlet(servletHolder, servletPath);
            }
        };
    };

    /**
     * Start the HTTP server.
     */
    this.start = function() {
        jetty.start();
    };

    /**
     * Stop the HTTP server.
     */
    this.stop = function() {
        jetty.stop();
    };

    /**
     * Destroy the HTTP server, freeing its resources.
     */
    this.destroy = function() {
        jetty.destroy();
    };

    /**
     * Checks whether this server is currently running.
     * @returns true if the server is running, false otherwise.
     */
    this.isRunning = function() {
        return jetty != null && jetty.isRunning();
    };

    /**
     * Get the Jetty server instance
     * @returns the Jetty Server instance
     */
    this.getJetty = function() {
        return jetty;
    };

    options = options || {};

    var jettyFile = options.jettyConfig || 'config/jetty.xml';
    var jettyConfig = getResource(jettyFile);
    if (!jettyConfig.exists()) {
        throw Error('Resource "' + jettyFile + '" not found');
    }
    var XmlConfiguration = org.eclipse.jetty.xml.XmlConfiguration;
    var JsgiServlet = org.ringojs.jsgi.JsgiServlet;
    jetty = new org.eclipse.jetty.server.Server();
    xmlconfig = new XmlConfiguration(jettyConfig.inputStream);
    // port config is done via properties
    var props = xmlconfig.getProperties();
    props.put('port', (options.port || 8080).toString());
    if (options.host) props.put('host', options.host);
    xmlconfig.configure(jetty);

    // create default context
    defaultContext = this.getContext(options.mountpoint || "/", options.virtualHost, {
        security: true,
        sessions: true
    });

    // If options defines an application mount it
    if (typeof options.app === "function") {
        defaultContext.serveApplication(options.app);
    } else if (options.app && options.config) {
        defaultContext.serveApplication(options);
    }

    // Allow definition of app/static mappings in server config for convenience
    if (options.staticDir) {
        var files = require('ringo/utils/files');
        var staticContext = this.getContext(options.staticMountpoint || '/static', options.virtualHost);
        staticContext.serveStatic(files.resolveId(options.config, options.staticDir));
    }

    // Start listeners. This allows us to run on priviledged port 80 under jsvc
    // even as non-root user if the constructor is called with root privileges
    // while start() is called with the user we will actually run as
    var connectors = jetty.getConnectors();
    for each (var connector in connectors) {
        connector.open();
    }

}

<commit_msg>Log the URL httpserver listens on (after startup)<commit_after>/**
 * @fileOverview A wrapper for the Jetty HTTP server.
 */

export('Server');

var log = require('ringo/logging').getLogger(module.id);

/**
 * Create a Jetty HTTP server with the given options. The options may
 * either define properties to be used with the default jetty.xml, or define
 * a custom configuration file.
 *
 * @param {Object} options A javascript object with any of the following properties,
 * with the default value in parentheses:
 *

 *
jettyConfig ('config/jetty.xml')

 *
port (8080)

 *
host (undefined)

 *

 *
 * For convenience, the constructor supports the definition of a JSGI application
 * and static resource mapping in the config object using the following properties:
 *

 *
virtualHost (undefined)

 *
mountpoint ('/')

 *
staticDir ('static')

 *
staticMountpoint ('/static')

 *
config ('config')

 *
app ('app')

 *

 */
function Server(options) {

    if (!(this instanceof Server)) {
        return new Server(options);
    }

    // the jetty server instance
    var jetty;
    var defaultContext;
    var contextMap = {};
    var xmlconfig;

    /**
     * Get the server's default context. The default context is the
     * context that is created when the server is created.
     * @since: 0.6
     * @returns the default context
     */
    this.getDefaultContext = function() {
        return defaultContext;
    };

    /**
     * Get a servlet application context for the given path and virtual hosts, creating
     * it if it doesn't exist.
     * @param {string} path the context root path such as "/" or "/app"
     * @param {string|array} virtualHosts optional single or multiple virtual host names.
     *   A virtual host may start with a "*." wildcard.
     * @param {Object} options may have the following properties:
     *   sessions: true to enable sessions for this context, false otherwise
     *   security: true to enable security for this context, false otherwise
     * @since: 0.6
     * @returns a Context object
     */
    this.getContext = function(path, virtualHosts, options) {
        var idMap = xmlconfig.getIdMap();
        options = options || {};
        var contextKey = virtualHosts ? String(virtualHosts) + path : path;
        var cx = contextMap[contextKey];
        if (!cx) {
            var contexts = idMap.get("Contexts");
            var sessions = Boolean(options.sessions);
            var security = Boolean(options.security);
            cx = new org.eclipse.jetty.servlet.ServletContextHandler(contexts, path, sessions, security);
            if (virtualHosts) {
                cx.setVirtualHosts(Array.isArray(virtualHosts) ? virtualHosts : [String(virtualHosts)]);
            }
            contextMap[contextKey] = cx;
            if (jetty.isRunning()) {
                cx.start();
            }
        }

        return {
            /**
             * Map this context to a JSGI application.
             * @param {function|object} app a JSGI application, either as a function or an object
             *   with properties config and app defining
             *   the application.
             *
{ config: 'config', app: 'app' }

             * @param {RhinoEngine} engine optional RhinoEngine instance for multi-engine setups
             * @since: 0.6
             * @name Context.instance.serveApplication
             */
            serveApplication: function(app, engine) {
                log.debug("Adding JSGI application:", cx, "->", app);
                engine = engine || require('ringo/engine').getRhinoEngine();
                var isFunction = typeof app === "function";
                var servlet = isFunction ?
                              new JsgiServlet(engine, app) :
                              new JsgiServlet(engine);
                var jpkg = org.eclipse.jetty.servlet;
                var servletHolder = new jpkg.ServletHolder(servlet);
                if (!isFunction) {
                    servletHolder.setInitParameter('config', app.config || 'config');
                    servletHolder.setInitParameter('app', app.app || 'app');
                }
                cx.addServlet(servletHolder, "/*");
            },
            /**
             * Map this context to a directory containing static resources.
             * @param {string} dir the directory from which to serve static resources
             * @since: 0.6
             * @name Context.instance.serveStatic
             */
            serveStatic: function(dir) {
                log.debug("Adding static handler:", cx, "->", dir);
                var repo = getRepository(dir);
                cx.setResourceBase(repo.exists() ? repo.getPath() : dir);
                var jpkg = org.eclipse.jetty.servlet;
                var servletHolder = new jpkg.ServletHolder(jpkg.DefaultServlet);
                cx.addServlet(servletHolder, "/*");
            },
            /**
             * Map a request path within this context to the given servlet.
             * @param {string} servletPath the servlet path
             * @param {Servlet} servlet a java object implementing the javax.servlet.Servlet interface.
             * @param {Object} initParams optional object containing servlet init parameters
             * @since: 0.6
             * @name Context.instance.addServlet
             */
            addServlet: function(servletPath, servlet, initParams) {
                log.debug("Adding Servlet:", servletPath, "->", servlet);
                var jpkg = org.eclipse.jetty.servlet;
                var servletHolder = new jpkg.ServletHolder(servlet);
                for (var p in initParams) {
                    servletHolder.setInitParameter(p, initParams[p])
                }
                cx.addServlet(servletHolder, servletPath);
            }
        };
    };

    /**
     * Start the HTTP server.
     */
    this.start = function() {
        jetty.start();
        log.info('Server on http://' + (props.get('host') || 'localhost') +
                ':' + props.get('port') + ' started.');
    };

    /**
     * Stop the HTTP server.
     */
    this.stop = function() {
        jetty.stop();
    };

    /**
     * Destroy the HTTP server, freeing its resources.
     */
    this.destroy = function() {
        jetty.destroy();
    };

    /**
     * Checks whether this server is currently running.
     * @returns true if the server is running, false otherwise.
     */
    this.isRunning = function() {
        return jetty != null && jetty.isRunning();
    };

    /**
     * Get the Jetty server instance
     * @returns the Jetty Server instance
     */
    this.getJetty = function() {
        return jetty;
    };

    options = options || {};

    var jettyFile = options.jettyConfig || 'config/jetty.xml';
    var jettyConfig = getResource(jettyFile);
    if (!jettyConfig.exists()) {
        throw Error('Resource "' + jettyFile + '" not found');
    }
    var XmlConfiguration = org.eclipse.jetty.xml.XmlConfiguration;
    var JsgiServlet = org.ringojs.jsgi.JsgiServlet;
    jetty = new org.eclipse.jetty.server.Server();
    xmlconfig = new XmlConfiguration(jettyConfig.inputStream);
    // port config is done via properties
    var props = xmlconfig.getProperties();
    props.put('port', (options.port || 8080).toString());
    if (options.host) props.put('host', options.host);
    xmlconfig.configure(jetty);

    // create default context
    defaultContext = this.getContext(options.mountpoint || "/", options.virtualHost, {
        security: true,
        sessions: true
    });

    // If options defines an application mount it
    if (typeof options.app === "function") {
        defaultContext.serveApplication(options.app);
    } else if (options.app && options.config) {
        defaultContext.serveApplication(options);
    }

    // Allow definition of app/static mappings in server config for convenience
    if (options.staticDir) {
        var files = require('ringo/utils/files');
        var staticContext = this.getContext(options.staticMountpoint || '/static', options.virtualHost);
        staticContext.serveStatic(files.resolveId(options.config, options.staticDir));
    }

    // Start listeners. This allows us to run on priviledged port 80 under jsvc
    // even as non-root user if the constructor is called with root privileges
    // while start() is called with the user we will actually run as
    var connectors = jetty.getConnectors();
    for each (var connector in connectors) {
        connector.open();
    }

}

<|endoftext|>


<commit_before>const Action = require("../models/action");

// Below are the possible actions
var actions = {
    // Normal user actions
    signIn: {
        displayName: "Sign in",
        inlineDisplayName: "Signed in",
        category: "auth"
    },
    signUp: {
        displayName: "Sign up",
        inlineDisplayName: "Signed up",
        category: "auth"
    },
    signOut: {
        displayName: "Sign out",
        inlineDisplayName: "Signed out",
        category: "auth"
    },
    changePassword: {
        displayName: "Change password",
        inlineDisplayName: "Changed password",
        category: "account"
    },
    deactivate: {
        displayName: "Deactivate own account",
        inlineDisplayName: "Deactivated their account",
        category: "account"
    },
    place: {
        displayName: "Place pixel",
        inlineDisplayName: "Placed a pixel",
        category: "gameplay",
        hideInfo: true,
        sentenceEndTextFormatting: " at (${x}, ${y})"
    },
    sendChatMessage: {
        displayName: "Send chat message",
        inlineDisplayName: "Sent a chat message",
        category: "chat"
    },
    // Moderation actions
    ban: {
        displayName: "Ban user",
        inlineDisplayName: "Banned user",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    unban: {
        displayName: "Unban user",
        inlineDisplayName: "Unbanned user",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    activateOther: {
        displayName: "Activate account",
        inlineDisplayName: "Activated account",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    deactivateOther: {
        displayName: "Deactivate account",
        inlineDisplayName: "Deactivated account",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    updateNotes: {
        displayName: "Update user notes",
        inlineDisplayName: "Updated user notes for",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    // Administrative actions
    giveModerator: {
        displayName: "Give moderator",
        inlineDisplayName: "Gave moderator to",
        category: "administrative",
        requiresModerator: true,
        isPrivileged: true
    },
    removeModerator: {
        displayName: "Remove moderator",
        inlineDisplayName: "Removed moderator from",
        category: "administrative",
        requiresModerator: true,
        isPrivileged: true
    },
    reloadConfig: {
        displayName: "Reload site configuration",
        inlineDisplayName: "Reloaded site configuration",
        category: "administrative",
        isPrivileged: true
    },
    refreshClients: {
        displayName: "Refresh all clients",
        inlineDisplayName: "Refreshed all clients",
        category: "administrative",
        isPrivileged: true
    },
    sendBroadcast: {
        displayName: "Broadcast a message to all users",
        inlineDisplayName: "Broadcasted a message to all users",
        category: "administrative",
        isPrivileged: true
    }
};

var actionLogger = {
    log: function(app, actionID, performingUser, moderatingUser = null, info = null) {
        Action({
            actionID: actionID,
            performingUserID: performingUser.id,
            moderatingUserID: moderatingUser ? moderatingUser.id : null,
            info: info,
            date: new Date()
        }).save().catch((err) => app.reportError("An error occurred while trying to log action: " + err));
    },

    infoForAction: function(actionID) {
        return actions[actionID];
    },

    getAllActionInfo: function() {
        return actions;
    },

    actionIDsToRetrieve: function(modOnly = false) {
        return Object.keys(actions).filter((a) => modOnly ? actions[a].isPrivileged : true);
    }
};

module.exports = actionLogger;
<commit_msg>Format coordinates properly in log<commit_after>const Action = require("../models/action");

// Below are the possible actions
var actions = {
    // Normal user actions
    signIn: {
        displayName: "Sign in",
        inlineDisplayName: "Signed in",
        category: "auth"
    },
    signUp: {
        displayName: "Sign up",
        inlineDisplayName: "Signed up",
        category: "auth"
    },
    signOut: {
        displayName: "Sign out",
        inlineDisplayName: "Signed out",
        category: "auth"
    },
    changePassword: {
        displayName: "Change password",
        inlineDisplayName: "Changed password",
        category: "account"
    },
    deactivate: {
        displayName: "Deactivate own account",
        inlineDisplayName: "Deactivated their account",
        category: "account"
    },
    place: {
        displayName: "Place pixel",
        inlineDisplayName: "Placed a pixel",
        category: "gameplay",
        hideInfo: true,
        sentenceEndTextFormatting: " at (${x.toLocaleString()}, ${y.toLocaleString()})"
    },
    sendChatMessage: {
        displayName: "Send chat message",
        inlineDisplayName: "Sent a chat message",
        category: "chat"
    },
    // Moderation actions
    ban: {
        displayName: "Ban user",
        inlineDisplayName: "Banned user",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    unban: {
        displayName: "Unban user",
        inlineDisplayName: "Unbanned user",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    activateOther: {
        displayName: "Activate account",
        inlineDisplayName: "Activated account",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    deactivateOther: {
        displayName: "Deactivate account",
        inlineDisplayName: "Deactivated account",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    updateNotes: {
        displayName: "Update user notes",
        inlineDisplayName: "Updated user notes for",
        category: "moderation",
        requiresModerator: true,
        isPrivileged: true
    },
    // Administrative actions
    giveModerator: {
        displayName: "Give moderator",
        inlineDisplayName: "Gave moderator to",
        category: "administrative",
        requiresModerator: true,
        isPrivileged: true
    },
    removeModerator: {
        displayName: "Remove moderator",
        inlineDisplayName: "Removed moderator from",
        category: "administrative",
        requiresModerator: true,
        isPrivileged: true
    },
    reloadConfig: {
        displayName: "Reload site configuration",
        inlineDisplayName: "Reloaded site configuration",
        category: "administrative",
        isPrivileged: true
    },
    refreshClients: {
        displayName: "Refresh all clients",
        inlineDisplayName: "Refreshed all clients",
        category: "administrative",
        isPrivileged: true
    },
    sendBroadcast: {
        displayName: "Broadcast a message to all users",
        inlineDisplayName: "Broadcasted a message to all users",
        category: "administrative",
        isPrivileged: true
    }
};

var actionLogger = {
    log: function(app, actionID, performingUser, moderatingUser = null, info = null) {
        Action({
            actionID: actionID,
            performingUserID: performingUser.id,
            moderatingUserID: moderatingUser ? moderatingUser.id : null,
            info: info,
            date: new Date()
        }).save().catch((err) => app.reportError("An error occurred while trying to log action: " + err));
    },

    infoForAction: function(actionID) {
        return actions[actionID];
    },

    getAllActionInfo: function() {
        return actions;
    },

    actionIDsToRetrieve: function(modOnly = false) {
        return Object.keys(actions).filter((a) => modOnly ? actions[a].isPrivileged : true);
    }
};

module.exports = actionLogger;
<|endoftext|>


<commit_before>/*
 * decaffeinate suggestions:
 * DS101: Remove unnecessary use of Array.from
 * DS102: Remove unnecessary code created because of implicit returns
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
const AsciiArt = require('../lib/ascii-art');

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.

describe("AsciiArt", function() {
  let [workspaceElement, activationPromise] = Array.from([]);

  beforeEach(function() {
    workspaceElement = atom.views.getView(atom.workspace);
    activationPromise = atom.packages.activatePackage('ascii-art');

    return waitsForPromise(() => atom.workspace.open());
  });

  return it("converts", function() {
    const editor = atom.workspace.getActiveTextEditor();
    editor.insertText("cool");
    editor.selectAll();
    const changeHandler = jasmine.createSpy('changeHandler');
    editor.onDidChange(changeHandler);

    atom.commands.dispatch(workspaceElement, 'ascii-art:convert');

    waitsForPromise(() => activationPromise);

    waitsFor(() => changeHandler.callCount > 0);

    return runs(() =>
      expect(editor.getText()).toEqual(`\

                                   o888
  ooooooo     ooooooo     ooooooo   888
888     888 888     888 888     888 888
888         888     888 888     888 888
  88ooo888    88ooo88     88ooo88  o888o

\
`
      )
    );
  });
});
<commit_msg>remove warnings from decaffinating and ran standard --fix<commit_after>const AsciiArt = require('../lib/ascii-art');

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.

describe("AsciiArt", function() {
  let [workspaceElement, activationPromise] = Array.from([]);

  beforeEach(function() {
    workspaceElement = atom.views.getView(atom.workspace);
    activationPromise = atom.packages.activatePackage('ascii-art');

    return waitsForPromise(() => atom.workspace.open());
  });

  return it("converts", function() {
    const editor = atom.workspace.getActiveTextEditor();
    editor.insertText("cool");
    editor.selectAll();
    const changeHandler = jasmine.createSpy('changeHandler');
    editor.onDidChange(changeHandler);

    atom.commands.dispatch(workspaceElement, 'ascii-art:convert');

    waitsForPromise(() => activationPromise);

    waitsFor(() => changeHandler.callCount > 0);

    return runs(() =>
      expect(editor.getText()).toEqual(`\

                                   o888
  ooooooo     ooooooo     ooooooo   888
888     888 888     888 888     888 888
888         888     888 888     888 888
  88ooo888    88ooo88     88ooo88  o888o

\
`
      )
    );
  });
});
<|endoftext|>


<commit_before>var subject = require('../lib/exec');
var assert = require('assert');

/* global describe, it, beforeEach */

describe('exec', function() {
  var req;

  beforeEach(function() {
    req = {};
    req.package = {};
    req.prefix = '';
  });
  it('spawns a child process for the given command', function(done) {
    req.command = 'echo';
    req.args    = ['OK'];

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.data(cp.stdout, 'OK\n', done);
    });
  });
  it('passes if the command does not exist', function(done) {
    req.command = 'bad_command';

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.equal(cp, null);
      done();
    });
  });
  it('exports HOAGIE_NAME', function(done) {
    req.package.name = 'foo';
    req.command = 'bash';
    req.args    = ['-c', 'echo $HOAGIE_NAME'];

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.data(cp.stdout, 'foo\n', done);
    });
  });
  it('exports $HOAGIE_VERSION', function(done) {
    req.package.version = '1.2.3';
    req.command = 'bash';
    req.args    = ['-c', 'echo $HOAGIE_VERSION'];

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.data(cp.stdout, '1.2.3\n', done);
    });
  });
  it('exports $HOAGIE_COMMAND', function(done) {
    req.command = 'bash';
    req.args    = ['-c', 'echo $HOAGIE_COMMAND'];

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.data(cp.stdout, 'bash\n', done);
    });
  });
});
<commit_msg>Use printenv instead of bash for exec tests<commit_after>var subject = require('../lib/exec');
var assert = require('assert');

/* global describe, it, beforeEach */

describe('exec', function() {
  var req;

  beforeEach(function() {
    req = {};
    req.package = {};
    req.prefix = '';
  });
  it('spawns a child process for the given command', function(done) {
    req.command = 'echo';
    req.args = ['OK'];

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.data(cp.stdout, 'OK\n', done);
    });
  });
  it('passes if the command does not exist', function(done) {
    req.command = 'bad_command';

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.equal(cp, null);
      done();
    });
  });
  it('exports HOAGIE_NAME', function(done) {
    req.package.name = 'foo';
    req.command = 'printenv';
    req.args = ['HOAGIE_NAME'];

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.data(cp.stdout, 'foo\n', done);
    });
  });
  it('exports $HOAGIE_VERSION', function(done) {
    req.package.version = '1.2.3';
    req.command = 'printenv';
    req.args = ['HOAGIE_VERSION'];

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.data(cp.stdout, '1.2.3\n', done);
    });
  });
  it('exports $HOAGIE_COMMAND', function(done) {
    req.command = 'printenv';
    req.args = ['HOAGIE_COMMAND'];

    subject(req, function(err, cp) {
      assert.ifError(err);
      assert.data(cp.stdout, 'printenv\n', done);
    });
  });
});
<|endoftext|>


<commit_before>const fs = require('fs')
const tape = require('tape')
const Kernel = require('ewasm-kernel')
const ethUtil = require('ethereumjs-util')
const compiler = require('../index.js')
const dir = `${__dirname}/opcode`

let testFiles = fs.readdirSync(dir).filter((name) => name.endsWith('.json'))

tape('testing EVM1 Ops', (t) => {
  testFiles.forEach((path) => {
    let opTest = require(`${dir}/${path}`)
    opTest.forEach((test) => {
      const testInstance = buildTest(test.op)
      t.comment(`testing ${test.description}`)

      // populate the stack with predefined values
      test.stack.in.reverse().forEach((item, index) => {
        item = hexToUint8Array(item)
        setMemory(testInstance, item, index * 32)
      })

      // populate the memory
      if (test.memory) {
        Object.keys(test.memory.in).forEach((offset) => {
          test.memory.in[offset].forEach((item, index) => {
            offset |= 0
            item = hexToUint8Array(item)
            setMemory(testInstance, item, offset + index * 32)
          })
        })
      }

      // Runs the opcode. An empty stack must start with the stack pointer at -8.
      // also we have to add 8 to the resulting sp to accommodate for the fact
      // that the sp is pointing to memory segment holding the last stack item
      let sp = testInstance.exports[test.op](test.stack.in.length * 32 - 8) + 8
      t.equal(sp / 32, test.stack.out.length, 'should have corrent number of items on the stack')
      sp = 0

      // compare the output stack against the predefined values
      test.stack.out.forEach((item, index) => {
        const expectedItem = hexToUint8Array(item)
        const result = getMemory(testInstance, sp, sp = sp + 32)
        t.equals(result.toString(), expectedItem.toString(), 'should have correct item on stack')
      })

      // check the memory
      if (test.memory) {
        Object.keys(test.memory.out).forEach((offset) => {
          test.memory.out[offset].forEach((item, index) => {
            offset |= 0
            const expectedItem = hexToUint8Array(item)
            const result = getMemory(testInstance, offset + index * 32, offset + index * 32 + expectedItem.length)
            t.equals(result.toString(), expectedItem.toString(), `should have the correct memory slot at ${offset}:${index}`)
          })
        })
      }

    })
  })
  t.end()
})

function buildTest (op) {
  const funcs = compiler.resolveFunctions(new Set([op]))
  const linked = compiler.buildModule(funcs, [], [op])
  const wasm = compiler.compileWAST(linked)
  return Kernel.codeHandler(wasm)
}

function hexToUint8Array(item, length) {
  return new Uint8Array(ethUtil.setLength(new Buffer(item.slice(2), 'hex'), 32)).reverse()
}

function setMemory(instance, value, start) {
  new Uint8Array(instance.exports.memory).set(value, start)
}

function getMemory(instance, start, end) {
  return new Uint8Array(instance.exports.memory).slice(start, end)
}
<commit_msg>opcodeRunner: instantiate interface/environment locally<commit_after>const fs = require('fs')
const tape = require('tape')
const Kernel = require('ewasm-kernel')
const KernelInterface = require('ewasm-kernel/interface.js')
const KernelEnvironment = require('ewasm-kernel/environment.js')
const ethUtil = require('ethereumjs-util')
const compiler = require('../index.js')
const dir = `${__dirname}/opcode`

let testFiles = fs.readdirSync(dir).filter((name) => name.endsWith('.json'))

tape('testing EVM1 Ops', (t) => {
  testFiles.forEach((path) => {
    let opTest = require(`${dir}/${path}`)
    opTest.forEach((test) => {
      const testEnvironment = new KernelEnvironment()
      const testInterface = new KernelInterface(testEnvironment)
      const testInstance = buildTest(test.op)

      t.comment(`testing ${test.description}`)

      // populate the stack with predefined values
      test.stack.in.reverse().forEach((item, index) => {
        item = hexToUint8Array(item)
        setMemory(testInstance, item, index * 32)
      })

      // populate the memory
      if (test.memory) {
        Object.keys(test.memory.in).forEach((offset) => {
          test.memory.in[offset].forEach((item, index) => {
            offset |= 0
            item = hexToUint8Array(item)
            setMemory(testInstance, item, offset + index * 32)
          })
        })
      }

      // Runs the opcode. An empty stack must start with the stack pointer at -8.
      // also we have to add 8 to the resulting sp to accommodate for the fact
      // that the sp is pointing to memory segment holding the last stack item
      let sp = testInstance.exports[test.op](test.stack.in.length * 32 - 8) + 8
      t.equal(sp / 32, test.stack.out.length, 'should have corrent number of items on the stack')
      sp = 0

      // compare the output stack against the predefined values
      test.stack.out.forEach((item, index) => {
        const expectedItem = hexToUint8Array(item)
        const result = getMemory(testInstance, sp, sp = sp + 32)
        t.equals(result.toString(), expectedItem.toString(), 'should have correct item on stack')
      })

      // check the memory
      if (test.memory) {
        Object.keys(test.memory.out).forEach((offset) => {
          test.memory.out[offset].forEach((item, index) => {
            offset |= 0
            const expectedItem = hexToUint8Array(item)
            const result = getMemory(testInstance, offset + index * 32, offset + index * 32 + expectedItem.length)
            t.equals(result.toString(), expectedItem.toString(), `should have the correct memory slot at ${offset}:${index}`)
          })
        })
      }

    })
  })
  t.end()
})

function buildTest (op, interface) {
  const funcs = compiler.resolveFunctions(new Set([op]))
  const linked = compiler.buildModule(funcs, [], [op])
  const wasm = compiler.compileWAST(linked)
  return Kernel.codeHandler(wasm, interface)
}

function hexToUint8Array(item, length) {
  return new Uint8Array(ethUtil.setLength(new Buffer(item.slice(2), 'hex'), 32)).reverse()
}

function setMemory(instance, value, start) {
  new Uint8Array(instance.exports.memory).set(value, start)
}

function getMemory(instance, start, end) {
  return new Uint8Array(instance.exports.memory).slice(start, end)
}
<|endoftext|>


<commit_before>// Bootstrap the module system.

if (typeof Object.create !== 'function') {
    Object.create = function(parent) {
        function F() {}
        F.prototype = parent;
        return new F();
    };
}

if (typeof Object.newChildOf !== 'function') {
    Object.newChildOf = function(parent) {
        var child = Object.create(parent);
        if (child.initialize) {
          var args = $A(arguments); args.shift();
          child.initialize.apply(child, args);
        }
        return child;
    };
}

function annotationOf(o) {
  if (o.hasOwnProperty('__annotation__')) { return o.__annotation__; }
  return o.__annotation__ = {slotAnnotations: {}};
}

function annotationNameForSlotNamed(slotName) {
  // can't just use slotName because it leads to conflicts with stuff inherited from Object.prototype
  return "anno_" + slotName;
}

function existingSlotAnnotation(holder, name) {
  if (! holder.hasOwnProperty('__annotation__')) { return null; }
  var holderAnno = holder.__annotation__;
  if (! holderAnno.slotAnnotations) { return null; }
  return holderAnno.slotAnnotations[annotationNameForSlotNamed(name)];
}

function setCreatorSlot(annotation, name, holder) {
  annotation.creatorSlotName   = name;
  annotation.creatorSlotHolder = holder;
}

function creatorChainLength(o) {
  if (o === lobby) { return 0; }
  if (! o.hasOwnProperty('__annotation__')) { return null; }
  var creatorSlotHolder = o.__annotation__.creatorSlotHolder;
  if (creatorSlotHolder === undefined) { return null; }
  return creatorChainLength(creatorSlotHolder) + 1;
}

function copyDownSlots(dst, src, slotsToOmit) {
  slotsToOmit = slotsToOmit || [];
  if (typeof slotsToOmit === 'string') {
    slotsToOmit = slotsToOmit.split(" ");
  }
  slotsToOmit.push('__annotation__');

  var dstAnno = annotationOf(dst);
  for (var name in src) {
    if (src.hasOwnProperty(name)) {
      if (! slotsToOmit.include(name)) {
        dst[name] = src[name];

        // Copy down the category (and maybe other stuff?).
        try {if (name === 'addCategory') {throw "halt";}} catch (ex) {}
        var srcSlotAnno = existingSlotAnnotation(src, name);
        if (srcSlotAnno && srcSlotAnno.category) {
          var dstSlotAnno = dstAnno.slotAnnotations[annotationNameForSlotNamed(name)] = {};
          dstSlotAnno.category = srcSlotAnno.category;
        }
      }
    }
  }
}

// aaa - Copied from Base.js. Just a hack to make $super work. Not really sure
// what the right solution is in the long run - how do we make this work with
// both prototype-style inheritance and class-style inheritance?
function hackToMakeSuperWork(holder, property, contents) {
  var value = contents;
  var superclass = holder.constructor && holder.constructor.superclass;
  var ancestor = superclass && superclass.prototype;
  if (ancestor && Object.isFunction(value) && value.argumentNames && value.argumentNames().first() === "$super") {
    (function() { // wrapped in a method to save the value of 'method' for advice
      var method = value;
      var advice = (function(m) {
        return function callSuper() {
          return ancestor[m].apply(this, arguments);
        };
      })(property);
      advice.methodName = "$super:" + (superclass ? superclass.type + "." : "") + property;

      value = Object.extend(advice.wrap(method), {
        valueOf:  function() { return method },
        toString: function() { return method.toString() },
        originalFunction: method
      });
    })();
  }
  return value;
}

var lobby = window; // still not sure whether I want this to be window, or Object.create(window), or {}

lobby.modules = {};
setCreatorSlot(annotationOf(lobby.modules), 'modules', lobby);

lobby.transporter = {};
setCreatorSlot(annotationOf(lobby.transporter), 'transporter', lobby);

lobby.transporter.module = {};
setCreatorSlot(annotationOf(lobby.transporter.module), 'module', lobby.transporter);

lobby.transporter.module.cache = {};

lobby.transporter.module.named = function(n) {
  var m = lobby.modules[n];
  if (m) {return m;}
  m = lobby.modules[n] = Object.create(this);
  m._name = n;
  lobby.transporter.module.cache[n] = [];
  return m;
};

lobby.transporter.module.create = function(n, block) {
  if (lobby.modules[n]) { throw 'The ' + n + ' module is already loaded.'; }
  block(this.named(n));
};

lobby.transporter.module.slotAdder = {
  data: function(name, contents, slotAnnotation, contentsAnnotation) {
    if (! slotAnnotation) { slotAnnotation = {}; }
    this.holder[name] = contents;
    slotAnnotation.module = this.module;
    annotationOf(this.holder).slotAnnotations[annotationNameForSlotNamed(name)] = slotAnnotation;
    if (contentsAnnotation) { // used for creator slots
      var a = annotationOf(contents);
      a.creatorSlotName   = name;
      a.creatorSlotHolder = this.holder;
      Object.extend(a, contentsAnnotation);

      if (contentsAnnotation.copyDownParents) {
        for (var i = 0; i < contentsAnnotation.copyDownParents.length; i += 1) {
          var cdp = contentsAnnotation.copyDownParents[i];
          copyDownSlots(contents, cdp.parent, cdp.slotsToOmit);
        }
      }
    }
  },

  creator: function(name, contents, slotAnnotation, objectAnnotation) {
    this.data(name, contents, slotAnnotation, objectAnnotation || {});
  },

  method: function(name, contents, slotAnnotation) {
    this.creator(name, hackToMakeSuperWork(this.holder, name, contents), slotAnnotation);
  }
};

lobby.transporter.module.addSlots = function(holder, block) {
  lobby.transporter.module.cache[this._name].push(holder);
  var slotAdder = Object.create(this.slotAdder);
  slotAdder.module = this;
  slotAdder.holder = holder;
  block(slotAdder);
};
<commit_msg>Lalala.<commit_after>// Bootstrap the module system.

// aaa - This file is kind of a mess. Gotta figure out exactly what the
// minimal amount of stuff needed here is.

if (typeof Object.create !== 'function') {
    Object.create = function(parent) {
        function F() {}
        F.prototype = parent;
        return new F();
    };
}

if (typeof Object.newChildOf !== 'function') {
    Object.newChildOf = function(parent) {
        var child = Object.create(parent);
        if (child.initialize) {
          var args = $A(arguments); args.shift();
          child.initialize.apply(child, args);
        }
        return child;
    };
}

function annotationOf(o) {
  if (o.hasOwnProperty('__annotation__')) { return o.__annotation__; }
  return o.__annotation__ = {slotAnnotations: {}};
}

function annotationNameForSlotNamed(slotName) {
  // can't just use slotName because it leads to conflicts with stuff inherited from Object.prototype
  return "anno_" + slotName;
}

function existingSlotAnnotation(holder, name) {
  if (! holder.hasOwnProperty('__annotation__')) { return null; }
  var holderAnno = holder.__annotation__;
  if (! holderAnno.slotAnnotations) { return null; }
  return holderAnno.slotAnnotations[annotationNameForSlotNamed(name)];
}

function setCreatorSlot(annotation, name, holder) {
  annotation.creatorSlotName   = name;
  annotation.creatorSlotHolder = holder;
}

function creatorChainLength(o) {
  if (o === lobby) { return 0; }
  if (! o.hasOwnProperty('__annotation__')) { return null; }
  var creatorSlotHolder = o.__annotation__.creatorSlotHolder;
  if (creatorSlotHolder === undefined) { return null; }
  return creatorChainLength(creatorSlotHolder) + 1;
}

function copyDownSlots(dst, src, slotsToOmit) {
  slotsToOmit = slotsToOmit || [];
  if (typeof slotsToOmit === 'string') {
    slotsToOmit = slotsToOmit.split(" ");
  }
  slotsToOmit.push('__annotation__');

  var dstAnno = annotationOf(dst);
  for (var name in src) {
    if (src.hasOwnProperty(name)) {
      if (! slotsToOmit.include(name)) {
        dst[name] = src[name];

        // Copy down the category (and maybe other stuff?).
        try {if (name === 'addCategory') {throw "halt";}} catch (ex) {}
        var srcSlotAnno = existingSlotAnnotation(src, name);
        if (srcSlotAnno && srcSlotAnno.category) {
          var dstSlotAnno = dstAnno.slotAnnotations[annotationNameForSlotNamed(name)] = {};
          dstSlotAnno.category = srcSlotAnno.category;
        }
      }
    }
  }
}

// aaa - Copied from Base.js. Just a hack to make $super work. Not really sure
// what the right solution is in the long run - how do we make this work with
// both prototype-style inheritance and class-style inheritance?
function hackToMakeSuperWork(holder, property, contents) {
  var value = contents;
  var superclass = holder.constructor && holder.constructor.superclass;
  var ancestor = superclass && superclass.prototype;
  if (ancestor && Object.isFunction(value) && value.argumentNames && value.argumentNames().first() === "$super") {
    (function() { // wrapped in a method to save the value of 'method' for advice
      var method = value;
      var advice = (function(m) {
        return function callSuper() {
          return ancestor[m].apply(this, arguments);
        };
      })(property);
      advice.methodName = "$super:" + (superclass ? superclass.type + "." : "") + property;

      value = Object.extend(advice.wrap(method), {
        valueOf:  function() { return method },
        toString: function() { return method.toString() },
        originalFunction: method
      });
    })();
  }
  return value;
}

var lobby = window; // still not sure whether I want this to be window, or Object.create(window), or {}

lobby.modules = {};
setCreatorSlot(annotationOf(lobby.modules), 'modules', lobby);

lobby.transporter = {};
setCreatorSlot(annotationOf(lobby.transporter), 'transporter', lobby);

lobby.transporter.module = {};
setCreatorSlot(annotationOf(lobby.transporter.module), 'module', lobby.transporter);

lobby.transporter.module.cache = {};

lobby.transporter.module.named = function(n) {
  var m = lobby.modules[n];
  if (m) {return m;}
  m = lobby.modules[n] = Object.create(this);
  m._name = n;
  lobby.transporter.module.cache[n] = [];
  return m;
};

lobby.transporter.module.create = function(n, block) {
  if (lobby.modules[n]) { throw 'The ' + n + ' module is already loaded.'; }
  block(this.named(n));
};

lobby.transporter.module.slotAdder = {
  data: function(name, contents, slotAnnotation, contentsAnnotation) {
    if (! slotAnnotation) { slotAnnotation = {}; }
    this.holder[name] = contents;
    slotAnnotation.module = this.module;
    annotationOf(this.holder).slotAnnotations[annotationNameForSlotNamed(name)] = slotAnnotation;
    if (contentsAnnotation) { // used for creator slots
      var a = annotationOf(contents);
      a.creatorSlotName   = name;
      a.creatorSlotHolder = this.holder;
      Object.extend(a, contentsAnnotation);

      if (contentsAnnotation.copyDownParents) {
        for (var i = 0; i < contentsAnnotation.copyDownParents.length; i += 1) {
          var cdp = contentsAnnotation.copyDownParents[i];
          copyDownSlots(contents, cdp.parent, cdp.slotsToOmit);
        }
      }
    }
  },

  creator: function(name, contents, slotAnnotation, objectAnnotation) {
    this.data(name, contents, slotAnnotation, objectAnnotation || {});
  },

  method: function(name, contents, slotAnnotation) {
    this.creator(name, hackToMakeSuperWork(this.holder, name, contents), slotAnnotation);
  }
};

lobby.transporter.module.addSlots = function(holder, block) {
  lobby.transporter.module.cache[this._name].push(holder);
  var slotAdder = Object.create(this.slotAdder);
  slotAdder.module = this;
  slotAdder.holder = holder;
  block(slotAdder);
};
<|endoftext|>


<commit_before>import Phaser from 'phaser'
import MenuBuilder from '../controllers/menucontrol/MenuBuilder'
import utils from '../utils'
import config from '../../assets/json/configurations'

export default class Highscores extends Phaser.State {
  init (gameData) {
    this.gameData = gameData
  }
  create () {
    this.menu = new MenuBuilder(this, 'start', this.camera.height * 5 / 9, this.gameData.config)
    this.menu.createTitle('Tulokset')
    var scores = utils.fetchScores(config.gameSettings.scoreServer)
    var fmt = ''
    var i, score
    var len = scores.length
    for (i = 0; i < 5 && i < len; i++) {
      score = scores[i]
      fmt += (i + 1) + ': ' + score.player + ' - ' + score.points + '\n'
    }
    this.menu.createDescription(fmt)
    this.menu.createButton('Uusi peli',
      () => { this.state.start('Start', true, false, this.gameData) })
    this.menu.finishMenu()
  }
}
<commit_msg>fixed highscores<commit_after>import Phaser from 'phaser'
import MenuBuilder from '../controllers/menucontrol/MenuBuilder'
import utils from '../utils'
import config from '../../assets/json/configurations'

export default class Highscores extends Phaser.State {
  init (gameData) {
    this.gameData = gameData
  }
  create () {
    this.menu = new MenuBuilder(this, 'start', this.camera.height * 1 / 10, this.gameData.config)
    this.menu.createTitle('Tulokset')
    var scores = utils.fetchScores(config.gameSettings.scoreServer)
    var i, score
    var len = scores.length
    for (i = 0; i < 10 && i < len; i++) {
      score = scores[i]
      this.menu.createDescription('' + (i + 1) + ': ' + score.player + ' - ' + score.points + '\n')
    }
    this.menu.createButton('Uusi peli',
      () => { this.state.start('Start', true, false, this.gameData) })
    this.menu.finishMenu()
  }
}
<|endoftext|>


<commit_before>var recurse = require('../');
var test = require('tap').test;
var fs = require('fs');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');

// TODO: extract to module:
var testfs = require('./lib/testfs');

test('flat dir', function (t) {
  t.plan(3);

  testfs(['1.txt', '2.txt'], 'flat', function (err) {
    var writes = 0;

    var flat = recurse('flat');
    flat.on('data', function (data) {
      t.similar(data, /flat\/\d\.txt/);
      writes++;
    });
    flat.on('end', function () {
      t.equal(writes, 2);
      rimraf.sync('flat');
    });
  });
});
<commit_msg>Remove unused modules in flat test.<commit_after>var recurse = require('../');
var test = require('tap').test;
var rimraf = require('rimraf');

// TODO: extract to module:
var testfs = require('./lib/testfs');

test('flat dir', function (t) {
  t.plan(3);

  testfs(['1.txt', '2.txt'], 'flat', function (err) {
    var writes = 0;

    var flat = recurse('flat');
    flat.on('data', function (data) {
      t.similar(data, /flat\/\d\.txt/);
      writes++;
    });
    flat.on('end', function () {
      t.equal(writes, 2);
      rimraf.sync('flat');
    });
  });
});
<|endoftext|>


<commit_before>var App = App || {};
App.LoadAssetsState = App.LoadAssetsState || {};

App.LoadAssetsState = (function () {
    "use strict";

    // constructor: Run only once at compile time
    var fn = function (game) {
        Phaser.State.call(this, game);
    };
    fn.prototype = Object.create(Phaser.State.prototype);
    fn.prototype.constructor = fn;

    // init: Run every time this state is started or restart:
    fn.prototype.init = function () {
        this.game.assets = this.game.assets || {};
        this.game.assetsMustLoad = this.game.assetsMustLoad || {};
        this.game.assetsPreLoad = this.game.assetsPreLoad || {};
        this.game.assetsLoaded = this.game.assetsLoaded || {};
        this.game.assetsNextState = this.game.assetsNextState || "DefaultNextState";
    };

    // preload: Call "preload_TYPE" routine on each asset
    fn.prototype.preload = function () {
        for (var type in this.game.assetsMustLoad) {
            this.game.assetsPreLoad[type] = this.game.assetsPreLoad[type] || {};
            this.game.assetsLoaded[type] = this.game.assetsLoaded[type] || {};
            var handler = this["preload_" + type];
            if (handler && "function" === typeof handler) {
                for (var key in this.game.assetsMustLoad[type]) {
                    if (!this.game.assetsLoaded[type][key] &&
                        !this.game.assetsPreLoad[type][key]) {
                        var data = this.game.assetsMustLoad[type][key];
                        //this.game.assetsPreLoad[type][key] = handler(key,data);
                        this.game.assetsPreLoad[type][key] = this["preload_" + type](key,data);
                    }
                    delete this.game.assetsMustLoad[type][key];
                }
            }
            else {
                console.log('Asset handler "preload_' + type + '" not found for key "' + key + '"');
            }
            delete this.game.assetsMustLoad[type];
        }
    };

    // create: Call "process_TYPE" routine on each asset once preload is complete
    fn.prototype.create = function () {
        for (var type in this.game.assetsPreLoad) {
            this.game.assetsLoaded[type] = this.game.assetsLoaded[type] || {};
            var handler = this["process_" + type];
            if (handler && "function" === typeof handler) {
                for (var key in this.game.assetsPreLoad[type]) {
                    this.game.assetsLoaded[type][key] = 1;
                    var preload_data = this.game.assetsPreLoad[type][key];
                    delete this.game.assetsPreLoad[type][key];
                    this["process_" + type](key,preload_data);
                    //handler(key,preload_data);
                }
            }
            else {
                console.log('Asset handler "process_' + type + '" not found for key "' + key + '"');
            }
        }

        if (_.keys(this.game.assetsMustLoad).length) {
            // Found more assets to left to load?
            // Need to run through this process again:
            console.log("Restarting STATE because found more assets not loaded yet",this.game.assetsMustLoad);
            this.game.state.restart();
        }
        else {
            // Everything is loaded?
            // Finally we can process to the next state:
            this.game.state.start(this.game.assetsNextState);
        }
    };

    // preload_TYPE(KEY,DATA):
    //   Define how to preload TYPE asset into KEY from DATA
    // process_TYPE:
    //   Now that asset has been loaded, populate final Object into game.assets.KEY, if appropriate
    //   If other assets are required to be loaded, then also populate
    //   this.game.assetsMustLoad.<NEWTYPE>.<NEWKEY> with more dependency DATA assets

    return fn;
})();
<commit_msg>Fix key "undefined" spewage, such as:<commit_after>var App = App || {};
App.LoadAssetsState = App.LoadAssetsState || {};

App.LoadAssetsState = (function () {
    "use strict";

    // constructor: Run only once at compile time
    var fn = function (game) {
        Phaser.State.call(this, game);
    };
    fn.prototype = Object.create(Phaser.State.prototype);
    fn.prototype.constructor = fn;

    // init: Run every time this state is started or restart:
    fn.prototype.init = function () {
        this.game.assets = this.game.assets || {};
        this.game.assetsMustLoad = this.game.assetsMustLoad || {};
        this.game.assetsPreLoad = this.game.assetsPreLoad || {};
        this.game.assetsLoaded = this.game.assetsLoaded || {};
        this.game.assetsNextState = this.game.assetsNextState || "DefaultNextState";
    };

    // preload: Call "preload_TYPE" routine on each asset
    fn.prototype.preload = function () {
        for (var type in this.game.assetsMustLoad) {
            this.game.assetsPreLoad[type] = this.game.assetsPreLoad[type] || {};
            this.game.assetsLoaded[type] = this.game.assetsLoaded[type] || {};
            var handler = this["preload_" + type];
            if (handler && "function" === typeof handler) {
                for (var key in this.game.assetsMustLoad[type]) {
                    if (!this.game.assetsLoaded[type][key] &&
                        !this.game.assetsPreLoad[type][key]) {
                        var data = this.game.assetsMustLoad[type][key];
                        //this.game.assetsPreLoad[type][key] = handler(key,data);
                        this.game.assetsPreLoad[type][key] = this["preload_" + type](key,data);
                    }
                    delete this.game.assetsMustLoad[type][key];
                }
            }
            else {
                console.log('Asset handler "preload_' + type + '" not defined');
            }
            delete this.game.assetsMustLoad[type];
        }
    };

    // create: Call "process_TYPE" routine on each asset once preload is complete
    fn.prototype.create = function () {
        for (var type in this.game.assetsPreLoad) {
            this.game.assetsLoaded[type] = this.game.assetsLoaded[type] || {};
            var handler = this["process_" + type];
            if (handler && "function" === typeof handler) {
                for (var key in this.game.assetsPreLoad[type]) {
                    this.game.assetsLoaded[type][key] = 1;
                    var preload_data = this.game.assetsPreLoad[type][key];
                    delete this.game.assetsPreLoad[type][key];
                    this["process_" + type](key,preload_data);
                    //handler(key,preload_data);
                }
            }
            else {
                console.log('Asset handler "process_' + type + '" not defined');
            }
        }

        if (_.keys(this.game.assetsMustLoad).length) {
            // Found more assets to left to load?
            // Need to run through this process again:
            console.log("Restarting STATE because found more assets not loaded yet",this.game.assetsMustLoad);
            this.game.state.restart();
        }
        else {
            // Everything is loaded?
            // Finally we can process to the next state:
            this.game.state.start(this.game.assetsNextState);
        }
    };

    // preload_TYPE(KEY,DATA):
    //   Define how to preload TYPE asset into KEY from DATA
    // process_TYPE:
    //   Now that asset has been loaded, populate final Object into game.assets.KEY, if appropriate
    //   If other assets are required to be loaded, then also populate
    //   this.game.assetsMustLoad.<NEWTYPE>.<NEWKEY> with more dependency DATA assets

    return fn;
})();
<|endoftext|>