<commit_before>/* jslint node: true */
'use strict';

var request = require('request');
var jsonPath = require('JSONPath');
var select = require('xpath.js');
var dom = require('xmldom').DOMParser;
var fs = require('fs');

var accessToken;
var globalVariables = {};

var ATTRIBUTE = 2;

function Apickli(scheme, domain, fixturesDirectory) {
	this.domain = scheme + '://' + domain;
	this.headers = {};
	this.httpResponse = {};
	this.requestBody = '';
	this.scenarioVariables = {};
	this.fixturesDirectory = (fixturesDirectory ? fixturesDirectory : '');
	this.queryParameters = [];
}

Apickli.prototype.addRequestHeader = function(name, value) {
	this.headers[name] = value;
};

Apickli.prototype.getResponseObject = function() {
	return this.httpResponse;
};

Apickli.prototype.setRequestBody = function(body) {
	this.requestBody = body;
};

Apickli.prototype.setQueryParameters = function(queryParameters) {
    var paramsObject = {};
    queryParameters.forEach(function(q) {
        paramsObject[q.parameter] = q.value;
    });

	this.queryParameters = paramsObject;
};

Apickli.prototype.pipeFileContentsToRequestBody = function(file, callback) {
	var self = this;
	fs.readFile(this.fixturesDirectory + file, 'utf8', function(err, data) {
		if (err) {
			callback(err);
		}

		self.setRequestBody(data);
		callback();
	});
};

Apickli.prototype.get = function(resource, callback) { // callback(error, response)
	var self = this;

	request.get({
		url: this.domain + resource,
		headers: this.headers,
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.post = function(resource, callback) { // callback(error, response)
	var self = this;
	request({
		url: this.domain + resource,
		headers: this.headers,
		body: this.requestBody,
		method: 'POST',
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.put = function(resource, callback) { // callback(error, response)
	var self = this;
	request({
		url: this.domain + resource,
		headers: this.headers,
		body: this.requestBody,
		method: 'PUT',
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.delete = function(resource, callback) { // callback(error, response)
	var self = this;
	request({
		url: this.domain + resource,
		headers: this.headers,
		body: this.requestBody,
		method: 'DELETE',
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.patch = function(resource, callback) { // callback(error, response)
	var self = this;

	request({
		url: this.domain + resource,
		headers: this.headers,
		body: this.requestBody,
		method: 'PATCH',
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.addHttpBasicAuthorizationHeader = function(username, password) {
	var b64EncodedValue = base64Encode(username + ':' + password);
	this.addRequestHeader('Authorization', 'Basic ' + b64EncodedValue);
};

Apickli.prototype.assertResponseCode = function(responseCode) {
	var realResponseCode = this.getResponseObject().statusCode;
	return (realResponseCode == responseCode);
};

Apickli.prototype.assertResponseContainsHeader = function(header, callback) {
	if (this.getResponseObject().headers[header.toLowerCase()]) {
		return true;
	} else {
		return false;
	}
};

Apickli.prototype.assertHeaderValue = function (header, expression) {
	var realHeaderValue = this.getResponseObject().headers[header.toLowerCase()];
	var regex = new RegExp(expression);
	return (regex.test(realHeaderValue));
};

Apickli.prototype.assertPathInResponseBodyMatchesExpression = function(path, regexp) {
	var regExpObject = new RegExp(regexp);
	var evalValue = evaluatePath(path, this.getResponseObject().body);
	return (regExpObject.test(evalValue));
};

Apickli.prototype.assertResponseBodyContainsExpression = function(expression) {
	var regex = new RegExp(expression);
	return (regex.test(this.getResponseObject().body));
};

Apickli.prototype.assertResponseBodyContentType = function(contentType) {
	var realContentType = getContentType(this.getResponseObject().body);
	return (realContentType === contentType);
};

Apickli.prototype.evaluatePathInResponseBody = function(path) {
	return evaluatePath(path, this.getResponseObject().body);
};

Apickli.prototype.setAccessTokenFromResponseBodyPath = function(path) {
	accessToken = evaluatePath(path, this.getResponseObject().body);
};

Apickli.prototype.setBearerToken = function() {
	this.addRequestHeader('Authorization', 'Bearer ' + accessToken);
};

Apickli.prototype.storeValueOfHeaderInScenarioScope = function(header, variableName) {
	var value = this.getResponseObject().headers[header.toLowerCase()];
	this.scenarioVariables[variableName] = value;
};

Apickli.prototype.storeValueOfResponseBodyPathInScenarioScope = function(path, variableName) {
	var value = evaluatePath(path, this.getResponseObject().body);
	this.scenarioVariables[variableName] = value;
};

Apickli.prototype.assertScenarioVariableValue = function(variable, value) {
	return (String(this.scenarioVariables[variable]) === value);
};

Apickli.prototype.storeValueOfHeaderInGlobalScope = function(headerName, variableName) {
	var value = this.getResponseObject().headers[headerName.toLowerCase()];
	this.setGlobalVariable(variableName, value);
};

Apickli.prototype.storeValueOfResponseBodyPathInGlobalScope = function(path, variableName) {
	var value = evaluatePath(path, this.getResponseObject().body);
	this.setGlobalVariable(variableName, value);
};

Apickli.prototype.setGlobalVariable = function(name, value) {
	globalVariables[name] = value;
};

Apickli.prototype.getGlobalVariable = function(name) {
	return globalVariables[name];
};

exports.Apickli = Apickli;

var getContentType = function(content) {
	try{
		JSON.parse(content);
		return 'json';
	} catch(e) {
		try{
			new dom().parseFromString(content);
			return 'xml';
		} catch(e) {
			return null;
		}
	}
};

var evaluatePath = function(path, content) {
	var contentType = getContentType(content);

	switch (contentType) {
		case 'json':
			var contentJson = JSON.parse(content);
			return jsonPath.eval(contentJson, path);
		case 'xml':
			var xmlDocument = new dom().parseFromString(content);
			var node = select(xmlDocument, path)[0];
			if (node.nodeType === ATTRIBUTE) {
				return node.value;
			}

			return node.firstChild.data; // element or comment
		default:
			return null;
	}
};

var base64Encode = function(str) {
	return new Buffer(str).toString('base64');
};
<commit_msg>queryparameters should be an object - not an array<commit_after>/* jslint node: true */
'use strict';

var request = require('request');
var jsonPath = require('JSONPath');
var select = require('xpath.js');
var dom = require('xmldom').DOMParser;
var fs = require('fs');

var accessToken;
var globalVariables = {};

var ATTRIBUTE = 2;

function Apickli(scheme, domain, fixturesDirectory) {
	this.domain = scheme + '://' + domain;
	this.headers = {};
	this.httpResponse = {};
	this.requestBody = '';
	this.scenarioVariables = {};
	this.fixturesDirectory = (fixturesDirectory ? fixturesDirectory : '');
	this.queryParameters = {};
}

Apickli.prototype.addRequestHeader = function(name, value) {
	this.headers[name] = value;
};

Apickli.prototype.getResponseObject = function() {
	return this.httpResponse;
};

Apickli.prototype.setRequestBody = function(body) {
	this.requestBody = body;
};

Apickli.prototype.setQueryParameters = function(queryParameters) {
    var paramsObject = {};
    queryParameters.forEach(function(q) {
        paramsObject[q.parameter] = q.value;
    });

	this.queryParameters = paramsObject;
};

Apickli.prototype.pipeFileContentsToRequestBody = function(file, callback) {
	var self = this;
	fs.readFile(this.fixturesDirectory + file, 'utf8', function(err, data) {
		if (err) {
			callback(err);
		}

		self.setRequestBody(data);
		callback();
	});
};

Apickli.prototype.get = function(resource, callback) { // callback(error, response)
	var self = this;

	request.get({
		url: this.domain + resource,
		headers: this.headers,
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.post = function(resource, callback) { // callback(error, response)
	var self = this;
	request({
		url: this.domain + resource,
		headers: this.headers,
		body: this.requestBody,
		method: 'POST',
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.put = function(resource, callback) { // callback(error, response)
	var self = this;
	request({
		url: this.domain + resource,
		headers: this.headers,
		body: this.requestBody,
		method: 'PUT',
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.delete = function(resource, callback) { // callback(error, response)
	var self = this;
	request({
		url: this.domain + resource,
		headers: this.headers,
		body: this.requestBody,
		method: 'DELETE',
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.patch = function(resource, callback) { // callback(error, response)
	var self = this;

	request({
		url: this.domain + resource,
		headers: this.headers,
		body: this.requestBody,
		method: 'PATCH',
		followRedirect: false,
        qs: this.queryParameters
	},
	function(error, response) {
		if (error) {
			return callback(error);
		}

		self.httpResponse = response;
		callback(null, response);
	});
};

Apickli.prototype.addHttpBasicAuthorizationHeader = function(username, password) {
	var b64EncodedValue = base64Encode(username + ':' + password);
	this.addRequestHeader('Authorization', 'Basic ' + b64EncodedValue);
};

Apickli.prototype.assertResponseCode = function(responseCode) {
	var realResponseCode = this.getResponseObject().statusCode;
	return (realResponseCode == responseCode);
};

Apickli.prototype.assertResponseContainsHeader = function(header, callback) {
	if (this.getResponseObject().headers[header.toLowerCase()]) {
		return true;
	} else {
		return false;
	}
};

Apickli.prototype.assertHeaderValue = function (header, expression) {
	var realHeaderValue = this.getResponseObject().headers[header.toLowerCase()];
	var regex = new RegExp(expression);
	return (regex.test(realHeaderValue));
};

Apickli.prototype.assertPathInResponseBodyMatchesExpression = function(path, regexp) {
	var regExpObject = new RegExp(regexp);
	var evalValue = evaluatePath(path, this.getResponseObject().body);
	return (regExpObject.test(evalValue));
};

Apickli.prototype.assertResponseBodyContainsExpression = function(expression) {
	var regex = new RegExp(expression);
	return (regex.test(this.getResponseObject().body));
};

Apickli.prototype.assertResponseBodyContentType = function(contentType) {
	var realContentType = getContentType(this.getResponseObject().body);
	return (realContentType === contentType);
};

Apickli.prototype.evaluatePathInResponseBody = function(path) {
	return evaluatePath(path, this.getResponseObject().body);
};

Apickli.prototype.setAccessTokenFromResponseBodyPath = function(path) {
	accessToken = evaluatePath(path, this.getResponseObject().body);
};

Apickli.prototype.setBearerToken = function() {
	this.addRequestHeader('Authorization', 'Bearer ' + accessToken);
};

Apickli.prototype.storeValueOfHeaderInScenarioScope = function(header, variableName) {
	var value = this.getResponseObject().headers[header.toLowerCase()];
	this.scenarioVariables[variableName] = value;
};

Apickli.prototype.storeValueOfResponseBodyPathInScenarioScope = function(path, variableName) {
	var value = evaluatePath(path, this.getResponseObject().body);
	this.scenarioVariables[variableName] = value;
};

Apickli.prototype.assertScenarioVariableValue = function(variable, value) {
	return (String(this.scenarioVariables[variable]) === value);
};

Apickli.prototype.storeValueOfHeaderInGlobalScope = function(headerName, variableName) {
	var value = this.getResponseObject().headers[headerName.toLowerCase()];
	this.setGlobalVariable(variableName, value);
};

Apickli.prototype.storeValueOfResponseBodyPathInGlobalScope = function(path, variableName) {
	var value = evaluatePath(path, this.getResponseObject().body);
	this.setGlobalVariable(variableName, value);
};

Apickli.prototype.setGlobalVariable = function(name, value) {
	globalVariables[name] = value;
};

Apickli.prototype.getGlobalVariable = function(name) {
	return globalVariables[name];
};

exports.Apickli = Apickli;

var getContentType = function(content) {
	try{
		JSON.parse(content);
		return 'json';
	} catch(e) {
		try{
			new dom().parseFromString(content);
			return 'xml';
		} catch(e) {
			return null;
		}
	}
};

var evaluatePath = function(path, content) {
	var contentType = getContentType(content);

	switch (contentType) {
		case 'json':
			var contentJson = JSON.parse(content);
			return jsonPath.eval(contentJson, path);
		case 'xml':
			var xmlDocument = new dom().parseFromString(content);
			var node = select(xmlDocument, path)[0];
			if (node.nodeType === ATTRIBUTE) {
				return node.value;
			}

			return node.firstChild.data; // element or comment
		default:
			return null;
	}
};

var base64Encode = function(str) {
	return new Buffer(str).toString('base64');
};
<|endoftext|>


<commit_before>(function(module) {

    "use strict";

    var Inigo = require("__buttercup/classes/InigoGenerator.js"),
        commandTools = require("__buttercup/tools/command.js"),
        searching = require("__buttercup/tools/searching-raw.js"),
        entry = require("__buttercup/tools/entry.js");

    var VALID_COMMAND_EXP =             /^[a-z]{3}[ ].+$/;

    var commandClasses = {
        cen: require("__buttercup/classes/commands/command.cen.js"),
        cgr: require("__buttercup/classes/commands/command.cgr.js"),
        cmm: require("__buttercup/classes/commands/command.cmm.js"),
        dea: require("__buttercup/classes/commands/command.dea.js"),
        dem: require("__buttercup/classes/commands/command.dem.js"),
        den: require("__buttercup/classes/commands/command.den.js"),
        dga: require("__buttercup/classes/commands/command.dga.js"),
        dgr: require("__buttercup/classes/commands/command.dgr.js"),
        fmt: require("__buttercup/classes/commands/command.fmt.js"),
        men: require("__buttercup/classes/commands/command.men.js"),
        mgr: require("__buttercup/classes/commands/command.mgr.js"),
        pad: require("__buttercup/classes/commands/command.pad.js"),
        sea: require("__buttercup/classes/commands/command.sea.js"),
        sem: require("__buttercup/classes/commands/command.sem.js"),
        sep: require("__buttercup/classes/commands/command.sep.js"),
        sga: require("__buttercup/classes/commands/command.sga.js"),
        tgr: require("__buttercup/classes/commands/command.tgr.js")
    };

    /**
     * Westley. Archive object dataset and history manager. Handles parsing and
     * revenge for the princess.
     * @class Westley
     */
    var Westley = function() {
        this.clear();
    };

    /**
     * Clear the dataset and history
     * @returns {Westley} Returns self
     * @memberof Westley
     */
    Westley.prototype.clear = function() {
        this._dataset = {};
        this._history = [];
        this._cachedCommands = {};
        return this;
    };

    /**
     * Execute a command - stored in history and modifies the dataset
     * @param {String} command The command to execute
     * @returns {Westley} Returns self
     * @memberof Westley
     */
    Westley.prototype.execute = function(command) {
        if (!VALID_COMMAND_EXP.test(command)) {
            throw new Error("Invalid command");
        }
        var commandComponents = commandTools.extractCommandComponents(command),
            commandKey = commandComponents.shift();

        var commandObject = this._getCommandForKey(commandKey);

        this._history.push(command);
        commandObject.execute.apply(commandObject, [this._dataset].concat(commandComponents));
        return this;
    };

    /**
     * Gets a command by its key from the cache with its dependencies injected
     * @param {String} commandKey The key of the command
     * @returns {Command} Returns the command
     * @memberof Westley
     */
    Westley.prototype._getCommandForKey = function(commandKey) {
        // If the command doesn't exist in the cache
        if (this._cachedCommands[commandKey] === undefined) {
            // Get the command object and inject its dependencies
            var requirement = new (commandClasses[commandKey])();

            if (requirement.injectSearching !== undefined) {
                requirement.injectSearching(searching);
            }

            if (requirement.injectEntry !== undefined) {
                requirement.injectEntry(entry);
            }

            if (requirement.injectCommentCallback !== undefined) {
                requirement.injectCommentCallback(function (comment) {
                    console.log(" COMMENT -> " + comment);
                });
            }

            // Store it in the cache
            this._cachedCommands[commandKey] = requirement;
        }

        return this._cachedCommands[commandKey];
    };

    /**
     * Insert a padding in the archive (used for delta tracking)
     * @returns {Westley} Returns self
     * @memberof Westley
     */
    Westley.prototype.pad = function() {
        this.execute(Inigo.generatePaddingCommand());
        return this;
    };

    /**
     * Get the core dataset
     * @returns {Object}
     * @memberof Westley
     */
    Westley.prototype.getDataset = function() {
        return this._dataset;
    };

    /**
     * Get the history (deltas)
     * @returns {String[]}
     * @memberof Westley
     */
    Westley.prototype.getHistory = function() {
        return this._history;
    };

    module.exports = Westley;

})(module);
<commit_msg>Comment out console log<commit_after>(function(module) {

    "use strict";

    var Inigo = require("__buttercup/classes/InigoGenerator.js"),
        commandTools = require("__buttercup/tools/command.js"),
        searching = require("__buttercup/tools/searching-raw.js"),
        entry = require("__buttercup/tools/entry.js");

    var VALID_COMMAND_EXP =             /^[a-z]{3}[ ].+$/;

    var commandClasses = {
        cen: require("__buttercup/classes/commands/command.cen.js"),
        cgr: require("__buttercup/classes/commands/command.cgr.js"),
        cmm: require("__buttercup/classes/commands/command.cmm.js"),
        dea: require("__buttercup/classes/commands/command.dea.js"),
        dem: require("__buttercup/classes/commands/command.dem.js"),
        den: require("__buttercup/classes/commands/command.den.js"),
        dga: require("__buttercup/classes/commands/command.dga.js"),
        dgr: require("__buttercup/classes/commands/command.dgr.js"),
        fmt: require("__buttercup/classes/commands/command.fmt.js"),
        men: require("__buttercup/classes/commands/command.men.js"),
        mgr: require("__buttercup/classes/commands/command.mgr.js"),
        pad: require("__buttercup/classes/commands/command.pad.js"),
        sea: require("__buttercup/classes/commands/command.sea.js"),
        sem: require("__buttercup/classes/commands/command.sem.js"),
        sep: require("__buttercup/classes/commands/command.sep.js"),
        sga: require("__buttercup/classes/commands/command.sga.js"),
        tgr: require("__buttercup/classes/commands/command.tgr.js")
    };

    /**
     * Westley. Archive object dataset and history manager. Handles parsing and
     * revenge for the princess.
     * @class Westley
     */
    var Westley = function() {
        this.clear();
    };

    /**
     * Clear the dataset and history
     * @returns {Westley} Returns self
     * @memberof Westley
     */
    Westley.prototype.clear = function() {
        this._dataset = {};
        this._history = [];
        this._cachedCommands = {};
        return this;
    };

    /**
     * Execute a command - stored in history and modifies the dataset
     * @param {String} command The command to execute
     * @returns {Westley} Returns self
     * @memberof Westley
     */
    Westley.prototype.execute = function(command) {
        if (!VALID_COMMAND_EXP.test(command)) {
            throw new Error("Invalid command");
        }
        var commandComponents = commandTools.extractCommandComponents(command),
            commandKey = commandComponents.shift();

        var commandObject = this._getCommandForKey(commandKey);

        this._history.push(command);
        commandObject.execute.apply(commandObject, [this._dataset].concat(commandComponents));
        return this;
    };

    /**
     * Gets a command by its key from the cache with its dependencies injected
     * @param {String} commandKey The key of the command
     * @returns {Command} Returns the command
     * @memberof Westley
     */
    Westley.prototype._getCommandForKey = function(commandKey) {
        // If the command doesn't exist in the cache
        if (this._cachedCommands[commandKey] === undefined) {
            // Get the command object and inject its dependencies
            var requirement = new (commandClasses[commandKey])();

            if (requirement.injectSearching !== undefined) {
                requirement.injectSearching(searching);
            }

            if (requirement.injectEntry !== undefined) {
                requirement.injectEntry(entry);
            }

            if (requirement.injectCommentCallback !== undefined) {
                requirement.injectCommentCallback(function (comment) {
                    //console.log(" COMMENT -> " + comment);
                });
            }

            // Store it in the cache
            this._cachedCommands[commandKey] = requirement;
        }

        return this._cachedCommands[commandKey];
    };

    /**
     * Insert a padding in the archive (used for delta tracking)
     * @returns {Westley} Returns self
     * @memberof Westley
     */
    Westley.prototype.pad = function() {
        this.execute(Inigo.generatePaddingCommand());
        return this;
    };

    /**
     * Get the core dataset
     * @returns {Object}
     * @memberof Westley
     */
    Westley.prototype.getDataset = function() {
        return this._dataset;
    };

    /**
     * Get the history (deltas)
     * @returns {String[]}
     * @memberof Westley
     */
    Westley.prototype.getHistory = function() {
        return this._history;
    };

    module.exports = Westley;

})(module);
<|endoftext|>


<commit_before>/************************************************
 * jQuery iOS App Switcher
 *  - by Ryan Scherf
 *
 * Convert your site's links to URL
 * schemes to deeplink to iOS apps.
 ************************************************/

(function($) {
  $.fn.switcher = function(options) {

  var settings = $.extend({
    additionalSchemas : [],
    debug             : false,
    iOS               : /(iPad|iPhone|iPod)/g.test(navigator.userAgent)
  }, options);

  if(settings.iOS || settings.debug)
  {
    // Define the native apps to deeplink
    var services = [
      {
        pattern : /(facebook)/g,
        scheme  : function(username) {

          var facebookId = "";

          if(isNaN(parseInt(username)))
          {
            $.ajax({
              url       : "http://graph.facebook.com/" + username,
              type      : "get",
              dataType  : "json",
              async     : false,
            }).done(function(response) {
              facebookId = response.id;
            });
          }
          else
          {
            facebookId = username;
          }

          return "fb://profile/" + facebookId;
        }
      },
      {
        pattern : /(linkedin)/g,
        scheme  : function(username) {
          return "linkedin://#profile/" + username
        }
      },
      {
        pattern : /(instagram)/g,
        scheme  : function(username) {
          return "instagram://user?username=" + username
        }
      },
      {
        pattern : /(quirky)/g,
        scheme  : function(username) {
          return "quirky:///" + username
        }
      },
      {
        pattern : /(twitter)/g,
        scheme  : function(username) {
          return "twitter://user?screen_name=" + username
        }
      }
    ];

    // Add on any user defined schemas
    services = services.concat(settings.additionalSchemas);

    // Iterate through the set
    this.each(function() {

      var $this  = $(this),
      href       = $(this).attr("href"),
      identifier = href.split(".com/");

      if($this.data("username"))
        username = $this.data("username");
      else if(identifier.length > 1)
        username = identifier[1];
      else
        username = "notfound";

      $(services).each(function(i) {
        if(services[i].pattern.test(href))
        {
          $this.attr("href", services[i].scheme(username));

          // If visitor doesn't have the app, open the link
          $this.bind("click", function() {
            setTimeout(function() {
              window.location = href;
            }, 300);
          });

          return false;
        }
      });

    });

  }

  return this;

  };
}(jQuery));
<commit_msg>Fixes #3 where Safari still redirects on inactive tab after app switching<commit_after>/************************************************
 * jQuery iOS App Switcher
 *  - by Ryan Scherf
 *
 * Convert your site's links to URL
 * schemes to deeplink to iOS apps.
 ************************************************/

(function($) {
  $.fn.switcher = function(options) {

  // For prevention of Safari executing redirect if app is found
  window.hasHidden = false;
  $(window).bind("blur pagehide",  function() { window.hasHidden = true; });

  var settings = $.extend({
    additionalSchemas : [],
    debug             : false,
    iOS               : /(iPad|iPhone|iPod)/g.test(navigator.userAgent)
  }, options);

  if(settings.iOS || settings.debug)
  {
    // Define the native apps to deeplink
    var services = [
      {
        pattern : /(facebook)/g,
        scheme  : function(username) {

          var facebookId = "";

          if(isNaN(parseInt(username)))
          {
            $.ajax({
              url       : "http://graph.facebook.com/" + username,
              type      : "get",
              dataType  : "json",
              async     : false,
            }).done(function(response) {
              facebookId = response.id;
            });
          }
          else
          {
            facebookId = username;
          }

          return "fb://profile/" + facebookId;
        }
      },
      {
        pattern : /(linkedin)/g,
        scheme  : function(username) {
          return "linkedin://#profile/" + username
        }
      },
      {
        pattern : /(instagram)/g,
        scheme  : function(username) {
          return "instagram://user?username=" + username
        }
      },
      {
        pattern : /(quirky)/g,
        scheme  : function(username) {
          return "quirky:///" + username
        }
      },
      {
        pattern : /(twitter)/g,
        scheme  : function(username) {
          return "twitter://user?screen_name=" + username
        }
      }
    ];

    // Add on any user defined schemas
    services = services.concat(settings.additionalSchemas);

    // Iterate through the set
    this.each(function() {

      var $this  = $(this),
      href       = $(this).attr("href"),
      identifier = href.split(".com/");

      if($this.data("username"))
        username = $this.data("username");
      else if(identifier.length > 1)
        username = identifier[1];
      else
        username = "notfound";

      $(services).each(function(i) {
        if(services[i].pattern.test(href))
        {
          $this.attr("href", services[i].scheme(username));

          // If visitor doesn't have the app, open the link
          $this.bind("click", function() {
            setTimeout(function() {
              if(!window.hasHidden) {
                window.location  = href;
              } else {
                window.hasHidden = false;
              }
            }, 1000);
          });

          return false;
        }
      });

    });

  }

  return this;

  };
}(jQuery));
<|endoftext|>


<commit_before>var _ = require('lodash');
var FixtureBuilder = require('./FixtureBuilder');
var xmlify = require('./xmlify');

var todoLists = require('./fixtures/todoLists.json');
var todoListItems = require('./fixtures/todoListItems.json');

var fixtureBuilder = new FixtureBuilder("todo-list", "todo-lists");

var data = {};

_.forEach(todoLists, function (todoList) {
    "use strict";
    data[todoList.id] = _.clone(todoList);
    var itemsForThisList = _(todoListItems)
        .filter(function (item) {
            return item['todo-list-id'] === todoList.id;
        }).value();
    data[todoList.id]['todo-items'] = itemsForThisList;
});

console.log(JSON.stringify(data, null, 4));

module.exports = fixtureBuilder
    .setData(data)
    .addEndpoint({
        matcher: function (url) {
            "use strict";
            return url.match(new RegExp("/todo_lists.xml\\?responsible_party=(\\d*)"));
        },
        handler: function (url) {
            "use strict";
            var found = this.matcher(url);
            var partyId = found[1];
            var response = {};

            _.forEach(this.data, function (list) {
                var matchingItems = _.filter(list['todo-items'], function (item) {
                    if (_.isEmpty(partyId)) {
                        return _.isUndefined(item["responsible-party-id"]);
                    } else {
                        return item["responsible-party-id"] === +partyId;
                    }
                });

                if (_.size(matchingItems) > 0) {
                    response[list.id] = _.clone(list);
                    response[list.id]['todo-items'] = matchingItems;
                    response[list.id]['completed'] = _.all(list['todo-items'], function (item) { return item.completed; });
                }
            });

            if(_.size(response) > 0) {
                return _.reduce(response, function (response, companyXml) {
                        return response + xmlify(this.singular, companyXml);
                    }, "<" + this.plural + " type=\"array\">", this) + "</" + this.plural + ">";
            }
        }
    })
    .addEndpoint({
        matcher: function (url) {
            "use strict";
            return url.match(new RegExp("/projects/(\\d*)/todo_lists.xml?filter=(.*)"));
        },
        handler: function (url) {
            "use strict";
            var found = this.matcher(url);
            var partyId = found[1];
            var response = {};

            _.forEach(this.data, function (list) {
                var matchingItems = _.filter(list['todo-items'], function (item) {
                    if (_.isEmpty(partyId)) {
                        return _.isUndefined(item["responsible-party-id"]);
                    } else {
                        return item["responsible-party-id"] === +partyId;
                    }
                });

                if (_.size(matchingItems) > 0) {
                    response[list.id] = _.clone(list);
                    response[list.id]['todo-items'] = matchingItems;
                    response[list.id]['completed'] = _.all(list['todo-items'], function (item) { return item.completed; });
                }
            });

            if(_.size(response) > 0) {
                return _.reduce(response, function (response, companyXml) {
                        return response + xmlify(this.singular, companyXml);
                    }, "<" + this.plural + " type=\"array\">", this) + "</" + this.plural + ">";
            }
        }
    })
    .build();<commit_msg>Added method to get lists associated with a project<commit_after>var _ = require('lodash');
var FixtureBuilder = require('./FixtureBuilder');
var xmlify = require('./xmlify');

var todoLists = require('./fixtures/todoLists.json');
var todoListItems = require('./fixtures/todoListItems.json');

var fixtureBuilder = new FixtureBuilder("todo-list", "todo-lists");

var data = {};

_.forEach(todoLists, function (todoList) {
    "use strict";
    var clonedList = _.clone(todoList);
    data[todoList.id] = clonedList;
    var itemsForThisList = _(todoListItems)
        .filter(function (item) {
            return item['todo-list-id'] === todoList.id;
        }).value();
    clonedList['todo-items'] = itemsForThisList;
    clonedList.completed = _.all(todoListItems, function(item) { return item.completed });
});

console.log(JSON.stringify(data, null, 4));

module.exports = fixtureBuilder
    .setData(data)
    .addEndpoint({
        matcher: function (url) {
            "use strict";
            return url.match(new RegExp("/todo_lists.xml\\?responsible_party=(\\d*)"));
        },
        handler: function (url) {
            "use strict";
            var found = this.matcher(url);
            var partyId = found[1];
            var response = {};

            _.forEach(this.data, function (list) {
                var matchingItems = _.filter(list['todo-items'], function (item) {
                    if (_.isEmpty(partyId)) {
                        return _.isUndefined(item["responsible-party-id"]);
                    } else {
                        return item["responsible-party-id"] === +partyId;
                    }
                });

                if (_.size(matchingItems) > 0) {
                    response[list.id] = _.clone(list);
                    response[list.id]['todo-items'] = matchingItems;
                    response[list.id]['completed'] = _.all(list['todo-items'], function (item) { return item.completed; });
                }
            });

            if(_.size(response) > 0) {
                return _.reduce(response, function (response, companyXml) {
                        return response + xmlify(this.singular, companyXml);
                    }, "<" + this.plural + " type=\"array\">", this) + "</" + this.plural + ">";
            }
        }
    })
    .addEndpoint({
        matcher: function (url) {
            "use strict";
            return url.match(new RegExp("/projects/(\\d*)/todo_lists.xml(?:\\?filter=(.*)){0,1}"));
        },
        handler: function (url) {
            "use strict";
            var found = this.matcher(url);
            var projectId = found[1];
            var response =  _.filter(this.data, function (list) {
                return list['project-id'] === + projectId;
            });

            if(_.size(response) > 0) {
                return _.reduce(response, function (response, companyXml) {
                        return response + xmlify(this.singular, companyXml);
                    }, "<" + this.plural + " type=\"array\">", this) + "</" + this.plural + ">";
            }
        }
    })
    .build();<|endoftext|>


<commit_before>(function() {
  var $ = jQuery.noConflict();
  var API_SUBDOMAIN = 'api';
  var API = {
    REGISTER: '/users/register'
  };
  var STORAGE = {
    RALLY_NAME_KEY: 'rally-name',
    SAVED_CONTACTS_KEY: 'saved-contacts'
  }

  // form setup (domain) & hooks
  function setupForm(selector) {
    var form = $(selector);
    if (form.length === 0) { return; }

    // Contact preference
    form.find('input[name=contact_preference]:radio').click(function () {
      contactChangeHandler(form);
    });
    contactChangeHandler(form);

    // Form handler
    form.attr('action', apiServer() + API.REGISTER);
    form.submit(submitHandler);
  }

  function contactChangeHandler(form) {
    var preference = form.find('input[name=contact_preference]:checked').val();
    form.find('input[name=phone_number]').attr('required', (preference === 'sms' || preference === 'both'));
  }

  function submitHandler(event) {
    form = $(event.target);
    event.preventDefault();

    if (!isValid(form)) {
      showFormErrors(form);
      return;
    }

    // data-offline on form to track
    if (isOffline(form)) {
      // save to localStorage
      showFormSuccess(form);
      return;
    }

    // Fall through allows form to send via AJAX
    submitFormAjax(form);
  }

  function submitFormAjax(form) {
    lockFormButton(form);
    clearFormMessage(form);

    $.ajax({
      type: "POST",
      url: form.attr('action'),
      data: form.serialize()
    })
    .then(function (data) { showFormSuccess(form); })
    .catch(function (error) { showAjaxErrors(form, error); })
    .then(function () { unlockFormButton(form); });
  }

  function apiServer() {
    var location = window.location;
    var baseDomain = location.host.replace('www.', '');
    return location.protocol + '//' + API_SUBDOMAIN + '.' + baseDomain;
  }

  // Form validation
  function isValid(form) {
    // TODO
    return true;
  }

  function lockFormButton(form) {
    var submit = $(form).find('input[type="submit"]');
    submit.attr('disabled', true);
  }

  function unlockFormButton(form) {
    var submit = $(form).find('input[type="submit"]');
    submit.attr('disabled', false);
  }

  function showFormSuccess(form) {
    // TODO
    $(form)[0].reset();
    setFormMessage(form, 'All set, we received your information!  Look for your first text/email from us soon.');
  }

  function showFormErrors(form) {
    // TODO
  }

  function showAjaxErrors(form, erorr) {
    setFormMessage(form, 'Oops! Something went wrong, please check the form and try again.', true);
  }

  function clearFormMessage(form) {
    var box = $(form).find('.form-message');
    box.text('').addClass('hide');
  }

  function setFormMessage(form, message, isError) {
    var box = $(form).find('.form-message');
    if (isError) {
      box.removeClass('text-success').addClass('text-danger');
    } else {
      box.removeClass('text-danger').addClass('text-success');
    }

    box.text(message).removeClass('hide');

    if (!isError) {
      setTimeout(function () {
        box.slideUp("slow", function () {
          box.addClass('hide').show();
        });
      }, 3000);
    }
  }

  // offline mode and stats
  function setupStatus(selector) {
    var panel = $(selector);
    var form = $('#signup');
    if (panel.length === 0) { return; }

    // Edit rally name
    $('#edit-rally-name').click(function (event) {
      var rallyName = $('#rally-name-set');
      var rallyForm = $('#rally-name-form');

      rallyName.addClass('hide');
      rallyForm.find('input').val("").on('keyup', function (event) {
        if (event.keyCode === 13) {
          setRallyName(event.target.value);

          rallyForm.addClass('hide');
          rallyName.removeClass('hide');
        }
      });
      rallyForm.removeClass('hide');
    });
    setRallyName(localStorage.getItem(STORAGE.RALLY_NAME_KEY));

    // Statistics
    updateStoredCount();
    updateTodayCount();

    // Online and offline control
    $('#go-offline').click(function () { goOffline(form); });
    $('#go-online').click(function () { goOnline(form); });
    updateOnlineStatus();

    // Auto detect offline and auto-switch
    window.addEventListener('online',  updateOnlineStatus);
    window.addEventListener('offline', updateOnlineStatus);
  }

  function updateOnlineStatus() {
    var form = $('#signup');
    if (window.navigator.onLine) {
      if (form.data('offline') === undefined) {
        // We haven't set this yet, let's do it now
        // We do not force online in case the user manually disabled it.
        goOnline(form);
      }
      $('#go-online').attr('disabled', false);
      $('#go-online-disabled').addClass('hide');
    } else {
      goOffline(form);
      $('#go-online').attr('disabled', true);
      $('#go-online-disabled').removeClass('hide');
    }
  }

  function isOffline(form) {
    return !!form.data('offline');
  }

  function goOffline(form) {
    form.data('offline', true);

    $('#status-online').addClass('hide');
    $('#status-offline').removeClass('hide');
  }

  function goOnline(form) {
    form.data('offline', false);

    $('#status-online').removeClass('hide');
    $('#status-offline').addClass('hide');
  }

  function setRallyName(name) {
    if (!name || name.trim() === "") {
      name = "Rally Name";
    }

    $('#rally-name').text(name);
    localStorage.setItem(STORAGE.RALLY_NAME_KEY, name);
  }

  function updateStoredCount() {
    var contactCount = (localStorage.getItem(STORAGE.SAVED_CONTACTS_KEY) || []).length;
    $('#rally-pending').text(contactCount);
  }

  function updateTodayCount() {
    var contacts = localStorage.getItem(STORAGE.SAVED_CONTACTS_KEY) || [];
    var todayCount = contacts.filter(function (contact) {
      // return if contact saved today
      // TODO
      return true;
    }).length;

    $('#rally-num-today').text(todayCount);
  }

  function sendPendingContacts(formTemplate) {
    // Use the passed form as a template to clone, fill data and send
    // On successful send, clear entry from localStorage
    // On error, add to errors store

    // TODO
  }

  function start() {
    setupForm('#signup');
    setupStatus('#status');
  }
  start();

})();
<commit_msg>email is only required when the contact preference is email<commit_after>(function() {
  var $ = jQuery.noConflict();
  var API_SUBDOMAIN = 'api';
  var API = {
    REGISTER: '/users/register'
  };
  var STORAGE = {
    RALLY_NAME_KEY: 'rally-name',
    SAVED_CONTACTS_KEY: 'saved-contacts'
  }

  // form setup (domain) & hooks
  function setupForm(selector) {
    var form = $(selector);
    if (form.length === 0) { return; }

    // Contact preference
    form.find('input[name=contact_preference]:radio').click(function () {
      contactChangeHandler(form);
    });
    contactChangeHandler(form);

    // Form handler
    form.attr('action', apiServer() + API.REGISTER);
    form.submit(submitHandler);
  }

  function contactChangeHandler(form) {
    var preference = form.find('input[name=contact_preference]:checked').val();
    form.find('input[name=email_address]').attr('required', (preference === 'email' || preference === 'both'));
    form.find('input[name=phone_number]').attr('required', (preference === 'sms' || preference === 'both'));
  }

  function submitHandler(event) {
    form = $(event.target);
    event.preventDefault();

    if (!isValid(form)) {
      showFormErrors(form);
      return;
    }

    // data-offline on form to track
    if (isOffline(form)) {
      // save to localStorage
      showFormSuccess(form);
      return;
    }

    // Fall through allows form to send via AJAX
    submitFormAjax(form);
  }

  function submitFormAjax(form) {
    lockFormButton(form);
    clearFormMessage(form);

    $.ajax({
      type: "POST",
      url: form.attr('action'),
      data: form.serialize()
    })
    .then(function (data) { showFormSuccess(form); })
    .catch(function (error) { showAjaxErrors(form, error); })
    .then(function () { unlockFormButton(form); });
  }

  function apiServer() {
    var location = window.location;
    var baseDomain = location.host.replace('www.', '');
    return location.protocol + '//' + API_SUBDOMAIN + '.' + baseDomain;
  }

  // Form validation
  function isValid(form) {
    // TODO
    return true;
  }

  function lockFormButton(form) {
    var submit = $(form).find('input[type="submit"]');
    submit.attr('disabled', true);
  }

  function unlockFormButton(form) {
    var submit = $(form).find('input[type="submit"]');
    submit.attr('disabled', false);
  }

  function showFormSuccess(form) {
    // TODO
    $(form)[0].reset();
    setFormMessage(form, 'All set, we received your information!  Look for your first text/email from us soon.');
  }

  function showFormErrors(form) {
    // TODO
  }

  function showAjaxErrors(form, erorr) {
    setFormMessage(form, 'Oops! Something went wrong, please check the form and try again.', true);
  }

  function clearFormMessage(form) {
    var box = $(form).find('.form-message');
    box.text('').addClass('hide');
  }

  function setFormMessage(form, message, isError) {
    var box = $(form).find('.form-message');
    if (isError) {
      box.removeClass('text-success').addClass('text-danger');
    } else {
      box.removeClass('text-danger').addClass('text-success');
    }

    box.text(message).removeClass('hide');

    if (!isError) {
      setTimeout(function () {
        box.slideUp("slow", function () {
          box.addClass('hide').show();
        });
      }, 3000);
    }
  }

  // offline mode and stats
  function setupStatus(selector) {
    var panel = $(selector);
    var form = $('#signup');
    if (panel.length === 0) { return; }

    // Edit rally name
    $('#edit-rally-name').click(function (event) {
      var rallyName = $('#rally-name-set');
      var rallyForm = $('#rally-name-form');

      rallyName.addClass('hide');
      rallyForm.find('input').val("").on('keyup', function (event) {
        if (event.keyCode === 13) {
          setRallyName(event.target.value);

          rallyForm.addClass('hide');
          rallyName.removeClass('hide');
        }
      });
      rallyForm.removeClass('hide');
    });
    setRallyName(localStorage.getItem(STORAGE.RALLY_NAME_KEY));

    // Statistics
    updateStoredCount();
    updateTodayCount();

    // Online and offline control
    $('#go-offline').click(function () { goOffline(form); });
    $('#go-online').click(function () { goOnline(form); });
    updateOnlineStatus();

    // Auto detect offline and auto-switch
    window.addEventListener('online',  updateOnlineStatus);
    window.addEventListener('offline', updateOnlineStatus);
  }

  function updateOnlineStatus() {
    var form = $('#signup');
    if (window.navigator.onLine) {
      if (form.data('offline') === undefined) {
        // We haven't set this yet, let's do it now
        // We do not force online in case the user manually disabled it.
        goOnline(form);
      }
      $('#go-online').attr('disabled', false);
      $('#go-online-disabled').addClass('hide');
    } else {
      goOffline(form);
      $('#go-online').attr('disabled', true);
      $('#go-online-disabled').removeClass('hide');
    }
  }

  function isOffline(form) {
    return !!form.data('offline');
  }

  function goOffline(form) {
    form.data('offline', true);

    $('#status-online').addClass('hide');
    $('#status-offline').removeClass('hide');
  }

  function goOnline(form) {
    form.data('offline', false);

    $('#status-online').removeClass('hide');
    $('#status-offline').addClass('hide');
  }

  function setRallyName(name) {
    if (!name || name.trim() === "") {
      name = "Rally Name";
    }

    $('#rally-name').text(name);
    localStorage.setItem(STORAGE.RALLY_NAME_KEY, name);
  }

  function updateStoredCount() {
    var contactCount = (localStorage.getItem(STORAGE.SAVED_CONTACTS_KEY) || []).length;
    $('#rally-pending').text(contactCount);
  }

  function updateTodayCount() {
    var contacts = localStorage.getItem(STORAGE.SAVED_CONTACTS_KEY) || [];
    var todayCount = contacts.filter(function (contact) {
      // return if contact saved today
      // TODO
      return true;
    }).length;

    $('#rally-num-today').text(todayCount);
  }

  function sendPendingContacts(formTemplate) {
    // Use the passed form as a template to clone, fill data and send
    // On successful send, clear entry from localStorage
    // On error, add to errors store

    // TODO
  }

  function start() {
    setupForm('#signup');
    setupStatus('#status');
  }
  start();

})();
<|endoftext|>


<commit_before>/**
 * Created by wander on 9/15/2016.
 */
var Neuron = synaptic.Neuron,
    Layer = synaptic.Layer,
    Network = synaptic.Network;

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0x221f36, 1 );
document.body.appendChild( renderer.domElement );

var loader = new THREE.TextureLoader();
var clock = new THREE.Clock();

function Cube (xSize,ySize,zSize,color) {
    this.geometry = new THREE.BoxGeometry(xSize, ySize, zSize);
    this.material = new THREE.MeshLambertMaterial({color: color});
    return new THREE.Mesh(this.geometry, this.material);
}

function Perceptron(input, hidden, output)
{
    // create the layers
    var inputLayer = new Layer(input);
    var hiddenLayer = new Layer(hidden);
    var outputLayer = new Layer(output);

    // connect the layers
    inputLayer.project(hiddenLayer);
    hiddenLayer.project(outputLayer);

    // set the layers
    this.set({
        input: inputLayer,
        hidden: [hiddenLayer],
        output: outputLayer
    });

    //var standalone = this.standalone();
}

// extend the prototype chain
Perceptron.prototype = new Network();
Perceptron.prototype.constructor = Perceptron;

class Car {
    constructor(mesh,brain) {
        this.mesh = mesh;
        this.brain = brain ? brain : new Perceptron(2,2,2);
        this.velocity = 1;
        //You want to log out the object file so we can explore it, just once per session though.
        //TODO: remove this when no longer needed.
       // console.log(this.brain.layers);
    }

    Destroy() {
        //TODO: Would be nice to be able to remove the neural network too.
        scene.remove(this.mesh);
    }

    Create() {
        this.mesh.position.set(0,0.3,-2);
        scene.add(this.mesh);
    }
}

var collisionList = [];

var seed = function() {
    var car = new Car(Cube(0.5,0.25,1,0x47475b));
    car.Create();
    //collisionList.push(car.mesh);
    return car
};

var fitness = function(entity) {
    var moral = 0;
    moral = entity.mesh.position.z;
    return moral;
};

var copy = function(entity)
{
    var newEntity = new Car(Cube(0.5,0.25,1,0x47475b),entity.brain.clone());
    newEntity.brain = jQuery.extend(true, {}, entity.brain);
    return newEntity;
}

var crossoverRandom = function(father,mother)
{
    var son = new Car(Cube(0.5,0.25,1,0x47475b));
    var daughter = new Car(Cube(0.5,0.25,1,0x47475b));

    var dadNeurons = father.brain.neurons();
    var dadWeights = [];
    for(let s in dadNeurons){
        for(let i in dadNeurons[s].neuron.connections.inputs){
            var input = dadNeurons[s].neuron.connections.inputs[i];
            dadWeights.push(input);
        }
    }

    var momNeurons = mother.brain.neurons();
    var momWeights = [];
    for(let s in momNeurons){
        for(let i in momNeurons[s].neuron.connections.inputs){
            var input = momNeurons[s].neuron.connections.inputs[i];
            momWeights.push(input);
        }
    }

    var splice = function (dad,mom) {
        var slice = Math.random().toFixed(2);
        var son = [];
        var daughter = [];

        for(let i = 0; i <= dad.length;i++){
            var len = dad.length * slice;

            son.push(i <= len ? dad[i] : mom[i]);
            daughter.push(i <= len ? mom[i] : dad[i]);
        }

        return [son,daughter];
    }

    var newWeights = splice(dadWeights,momWeights);

    var sonNeurons = son.brain.neurons();
    for(let s in sonNeurons){
        for(let i in sonNeurons[s].neuron.connections.inputs){
            son.brain.neurons()[s].neuron.connections.inputs[i].weight = newWeights[0][s].weight;
        }
    }

    var daughterNeurons = daughter.brain.neurons();
    for(let s in daughterNeurons){
        for(let i in daughterNeurons[s].neuron.connections.inputs){
            daughter.brain.neurons()[s].neuron.connections.inputs[i].weight = newWeights[1][s].weight;
        }
    }

    return [son,daughter];
}

var mutate = function (oldEntity) {
    var entity = oldEntity;
    var randomEntity = new Car(Cube(0.5,0.25,1,0x47475b));

    var inputConn = entity.brain.layers.input.connectedTo;
    var randomInputConn = randomEntity.brain.layers.input.connectedTo;

    for(let idx = 0; idx < Object.keys(inputConn[0].connections).length; idx++) {
        inputConn[0].connections[Object.keys(inputConn[0].connections)[idx]].weight = randomInputConn[0].connections[Object.keys(randomInputConn[0].connections)[idx]].weight;
    }

    var hiddenLayerAmt = entity.brain.layers.hidden.length;
    for(let depth = 0; depth < hiddenLayerAmt; depth++) {
        var hiddenConn = entity.brain.layers.hidden[depth].connectedTo;
        var randomHiddenConn = randomEntity.brain.layers.hidden[depth].connectedTo;

        for(let idx = 0; idx < Object.keys(inputConn[0].connections).length; idx++) {
            hiddenConn[0].connections[Object.keys(hiddenConn[0].connections)[idx]].weight = randomHiddenConn[0].connections[Object.keys(randomHiddenConn[0].connections)[idx]].weight;
        }
    }

    var inputNeurons = entity.brain.layers.input.list;
    var randomInputNeurons = entity.brain.layers.input.list;

    for(let idx = 0; idx < inputNeurons.length; idx++) {
        inputNeurons[0].bias = randomInputNeurons[0].bias;
    }

    for(let depth = 0; depth < hiddenLayerAmt; depth++) {
        var hiddenNeurons = entity.brain.layers.hidden[depth].list;
        var randomHiddenNeurons = entity.brain.layers.hidden[depth].list;

        for(let idx = 0; idx < inputNeurons.length; idx++) {
            hiddenNeurons[0].bias = randomHiddenNeurons[0].bias;
        }
    }
    return entity;
}

var pool = new Genegen(seed,fitness,copy,crossoverRandom,mutate);

pool.Start();

var floor = new Cube(6,0.25,11,0x0078dc);
floor.position.set(0,0,0);
var left = new Cube(0.5,0.5,10,0x47475b);
left.position.set(-2.75,0.3,0);
collisionList.push(left);
var right = new Cube(0.5,0.5,10,0x47475b);
right.position.set(2.75,0.3,0);
collisionList.push(right);
var front = new Cube(6,0.5,0.5,0x47475b);
front.position.set(0,0.3,-5.25);
collisionList.push(front);
var back = new Cube(6,0.5,0.5,0x47475b);
back.position.set(0,0.3,5.25);
collisionList.push(back);
table = new THREE.Group();
table.add(floor);
table.add(left);
table.add(right);
table.add(front);
table.add(back);

scene.add( table );

camera.position.z = 10;
camera.position.y = 5
camera.lookAt(table.position);

// create a point light
var pointLight =
    new THREE.PointLight(0xcdcde7);

// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 25;

// add to the scene
scene.add(pointLight);

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var point = new THREE.Vector3();

function onMouseDown( event ) {
    event.preventDefault();

    mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;

    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObjects( collisionList );
    if(intersects[0] != undefined)
    {
        point = intersects[0].point;
    }
}

function moveCar(object,delta)
{
    //var objDistance = point.distanceTo(object.mesh.position);
    var input = [];
    input.push(object.velocity);
    input.push(((object.mesh.rotation.y + 1.6) / 3.2));
    // TODO: Add the positive and negative rotation axis.
    //input.push((Math.abs(object.mesh.rotation.x / Math.PI)));
    var output = object.brain.activate(input);
    object.brain.restore();
    var speed = 5;
    object.velocity = output[0];
    object.mesh.translateZ(output[0] * speed * delta);
    object.mesh.rotateY((output[1] - 0.5) * speed * delta);

    var learningRate = 0.01;
    var target = [(mouse.y/2)+0.5,(mouse.x/2)+0.5];
    var outLog = document.getElementById("outLog");

    // Some sort of output for checking on our neural network
    // TODO: This should be generated but because we don't really know how we want it to look like this will function as a prototype.
    // TODO: Make some variables so that these sentences can become shorter.. right now they are there so we can fully understand how it works.
    //    outLog.innerHTML =
    //    "
 Input:" + input[0].toFixed(2) + " Bias:" + object.brain.layers.input.list[0].bias.toFixed(2)  + " | " + " Weights:" + object.brain.layers.hidden[0].list[0].connections.inputs[6].weight.toFixed(2) + " and " + object.brain.layers.hidden[0].list[0].connections.inputs[8].weight.toFixed(2) + " Bias:" + object.brain.layers.hidden[0].list[0].bias.toFixed(2) + " | " + " Weights:" + object.brain.layers.output.list[0].connections.inputs[10].weight.toFixed(2) + " and " + object.brain.layers.output.list[0].connections.inputs[12].weight.toFixed(2) + " Bias:" + object.brain.layers.output.list[0].bias.toFixed(2) + " Output:" + output[0].toFixed(2) + "
" +
    //    "
 Input:" + input[1].toFixed(2) + " Bias:" + object.brain.layers.input.list[1].bias.toFixed(2)  + " | " + " Weights:" + object.brain.layers.hidden[0].list[1].connections.inputs[7].weight.toFixed(2) + " and " + object.brain.layers.hidden[0].list[1].connections.inputs[9].weight.toFixed(2) + " Bias:" + object.brain.layers.hidden[0].list[1].bias.toFixed(2)  + " | " + " Weights:" + object.brain.layers.output.list[1].connections.inputs[11].weight.toFixed(2) + " and " + object.brain.layers.output.list[1].connections.inputs[13].weight.toFixed(2) + " Bias:" + object.brain.layers.output.list[1].bias.toFixed(2) + " Output:" + output[1].toFixed(2) + "
";
    // console.log(object.brain);
    // object.brain.propagate(learningRate, target);
    // object.brain.restore();
};

var update = function () {
    requestAnimationFrame( update );
    var delta = clock.getDelta(); // seconds.
    for (car in pool.entities){
        moveCar(pool.entities[car],delta);
    }
    render();
};

var render = function () {
    renderer.render(scene, camera);
};

function addMouseHandler(canvas) {
    canvas.addEventListener('mousemove', function (e) {
        // onMouseMove(e);
    }, false);
    canvas.addEventListener('mousedown', function (e) {
        onMouseDown(e);
    }, false);
    canvas.addEventListener('mouseup', function (e) {
        // onMouseUp(e);
    }, false);
}

addMouseHandler(document);

update();

<commit_msg>Remove mutating biases<commit_after>/**
 * Created by wander on 9/15/2016.
 */
var Neuron = synaptic.Neuron,
    Layer = synaptic.Layer,
    Network = synaptic.Network;

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0x221f36, 1 );
document.body.appendChild( renderer.domElement );

var loader = new THREE.TextureLoader();
var clock = new THREE.Clock();

function Cube (xSize,ySize,zSize,color) {
    this.geometry = new THREE.BoxGeometry(xSize, ySize, zSize);
    this.material = new THREE.MeshLambertMaterial({color: color});
    return new THREE.Mesh(this.geometry, this.material);
}

function Perceptron(input, hidden, output)
{
    // create the layers
    var inputLayer = new Layer(input);
    var hiddenLayer = new Layer(hidden);
    var outputLayer = new Layer(output);

    // connect the layers
    inputLayer.project(hiddenLayer);
    hiddenLayer.project(outputLayer);

    // set the layers
    this.set({
        input: inputLayer,
        hidden: [hiddenLayer],
        output: outputLayer
    });

    //var standalone = this.standalone();
}

// extend the prototype chain
Perceptron.prototype = new Network();
Perceptron.prototype.constructor = Perceptron;

class Car {
    constructor(mesh,brain) {
        this.mesh = mesh;
        this.brain = brain ? brain : new Perceptron(2,2,2);
        this.velocity = 1;
        //You want to log out the object file so we can explore it, just once per session though.
        //TODO: remove this when no longer needed.
       // console.log(this.brain.layers);
    }

    Destroy() {
        //TODO: Would be nice to be able to remove the neural network too.
        scene.remove(this.mesh);
    }

    Create() {
        this.mesh.position.set(0,0.3,-2);
        scene.add(this.mesh);
    }
}

var collisionList = [];

var seed = function() {
    var car = new Car(Cube(0.5,0.25,1,0x47475b));
    car.Create();
    //collisionList.push(car.mesh);
    return car
};

var fitness = function(entity) {
    var moral = 0;
    moral = entity.mesh.position.z;
    return moral;
};

var copy = function(entity)
{
    var newEntity = new Car(Cube(0.5,0.25,1,0x47475b),entity.brain.clone());
    newEntity.brain = jQuery.extend(true, {}, entity.brain);
    return newEntity;
}

var crossoverRandom = function(father,mother)
{
    var son = new Car(Cube(0.5,0.25,1,0x47475b));
    var daughter = new Car(Cube(0.5,0.25,1,0x47475b));

    var dadNeurons = father.brain.neurons();
    var dadWeights = [];
    for(let s in dadNeurons){
        for(let i in dadNeurons[s].neuron.connections.inputs){
            var input = dadNeurons[s].neuron.connections.inputs[i];
            dadWeights.push(input);
        }
    }

    var momNeurons = mother.brain.neurons();
    var momWeights = [];
    for(let s in momNeurons){
        for(let i in momNeurons[s].neuron.connections.inputs){
            var input = momNeurons[s].neuron.connections.inputs[i];
            momWeights.push(input);
        }
    }

    var splice = function (dad,mom) {
        var slice = Math.random().toFixed(2);
        var son = [];
        var daughter = [];

        for(let i = 0; i <= dad.length;i++){
            var len = dad.length * slice;

            son.push(i <= len ? dad[i] : mom[i]);
            daughter.push(i <= len ? mom[i] : dad[i]);
        }

        return [son,daughter];
    }

    var newWeights = splice(dadWeights,momWeights);

    var sonNeurons = son.brain.neurons();
    for(let s in sonNeurons){
        for(let i in sonNeurons[s].neuron.connections.inputs){
            son.brain.neurons()[s].neuron.connections.inputs[i].weight = newWeights[0][s].weight;
        }
    }

    var daughterNeurons = daughter.brain.neurons();
    for(let s in daughterNeurons){
        for(let i in daughterNeurons[s].neuron.connections.inputs){
            daughter.brain.neurons()[s].neuron.connections.inputs[i].weight = newWeights[1][s].weight;
        }
    }

    return [son,daughter];
}

var mutate = function (oldEntity) {
    var entity = oldEntity;
    var randomEntity = new Car(Cube(0.5,0.25,1,0x47475b));

    var inputConn = entity.brain.layers.input.connectedTo;
    var randomInputConn = randomEntity.brain.layers.input.connectedTo;

    for(let idx = 0; idx < Object.keys(inputConn[0].connections).length; idx++) {
        inputConn[0].connections[Object.keys(inputConn[0].connections)[idx]].weight = randomInputConn[0].connections[Object.keys(randomInputConn[0].connections)[idx]].weight;
    }

    var hiddenLayerAmt = entity.brain.layers.hidden.length;
    for(let depth = 0; depth < hiddenLayerAmt; depth++) {
        var hiddenConn = entity.brain.layers.hidden[depth].connectedTo;
        var randomHiddenConn = randomEntity.brain.layers.hidden[depth].connectedTo;

        for(let idx = 0; idx < Object.keys(inputConn[0].connections).length; idx++) {
            hiddenConn[0].connections[Object.keys(hiddenConn[0].connections)[idx]].weight = randomHiddenConn[0].connections[Object.keys(randomHiddenConn[0].connections)[idx]].weight;
        }
    }

    return entity;
}

var pool = new Genegen(seed,fitness,copy,crossoverRandom,mutate);

pool.Start();

var floor = new Cube(6,0.25,11,0x0078dc);
floor.position.set(0,0,0);
var left = new Cube(0.5,0.5,10,0x47475b);
left.position.set(-2.75,0.3,0);
collisionList.push(left);
var right = new Cube(0.5,0.5,10,0x47475b);
right.position.set(2.75,0.3,0);
collisionList.push(right);
var front = new Cube(6,0.5,0.5,0x47475b);
front.position.set(0,0.3,-5.25);
collisionList.push(front);
var back = new Cube(6,0.5,0.5,0x47475b);
back.position.set(0,0.3,5.25);
collisionList.push(back);
table = new THREE.Group();
table.add(floor);
table.add(left);
table.add(right);
table.add(front);
table.add(back);

scene.add( table );

camera.position.z = 10;
camera.position.y = 5
camera.lookAt(table.position);

// create a point light
var pointLight =
    new THREE.PointLight(0xcdcde7);

// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 25;

// add to the scene
scene.add(pointLight);

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var point = new THREE.Vector3();

function onMouseDown( event ) {
    event.preventDefault();

    mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;

    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObjects( collisionList );
    if(intersects[0] != undefined)
    {
        point = intersects[0].point;
    }
}

function moveCar(object,delta)
{
    //var objDistance = point.distanceTo(object.mesh.position);
    var input = [];
    input.push(object.velocity);
    input.push(((object.mesh.rotation.y + 1.6) / 3.2));
    // TODO: Add the positive and negative rotation axis.
    //input.push((Math.abs(object.mesh.rotation.x / Math.PI)));
    var output = object.brain.activate(input);
    object.brain.restore();
    var speed = 5;
    object.velocity = output[0];
    object.mesh.translateZ(output[0] * speed * delta);
    object.mesh.rotateY((output[1] - 0.5) * speed * delta);

    var learningRate = 0.01;
    var target = [(mouse.y/2)+0.5,(mouse.x/2)+0.5];
    var outLog = document.getElementById("outLog");

    // Some sort of output for checking on our neural network
    // TODO: This should be generated but because we don't really know how we want it to look like this will function as a prototype.
    // TODO: Make some variables so that these sentences can become shorter.. right now they are there so we can fully understand how it works.
    //    outLog.innerHTML =
    //    "
 Input:" + input[0].toFixed(2) + " Bias:" + object.brain.layers.input.list[0].bias.toFixed(2)  + " | " + " Weights:" + object.brain.layers.hidden[0].list[0].connections.inputs[6].weight.toFixed(2) + " and " + object.brain.layers.hidden[0].list[0].connections.inputs[8].weight.toFixed(2) + " Bias:" + object.brain.layers.hidden[0].list[0].bias.toFixed(2) + " | " + " Weights:" + object.brain.layers.output.list[0].connections.inputs[10].weight.toFixed(2) + " and " + object.brain.layers.output.list[0].connections.inputs[12].weight.toFixed(2) + " Bias:" + object.brain.layers.output.list[0].bias.toFixed(2) + " Output:" + output[0].toFixed(2) + "
" +
    //    "
 Input:" + input[1].toFixed(2) + " Bias:" + object.brain.layers.input.list[1].bias.toFixed(2)  + " | " + " Weights:" + object.brain.layers.hidden[0].list[1].connections.inputs[7].weight.toFixed(2) + " and " + object.brain.layers.hidden[0].list[1].connections.inputs[9].weight.toFixed(2) + " Bias:" + object.brain.layers.hidden[0].list[1].bias.toFixed(2)  + " | " + " Weights:" + object.brain.layers.output.list[1].connections.inputs[11].weight.toFixed(2) + " and " + object.brain.layers.output.list[1].connections.inputs[13].weight.toFixed(2) + " Bias:" + object.brain.layers.output.list[1].bias.toFixed(2) + " Output:" + output[1].toFixed(2) + "
";
    // console.log(object.brain);
    // object.brain.propagate(learningRate, target);
    // object.brain.restore();
};

var update = function () {
    requestAnimationFrame( update );
    var delta = clock.getDelta(); // seconds.
    for (car in pool.entities){
        moveCar(pool.entities[car],delta);
    }
    render();
};

var render = function () {
    renderer.render(scene, camera);
};

function addMouseHandler(canvas) {
    canvas.addEventListener('mousemove', function (e) {
        // onMouseMove(e);
    }, false);
    canvas.addEventListener('mousedown', function (e) {
        onMouseDown(e);
    }, false);
    canvas.addEventListener('mouseup', function (e) {
        // onMouseUp(e);
    }, false);
}

addMouseHandler(document);

update();

<|endoftext|>


<commit_before>var albums_queue;
var releases_queue;
var album_requests;
var releases_requests;
var max_request_size = 20;
var length;
var days = 14;

var loading_image;
var releases_div;

String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

function setDays() {
    days = parseInt(document.getElementById('time').value);
    loading_image.style.visibility = "visible";
    reload();
}

function reload() {
    releases_div.innerHTML = "";
    i = 0;
    start = 0;
    end = 20;
    albums_queue = [];
    releases_queue = [];
    album_requests = 0;
    releases_requests = 0;
    $.getJSON('get_artists', function (artists) {
        album_requests = artists.length;
        get_artists(artists);
    });
}

var i = 0;
function get_artists(artists) {
    if (i < artists.length) {
        $.ajax({
            type: 'GET',
            url: 'https://api.spotify.com/v1/artists/' + artists[i] + '/albums',
            success: function (data) {
                var albums = extract_albums_from_json(data);
                for (var i = 0; i < albums.length; i++) {
                    if ($.inArray(albums[i], albums_queue) === -1) {
                        albums_queue.push(albums[i]);
                    }
                }
                albums_request_success();
            },
            error: function () {
                --album_requests;
            }
        });
        i++;
        setTimeout(get_artists(artists), 500);
    }
}

function albums_request_success() {
    if (--album_requests === 0) {
        releases_requests = albums_queue.length / max_request_size - 1;
        get_recent_releases();
    }
}

function extract_albums_from_json(albums_json) {
    var albums = [];
    var item_list = albums_json['items'];
    for (var i = 0; i < item_list.length; i++) {
        albums.push(item_list[i]['id']);
    }
    return albums;
}

var start = 0;
var end = 20;
function get_recent_releases() {
    if (end < albums_queue.length) {
        var sliced = albums_queue.slice(start, end);
        var albums_string = sliced.join(',');
        start = end;
        end += 20;
        $.ajax({
            type: 'GET',
            url: 'https://api.spotify.com/v1/albums',
            data: {ids: albums_string},
            success: function (data) {
                releases_queue = releases_queue.concat(filter_recent_releases(data));
                --releases_requests;
                check_releases_requests();
            },
            error: function () {
                --releases_requests;
                check_releases_requests();
            },
            timeout: 3000
        });
        setTimeout(get_recent_releases(), 500);
    }
}

function check_releases_requests() {
    if (releases_requests === 0) {
        var albums = [];
        loading_image.style.visibility = "hidden";
        for (var i = 0; i < releases_queue.length; i++) {
            if ($.inArray(releases_queue[i]['name'].toLowerCase(), albums) === -1) {
                albums.push(releases_queue[i]['name'].toLowerCase());
                append_album_to_html(releases_queue[i]);
            }
        }
    }
}

function append_album_to_html(album) {
    var post_row = document.createElement("div");
    var post_col = document.createElement("div");
    var img = document.createElement("img");
    img.setAttribute('src', album['cover']);
    post_col.appendChild(img);
    var post_content = document.createElement('div');
    var name = document.createTextNode(album['album_type'] + ': ' + album['artist'] + ' - ' + album['name']);
    var uri = document.createElement("a");
    uri.setAttribute('href', album['uri']);
    uri.innerHTML = "Open in Spotify";
    post_col.setAttribute('class', 'album_image');
    post_content.appendChild(name);
    post_content.appendChild(document.createElement("br"));
    post_content.appendChild(uri);
    post_content.setAttribute('class', 'album_description');
    post_row.appendChild(post_col);
    post_row.appendChild(post_content);
    post_row.setAttribute('class', 'album');
    releases_div.appendChild(post_row);
}

function filter_recent_releases(albums_info) {
    var current_date = new Date();
    current_date.setDate(current_date.getDate() - days);
    var recently_released_albums = [];
    var albums_list = albums_info['albums'];
    for (var i = 0; i < albums_list.length; i++) {
        var album = albums_list[i];
        var parts = album['release_date'].split('-');
        if (parts.length == 3) {
            var release_date = new Date(parts[0], parts[1], parts[2]);
            if (release_date > current_date) {
                var artists = [];
                for (var x = 0; x < album['artists'].length; x++) {
                    artists.push(album['artists'][x]['name']);
                }
                if (artists.length > 5) {
                    artists = "Various Artists"
                } else {
                    artists = artists.join(', ')
                }
                var album_obj = {
                    'id': album['id'],
                    'album_type': album['album_type'].capitalizeFirstLetter(),
                    'artist': artists,
                    'name': album['name'],
                    'cover': album['images'][1]['url'],
                    'uri': album['uri']
                };
                recently_released_albums.push(album_obj);
            }
        }
    }
    return recently_released_albums;
}

$(document).ready(function () {
    loading_image = document.getElementById("loading_image");
    releases_div = document.getElementById('releases_container');
    reload();
});

<commit_msg>added timeout to artists request<commit_after>var albums_queue;
var releases_queue;
var album_requests;
var releases_requests;
var max_request_size = 20;
var length;
var days = 14;

var loading_image;
var releases_div;

String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

function setDays() {
    days = parseInt(document.getElementById('time').value);
    loading_image.style.visibility = "visible";
    reload();
}

function reload() {
    releases_div.innerHTML = "";
    i = 0;
    start = 0;
    end = 20;
    albums_queue = [];
    releases_queue = [];
    album_requests = 0;
    releases_requests = 0;
    $.getJSON('get_artists', function (artists) {
        album_requests = artists.length;
        get_artists(artists);
    });
}

var i = 0;
function get_artists(artists) {
    if (i < artists.length) {
        $.ajax({
            type: 'GET',
            url: 'https://api.spotify.com/v1/artists/' + artists[i] + '/albums',
            success: function (data) {
                var albums = extract_albums_from_json(data);
                for (var i = 0; i < albums.length; i++) {
                    if ($.inArray(albums[i], albums_queue) === -1) {
                        albums_queue.push(albums[i]);
                    }
                }
                --album_requests;
                check_albums_request();
            },
            error: function () {
                --album_requests;
                check_albums_request();
            },
            timeout: 3000
        });
        i++;
        setTimeout(get_artists(artists), 500);
    }
}

function check_albums_request() {
    if (album_requests === 0) {
        releases_requests = albums_queue.length / max_request_size - 1;
        get_recent_releases();
    }
}

function extract_albums_from_json(albums_json) {
    var albums = [];
    var item_list = albums_json['items'];
    for (var i = 0; i < item_list.length; i++) {
        albums.push(item_list[i]['id']);
    }
    return albums;
}

var start = 0;
var end = 20;
function get_recent_releases() {
    if (end < albums_queue.length) {
        var sliced = albums_queue.slice(start, end);
        var albums_string = sliced.join(',');
        start = end;
        end += 20;
        $.ajax({
            type: 'GET',
            url: 'https://api.spotify.com/v1/albums',
            data: {ids: albums_string},
            success: function (data) {
                releases_queue = releases_queue.concat(filter_recent_releases(data));
                --releases_requests;
                check_releases_requests();
            },
            error: function () {
                --releases_requests;
                check_releases_requests();
            },
            timeout: 3000
        });
        setTimeout(get_recent_releases(), 500);
    }
}

function check_releases_requests() {
    if (releases_requests === 0) {
        var albums = [];
        loading_image.style.visibility = "hidden";
        for (var i = 0; i < releases_queue.length; i++) {
            if ($.inArray(releases_queue[i]['name'].toLowerCase(), albums) === -1) {
                albums.push(releases_queue[i]['name'].toLowerCase());
                append_album_to_html(releases_queue[i]);
            }
        }
    }
}

function append_album_to_html(album) {
    var post_row = document.createElement("div");
    var post_col = document.createElement("div");
    var img = document.createElement("img");
    img.setAttribute('src', album['cover']);
    post_col.appendChild(img);
    var post_content = document.createElement('div');
    var name = document.createTextNode(album['album_type'] + ': ' + album['artist'] + ' - ' + album['name']);
    var uri = document.createElement("a");
    uri.setAttribute('href', album['uri']);
    uri.innerHTML = "Open in Spotify";
    post_col.setAttribute('class', 'album_image');
    post_content.appendChild(name);
    post_content.appendChild(document.createElement("br"));
    post_content.appendChild(uri);
    post_content.setAttribute('class', 'album_description');
    post_row.appendChild(post_col);
    post_row.appendChild(post_content);
    post_row.setAttribute('class', 'album');
    releases_div.appendChild(post_row);
}

function filter_recent_releases(albums_info) {
    var current_date = new Date();
    current_date.setDate(current_date.getDate() - days);
    var recently_released_albums = [];
    var albums_list = albums_info['albums'];
    for (var i = 0; i < albums_list.length; i++) {
        var album = albums_list[i];
        var parts = album['release_date'].split('-');
        if (parts.length == 3) {
            var release_date = new Date(parts[0], parts[1], parts[2]);
            if (release_date > current_date) {
                var artists = [];
                for (var x = 0; x < album['artists'].length; x++) {
                    artists.push(album['artists'][x]['name']);
                }
                if (artists.length > 5) {
                    artists = "Various Artists"
                } else {
                    artists = artists.join(', ')
                }
                var album_obj = {
                    'id': album['id'],
                    'album_type': album['album_type'].capitalizeFirstLetter(),
                    'artist': artists,
                    'name': album['name'],
                    'cover': album['images'][1]['url'],
                    'uri': album['uri']
                };
                recently_released_albums.push(album_obj);
            }
        }
    }
    return recently_released_albums;
}

$(document).ready(function () {
    loading_image = document.getElementById("loading_image");
    releases_div = document.getElementById('releases_container');
    reload();
});

<|endoftext|>


<commit_before>var albums_queue;
var releases_queue;
var album_requests;
var releases_requests;
var max_request_size = 20;
var length;
var days = 14;

var loading_image;
var releases_div;

String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

function setDays() {
    days = parseInt(document.getElementById('time').value);
    loading_image.style.visibility = "visible";
    reload();
}

function reload() {
    releases_div.innerHTML = "";
    i = 0;
    start = 0;
    end = 20;
    albums_queue = [];
    releases_queue = [];
    album_requests = 0;
    releases_requests = 0;
    $.getJSON('get_artists', function (artists) {
        album_requests = artists.length;
        get_artists(artists);
    });
}

var i = 0;
function get_artists(artists) {
    if (i < artists.length) {
        $.ajax({
            type: 'GET',
            url: 'https://api.spotify.com/v1/artists/' + artists[i] + '/albums',
            success: function (data) {
                var albums = extract_albums_from_json(data);
                for (var i = 0; i < albums.length; i++) {
                    if ($.inArray(albums[i], albums_queue) === -1) {
                        albums_queue.push(albums[i]);
                    }
                }
                --album_requests;
                check_albums_request();
            },
            error: function () {
                --album_requests;
                check_albums_request();
            },
            timeout: 3000
        });
        i++;
        setTimeout(get_artists(artists), 500);
    }
}

function check_albums_request() {
    if (album_requests === 0) {
        releases_requests = albums_queue.length / max_request_size - 1;
        get_recent_releases();
    }
}

function extract_albums_from_json(albums_json) {
    var albums = [];
    var item_list = albums_json['items'];
    for (var i = 0; i < item_list.length; i++) {
        albums.push(item_list[i]['id']);
    }
    return albums;
}

var start = 0;
var end = 20;
function get_recent_releases() {
    if (end < albums_queue.length) {
        var sliced = albums_queue.slice(start, end);
        var albums_string = sliced.join(',');
        start = end;
        end += 20;
        $.ajax({
            type: 'GET',
            url: 'https://api.spotify.com/v1/albums',
            data: {ids: albums_string},
            success: function (data) {
                releases_queue = releases_queue.concat(filter_recent_releases(data));
                --releases_requests;
                check_releases_requests();
            },
            error: function () {
                --releases_requests;
                check_releases_requests();
            },
            timeout: 3000
        });
        setTimeout(get_recent_releases(), 500);
    }
}

function check_releases_requests() {
    if (releases_requests === 0) {
        var albums = [];
        loading_image.style.visibility = "hidden";
        for (var i = 0; i < releases_queue.length; i++) {
            if ($.inArray(releases_queue[i]['name'].toLowerCase(), albums) === -1) {
                albums.push(releases_queue[i]['name'].toLowerCase());
                append_album_to_html(releases_queue[i]);
            }
        }
    }
}

function append_album_to_html(album) {
    var post_row = document.createElement("div");
    var post_col = document.createElement("div");
    var img = document.createElement("img");
    img.setAttribute('src', album['cover']);
    post_col.appendChild(img);
    var post_content = document.createElement('div');
    var name = document.createTextNode(album['album_type'] + ': ' + album['artist'] + ' - ' + album['name']);
    var uri = document.createElement("a");
    uri.setAttribute('href', album['uri']);
    uri.innerHTML = "Open in Spotify";
    post_col.setAttribute('class', 'album_image');
    post_content.appendChild(name);
    post_content.appendChild(document.createElement("br"));
    post_content.appendChild(uri);
    post_content.setAttribute('class', 'album_description');
    post_row.appendChild(post_col);
    post_row.appendChild(post_content);
    post_row.setAttribute('class', 'album');
    releases_div.appendChild(post_row);
}

function filter_recent_releases(albums_info) {
    var current_date = new Date();
    current_date.setDate(current_date.getDate() - days);
    var recently_released_albums = [];
    var albums_list = albums_info['albums'];
    for (var i = 0; i < albums_list.length; i++) {
        var album = albums_list[i];
        var parts = album['release_date'].split('-');
        if (parts.length == 3) {
            var release_date = new Date(parts[0], parts[1], parts[2]);
            if (release_date > current_date) {
                var artists = [];
                for (var x = 0; x < album['artists'].length; x++) {
                    artists.push(album['artists'][x]['name']);
                }
                if (artists.length > 5) {
                    artists = "Various Artists"
                } else {
                    artists = artists.join(', ')
                }
                var album_obj = {
                    'id': album['id'],
                    'album_type': album['album_type'].capitalizeFirstLetter(),
                    'artist': artists,
                    'name': album['name'],
                    'cover': album['images'][1]['url'],
                    'uri': album['uri']
                };
                recently_released_albums.push(album_obj);
            }
        }
    }
    return recently_released_albums;
}

$(document).ready(function () {
    loading_image = document.getElementById("loading_image");
    releases_div = document.getElementById('releases_container');
    reload();
});

<commit_msg>testing different timeout values<commit_after>var albums_queue;
var releases_queue;
var album_requests;
var releases_requests;
var max_request_size = 20;
var length;
var days = 14;

var loading_image;
var releases_div;

String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

function setDays() {
    days = parseInt(document.getElementById('time').value);
    loading_image.style.visibility = "visible";
    reload();
}

function reload() {
    releases_div.innerHTML = "";
    i = 0;
    start = 0;
    end = 20;
    albums_queue = [];
    releases_queue = [];
    album_requests = 0;
    releases_requests = 0;
    $.getJSON('get_artists', function (artists) {
        album_requests = artists.length;
        get_artists(artists);
    });
}

var i = 0;
function get_artists(artists) {
    if (i < artists.length) {
        $.ajax({
            type: 'GET',
            url: 'https://api.spotify.com/v1/artists/' + artists[i] + '/albums',
            success: function (data) {
                var albums = extract_albums_from_json(data);
                for (var i = 0; i < albums.length; i++) {
                    if ($.inArray(albums[i], albums_queue) === -1) {
                        albums_queue.push(albums[i]);
                    }
                }
                --album_requests;
                check_albums_request();
            },
            error: function () {
                --album_requests;
                check_albums_request();
            }
        });
        i++;
        setTimeout(function() {
    get_artists(artists);
}, 5);
    }
}

function check_albums_request() {
    if (album_requests === 0) {
        releases_requests = Math.floor(albums_queue.length / max_request_size);
        get_recent_releases();
    }
}

function extract_albums_from_json(albums_json) {
    var albums = [];
    var item_list = albums_json['items'];
    for (var i = 0; i < item_list.length; i++) {
        albums.push(item_list[i]['id']);
    }
    return albums;
}

var start = 0;
var end = 20;
function get_recent_releases() {
    if (end < albums_queue.length) {
        var sliced = albums_queue.slice(start, end);
        var albums_string = sliced.join(',');
        start = end;
        end += 20;
        $.ajax({
            type: 'GET',
            url: 'https://api.spotify.com/v1/albums',
            data: {ids: albums_string},
            success: function (data) {
                releases_queue = releases_queue.concat(filter_recent_releases(data));
                --releases_requests;
                check_releases_requests();
            },
            error: function () {
                --releases_requests;
                check_releases_requests();
            }
        });
        setTimeout(get_recent_releases, 5);
    }
}

function check_releases_requests() {
    if (releases_requests <= 0) {
        var albums = [];
        loading_image.style.visibility = "hidden";
        for (var i = 0; i < releases_queue.length; i++) {
            if ($.inArray(releases_queue[i]['name'].toLowerCase(), albums) === -1) {
                albums.push(releases_queue[i]['name'].toLowerCase());
                append_album_to_html(releases_queue[i]);
            }
        }
    }
}

function append_album_to_html(album) {
    var post_row = document.createElement("div");
    var post_col = document.createElement("div");
    var img = document.createElement("img");
    img.setAttribute('src', album['cover']);
    post_col.appendChild(img);
    var post_content = document.createElement('div');
    var name = document.createTextNode(album['album_type'] + ': ' + album['artist'] + ' - ' + album['name']);
    var uri = document.createElement("a");
    uri.setAttribute('href', album['uri']);
    uri.innerHTML = "Open in Spotify";
    post_col.setAttribute('class', 'album_image');
    post_content.appendChild(name);
    post_content.appendChild(document.createElement("br"));
    post_content.appendChild(uri);
    post_content.setAttribute('class', 'album_description');
    post_row.appendChild(post_col);
    post_row.appendChild(post_content);
    post_row.setAttribute('class', 'album');
    releases_div.appendChild(post_row);
}

function filter_recent_releases(albums_info) {
    var current_date = new Date();
    current_date.setDate(current_date.getDate() - days);
    var recently_released_albums = [];
    var albums_list = albums_info['albums'];
    for (var i = 0; i < albums_list.length; i++) {
        var album = albums_list[i];
        var parts = album['release_date'].split('-');
        if (parts.length == 3) {
            var release_date = new Date(parts[0], parts[1], parts[2]);
            if (release_date > current_date) {
                var artists = [];
                for (var x = 0; x < album['artists'].length; x++) {
                    artists.push(album['artists'][x]['name']);
                }
                if (artists.length > 5) {
                    artists = "Various Artists"
                } else {
                    artists = artists.join(', ')
                }
                var album_obj = {
                    'id': album['id'],
                    'album_type': album['album_type'].capitalizeFirstLetter(),
                    'artist': artists,
                    'name': album['name'],
                    'cover': album['images'][1]['url'],
                    'uri': album['uri']
                };
                recently_released_albums.push(album_obj);
            }
        }
    }
    return recently_released_albums;
}

$(document).ready(function () {
    loading_image = document.getElementById("loading_image");
    releases_div = document.getElementById('releases_container');
    reload();
});

<|endoftext|>