<commit_before>var util = require('util'),
    path = require('path'),
    fs = require('fs'),
    yeoman = require('../../../../'),
    grunt = require('grunt'),
    exec = require('child_process').exec;

module.exports = Generator;

function Generator() {
  yeoman.generators.Base.apply(this, arguments);

  this.sourceRoot(path.join(__dirname, 'templates'));
}

util.inherits(Generator, yeoman.generators.NamedBase);

Generator.prototype.askFor = function askFor() {
	var cb = this.async(),
      self = this;

	var prompts = [
		{
			name: 'appName',
      message: 'Name of the app',
      default: 'app'
		},
    {
      name: 'compassBootstrap',
      message: 'Would you like to include Twitter Bootstrap for Compass instead of CSS?',
      default: 'Y/n',
      warning: 'Yes: All Twitter Bootstrap files will be placed into the styles directory.'
    },
    {
      name: 'bootstrap',
      message: 'Would you like to include the Twitter Bootstrap JS plugins?',
      default: 'Y/n',
      warning: 'Yes: All Twitter Bootstrap plugins will be placed into the JavaScript vendor directory.'
    },
    {
      name: 'frozenFlask',
      message: 'Do you want to use Frozen-Flask to build an static version of the app?',
      default: 'Y/n'
    }
	];

  self.prompt(prompts, function(e, props) {
    if (e) { return self.emit('error', e); }

    // set the properties
    self.appName = props.appName;
    self.compassBootstrap = (/y/i).test(props.compassBootstrap);
    self.bootstrap = (/y/i).test(props.bootstrap);
    self.frozenFlask = (/y/i).test(props.frozenFlask);

    cb();
  });

}

// create the basic app structure
Generator.prototype.createStructure = function createStructure() {
  var cb = this.async();

  fs.mkdirSync(this.appName);
  fs.mkdirSync(this.appName + '/static');
  fs.mkdirSync(this.appName + '/static/css');
  fs.mkdirSync(this.appName + '/static/js');
  fs.mkdirSync(this.appName + '/static/js/vendors');
  fs.mkdirSync(this.appName + '/static/img');
  fs.mkdirSync(this.appName + '/templates');

  this.copy('jquery-1.8.3.min.js', this.appName + '/static/js/vendors/jquery-1.8.3.min.js');

  cb();
}

// The Bootstrap functions are copies from the basic Yeoman app generator, edited to fit with the flask app structure
// Bootstrap plugins
Generator.prototype.fetchBootstrap = function fetchBootstrap() {
  // prevent the bootstrap fetch is user said NO
  if(!this.bootstrap) { return; }

  var cb = this.async(),
      self = this;

  // third optional argument is the branch / sha1. Defaults to master when ommitted.
  this.remote('twitter', 'bootstrap', 'v2.1.0', function(err, remote, files) {
    if (err) { return cb(err); }

    'affix alert button carousel collapse dropdown modal popover scrollspy tab tooltip transition typeahead'.split(' ')
    .forEach(function( el ) {
      var filename = 'bootstrap-' + el + '.js';
      remote.copy('js/' + filename, self.appName + '/static/js/vendors/bootstrap/' + filename);
    });

    cb();
  });
};

// Bootstrap css / scss
Generator.prototype.compassBootstrapFiles = function compassBootstrapFiles() {
  if ( this.compassBootstrap ) {
    var cb = this.async(),
        self = this;

    this.write(this.appName + '/static/css/main.scss', '@import "compass_twitter_bootstrap";');

    this.remote('kristianmandrup', 'compass-twitter-bootstrap', 'c3ccce2cca5ec52437925e8feaaa11fead51e132', function(err, remote) {
      if (err) { return cb(err); }

      remote.directory('stylesheets', self.appName + '/static/css');

      cb();
    });
  }
  else {
    this.log.writeln('Writing compiled Bootstrap');
    this.copy('bootstrap.css', this.appName + '/static/css/bootstrap.css');
  }
};

Generator.prototype.bootstrapImages = function bootstrapImages() {
  this.copy('glyphicons-halflings.png', this.appName + '/static/img/glyphicons-halflings.png');
  this.copy('glyphicons-halflings-white.png', this.appName + '/static/img/glyphicons-halflings-white.png');
};

// create the basic files
Generator.prototype.createAppFiles = function createAppFiles() {
  this.template('init.py', this.appName + '/__init__.py');
  this.template('server.py', 'server.py');
  this.template('views.py', this.appName + '/views.py');
  this.copy('index.html', this.appName + '/templates/index.html');
  this.copy('base.html', this.appName + '/templates/base.html');

  // make the server file executable
  exec('chmod a+x server.py');
}

// create the frozen-flask file to build a static version of the app
Generator.prototype.createFreezeFile = function createFreezeFile() {
  if (this.frozenFlask) {
    this.template('freeze.py', 'freeze.py');
  }
}

// create the yeoman and git files
Generator.prototype.createYeomanFiles = function createYeomanFiles() {
  this.copy('Gruntfile.js', 'Gruntfile.js');
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
}

Generator.prototype.end = function end() {
  grunt.log.writeln('\nYour app is ready !\n');
}
<commit_msg>Added an explanation for the frozen-flask thingy<commit_after>var util = require('util'),
    path = require('path'),
    fs = require('fs'),
    yeoman = require('../../../../'),
    grunt = require('grunt'),
    exec = require('child_process').exec;

module.exports = Generator;

function Generator() {
  yeoman.generators.Base.apply(this, arguments);

  this.sourceRoot(path.join(__dirname, 'templates'));
}

util.inherits(Generator, yeoman.generators.NamedBase);

Generator.prototype.askFor = function askFor() {
	var cb = this.async(),
      self = this;

	var prompts = [
		{
			name: 'appName',
      message: 'Name of the app',
      default: 'app'
		},
    {
      name: 'compassBootstrap',
      message: 'Would you like to include Twitter Bootstrap for Compass instead of CSS?',
      default: 'Y/n',
      warning: 'Yes: All Twitter Bootstrap files will be placed into the css directory.'
    },
    {
      name: 'bootstrap',
      message: 'Would you like to include the Twitter Bootstrap JS plugins?',
      default: 'Y/n',
      warning: 'Yes: All Twitter Bootstrap plugins will be placed into the JavaScript vendor directory.'
    },
    {
      name: 'frozenFlask',
      message: 'Do you want to use Frozen-Flask to build an static version of the app?',
      default: 'Y/n',
      warning: 'Yes: You will be able to build a static version of your app with `$ python freeze.py`.'
    }
	];

  self.prompt(prompts, function(e, props) {
    if (e) { return self.emit('error', e); }

    // set the properties
    self.appName = props.appName;
    self.compassBootstrap = (/y/i).test(props.compassBootstrap);
    self.bootstrap = (/y/i).test(props.bootstrap);
    self.frozenFlask = (/y/i).test(props.frozenFlask);

    cb();
  });

}

// create the basic app structure
Generator.prototype.createStructure = function createStructure() {
  var cb = this.async();

  fs.mkdirSync(this.appName);
  fs.mkdirSync(this.appName + '/static');
  fs.mkdirSync(this.appName + '/static/css');
  fs.mkdirSync(this.appName + '/static/js');
  fs.mkdirSync(this.appName + '/static/js/vendors');
  fs.mkdirSync(this.appName + '/static/img');
  fs.mkdirSync(this.appName + '/templates');

  this.copy('jquery-1.8.3.min.js', this.appName + '/static/js/vendors/jquery-1.8.3.min.js');

  cb();
}

// The Bootstrap functions are copies from the basic Yeoman app generator, edited to fit with the flask app structure
// Bootstrap plugins
Generator.prototype.fetchBootstrap = function fetchBootstrap() {
  // prevent the bootstrap fetch is user said NO
  if(!this.bootstrap) { return; }

  var cb = this.async(),
      self = this;

  // third optional argument is the branch / sha1. Defaults to master when ommitted.
  this.remote('twitter', 'bootstrap', 'v2.1.0', function(err, remote, files) {
    if (err) { return cb(err); }

    'affix alert button carousel collapse dropdown modal popover scrollspy tab tooltip transition typeahead'.split(' ')
    .forEach(function( el ) {
      var filename = 'bootstrap-' + el + '.js';
      remote.copy('js/' + filename, self.appName + '/static/js/vendors/bootstrap/' + filename);
    });

    cb();
  });
};

// Bootstrap css / scss
Generator.prototype.compassBootstrapFiles = function compassBootstrapFiles() {
  if ( this.compassBootstrap ) {
    var cb = this.async(),
        self = this;

    this.write(this.appName + '/static/css/main.scss', '@import "compass_twitter_bootstrap";');

    this.remote('kristianmandrup', 'compass-twitter-bootstrap', 'c3ccce2cca5ec52437925e8feaaa11fead51e132', function(err, remote) {
      if (err) { return cb(err); }

      remote.directory('stylesheets', self.appName + '/static/css');

      cb();
    });
  }
  else {
    this.log.writeln('Writing compiled Bootstrap');
    this.copy('bootstrap.css', this.appName + '/static/css/bootstrap.css');
  }
};

Generator.prototype.bootstrapImages = function bootstrapImages() {
  this.copy('glyphicons-halflings.png', this.appName + '/static/img/glyphicons-halflings.png');
  this.copy('glyphicons-halflings-white.png', this.appName + '/static/img/glyphicons-halflings-white.png');
};

// create the basic files
Generator.prototype.createAppFiles = function createAppFiles() {
  this.template('init.py', this.appName + '/__init__.py');
  this.template('server.py', 'server.py');
  this.template('views.py', this.appName + '/views.py');
  this.copy('index.html', this.appName + '/templates/index.html');
  this.copy('base.html', this.appName + '/templates/base.html');

  // make the server file executable
  exec('chmod a+x server.py');
}

// create the frozen-flask file to build a static version of the app
Generator.prototype.createFreezeFile = function createFreezeFile() {
  if (this.frozenFlask) {
    this.template('freeze.py', 'freeze.py');
  }
}

// create the yeoman and git files
Generator.prototype.createYeomanFiles = function createYeomanFiles() {
  this.copy('Gruntfile.js', 'Gruntfile.js');
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
}

Generator.prototype.end = function end() {
  grunt.log.writeln('\nYour app is ready !\n');
}
<|endoftext|>


<commit_before>var fbp = require('..');

// --- define network ---
var network = new fbp.Network();

var sender = network.defProc('./components/sender.js');
var copier = network.defProc('./components/copier.js');
var recvr  = network.defProc('./components/recvr.js');
// var recvr = fbp.defProc(require('../components/recvr.js'), 'recvr'); // equivalent

network.initialize(sender, 'COUNT', '100000000');
network.connect(sender, 'OUT', copier, 'IN', 5);
network.connect(copier, 'OUT', recvr, 'IN', 5);

// --- run ---
var fiberRuntime = new fbp.FiberRuntime();
network.run(fiberRuntime, { trace: false });<commit_msg>Reducing count of IPs - it was left at volume test level by mistake<commit_after>var fbp = require('..');

// --- define network ---
var network = new fbp.Network();

var sender = network.defProc('./components/sender.js');
var copier = network.defProc('./components/copier.js');
var recvr  = network.defProc('./components/recvr.js');
// var recvr = fbp.defProc(require('../components/recvr.js'), 'recvr'); // equivalent

network.initialize(sender, 'COUNT', '2000');
network.connect(sender, 'OUT', copier, 'IN', 5);
network.connect(copier, 'OUT', recvr, 'IN', 5);

// --- run ---
var fiberRuntime = new fbp.FiberRuntime();
network.run(fiberRuntime, { trace: false });<|endoftext|>


<commit_before>/**
 * This provides the principal function to make a call to the API. Basically
 * a fancy wrapper around XHR/JSONP/etc.
 */
'use strict';

goog.provide('Server');
goog.require('utils');
goog.require('goog.json');
goog.require('storage'); // jshint unused:false
goog.require('safejson');

/*globals Ti */

var RETRIES = 2;
var RETRY_DELAY = 200;
var TIMEOUT = 5000;

/**
 * @class Server
 * @constructor
 */
var Server = function() { };

Server.prototype._jsonp_callback_index = 0;

/**
 * @param {Object} obj
 * @param {string} prefix
 */
Server.prototype.serializeObject = function(obj, prefix) {
	if (typeof obj === 'undefined') {
		return '';
	}

	var pairs = [ ];
	if (obj instanceof Array) {
		for (var i = 0; i < obj.length; i++) {
			pairs.push(encodeURIComponent(prefix) + '=' + encodeURIComponent(obj[i]));
		}
		return pairs.join('&');
	}

	for (var prop in obj) {
		if (!obj.hasOwnProperty(prop)) {
			continue;
		}
		if (obj[prop] instanceof Array || typeof obj[prop] === 'object') {
			pairs.push(
				this.serializeObject(obj[prop], prefix ? prefix + '.' + prop : prop)
			);
		}
		else {
			pairs.push(encodeURIComponent(prefix ? prefix + '.' + prop : prop) +
				'=' +
				encodeURIComponent(obj[prop])
			);
		}
	}
	return pairs.join('&');
};

/**
 * @param {utils.resource} resource
 * @param {Object.<string, *>} data
 */
Server.prototype.getUrl = function(resource, data) {
	var k;
	var v;
	var err;
	var url = resource.destination + resource.endpoint;
	var branch_id = /^[0-9]{15,20}$/;
	var branch_key = /key_(live|test)_[A-Za-z0-9]{32}/;

	var appendKeyOrId = function(data, destinationObject) {
		if (typeof destinationObject === 'undefined') {
			destinationObject = { };
		}
		if (data['branch_key'] && branch_key.test(data['branch_key'])) {
			destinationObject['branch_key'] = data['branch_key'];
			return destinationObject;
		}
		else if (data['app_id'] && branch_id.test(data['app_id'])) {
			destinationObject['app_id'] = data['app_id'];
			return destinationObject;
		}
		else {
			throw Error(utils.message(
				utils.messages.missingParam,
				[
					resource.endpoint,
					'branch_key or app_id'
				]
			));
		}
	};

	if (resource.endpoint === '/v1/has-app') {
		try {
			resource.queryPart = appendKeyOrId(data, resource.queryPart);
		}
		catch (e) {
			return {
				error: e.message
			};
		}
	}

	if (typeof resource.queryPart !== 'undefined') {
		for (k in resource.queryPart) {
			if (!resource.queryPart.hasOwnProperty(k)) {
				continue;
			}
			err = (typeof resource.queryPart[k] === 'function') ?
				resource.queryPart[k](resource.endpoint, k, data[k]) :
				err;
			if (err) {
				return { error: err };
			}
			url += '/' + data[k];
		}
	}

	var d = { };
	if (typeof resource.params !== 'undefined') {
		for (k in resource.params) {
			if (resource.params.hasOwnProperty(k)) {
				err = resource.params[k](resource.endpoint, k, data[k]);
				if (err) {
					return {
						error: err
					};
				}

				v = data[k];
				if (!(typeof v === 'undefined' || v === '' || v === null)) {
					d[k] = v;
				}
			}
		}
	}

	if (resource.method === 'POST' || resource.endpoint === '/v1/credithistory') {
		try {
			data = appendKeyOrId(data, d);
		}
		catch (e) {
			return {
				error: e.message
			};
		}
	}

	if (resource.endpoint === '/v1/event') {
		d['metadata'] = JSON.stringify(d['metadata'] || {});
	}
	return {
		data: this.serializeObject(d, ''),
		url: url.replace(/^\//, '')
	};
};

/**
 * This function is standalone for easy mocking.
 * @param {string} src
 */
Server.prototype.createScript = function(src, onError, onLoad) {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.async = true;
	script.src = src;

	var heads = document.getElementsByTagName('head');
	if (!heads || heads.length < 1) {
		if (typeof onError === 'function') {
			onError();
		}
		return;
	}
	heads[0].appendChild(script);

	if (typeof onError === 'function') {
		utils.addEvent(script, 'error', onError);
	}
	if (typeof onLoad === 'function') {
		utils.addEvent(script, 'load', onLoad);
	}
};

var jsonp_callback_index = 0;

/**
 * @param {string} requestURL
 * @param {Object} requestData
 * @param {utils._httpMethod} requestMethod
 * @param {function(?Error,*=,?=)=} callback
 */
Server.prototype.jsonpRequest = function(requestURL, requestData, requestMethod, callback) {
	var callbackString = 'branch_callback__' + (this._jsonp_callback_index++);

	var postPrefix = (requestURL.indexOf('branch.io') >= 0) ? '&data=' : '&post_data=';
	var postData = (requestMethod === 'POST') ?
		encodeURIComponent(utils.base64encode(goog.json.serialize(requestData))) :
		'';

	var timeoutTrigger = window.setTimeout(
		function() {
			window[callbackString] = function() { };
			callback(new Error(utils.messages.timeout), null, 504);
		},
		TIMEOUT
	);

	window[callbackString] = function(data) {
		window.clearTimeout(timeoutTrigger);
		callback(null, data);
	};

	this.createScript(
		requestURL + (requestURL.indexOf('?') < 0 ? '?' : '') +
			(postData ? postPrefix + postData : '') +
			(requestURL.indexOf('/c/') >= 0 ? '&click=1' : '') +
			'&callback=' + callbackString,
		function onError() {
			callback(new Error(utils.messages.blockedByClient), null);
		},
		function onLoad() {
			try {
				if (typeof this.remove === 'function') {
					this.remove();
				}
				else {
					// some browsers do not have a 'remove' method
					// for Element, so fall back
					this.parentNode.removeChild(this);
				}
			}
			catch (e) {
				// we're trying to remove the script tag during a
				// jsonp request, but if that fails, we shouldn't
				// break anything else...just continue
			}
			delete window[callbackString];
		});
};

/**
 * @param {string} url
 * @param {Object} data
 * @param {utils._httpMethod} method
 * @param {BranchStorage} storage
 * @param {function(?Error,*=,?=)=} callback
 * @param {?boolean} noparse
 */
Server.prototype.XHRRequest = function(url, data, method, storage, callback, noparse) {
	var req = (window.XMLHttpRequest ?
			new XMLHttpRequest() :
			new ActiveXObject('Microsoft.XMLHTTP'));
	req.ontimeout = function() {
		callback(new Error(utils.messages.timeout), null, 504);
	};
	req.onerror = function(e) {
		callback(new Error(e.error || ('Error in API: ' + req.status)), null, req.status);
	};
	req.onreadystatechange = function() {
		var data;
		if (req.readyState === 4) {
			if (req.status === 200) {
				if (noparse) {
					data = req.responseText;
				}
				else {
					try {
						data = safejson.parse(req.responseText);
					}
					catch (e) {
						data = {};
					}
				}
				callback(null, data, req.status);
			}
			else if (req.status === 402) {
				callback(new Error('Not enough credits to redeem.'), null, req.status);
			}
			else if (req.status.toString().substring(0, 1) === '4' ||
					req.status.toString().substring(0, 1) === '5') {
				callback(new Error('Error in API: ' + req.status), null, req.status);
			}
		}
	};

	try {
		req.open(method, url, true);
		req.timeout = TIMEOUT;
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send(data);
	}
	catch (e) {
		storage.set('use_jsonp', true);
		this.jsonpRequest(url, data, method, callback);
	}
};

/**
 * @param {utils.resource} resource
 * @param {Object.<string, *>} data
 * @param {BranchStorage} storage
 * @param {function(?Error,*=)=} callback
 */
Server.prototype.request = function(resource, data, storage, callback) {
	var self = this;

	var u = this.getUrl(resource, data);
	if (u.error) {
		return callback(new Error(u.error));
	}

	var url;
	var postData = '';
	if (resource.method === 'GET') {
		url = u.url + '?' + u.data;
	}
	else {
		url = u.url;
		postData = u.data;
	}

	// How many times to retry the request if the initial attempt fails
	var retries = RETRIES;
	// If request fails, retry after X miliseconds
	/***
	 * @type {function(?Error,*=): ?undefined}
	 */
	var done = function(err, data, status) {
		if (err && retries > 0 && (status || "").toString().substring(0, 1) === '5') {
			retries--;
			window.setTimeout(function() {
				makeRequest();
			}, RETRY_DELAY);
		}
		else {
			callback(err, data);
		}
	};
	var makeRequest = function() {
		if (storage.get('use_jsonp') || resource.jsonp) {
			self.jsonpRequest(url, data, resource.method, done);
		}
		else {
			self.XHRRequest(url, postData, resource.method, storage, done);
		}
	};
	makeRequest();
};
<commit_msg>use same hack as v1-event<commit_after>/**
 * This provides the principal function to make a call to the API. Basically
 * a fancy wrapper around XHR/JSONP/etc.
 */
'use strict';

goog.provide('Server');
goog.require('utils');
goog.require('goog.json');
goog.require('storage'); // jshint unused:false
goog.require('safejson');

/*globals Ti */

var RETRIES = 2;
var RETRY_DELAY = 200;
var TIMEOUT = 5000;

/**
 * @class Server
 * @constructor
 */
var Server = function() { };

Server.prototype._jsonp_callback_index = 0;

/**
 * @param {Object} obj
 * @param {string} prefix
 */
Server.prototype.serializeObject = function(obj, prefix) {
	if (typeof obj === 'undefined') {
		return '';
	}

	var pairs = [ ];
	if (obj instanceof Array) {
		for (var i = 0; i < obj.length; i++) {
			pairs.push(encodeURIComponent(prefix) + '=' + encodeURIComponent(obj[i]));
		}
		return pairs.join('&');
	}

	for (var prop in obj) {
		if (!obj.hasOwnProperty(prop)) {
			continue;
		}
		if (obj[prop] instanceof Array || typeof obj[prop] === 'object') {
			pairs.push(
				this.serializeObject(obj[prop], prefix ? prefix + '.' + prop : prop)
			);
		}
		else {
			pairs.push(encodeURIComponent(prefix ? prefix + '.' + prop : prop) +
				'=' +
				encodeURIComponent(obj[prop])
			);
		}
	}
	return pairs.join('&');
};

/**
 * @param {utils.resource} resource
 * @param {Object.<string, *>} data
 */
Server.prototype.getUrl = function(resource, data) {
	var k;
	var v;
	var err;
	var url = resource.destination + resource.endpoint;
	var branch_id = /^[0-9]{15,20}$/;
	var branch_key = /key_(live|test)_[A-Za-z0-9]{32}/;

	var appendKeyOrId = function(data, destinationObject) {
		if (typeof destinationObject === 'undefined') {
			destinationObject = { };
		}
		if (data['branch_key'] && branch_key.test(data['branch_key'])) {
			destinationObject['branch_key'] = data['branch_key'];
			return destinationObject;
		}
		else if (data['app_id'] && branch_id.test(data['app_id'])) {
			destinationObject['app_id'] = data['app_id'];
			return destinationObject;
		}
		else {
			throw Error(utils.message(
				utils.messages.missingParam,
				[
					resource.endpoint,
					'branch_key or app_id'
				]
			));
		}
	};

	if (resource.endpoint === '/v1/has-app') {
		try {
			resource.queryPart = appendKeyOrId(data, resource.queryPart);
		}
		catch (e) {
			return {
				error: e.message
			};
		}
	}

	if (typeof resource.queryPart !== 'undefined') {
		for (k in resource.queryPart) {
			if (!resource.queryPart.hasOwnProperty(k)) {
				continue;
			}
			err = (typeof resource.queryPart[k] === 'function') ?
				resource.queryPart[k](resource.endpoint, k, data[k]) :
				err;
			if (err) {
				return { error: err };
			}
			url += '/' + data[k];
		}
	}

	var d = { };
	if (typeof resource.params !== 'undefined') {
		for (k in resource.params) {
			if (resource.params.hasOwnProperty(k)) {
				err = resource.params[k](resource.endpoint, k, data[k]);
				if (err) {
					return {
						error: err
					};
				}

				v = data[k];
				if (!(typeof v === 'undefined' || v === '' || v === null)) {
					d[k] = v;
				}
			}
		}
	}

	if (resource.method === 'POST' || resource.endpoint === '/v1/credithistory') {
		try {
			data = appendKeyOrId(data, d);
		}
		catch (e) {
			return {
				error: e.message
			};
		}
	}

	if (resource.endpoint === '/v1/event') {
		d['metadata'] = JSON.stringify(d['metadata'] || {});
	}

	if (resource.endpoint === '/v1/open') {
		d['options'] = JSON.stringify(d['options'] || {});
	}

	return {
		data: this.serializeObject(d, ''),
		url: url.replace(/^\//, '')
	};
};

/**
 * This function is standalone for easy mocking.
 * @param {string} src
 */
Server.prototype.createScript = function(src, onError, onLoad) {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.async = true;
	script.src = src;

	var heads = document.getElementsByTagName('head');
	if (!heads || heads.length < 1) {
		if (typeof onError === 'function') {
			onError();
		}
		return;
	}
	heads[0].appendChild(script);

	if (typeof onError === 'function') {
		utils.addEvent(script, 'error', onError);
	}
	if (typeof onLoad === 'function') {
		utils.addEvent(script, 'load', onLoad);
	}
};

var jsonp_callback_index = 0;

/**
 * @param {string} requestURL
 * @param {Object} requestData
 * @param {utils._httpMethod} requestMethod
 * @param {function(?Error,*=,?=)=} callback
 */
Server.prototype.jsonpRequest = function(requestURL, requestData, requestMethod, callback) {
	var callbackString = 'branch_callback__' + (this._jsonp_callback_index++);

	var postPrefix = (requestURL.indexOf('branch.io') >= 0) ? '&data=' : '&post_data=';
	var postData = (requestMethod === 'POST') ?
		encodeURIComponent(utils.base64encode(goog.json.serialize(requestData))) :
		'';

	var timeoutTrigger = window.setTimeout(
		function() {
			window[callbackString] = function() { };
			callback(new Error(utils.messages.timeout), null, 504);
		},
		TIMEOUT
	);

	window[callbackString] = function(data) {
		window.clearTimeout(timeoutTrigger);
		callback(null, data);
	};

	this.createScript(
		requestURL + (requestURL.indexOf('?') < 0 ? '?' : '') +
			(postData ? postPrefix + postData : '') +
			(requestURL.indexOf('/c/') >= 0 ? '&click=1' : '') +
			'&callback=' + callbackString,
		function onError() {
			callback(new Error(utils.messages.blockedByClient), null);
		},
		function onLoad() {
			try {
				if (typeof this.remove === 'function') {
					this.remove();
				}
				else {
					// some browsers do not have a 'remove' method
					// for Element, so fall back
					this.parentNode.removeChild(this);
				}
			}
			catch (e) {
				// we're trying to remove the script tag during a
				// jsonp request, but if that fails, we shouldn't
				// break anything else...just continue
			}
			delete window[callbackString];
		});
};

/**
 * @param {string} url
 * @param {Object} data
 * @param {utils._httpMethod} method
 * @param {BranchStorage} storage
 * @param {function(?Error,*=,?=)=} callback
 * @param {?boolean} noparse
 */
Server.prototype.XHRRequest = function(url, data, method, storage, callback, noparse) {
	var req = (window.XMLHttpRequest ?
			new XMLHttpRequest() :
			new ActiveXObject('Microsoft.XMLHTTP'));
	req.ontimeout = function() {
		callback(new Error(utils.messages.timeout), null, 504);
	};
	req.onerror = function(e) {
		callback(new Error(e.error || ('Error in API: ' + req.status)), null, req.status);
	};
	req.onreadystatechange = function() {
		var data;
		if (req.readyState === 4) {
			if (req.status === 200) {
				if (noparse) {
					data = req.responseText;
				}
				else {
					try {
						data = safejson.parse(req.responseText);
					}
					catch (e) {
						data = {};
					}
				}
				callback(null, data, req.status);
			}
			else if (req.status === 402) {
				callback(new Error('Not enough credits to redeem.'), null, req.status);
			}
			else if (req.status.toString().substring(0, 1) === '4' ||
					req.status.toString().substring(0, 1) === '5') {
				callback(new Error('Error in API: ' + req.status), null, req.status);
			}
		}
	};

	try {
		req.open(method, url, true);
		req.timeout = TIMEOUT;
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send(data);
	}
	catch (e) {
		storage.set('use_jsonp', true);
		this.jsonpRequest(url, data, method, callback);
	}
};

/**
 * @param {utils.resource} resource
 * @param {Object.<string, *>} data
 * @param {BranchStorage} storage
 * @param {function(?Error,*=)=} callback
 */
Server.prototype.request = function(resource, data, storage, callback) {
	var self = this;

	var u = this.getUrl(resource, data);
	if (u.error) {
		return callback(new Error(u.error));
	}

	var url;
	var postData = '';
	if (resource.method === 'GET') {
		url = u.url + '?' + u.data;
	}
	else {
		url = u.url;
		postData = u.data;
	}

	// How many times to retry the request if the initial attempt fails
	var retries = RETRIES;
	// If request fails, retry after X miliseconds
	/***
	 * @type {function(?Error,*=): ?undefined}
	 */
	var done = function(err, data, status) {
		if (err && retries > 0 && (status || "").toString().substring(0, 1) === '5') {
			retries--;
			window.setTimeout(function() {
				makeRequest();
			}, RETRY_DELAY);
		}
		else {
			callback(err, data);
		}
	};
	var makeRequest = function() {
		if (storage.get('use_jsonp') || resource.jsonp) {
			self.jsonpRequest(url, data, resource.method, done);
		}
		else {
			self.XHRRequest(url, postData, resource.method, storage, done);
		}
	};
	makeRequest();
};
<|endoftext|>


<commit_before>Reverse Linked List 2

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

<commit_msg>add params<commit_after>Reverse Linked List 2

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @param {number} m
 * @param {number} n
 * @return {ListNode}
 */

<|endoftext|>


<commit_before>(function($) {

    /*

    Example use:

        $("select").selectstyles();
        $('input[type="checkbox"], input[type="radio"]').checkboxstyles();
        $('input[type="submit"]').buttonstyles();

    TODO:

    ✔ Wrap selects in a mask
    ✔ Wrap checkbox/radio
    ✔ Wrap submit buttons
    ✔ select to 0.01 opacity and fill mask
    ✔ customisable callback to set text in mask on change
    - expose an api to update the content, maybe? or not needed?
    ✔ handle focused states
    - handle disabled states
    - ellipsis for text that's too long? Or do we rely on css

    */

    COMMON_CSS = {
        position: 'absolute',
        top: 0,
        right: 0,
        bottom: 0,
        left: '0',
        height: '100%',
        width: '100%',
        opacity: 0.01,
        background: 'none',
        zIndex: 1
        border: 'none'
    };

    function createmask(el, classname) {
        var mask = $('<div>').addClass(classname);
        mask.insertBefore(el).append(el);
        if (mask.css('position') === 'static') {
            mask.css({
                position: 'relative'
            });
        }
        handle_focus(el, mask);
        return mask;
    };

    function handle_focus(el, mask) {
        el.on('focus', function() {
            mask.addClass('focused');
        });
        el.on('blur', function() {
            mask.removeClass('focused');
        });
    };

    $.fn.selectstyles = (function(options) {
        var options = $.extend({
                display_val: function(val, select) {
                    return val;
                },
                classname: 'select-mask',
            }, options);

        this.each(function() {
            var select = $(this),
                mask = createmask(select, options.classname),
                label = $('<span>');

            mask.css('minWidth', select.width());
            mask.append(label);

            select.css(COMMON_CSS);

            function set_val() {
                var val = select.find('option:selected').text();
                label.text(options.display_val(val, select));
            };
            set_val();
            select.on('change', set_val);

            // needed to set the width in ie
            select[0].style.width = mask.outerWidth() + 'px';
            select[0].style.height = mask.outerHeight() + 'px';
        });

        return this;
    });

    $.fn.checkboxstyles = (function(options) {
        this.each(function() {
            var input = $(this),
                options = $.extend({
                    classname: input.attr('type') + '-mask',
                }, options),
                mask = createmask(input, options.classname);

            input.css(COMMON_CSS).css({
                width: mask.outerWidth(),
                height: mask.outerHeight()
            });

            function set_val() {
                if (input.is(':checked')) {
                    mask.addClass('checked');
                }
                else {
                    mask.removeClass('checked');
                }
            };
            set_val();
            input.on('change', set_val);
            if (input.attr('type') === 'radio') {
                // for radio inputs, we need to change state on change for any
                // of the related inputs
                $('input[name="' + input.attr('name') + '"]').on('change', set_val);
            }
        });

        return this;
    });

    $.fn.buttonstyles = (function(options) {
        var options = $.extend({
                classname: 'button-mask',
            }, options);

        this.each(function() {
            var input = $(this),
                mask = createmask(input, options.classname);

            input.css(COMMON_CSS);
            mask.append(input.val());
        });

        return this;
    });

    $.fn.fileinputstyles = (function(options) {
        var options = $.extend({
                classname: 'fileinput-mask',
            }, options);

        this.each(function() {
            var input = $(this),
                mask = createmask(input, options.classname),
                title = input.attr('title') || 'Upload file',
                text = $('<span>');

            function set_val() {
                var val = input.val();
                text.text(title + (val ? ': ' + val : ''));
            };

            mask.append(text);
            set_val();
            input.css(COMMON_CSS);
            mask.append(input.val());

            input.on('change', set_val);
        });

        return this;
    });

})(jQuery);

<commit_msg>ie fix caused issues for hidden selects<commit_after>(function($) {

    /*

    Example use:

        $("select").selectstyles();
        $('input[type="checkbox"], input[type="radio"]').checkboxstyles();
        $('input[type="submit"]').buttonstyles();

    TODO:

    ✔ Wrap selects in a mask
    ✔ Wrap checkbox/radio
    ✔ Wrap submit buttons
    ✔ select to 0.01 opacity and fill mask
    ✔ customisable callback to set text in mask on change
    - expose an api to update the content, maybe? or not needed?
    ✔ handle focused states
    - handle disabled states
    - ellipsis for text that's too long? Or do we rely on css

    */

    COMMON_CSS = {
        position: 'absolute',
        top: 0,
        right: 0,
        bottom: 0,
        left: '0',
        height: '100%',
        width: '100%',
        opacity: 0.01,
        background: 'none',
        zIndex: 1
        border: 'none'
    };

    function createmask(el, classname) {
        var mask = $('<div>').addClass(classname);
        mask.insertBefore(el).append(el);
        if (mask.css('position') === 'static') {
            mask.css({
                position: 'relative'
            });
        }
        handle_focus(el, mask);
        return mask;
    };

    function handle_focus(el, mask) {
        el.on('focus', function() {
            mask.addClass('focused');
        });
        el.on('blur', function() {
            mask.removeClass('focused');
        });
    };

    $.fn.selectstyles = (function(options) {
        var options = $.extend({
                display_val: function(val, select) {
                    return val;
                },
                classname: 'select-mask',
            }, options);

        this.each(function() {
            var select = $(this),
                mask = createmask(select, options.classname),
                label = $('<span>');

            mask.css('minWidth', select.width());
            mask.append(label);

            select.css(COMMON_CSS);

            function set_val() {
                var val = select.find('option:selected').text();
                label.text(options.display_val(val, select));
            };
            set_val();
            select.on('change', set_val);

            // needed to set the width in ie
            select[0].style.minWidth = mask.outerWidth() + 'px';
            select[0].style.minHeight = mask.outerHeight() + 'px';
        });

        return this;
    });

    $.fn.checkboxstyles = (function(options) {
        this.each(function() {
            var input = $(this),
                options = $.extend({
                    classname: input.attr('type') + '-mask',
                }, options),
                mask = createmask(input, options.classname);

            input.css(COMMON_CSS).css({
                width: mask.outerWidth(),
                height: mask.outerHeight()
            });

            function set_val() {
                if (input.is(':checked')) {
                    mask.addClass('checked');
                }
                else {
                    mask.removeClass('checked');
                }
            };
            set_val();
            input.on('change', set_val);
            if (input.attr('type') === 'radio') {
                // for radio inputs, we need to change state on change for any
                // of the related inputs
                $('input[name="' + input.attr('name') + '"]').on('change', set_val);
            }
        });

        return this;
    });

    $.fn.buttonstyles = (function(options) {
        var options = $.extend({
                classname: 'button-mask',
            }, options);

        this.each(function() {
            var input = $(this),
                mask = createmask(input, options.classname);

            input.css(COMMON_CSS);
            mask.append(input.val());
        });

        return this;
    });

    $.fn.fileinputstyles = (function(options) {
        var options = $.extend({
                classname: 'fileinput-mask',
            }, options);

        this.each(function() {
            var input = $(this),
                mask = createmask(input, options.classname),
                title = input.attr('title') || 'Upload file',
                text = $('<span>');

            function set_val() {
                var val = input.val();
                text.text(title + (val ? ': ' + val : ''));
            };

            mask.append(text);
            set_val();
            input.css(COMMON_CSS);
            mask.append(input.val());

            input.on('change', set_val);
        });

        return this;
    });

})(jQuery);

<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/firebug",
    "firebug/lib/trace",
    "firebug/lib/object",
    "firebug/lib/dom",
    "firebug/lib/locale",
    "firebug/chrome/menu"
],
function(Firebug, FBTrace, Obj, Dom, Locale, Menu) {

// ********************************************************************************************* //
// Model implementation

var SelectorModule = Obj.extend(Firebug.Module,
{
    dispatchName: "selectorModule",

    initialize: function()
    {
        Firebug.NetMonitor.NetInfoBody.addListener(this);
        Firebug.registerUIListener(this);
    },

    shutdown: function()
    {
        Firebug.NetMonitor.NetInfoBody.removeListener(this);
        Firebug.unregisterUIListener(this);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Context Menu

    onContextMenu: function(items, object, target, context, panel, popup)
    {
        if (panel.name != "stylesheet")
            return;

        var cssRule = Dom.getAncestorByClass(target, "cssRule");
        if (!cssRule)
            return;

        var rule = cssRule.repObject;
        if (!rule)
            return;

        var panel = context.getPanel("selector");
        if (!panel)
            return;

        var item = {
           id: "fbGetMatchingElements",
           nol10n: true,
           label: Locale.$STR("css.selector.cmd.getMatchingElements"),
           command: Obj.bindFixed(panel.getMatchingElements, panel, rule)
        };

        var refreshMenuItem = popup.querySelector("#fbRefresh");
        Menu.createMenuItem(popup, item, refreshMenuItem);

        return [];
    },
});

// ********************************************************************************************* //
// Registration

Firebug.registerModule(SelectorModule);

return SelectorModule;

// ********************************************************************************************* //
});
<commit_msg>Issue 6405 ("Get Matching Elements" must not be displayed for @-rules) http://code.google.com/p/fbug/issues/detail?id=6405<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/firebug",
    "firebug/lib/trace",
    "firebug/lib/object",
    "firebug/lib/dom",
    "firebug/lib/locale",
    "firebug/chrome/menu"
],
function(Firebug, FBTrace, Obj, Dom, Locale, Menu) {

// ********************************************************************************************* //
// Model implementation

var SelectorModule = Obj.extend(Firebug.Module,
{
    dispatchName: "selectorModule",

    initialize: function()
    {
        Firebug.NetMonitor.NetInfoBody.addListener(this);
        Firebug.registerUIListener(this);
    },

    shutdown: function()
    {
        Firebug.NetMonitor.NetInfoBody.removeListener(this);
        Firebug.unregisterUIListener(this);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Context Menu

    onContextMenu: function(items, object, target, context, panel, popup)
    {
        if (panel.name != "stylesheet")
            return;

        var cssRule = Dom.getAncestorByClass(target, "cssRule");
        if (!cssRule)
            return;

        var rule = cssRule.repObject;
        if (!rule || !rule.selectorText)
            return;

        var panel = context.getPanel("selector");
        if (!panel)
            return;

        var item = {
           id: "fbGetMatchingElements",
           nol10n: true,
           label: Locale.$STR("css.selector.cmd.getMatchingElements"),
           command: Obj.bindFixed(panel.getMatchingElements, panel, rule)
        };

        var refreshMenuItem = popup.querySelector("#fbRefresh");
        Menu.createMenuItem(popup, item, refreshMenuItem);

        return [];
    },
});

// ********************************************************************************************* //
// Registration

Firebug.registerModule(SelectorModule);

return SelectorModule;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>
const Component = require('../../../ui-base/component');
const template = require('./index.html');
const _ = require('../../../ui-base/_');

/**
 * @class KLMessage
 * @extend Component
 * @param {object}      [options.data]                      = 绑定属性
 * @param {string}      [options.data.type]                 => 消息类型，可选参数：`success`、`warning`、`info`、`error`
 * @param {string}      [options.data.class]                => 补充`class`
 * @param {string}      [options.data.title]                => 补充`title`
 * @param {string}      [options.data.addClose]                => 补充`addClose`  添加了该字段, 为message添加了关闭按钮
 */

const KLMessage = Component.extend({
  name: 'kl-message',
  template,
  config() {
    _.extend(this.data, {
      type: '',
      addClose: false,
      title: '',
      visible: true,
    });
    this.supr();
  },
  init() {
    this.supr();
  },
  close(result) {
    this.data.visible = Boolean(result);
    this.$update();
  },
});
module.exports = KLMessage;
<commit_msg>klmessage 关闭增加close事件<commit_after>
const Component = require('../../../ui-base/component');
const template = require('./index.html');
const _ = require('../../../ui-base/_');

/**
 * @class KLMessage
 * @extend Component
 * @param {object}      [options.data]                      = 绑定属性
 * @param {string}      [options.data.type]                 => 消息类型，可选参数：`success`、`warning`、`info`、`error`
 * @param {string}      [options.data.class]                => 补充`class`
 * @param {string}      [options.data.title]                => 补充`title`
 * @param {string}      [options.data.addClose]                => 补充`addClose`  添加了该字段, 为message添加了关闭按钮
 */

const KLMessage = Component.extend({
  name: 'kl-message',
  template,
  config() {
    _.extend(this.data, {
      type: '',
      addClose: false,
      title: '',
      visible: true,
    });
    this.supr();
  },
  init() {
    this.supr();
  },
  close(result) {
    this.data.visible = Boolean(result);
    this.$emit('close');
    this.$update();
  },
});
module.exports = KLMessage;
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */
var URL = require('url')
  ;

/**
 * Merge object b with object a.
 *
 * var a = { foo: 'bar' }
 *   , b = { foo: 'quux', bar: 'baz' };
 *
 * merge(a, b);
 * // => { foo: 'quux', bar: 'baz' }
 *
 * merge(a, b, true);
 * // => { foo: 'bar', bar: 'baz' }
 *
 * @param {Object} a
 * @param {Object} b
 * @param {Boolean} [noforce] Optionally, don't overwrite any existing keys in a found in b
 * @return {Object}
 */
function merge (a, b, noforce) {
  if (a && b && a === Object(a) && b === Object(b)) {
    for (var key in b) {
      if (noforce) {
        if (!a.hasOwnProperty(key)) a[key] = b[key];
      } else {
        a[key] = b[key];
      }
    }
  }
  return a;
}
exports.merge = merge;

/**
 * Create an array containing the unique members of an array.
 *
 * var array = ['a', 'b', 1, 2, 'a', 3 ];
 *
 * unique(array);
 * // => ['b', 1, 2, 'a', 3 ]
 *
 * @param {Array} array
 * @return {Array}
 */
function unique (array) {
  var a = [];
  var l = array.length;
  for (var i=0; i<l; i++) {
    for (var j=i+1; j<l; j++) {
      // If array[i] is found later in the array
      if (array[i] === array[j])
        j = ++i;
    }
    a.push(array[i]);
  }
  return a;
}
exports.unique = unique;

/**
 * Utility function to test for and extract a subkey.
 *
 * var obj = { '#': 'foo', 'bar': 'baz' };
 *
 * get(obj);
 * // => 'foo'
 *
 * get(obj, 'bar');
 * // => 'baz'
 *
 * @param {Object} obj
 * @param {String} [subkey="#"] By default, use the '#' key, but you may pass any key you like
 * @return Returns the value of the selected key or 'null' if undefined.
 */
function get(obj, subkey) {
  if (!subkey)
    subkey = '#';

  if (Array.isArray(obj))
    obj = obj[0];

  if (obj && obj[subkey])
    return obj[subkey];
  else
    return null;
}
exports.get = get;

function resolve (baseUrl, pathUrl) {
  return URL.resolve(baseUrl, pathUrl);
}
exports.resolve = resolve;<commit_msg>Add nslookup function for checking whether a uri matches the default for a namespace.<commit_after>
/**
 * Module dependencies.
 */
var URL = require('url')
  , NS = require('./namespaces')
  ;

/**
 * Merge object b with object a.
 *
 * var a = { foo: 'bar' }
 *   , b = { foo: 'quux', bar: 'baz' };
 *
 * merge(a, b);
 * // => { foo: 'quux', bar: 'baz' }
 *
 * merge(a, b, true);
 * // => { foo: 'bar', bar: 'baz' }
 *
 * @param {Object} a
 * @param {Object} b
 * @param {Boolean} [noforce] Optionally, don't overwrite any existing keys in a found in b
 * @return {Object}
 */
function merge (a, b, noforce) {
  if (a && b && a === Object(a) && b === Object(b)) {
    for (var key in b) {
      if (noforce) {
        if (!a.hasOwnProperty(key)) a[key] = b[key];
      } else {
        a[key] = b[key];
      }
    }
  }
  return a;
}
exports.merge = merge;

/**
 * Create an array containing the unique members of an array.
 *
 * var array = ['a', 'b', 1, 2, 'a', 3 ];
 *
 * unique(array);
 * // => ['b', 1, 2, 'a', 3 ]
 *
 * @param {Array} array
 * @return {Array}
 */
function unique (array) {
  var a = [];
  var l = array.length;
  for (var i=0; i<l; i++) {
    for (var j=i+1; j<l; j++) {
      // If array[i] is found later in the array
      if (array[i] === array[j])
        j = ++i;
    }
    a.push(array[i]);
  }
  return a;
}
exports.unique = unique;

/**
 * Utility function to test for and extract a subkey.
 *
 * var obj = { '#': 'foo', 'bar': 'baz' };
 *
 * get(obj);
 * // => 'foo'
 *
 * get(obj, 'bar');
 * // => 'baz'
 *
 * @param {Object} obj
 * @param {String} [subkey="#"] By default, use the '#' key, but you may pass any key you like
 * @return Returns the value of the selected key or 'null' if undefined.
 */
function get(obj, subkey) {
  if (!subkey)
    subkey = '#';

  if (Array.isArray(obj))
    obj = obj[0];

  if (obj && obj[subkey])
    return obj[subkey];
  else
    return null;
}
exports.get = get;

function resolve (baseUrl, pathUrl) {
  return URL.resolve(baseUrl, pathUrl);
}
exports.resolve = resolve;

/*
 * Check whether a given namespace URI matches the given default
 *
 * @param {String} URI
 * @param {String} default, e.g., 'atom'
 * @return {Boolean}
 */
function nslookup (uri, def) {
  return NS[uri] === def;
}
exports.nslookup = nslookup;<|endoftext|>


<commit_before>import React from 'react'

var imageStyles = {
    width: '450px',
    height: '350px'
}

const About = () => (

MARVELUS - Canvas Group 15

            {/*  */}

Marvelus is for users who want to browse
                superheros, movies, TV shows, comics, creators, events having to do with the Marvel Universe.

Group Members

Andrew Martin

Bio:  Andrew Martin is a third year Computer Science student, expecting to graduate
                            at the end of this year. I am also interested in music and linguistics, and I love to
                            travel.

Responsibilities: Database and back end

No. of Commits: 53

No. of Issues: 10

No. of Unit Tests:  6

 Bhavish Yalamanchi

Bio:  I am a senior studying CS. I am currently exploring my options and figuring out
                            what I want to specialize in. I am currently interested in Data Science and am learning how
                            to use TensorFlow in my freetime. I also love making music and photography. Whether it be
                            photos, videos, or music, I think art is an important outlet that everyone should try.

Responsibilities: Front end

No. of Commits: 14

No. of Issues:  8

No. of Issues:

No. of Unit Tests:  2

Hannah Anees

Bio:  Hannah Anees is in her third year of Computer Science at the University of
                            Texas and will be graduating in 2019 with a Bachelor’s of Science degree. She enjoys
                            conspiracy theories, urban myths and legends and anything else that might make the world
                            seem more interesting. She also is interested in music and TV Shows and only tolerates some
                            of the Marvel creations, most notably Spider-Man.

Responsibilities: Front end

No. of Commits: 70

No. of Issues:  8

No. of Unit Tests: 2

Helen Salgi

Bio: Sophomore majoring in Linguistics. Loves traveling and food and will be
                            graduating in May 2020.

Observer

Sunaina Krishnamoorthy

Bio:  Sunaina Krishnamoorthy is a junior majoring in Computer Science at the
                            University of Texas. She loves travel, photography and music. She will be graduating in May
                            of 2019 with a Bachelor's degree in Computer Science.

Responsibilities: Database and back end

No. of Commits: 38

No. of Issues:  8

No. of Unit Tests:  2

Tesia Wu

Bio:  Tesia Wu is a junior majoring in Computer Science at the University of Texas.
                            She is a huge fan of the Korean boy band BTS and loves music and movies, especially the
                            Marvel Cinematic Universe. She will be graduating in May of 2019 with a Bachelor's degree in
                            Computer Science.

Responsibilities: Database and back end

No. of Commits: 66

No. of Issues:  8

No. of Unit Tests: 2

Statistics

Total No. of Commits:241

Total No. of Issues:42

Total No. of Unit Tests: 13

Apiary API

GITHUB REPO

TRELLO

Data

            {/*  */}

Marvel API: We did not use any
                specific libraries to scrape the Marvel API, just the python requests module.

The Movie Database: We used the
                 tmdbsimple library to scrape data from the tmdb
                API

Tools used

Technical report

)

export default About
<commit_msg>started adding comments<commit_after>import React from 'react'

// Style for pictures so all consistent sizes
var imageStyles = {
    width: '450px',
    height: '350px'
}

const About = () => (

MARVELUS - Canvas Group 15

            // General description for the site -- tells what this site is about

Marvelus is for users who want to browse
                superheros, movies, TV shows, comics, creators, events having to do with the Marvel Universe.

            // Start group member information/statistics

Group Members

Andrew Martin

Bio:  Andrew Martin is a third year Computer Science student, expecting to graduate
                            at the end of this year. I am also interested in music and linguistics, and I love to
                            travel.

Responsibilities: Database and back end

No. of Commits: 53

No. of Issues: 10

No. of Unit Tests:  6

 Bhavish Yalamanchi

Bio:  I am a senior studying CS. I am currently exploring my options and figuring out
                            what I want to specialize in. I am currently interested in Data Science and am learning how
                            to use TensorFlow in my freetime. I also love making music and photography. Whether it be
                            photos, videos, or music, I think art is an important outlet that everyone should try.

Responsibilities: Front end

No. of Commits: 14

No. of Issues:  8

No. of Issues:

No. of Unit Tests:  2

Hannah Anees

Bio:  Hannah Anees is in her third year of Computer Science at the University of
                            Texas and will be graduating in 2019 with a Bachelor’s of Science degree. She enjoys
                            conspiracy theories, urban myths and legends and anything else that might make the world
                            seem more interesting. She also is interested in music and TV Shows and only tolerates some
                            of the Marvel creations, most notably Spider-Man.

Responsibilities: Front end

No. of Commits: 70

No. of Issues:  8

No. of Unit Tests: 2

Helen Salgi

Bio: Sophomore majoring in Linguistics. Loves traveling and food and will be
                            graduating in May 2020.

Observer

Sunaina Krishnamoorthy

Bio:  Sunaina Krishnamoorthy is a junior majoring in Computer Science at the
                            University of Texas. She loves travel, photography and music. She will be graduating in May
                            of 2019 with a Bachelor's degree in Computer Science.

Responsibilities: Database and back end

No. of Commits: 38

No. of Issues:  8

No. of Unit Tests:  2

Tesia Wu

Bio:  Tesia Wu is a junior majoring in Computer Science at the University of Texas.
                            She is a huge fan of the Korean boy band BTS and loves music and movies, especially the
                            Marvel Cinematic Universe. She will be graduating in May of 2019 with a Bachelor's degree in
                            Computer Science.

Responsibilities: Database and back end

No. of Commits: 66

No. of Issues:  8

No. of Unit Tests: 2

            // General group statistics

Statistics

Total No. of Commits:241

Total No. of Issues:42

Total No. of Unit Tests: 13

Apiary API

GITHUB REPO

TRELLO

            // Links to the required resources

Data

Marvel API: We did not use any
                specific libraries to scrape the Marvel API, just the python requests module.

The Movie Database: We used the
                 tmdbsimple library to scrape data from the tmdb
                API

Tools used

Technical report

)

export default About
<|endoftext|>


<commit_before>/**
 * @preserve jquery.fullscreen 1.1.5
 * https://github.com/kayahr/jquery-fullscreen-plugin
 * Copyright (C) 2012-2013 Klaus Reimer <k@ailis.de>
 * Licensed under the MIT license
 * (See http://www.opensource.org/licenses/mit-license)
 */

(function() {

/**
 * Sets or gets the fullscreen state.
 *
 * @param {boolean=} state
 *            True to enable fullscreen mode, false to disable it. If not
 *            specified then the current fullscreen state is returned.
 * @return {boolean|Element|jQuery|null}
 *            When querying the fullscreen state then the current fullscreen
 *            element (or true if browser doesn't support it) is returned
 *            when browser is currently in full screen mode. False is returned
 *            if browser is not in full screen mode. Null is returned if
 *            browser doesn't support fullscreen mode at all. When setting
 *            the fullscreen state then the current jQuery selection is
 *            returned for chaining.
 * @this {jQuery}
 */
function fullScreen(state)
{
    var e, func, doc;

    // Do nothing when nothing was selected
    if (!this.length) return this;

    // We only use the first selected element because it doesn't make sense
    // to fullscreen multiple elements.
    e = (/** @type {Element} */ this[0]);

    // Find the real element and the document (Depends on whether the
    // document itself or a HTML element was selected)
    if (e.ownerDocument)
    {
        doc = e.ownerDocument;
    }
    else
    {
        doc = e;
        e = doc.documentElement;
    }

    // When no state was specified then return the current state.
    if (state == null)
    {
        // When fullscreen mode is not supported then return null
        if (!((/** @type {?Function} */ doc["exitFullscreen"])
            || (/** @type {?Function} */ doc["webkitExitFullscreen"])
            || (/** @type {?Function} */ doc["webkitCancelFullScreen"])
            || (/** @type {?Function} */ doc["msExitFullscreen"])
            || (/** @type {?Function} */ doc["mozCancelFullScreen"])))
        {
            return null;
        }

        // Check fullscreen state
        state = !!doc["fullscreenElement"]
            || !!doc["msFullscreenElement"]
            || !!doc["webkitIsFullScreen"]
            || !!doc["mozFullScreen"];
        if (!state) return state;

        // Return current fullscreen element or "true" if browser doesn't
        // support this
        return (/** @type {?Element} */ doc["fullscreenElement"])
            || (/** @type {?Element} */ doc["webkitFullscreenElement"])
            || (/** @type {?Element} */ doc["webkitCurrentFullScreenElement"])
            || (/** @type {?Element} */ doc["msFullscreenElement"])
            || (/** @type {?Element} */ doc["mozFullScreenElement"])
            || state;
    }

    // When state was specified then enter or exit fullscreen mode.
    if (state)
    {
        // Enter fullscreen
        func = (/** @type {?Function} */ e["requestFullscreen"])
            || (/** @type {?Function} */ e["webkitRequestFullscreen"])
            || (/** @type {?Function} */ e["webkitRequestFullScreen"])
            || (/** @type {?Function} */ e["msRequestFullscreen"])
            || (/** @type {?Function} */ e["mozRequestFullScreen"]);
        if (func)
        {
            func.call(e);
        }
        return this;
    }
    else
    {
        // Exit fullscreen
        func = (/** @type {?Function} */ doc["exitFullscreen"])
            || (/** @type {?Function} */ doc["webkitExitFullscreen"])
            || (/** @type {?Function} */ doc["webkitCancelFullScreen"])
            || (/** @type {?Function} */ doc["msExitFullscreen"])
            || (/** @type {?Function} */ doc["mozCancelFullScreen"]);
        if (func) func.call(doc);
        return this;
    }
}

/**
 * Toggles the fullscreen mode.
 *
 * @return {!jQuery}
 *            The jQuery selection for chaining.
 * @this {jQuery}
 */
function toggleFullScreen()
{
    return (/** @type {!jQuery} */ fullScreen.call(this,
        !fullScreen.call(this)));
}

/**
 * Handles the browser-specific fullscreenchange event and triggers
 * a jquery event for it.
 *
 * @param {?Event} event
 *            The fullscreenchange event.
 */
function fullScreenChangeHandler(event)
{
    jQuery(document).trigger(new jQuery.Event("fullscreenchange"));
}

/**
 * Handles the browser-specific fullscreenerror event and triggers
 * a jquery event for it.
 *
 * @param {?Event} event
 *            The fullscreenerror event.
 */
function fullScreenErrorHandler(event)
{
    jQuery(document).trigger(new jQuery.Event("fullscreenerror"));
}

/**
 * Installs the fullscreenchange event handler.
 */
function installFullScreenHandlers()
{
    var e, change, error;

    // Determine event name
    e = document;
    if (e["webkitCancelFullScreen"])
    {
        change = "webkitfullscreenchange";
        error = "webkitfullscreenerror";
    }
    else if (e["msExitFullscreen"])
    {
        change = "MSFullscreenChange";
        error = "MSFullscreenError";
    }
    else if (e["mozCancelFullScreen"])
    {
        change = "mozfullscreenchange";
        error = "mozfullscreenerror";
    }
    else
    {
        change = "fullscreenchange";
        error = "fullscreenerror";
    }

    // Install the event handlers
    jQuery(document).bind(change, fullScreenChangeHandler);
    jQuery(document).bind(error, fullScreenErrorHandler);
}

jQuery.fn["fullScreen"] = fullScreen;
jQuery.fn["toggleFullScreen"] = toggleFullScreen;
installFullScreenHandlers();

})();
<commit_msg>Pass the jQuery variable in to the setup function, this is necessary in environments where jQuery is removed from the window scope (via `jQuery.noConflict(true);`).<commit_after>/**
 * @preserve jquery.fullscreen 1.1.5
 * https://github.com/kayahr/jquery-fullscreen-plugin
 * Copyright (C) 2012-2013 Klaus Reimer <k@ailis.de>
 * Licensed under the MIT license
 * (See http://www.opensource.org/licenses/mit-license)
 */

(function(jQuery) {

/**
 * Sets or gets the fullscreen state.
 *
 * @param {boolean=} state
 *            True to enable fullscreen mode, false to disable it. If not
 *            specified then the current fullscreen state is returned.
 * @return {boolean|Element|jQuery|null}
 *            When querying the fullscreen state then the current fullscreen
 *            element (or true if browser doesn't support it) is returned
 *            when browser is currently in full screen mode. False is returned
 *            if browser is not in full screen mode. Null is returned if
 *            browser doesn't support fullscreen mode at all. When setting
 *            the fullscreen state then the current jQuery selection is
 *            returned for chaining.
 * @this {jQuery}
 */
function fullScreen(state)
{
    var e, func, doc;

    // Do nothing when nothing was selected
    if (!this.length) return this;

    // We only use the first selected element because it doesn't make sense
    // to fullscreen multiple elements.
    e = (/** @type {Element} */ this[0]);

    // Find the real element and the document (Depends on whether the
    // document itself or a HTML element was selected)
    if (e.ownerDocument)
    {
        doc = e.ownerDocument;
    }
    else
    {
        doc = e;
        e = doc.documentElement;
    }

    // When no state was specified then return the current state.
    if (state == null)
    {
        // When fullscreen mode is not supported then return null
        if (!((/** @type {?Function} */ doc["exitFullscreen"])
            || (/** @type {?Function} */ doc["webkitExitFullscreen"])
            || (/** @type {?Function} */ doc["webkitCancelFullScreen"])
            || (/** @type {?Function} */ doc["msExitFullscreen"])
            || (/** @type {?Function} */ doc["mozCancelFullScreen"])))
        {
            return null;
        }

        // Check fullscreen state
        state = !!doc["fullscreenElement"]
            || !!doc["msFullscreenElement"]
            || !!doc["webkitIsFullScreen"]
            || !!doc["mozFullScreen"];
        if (!state) return state;

        // Return current fullscreen element or "true" if browser doesn't
        // support this
        return (/** @type {?Element} */ doc["fullscreenElement"])
            || (/** @type {?Element} */ doc["webkitFullscreenElement"])
            || (/** @type {?Element} */ doc["webkitCurrentFullScreenElement"])
            || (/** @type {?Element} */ doc["msFullscreenElement"])
            || (/** @type {?Element} */ doc["mozFullScreenElement"])
            || state;
    }

    // When state was specified then enter or exit fullscreen mode.
    if (state)
    {
        // Enter fullscreen
        func = (/** @type {?Function} */ e["requestFullscreen"])
            || (/** @type {?Function} */ e["webkitRequestFullscreen"])
            || (/** @type {?Function} */ e["webkitRequestFullScreen"])
            || (/** @type {?Function} */ e["msRequestFullscreen"])
            || (/** @type {?Function} */ e["mozRequestFullScreen"]);
        if (func)
        {
            func.call(e);
        }
        return this;
    }
    else
    {
        // Exit fullscreen
        func = (/** @type {?Function} */ doc["exitFullscreen"])
            || (/** @type {?Function} */ doc["webkitExitFullscreen"])
            || (/** @type {?Function} */ doc["webkitCancelFullScreen"])
            || (/** @type {?Function} */ doc["msExitFullscreen"])
            || (/** @type {?Function} */ doc["mozCancelFullScreen"]);
        if (func) func.call(doc);
        return this;
    }
}

/**
 * Toggles the fullscreen mode.
 *
 * @return {!jQuery}
 *            The jQuery selection for chaining.
 * @this {jQuery}
 */
function toggleFullScreen()
{
    return (/** @type {!jQuery} */ fullScreen.call(this,
        !fullScreen.call(this)));
}

/**
 * Handles the browser-specific fullscreenchange event and triggers
 * a jquery event for it.
 *
 * @param {?Event} event
 *            The fullscreenchange event.
 */
function fullScreenChangeHandler(event)
{
    jQuery(document).trigger(new jQuery.Event("fullscreenchange"));
}

/**
 * Handles the browser-specific fullscreenerror event and triggers
 * a jquery event for it.
 *
 * @param {?Event} event
 *            The fullscreenerror event.
 */
function fullScreenErrorHandler(event)
{
    jQuery(document).trigger(new jQuery.Event("fullscreenerror"));
}

/**
 * Installs the fullscreenchange event handler.
 */
function installFullScreenHandlers()
{
    var e, change, error;

    // Determine event name
    e = document;
    if (e["webkitCancelFullScreen"])
    {
        change = "webkitfullscreenchange";
        error = "webkitfullscreenerror";
    }
    else if (e["msExitFullscreen"])
    {
        change = "MSFullscreenChange";
        error = "MSFullscreenError";
    }
    else if (e["mozCancelFullScreen"])
    {
        change = "mozfullscreenchange";
        error = "mozfullscreenerror";
    }
    else
    {
        change = "fullscreenchange";
        error = "fullscreenerror";
    }

    // Install the event handlers
    jQuery(document).bind(change, fullScreenChangeHandler);
    jQuery(document).bind(error, fullScreenErrorHandler);
}

jQuery.fn["fullScreen"] = fullScreen;
jQuery.fn["toggleFullScreen"] = toggleFullScreen;
installFullScreenHandlers();

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

var Runtime = require('../.');

var runtime = Runtime.create({
  wait: true,
  onHandle: function(site, index, next){
    var props = this.props[index];

    if(!this.time && !props.host){
      console.log(' start ->', this.tree().label);
      this.time = process.hrtime();
    } else if(!props.time && props.host){
      console.log('start ->', props.host.tree().label);
    }

    if(props.site){
      console.log(props.time ? ' ended' : ' start',
        props.site.name
      );
    }

    if(props.host && props.host.end){
      console.log('ended ->', props.host.tree().label);
    } else if(this.end && !props.host){
      console.log(' ended ->', this.tree().label);
    }
    props.time = process.hrtime();
  },
  reduceStack: function(stack, site){
    if(typeof site !== 'function'){ return stack; }

    stack.push(site);
    stack.props = stack.props || [];
    if(site.stack instanceof this.Stack){
      stack.props.push({host: stack});
    } else {
      stack.props.push({site: site});
    }

    return stack;
  }
});

function one(next){
  setTimeout(next, 10*Math.random());
}

function two(next){
  setTimeout(next, 10*Math.random());
}

function three(next){
  setTimeout(next, 10*Math.random());
}

var taskOne = runtime.stack(one, two);
var taskTwo = runtime.stack(three);

runtime.stack(taskOne, taskTwo)();
<commit_msg>docs: series + parallel hostStack example<commit_after>'use strict';

var Runtime = require('../.');

var runtime = Runtime.create({
  onHandle: function(site, index, stack){
    var props = this.props[index];

    if(!this.time && !props.host){
      console.log(' start ->', this.tree().label);
      this.time = process.hrtime();
    } else if(!props.time && props.host){
      console.log('start ->', props.host.tree().label);
    }

    if(props.site){
      console.log(props.time ? ' ended' : ' start',
        props.site.name
      );
    }

    if(props.host && props.host.end){
      console.log('ended ->', props.host.tree().label);
    } else if(this.end && !props.host){
      console.log(' ended ->', this.tree().label);
    }
    props.time = process.hrtime();
  },
  reduceStack: function(stack, site){
    if(typeof site !== 'function'){ return stack; }

    stack.push(site);
    stack.props = stack.props || [];
    if(site.stack instanceof this.Stack){
      stack.props.push({host: stack});
    } else {
      stack.props.push({site: site});
    }

    return stack;
  }
});

function one(next){
  setTimeout(next, 1000*Math.random());
}

function two(next){
  setTimeout(next, 2000*Math.random());
}

function three(next){
  setTimeout(next, 3000*Math.random());
}

var taskOne = runtime.stack(one, two, {wait: true});
var taskTwo = runtime.stack(three);

runtime.stack(taskOne, taskTwo)();
<|endoftext|>


<commit_before>"use strict";

const util = require('util');
const stream = require('stream');

const fullTierList = ['Uber', 'OU', 'BL', 'UU', 'BL2', 'RU', 'BL3', 'NU', 'BL4', 'PU'];
const tierPositions = Object.create(null);
for (let i = 0; i < fullTierList.length; i++) {
	tierPositions[fullTierList[i]] = i;
}

exports.tiers = fullTierList;
exports.getTierIndex = function (tier) {
	return tierPositions[tier.replace(/[\(\)]/g, '')];
};

function RangeValidator(start, end) {
	return function (value) {
		return value >= start && value <= end;
	};
}

/* Assume integer inputs */
exports.isValidEV = new RangeValidator(0, 252);
exports.isValidIV = new RangeValidator(0, 32);
exports.isValidLevel = new RangeValidator(1, 100);
exports.isValidHappiness = new RangeValidator(0, 252);

exports.toDict = function (data) {
	if (!Array.isArray(data)) throw new TypeError("toDict only accepts arrays as input");
	const dict = Object.create(null);
	for (let i = 0, len = data.length; i < len; i++) {
		dict[data[i]] = 1;
	}
	return dict;
};

exports.inValues = function inValues(obj, val) {
	for (let key in obj) {
		if (obj[key] === val) return true;
	}
	return false;
};

const cloneObject = exports.clone = function clone(obj) {
	const clonedObj = {};
	for (let key in obj) {
		clonedObj[key] = obj[key];
	}
	return clonedObj;
};

const setKeys = ['species', 'gender', 'item', 'ability', 'shiny', 'level', 'happiness', 'evs', 'ivs', 'nature', 'moves'];

exports.markConflict = function markConflict(set, conflict) {
	return Object.defineProperty(set, 'conflict', {
		value: conflict,
		enumerable: false,
		writable: true,
		configurable: true,
	});
};

const markClone = exports.markClone = function markClone(set) {
	return Object.defineProperty(set, 'isClone', {
		value: true,
		enumerable: false,
		writable: true,
		configurable: true,
	});
};

exports.copySet = function copySet(set) {
	const clone = {};

	for (let i = 0; i < setKeys.length; i++) {
		let key = setKeys[i];
		if (!(key in set)) continue;
		if (typeof set[key] !== 'object') {
			// Primitive; never a function (or symbol)
			clone[key] = set[key];
		} else if (!Array.isArray(set[key])) {
			// Object with depth 1
			clone[key] = cloneObject(set[key]);
		} else {
			// Array of arrays
			clone[key] = Array(set[key].length);
			for (let j = 0; j < set[key].length; j++) {
				clone[key][j] = set[key][j].slice();
			}
		}
	}

	return markClone(clone);
};

// Notations supported by PS teambuilder
exports.statIDs = {
	HP: 'hp', hp: 'hp',
	Atk: 'atk', atk: 'atk',
	Def: 'def', def: 'def',
	SpA: 'spa', SAtk: 'spa', SpAtk: 'spa', spa: 'spa',
	SpD: 'spd', SDef: 'spd', SpDef: 'spd', spd: 'spd',
	Spe: 'spe', Spd: 'spe', spe: 'spe',
};

function OutputStream() {
	stream.Writable.call(this);
	this.setData = '';
}
util.inherits(OutputStream, stream.Writable);
OutputStream.prototype.write = function (data) {
	this.setData += data;
};

exports.OutputStream = OutputStream;
<commit_msg>Fix usage of the WritableStream API<commit_after>"use strict";

const util = require('util');
const stream = require('stream');

const fullTierList = ['Uber', 'OU', 'BL', 'UU', 'BL2', 'RU', 'BL3', 'NU', 'BL4', 'PU'];
const tierPositions = Object.create(null);
for (let i = 0; i < fullTierList.length; i++) {
	tierPositions[fullTierList[i]] = i;
}

exports.tiers = fullTierList;
exports.getTierIndex = function (tier) {
	return tierPositions[tier.replace(/[\(\)]/g, '')];
};

function RangeValidator(start, end) {
	return function (value) {
		return value >= start && value <= end;
	};
}

/* Assume integer inputs */
exports.isValidEV = new RangeValidator(0, 252);
exports.isValidIV = new RangeValidator(0, 32);
exports.isValidLevel = new RangeValidator(1, 100);
exports.isValidHappiness = new RangeValidator(0, 252);

exports.toDict = function (data) {
	if (!Array.isArray(data)) throw new TypeError("toDict only accepts arrays as input");
	const dict = Object.create(null);
	for (let i = 0, len = data.length; i < len; i++) {
		dict[data[i]] = 1;
	}
	return dict;
};

exports.inValues = function inValues(obj, val) {
	for (let key in obj) {
		if (obj[key] === val) return true;
	}
	return false;
};

const cloneObject = exports.clone = function clone(obj) {
	const clonedObj = {};
	for (let key in obj) {
		clonedObj[key] = obj[key];
	}
	return clonedObj;
};

const setKeys = ['species', 'gender', 'item', 'ability', 'shiny', 'level', 'happiness', 'evs', 'ivs', 'nature', 'moves'];

exports.markConflict = function markConflict(set, conflict) {
	return Object.defineProperty(set, 'conflict', {
		value: conflict,
		enumerable: false,
		writable: true,
		configurable: true,
	});
};

const markClone = exports.markClone = function markClone(set) {
	return Object.defineProperty(set, 'isClone', {
		value: true,
		enumerable: false,
		writable: true,
		configurable: true,
	});
};

exports.copySet = function copySet(set) {
	const clone = {};

	for (let i = 0; i < setKeys.length; i++) {
		let key = setKeys[i];
		if (!(key in set)) continue;
		if (typeof set[key] !== 'object') {
			// Primitive; never a function (or symbol)
			clone[key] = set[key];
		} else if (!Array.isArray(set[key])) {
			// Object with depth 1
			clone[key] = cloneObject(set[key]);
		} else {
			// Array of arrays
			clone[key] = Array(set[key].length);
			for (let j = 0; j < set[key].length; j++) {
				clone[key][j] = set[key][j].slice();
			}
		}
	}

	return markClone(clone);
};

// Notations supported by PS teambuilder
exports.statIDs = {
	HP: 'hp', hp: 'hp',
	Atk: 'atk', atk: 'atk',
	Def: 'def', def: 'def',
	SpA: 'spa', SAtk: 'spa', SpAtk: 'spa', spa: 'spa',
	SpD: 'spd', SDef: 'spd', SpDef: 'spd', spd: 'spd',
	Spe: 'spe', Spd: 'spe', spe: 'spe',
};

function OutputStream() {
	stream.Writable.call(this);
	this.setData = '';
}
util.inherits(OutputStream, stream.Writable);
OutputStream.prototype._write = function (data, encoding, cb) {
	this.setData += data;
	cb();
};

exports.OutputStream = OutputStream;
<|endoftext|>


<commit_before>var Section = null;

$(document).ready(function() {
    var $body = $('body');

    Section = Class.extend({
        init: function(name, transEndTrigger, firstPage) {
            this.name = name;
            this.transEndTrigger = transEndTrigger;
            this.firstPage = firstPage;
            this.currentPage = null;
        },

        hide: function(callback) {
            $body.removeClass(this.name);
            if(this.currentPage) {
                $body.removeClass(this.currentPage);
                this.currentPage = null;
            }
            onTransitionEndOnce($(this.transEndTrigger), callback);
        },

        show: function() {
            var self = this;
            $body.addClass(this.name);
            if(this.firstPage) {
                onTransitionEndOnce($(this.transEndTrigger), function() {
                    self.changePage(self.firstPage);
                });
            }
        },

        changePage: function(pageName) {
            var self = this,
                doChangePage = function() {
                    $body.addClass(pageName);
                    publish("pagechange", [pageName]);
                };

            if(pageName !== this.currentPage) {
                if(this.currentPage) {
                    $body.removeClass(this.currentPage);
                    onTransitionEndOnce($('#'+this.currentPage), doChangePage);
                } else {
                    doChangePage();
                }
                this.currentPage = pageName;
            }
        }
    });
});<commit_msg>Fixed a bug displaying two pages simultaneously when changing pages too fast<commit_after>var Section = null;

$(document).ready(function() {
    var $body = $('body');

    Section = Class.extend({
        init: function(name, transEndTrigger, firstPage) {
            this.name = name;
            this.transEndTrigger = transEndTrigger;
            this.firstPage = firstPage;
            this.currentPage = null;
            this.isChangingPage = false;
        },

        hide: function(callback) {
            $body.removeClass(this.name);
            if(this.currentPage) {
                $body.removeClass(this.currentPage);
                this.currentPage = null;
            }
            onTransitionEndOnce($(this.transEndTrigger), callback);
        },

        show: function() {
            var self = this;
            this.isChangingPage = false;
            this.currentPage = null;
            $body.addClass(this.name);
            if(this.firstPage) {
                onTransitionEndOnce($(this.transEndTrigger), function() {
                    self.changePage(self.firstPage);
                });
            }
        },

        changePage: function(pageName) {
            var self = this,
                doChangePage = function() {
                    $body.addClass(pageName);
                    publish("pagechange", [pageName]);
                    self.isChangingPage = false;
                };

            if(pageName !== this.currentPage && !this.isChangingPage) {
                this.isChangingPage = true;
                if(this.currentPage) {
                    $body.removeClass(this.currentPage);
                    onTransitionEndOnce($('#'+this.currentPage), doChangePage);
                } else {
                    doChangePage();
                }
                this.currentPage = pageName;
            }
        }
    });
});<|endoftext|>


<commit_before>var $selects;

// Access nested values in a hash by passing a string,
// where nested keys are denoted by a period.
// E.g.
//     var myObj = {hi: {there: {whats: 'up'}}};
//     getKey(myObj, 'hi.there.whats'); //=> 'up'
var getKey = function(o, k) {
  var a = k.split('.');
  while (a.length) {
    var n = a.shift();
    if (n in o) {
      o = o[n];
    } else {
      return;
    }
  }
  return o;
};

// Replace mustache-style string variables in text with corresponding property in response object
// E.g.
//     response = {name: "you"};
//     subWithResponse("hi {{ name }}", response); //=> "hi you"
var subWithResponse = function(text, response) {
  return text && text.replace(/{{\s*([\w\.]+)\s*}}/g, function (match, capture) { return response[capture];});
}

var refreshAnalytics = function() {
  var $this = $(this),
      chartType = $this.data('chart'),
      $thisSelects = $selects.filter('[data-for-chart="' + this.id + '"]'),
      $granularity = $thisSelects.filter('[data-select="granularity"]'),
      $range = $thisSelects.filter('[data-select="range"]'),
      requestOptions = {},
      $refresh = $('[data-refresh-chart="' + this.id + '"]');

  if ($granularity.length) {
    requestOptions.granularity = $granularity.val();
  }
  if ($range.length) {
    requestOptions.range = $range.val();
  }

  $.ajax({
    dataType: "json",
    url: $this.data('url'),
    data: requestOptions,
    beforeSend: function() {
      $refresh.html('Loading...').removeClass('analytics-refresh-now').addClass('analytics-loading');
    },
    complete: function() {
      $refresh.html('Refresh').removeClass('analytics-loading');
    },
    success: function(response) {
      if (chartType === 'timeseries') {
        var range = response.range,
            keys = response.lookup_keys,
            series = [],
            dateStart = range[0]*1000,
            dateInterval = (range[1] - range[0])*1000,
            showLegend = false;

        // Loop through results
        for (var i = 0, ilen = response.results.length; i < ilen; i++) {
          var record = response.results[i];

          // Loop through keys for each record (events, count, total, etc.)
          for (var k = 0, klen = keys.length; k < klen; k++) {
            var timeKey = keys[k],
                recordName = record.name,
                s = {
                  data: [],
                  pointInterval: dateInterval,
                  pointStart: dateStart
                };

            // If record contains multiple aggregate keys, add key to series label
            if (klen > 1) {
              var timeKeyArray = timeKey.split('.'),
                  index = timeKeyArray.indexOf('{{t}}');

              // But don't count the different timestamps as multiple keys
              timeKeyArray.splice(index, 1);

              if (timeKeyArray.length) {
                // Don't know if recordName is defined or not,
                // and don't want a separator if it's undefined.
                recordName = recordName ? recordName + ' - ' : '';
                recordName += timeKeyArray.slice(-1)[0];
              }
            }
            s.name = recordName;
            // Only display legend when more than one series is present
            // and there are series labels to show.
            if (s.name) {
              showLegend = true;
            }

            // Build the array of plot values
            for (var t = 0, tlen = range.length; t < tlen; t++) {
              var x = range[t],
                  y = getKey(record, timeKey.replace('{{t}}', response.granularity + '.' + x)) || 0;
              s.data.push( y );
            }

            series.push(s);
          }
        }

        // Set highcharts defaults from data attributes and response values
        options = {
          title: {
            text: subWithResponse($this.data('title'), response),
            x: -20 //center
          },
          subtitle: {
            text: subWithResponse($this.data('subtitle'), response),
            x: -20
          },
          xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: { // don't display the year
              minute: '%H:%M'
            }
          },
          yAxis: {
            min: 0,
            title: {
              text: subWithResponse($this.data('y-axis-label'), response)
            },
            plotLines: [{
              value: 0,
              width: 1,
              color: '#808080'
            }]
          },
          legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
          },
          plotOptions: {
            series: {
              events: {

                // Allow filtering shown series in chart
                legendItemClick: function(event) {
                  var selected = this.index,
                  allSeries = this.chart.series,
                  state = this.toggleState || 'visible',
                  othersAction;

                  if (state === 'visible') {
                    othersAction = 'hide';
                    this.toggleState = 'solo';
                  } else {
                    othersAction = 'show';
                    this.toggleState = 'visible';
                  }

                  // Hold shift, ctrl, or cmd to toggle just the clicked series
                  if (event.browserEvent.metaKey || event.browserEvent.shiftKey || event.browserEvent.ctrlKey) {
                    if (state === 'solo') {
                      allSeries[selected].hide();
                    } else {
                      allSeries[selected].show();
                    }

                    // Otherwise, toggle between showing only the clicked series or all series
                  } else {
                    var i = 0,
                    len = allSeries.length;

                    // No idea why highcharts takes so long to loop through and hide/show series,
                    // so for now, we need to use setTimeout to show the user something is happening
                    // and not lock up the UI.
                    function loopSeries() {
                      if (selected === i) {
                        allSeries[selected].show();
                      } else {
                        allSeries[i][othersAction]();
                        delete allSeries[i]['toggle'];
                      }

                      i++;

                      if (i < len) {
                        setTimeout(loopSeries, 0.5);
                      }
                    }

                    loopSeries();
                  }

                  return false;
                }
              }
            }
          },
          series: series
        };

        if (!showLegend) {
          options.legend.enabled = false;
        }

        if ($this.data('y-axis-max')) {
          options.yAxis.max = parseFloat($this.data('y-axis-max'));
        }

        $this.highcharts(options);
      }
      $refresh.html('Refresh').removeClass('analytics-loading');
    }
  });
}

var loadAnalytics = function() {
  $('[data-chart]').each( function() {
    refreshAnalytics.call(this);
  });
};

$(document)
  .delegate('[data-refresh-chart]', 'click', function(e) {
    var chart = $(this).data('refresh-chart');
    refreshAnalytics.call( document.getElementById(chart) );
    e.preventDefault();
  })
  .delegate('[data-for-chart]', 'change', function() {
    var chart = $(this).data('for-chart');
    $('[data-refresh-chart="' + chart + '"]').addClass('analytics-refresh-now');
  });

$(function () {
  // Show charts in browser's timezone instead of UTC as they are stored
  Highcharts.setOptions({
    global: {
      useUTC: false
    }
  });
  $selects = $('[data-for-chart]');
  loadAnalytics();
});
<commit_msg>Updated styling for analytics dashboard.<commit_after>var $selects;

// Access nested values in a hash by passing a string,
// where nested keys are denoted by a period.
// E.g.
//     var myObj = {hi: {there: {whats: 'up'}}};
//     getKey(myObj, 'hi.there.whats'); //=> 'up'
var getKey = function(o, k) {
  var a = k.split('.');
  while (a.length) {
    var n = a.shift();
    if (n in o) {
      o = o[n];
    } else {
      return;
    }
  }
  return o;
};

// Replace mustache-style string variables in text with corresponding property in response object
// E.g.
//     response = {name: "you"};
//     subWithResponse("hi {{ name }}", response); //=> "hi you"
var subWithResponse = function(text, response) {
  return text && text.replace(/{{\s*([\w\.]+)\s*}}/g, function (match, capture) { return response[capture];});
}

var refreshAnalytics = function() {
  var $this = $(this),
      chartType = $this.data('chart'),
      $thisSelects = $selects.filter('[data-for-chart="' + this.id + '"]'),
      $granularity = $thisSelects.filter('[data-select="granularity"]'),
      $range = $thisSelects.filter('[data-select="range"]'),
      requestOptions = {},
      $refresh = $('[data-refresh-chart="' + this.id + '"]');

  if ($granularity.length) {
    requestOptions.granularity = $granularity.val();
  }
  if ($range.length) {
    requestOptions.range = $range.val();
  }

  $.ajax({
    dataType: "json",
    url: $this.data('url'),
    data: requestOptions,
    beforeSend: function() {
      $refresh.html('Loading...').removeClass('btn-success').addClass('analytics-loading');
    },
    complete: function() {
      $refresh.html('Refresh').removeClass('analytics-loading');
    },
    success: function(response) {
      if (chartType === 'timeseries') {
        var range = response.range,
            keys = response.lookup_keys,
            series = [],
            dateStart = range[0]*1000,
            dateInterval = (range[1] - range[0])*1000,
            showLegend = false;

        // Loop through results
        for (var i = 0, ilen = response.results.length; i < ilen; i++) {
          var record = response.results[i];

          // Loop through keys for each record (events, count, total, etc.)
          for (var k = 0, klen = keys.length; k < klen; k++) {
            var timeKey = keys[k],
                recordName = record.name,
                s = {
                  data: [],
                  pointInterval: dateInterval,
                  pointStart: dateStart
                };

            // If record contains multiple aggregate keys, add key to series label
            if (klen > 1) {
              var timeKeyArray = timeKey.split('.'),
                  index = timeKeyArray.indexOf('{{t}}');

              // But don't count the different timestamps as multiple keys
              timeKeyArray.splice(index, 1);

              if (timeKeyArray.length) {
                // Don't know if recordName is defined or not,
                // and don't want a separator if it's undefined.
                recordName = recordName ? recordName + ' - ' : '';
                recordName += timeKeyArray.slice(-1)[0];
              }
            }
            s.name = recordName;
            // Only display legend when more than one series is present
            // and there are series labels to show.
            if (s.name) {
              showLegend = true;
            }

            // Build the array of plot values
            for (var t = 0, tlen = range.length; t < tlen; t++) {
              var x = range[t],
                  y = getKey(record, timeKey.replace('{{t}}', response.granularity + '.' + x)) || 0;
              s.data.push( y );
            }

            series.push(s);
          }
        }

        // Set highcharts defaults from data attributes and response values
        options = {
          title: {
            text: subWithResponse($this.data('title'), response),
            x: -20 //center
          },
          subtitle: {
            text: subWithResponse($this.data('subtitle'), response),
            x: -20
          },
          xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: { // don't display the year
              minute: '%H:%M'
            }
          },
          yAxis: {
            min: 0,
            title: {
              text: subWithResponse($this.data('y-axis-label'), response)
            },
            plotLines: [{
              value: 0,
              width: 1,
              color: '#808080'
            }]
          },
          legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
          },
          plotOptions: {
            series: {
              events: {

                // Allow filtering shown series in chart
                legendItemClick: function(event) {
                  var selected = this.index,
                  allSeries = this.chart.series,
                  state = this.toggleState || 'visible',
                  othersAction;

                  if (state === 'visible') {
                    othersAction = 'hide';
                    this.toggleState = 'solo';
                  } else {
                    othersAction = 'show';
                    this.toggleState = 'visible';
                  }

                  // Hold shift, ctrl, or cmd to toggle just the clicked series
                  if (event.browserEvent.metaKey || event.browserEvent.shiftKey || event.browserEvent.ctrlKey) {
                    if (state === 'solo') {
                      allSeries[selected].hide();
                    } else {
                      allSeries[selected].show();
                    }

                    // Otherwise, toggle between showing only the clicked series or all series
                  } else {
                    var i = 0,
                    len = allSeries.length;

                    // No idea why highcharts takes so long to loop through and hide/show series,
                    // so for now, we need to use setTimeout to show the user something is happening
                    // and not lock up the UI.
                    function loopSeries() {
                      if (selected === i) {
                        allSeries[selected].show();
                      } else {
                        allSeries[i][othersAction]();
                        delete allSeries[i]['toggle'];
                      }

                      i++;

                      if (i < len) {
                        setTimeout(loopSeries, 0.5);
                      }
                    }

                    loopSeries();
                  }

                  return false;
                }
              }
            }
          },
          series: series
        };

        if (!showLegend) {
          options.legend.enabled = false;
        }

        if ($this.data('y-axis-max')) {
          options.yAxis.max = parseFloat($this.data('y-axis-max'));
        }

        $this.highcharts(options);
      }
      $refresh.html('Refresh').removeClass('analytics-loading');
    }
  });
}

var loadAnalytics = function() {
  $('[data-chart]').each( function() {
    refreshAnalytics.call(this);
  });
};

$(document)
  .delegate('[data-refresh-chart]', 'click', function(e) {
    var chart = $(this).data('refresh-chart');
    refreshAnalytics.call( document.getElementById(chart) );
    e.preventDefault();
  })
  .delegate('[data-for-chart]', 'change', function() {
    var chart = $(this).data('for-chart');
    $('[data-refresh-chart="' + chart + '"]').addClass('btn-success');
  });

$(function () {
  // Show charts in browser's timezone instead of UTC as they are stored
  Highcharts.setOptions({
    global: {
      useUTC: false
    }
  });
  $selects = $('[data-for-chart]');
  loadAnalytics();
});
<|endoftext|>


<commit_before>// style of http://caozhi.news.163.com/
// auther Peter Zhang
// July 12 2017

(function($,window){
  var HoverSwing = function(element, option){
    this.$element = $(element);
    this.option = $.extend({},HoverSwing.DEFAULT,option);
    this.$element.css({display: 'block',overflow: 'hidden',transition: 'transform .2s linear',transform: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)'});
    this.$element.on('mousemove', $.proxy(this.transform, this));
    this.$element.on('mouseleave', $.proxy(this.restore, this));
  }

  HoverSwing.DEFAULT = {
    extent: 0.00025
  }

  HoverSwing.prototype.transform = function(e){
    var halfWidth = this.$element.width()/2, halfHeight = this.$element.height()/2;
    var M14 = (e.offsetX/halfWidth-1)*this.option.extent, M24 = (e.offsetY/halfHeight-1)*this.option.extent;
    this.$element.css('transform','matrix3d(1,0,0,'+ M14 +',0,1,0,'+ M24 +',0,0,1,0,0,0,0,1)');
  }

  HoverSwing.prototype.restore = function(e){
    this.$element.css('transform','matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)');
  }

  function Plugin(option){
    return this.each(function(){
      var $this = $(this);
      var data = $this.data('hoverSwing');
      if(!data) $this.data('hoverSwing',(data = new HoverSwing(this, option)));
    })
  }

  var old = $.fn.hoverswing;

  $.fn.hoverswing = Plugin;
  $.fn.hoverswing.Constructor = HoverSwing;

  $.fn.hoverswing.noConflict = function(){
    $.fn.hoverswing = old;
    return this;
  }
})(jQuery,window);
<commit_msg>minor implements<commit_after>// style of http://caozhi.news.163.com/
// auther Peter Zhang
// July 12 2017
(function (factory) {
    var jQuery;
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jQuery'], factory);
    } else if (typeof module === 'object' && typeof module.exports === "object") {
        // Node/CommonJS
        jQuery = require('jQuery');
        module.exports = factory(jQuery);
    } else {
        // Browser globals
        if (typeof window.jQuery === 'undefined')
            throw 'jQuery must be loaded first';
        factory(window.jQuery);
    }
}(function($){
  var HoverSwing = function(element, option){
    this.$element = $(element);
    this.option = $.extend({},HoverSwing.DEFAULT,option);
    this.$element.css({display: 'block',overflow: 'hidden',transition: 'transform .2s linear',transform: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)'});
    this.$element.on('mousemove', $.proxy(this.transform, this));
    this.$element.on('mouseleave', $.proxy(this.restore, this));
  }

  HoverSwing.DEFAULT = {
    extent: 0.00025
  }

  HoverSwing.prototype.transform = function(e){
    var halfWidth = this.$element.width()/2, halfHeight = this.$element.height()/2;
    var M14 = (e.offsetX/halfWidth-1)*this.option.extent, M24 = (e.offsetY/halfHeight-1)*this.option.extent;
    this.$element.css('transform','matrix3d(1,0,0,'+ M14 +',0,1,0,'+ M24 +',0,0,1,0,0,0,0,1)');
  }

  HoverSwing.prototype.restore = function(e){
    this.$element.css('transform','matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)');
  }

  function Plugin(option){
    return this.each(function(){
      var $this = $(this);
      var data = $this.data('hoverSwing');
      if(!data) $this.data('hoverSwing',(data = new HoverSwing(this, option)));
    })
  }

  var old = $.fn.hoverswing;

  $.fn.hoverswing = Plugin;
  $.fn.hoverswing.Constructor = HoverSwing;

  $.fn.hoverswing.noConflict = function(){
    $.fn.hoverswing = old;
    return this;
  }
}));
<|endoftext|>