<commit_before>const logAF = function logAF(...args) {
  if (logAF.label) {
    const lineNum = logAF.setFormat(args[0]);
    args.unshift(lineNum);
  }
  Promise.all(args).then((toLog) => {
    // eslint-disable-next-line
    console ? console.log ? console.log(...toLog) : null : null;
  });
};

logAF.label = true;
logAF.labelFormat = 'file';

/*
* labelFormat options:
*
* - file -
* @file.js:line:col: non-object
* @file.js:line:col:
* [Object]
*
* - path -
* @/Path/to/current/directory/file.js:line:col:
* non-object
* @/Path/to/current/directory/file.js:line:col:
* [Object]
*
* - parent -
* @parentDirectory/file.js:line:col: non-object
* @parentDirectory/file.js:line:col:
* [Object]
*
* - arrow -
* ========================> non-object
* ========================> [Object]
*/

logAF.setFormat = function setFormat(firstArg) {
  const error = new Error();
  if (!error.stack) return '';
  const newLineForObjs = typeof firstArg === 'object' ? '\n' : '';
  const target = error.stack.lastIndexOf`/`;
  const formats = {
    file() {
      const end = error.stack.indexOf(')', target + 1);
      return `@${error.stack.slice(target + 1, end)}:${newLineForObjs}`;
    },
    path() {
      const cutoff = error.stack.slice(0, error.stack.indexOf(')', target));
      return `@${cutoff.slice(cutoff.lastIndexOf`(` + 1)}:\n`;
    },
    parent() {
      const end = error.stack.indexOf(')', target);
      const start = error.stack.slice(0, target).lastIndexOf`/` + 1;
      return `@${error.stack.slice(start, end)}:${newLineForObjs}`;
    },
    arrow() {
      return '========================>';
    },
    custom(format) { /* eslint-disable no-unused-vars, prefer-const, no-eval */
      const location = formats.path().slice(1).split`:`;
      let [path, line, col] = location;
      path = path.split`/`;
      const file = path.pop();
      path = path.join`/`;
      const parent = `${path.split`/`.pop()}/`;
      path += '/';
      const arrow = formats.arrow();
      return eval(format.toString());
    }, /* eslint-enable */
  };
  if (logAF.labelFormat === 'custom') {
    const format = logAF.fullFormat;
    return formats.custom(format.slice(format.indexOf`=` + 1));
  }
  return formats[logAF.labelFormat]();
};

logAF.options = function logAFOptions(options) {
  if (options.label === false) logAF.label = false;
  if (options.labelFormat) {
    const validFormats = [
      'file',
      'path',
      'parent',
      'arrow',
      'custom',
    ];
    const desiredFormat = options.labelFormat.slice(0, 6);
    if (!validFormats.includes(desiredFormat)) {
      const msg = 'AsyncAF Warning: logAF labelFormat option must be set to \'file\' (default), \'path\', \'parent\', \'arrow\', or \'custom\'';
      // eslint-disable-next-line
      console ? console.warn ? console.warn(msg) : console.log ? console.log(msg) : null : null;
    } else {
      logAF.labelFormat = desiredFormat;
      logAF.fullFormat = options.labelFormat;
    }
  }
};

module.exports = logAF;
<commit_msg>(docs) add JSDoc docs to logAF<commit_after>/**
 * - Logs items to the console; if an item is a promise,
 * logAF will first resolve the promise then log its value.
 *
 * - **Note:** The label (file:line:col) may not work correctly
 * in all environments; to turn the label off, set label to false
 * in logAF options, where you can also change the label's format.
 *
 * @since 1.3.0
 * @param {*} items The items to print (log to the console)
 * @see logAF.options to turn the label off or change its format
 */

const logAF = function logAF(...items) {
  if (logAF.label) {
    const lineNum = logAF.setFormat(items[0]);
    items.unshift(lineNum);
  }
  Promise.all(items).then((toLog) => {
    // eslint-disable-next-line
    console ? console.log ? console.log(...toLog) : null : null;
  });
};

logAF.label = true;
logAF.labelFormat = 'file';

/*
* labelFormat options:
*
* - file -
* @file.js:line:col: non-object
* @file.js:line:col:
* [Object]
*
* - path -
* @/Path/to/current/directory/file.js:line:col:
* non-object
* @/Path/to/current/directory/file.js:line:col:
* [Object]
*
* - parent -
* @parentDirectory/file.js:line:col: non-object
* @parentDirectory/file.js:line:col:
* [Object]
*
* - arrow -
* ========================> non-object
* ========================> [Object]
*/

logAF.setFormat = function setFormat(firstArg) {
  const error = new Error();
  if (!error.stack) return '';
  const newLineForObjs = typeof firstArg === 'object' ? '\n' : '';
  const target = error.stack.lastIndexOf`/`;
  const formats = {
    file() {
      const end = error.stack.indexOf(')', target + 1);
      return `@${error.stack.slice(target + 1, end)}:${newLineForObjs}`;
    },
    path() {
      const cutoff = error.stack.slice(0, error.stack.indexOf(')', target));
      return `@${cutoff.slice(cutoff.lastIndexOf`(` + 1)}:\n`;
    },
    parent() {
      const end = error.stack.indexOf(')', target);
      const start = error.stack.slice(0, target).lastIndexOf`/` + 1;
      return `@${error.stack.slice(start, end)}:${newLineForObjs}`;
    },
    arrow() {
      return '========================>';
    },
    custom(format) { /* eslint-disable no-unused-vars, prefer-const, no-eval */
      const location = formats.path().slice(1).split`:`;
      let [path, line, col] = location;
      path = path.split`/`;
      const file = path.pop();
      path = path.join`/`;
      const parent = `${path.split`/`.pop()}/`;
      path += '/';
      const arrow = formats.arrow();
      return eval(format.toString());
    }, /* eslint-enable */
  };
  if (logAF.labelFormat === 'custom') {
    const format = logAF.fullFormat;
    return formats.custom(format.slice(format.indexOf`=` + 1));
  }
  return formats[logAF.labelFormat]();
};

logAF.options = function logAFOptions(options) {
  if (options.label === false) logAF.label = false;
  if (options.labelFormat) {
    const validFormats = [
      'file',
      'path',
      'parent',
      'arrow',
      'custom',
    ];
    const desiredFormat = options.labelFormat.slice(0, 6);
    if (!validFormats.includes(desiredFormat)) {
      const msg = 'AsyncAF Warning: logAF labelFormat option must be set to \'file\' (default), \'path\', \'parent\', \'arrow\', or \'custom\'';
      // eslint-disable-next-line
      console ? console.warn ? console.warn(msg) : console.log ? console.log(msg) : null : null;
    } else {
      logAF.labelFormat = desiredFormat;
      logAF.fullFormat = options.labelFormat;
    }
  }
};

module.exports = logAF;
<|endoftext|>


<commit_before>/*
 * Copyright 2018 balena
 *
 * @license Apache-2.0
 */

'use strict';

const assert = require('assert');
const fse = require('fs-extra');
const { join } = require('path');
const { homedir } = require('os');

module.exports = {
	title: 'Unmanaged BalenaOS release suite',
	run: async function(test) {
		// The worker class contains methods to interact with the DUT, such as flashing, or executing a command on the device
		const Worker = this.require('common/worker');
		// The balenaOS class contains information on the OS image to be flashed, and methods to configure it
		const BalenaOS = this.require('components/os/balenaos');

		await fse.ensureDir(this.suite.options.tmpdir);

		// The suite contex is an object that is shared across all tests. Setting something into the context makes it accessible by every test
		this.suite.context.set({
			utils: this.require('common/utils'),
			sshKeyPath: join(homedir(), 'id'),
			link: `${this.suite.options.balenaOS.config.uuid.slice(0, 7)}.local`,
			worker: new Worker(this.suite.deviceType.slug, this.getLogger()),
		});

		// Network definitions - here we check what network configuration is selected for the DUT for the suite, and add the appropriate configuration options (e.g wifi credentials)
		if (this.suite.options.balenaOS.network.wired === true) {
			this.suite.options.balenaOS.network.wired = {
				nat: true,
			};
		} else {
			delete this.suite.options.balenaOS.network.wired;
		}
		if (this.suite.options.balenaOS.network.wireless === true) {
			this.suite.options.balenaOS.network.wireless = {
				ssid: this.suite.options.id,
				psk: `${this.suite.options.id}_psk`,
				nat: true,
			};
		} else {
			delete this.suite.options.balenaOS.network.wireless;
		}

		// Create an instance of the balenOS object, containing information such as device type, and config.json options
		this.suite.context.set({
			os: new BalenaOS(
				{
					deviceType: this.suite.deviceType.slug,
					network: this.suite.options.balenaOS.network,
					configJson: {
						uuid: this.suite.options.balenaOS.config.uuid,
						os: {
							sshKeys: [
								await this.context
									.get()
									.utils.createSSHKey(this.context.get().sshKeyPath),
							],
						},
						// persistentLogging is managed by the supervisor and only read at first boot
						persistentLogging: true,
						// Set local mode so we can perform local pushes of containers to the DUT
						localMode: true,
					},
				},
				this.getLogger(),
			),
		});

		// Register a teardown function execute at the end of the test, regardless of a pass or fail
		this.suite.teardown.register(() => {
			this.log('Worker teardown');
			return this.context.get().worker.teardown();
		});

		this.log('Setting up worker');

		// Retrieving journalctl logs
		this.suite.teardown.register(async () => {
			await this.context.get().worker.archiveLogs(this.id, this.context.get().link);
		});

		// Create network AP on testbot
		await this.context
			.get()
			.worker.network(this.suite.options.balenaOS.network);

		// Unpack OS image .gz
		await this.context.get().os.fetch();

		// Configure OS image
		await this.context.get().os.configure();

		// Flash the DUT
		await this.context.get().worker.off(); // Ensure DUT is off before starting tests
		await this.context.get().worker.flash(this.context.get().os.image.path);
		await this.context.get().worker.on();

		this.log('Waiting for device to be reachable');
		assert.equal(
			await this.context
				.get()
				.worker.executeCommandInHostOS(
					'cat /etc/hostname',
					this.context.get().link,
				),
			this.context.get().link.split('.')[0],
			'Device should be reachable',
		);
	},
	tests: [
		'./tests/fingerprint',
		'./tests/os-release',
		'./tests/chrony',
		'./tests/kernel-overlap',
		'./tests/bluetooth',
		'./tests/healthcheck',
		'./tests/variables',
		'./tests/led',
		'./tests/config-json',
		'./tests/boot-splash',
		'./tests/connectivity',
		'./tests/engine-healthcheck',
		'./tests/udev',
		'./tests/device-tree',
	],
};
<commit_msg>tests: Register teardown only when DUT is reachable<commit_after>/*
 * Copyright 2018 balena
 *
 * @license Apache-2.0
 */

'use strict';

const assert = require('assert');
const fse = require('fs-extra');
const { join } = require('path');
const { homedir } = require('os');

module.exports = {
	title: 'Unmanaged BalenaOS release suite',
	run: async function(test) {
		// The worker class contains methods to interact with the DUT, such as flashing, or executing a command on the device
		const Worker = this.require('common/worker');
		// The balenaOS class contains information on the OS image to be flashed, and methods to configure it
		const BalenaOS = this.require('components/os/balenaos');

		await fse.ensureDir(this.suite.options.tmpdir);

		// The suite contex is an object that is shared across all tests. Setting something into the context makes it accessible by every test
		this.suite.context.set({
			utils: this.require('common/utils'),
			sshKeyPath: join(homedir(), 'id'),
			link: `${this.suite.options.balenaOS.config.uuid.slice(0, 7)}.local`,
			worker: new Worker(this.suite.deviceType.slug, this.getLogger()),
		});

		// Network definitions - here we check what network configuration is selected for the DUT for the suite, and add the appropriate configuration options (e.g wifi credentials)
		if (this.suite.options.balenaOS.network.wired === true) {
			this.suite.options.balenaOS.network.wired = {
				nat: true,
			};
		} else {
			delete this.suite.options.balenaOS.network.wired;
		}
		if (this.suite.options.balenaOS.network.wireless === true) {
			this.suite.options.balenaOS.network.wireless = {
				ssid: this.suite.options.id,
				psk: `${this.suite.options.id}_psk`,
				nat: true,
			};
		} else {
			delete this.suite.options.balenaOS.network.wireless;
		}

		// Create an instance of the balenOS object, containing information such as device type, and config.json options
		this.suite.context.set({
			os: new BalenaOS(
				{
					deviceType: this.suite.deviceType.slug,
					network: this.suite.options.balenaOS.network,
					configJson: {
						uuid: this.suite.options.balenaOS.config.uuid,
						os: {
							sshKeys: [
								await this.context
									.get()
									.utils.createSSHKey(this.context.get().sshKeyPath),
							],
						},
						// persistentLogging is managed by the supervisor and only read at first boot
						persistentLogging: true,
						// Set local mode so we can perform local pushes of containers to the DUT
						localMode: true,
					},
				},
				this.getLogger(),
			),
		});

		// Register a teardown function execute at the end of the test, regardless of a pass or fail
		this.suite.teardown.register(() => {
			this.log('Worker teardown');
			return this.context.get().worker.teardown();
		});

		this.log('Setting up worker');

		// Create network AP on testbot
		await this.context
			.get()
			.worker.network(this.suite.options.balenaOS.network);

		// Unpack OS image .gz
		await this.context.get().os.fetch();

		// Configure OS image
		await this.context.get().os.configure();

		// Flash the DUT
		await this.context.get().worker.off(); // Ensure DUT is off before starting tests
		await this.context.get().worker.flash(this.context.get().os.image.path);
		await this.context.get().worker.on();

		this.log('Waiting for device to be reachable');
		assert.equal(
			await this.context
				.get()
				.worker.executeCommandInHostOS(
					'cat /etc/hostname',
					this.context.get().link,
				),
			this.context.get().link.split('.')[0],
			'Device should be reachable',
		);

    // Retrieving journalctl logs: register teardown after device is reachable
    this.suite.teardown.register(async () => {
			await this.context.get().worker.archiveLogs(this.id, this.context.get().link);
		});

	},
	tests: [
		'./tests/fingerprint',
		'./tests/os-release',
		'./tests/chrony',
		'./tests/kernel-overlap',
		'./tests/bluetooth',
		'./tests/healthcheck',
		'./tests/variables',
		'./tests/led',
		'./tests/config-json',
		'./tests/boot-splash',
		'./tests/connectivity',
		'./tests/engine-healthcheck',
		'./tests/udev',
		'./tests/device-tree',
	],
};
<|endoftext|>


<commit_before>
maxId = 0;
maxColorId = 0;

mainFoodChain = JSON.parse('[ { "type": "family", "id": 1, "gators": [ { "type": "gator", "id": 2, "colorId": 1 } ], "foodChain": [ { "type": "egg", "id": 3, "colorId": 1 }, { "type": "family", "id": 4, "gators": [ { "type": "gator", "id": 6, "colorId": 2 }, { "type": "gator", "id": 7, "colorId": 3 } ], "foodChain": [ { "type": "egg", "id": 8, "colorId": 3 } ] }, { "type": "family", "id": 5, "gators": [ { "type": "gator", "id": 9, "colorId": 4 }, { "type": "gator", "id": 10, "colorId": 5 } ], "foodChain": [ { "type": "egg", "id": 11, "colorId": 4 } ] } ] }, { "type": "family", "id": 12, "gators": [ { "type": "gator", "id": 13, "colorId": 6 }, { "type": "gator", "id": 14, "colorId": 7 } ], "foodChain": [ { "type": "egg", "id": 15, "colorId": 6 } ] }]');

function getMaxIds(foodChain){
  for (var i = 0; i < foodChain.length; i++) {
    if(foodChain[i].id>maxId){
      maxId = foodChain[i].id;
    }

    if(foodChain[i].type=="family"){
      getMaxIds(foodChain[i].foodChain);

      for (var j = 0; j < foodChain[i].gators.length; j++) {
        if(foodChain[i].gators[j].colorId > maxColorId){
          maxColorId = foodChain[i].gators[j].colorId;
        }

        if(foodChain[i].gators[j].id>maxId){
          maxId = foodChain[i].id;
        }
      }
    }else{
      if(foodChain[i].colorId > maxColorId){
        maxColorId = foodChain[i].colorId;
      }
    }
  }
}

function reduce(foodChain){
  if(foodChain[0].gators.length>0){//alpha reduce or done
    gator = foodChain[0].gators[0];
    food = families[1];
    replaceEggs(foodChain[0], gator.colorId, food);
    //search through eater's foodChain recursively and replace eggs with a matching
  }else{//eta reduce

  }
}

function isEqual(foodChain1, foodChain2) {
	if (foodChain1.length != foodChain2.length) return 0;
	for (var i = 0; i < foodChain1.length; i++)
		if (foodChain1[i].type != foodChain2[i].type) return 0;
	var eggMap = {};
	var gatorMap = {};
	// Iterate over families and eggs (elements)
	for (var i = 0; i < foodChain1.length; i++) {
		var element1 = foodChain1[i];
		var element2 = foodChain2[i];
		if (element1.type == "egg") {
			if (element1.colorid in eggMap && eggMap[element1.colorid] != element2.colorid)
				return 0;
			else if (!(element1 in eggMap))
				eggMap[element1.colorid] = element2.colorid;
		}
		else if (element1.type == "family") {
			if (element1.gators.length != element2.gators.length) return 0;
			if (element1.foodChain.length != element2.foodChain.length) return 0;
			// Iterate over gators
			var gators1 = element1.gators;
			var gators2 = element2.gators;
			for (var i = 0; i < gators1.length(); i++) {
				if (gators1[i].colorid in gatorMap) && gatorMap[gators1[i].colorid] != gators2[i].colorid)
					return 0;
				else if (!(gators1[i] in gatorMap))
					gatorMap[gators1[i].colorid] = gators2[i].colorid;
			}
			// Recurse for sub-foodChains
			if (!isEqual(element1.foodChain, element2.foodChain)) return 0;
		}
	}
	return 1;
}

function replaceEggs(family, colorId, newFamily){
  for (var i = 0; i < family.foodChain.length; i++) {
    if(family.foodChain[i].type=="family"){
      replaceEggs(family.foodChain[i], colorId, newFamily);
    }else{
      family.foodChain[i].type="family";
    }
  }
}

function copyFamily(family, colorMap){

  newFamily = {type:"family", id:maxId++, gators:[], foodChain:[]};//create blank family with new Id

  for (var i=0; i < family.gators.length; i++){//add each gator over with new Id's and new color Id's
    newFamily.gators[i]={type:"gator", id:maxId++, colorId:maxColorId++};
    colorMap[family.gators[i].colorId]=maxColorId;//mark that this colorId is changed for all children eggs
  }

  for (var i=0; i < family.foodChain.length; i++){
    if(family.foodChain[i].type=="family"){
      newFamily.foodChain[i] = copyFamily(family.foodChain[i], colorMap);
    }else{
      newFamily.foodChain[i] = {type:"egg", id:maxId++};

      if(family.foodChain[i].colorId in colorMap){
        newFamily.foodChain[i].colorId = colorMap[family.foodChain[i].colorId];
      }else{
        newFamily.foodChain[i].colorId = family.foodChain[i].colorId;
      }
    }
  }
  return newFamily;

}

getMaxIds(mainFoodChain);
console.log(JSON.stringify(copyFamily(mainFoodChain[1], {})));
console.log(maxId);
console.log(maxColorId);

/*
family:
  type="family"
  id
  gators = []//gators
  foodChain = []//eggs or families

gator:
  type="gator"
  id
  colorId

egg:
  type="egg"
  id
  colorId
<<<<<<< HEAD

*/
<commit_msg>huge progress.  can successfully reduce the NOT example.  will move onto creating other examples and testing.<commit_after>
maxId = 0;
maxColorId = 0;

mainFoodChain = JSON.parse('[ { "type": "family", "id": 1, "gators": [ { "type": "gator", "id": 2, "colorId": 1 } ], "foodChain": [ { "type": "egg", "id": 3, "colorId": 1 }, { "type": "family", "id": 4, "gators": [ { "type": "gator", "id": 6, "colorId": 2 }, { "type": "gator", "id": 7, "colorId": 3 } ], "foodChain": [ { "type": "egg", "id": 8, "colorId": 3 } ] }, { "type": "family", "id": 5, "gators": [ { "type": "gator", "id": 9, "colorId": 4 }, { "type": "gator", "id": 10, "colorId": 5 } ], "foodChain": [ { "type": "egg", "id": 11, "colorId": 4 } ] } ] }, { "type": "family", "id": 12, "gators": [ { "type": "gator", "id": 13, "colorId": 6 }, { "type": "gator", "id": 14, "colorId": 7 } ], "foodChain": [ { "type": "egg", "id": 15, "colorId": 7 } ] }]');

function getMaxIds(foodChain){
  for (var i = 0; i < foodChain.length; i++) {
    if(foodChain[i].id>maxId){
      maxId = foodChain[i].id;
    }

    if(foodChain[i].type=="family"){
      getMaxIds(foodChain[i].foodChain);

      for (var j = 0; j < foodChain[i].gators.length; j++) {
        if(foodChain[i].gators[j].colorId > maxColorId){
          maxColorId = foodChain[i].gators[j].colorId;
        }

        if(foodChain[i].gators[j].id>maxId){
          maxId = foodChain[i].id;
        }
      }
    }else{
      if(foodChain[i].colorId > maxColorId){
        maxColorId = foodChain[i].colorId;
      }
    }
  }
}

function reduce(foodChain){
  if(foodChain[0].gators.length>0){//alpha reduce or done
    if(foodChain.length==1){
      console.log("donezo");
      return 0;
    }
    console.log("alpha");

    gator = foodChain[0].gators[0];
    food = foodChain[1];
    replaceEggs(foodChain[0], gator.colorId, food);
    foodChain.splice(1, 1);//removes the food
    foodChain[0].gators.splice(0,1);//removes the gator
  }else{//eta reduce
    console.log("eta");
    Array.prototype.unshift.apply(foodChain, foodChain.shift().foodChain);
  }
  return 1;
}

function isEqual(foodChain1, foodChain2) {
	if (foodChain1.length != foodChain2.length) return 0;
	for (var i = 0; i < foodChain1.length; i++)
		if (foodChain1[i].type != foodChain2[i].type) return 0;
	var eggMap = {};
	var gatorMap = {};
	// Iterate over families and eggs (elements)
	for (var i = 0; i < foodChain1.length; i++) {
		var element1 = foodChain1[i];
		var element2 = foodChain2[i];
		if (element1.type == "egg") {
			if (element1.colorid in eggMap && eggMap[element1.colorid] != element2.colorid)
				return 0;
			else if (!(element1 in eggMap))
				eggMap[element1.colorid] = element2.colorid;
		}
		else if (element1.type == "family") {
			if (element1.gators.length != element2.gators.length) return 0;
			if (element1.foodChain.length != element2.foodChain.length) return 0;
			// Iterate over gators
			var gators1 = element1.gators;
			var gators2 = element2.gators;
			for (var i = 0; i < gators1.length(); i++) {
				if (gators1[i].colorid in gatorMap) && gatorMap[gators1[i].colorid] != gators2[i].colorid)
					return 0;
				else if (!(gators1[i] in gatorMap))
					gatorMap[gators1[i].colorid] = gators2[i].colorid;
			}
			// Recurse for sub-foodChains
			if (!isEqual(element1.foodChain, element2.foodChain)) return 0;
		}
	}
	return 1;
}

function replaceEggs(family, colorId, newFamily){
  for (var i = 0; i < family.foodChain.length; i++) {
    if(family.foodChain[i].type=="family"){
      replaceEggs(family.foodChain[i], colorId, newFamily);
    }else{
      if(family.foodChain[i].colorId==colorId){
        family.foodChain[i] = copyFamily(newFamily, {});
      }
    }
  }
}

function copyFamily(family, colorMap){
  newFamily = {type:"family", id:++maxId, gators:[], foodChain:[]};//create blank family with new Id

  for (var i=0; i < family.gators.length; i++){//add each gator over with new Id's and new color Id's
    newFamily.gators[i]={type:"gator", id:++maxId, colorId:++maxColorId};
    colorMap[family.gators[i].colorId]=maxColorId;//mark that this colorId is changed for all children eggs
  }

  for (var i=0; i < family.foodChain.length; i++){
    if(family.foodChain[i].type=="family"){
      newFamily.foodChain[i] = copyFamily(family.foodChain[i], colorMap);
    }else{
      newFamily.foodChain[i] = {type:"egg", id:++maxId};

      if(family.foodChain[i].colorId in colorMap){
        newFamily.foodChain[i].colorId = colorMap[family.foodChain[i].colorId];
      }else{
        newFamily.foodChain[i].colorId = family.foodChain[i].colorId;
      }
    }
  }
  return newFamily;

}

getMaxIds(mainFoodChain);

console.log(JSON.stringify(mainFoodChain));
reduce(mainFoodChain);
console.log(JSON.stringify(mainFoodChain));
reduce(mainFoodChain);
console.log(JSON.stringify(mainFoodChain));
reduce(mainFoodChain);
console.log(JSON.stringify(mainFoodChain));
reduce(mainFoodChain);
console.log(JSON.stringify(mainFoodChain));
reduce(mainFoodChain);
console.log(JSON.stringify(mainFoodChain));
reduce(mainFoodChain);
console.log(JSON.stringify(mainFoodChain));
reduce(mainFoodChain);
console.log(JSON.stringify(mainFoodChain));
reduce(mainFoodChain);
console.log(JSON.stringify(mainFoodChain));

console.log(maxColorId);

/*
family:
  type="family"
  id
  gators = []//gators
  foodChain = []//eggs or families

gator:
  type="gator"
  id
  colorId

egg:
  type="egg"
  id
  colorId
*/
<|endoftext|>


<commit_before>define('login',
    ['cache', 'capabilities', 'defer', 'jquery', 'log', 'notification',
     'polyfill', 'settings', 'site_config', 'storage', 'underscore', 'urls',
     'user', 'utils', 'requests', 'z'],
    function(cache, capabilities, defer, $, log, notification,
             polyfill, settings, siteConfig, storage, _, urls,
             user, utils, requests, z) {

    var console = log('login');
    var fxa_popup;
    var retainPopup;
    var pending_logins = [];
    var packaged_origin = "app://packaged." + window.location.host;
    function oncancel() {
        console.log('Login cancelled');
        z.page.trigger('login_cancel');
        _.invoke(pending_logins, 'reject');
        pending_logins = [];
    }

    function signOutNotification() {
        notification.notification({message: gettext('You have been signed out')});
    }

    function signInNotification() {
        notification.notification({message: gettext('You have been signed in')});
    }

    function logOut() {
        cache.flush_signed();
        user.clear_token();

        z.body.removeClass('logged-in');
        z.page.trigger('reload_chrome').trigger('before_logout');
        if (!z.context.dont_reload_on_login) {
            z.page.trigger('logged_out');
            signOutNotification();
            require('views').reload();
        } else {
            console.log('Reload on logout aborted by current view');
        }
    }

    function logIn(data) {
        var should_reload = !user.logged_in();

        user.set_token(data.token, data.settings);
        user.update_permissions(data.permissions);
        user.update_apps(data.apps);
        console.log('Login succeeded, preparing the app');

        z.body.addClass('logged-in');
        $('.loading-submit').removeClass('loading-submit');
        z.page.trigger('reload_chrome').trigger('logged_in');

        function resolve_pending() {
            _.invoke(pending_logins, 'resolve');
            pending_logins = [];
        }

        if (should_reload && !z.context.dont_reload_on_login) {
            require('views').reload().done(function() {
                resolve_pending();
                signInNotification();
            });
        } else {
            console.log('Reload on login aborted by current view');
        }
    }

    function logInFailed(message) {
        message = message || gettext('Sign in failed');
        notification.notification({message: message});
        $('.loading-submit').removeClass('loading-submit');
        z.page.trigger('login_fail');
        _.invoke(pending_logins, 'reject');
        pending_logins = [];
    }

    z.body.on('click', '.persona', function(e) {
        e.preventDefault();

        var $this = $(this);
        $this.addClass('loading-submit');
        startLogin({register: $this.hasClass('register')}).always(function() {
            $this.removeClass('loading-submit').trigger('blur');
        });

    }).on('click', '.logout', utils._pd(function(e) {
        requests.del(urls.api.url('logout'));

        if (capabilities.fallbackFxA()) {
            logOut();
        }
    }));

    function startLogin(options) {
        var def = defer.Deferred();
        pending_logins.push(def);
        var opt = {register: false};
        // Override our settings with the provided ones.
        _.extend(opt, options);
        if (capabilities.yulelogFxA()) {
            window.top.postMessage({type: 'fxa-request'}, packaged_origin);
        } else if (capabilities.fallbackFxA()) {
            var fxa_url = settings.fxa_auth_url;
            if (opt.register) {
                fxa_url = utils.urlparams(fxa_url, {action: 'signup'});
            }

            if (opt.popupWindow) {
                console.log('Changing location of supplied window to', fxa_url);
                fxa_popup = opt.popupWindow;
                fxa_popup.location = fxa_url;
                retainPopup = true;
            } else {
                console.log('Opening new login window');
                fxa_popup = utils.openWindow({url: fxa_url});
                retainPopup = false;
            }

            // The same-origin policy prevents us from listening to events to
            // know when the cross-origin FxA popup was closed. And we can't
            // listen to `focus` on the main window because, unlike Chrome,
            // Firefox does not fire `focus` when a popup is closed (presumably
            // because the page never truly lost focus).
            var popup_interval = setInterval(function() {
                 if (!fxa_popup || fxa_popup.closed) {
                    // The oncancel was cancelling prematurely when window is closed,
                    // prevents review dialog from popping up on login success.
                    // oncancel();
                    $('.loading-submit').removeClass('loading-submit').trigger('blur');
                    clearInterval(popup_interval);
                } else {
                    // If login dialog ends up behind another window, we want
                    // to bring it to the front, otherwise it looks like login
                    // is stuck / broken.
                    fxa_popup.focus();
                }
            }, 150);
        } else {
            console.log('Requesting login from Native FxA');
            navigator.mozId.request({oncancel: oncancel});
        }
        return def.promise();
    }

    function gotVerifiedEmail(assertion) {
        console.log('Got assertion from FxA');
        var aud;
        if (capabilities.yulelogFxA()) {
            aud = packaged_origin;
        } else {
            aud = window.location.origin;
        }
        var data = {
            assertion: assertion,
            audience: aud,
        };

        z.page.trigger('before_login');

        requests.post(urls.api.url('login'), data)
                .done(logIn)
                .fail(function(jqXHR, textStatus, error) {
            console.warn('Assertion verification failed!', textStatus, error);

            var err = jqXHR.responseText;
            // Catch-all for XHR errors otherwise we'll trigger a notification
            // with its message as one of the error templates.
            if (jqXHR.status != 200) {
                err = gettext('FxA login failed. A server error was encountered.');
            }
            logInFailed(err);
        });
    }

    function startNativeFxA() {
        var email = user.get_setting('email') || '';
        if (email) {
            console.log('Detected user', email);
        } else {
            console.log('No previous user detected');
        }
        console.log('Calling navigator.mozId.watch');
        navigator.mozId.watch({
            wantIssuer: 'firefox-accounts',
            loggedInUser: email,
            // This lets us change the cursor for the "Sign in" link.
            onready: function() {z.body.addClass('persona-loaded');},
            onlogin: gotVerifiedEmail,
            onlogout: function() {
                z.body.removeClass('logged-in');
                z.page.trigger('reload_chrome').trigger('logout');
            }
        });
    }

    function registerFxAPostMessageHandler() {
        window.addEventListener('message', function (msg) {
            var valid_origins = [settings.api_url, window.location.origin];
            if (msg.data && msg.data.auth_code &&
                    valid_origins.indexOf(msg.origin) !== -1) {
                handle_fxa_login(msg.data.auth_code);
            }
        });
    }

    siteConfig.promise.done(function(data) {
        if (capabilities.yulelogFxA()) {
            console.log("setting up yulelog-fxa");
            window.addEventListener('message', function (msg) {
                if (!msg.data || !msg.data.type || msg.origin !== packaged_origin) {
                    return;
                }
                console.log("fxa message " + JSON.stringify(msg.data));
                if (msg.data.type === 'fxa-login') {
                    gotVerifiedEmail(msg.data.assertion);
                } else if (msg.data.type === 'fxa-logout') {
                    logOut();
                } else if (msg.data.type === 'fxa-cancel') {
                    oncancel();
                }
            });
            window.top.postMessage({type: 'fxa-watch',
                                    email: user.get_setting('email') || ''},
                                   packaged_origin);
        } else if (!capabilities.fallbackFxA()) {
            startNativeFxA();
        } else {
            // This lets us change the cursor for the "Sign in" link.
            z.body.addClass('persona-loaded');
            // Register the "message" handler here to avoid it being registered
            // multiple times.
            registerFxAPostMessageHandler();
        }
    });

    var fxa_auth_url_key = 'fxa_auth_url';
    function save_fxa_auth_url(url) {
        storage.setItem(fxa_auth_url_key, url);
    }

    function get_fxa_auth_url() {
        return storage.getItem(fxa_auth_url_key);
    }

    function handle_fxa_login(auth_code, state) {
        var loginData = {
            'auth_response': auth_code,
            'state': state || settings.fxa_auth_state,
        };
        // Check for a host secific client_id override. See site_config.js for
        // more info.
        var clientIdOverride = siteConfig.fxa_client_id_for_origin();
        if (clientIdOverride) {
            loginData.client_id = clientIdOverride;
        }
        z.page.trigger('before_login');
        requests.post(urls.api.url('fxa-login'), loginData)
                .done(logIn)
                .fail(function(jqXHR, textStatus, error) {
            console.warn('FxA login failed', jqXHR, textStatus, error);
            logInFailed();
        }).always(function() {
            if (fxa_popup && !retainPopup) {
                console.log('Closing login popup');
                fxa_popup.close();
            } else if (fxa_popup) {
                console.log('Keeping window around for re-use');
            }
        });
    }

    return {
        login: startLogin,
        get_fxa_auth_url: get_fxa_auth_url,
        handle_fxa_login: handle_fxa_login,
    };
});
<commit_msg>Move interval so it applies to the popup created by login.js (bug 1124790)<commit_after>define('login',
    ['cache', 'capabilities', 'defer', 'jquery', 'log', 'notification',
     'polyfill', 'settings', 'site_config', 'storage', 'underscore', 'urls',
     'user', 'utils', 'requests', 'z'],
    function(cache, capabilities, defer, $, log, notification,
             polyfill, settings, siteConfig, storage, _, urls,
             user, utils, requests, z) {

    var console = log('login');
    var fxa_popup;
    var retainPopup;
    var pending_logins = [];
    var packaged_origin = "app://packaged." + window.location.host;
    function oncancel() {
        console.log('Login cancelled');
        z.page.trigger('login_cancel');
        _.invoke(pending_logins, 'reject');
        pending_logins = [];
    }

    function signOutNotification() {
        notification.notification({message: gettext('You have been signed out')});
    }

    function signInNotification() {
        notification.notification({message: gettext('You have been signed in')});
    }

    function logOut() {
        cache.flush_signed();
        user.clear_token();

        z.body.removeClass('logged-in');
        z.page.trigger('reload_chrome').trigger('before_logout');
        if (!z.context.dont_reload_on_login) {
            z.page.trigger('logged_out');
            signOutNotification();
            require('views').reload();
        } else {
            console.log('Reload on logout aborted by current view');
        }
    }

    function logIn(data) {
        var should_reload = !user.logged_in();

        user.set_token(data.token, data.settings);
        user.update_permissions(data.permissions);
        user.update_apps(data.apps);
        console.log('Login succeeded, preparing the app');

        z.body.addClass('logged-in');
        $('.loading-submit').removeClass('loading-submit');
        z.page.trigger('reload_chrome').trigger('logged_in');

        function resolve_pending() {
            _.invoke(pending_logins, 'resolve');
            pending_logins = [];
        }

        if (should_reload && !z.context.dont_reload_on_login) {
            require('views').reload().done(function() {
                resolve_pending();
                signInNotification();
            });
        } else {
            console.log('Reload on login aborted by current view');
        }
    }

    function logInFailed(message) {
        message = message || gettext('Sign in failed');
        notification.notification({message: message});
        $('.loading-submit').removeClass('loading-submit');
        z.page.trigger('login_fail');
        _.invoke(pending_logins, 'reject');
        pending_logins = [];
    }

    z.body.on('click', '.persona', function(e) {
        e.preventDefault();

        var $this = $(this);
        $this.addClass('loading-submit');
        startLogin({register: $this.hasClass('register')}).always(function() {
            $this.removeClass('loading-submit').trigger('blur');
        });

    }).on('click', '.logout', utils._pd(function(e) {
        requests.del(urls.api.url('logout'));

        if (capabilities.fallbackFxA()) {
            logOut();
        }
    }));

    function startLogin(options) {
        var def = defer.Deferred();
        pending_logins.push(def);
        var opt = {register: false};
        // Override our settings with the provided ones.
        _.extend(opt, options);
        if (capabilities.yulelogFxA()) {
            window.top.postMessage({type: 'fxa-request'}, packaged_origin);
        } else if (capabilities.fallbackFxA()) {
            var fxa_url = settings.fxa_auth_url;
            if (opt.register) {
                fxa_url = utils.urlparams(fxa_url, {action: 'signup'});
            }

            if (opt.popupWindow) {
                console.log('Changing location of supplied window to', fxa_url);
                fxa_popup = opt.popupWindow;
                fxa_popup.location = fxa_url;
                retainPopup = true;
            } else {
                console.log('Opening new login window');
                fxa_popup = utils.openWindow({url: fxa_url});
                retainPopup = false;

                // The same-origin policy prevents us from listening to events to
                // know when the cross-origin FxA popup was closed. And we can't
                // listen to `focus` on the main window because, unlike Chrome,
                // Firefox does not fire `focus` when a popup is closed (presumably
                // because the page never truly lost focus).
                var popup_interval = setInterval(function() {
                     if (!fxa_popup || fxa_popup.closed) {
                        // The oncancel was cancelling prematurely when window is closed,
                        // prevents review dialog from popping up on login success.
                        // oncancel();
                        $('.loading-submit').removeClass('loading-submit').trigger('blur');
                        clearInterval(popup_interval);
                    }
                }, 150);
            }

        } else {
            console.log('Requesting login from Native FxA');
            navigator.mozId.request({oncancel: oncancel});
        }
        return def.promise();
    }

    function gotVerifiedEmail(assertion) {
        console.log('Got assertion from FxA');
        var aud;
        if (capabilities.yulelogFxA()) {
            aud = packaged_origin;
        } else {
            aud = window.location.origin;
        }
        var data = {
            assertion: assertion,
            audience: aud,
        };

        z.page.trigger('before_login');

        requests.post(urls.api.url('login'), data)
                .done(logIn)
                .fail(function(jqXHR, textStatus, error) {
            console.warn('Assertion verification failed!', textStatus, error);

            var err = jqXHR.responseText;
            // Catch-all for XHR errors otherwise we'll trigger a notification
            // with its message as one of the error templates.
            if (jqXHR.status != 200) {
                err = gettext('FxA login failed. A server error was encountered.');
            }
            logInFailed(err);
        });
    }

    function startNativeFxA() {
        var email = user.get_setting('email') || '';
        if (email) {
            console.log('Detected user', email);
        } else {
            console.log('No previous user detected');
        }
        console.log('Calling navigator.mozId.watch');
        navigator.mozId.watch({
            wantIssuer: 'firefox-accounts',
            loggedInUser: email,
            // This lets us change the cursor for the "Sign in" link.
            onready: function() {z.body.addClass('persona-loaded');},
            onlogin: gotVerifiedEmail,
            onlogout: function() {
                z.body.removeClass('logged-in');
                z.page.trigger('reload_chrome').trigger('logout');
            }
        });
    }

    function registerFxAPostMessageHandler() {
        window.addEventListener('message', function (msg) {
            var valid_origins = [settings.api_url, window.location.origin];
            if (msg.data && msg.data.auth_code &&
                    valid_origins.indexOf(msg.origin) !== -1) {
                handle_fxa_login(msg.data.auth_code);
            }
        });
    }

    siteConfig.promise.done(function(data) {
        if (capabilities.yulelogFxA()) {
            console.log("setting up yulelog-fxa");
            window.addEventListener('message', function (msg) {
                if (!msg.data || !msg.data.type || msg.origin !== packaged_origin) {
                    return;
                }
                console.log("fxa message " + JSON.stringify(msg.data));
                if (msg.data.type === 'fxa-login') {
                    gotVerifiedEmail(msg.data.assertion);
                } else if (msg.data.type === 'fxa-logout') {
                    logOut();
                } else if (msg.data.type === 'fxa-cancel') {
                    oncancel();
                }
            });
            window.top.postMessage({type: 'fxa-watch',
                                    email: user.get_setting('email') || ''},
                                   packaged_origin);
        } else if (!capabilities.fallbackFxA()) {
            startNativeFxA();
        } else {
            // This lets us change the cursor for the "Sign in" link.
            z.body.addClass('persona-loaded');
            // Register the "message" handler here to avoid it being registered
            // multiple times.
            registerFxAPostMessageHandler();
        }
    });

    var fxa_auth_url_key = 'fxa_auth_url';
    function save_fxa_auth_url(url) {
        storage.setItem(fxa_auth_url_key, url);
    }

    function get_fxa_auth_url() {
        return storage.getItem(fxa_auth_url_key);
    }

    function handle_fxa_login(auth_code, state) {
        var loginData = {
            'auth_response': auth_code,
            'state': state || settings.fxa_auth_state,
        };
        // Check for a host secific client_id override. See site_config.js for
        // more info.
        var clientIdOverride = siteConfig.fxa_client_id_for_origin();
        if (clientIdOverride) {
            loginData.client_id = clientIdOverride;
        }
        z.page.trigger('before_login');
        requests.post(urls.api.url('fxa-login'), loginData)
                .done(logIn)
                .fail(function(jqXHR, textStatus, error) {
            console.warn('FxA login failed', jqXHR, textStatus, error);
            logInFailed();
        }).always(function() {
            if (fxa_popup && !retainPopup) {
                console.log('Closing login popup');
                fxa_popup.close();
            } else if (fxa_popup) {
                console.log('Keeping window around for re-use');
            }
        });
    }

    return {
        login: startLogin,
        get_fxa_auth_url: get_fxa_auth_url,
        handle_fxa_login: handle_fxa_login,
    };
});
<|endoftext|>


<commit_before>
class MyToggle extends React.Component {

	constructor(props) {
		super(props);
		this.handleToggleClick = this.handleToggleClick.bind(this);
		this.state = {
			isToggleOn: false
		};
	}

	handleToggleClick(e) {

		this.setState(
			function(prevState) {
				return ({isToggleOn: !prevState.isToggleOn})
			}
		);
	}

	render() {
		let button = null;

		if(this.props.hide) {
			return null; // Return null stops the component from being rendered.
		}

		if(this.props.showAsButton){
			button = <button onClick={this.handleToggleClick} >
					     {this.state.isToggleOn ? 'State: ON' : 'State: OFF'}
				     </button>;

		} else {

			button =
					     {this.state.isToggleOn ? 'State: ON' : 'State: OFF'}
				     ;

		}

		return (
 {button}
);

	}
}

//MyActionHandler Written using a function
var MyActionHandler = () => {

    //Function to handle the click event
	const handleClick = (e) => {
    	e.preventDefault();
    	console.log('The link was clicked. THIS: '+ this);
    };

	return (
		Click Me
	);
};

//Written using a class. Note the this.handleClick call
class MyActionHandlerClass extends React.Component {
	constructor(props) {
		super(props);
		this.handleClick1 = this.handleClick1.bind(this); //To ensure this get bound with handleclick1
	}

	handleClick1(e) {
    	e.preventDefault();
    	console.log('The link CLICK ME HERE was clicked. THIS: '+ this);
    }

    render() {
		return (
			Click Me Here
		);
    }
}

class MyClock extends React.Component {
	constructor(props) {
		super(props);
		this.state = {date: new Date()};
	}

	render() {
		return (

 CLOCK TIME: {this.state.date.toLocaleTimeString()}

			);
	}

	componentDidMount() {
		setInterval (
			() => {this.tick()},
			1000);
	}

	tick() {
	    this.setState (
		    {
	    	  date: new Date()
	    	}
    	);
  	}

}

class MyList extends React.Component {
	constructor(props) {
		super(props);
	}

	render() {

		const numbers = this.props.numbers;
		const listItems = numbers.map(
							(x) =>

 Value: {x}

						   );

		return (

				{listItems}

			);
	}

}

class MyCuteLittleForm extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			nameOfPerson: 'Enter name here',
			address: 'Enter address here'
		};

		this.handleOnChangeNameOfPerson = this.handleOnChangeNameOfPerson.bind(this);
		this.handleOnChangeAddress = this.handleOnChangeAddress.bind(this);
		this.handleSubmit = this.handleSubmit.bind(this);
	}

	handleSubmit(e) {
		alert("Form has been submitted, with name: "+ this.state.nameOfPerson + " address: "+ this.state.address);
		e.preventDefault();

	}

	handleOnChangeNameOfPerson(e) {
		this.setState({nameOfPerson: e.target.value.toUpperCase()});
	}

	handleOnChangeAddress(e) {
		this.setState({address: e.target.value.toUpperCase()});
	}

	render() {
		const formView =
			<form onSubmit={this.handleSubmit}>

					Name:
					<input type="text" value = {this.state.nameOfPerson} onChange = {this.handleOnChangeNameOfPerson} />

					Address:

					<textarea value = {this.state.address} onChange = {this.handleOnChangeAddress} />

				<input type="submit" value = "SUBMIT" />

			</form>

		return (

				{formView}

			);
	}

}

var MyHelloTag = () => {
	return(

Hello Clock

			<MyClock/>
			<MyActionHandler/>

			<MyActionHandlerClass/>

			<MyToggle showAsButton={true} hide={false}/>
			<MyList numbers={["First","Second","Third","Fourth","Fifth"]}/>
			<MyCuteLittleForm/>

		);
};

ReactDOM.render(
	<MyHelloTag/>,
	document.getElementById('root')
);
<commit_msg>Added STATE with Select/Option element for dropdown<commit_after>
class MyToggle extends React.Component {

	constructor(props) {
		super(props);
		this.handleToggleClick = this.handleToggleClick.bind(this);
		this.state = {
			isToggleOn: false
		};
	}

	handleToggleClick(e) {

		this.setState(
			function(prevState) {
				return ({isToggleOn: !prevState.isToggleOn})
			}
		);
	}

	render() {
		let button = null;

		if(this.props.hide) {
			return null; // Return null stops the component from being rendered.
		}

		if(this.props.showAsButton){
			button = <button onClick={this.handleToggleClick} >
					     {this.state.isToggleOn ? 'State: ON' : 'State: OFF'}
				     </button>;

		} else {

			button =
					     {this.state.isToggleOn ? 'State: ON' : 'State: OFF'}
				     ;

		}

		return (
 {button}
);

	}
}

//MyActionHandler Written using a function
var MyActionHandler = () => {

    //Function to handle the click event
	const handleClick = (e) => {
    	e.preventDefault();
    	console.log('The link was clicked. THIS: '+ this);
    };

	return (
		Click Me
	);
};

//Written using a class. Note the this.handleClick call
class MyActionHandlerClass extends React.Component {
	constructor(props) {
		super(props);
		this.handleClick1 = this.handleClick1.bind(this); //To ensure this get bound with handleclick1
	}

	handleClick1(e) {
    	e.preventDefault();
    	console.log('The link CLICK ME HERE was clicked. THIS: '+ this);
    }

    render() {
		return (
			Click Me Here
		);
    }
}

class MyClock extends React.Component {
	constructor(props) {
		super(props);
		this.state = {date: new Date()};
	}

	render() {
		return (

 CLOCK TIME: {this.state.date.toLocaleTimeString()}

			);
	}

	componentDidMount() {
		setInterval (
			() => {this.tick()},
			1000);
	}

	tick() {
	    this.setState (
		    {
	    	  date: new Date()
	    	}
    	);
  	}

}

class MyList extends React.Component {
	constructor(props) {
		super(props);
	}

	render() {

		const numbers = this.props.numbers;
		const listItems = numbers.map(
							(x) =>

 Value: {x}

						   );

		return (

				{listItems}

			);
	}

}

class MyCuteLittleForm extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			nameOfPerson: 'Enter name here',
			address: 'Enter address here',
			state: '2'
		};

		this.handleOnChangeNameOfPerson = this.handleOnChangeNameOfPerson.bind(this);
		this.handleOnChangeAddress = this.handleOnChangeAddress.bind(this);
		this.handleOnChangeState = this.handleOnChangeState.bind(this);

		this.handleSubmit = this.handleSubmit.bind(this);
	}

	handleSubmit(e) {
		alert("Form has been submitted, with name: "+ this.state.nameOfPerson + " address: "+ this.state.address);
		e.preventDefault();

	}

	handleOnChangeNameOfPerson(e) {
		this.setState({nameOfPerson: e.target.value.toUpperCase()});
	}

	handleOnChangeAddress(e) {
		this.setState({address: e.target.value.toUpperCase()});
	}

	handleOnChangeState(e) {
		this.setState({state: e.target.value});
	}

	render() {
		const formView =
			<form onSubmit={this.handleSubmit}>

					Name:
					<input type="text" value = {this.state.nameOfPerson} onChange = {this.handleOnChangeNameOfPerson} />

					Address:

					<textarea value = {this.state.address} onChange = {this.handleOnChangeAddress} />

					State:

					<select value = {this.state.state} onChange = {this.handleOnChangeState}>
						<option value="1">Maharashtra</option>
						<option value="2">UP</option>
						<option value="3">Tamil Nadu</option>
					</select>

Name: {this.state.nameOfPerson}

Address: {this.state.address}

State: {this.state.state}

				<input type="submit" value = "SUBMIT" />

			</form>

		return (

				{formView}

			);
	}

}

var MyHelloTag = () => {
	return(

Hello Clock

			<MyClock/>
			<MyActionHandler/>

			<MyActionHandlerClass/>

			<MyToggle showAsButton={true} hide={false}/>
			<MyList numbers={["First","Second","Third","Fourth","Fifth"]}/>
			<MyCuteLittleForm/>

		);
};

ReactDOM.render(
	<MyHelloTag/>,
	document.getElementById('root')
);
<|endoftext|>


<commit_before>require('jquery');

module.exports = function() {

  var contactHmrc = '/contact-hmrc',
    baseUrlRegex = new RegExp(contactHmrc + '.*'),

  updateSelectedMenuItem = function(selected) {
    $('.menu__list li').removeClass('menu__list-item--selected');
    var selectedLi = $('.menu__list a[href*='+selected+']').closest('li');
    selectedLi.addClass('menu__list-item--selected');
  },

  updateHistory = function(selected) {
    var baseUrl = window.location.href.replace(baseUrlRegex, '');
    var newUrl = baseUrl + contactHmrc + '/' + selected;
    history.pushState(selected, null, newUrl);
  },

  updateHelpContent = function(partial) {
    var ajaxUrl = '/account/contact-hmrc/partial/'+partial;
    var $contentPane = $('.help-content');
    $contentPane.load(ajaxUrl, function(response, status, xhr) {
      updateSelectedMenuItem(partial);
      initYoutubeLinks();
      applyDetailsPolyfill();
    });
  },

  applyDetailsPolyfill = function(){
    window.dispatchEvent(new Event('reapplyDetails'));
  },

  supportsHistoryApi = function() {
    return !!(window.history && history.pushState);
  },

  initYoutubeLinks = function() {

    // 'Jump links' to timed points in embedded YouTube video replace the iframe contents
    var $videoIframe = $('#video-iframe');
    if ($($videoIframe).length) {
      $('.youtube-link').click(function(e) {
        e.preventDefault();
        var iframeUrl = $(this).attr('href').replace(/.*\//, 'https://www.youtube.com/embed/');
        if (iframeUrl) {
          $videoIframe.attr('src', iframeUrl);
        }
      });
    }
  },

  init = function() {

    // Allow Ajax help menu sub page switching
    if (supportsHistoryApi()) {

      $('.help-menu-link').click(function(e) {
        e.preventDefault();
        var partial = $(this).attr('href').replace(/.*\//, '');
        updateHelpContent(partial);
        updateHistory(partial);
      });

      window.addEventListener('popstate', function (e) {
        if (window.location.pathname.indexOf(contactHmrc) > -1) {
          updateHelpContent(e.state);
        }
      });
    }

    initYoutubeLinks();
  };

  return {
    init: init
  };
};
<commit_msg>[YTA-1007] Use event.target.location for popstate, to avoid problem on initial pop.<commit_after>require('jquery');

module.exports = function() {

  var contactHmrc = '/contact-hmrc',
    baseUrlRegex = new RegExp(contactHmrc + '.*'),

  updateSelectedMenuItem = function(selected) {
    $('.menu__list li').removeClass('menu__list-item--selected');
    var selectedLi = $('.menu__list a[href*='+selected+']').closest('li');
    selectedLi.addClass('menu__list-item--selected');
  },

  updateHistory = function(selected) {
    var baseUrl = window.location.href.replace(baseUrlRegex, '');
    var newUrl = baseUrl + contactHmrc + '/' + selected;
    history.pushState(null, null, newUrl);
  },

  updateHelpContent = function(partial) {
    var ajaxUrl = '/account/contact-hmrc/partial/'+partial;
    var $contentPane = $('.help-content');
    $contentPane.load(ajaxUrl, function(response, status, xhr) {
      updateSelectedMenuItem(partial);
      initYoutubeLinks();
      applyDetailsPolyfill();
    });
  },

  applyDetailsPolyfill = function(){
    window.dispatchEvent(new Event('reapplyDetails'));
  },

  supportsHistoryApi = function() {
    return !!(window.history && history.pushState);
  },

  initYoutubeLinks = function() {

    // 'Jump links' to timed points in embedded YouTube video replace the iframe contents
    var $videoIframe = $('#video-iframe');
    if ($($videoIframe).length) {
      $('.youtube-link').click(function(e) {
        e.preventDefault();
        var iframeUrl = $(this).attr('href').replace(/.*\//, 'https://www.youtube.com/embed/');
        if (iframeUrl) {
          $videoIframe.attr('src', iframeUrl);
        }
      });
    }
  },

  init = function() {

    // Allow Ajax help menu sub page switching
    if (supportsHistoryApi()) {

      $('.help-menu-link').click(function(e) {
        e.preventDefault();
        var partial = $(this).attr('href').replace(/.*\//, '');
        updateHelpContent(partial);
        updateHistory(partial);
      });

      window.addEventListener('popstate', function (e) {
        if (window.location.pathname.indexOf(contactHmrc) > -1) {
          var partial = e.target.location.pathname.replace(/.*\//, '');
          updateHelpContent(partial);
        }
      });
    }

    initYoutubeLinks();
  };

  return {
    init: init
  };
};
<|endoftext|>


<commit_before>// https://dl.dropboxusercontent.com/u/133374/hades.txt
// downloaded at 11/11/2013
// coded by sam@hades
// hades: telnet hades-talker.org 6660

var net = require('net');

var sockets = [];

var port = process.env.PORT || 8888;

var talkername = "Moosville";

/*
 * Cleans the input of carriage return, newline and control characters
 */
function cleanInput(data) {
        var newString = data.toString().replace("[\u0000-\u001f]", "");
        return newString.replace(/(\r\n|\n|\r)/gm,"");
}

/*
 * Method executed when data is received from a socket
 */
function receiveData(socket, data) {

        var cleanData = cleanInput(data);

        if(cleanData.length == 0)
                return;

        console.log("Moo [" + cleanData + "]");

		// TODO: We're just filtering out IAC commands. We should be dealing with them instead...
		// IAC commands
		var IAC = [
			1 , // Telnet IAC - Echo
			3 , // Telnet IAC - Suppress Go Ahead
			5 , // Telnet IAC - Status
			6 , // Telnet IAC - Timing Mark
			24, // Telnet IAC - Terminal Type
			31, // Telnet IAC - Window Size
			32, // Telnet IAC - Window Speed
			33, // Telnet IAC - Remote Flow Control
			34, // Telnet IAC - Linemode
			36  // Telnet IAC - Environment Variables
		];
		if (IAC.indexOf(cleanData.charCodeAt(0)) !== -1) {
			// This is IAC, not an user input
			console.log("Moo: IAC: [" + cleanData.charCodeAt(0) +"]");
		    return;
		}

        if(socket.username == undefined)
        {
                socket.username = cleanData;
                socket.write("\r\n\r\nWelcome " + socket.username + "\r\n");
        }

        if(cleanData === ".quit") {
                socket.end('Goodbye!\n');
        }
        else {
                for(var i = 0; i<sockets.length; i++) {
                        if (sockets[i] !== socket) {
                                sockets[i].write(socket.username + ": " + data);
                        }
                }
        }
}

/*
 * Method executed when a socket ends
 */
function closeSocket(socket) {
        var i = sockets.indexOf(socket);
        if (i != -1) {
                sockets.splice(i, 1);
        }
}

/*
 * Callback method executed when a new TCP socket is opened.
 */
function newSocket(socket) {
        sockets.push(socket);
        socket.write('Welcome to the '+talkername+'!\r\n\r\nGive me a name:  ');
        socket.on('data', function(data) {
                receiveData(socket, data);
        })
        socket.on('end', function() {
                closeSocket(socket);
        })
}

// Create a new server and provide a callback for when a connection occurs
var server = net.createServer(newSocket);

// Listen on defined port
server.listen(port);
<commit_msg>bugfix<commit_after>// https://dl.dropboxusercontent.com/u/133374/hades.txt
// downloaded at 11/11/2013
// coded by sam@hades
// hades: telnet hades-talker.org 6660

var net = require('net');

var sockets = [];

var port = process.env.PORT || 8888;

var talkername = "Moosville";

/*
 * Cleans the input of carriage return, newline and control characters
 */
function cleanInput(data) {
        var newString = data.toString().replace("[\u0000-\u001f]", "");
        return newString.replace(/(\r\n|\n|\r)/gm,"");
}

/*
 * Method executed when data is received from a socket
 */
function receiveData(socket, data) {

        var cleanData = cleanInput(data);

        if(cleanData.length == 0)
                return;

        console.log("Moo [" + cleanData + "]");

		// TODO: We're just filtering out IAC commands. We should be dealing with them instead...
		// IAC commands
		var IAC = [
			1 , // Telnet IAC - Echo
			3 , // Telnet IAC - Suppress Go Ahead
			5 , // Telnet IAC - Status
			6 , // Telnet IAC - Timing Mark
			24, // Telnet IAC - Terminal Type
			31, // Telnet IAC - Window Size
			32, // Telnet IAC - Window Speed
			33, // Telnet IAC - Remote Flow Control
			34, // Telnet IAC - Linemode
			36  // Telnet IAC - Environment Variables
		];
		if (IAC.indexOf(cleanData.charCodeAt(0)) !== -1) {
			// This is IAC, not an user input
			console.log("Moo: IAC: [" + cleanData.charCodeAt(0) +"]");
		    return;
		}

        if(socket.username == undefined)
        {
                socket.username = cleanData;
                socket.write("\r\n\r\nWelcome " + socket.username + "\r\n");
				return;
        }

        if(cleanData === ".quit") {
                socket.end('Goodbye!\n');
        }
        else {
                for(var i = 0; i<sockets.length; i++) {
                        if (sockets[i] !== socket) {
                                sockets[i].write(socket.username + ": " + data);
                        }
                }
        }
}

/*
 * Method executed when a socket ends
 */
function closeSocket(socket) {
        var i = sockets.indexOf(socket);
        if (i != -1) {
                sockets.splice(i, 1);
        }
}

/*
 * Callback method executed when a new TCP socket is opened.
 */
function newSocket(socket) {
        sockets.push(socket);
        socket.write('Welcome to the '+talkername+'!\r\n\r\nGive me a name:  ');
        socket.on('data', function(data) {
                receiveData(socket, data);
        })
        socket.on('end', function() {
                closeSocket(socket);
        })
}

// Create a new server and provide a callback for when a connection occurs
var server = net.createServer(newSocket);

// Listen on defined port
server.listen(port);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'

export default class hello extends Component {
  render() {
    return (

    )
  }
}

hello.propTypes = {}
hello.defaultProps = {}
<commit_msg>Delete hello.js<commit_after><|endoftext|>


<commit_before>const fs = require('fs');
const renderMenu = require('./renderMenu.js')
module.exports = (globalJSON, content) => {

    if (! globalJSON) {
        globalJSON = JSON.parse(fs.readFileSync('./docs/globalJSON.json', 'utf8'));
    }

    if (! content) {
        const wrap = (el) => {
            const html = el.html ? `<div class="sample">${JSON.parse(el.html)}</div>` : '';

            const sample = (type, content) => {
                return `

                            <button class="clipbrd-btn" data-clipboard-target="#copy_code-${type}-${el.name}"  alt="Copy to clipboard"></button>

${content}

Show ${type} sample

                `
            }

            const codeSample = el.codeExample ? sample('code', JSON.parse(el.codeExample)) : '';
            const jsSample = el.jsExample ? sample('js', JSON.parse(el.jsExample)) : '';

            return `

${JSON.parse(el.markDown)}

                   ${html} ${codeSample} ${jsSample}

            `
        }
        let type = [];
        let group = [];
        content = Object.keys(globalJSON)
                .map((el, index) => {
                    let content = '';
                    if (group.indexOf(globalJSON[el].group) === - 1) {
                        if (index != 0) {
                            content += `<hr>`;
                            content += '
';
                        }
                        content += `<div id="${globalJSON[el].group}-link" class="positon-anchor">`
                    }
                    if (type.indexOf(globalJSON[el].type) === - 1) {
                        type.push(globalJSON[el].type);
                        content += `<h2 class="type_name">${globalJSON[el].type}</h2>`;
                    }
                    content += wrap(globalJSON[el])
                    group.push(globalJSON[el].group);
                    return content;
                }).join('\n') || 'empty';
    }

    let scriptsFiles = [
        'dist/showcar-icons.js',
        'dist/showcar-tracking.js',
        'dist/showcar-ui.js',
        'docs/assets/js/highlight.min.js',
        'docs/assets/js/clipboard.min.js',
        'docs/assets/js/smooth-scroll.min.js',
        'docs/assets/js/docs.js',
    ];
    let stylesFiles = [
        'docs/assets/styles/github.min.css',
        'dist/showcar-ui.css',
        'docs/assets/styles/docs.css',
    ];

    scriptsFiles = scriptsFiles.map(script => {
        return `<script src="/showcar-ui/${script}"></script>`
    }).join('\n');

    stylesFiles = stylesFiles.map(style => {
        return `<link rel="stylesheet" href="/showcar-ui/${style}">`
    }).join('\n');
    const polyfils = require('./polyfils.js')

    const head = `
        <!DOCTYPE html>

                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width">
                <title v-text="ShowCar UI docs"></title>
                <link rel="shortcut icon" type="image/png" href="favicon.png"/>

                ${scriptsFiles}
                ${stylesFiles}

    `;

    const menu = renderMenu(globalJSON);

    const leftMenu = `

ShowCar UI

Show all code samples

                ${menu}

    `;

    const body = `

${content}

    `;

    const footer = `

    `;

    const html = head + leftMenu + body + footer;
    return html;
}

<commit_msg>add temporary title<commit_after>const fs = require('fs');
const renderMenu = require('./renderMenu.js')
module.exports = (globalJSON, content) => {

    if (! globalJSON) {
        globalJSON = JSON.parse(fs.readFileSync('./docs/globalJSON.json', 'utf8'));
    }

    if (! content) {
        const wrap = (el) => {
            const html = el.html ? `<div class="sample">${JSON.parse(el.html)}</div>` : '';

            const sample = (type, content) => {
                return `

                            <button class="clipbrd-btn" data-clipboard-target="#copy_code-${type}-${el.name}"  alt="Copy to clipboard"></button>

${content}

Show ${type} sample

                `
            }

            const codeSample = el.codeExample ? sample('code', JSON.parse(el.codeExample)) : '';
            const jsSample = el.jsExample ? sample('js', JSON.parse(el.jsExample)) : '';

            return `

${el.name}

${JSON.parse(el.markDown)}

                   ${html} ${codeSample} ${jsSample}

            `
        }
        let type = [];
        let group = [];
        content = Object.keys(globalJSON)
                .map((el, index) => {
                    let content = '';
                    if (group.indexOf(globalJSON[el].group) === - 1) {
                        if (index != 0) {
                            content += `<hr>`;
                            content += '
';
                        }
                        content += `<div id="${globalJSON[el].group}-link" class="positon-anchor">`
                    }
                    if (type.indexOf(globalJSON[el].type) === - 1) {
                        type.push(globalJSON[el].type);
                        content += `<h2 class="type_name">${globalJSON[el].type}</h2>`;
                    }
                    content += wrap(globalJSON[el])
                    group.push(globalJSON[el].group);
                    return content;
                }).join('\n') || 'empty';
    }

    let scriptsFiles = [
        'dist/showcar-icons.js',
        'dist/showcar-tracking.js',
        'dist/showcar-ui.js',
        'docs/assets/js/highlight.min.js',
        'docs/assets/js/clipboard.min.js',
        'docs/assets/js/smooth-scroll.min.js',
        'docs/assets/js/docs.js',
    ];
    let stylesFiles = [
        'docs/assets/styles/github.min.css',
        'dist/showcar-ui.css',
        'docs/assets/styles/docs.css',
    ];

    scriptsFiles = scriptsFiles.map(script => {
        return `<script src="/showcar-ui/${script}"></script>`
    }).join('\n');

    stylesFiles = stylesFiles.map(style => {
        return `<link rel="stylesheet" href="/showcar-ui/${style}">`
    }).join('\n');
    const polyfils = require('./polyfils.js')

    const head = `
        <!DOCTYPE html>

                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width">
                <title v-text="ShowCar UI docs"></title>
                <link rel="shortcut icon" type="image/png" href="favicon.png"/>

                ${scriptsFiles}
                ${stylesFiles}

    `;

    const menu = renderMenu(globalJSON);

    const leftMenu = `

ShowCar UI

Show all code samples

                ${menu}

    `;

    const body = `

${content}

    `;

    const footer = `

    `;

    const html = head + leftMenu + body + footer;
    return html;
}

<|endoftext|>


<commit_before>var OpenLayersPlusLegend = {};

OpenLayersPlusLegend = {};

OpenLayersPlusLegend.attach = function(context) {
  var data = $(context).data('openlayers');
  if (data && data.map.behaviors.openlayers_plus_behavior_legend) {
    var layer, i;
    for (i in data.openlayers.layers) {
      layer = data.openlayers.layers[i];
      if (data.map.behaviors.openlayers_plus_behavior_legend[layer.drupalID]) {
        if (!$('div.openlayers-legends', context).size()) {
          $(context).append("

");
        }
        layer.events.register('visibilitychanged', layer, OpenLayersPlusLegend.setLegend);

        // Trigger the setLegend() method at attach time. We don't know whether
        // our behavior is being called after the map has already been drawn.
        OpenLayersPlusLegend.setLegend(layer);
      }
    }
  }
};

OpenLayersPlusLegend.setLegend = function(layer) {
  // The layer param may vary based on the context from which we are called.
  layer = layer.object ? layer.object : layer;

  var name = layer.drupalID;
  var map = $(layer.map.div);
  var data = map.data('openlayers');
  var legend = data.map.behaviors.openlayers_plus_behavior_legend[name];
  var legends = $('div.openlayers-legends', map);
  if (layer.visibility && $('#openlayers-legend-'+ name, legends).size() === 0) {
    legends.append(legend);
  }
  else if (!layer.visibility) {
    $('#openlayers-legend-'+name, legends).remove();
  }
};
<commit_msg>Rewrite OL+ legend to be non-drupaly.<commit_after>var OpenLayersPlusLegend = function(opts) {
    var self = this;
    this.map = $(opts[0]).data('map');

    this.setLegend = function(layer) {
        // The layer param may vary based on the context from which we are called.
        layer = layer.object ? layer.object : layer;
        if ('legend' in layer) {
            var legend_content = layer.legend || 'your mother';
            var legends = $('div.openlayers-legends', self.map.div);
            if (layer.visibility && !('legendDiv' in layer)) {
                layer.legendDiv = $("

").append(legend_content);
                legends.append(layer.legendDiv);
            }
            else if (!layer.visibility && ('legendDiv' in layer)) {
                layer.legendDiv.remove();
                delete layer.legendDiv;
            }
        }
    };

    this.map.layers.forEach(function (layer) {
        if (!$('div.openlayers-legends', self.map.div).size()) {
            $(self.map.div).append("

");
        }
        layer.events.register('visibilitychanged', layer, self.setLegend);
        self.setLegend(layer);
    });
};
<|endoftext|>


<commit_before>$(document).ready(() => {
	let outputEl = $('#products')
	let cats = []
	let prods = []

// 	$.ajax({
//        url: 'https://new-cool-project-7d0fa.firebaseio.com/.json',
//        type: "GET",
//        cache: false,
//        dataType: "jsonp",
//        success : function(result){console.log(result);},
//        error : function(error){console.log(error);}
// });

$.ajax('https://new-cool-project-7d0fa.firebaseio.com/.json')
.then(result => {
	console.log(result)
})

	$.ajax('products.json')
		.then(products => {

			$.ajax('categories.json')

			.then((categories) => {

				cats = categories.categories
				prods = products.products

				outputEl.html(writeToDom(cats, prods))
				return 10
			})
			.then((stuff) => {
				console.log(stuff)
			})
		})

		$('select').change((e) => {
			outputEl.html(writeToDom(cats, prods))
			let categorySelected = e.target.value
			if (categorySelected === "none") {
				return
			}
			let discountFound = cats.find((cat) => {
				return cat.name === categorySelected
			})
			console.log(discountFound)
			let selectedCategory = Array.from($(`.${categorySelected}`))
			let priceEl = Array.from($(`.price__${discountFound.id}`))

			priceEl.forEach(el => {
				let currentPrice = el.innerHTML
				currentPrice = currentPrice - (currentPrice * discountFound.discount)
				el.innerHTML = currentPrice.toFixed(2)
			})

		})

})

let writeToDom = (cats, prods) => {

	let htmlString = ""

	cats.forEach(cat => {

		htmlString +=
		`

${cat.name}
`

		prods.forEach(prod => {

			if (cat.id == prod.category_id) {

				htmlString += `

${prod.name}

${prod.price}

`

			}
		})

		htmlString += "
"
	})

	return htmlString
}<commit_msg>whitespace and stuff<commit_after>$(document).ready(() => {
	let outputEl = $('#products')
	let cats = []
	let prods = []

// 	$.ajax({
//        url: 'https://new-cool-project-7d0fa.firebaseio.com/.json',
//        type: "GET",
//        cache: false,
//        dataType: "jsonp",
//        success : function(result){console.log(result);},
//        error : function(error){console.log(error);}
// });

$.ajax('https://new-cool-project-7d0fa.firebaseio.com/.json')
.then(result => {
	console.log(result)
})

	$.ajax('products.json')
		.then(products => {

			$.ajax('categories.json')

			.then((categories) => {

				cats = categories.categories
				prods = products.products

				outputEl.html(writeToDom(cats, prods))
				return 10
			})
			.then((stuff) => {
				console.log(stuff)
			})
		})

		$('select').change((e) => {
			outputEl.html(writeToDom(cats, prods))
			let categorySelected = e.target.value
			if (categorySelected === "none") {
				return
			}
			let discountFound = cats.find((cat) => {
				return cat.name === categorySelected
			})
			console.log(discountFound)
			let selectedCategory = Array.from($(`.${categorySelected}`))
			let priceEl = Array.from($(`.price__${discountFound.id}`))

			priceEl.forEach(el => {
				let currentPrice = el.innerHTML
				currentPrice = currentPrice - (currentPrice * discountFound.discount)
				el.innerHTML = currentPrice.toFixed(2)
			})

		})

})

let writeToDom = (cats, prods) => {

	let htmlString = ""

	cats.forEach(cat => {

		htmlString +=
		`

${cat.name}
`

		prods.forEach(prod => {

			if (cat.id == prod.category_id) {

				htmlString += `

${prod.name}

${prod.price}

`

			}
		})

		htmlString += "
"
	})

	return htmlString
}<|endoftext|>


<commit_before>window.onload = first;

var canv;
var ctxcanv;

var player;
var ctxPlayer;

var food1;
var ctxfood;

var stats;
var ctxStats;

var way;

var gameWidth = 1000;
var gameHeight = 550;

var background1 = new Image();
background1.src = "bag.jpg";

var background = new Image();
background.src = "bag.jpg";

var products = new Image();
products.src = "pic.png";

var player1;
var allfood = [];
var allfood1 = [];

var isPlaying;
var health;

var mapX = 0;
var map1X = gameWidth;

var spawnInterval;
var spawnTime = 7000;
spawnAmount = 6;

var requestAnimFrame = window.requestAnimFrame ||
						window.webkitRequestAnimationFrame ||
						window.mozRequestAnimationFrame ||
						window.oRequestAnimationFrame ||
						window.msRequestAnimationFrame;

function first() {
		canv = document.getElementById("bg");
		ctxcanv = canv.getContext("2d");

		player = document.getElementById("player");
		ctxPlayer = player.getContext("2d");

		food1 = document.getElementById("lemon");
		ctxfood = food1.getContext("2d");

		stats = document.getElementById("stats");
		ctxStats = stats.getContext("2d");

		canv.width = gameWidth;
		canv.height = gameHeight;
		player.width = gameWidth;
		player.height = gameHeight;
		food1.width = gameWidth;
		food1.height = gameHeight;
		stats.width = gameWidth;
		stats.height = gameHeight;

		ctxStats.fill = "#3D3D3D";
		ctxStats.font = "bold 15pt Cursive";

		player1 = new Player();

		resetHealth();
		resetWay();

		startLoop();

		document.addEventListener("keydown", checkKeyDown, false);
		document.addEventListener("keyup", checkKeyUp, false);
}

function resetHealth() {
	health = 100;
}

function resetWay(){
	way = 0;
}

function loop() {
	if(isPlaying) {
		draw();
		update();
		requestAnimFrame(loop);
	}
}

function startLoop() {
	isPlaying = true;
	loop();
	startCreatingallfood();
}

function stopLoop() {
	isPlaying = false;
	loop();
}

function draw() {
	player1.draw();

	clearCtxFood();
	for(var i = 0; i < allfood.length; i++) {
		allfood[i].draw();
	}
}

function update() {

	drawBackground();
	updateStats();
	player1.update();

	for(var i = 0; i < allfood.length; i++) {
		allfood[i].update();
	}
}

function Player() {

	this.srcX = 0;
	this.srcY = 0;
	this.drawX = 0;
	this.drawY = 0;
	this.width = 155;
	this.height = 155;
	this.drawWidth = 120;
	this.drawHeight = 120;
	this.isUp = false;
	this.isDown = false;
	this.isRight = false;
	this.isLeft = false;

	this.speed = 7;
}

function Lemon() {

	this.srcX = 0;
	this.srcY = 795;
	this.drawX = Math.floor(Math.random() * gameWidth) + gameWidth;
	this.drawY = Math.floor(Math.random() * gameHeight);
	this.width = 130;
	this.height = 130;
	this.drawWidth = 100;
	this.drawHeight = 100;
	this.speed = 8;
}
function spawnFood3(count) {
	for(var i = 0; i < count; i++) {
		allfood3[i] = new Lemon;
	}
}

function startCreatingallfood3() {
	stopCreatingallfood3();
	spawnInterval3 = setInterval(function(){spawnFood3(spawnAmount)},spawnTime)
}

function stopCreatingallfood3() {
	clearInterval(spawnInterval3);
}
Food.prototype.draw = function() {
	ctxfood3.drawImage(products, this.srcX, this.srcY, this.width,this.height,
		this.drawX, this.drawY, this.drawWidth, this.drawHeight);
}

Lemon.prototype.update = function() {
	this.drawX -= 7;
	if(this.drawX + this.width < 0) {
		this.destroy();
	}
}

Lemon.prototype.destroy = function() {
	allfood3.splice(allfood3.indexOf(this),1);
}
function clearCtxFood3() {
	ctxfood3.clearRect(0, 0, gameWidth, gameHeight);
}

Player.prototype.draw = function() {
	clearCtxPlayer();
	ctxPlayer.drawImage(products, this.srcX, this.srcY, this.width,this.height,
		this.drawX, this.drawY, this.drawWidth, this.drawHeight);
}

Player.prototype.update = function() {
	if(health <= 0) {
		stopLoop();
		alert ("Давай снова собирать мою любимую еду! Нажми OK, затем F5");
	}
	way++;

	if(this.drawX < 0) this.drawX = 0;
	if(this.drawX > gameWidth - this.drawWidth) this.drawX = gameWidth - this.drawWidth;
	if(this.drawY < 0) this.drawY = 0;
	if(this.drawY > gameHeight - this.drawHeight) this.drawY = gameHeight - this.drawHeight;

	for(var i = 0; i < allfood.length; i++) {
		if(this.drawX >= allfood[i].drawX &&
			this.drawY+60 >= allfood[i].drawY &&
			this.drawX <= allfood[i].drawX + allfood[i].width &&
			this.drawY+60 <= allfood[i].drawY + allfood[i].height){
				health--;
			}

	}

	this.chooseDirection();
}

Player.prototype.chooseDirection = function() {
	if(this.isUp)
		this.drawY -= this.speed;
	if(this.isDown)
		this.drawY += this.speed;
	if(this.isRight)
		this.drawX += this.speed;
	if(this.isLeft)
		this.drawX -= this.speed;
}

function checkKeyDown(e) {
	var keyID = e.keyCode || e.which;
	var keyChar = String.fromCharCode(keyID);

	if(keyChar == "W") {
		player1.isUp = true;
		e.preventDefault();
	}
	if(keyChar == "S") {
		player1.isDown = true;
		e.preventDefault();
	}
	if(keyChar == "D") {
		player1.isRight = true;
		e.preventDefault();
	}
	if(keyChar == "A") {
		player1.isLeft = true;
		e.preventDefault();
	}
}

function checkKeyUp(e) {
	var keyID = e.keyCode || e.which;
	var keyChar = String.fromCharCode(keyID);

	if(keyChar == "W") {
		player1.isUp = false;
		e.preventDefault();
	}
	if(keyChar == "S") {
		player1.isDown = false;
		e.preventDefault();
	}
	if(keyChar == "D") {
		player1.isRight = false;
		e.preventDefault();
	}
	if(keyChar == "A") {
		player1.isLeft = false;
		e.preventDefault();
	}
}

function clearCtxPlayer() {
	ctxPlayer.clearRect(0, 0, gameWidth, gameHeight);
}

function updateStats() {
	ctxStats.clearRect(0, 0, gameWidth, gameHeight);
	ctxStats.fillText("Очки: " + health, 10, 20);
	ctxStats.fillText("Путь: " + way, 10, 50);
}

function drawBackground() {
	ctxcanv.clearRect(0, 0, gameWidth, gameHeight);
	ctxcanv.drawImage(background, 0, 0, 600, 349,
		mapX, 0, gameWidth, gameHeight);
	ctxcanv.drawImage(background1, 0, 0, 600, 349,
		map1X, 0, gameWidth, gameHeight);
}

<commit_msg>Delete game1.js<commit_after><|endoftext|>


<commit_before>var GEO = {

	distanceLatLonInKilometers: function(lat1,lon1,lat2,lon2){
		var R = 6378.15;
		var dLat = (lat2-lat1) * Math.PI / 180;
		var dLon = (lon2-lon1) * Math.PI / 180;
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
			Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = R * c;
		return d;
	},

	distanceLatLonInMeters: function(lat1,lon1,lat2,lon2){
		return Math.distanceLatLonInKilometers(lat1,lon1,lat2,lon2) * 1000;
	},

	distanceLatLonInMiles: function(lat1,lon1,lat2,lon2){
		var kilometersToMilesConstant = 0.621371;
		return Math.distanceLatLonInKilometers(lat1,lon1,lat2,lon2) * kilometersToMilesConstant;
	}

};
<commit_msg>Update geo.o.js<commit_after>var GEO = {

	distanceLatLonInKilometers: function(lat1,lon1,lat2,lon2){
		var R = 6378.15;
		var dLat = (lat2-lat1) * Math.PI / 180;
		var dLon = (lon2-lon1) * Math.PI / 180;
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
			Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = R * c;
		return d;
	},

	distanceLatLonInMeters: function(lat1,lon1,lat2,lon2){
		return GEO.distanceLatLonInKilometers(lat1,lon1,lat2,lon2) * 1000;
	},

	distanceLatLonInMiles: function(lat1,lon1,lat2,lon2){
		var kilometersToMilesConstant = 0.621371;
		return GEO.distanceLatLonInKilometers(lat1,lon1,lat2,lon2) * kilometersToMilesConstant;
	}

};
<|endoftext|>


<commit_before>var geoid = (function() {

  var watchId = null;
  var hasPosition = false;
  var currentPosition = null;

  function getPosition() {

    // Default Settings

    // Minimimum Accuracy: The minimum level of accuracy (measured in meters)
    // to accept
    // Default: 10 meters (30 feet)
    var minAccuracy = 10; // Default: 10 meters (30 feet)

    // Enable High Accuracy: Whether or not an accurate, but possibly
    // expensive, geolocation result should be returned
    // Default: true
    var enableHighAccuracy = true;

    // Timeout: How long to wait for a result before giving up
    // Default: 30 seconds
    var timeout = 30000;

    // Maximum Age: How old (in milliseconds) of a cached position to accept
    // Default: 0 (don't accept a cached position)
    var maximumAge = 0;

    // Immediately get an inaccurate current position as a fallback in case
    // our other attempts fail
    navigator.geolocation.getCurrentPosition(

      // On Success
      function(position) {

        // Don't override an accurate position (if it somehow came in first)
        if(!geoid.hasPosition)
          {
            hasPosition = true;
            currentPosition = position;
          }

        },

        // On Error
        function(error) {

          // Swallow errors occurring from this initial call

        },

        // Settings (for a quick, inaccurate call)
        {
          enableHighAccuracy: false,
          maximumAge: Math.Infinity
        }

      );

      // Set up the promise for the more accurate geolocation call using
      // repeated watchPosition calls
      return new Promise(function(resolve, reject) {

        // Start measuring elapsed time
        var time = 0;
        var timeMeasureInterval = 10;

        function updateTime()
        {

          time += timeMeasureInterval;

          // We've exceeded our timeout
          if(time > timeout) {

            if(currentPosition === null) {

              // We weren't able to get *any* position, so we return an
              // error state
              reject('Unable to retrieve position');

            }
            else {

              // Return the best geolocation data we were able to get
              clearInterval(intervalId);
              navigator.geolocation.clearWatch(watchId);
              resolve(currentPosition);

            }

          }

        }

        var intervalId = setInterval(updateTime, timeMeasureInterval);

        watchId = navigator.geolocation.watchPosition(

          // On Success
          function(position) {

            hasPosition = true;
            currentPosition = position;

            if(position.coords.accuracy <= minAccuracy) {

              // As soon as we have achieved the desired accuracy,
              // clear the watch
              clearInterval(intervalId);
              navigator.geolocation.clearWatch(watchId);
              resolve(position);

            }

          },

          // On Error
          function(error) {
            reject(error)
          },

          // Settings
          {
            enableHighAccuracy: enableHighAccuracy,
            timeout: timeout,
            maximumAge: maximumAge
          }

        );
    });
  }

  return {
    getPosition: getPosition,
    hasPosition: function() { return hasPosition; },
    getLastPosition: function() { return currentPosition; }
  };

})();
<commit_msg>Moved quick, innaccurate geolocation call into a separate function<commit_after>var geoid = (function() {

  var watchId = null;
  var hasPosition = false;
  var currentPosition = null;

  function getPosition() {

    // Default Settings

    // Minimimum Accuracy: The minimum level of accuracy (measured in meters)
    // to accept
    // Default: 10 meters (30 feet)
    var minAccuracy = 10; // Default: 10 meters (30 feet)

    // Enable High Accuracy: Whether or not an accurate, but possibly
    // expensive, geolocation result should be returned
    // Default: true
    var enableHighAccuracy = true;

    // Timeout: How long to wait for a result before giving up
    // Default: 30 seconds
    var timeout = 30000;

    // Maximum Age: How old (in milliseconds) of a cached position to accept
    // Default: 0 (don't accept a cached position)
    var maximumAge = 0;

    // Immediately get an inaccurate current position as a fallback in case
    // our other attempts fail
    getQuickPosition().then(function() {

        // Don't override an accurate position (if it somehow came in first)
        if(!geoid.hasPosition)
        {
          hasPosition = true;
          currentPosition = position;
        }

      }).catch(function() {

        // Swallow the exception for this quick call

      });

      // Set up the promise for the more accurate geolocation call using
      // repeated watchPosition calls
      return new Promise(function(resolve, reject) {

        // Start measuring elapsed time
        var time = 0;
        var timeMeasureInterval = 10;

        function updateTime()
        {

          time += timeMeasureInterval;

          // We've exceeded our timeout
          if(time > timeout) {

            if(currentPosition === null) {

              // We weren't able to get *any* position, so we return an
              // error state
              reject('Unable to retrieve position');

            }
            else {

              // Return the best geolocation data we were able to get
              clearInterval(intervalId);
              navigator.geolocation.clearWatch(watchId);
              resolve(currentPosition);

            }

          }

        }

        var intervalId = setInterval(updateTime, timeMeasureInterval);

        watchId = navigator.geolocation.watchPosition(

          // On Success
          function(position) {

            hasPosition = true;
            currentPosition = position;

            if(position.coords.accuracy <= minAccuracy) {

              // As soon as we have achieved the desired accuracy,
              // clear the watch
              clearInterval(intervalId);
              navigator.geolocation.clearWatch(watchId);
              resolve(position);

            }

          },

          // On Error
          function(error) {
            reject(error)
          },

          // Settings
          {
            enableHighAccuracy: enableHighAccuracy,
            timeout: timeout,
            maximumAge: maximumAge
          }

        );
    });
  }

  function getQuickPosition() {

    return new Promise(function(resolve, reject) {

      navigator.geolocation.getCurrentPosition(

        // On Success
        function(position) {
          resolve(position);
        },

        // On Error
        function(error) {
          reject(error);
        },

        // Settings (for a quick, inaccurate call)
        {
          enableHighAccuracy: false,
          maximumAge: Math.Infinity
        }

      );

    });

  }

  return {
    getPosition: getPosition,
    hasPosition: function() { return hasPosition; },
    getLastPosition: function() { return currentPosition; }
  };

})();
<|endoftext|>


<commit_before>// objective:
// Take the str string parameter being passed and
// return the number of vowels the string contains

// solution:
const assert = require("assert");

const countVowels = str =>
  Array.from(str).filter(letter => "aeiou".includes(letter)).length;

// console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
// console.log(countVowels('xxx')); // 0

const a1 = "September"; // input
const r1 = "3"; // output
const t1 = countVowels(a1);

// console.log(t1);
assert(r1, t1);
<commit_msg>wip-update function<commit_after>// objective:
// Take the str string parameter being passed and
// return the number of vowels the string contains

// solution:
const assert = require("assert");

function countVowels(str) {
  Array.from(str).filter(letter => "aeiou".includes(letter)).length;
}

// console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
// console.log(countVowels('xxx')); // 0

const a1 = "September"; // input
const r1 = "3"; // output
const t1 = countVowels(a1);

// console.log(t1);
assert(r1, t1);
<|endoftext|>