<commit_before>#!/usr/bin/env node

// @flow

import fs from 'fs';
import path from 'path';
import yargs from 'yargs';
import { printErrors } from './printErrors';

import type { Argv } from 'yargs';

type Yargs = typeof yargs;

export type CommandModule = {
  command: string,
  description: string,
  builder?: (yargs: Yargs) => Yargs,
  handler: (argv: Object) => Promise<number>,
};

const cwd = process.cwd();

// Use the visit option (of `node-require-directory`) to provide a visitor function
// Ref: https://github.com/yargs/yargs/blob/0942a1518aad77656c135439194f8f825bd8b33a/test/command.js#L570-L599
// Ref (node-require-directory): https://github.com/troygoode/node-require-directory#visiting-objects-as-theyre-loaded
// Ref (node-require-directory): https://github.com/troygoode/node-require-directory/blob/f043664108f4a4cdb9a1c10e42268d6db754c855/test/test.js#L161-L171
export function visit(cmd: CommandModule) {
  return JSON.stringify(cmd) === '{}'
    ? // If the cmd module is an empty object, just return the object
    cmd
    : // If the cmd module isn't empty, modify the handler function by currying in some
    // parameters that we need and providing fulfillment and rejection callback
    // functions for the promise.
    {
      ...cmd,
      handler: (argv: Argv): Promise<void> =>
        cmd
          .handler({
            argv,
            cwd,
            clog: console.log,
            cerr: console.error,
          })
        // Log out error and then exit with a failure exit code
          .catch((err) => {
            const exitCode = printErrors(
              console.error,
              `Uncaught error in ${cmd.command} command:`,
              err,
            );
            process.exit(exitCode);
          })
        // Process returned with an exit code of typically 0 (success) or 1 (failure)
          .then(code => process.exit(code)),
    };
}

export async function runCLI() {
  try {
    // eslint-disable-next-line no-unused-expressions
    yargs
      // Use yargs.commandDir method to initialize a directory of commands
      // Ref: https://github.com/yargs/yargs/blob/e87f4873012e3541325e7ec6dafb11a93b5717e0/docs/advanced.md#commanddirdirectory-opts
      .commandDir('commands', { visit })
      // Require entry of at least one command after `lagoon`, such as `lagoon login`.
      // `lagoon` by itself has no assigned function at the moment.
      .demandCommand()
      .strict()
      .help().argv;
  } catch (err) {
    const exitCode = printErrors(console.error, 'Uncaught error:', err);
    process.exit(exitCode);
  }
}

/**
 * Look to see if the CWD is within an npm project. If it is, and that project
 * has a lagoon CLI `npm install`ed, use that version instead of the global
 * version of the CLI.
 */
if (require.main === module) {
  let currDir = cwd;
  let lastDir = null;
  let main = runCLI;

  while (currDir !== lastDir) {
    const localCLIPath = path.join(
      currDir,
      'node_modules',
      '.bin',
      'lagoon-cli',
    );
    try {
      if (fs.statSync(localCLIPath).isFile()) {
        main = require.call(null, localCLIPath).runCLI;
        break;
      }
    } catch (e) {
      // File doesn't exist, move up a dir...
    }
    lastDir = currDir;
    currDir = path.resolve(currDir, '..');
  }

  main();
}
<commit_msg>Continue documenting yargs usage options<commit_after>#!/usr/bin/env node

// @flow

import fs from 'fs';
import path from 'path';
import yargs from 'yargs';
import { printErrors } from './printErrors';

import type { Argv } from 'yargs';

type Yargs = typeof yargs;

export type CommandModule = {
  command: string,
  description: string,
  builder?: (yargs: Yargs) => Yargs,
  handler: (argv: Object) => Promise<number>,
};

const cwd = process.cwd();

// Use the visit option (of `node-require-directory`) to provide a visitor function
// Ref: https://github.com/yargs/yargs/blob/0942a1518aad77656c135439194f8f825bd8b33a/test/command.js#L570-L599
// Ref (node-require-directory): https://github.com/troygoode/node-require-directory#visiting-objects-as-theyre-loaded
// Ref (node-require-directory): https://github.com/troygoode/node-require-directory/blob/f043664108f4a4cdb9a1c10e42268d6db754c855/test/test.js#L161-L171
export function visit(cmd: CommandModule) {
  return JSON.stringify(cmd) === '{}'
    ? // If the cmd module is an empty object, just return the object
    cmd
    : // If the cmd module isn't empty, modify the handler function by currying in some
    // parameters that we need and providing fulfillment and rejection callback
    // functions for the promise.
    {
      ...cmd,
      handler: (argv: Argv): Promise<void> =>
        cmd
          .handler({
            argv,
            cwd,
            clog: console.log,
            cerr: console.error,
          })
        // Log out error and then exit with a failure exit code
          .catch((err) => {
            const exitCode = printErrors(
              console.error,
              `Uncaught error in ${cmd.command} command:`,
              err,
            );
            process.exit(exitCode);
          })
        // Process returned with an exit code of typically 0 (success) or 1 (failure)
          .then(code => process.exit(code)),
    };
}

export async function runCLI() {
  try {
    // eslint-disable-next-line no-unused-expressions
    yargs
      // Use yargs.commandDir method to initialize a directory of commands
      // Ref: https://github.com/yargs/yargs/blob/e87f4873012e3541325e7ec6dafb11a93b5717e0/docs/advanced.md#commanddirdirectory-opts
      .commandDir('commands', { visit })
      // Require entry of at least one command after `lagoon`, such as `lagoon login`.
      // `lagoon` by itself has no assigned function at the moment.
      .demandCommand()
      // .strict(): Error out on non-demanded or non-described command line argument
      // .argv: Get arguments as an object
      .strict().help().argv;
  } catch (err) {
    const exitCode = printErrors(console.error, 'Uncaught error:', err);
    process.exit(exitCode);
  }
}

/**
 * Look to see if the CWD is within an npm project. If it is, and that project
 * has a lagoon CLI `npm install`ed, use that version instead of the global
 * version of the CLI.
 */
if (require.main === module) {
  let currDir = cwd;
  let lastDir = null;
  let main = runCLI;

  while (currDir !== lastDir) {
    const localCLIPath = path.join(
      currDir,
      'node_modules',
      '.bin',
      'lagoon-cli',
    );
    try {
      if (fs.statSync(localCLIPath).isFile()) {
        main = require.call(null, localCLIPath).runCLI;
        break;
      }
    } catch (e) {
      // File doesn't exist, move up a dir...
    }
    lastDir = currDir;
    currDir = path.resolve(currDir, '..');
  }

  main();
}
<|endoftext|>


<commit_before>// DEFINITIONS
// a single forest isolated block would have negative rate of change

// need function to update rate of change and population

// function to determine count of neighboring forests to a cell
// inputs:
//   field: field 2d array
//   row: row of the cell
//   column: column number of the cell
// return:
//   info on the neighboring cells
//   forest: count of neighboring forest cells
//   crops: count of neighboring crop cells
//   population: sum of bee population in neighboring cells
var neighbor = function(field, row, col) {

  var forest = 0, // count all the forests found
    population = 0,
    crop = 0,
    // begin counting one row up, unless already in topmost row
    i = row > 0 ? row - 1 : row,
    // begin counting one column left, unless already in leftmost column
    min_j = col > 0 ? col - 1 : col,
    // finish counting one row down, unless already in bottommost row
    max_i = (row >= field.length - 1) ? row : row + 1,
    // finish counting one column right, unless already in rightmost column
    max_j = (col >= field[0].length - 1) ? col : col + 1;

  for (; i <= max_i; i++) {
    for (var j = min_j; j <= max_j; j++) {

      // Don't add the block you're on!
      if (i == row && j == col) continue;

      // Increase count when you find a forest
      if (field[i][j].type == "forest") {
        forest++;
        population += field[i][j].bees.population;
      } else {
        crop++;
      }

    }
  }

  // Return info on the neighboring cells.
  // Number of forests/crops, bee population
  return {
    forests: forest,
    population: population,
    crops: crop,
    capacity: (field[row][col].type == "forest" ? 1000 : 0) + (forest*10)
  };
}

module.exports.neighbor = neighbor;<commit_msg>Updates for when you're on a forest cell<commit_after>// DEFINITIONS
// a single forest isolated block would have negative rate of change

// need function to update rate of change and population

// function to determine count of neighboring forests to a cell
// inputs:
//   field: field 2d array
//   row: row of the cell
//   column: column number of the cell
// return:
//   info on the neighboring cells
//   forest: count of neighboring forest cells
//   crops: count of neighboring crop cells
//   population: sum of bee population in neighboring cells
var neighbor = function(field, row, col) {

  var forest = 0, // count all the forests found
    population = 0,
    crop = 0,
    capacity = 0,
    // begin counting one row up, unless already in topmost row
    i = row > 0 ? row - 1 : row,
    // begin counting one column left, unless already in leftmost column
    min_j = col > 0 ? col - 1 : col,
    // finish counting one row down, unless already in bottommost row
    max_i = (row >= field.length - 1) ? row : row + 1,
    // finish counting one column right, unless already in rightmost column
    max_j = (col >= field[0].length - 1) ? col : col + 1;

  for (; i <= max_i; i++) {
    for (var j = min_j; j <= max_j; j++) {

      // Don't add the block you're on!
      if (i == row && j == col) continue;

      // Increase count when you find a forest
      if (field[i][j].type == "forest") {
        forest++;
        population += field[i][j].bees.population;
      } else {
        crop++;
      }

    }
  }

  // If we're currently on a forest, increase capacity and add bee pop'n
  if(field[row][col].type == "forest"){
    capacity = 1000;
    population += field[row][col].bees.population;
  }

  // Return info on the neighboring cells.
  // Number of forests/crops, bee population
  return {
    forests: forest,
    population: population,
    crops: crop,
    capacity: capacity + (forest*10)
  };
}

module.exports.neighbor = neighbor;<|endoftext|>


<commit_before>State.Game = function (game) {
	"use strict";
	this.game = game;
};

var layer;
var player;
var cursors;
var attackButton;
var map;
var rotate;
var bg1;
var bg2;
var bg3;
var bg4;
var bg5;
var bar, bar2, bar3;
var previousX;
var previousY;
var collects;
var itemsTaken;
var idPlayer;
var helper;
var flagId, flagMove;
var monster;
var playerCollisionGroup, obstacleCollisionGroup, monsterCollisionGroup, tileCollisionGroup, collectCollisionGroup, barCollisionGroup;
var isJumping, beInGround, yBeforeJump;
var timer;

State.Game.prototype = {
		preload: function () {
			"use strict";
			itemsTaken = 0;
			flagId = false;
			idPlayer = 0;
			beInGround = true;
			isJumping = false;
			yBeforeJump = 3504;
			rotate = 0.05;
			previousX = 0;
		    previousY = 0;
		    flagMove = false;
		    timer = 0;
		},
		create: function () {
			"use strict";

			//set p2
			this.game.physics.startSystem(Phaser.Physics.P2JS);
			this.game.physics.p2.setImpactEvents(true);
			this.game.physics.p2.restitution = 0.1;
		    this.game.physics.p2.gravity.y = 800;
		    this.game.stage.backgroundColor = '#2d2d2d';
		    this.game.physics.p2.updateBoundsCollisionGroup();

		    //collision groups
		    //start collision groups
			playerCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    obstacleCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    monsterCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    tileCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    collectCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    barCollisionGroup = this.game.physics.p2.createCollisionGroup();

		    //bg
		    bg1 = this.game.add.tileSprite(0, 3060, 3000, 540, 'bg1');
		    bg2 = this.game.add.tileSprite(0, 3060, 3000, 540, 'bg2');
		    bg3 = this.game.add.tileSprite(0, 3060, 3000, 540, 'bg3');
		    bg4 = this.game.add.tileSprite(2560, 3060, 3000, 540, 'bg4');

		    //Map
		    map = this.game.add.tilemap('stage');
			map.addTilesetImage('tileset_arcane_forest', 'tileset');
			layer = map.createLayer('Camada de Tiles 1');
			map.setCollisionBetween(0, 38);
			this.game.physics.p2.enable(layer);
			var tileObjects = this.game.physics.p2.convertTilemap(map, layer);

		    //Tile collision
		    for(var tile in tileObjects)
		    {
		    	tileObjects[tile].setCollisionGroup(tileCollisionGroup);
		    	tileObjects[tile].collides(playerCollisionGroup, hitTiles, this);
		    }

		    //player
		    player = this.game.add.sprite(60, 3300, 'dude');
		    player.animations.add('left', [0, 1, 2, 3], 10, true);
		    player.animations.add('turn', [4], 20, true);
		    player.animations.add('right', [5, 6, 7, 8], 10, true);
			player.smoothed = false;
		    this.game.physics.p2.enable(player, true);
			this.game.camera.follow(player);
		    player.body.collideWorldBounds = true;
		    player.body.fixedRotation = true;
		    player.body.setCollisionGroup(playerCollisionGroup);

		    //collide
			player.body.collides(monsterCollisionGroup, hitMonsters, this);
			player.body.collides(obstacleCollisionGroup, hitObstacles, this);
			player.body.collides(tileCollisionGroup, hitTiles, this);
			player.body.collides(collectCollisionGroup, this.collectItems, this);
			player.body.collides(barCollisionGroup);

			//add 'things' to the world
			putObstacles();
			putMonsters();
			putBar();
			putCollect();

		    //DEBUG LAYER - deletar
		    layer.debug = true;

			layer.resizeWorld();

		    cursors = this.game.input.keyboard.createCursorKeys();
			attackButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

		},
		update: function () {
			"use strict";

			//move the bars
			this.moveBar(bar, 500);
			this.moveBar(bar2, 300);
			this.moveBar(bar3, 500);

//			Config.global.screen.resize(this.game);
			if (cursors.left.isDown){
				player.body.moveLeft(200);
				player.animations.play('left');
			} else if (cursors.right.isDown) {
				player.body.moveRight(200);
				player.animations.play('right');
			} else if(cursors.up.isDown){
//				layer.rotation -=0.05;
//				layer.resizeWorld();
//				map.setCollisionBetween(1, 12);
//				this.game.physics.p2.enable(layer);
			}else if(cursors.down.isDown){
//				layer.rotation +=0.05;
//				layer.resizeWorld();
			}else{
				player.body.velocity.x = 0;
				player.animations.stop();
				player.frame = 4;
			}

			if( parseInt(player.x) > (Config.global.screen.width/2) && previousX!= parseInt(player.x)){
				if(previousX>player.x){
					bg2.tilePosition.x += 0.2;
					bg3.tilePosition.x += 0.3;
				}else{
					bg2.tilePosition.x -= 0.2;
					bg3.tilePosition.x -= 0.3;
				}
			}

			previousX = parseInt(player.x);

			doJump();
			doAttack();
			followPlayer();

			if(player.x	<3050 && player.y<2451){
				this.gameRotate();
			}
		},

		onClick: function () {
			"use strict";
		},

		gameRotate: function () {
			"use strict";
			this.game.state.start('GameRotate');
		},

		render: function () {
			"use strict";
			//DEBUG
		    this.game.debug.spriteInfo(player, 32, 32);
		},

		//collect item (diamond and key)
		collectItems: function (varPlayer, collect) {
			"use strict";
			//hit once
			if ((collect.data.id != idPlayer) && !flagId) {
				idPlayer = collect.data.id;

				console.log(varPlayer.data.id, collect.data.id);
				collect.sprite.kill();
				itemsTaken++;

				if (itemsTaken > 0) {
					var fixedItem = this.game.add.sprite(0, 0, 'collect');
					fixedItem.fixedToCamera = true;
					fixedItem.cameraOffset.setTo(720 + (40 * itemsTaken), 40);
					flagId = true;
				}
			}
			if ((collect.data.id == idPlayer) && flagId) {
				flagId = false;
			}
		},

		//move the bar (obstacle)
		moveBar: function (obj, velocity) {
			"use strict";
			obj.timer++;
			if(obj.timer >= 100 ){
				obj.body.moveLeft(velocity);
				if(obj.timer >= 200){obj.timer = 0;}
			}else {
				obj.body.moveRight(velocity);
			}
		},

};

function doJump(){
	if(cursors.up.isDown)
    {
		if(isJumping === false && beInGround === true)
		{
			yBeforeJump = player.body.y;
			player.body.moveUp(500);
			isJumping = true;
			beInGround = false;
		}
    }
	if(isJumping === true){
		player.body.moveUp(500);
		if(player.body.y <= (yBeforeJump-400)){
			isJumping = false;
			player.body.moveDown(500);
		}
	}else if (beInGround != true){
		player.body.moveDown(500);
	}
}

function doAttack(){
	if(attackButton.isDown)
    {
		player.animations.play('turn');
    }
}

function hitTiles(){
	beInGround = checkIfCanJump();
	isJumping = false;
}

function hitObstacles(){
	beInGround = checkIfCanJump();
	isJumping = false;
}

function hitMonsters(){
	if(player.animations.currentFrame.index === 4 && checkIfConered()===true)
	{
		monster.kill();
		player.body.moveLeft(500);
	}else
	{
		player.kill();
		monster.body.moveRight(500);
	}
}

//internet magic...player is over something
function checkIfCanJump() {

    var yAxis = p2.vec2.fromValues(0, 1);
    var result = false;

    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++)
    {
        var c = game.physics.p2.world.narrowphase.contactEquations[i];

        if (c.bodyA === player.body.data || c.bodyB === player.body.data)
        {
            var d = p2.vec2.dot(c.normalA, yAxis); // Normal dot Y-axis
            if (c.bodyA === player.body.data) d *= -1;
            if (d > 0.5) result = true;
        }
    }

    return result;

}
//internet magic...player has something beside her rightside
function checkIfConered() {

    var xAxis = p2.vec2.fromValues(1, 0);
    var result = false;

    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++)
    {
        var c = game.physics.p2.world.narrowphase.contactEquations[i];

        if (c.bodyA === player.body.data || c.bodyB === player.body.data)
        {
            var d = p2.vec2.dot(c.normalA, xAxis); // Normal dot Y-axis
            if (c.bodyA === player.body.data) d *= -1;
            if (d > 0.5) result = true;
        }
    }

    return result;

}

//Create Obstacles
function putObstacles(){
	obstacles = game.add.group();

    for (var i = 1; i <= 4; i++)
    {
        var obstacle = obstacles.create(game.world.randomX, game.world.randomY, 'obstacle'+i);
        game.physics.p2.enable(obstacle, true);
        obstacle.body.fixedRotation = true; //no circle movement
        obstacle.body.kinematic = true;
        obstacle.body.setCollisionGroup(obstacleCollisionGroup);
        obstacle.body.collides([obstacleCollisionGroup, playerCollisionGroup]);
    }
}

//create monsters
function putMonsters(){
	//monster
    monster = game.add.sprite(160, 3500, 'monster1');
    monster.animations.add('walk', [0,1,2,3], 10, true);
    monster.play('walk');
    game.physics.p2.enable(monster, true);
    monster.body.fixedRotation = true; //no circle movement
    monster.body.kinematic = true;
    monster.body.setCollisionGroup(monsterCollisionGroup);
    monster.body.collides([monsterCollisionGroup, playerCollisionGroup]);
}

//Create Bars
function putBar(){
    //bar 1
    bar = this.game.add.sprite(Config.game.bar.startX, Config.game.bar.startY, 'bar');
    this.game.physics.p2.enable(bar, true);
    bar.body.kinematic = true;
    bar.body.setCollisionGroup(barCollisionGroup);
    bar.body.collides([barCollisionGroup, playerCollisionGroup]);
    bar.timer = 0;

    //bar 2
    bar2 = this.game.add.sprite(300, 3200, 'bar');
    this.game.physics.p2.enable(bar2, true);
    bar2.body.kinematic = true;
    bar2.body.setCollisionGroup(barCollisionGroup);
    bar2.body.collides([barCollisionGroup, playerCollisionGroup]);
    bar2.timer = 0;

	//bar 3
    bar3 = this.game.add.sprite(200, 3300, 'bar');
    this.game.physics.p2.enable(bar3, true);
    bar3.body.kinematic = true;
    bar3.body.setCollisionGroup(barCollisionGroup);
    bar3.body.collides([barCollisionGroup, playerCollisionGroup]);
    bar3.timer = 0;
}

//Create Collects
function putCollect(){
	//Group Item
    var collects = this.game.add.group();

    //Collect Items 1
    var collect = collects.create(90, 3500, 'collect');
    this.game.physics.p2.enable(collect, true);
    collect.body.fixedRotation = true; //no circle movement
    collect.body.kinematic = true;
    collect.body.setCollisionGroup(collectCollisionGroup);
    collect.body.collides([collectCollisionGroup ,playerCollisionGroup]);

    //Collect Items 2
    var collect = collects.create(150, 3500, 'collect');
    this.game.physics.p2.enable(collect, true);
    collect.body.fixedRotation = true; //no circle movement
    collect.body.kinematic = true;
    collect.body.setCollisionGroup(collectCollisionGroup);
    collect.body.collides([collectCollisionGroup ,playerCollisionGroup]);

    //Collect Items 3
    var collect = collects.create(200, 3500, 'collect');
    this.game.physics.p2.enable(collect, true);
    collect.body.fixedRotation = true; //no circle movement
    collect.body.kinematic = true;
    collect.body.setCollisionGroup(collectCollisionGroup);
    collect.body.collides([collectCollisionGroup ,playerCollisionGroup]);
}

var monster_speed = 5;
function followPlayer()
{
  if (player.body.x < monster.body.x)
  {
    monster.body.velocity.x = monster_speed * -1;
  }
  else
  {
    monster.body.velocity.x = monster_speed;
  }
    if (player.body.y < monster.body.y)
  {
    monster.body.velocity.y = monster_speed * -1;
  }
  else
  {
    monster.body.velocity.y = monster_speed;
  }

}<commit_msg>Duplicando a imagem do background<commit_after>State.Game = function (game) {
	"use strict";
	this.game = game;
};

var layer;
var player;
var cursors;
var attackButton;
var map;
var rotate;
var bg1;
var bg2;
var bg3;
var bg4;
var bg5;
var bar, bar2, bar3;
var previousX;
var previousY;
var collects;
var itemsTaken;
var idPlayer;
var helper;
var flagId, flagMove;
var monster;
var playerCollisionGroup, obstacleCollisionGroup, monsterCollisionGroup, tileCollisionGroup, collectCollisionGroup, barCollisionGroup;
var isJumping, beInGround, yBeforeJump;
var timer;

State.Game.prototype = {
		preload: function () {
			"use strict";
			itemsTaken = 0;
			flagId = false;
			idPlayer = 0;
			beInGround = true;
			isJumping = false;
			yBeforeJump = 3504;
			rotate = 0.05;
			previousX = 0;
		    previousY = 0;
		    flagMove = false;
		    timer = 0;
		},
		create: function () {
			"use strict";

			//set p2
			this.game.physics.startSystem(Phaser.Physics.P2JS);
			this.game.physics.p2.setImpactEvents(true);
			this.game.physics.p2.restitution = 0.1;
		    this.game.physics.p2.gravity.y = 800;
		    this.game.stage.backgroundColor = '#2d2d2d';
		    this.game.physics.p2.updateBoundsCollisionGroup();

		    //collision groups
		    //start collision groups
			playerCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    obstacleCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    monsterCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    tileCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    collectCollisionGroup = this.game.physics.p2.createCollisionGroup();
		    barCollisionGroup = this.game.physics.p2.createCollisionGroup();

		    //bg
		    bg1 = this.game.add.tileSprite(0, 3060, 3000, 540, 'bg1');
		    bg2 = this.game.add.tileSprite(0, 3060, 3000, 540, 'bg2');
		    bg3 = this.game.add.tileSprite(0, 3060, 3000, 540, 'bg3');
		    bg4 = this.game.add.tileSprite(2560, 3060, 3000, 540, 'bg4');
		    bg4 = this.game.add.tileSprite(2560, 2520, 3000, 540, 'bg4');
		    this.game.add.tileSprite(2560, 1980, 3000, 540, 'bg4');

		    //Map
		    map = this.game.add.tilemap('stage');
			map.addTilesetImage('tileset_arcane_forest', 'tileset');
			layer = map.createLayer('Camada de Tiles 1');
			map.setCollisionBetween(0, 38);
			this.game.physics.p2.enable(layer);
			var tileObjects = this.game.physics.p2.convertTilemap(map, layer);

		    //Tile collision
		    for(var tile in tileObjects)
		    {
		    	tileObjects[tile].setCollisionGroup(tileCollisionGroup);
		    	tileObjects[tile].collides(playerCollisionGroup, hitTiles, this);
		    }

		    //player
		    player = this.game.add.sprite(60, 3300, 'dude');
		    player.animations.add('left', [0, 1, 2, 3], 10, true);
		    player.animations.add('turn', [4], 20, true);
		    player.animations.add('right', [5, 6, 7, 8], 10, true);
			player.smoothed = false;
		    this.game.physics.p2.enable(player, true);
			this.game.camera.follow(player);
		    player.body.collideWorldBounds = true;
		    player.body.fixedRotation = true;
		    player.body.setCollisionGroup(playerCollisionGroup);

		    //collide
			player.body.collides(monsterCollisionGroup, hitMonsters, this);
			player.body.collides(obstacleCollisionGroup, hitObstacles, this);
			player.body.collides(tileCollisionGroup, hitTiles, this);
			player.body.collides(collectCollisionGroup, this.collectItems, this);
			player.body.collides(barCollisionGroup);

			//add 'things' to the world
			putObstacles();
			putMonsters();
			putBar();
			putCollect();

		    //DEBUG LAYER - deletar
		    layer.debug = true;

			layer.resizeWorld();

		    cursors = this.game.input.keyboard.createCursorKeys();
			attackButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

		},
		update: function () {
			"use strict";

			//move the bars
			this.moveBar(bar, 500);
			this.moveBar(bar2, 300);
			this.moveBar(bar3, 500);

//			Config.global.screen.resize(this.game);
			if (cursors.left.isDown){
				player.body.moveLeft(200);
				player.animations.play('left');
			} else if (cursors.right.isDown) {
				player.body.moveRight(200);
				player.animations.play('right');
			} else if(cursors.up.isDown){
//				layer.rotation -=0.05;
//				layer.resizeWorld();
//				map.setCollisionBetween(1, 12);
//				this.game.physics.p2.enable(layer);
			}else if(cursors.down.isDown){
//				layer.rotation +=0.05;
//				layer.resizeWorld();
			}else{
				player.body.velocity.x = 0;
				player.animations.stop();
				player.frame = 4;
			}

			if( parseInt(player.x) > (Config.global.screen.width/2) && previousX!= parseInt(player.x)){
				if(previousX>player.x){
					bg2.tilePosition.x += 0.2;
					bg3.tilePosition.x += 0.3;
				}else{
					bg2.tilePosition.x -= 0.2;
					bg3.tilePosition.x -= 0.3;
				}
			}

			previousX = parseInt(player.x);

			doJump();
			doAttack();
			followPlayer();

			if(player.x	<3050 && player.y<2451){
				this.gameRotate();
			}
		},

		onClick: function () {
			"use strict";
		},

		gameRotate: function () {
			"use strict";
			this.game.state.start('GameRotate');
		},

		render: function () {
			"use strict";
			//DEBUG
		    this.game.debug.spriteInfo(player, 32, 32);
		},

		//collect item (diamond and key)
		collectItems: function (varPlayer, collect) {
			"use strict";
			//hit once
			if ((collect.data.id != idPlayer) && !flagId) {
				idPlayer = collect.data.id;

				console.log(varPlayer.data.id, collect.data.id);
				collect.sprite.kill();
				itemsTaken++;

				if (itemsTaken > 0) {
					var fixedItem = this.game.add.sprite(0, 0, 'collect');
					fixedItem.fixedToCamera = true;
					fixedItem.cameraOffset.setTo(720 + (40 * itemsTaken), 40);
					flagId = true;
				}
			}
			if ((collect.data.id == idPlayer) && flagId) {
				flagId = false;
			}
		},

		//move the bar (obstacle)
		moveBar: function (obj, velocity) {
			"use strict";
			obj.timer++;
			if(obj.timer >= 100 ){
				obj.body.moveLeft(velocity);
				if(obj.timer >= 200){obj.timer = 0;}
			}else {
				obj.body.moveRight(velocity);
			}
		},

};

function doJump(){
	if(cursors.up.isDown)
    {
		if(isJumping === false && beInGround === true)
		{
			yBeforeJump = player.body.y;
			player.body.moveUp(500);
			isJumping = true;
			beInGround = false;
		}
    }
	if(isJumping === true){
		player.body.moveUp(500);
		if(player.body.y <= (yBeforeJump-400)){
			isJumping = false;
			player.body.moveDown(500);
		}
	}else if (beInGround != true){
		player.body.moveDown(500);
	}
}

function doAttack(){
	if(attackButton.isDown)
    {
		player.animations.play('turn');
    }
}

function hitTiles(){
	beInGround = checkIfCanJump();
	isJumping = false;
}

function hitObstacles(){
	beInGround = checkIfCanJump();
	isJumping = false;
}

function hitMonsters(){
	if(player.animations.currentFrame.index === 4 && checkIfConered()===true)
	{
		monster.kill();
		player.body.moveLeft(500);
	}else
	{
		player.kill();
		monster.body.moveRight(500);
	}
}

//internet magic...player is over something
function checkIfCanJump() {

    var yAxis = p2.vec2.fromValues(0, 1);
    var result = false;

    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++)
    {
        var c = game.physics.p2.world.narrowphase.contactEquations[i];

        if (c.bodyA === player.body.data || c.bodyB === player.body.data)
        {
            var d = p2.vec2.dot(c.normalA, yAxis); // Normal dot Y-axis
            if (c.bodyA === player.body.data) d *= -1;
            if (d > 0.5) result = true;
        }
    }

    return result;

}
//internet magic...player has something beside her rightside
function checkIfConered() {

    var xAxis = p2.vec2.fromValues(1, 0);
    var result = false;

    for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++)
    {
        var c = game.physics.p2.world.narrowphase.contactEquations[i];

        if (c.bodyA === player.body.data || c.bodyB === player.body.data)
        {
            var d = p2.vec2.dot(c.normalA, xAxis); // Normal dot Y-axis
            if (c.bodyA === player.body.data) d *= -1;
            if (d > 0.5) result = true;
        }
    }

    return result;

}

//Create Obstacles
function putObstacles(){
	obstacles = game.add.group();

    for (var i = 1; i <= 4; i++)
    {
        var obstacle = obstacles.create(game.world.randomX, game.world.randomY, 'obstacle'+i);
        game.physics.p2.enable(obstacle, true);
        obstacle.body.fixedRotation = true; //no circle movement
        obstacle.body.kinematic = true;
        obstacle.body.setCollisionGroup(obstacleCollisionGroup);
        obstacle.body.collides([obstacleCollisionGroup, playerCollisionGroup]);
    }
}

//create monsters
function putMonsters(){
	//monster
    monster = game.add.sprite(160, 3500, 'monster1');
    monster.animations.add('walk', [0,1,2,3], 10, true);
    monster.play('walk');
    game.physics.p2.enable(monster, true);
    monster.body.fixedRotation = true; //no circle movement
    monster.body.kinematic = true;
    monster.body.setCollisionGroup(monsterCollisionGroup);
    monster.body.collides([monsterCollisionGroup, playerCollisionGroup]);
}

//Create Bars
function putBar(){
    //bar 1
    bar = this.game.add.sprite(Config.game.bar.startX, Config.game.bar.startY, 'bar');
    this.game.physics.p2.enable(bar, true);
    bar.body.kinematic = true;
    bar.body.setCollisionGroup(barCollisionGroup);
    bar.body.collides([barCollisionGroup, playerCollisionGroup]);
    bar.timer = 0;

    //bar 2
    bar2 = this.game.add.sprite(300, 3200, 'bar');
    this.game.physics.p2.enable(bar2, true);
    bar2.body.kinematic = true;
    bar2.body.setCollisionGroup(barCollisionGroup);
    bar2.body.collides([barCollisionGroup, playerCollisionGroup]);
    bar2.timer = 0;

	//bar 3
    bar3 = this.game.add.sprite(200, 3300, 'bar');
    this.game.physics.p2.enable(bar3, true);
    bar3.body.kinematic = true;
    bar3.body.setCollisionGroup(barCollisionGroup);
    bar3.body.collides([barCollisionGroup, playerCollisionGroup]);
    bar3.timer = 0;
}

//Create Collects
function putCollect(){
	//Group Item
    var collects = this.game.add.group();

    //Collect Items 1
    var collect = collects.create(90, 3500, 'collect');
    this.game.physics.p2.enable(collect, true);
    collect.body.fixedRotation = true; //no circle movement
    collect.body.kinematic = true;
    collect.body.setCollisionGroup(collectCollisionGroup);
    collect.body.collides([collectCollisionGroup ,playerCollisionGroup]);

    //Collect Items 2
    var collect = collects.create(150, 3500, 'collect');
    this.game.physics.p2.enable(collect, true);
    collect.body.fixedRotation = true; //no circle movement
    collect.body.kinematic = true;
    collect.body.setCollisionGroup(collectCollisionGroup);
    collect.body.collides([collectCollisionGroup ,playerCollisionGroup]);

    //Collect Items 3
    var collect = collects.create(200, 3500, 'collect');
    this.game.physics.p2.enable(collect, true);
    collect.body.fixedRotation = true; //no circle movement
    collect.body.kinematic = true;
    collect.body.setCollisionGroup(collectCollisionGroup);
    collect.body.collides([collectCollisionGroup ,playerCollisionGroup]);
}

var monster_speed = 5;
function followPlayer()
{
  if (player.body.x < monster.body.x)
  {
    monster.body.velocity.x = monster_speed * -1;
  }
  else
  {
    monster.body.velocity.x = monster_speed;
  }
    if (player.body.y < monster.body.y)
  {
    monster.body.velocity.y = monster_speed * -1;
  }
  else
  {
    monster.body.velocity.y = monster_speed;
  }

}<|endoftext|>


<commit_before>'use strict';

module.exports.attributes = (DataTypes) => {
  return {
    id : {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },

    name : DataTypes.STRING
  };
}

<commit_msg>Deleted: person file<commit_after><|endoftext|>


<commit_before>import { Adapter } from 'ember-pouch';
import Ember from 'ember';

import PouchAdapterUtils from 'hospitalrun/mixins/pouch-adapter-utils';

export default Adapter.extend(PouchAdapterUtils, {
    databaseName: 'config',

    _mapQuery: function(doc, emit) {
        if (doc._id) {
            emit(doc._id, null);
        }
    },

    findQuery: function(store, type, query, options) {
        if (!query.exactKeys) {
            return this._super(store, type, query, options);
        } else {
            var self = this,
            queryParams = {
                reduce: false,
                include_docs: true
            };

            queryParams.keys = query.exactKeys.map(function(key) {
                return this.get('database').getPouchId(key, 'config');
            }.bind(this));
            return new Ember.RSVP.Promise(function(resolve, reject){
                self._getDb().then(function(db){
                    try {
                        db.query(self._mapQuery, queryParams, function(err, response) {
                            if (err) {
                                self._pouchError(reject)(err);
                            } else {
                                if (response.rows) {
                                    var data = Ember.A(response.rows).mapBy('doc');
                                    Ember.run(null, resolve, data);
                                }
                            }
                        });
                    } catch (err){
                        self._pouchError(reject)(err);
                    }
                }, self._pouchError(reject));
            }, "findQuery in config-pouchdb-adapter");
        }
    }
});
<commit_msg>Grr... removed wrong line<commit_after>import { Adapter } from 'ember-pouch';
import Ember from 'ember';

import PouchAdapterUtils from 'hospitalrun/mixins/pouch-adapter-utils';

export default Adapter.extend(PouchAdapterUtils, {
    databaseName: 'config',
    database: Ember.inject.service(),

    _mapQuery: function(doc, emit) {
        if (doc._id) {
            emit(doc._id, null);
        }
    },

    findQuery: function(store, type, query, options) {
        if (!query.exactKeys) {
            return this._super(store, type, query, options);
        } else {
            var self = this,
            queryParams = {
                reduce: false,
                include_docs: true
            };

            queryParams.keys = query.exactKeys.map(function(key) {
                return this.get('database').getPouchId(key, 'config');
            }.bind(this));
            return new Ember.RSVP.Promise(function(resolve, reject){
                self._getDb().then(function(db){
                    try {
                        db.query(self._mapQuery, queryParams, function(err, response) {
                            if (err) {
                                self._pouchError(reject)(err);
                            } else {
                                if (response.rows) {
                                    var data = Ember.A(response.rows).mapBy('doc');
                                    Ember.run(null, resolve, data);
                                }
                            }
                        });
                    } catch (err){
                        self._pouchError(reject)(err);
                    }
                }, self._pouchError(reject));
            }, "findQuery in config-pouchdb-adapter");
        }
    }
});
<|endoftext|>


<commit_before>var playername = window.location.search.split("name=")[1];
var xhr = new XMLHttpRequest();

xhr.open("GET", "https://api.wynncraft.com/public_api.php?action=playerStats&command=" + playername);
xhr.send();

xhr.addEventListener("readystatechange", processRequest, false);

function processRequest(e) {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);

    if (response.error == "Player not found") {
      document.getElementsByClassName("main")[0].innerHTML = "
WynnStats

Player not found!
";
      return
    }

    document.getElementsByTagName("title")[0].innerHTML = response.username + " - WynnStats";
    document.getElementById("username").innerHTML = response.username;

    if (response.tag != "") {
      document.getElementById("rank").innerHTML = response.rank + " (" + response.tag + ")";
    }
    else {
      document.getElementById("rank").innerHTML = response.rank;
    }

    if (response.current_server != "null") {
      document.getElementById("c_server").innerHTML = "Currently Online: " + response.current_server;
    }

    document.getElementById("playtime").innerHTML = response.playtime + " minutes
≈ " + Math.round((response.playtime / 60) * 100) / 100 + " hours";
    document.getElementById("first_join").innerHTML = response.first_join_friendly;
    document.getElementById("last_join").innerHTML = response.last_join_friendly;
    document.getElementById("items_ided").innerHTML = response.global.items_identified;
    document.getElementById("mobs_killed").innerHTML = response.global.mobs_killed;
    document.getElementById("pvp_kills").innerHTML = response.global.pvp_kills;
    document.getElementById("pvp_deaths").innerHTML = response.global.pvp_deaths;
    document.getElementById("chests_found").innerHTML = response.global.chests_found;
    document.getElementById("logins").innerHTML = response.global.logins;
    document.getElementById("deaths").innerHTML = response.global.deaths;
    document.getElementById("total_level").innerHTML = response.global.total_level;

    for (var classname in response.classes) {
      if (response.classes.hasOwnProperty(classname)) {
        c = eval("response.classes." + classname)
         var cur_stat_html = "

" + classname + "

Level	" + c.level + "

XP	" + c.xp + "%

Dungeons	" + c.dungeonsAmount + "
"
        for (var dungeonname in c.dungeons) {
          if (c.dungeons.hasOwnProperty(dungeonname)) {
            cur_stat_html += "
" + dungeonname + "	" + c.dungeons[dungeonname] + "
"
          }
        }
        cur_stat_html += "
Quests	" + c.questsAmount + "
"
        for (var questname in c.quests) {
          if (c.quests.hasOwnProperty(questname)) {
            cur_stat_html += "
	" + c.quests[questname] + "
"
          }
        }
        document.getElementById("classdiv").innerHTML += cur_stat_html + "

"
      }
    }
    document.getElementById("classdiv").innerHTML += "

"
  }
}

function toggleHideId(e) {
  if (document.getElementById(e).style.display == "") {
    document.getElementById(e).style.display = "none"
  }
  else {
    document.getElementById(e).style.display = ""
  }
}

function toggleHideClass(e) {
  for (var i in document.getElementsByClassName(e)) {
    if (document.getElementsByClassName(e).hasOwnProperty(i)) {
      j = eval(document.getElementsByClassName(e)[i])
      if (j.style.display == "") {
        j.style.display = "none"
      }
      else {
        j.style.display = ""
      }
    }
  }
}
<commit_msg>Moved dungeons to td from th<commit_after>var playername = window.location.search.split("name=")[1];
var xhr = new XMLHttpRequest();

xhr.open("GET", "https://api.wynncraft.com/public_api.php?action=playerStats&command=" + playername);
xhr.send();

xhr.addEventListener("readystatechange", processRequest, false);

function processRequest(e) {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);

    if (response.error == "Player not found") {
      document.getElementsByClassName("main")[0].innerHTML = "
WynnStats

Player not found!
";
      return
    }

    document.getElementsByTagName("title")[0].innerHTML = response.username + " - WynnStats";
    document.getElementById("username").innerHTML = response.username;

    if (response.tag != "") {
      document.getElementById("rank").innerHTML = response.rank + " (" + response.tag + ")";
    }
    else {
      document.getElementById("rank").innerHTML = response.rank;
    }

    if (response.current_server != "null") {
      document.getElementById("c_server").innerHTML = "Currently Online: " + response.current_server;
    }

    document.getElementById("playtime").innerHTML = response.playtime + " minutes
≈ " + Math.round((response.playtime / 60) * 100) / 100 + " hours";
    document.getElementById("first_join").innerHTML = response.first_join_friendly;
    document.getElementById("last_join").innerHTML = response.last_join_friendly;
    document.getElementById("items_ided").innerHTML = response.global.items_identified;
    document.getElementById("mobs_killed").innerHTML = response.global.mobs_killed;
    document.getElementById("pvp_kills").innerHTML = response.global.pvp_kills;
    document.getElementById("pvp_deaths").innerHTML = response.global.pvp_deaths;
    document.getElementById("chests_found").innerHTML = response.global.chests_found;
    document.getElementById("logins").innerHTML = response.global.logins;
    document.getElementById("deaths").innerHTML = response.global.deaths;
    document.getElementById("total_level").innerHTML = response.global.total_level;

    for (var classname in response.classes) {
      if (response.classes.hasOwnProperty(classname)) {
        c = eval("response.classes." + classname)
         var cur_stat_html = "

" + classname + "

Level	" + c.level + "

XP	" + c.xp + "%

Dungeons	" + c.dungeonsAmount + "
"
        for (var dungeonname in c.dungeons) {
          if (c.dungeons.hasOwnProperty(dungeonname)) {
            cur_stat_html += "
	" + dungeonname + " (" + c.dungeons[dungeonname] + ")
"
          }
        }
        cur_stat_html += "
Quests	" + c.questsAmount + "
"
        for (var questname in c.quests) {
          if (c.quests.hasOwnProperty(questname)) {
            cur_stat_html += "
	" + c.quests[questname] + "
"
          }
        }
        document.getElementById("classdiv").innerHTML += cur_stat_html + "

"
      }
    }
    document.getElementById("classdiv").innerHTML += "

"
  }
}

function toggleHideId(e) {
  if (document.getElementById(e).style.display == "") {
    document.getElementById(e).style.display = "none"
  }
  else {
    document.getElementById(e).style.display = ""
  }
}

function toggleHideClass(e) {
  for (var i in document.getElementsByClassName(e)) {
    if (document.getElementsByClassName(e).hasOwnProperty(i)) {
      j = eval(document.getElementsByClassName(e)[i])
      if (j.style.display == "") {
        j.style.display = "none"
      }
      else {
        j.style.display = ""
      }
    }
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var collectParallel = require('collect-parallel/array');
var metrics = require('metrics');

var allocCluster = require('./lib/alloc-cluster.js');
var BatchClient = require('./lib/batch-client.js');
var CollapsedAssert = require('./lib/collapsed-assert.js');

allocCluster.test('p2p requests from 40 -> 40', {
    numPeers: 80
}, function t(cluster, assert) {
    setup(cluster);

    collectParallel(cluster.batches, function runRequests(batch, _, cb) {
        batch.sendRequests(cb);
    }, onBatches);

    /*eslint max-statements: [2, 40]*/
    function onBatches(err, results) {
        var cassert = CollapsedAssert();
        cassert.ifError(err);

        var statuses = [];
        for (var i = 0; i < results.length; i++) {
            cassert.ifError(results[i].err, 'expect no batch error');
            cassert.ifError(results[i].value.errors.length > 0,
                'expect zero errors in batch');
            statuses.push(results[i].value);
        }
        cassert.report(assert, 'expected no errors');

        var statusTable = findServerHostDistribution(statuses);

        var uniqHosts = Object.keys(statusTable);
        if (uniqHosts.length < 35) {
            checkConnections();
            checkDistributions(statusTable);
        } else {
            assert.ok(true, 'SKIP: suprisingly large number of peers reached');
        }

        assert.end();
    }

    function checkConnections() {
        var cassert = CollapsedAssert();
        var distribution = new metrics.Histogram();
        for (var i = 0; i < cluster.batches.length; i++) {
            var connCount = countConnections(cluster.batches[i]);
            distribution.update(connCount);

            cassert.ok(
                connCount >= 1 &&
                connCount <= 5,
                'expected a small number of connections'
            );
        }

        var info = distribution.printObj();
        cassert.ok(info.min <= 2, 'expected low minimum');
        cassert.ok(info.max <= 5, 'expected low maximum');
        cassert.ok(info.sum <= 100, 'expected low total connections');
        cassert.ok(info.p75 <= 2, 'expected low p75');
        // console.log('conn distribution', info);

        cassert.report(assert, 'expected batch connections to be fine');
    }

    function checkDistributions(statusTable) {
        var uniqHosts = Object.keys(statusTable);
        assert.ok(uniqHosts.length <= 35,
            'Expected host reached (' + uniqHosts.length + ') to <= 35');

        var distribution = new metrics.Histogram();
        for (var i = 0; i < uniqHosts.length; i++) {
            distribution.update(statusTable[uniqHosts[i]]);
        }

        var info = distribution.printObj();

        var cassert = CollapsedAssert();
        cassert.ok(info.min <= 50,
            'expected minimum to be no more then 50'
        );
        cassert.equal(info.sum, 2000,
            'expected 2000 requests to be made'
        );
        cassert.ok(info.median >= 49,
            'expected median (' + info.median + ') to be huge'
        );
        cassert.ok(info.max >= 100, 'expected maximum to be huge');
        cassert.ok(info.p75 >= 50, 'expected P75 to be huge');
        cassert.ok(info.p95 > 80, 'expected P95 to be huge');
        cassert.ok(info.variance >= 600,
            'expected variance (' + info.variance + ') to be huge'
        );
        // console.log('conn distribution', info);

        cassert.report(assert, 'expected request distribution to be ok');
    }
});

allocCluster.test('p2p requests from 40 -> 40 with minConnections', {
    numPeers: 80,
    channelOptions: {
        choosePeerWithHeap: true
    }
}, function t(cluster, assert) {
    setup(cluster, {
        minConnections: 10
    });

    collectParallel(cluster.batches, function runRequests(batch, _, cb) {
        batch.sendRequests(cb);
    }, onBatches);

    /*eslint max-statements: [2, 40]*/
    function onBatches(err, results) {
        var cassert = CollapsedAssert();
        cassert.ifError(err);

        var statuses = [];
        for (var i = 0; i < results.length; i++) {
            cassert.ifError(results[i].err, 'expect no batch error');
            cassert.ifError(results[i].value.errors.length > 0,
                'expect zero errors in batch');
            statuses.push(results[i].value);
        }
        cassert.report(assert, 'expected no errors');

        var statusTable = findServerHostDistribution(statuses);

        cassert = verifyConnections(cluster, 10, 12);
        cassert.report(assert, 'expected batch connections to be fine');

        cassert = verifyDistributions(statusTable, {
            min: 40,
            sum: 2000,
            median: [40, 60],
            mean: [45, 55],
            max: 120,
            p75: [55, 70],
            p95: 95,
            variance: 400
        });
        cassert.report(assert, 'expected request distribution to be ok');

        assert.end();
    }
});

allocCluster.test('p2p requests where minConns > no of servers', {
    numPeers: 45,
    channelOptions: {
        choosePeerWithHeap: true
    }
}, function t(cluster, assert) {
    setup(cluster, {
        minConnections: 6,
        servers: 5
    });

    collectParallel(cluster.batches, function runRequests(batch, _, cb) {
        batch.sendRequests(cb);
    }, onBatches);

    /*eslint max-statements: [2, 40]*/
    function onBatches(err, results) {
        var cassert = CollapsedAssert();
        cassert.ifError(err);

        var statuses = [];
        for (var i = 0; i < results.length; i++) {
            cassert.ifError(results[i].err, 'expect no batch error');
            cassert.ifError(results[i].value.errors.length > 0,
                'expect zero errors in batch');

            statuses.push(results[i].value);
        }
        cassert.report(assert, 'expected no errors');

        var statusTable = findServerHostDistribution(statuses);

        cassert = verifyConnections(cluster, 5, 5);
        cassert.report(assert, 'expected batch connections to be fine');

        cassert = verifyDistributions(statusTable, {
            min: 395,
            sum: 2000,
            median: [380, 420],
            mean: [395, 405],
            max: 500,
            p75: [400, 450],
            p95: 475
        });
        cassert.report(assert, 'expected request distribution to be ok');

        assert.end();
    }
});

allocCluster.test('p2p requests where half of servers down', {
    numPeers: 48,
    channelOptions: {
        choosePeerWithHeap: true
    }
}, function t(cluster, assert) {
    cluster.logger.whitelist('info', 'resetting connection');
    setup(cluster, {
        minConnections: 5,
        servers: 8,
        retryLimit: 2
    });

    // Close half the servers...
    for (var j = 0; j < cluster.servers.length / 2; j++) {
        cluster.servers[j * 2].close();
    }

    collectParallel(cluster.batches, function runRequests(batch, _, cb) {
        batch.sendRequests(cb);
    }, onBatches);

    /*eslint max-statements: [2, 40]*/
    function onBatches(err, results) {
        var cassert = CollapsedAssert();
        cassert.ifError(err);

        var statuses = [];
        for (var i = 0; i < results.length; i++) {
            cassert.ifError(results[i].err, 'expect no batch error');
            cassert.ifError(results[i].value.errors.length > 2,
                'expect at most two error in batch(' +
                    results[i].value.errors.length + ')');

            statuses.push(results[i].value);
        }
        cassert.report(assert, 'expected no errors');

        var statusTable = findServerHostDistribution(statuses);

        cassert = verifyConnections(cluster, 4, 4);
        cassert.report(assert, 'expected batch connections to be fine');

        cassert = verifyDistributions(statusTable, {
            min: 495,
            sum: [1990, 2000],
            median: [480, 520],
            mean: [495, 505],
            max: 600,
            p75: [500, 550],
            p95: 575
        });
        cassert.report(assert, 'expected request distribution to be ok');

        assert.end();
    }
});

function findServerHostDistribution(statuses) {
    var statusTable = {};
    for (var i = 0; i < statuses.length; i++) {
        var records = statuses[i].results;
        for (var j = 0; j < records.length; j++) {
            var record = records[j];
            if (!statusTable[record.outReqHostPort]) {
                statusTable[record.outReqHostPort] = 0;
            }
            statusTable[record.outReqHostPort]++;
        }
    }
    return statusTable;
}

function countConnections(batchClient) {
    var subChannel = batchClient.subChannel;
    var peers = subChannel.peers.values();

    var conns = [];
    for (var i = 0; i < peers.length; i++) {
        var peer = peers[i];
        for (var j = 0; j < peer.connections.length; j++) {
            conns.push(peer.connections[j]);
        }
    }

    return conns.length;
}

function verifyConnections(cluster, min, max) {
    var MIN = min;
    var MAX = max;
    var COUNT = cluster.batches.length;

    var cassert = CollapsedAssert();
    var distribution = new metrics.Histogram();
    for (var i = 0; i < cluster.batches.length; i++) {
        var connCount = countConnections(cluster.batches[i]);
        distribution.update(connCount);

        cassert.ok(
            connCount >= MIN &&
            connCount <= MAX,
            'expected connections(' + connCount + ') to be ' +
                '>= ' + MIN + ' and <= ' + MAX
        );
    }

    var info = distribution.printObj();
    cassert.ok(info.min <= MAX,
        'expected min connections(' + info.min + ') to be <= ' + MAX);
    cassert.ok(info.max >= MIN,
        'expected max conns(' + info.max + ') to be >= ' + MIN);
    cassert.ok(info.sum >= COUNT * MIN,
        'expected sum of conns(' + info.sum + ') to be at ' +
            COUNT * MIN + ' conns');
    cassert.ok(info.p75 <= MAX,
        'expected p75(' + info.p75 + ') to be <= ' + MAX);

    return cassert;
}

function verifyDistributions(statusTable, opts) {
    var uniqHosts = Object.keys(statusTable);

    var distribution = new metrics.Histogram();
    for (var i = 0; i < uniqHosts.length; i++) {
        distribution.update(statusTable[uniqHosts[i]]);
    }

    var info = distribution.printObj();

    var cassert = CollapsedAssert();
    cassert.ok(info.min <= opts.min,
        'expected minimum(' + info.min + ') to be no more then ' + opts.min
    );

    if (Array.isArray(opts.sum)) {
        cassert.ok(
            info.sum >= opts.sum[0] &&
            info.sum <= opts.sum[1],
            'expected sum(' + info.sum + ') to be within ' +
                opts.sum[0] + ' & ' + opts.sum[1]
        );
    } else {
        cassert.equal(info.sum, opts.sum,
            'expected sum(' + info.sum + ') to be ' + opts.sum
        );
    }

    cassert.ok(
        info.median >= opts.median[0] &&
        info.median <= opts.median[1],
        'expected median(' + info.median + ') to be within ' +
            opts.median[0] + ' & ' + opts.median[1]
    );

    cassert.ok(
        info.mean >= opts.mean[0] &&
        info.mean <= opts.mean[1],
        'expected mean(' + info.mean + ') to be within ' +
            opts.mean[0] + ' & ' + opts.mean[1]
    );

    cassert.ok(info.max <= opts.max,
        'expected maximum(' + info.max + ') to no more then ' + opts.max
    );
    cassert.ok(
        info.p75 >= opts.p75[0] &&
        info.p75 <= opts.p75[1],
        'expected P75(' + info.p75 + ') to be within ' +
            opts.p75[0] + ' & ' + opts.p75[1]
    );
    cassert.ok(info.p95 <= opts.p95,
        'expected P95 (' + info.p95 + ') to be less than ' + opts.p95
    );

    if (opts.variance) {
        cassert.ok(info.variance <= opts.variance,
            'expected variance(' + info.variance + ') to be less than ' + opts.variance
        );
    }

    return cassert;
}

function setup(cluster, opts) {
    opts = opts || {};
    var NUM_CLIENTS = opts.clients || 40;
    var NUM_SERVERS = opts.servers || cluster.channels.length - NUM_CLIENTS;

    cluster.clients = cluster.channels.slice(0, NUM_CLIENTS);
    cluster.servers = cluster.channels.slice(
        NUM_CLIENTS, NUM_CLIENTS + NUM_SERVERS
    );

    var i;
    for (i = 0; i < cluster.servers.length; i++) {
        makeServer(cluster.servers[i], i);
    }

    cluster.serverHosts = [];
    for (i = 0; i < cluster.servers.length; i++) {
        cluster.serverHosts.push(cluster.servers[i].hostPort);
    }

    cluster.batches = [];
    for (i = 0; i < cluster.clients.length; i++) {
        cluster.batches.push(new BatchClient(
            cluster.clients[i], cluster.serverHosts, {
                delay: 40,
                batchSize: 1,
                totalRequests: 50,
                minConnections: opts.minConnections || null,
                retryLimit: opts.retryLimit || null
            }
        ));
    }
}

function makeServer(channel, index) {
    var chanNum = index + 1;

    var serverChan = channel.makeSubChannel({
        serviceName: 'server'
    });

    serverChan.register('echo', function echo(req, res, arg2, arg3) {
        res.headers.as = 'raw';
        res.sendOk(arg2, arg3 + ' served by ' + chanNum);
    });
}
<commit_msg>reduce flaps<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var collectParallel = require('collect-parallel/array');
var metrics = require('metrics');

var allocCluster = require('./lib/alloc-cluster.js');
var BatchClient = require('./lib/batch-client.js');
var CollapsedAssert = require('./lib/collapsed-assert.js');

allocCluster.test('p2p requests from 40 -> 40', {
    numPeers: 80
}, function t(cluster, assert) {
    setup(cluster);

    collectParallel(cluster.batches, function runRequests(batch, _, cb) {
        batch.sendRequests(cb);
    }, onBatches);

    /*eslint max-statements: [2, 40]*/
    function onBatches(err, results) {
        var cassert = CollapsedAssert();
        cassert.ifError(err);

        var statuses = [];
        for (var i = 0; i < results.length; i++) {
            cassert.ifError(results[i].err, 'expect no batch error');
            cassert.ifError(results[i].value.errors.length > 0,
                'expect zero errors in batch');
            statuses.push(results[i].value);
        }
        cassert.report(assert, 'expected no errors');

        var statusTable = findServerHostDistribution(statuses);

        var uniqHosts = Object.keys(statusTable);
        if (uniqHosts.length < 35) {
            checkConnections();
            checkDistributions(statusTable);
        } else {
            assert.ok(true, 'SKIP: suprisingly large number of peers reached');
        }

        assert.end();
    }

    function checkConnections() {
        var cassert = CollapsedAssert();
        var distribution = new metrics.Histogram();
        for (var i = 0; i < cluster.batches.length; i++) {
            var connCount = countConnections(cluster.batches[i]);
            distribution.update(connCount);

            cassert.ok(
                connCount >= 1 &&
                connCount <= 5,
                'expected a small number of connections'
            );
        }

        var info = distribution.printObj();
        cassert.ok(info.min <= 2, 'expected low minimum');
        cassert.ok(info.max <= 5, 'expected low maximum');
        cassert.ok(info.sum <= 100, 'expected low total connections');
        cassert.ok(info.p75 <= 2, 'expected low p75');
        // console.log('conn distribution', info);

        cassert.report(assert, 'expected batch connections to be fine');
    }

    function checkDistributions(statusTable) {
        var uniqHosts = Object.keys(statusTable);
        assert.ok(uniqHosts.length <= 35,
            'Expected host reached (' + uniqHosts.length + ') to <= 35');

        var distribution = new metrics.Histogram();
        for (var i = 0; i < uniqHosts.length; i++) {
            distribution.update(statusTable[uniqHosts[i]]);
        }

        var info = distribution.printObj();

        var cassert = CollapsedAssert();
        cassert.ok(info.min <= 50,
            'expected minimum to be no more then 50'
        );
        cassert.equal(info.sum, 2000,
            'expected 2000 requests to be made'
        );
        cassert.ok(info.median >= 48,
            'expected median (' + info.median + ') to be larger then 49'
        );
        cassert.ok(info.max >= 100, 'expected maximum to be huge');
        cassert.ok(info.p75 >= 50, 'expected P75 to be huge');
        cassert.ok(info.p95 > 80, 'expected P95 to be huge');
        cassert.ok(info.variance >= 600,
            'expected variance (' + info.variance + ') to be huge'
        );
        // console.log('conn distribution', info);

        cassert.report(assert, 'expected request distribution to be ok');
    }
});

allocCluster.test('p2p requests from 40 -> 40 with minConnections', {
    numPeers: 80,
    channelOptions: {
        choosePeerWithHeap: true
    }
}, function t(cluster, assert) {
    setup(cluster, {
        minConnections: 10
    });

    collectParallel(cluster.batches, function runRequests(batch, _, cb) {
        batch.sendRequests(cb);
    }, onBatches);

    /*eslint max-statements: [2, 40]*/
    function onBatches(err, results) {
        var cassert = CollapsedAssert();
        cassert.ifError(err);

        var statuses = [];
        for (var i = 0; i < results.length; i++) {
            cassert.ifError(results[i].err, 'expect no batch error');
            cassert.ifError(results[i].value.errors.length > 0,
                'expect zero errors in batch');
            statuses.push(results[i].value);
        }
        cassert.report(assert, 'expected no errors');

        var statusTable = findServerHostDistribution(statuses);

        cassert = verifyConnections(cluster, 10, 12);
        cassert.report(assert, 'expected batch connections to be fine');

        cassert = verifyDistributions(statusTable, {
            min: 40,
            sum: 2000,
            median: [40, 60],
            mean: [45, 55],
            max: 120,
            p75: [55, 70],
            p95: 95,
            variance: 400
        });
        cassert.report(assert, 'expected request distribution to be ok');

        assert.end();
    }
});

allocCluster.test('p2p requests where minConns > no of servers', {
    numPeers: 45,
    channelOptions: {
        choosePeerWithHeap: true
    }
}, function t(cluster, assert) {
    setup(cluster, {
        minConnections: 6,
        servers: 5
    });

    collectParallel(cluster.batches, function runRequests(batch, _, cb) {
        batch.sendRequests(cb);
    }, onBatches);

    /*eslint max-statements: [2, 40]*/
    function onBatches(err, results) {
        var cassert = CollapsedAssert();
        cassert.ifError(err);

        var statuses = [];
        for (var i = 0; i < results.length; i++) {
            cassert.ifError(results[i].err, 'expect no batch error');
            cassert.ifError(results[i].value.errors.length > 0,
                'expect zero errors in batch');

            statuses.push(results[i].value);
        }
        cassert.report(assert, 'expected no errors');

        var statusTable = findServerHostDistribution(statuses);

        cassert = verifyConnections(cluster, 5, 5);
        cassert.report(assert, 'expected batch connections to be fine');

        cassert = verifyDistributions(statusTable, {
            min: 395,
            sum: 2000,
            median: [380, 420],
            mean: [395, 405],
            max: 500,
            p75: [400, 450],
            p95: 475
        });
        cassert.report(assert, 'expected request distribution to be ok');

        assert.end();
    }
});

allocCluster.test('p2p requests where half of servers down', {
    numPeers: 48,
    channelOptions: {
        choosePeerWithHeap: true
    }
}, function t(cluster, assert) {
    cluster.logger.whitelist('info', 'resetting connection');
    setup(cluster, {
        minConnections: 5,
        servers: 8,
        retryLimit: 2
    });

    // Close half the servers...
    for (var j = 0; j < cluster.servers.length / 2; j++) {
        cluster.servers[j * 2].close();
    }

    collectParallel(cluster.batches, function runRequests(batch, _, cb) {
        batch.sendRequests(cb);
    }, onBatches);

    /*eslint max-statements: [2, 40]*/
    function onBatches(err, results) {
        var cassert = CollapsedAssert();
        cassert.ifError(err);

        var statuses = [];
        for (var i = 0; i < results.length; i++) {
            cassert.ifError(results[i].err, 'expect no batch error');
            cassert.ifError(results[i].value.errors.length > 5,
                'expect at most five error in batch(' +
                    results[i].value.errors.length + ')');

            statuses.push(results[i].value);
        }
        cassert.report(assert, 'expected no errors');

        var statusTable = findServerHostDistribution(statuses);

        cassert = verifyConnections(cluster, 4, 4);
        cassert.report(assert, 'expected batch connections to be fine');

        cassert = verifyDistributions(statusTable, {
            min: 495,
            sum: [1990, 2000],
            median: [480, 520],
            mean: [495, 505],
            max: 600,
            p75: [500, 575],
            p95: 600
        });
        cassert.report(assert, 'expected request distribution to be ok');

        assert.end();
    }
});

function findServerHostDistribution(statuses) {
    var statusTable = {};
    for (var i = 0; i < statuses.length; i++) {
        var records = statuses[i].results;
        for (var j = 0; j < records.length; j++) {
            var record = records[j];
            if (!statusTable[record.outReqHostPort]) {
                statusTable[record.outReqHostPort] = 0;
            }
            statusTable[record.outReqHostPort]++;
        }
    }
    return statusTable;
}

function countConnections(batchClient) {
    var subChannel = batchClient.subChannel;
    var peers = subChannel.peers.values();

    var conns = [];
    for (var i = 0; i < peers.length; i++) {
        var peer = peers[i];
        for (var j = 0; j < peer.connections.length; j++) {
            conns.push(peer.connections[j]);
        }
    }

    return conns.length;
}

function verifyConnections(cluster, min, max) {
    var MIN = min;
    var MAX = max;
    var COUNT = cluster.batches.length;

    var cassert = CollapsedAssert();
    var distribution = new metrics.Histogram();
    for (var i = 0; i < cluster.batches.length; i++) {
        var connCount = countConnections(cluster.batches[i]);
        distribution.update(connCount);

        cassert.ok(
            connCount >= MIN &&
            connCount <= MAX,
            'expected connections(' + connCount + ') to be ' +
                '>= ' + MIN + ' and <= ' + MAX
        );
    }

    var info = distribution.printObj();
    cassert.ok(info.min <= MAX,
        'expected min connections(' + info.min + ') to be <= ' + MAX);
    cassert.ok(info.max >= MIN,
        'expected max conns(' + info.max + ') to be >= ' + MIN);
    cassert.ok(info.sum >= COUNT * MIN,
        'expected sum of conns(' + info.sum + ') to be at ' +
            COUNT * MIN + ' conns');
    cassert.ok(info.p75 <= MAX,
        'expected p75(' + info.p75 + ') to be <= ' + MAX);

    return cassert;
}

function verifyDistributions(statusTable, opts) {
    var uniqHosts = Object.keys(statusTable);

    var distribution = new metrics.Histogram();
    for (var i = 0; i < uniqHosts.length; i++) {
        distribution.update(statusTable[uniqHosts[i]]);
    }

    var info = distribution.printObj();

    var cassert = CollapsedAssert();
    cassert.ok(info.min <= opts.min,
        'expected minimum(' + info.min + ') to be no more then ' + opts.min
    );

    if (Array.isArray(opts.sum)) {
        cassert.ok(
            info.sum >= opts.sum[0] &&
            info.sum <= opts.sum[1],
            'expected sum(' + info.sum + ') to be within ' +
                opts.sum[0] + ' & ' + opts.sum[1]
        );
    } else {
        cassert.equal(info.sum, opts.sum,
            'expected sum(' + info.sum + ') to be ' + opts.sum
        );
    }

    cassert.ok(
        info.median >= opts.median[0] &&
        info.median <= opts.median[1],
        'expected median(' + info.median + ') to be within ' +
            opts.median[0] + ' & ' + opts.median[1]
    );

    cassert.ok(
        info.mean >= opts.mean[0] &&
        info.mean <= opts.mean[1],
        'expected mean(' + info.mean + ') to be within ' +
            opts.mean[0] + ' & ' + opts.mean[1]
    );

    cassert.ok(info.max <= opts.max,
        'expected maximum(' + info.max + ') to no more then ' + opts.max
    );
    cassert.ok(
        info.p75 >= opts.p75[0] &&
        info.p75 <= opts.p75[1],
        'expected P75(' + info.p75 + ') to be within ' +
            opts.p75[0] + ' & ' + opts.p75[1]
    );
    cassert.ok(info.p95 <= opts.p95,
        'expected P95 (' + info.p95 + ') to be less than ' + opts.p95
    );

    if (opts.variance) {
        cassert.ok(info.variance <= opts.variance,
            'expected variance(' + info.variance + ') to be less than ' + opts.variance
        );
    }

    return cassert;
}

function setup(cluster, opts) {
    opts = opts || {};
    var NUM_CLIENTS = opts.clients || 40;
    var NUM_SERVERS = opts.servers || cluster.channels.length - NUM_CLIENTS;

    cluster.clients = cluster.channels.slice(0, NUM_CLIENTS);
    cluster.servers = cluster.channels.slice(
        NUM_CLIENTS, NUM_CLIENTS + NUM_SERVERS
    );

    var i;
    for (i = 0; i < cluster.servers.length; i++) {
        makeServer(cluster.servers[i], i);
    }

    cluster.serverHosts = [];
    for (i = 0; i < cluster.servers.length; i++) {
        cluster.serverHosts.push(cluster.servers[i].hostPort);
    }

    cluster.batches = [];
    for (i = 0; i < cluster.clients.length; i++) {
        cluster.batches.push(new BatchClient(
            cluster.clients[i], cluster.serverHosts, {
                delay: 40,
                batchSize: 1,
                totalRequests: 50,
                minConnections: opts.minConnections || null,
                retryLimit: opts.retryLimit || null
            }
        ));
    }
}

function makeServer(channel, index) {
    var chanNum = index + 1;

    var serverChan = channel.makeSubChannel({
        serviceName: 'server'
    });

    serverChan.register('echo', function echo(req, res, arg2, arg3) {
        res.headers.as = 'raw';
        res.sendOk(arg2, arg3 + ' served by ' + chanNum);
    });
}
<|endoftext|>


<commit_before>'use strict'
// support for presentations
var lines=[], index=-1, $i // $i:an <input type=file> used to open the file chooser dialog
function move(d){if(0<=index+d&&index+d<lines.length){index+=d;D.ide.wins[0].loadLine(lines[index])}}

// Key display mode:
var $p // DOM element for the pending key or null if key display mode is off
function keyInfo(e){ // returns a pair of the key name and an "is complete" flag
  var s='' // key name
  e.shiftKey&&e.which&&(s+='Shift-');e.ctrlKey&&(s+='Ctrl-');e.altKey&&(s+='Alt-');e.metaKey&&(s+='Cmd-')
  var k=CodeMirror.keyNames[e.which]||'['+e.which+']'
  var c=!!e.which&&k!=='Shift'&&k!=='Ctrl'&&k!=='Alt'&&k!=='Cmd' // c: is the key combination complete?
  c&&(s+=k);return[s,c]
}
function loadDemoScript(f){ // f:path to file, ignored if empty
  f&&D.readFile(f,'utf8',function(err,s){
    if(err){console.error(err);$.alert('Cannot load demo file');return}
    index=-1
    lines=s.replace(/^[\ufeff\ufffe]/,'').split(/\r?\n/)
           .filter(function(x){return!/^\s*(?:$|⍝⍝)/.test(x)})
           .map(function(x){return'      '+x})
  })
}
D.process&&loadDemoScript(D.process.env.RIDE_DEMO_SCRIPT)
$.extend(CodeMirror.commands,{
  DMN:function(){move( 1)}, // next line
  DMP:function(){move(-1)}, // prev line
  DMR:function(){ // load demo script
    if(D.nwjs&&!D.floating){
      ($i=$i||$('<input id=demo-input type=file style=display:none>').appendTo('body'))
        .trigger('click').change(function(){loadDemoScript(this.value)})
    }
  },
  DMK:function(){ // toggle key display mode
    if($p){$(document).off('.demo');$('#demo-keys').remove();$p=null;return}
    $('body').append($('
').append($p=$('').hide()))
    $(document)
      .on('keydown.demo',function(e){var s=keyInfo(e)[0];$p.text(s).toggle(!!s)})
      .on('keyup.demo',function(e){
        var h=keyInfo(e),s=h[0],c=h[1]
        if(c){$p.hide();var $k=$('').text(s).insertBefore($p);setTimeout(function(){$k.fadeOut(1000)},2000)}
        else{$p.text(s).toggle(!!s)}
      })
  }
})
<commit_msg>demo mode: unselect old file before showing file chooser<commit_after>'use strict'
// support for presentations
var lines=[], index=-1, $i // $i:an <input type=file> used to open the file chooser dialog
function move(d){if(0<=index+d&&index+d<lines.length){index+=d;D.ide.wins[0].loadLine(lines[index])}}

// Key display mode:
var $p // DOM element for the pending key or null if key display mode is off
function keyInfo(e){ // returns a pair of the key name and an "is complete" flag
  var s='' // key name
  e.shiftKey&&e.which&&(s+='Shift-');e.ctrlKey&&(s+='Ctrl-');e.altKey&&(s+='Alt-');e.metaKey&&(s+='Cmd-')
  var k=CodeMirror.keyNames[e.which]||'['+e.which+']'
  var c=!!e.which&&k!=='Shift'&&k!=='Ctrl'&&k!=='Alt'&&k!=='Cmd' // c: is the key combination complete?
  c&&(s+=k);return[s,c]
}
function loadDemoScript(f){ // f:path to file, ignored if empty
  f&&D.readFile(f,'utf8',function(err,s){
    if(err){console.error(err);$.alert('Cannot load demo file');return}
    index=-1
    lines=s.replace(/^[\ufeff\ufffe]/,'').split(/\r?\n/)
           .filter(function(x){return!/^\s*(?:$|⍝⍝)/.test(x)})
           .map(function(x){return'      '+x})
  })
}
D.process&&loadDemoScript(D.process.env.RIDE_DEMO_SCRIPT)
$.extend(CodeMirror.commands,{
  DMN:function(){move( 1)}, // next line
  DMP:function(){move(-1)}, // prev line
  DMR:function(){ // load demo script
    if(D.nwjs&&!D.floating){
      ($i=$i||$('<input id=demo-input type=file style=display:none>').appendTo('body'))
        .val('').click().change(function(){loadDemoScript(this.value)})
    }
  },
  DMK:function(){ // toggle key display mode
    if($p){$(document).off('.demo');$('#demo-keys').remove();$p=null;return}
    $('body').append($('
').append($p=$('').hide()))
    $(document)
      .on('keydown.demo',function(e){var s=keyInfo(e)[0];$p.text(s).toggle(!!s)})
      .on('keyup.demo',function(e){
        var h=keyInfo(e),s=h[0],c=h[1]
        if(c){$p.hide();var $k=$('').text(s).insertBefore($p);setTimeout(function(){$k.fadeOut(1000)},2000)}
        else{$p.text(s).toggle(!!s)}
      })
  }
})
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import Header from './commons/header';

const App = React.createClass({
	render: function() {
		return (

				{ this.props.children }

		);
	}
});

module.exports = App;<commit_msg>Update app.js<commit_after>'use strict'

import React from 'react'
import Header from './commons/header'

const App = React.createClass({
	render: function () {
		return (

				{ this.props.children }

		)
	}
})

module.exports = App
<|endoftext|>


<commit_before>;(function (engine) {
	if (typeof module !== 'undefined' && module.exports) {
		module.exports = engine;
	} else {
		this.ArtifactTemplateEngine = engine;
	}

})(function () {
	var exports = {},
		partials = {},
		helpers = {
			'each': function (object, contentBlock) {
				var content = '';

				for (var key in object) {
					if (object.hasOwnProperty(key)) {
						content += contentBlock(object[key], {key: key, index: key});
					}

				}

				return content;

			}

		},

		fnBegin = 'function(meta,root,parent,helpers,partials){meta=meta||{};' +
			'meta.context=this;meta.parent=parent;var out="',

		regexp = [
			// handle new lines :
			[/\n/g, '\\n'],
			// remove comments {{!-- xy --}} or {{! xy}} :
			[/({{!--.+?--}}|{{!.+?}})/g, ''],
			// handle double quotes :
			[/(")(?![^{]*}})/g, '\\"'],
			// if :
			[/{{#if (.+?)}}/g, '";if($1){out+="'],
			// else if :
			[/{{#elseif (.+?)}}/g, '"}else if($1){out+="'],
			// else :
			[/{{#else}}/g, '"}else{out+="'],
			// end if :
			[/{{\/if}}/g, '"}out+="'],
			// singe helper :
			[/{{#(.+?) (.+?)\/}}/g, '"+helpers.$1.call(this,($2))+"'],
			// singe helper without arguments :
			[/{{#(.+?)\/}}/g, '"+helpers.$1.call(this)+"'],
			// open block helper :
			[/{{#(.+?) (.+?)}}/g, '"+helpers.$1.call(this,($2),function(c,m){return(' + fnBegin],
			// open block helper without arguments :
			[/{{#(.+?)}}/g, '"+helpers.$1(function(c,m){return(' + fnBegin],
			// end block helper :
			[/{{\/(.+?)}}/g, '";return out}).call(c,m,root,meta,helpers,partials)})+"'],
			// partial :
			[/{{>(.+?) (.+?)}}/g, '"+partials.$1($2)+"'],
			// partial without arguments :
			[/{{>(.+?)}}/g, '"+partials.$1()+"'],
			// default :
			[/{{(.+?)}}/g, '"+($1)+"']
		];

	exports.template = function (_templateString) {
		return function (_context) {
			_context = _context || {};
			return eval('(' + fnBegin + (function () {
					for (var i = 0; i < regexp.length; i++) {
						_templateString = _templateString.replace(regexp[i][0], regexp[i][1]);
					}

					return _templateString;

				})() + '";return out})').call(_context, {}, _context, false, helpers, partials);

		}

	};

	exports.addHelper = function (_helperName, _function) {
		helpers[_helperName] = _function;
	};

	exports.addPartial = function (_partialName, _templateString) {
		partials[_partialName] = exports.template(_templateString);
	};

	return exports;

});
<commit_msg>Update engine.js<commit_after>;(function (engine) {
	if (typeof module !== 'undefined' && module.exports) {
		module.exports = engine;
	} else {
		this.Arti = engine;
	}

})(function () {
	var exports = {},
		partials = {},
		helpers = {
			'each': function (object, contentBlock) {
				var content = '';

				for (var key in object) {
					if (object.hasOwnProperty(key)) {
						content += contentBlock(object[key], {key: key, index: key});
					}
				}
				return content;

			}
		},

		fnBegin = 'function(meta,root,parent,helpers,partials){meta=meta||{};' +
			'meta.context=this;meta.parent=parent;var out="',

		regexp = [
			// handle new lines :
			[/\n/g, '\\n'],
			// remove comments {{!-- xy --}} or {{! xy}} :
			[/({{!--.+?--}}|{{!.+?}})/g, ''],
			// handle double quotes :
			[/(")(?![^{]*}})/g, '\\"'],
			// if :
			[/{{#if (.+?)}}/g, '";if($1){out+="'],
			// else if :
			[/{{#elseif (.+?)}}/g, '"}else if($1){out+="'],
			// else :
			[/{{#else}}/g, '"}else{out+="'],
			// end if :
			[/{{\/if}}/g, '"}out+="'],
			// singe helper :
			[/{{#(.+?) (.+?)\/}}/g, '"+helpers.$1.call(this,($2))+"'],
			// singe helper without arguments :
			[/{{#(.+?)\/}}/g, '"+helpers.$1.call(this)+"'],
			// open block helper :
			[/{{#(.+?) (.+?)}}/g, '"+helpers.$1.call(this,($2),function(c,m){return(' + fnBegin],
			// open block helper without arguments :
			[/{{#(.+?)}}/g, '"+helpers.$1(function(c,m){return(' + fnBegin],
			// end block helper :
			[/{{\/(.+?)}}/g, '";return out}).call(c,m,root,meta,helpers,partials)})+"'],
			// partial :
			[/{{>(.+?) (.+?)}}/g, '"+partials.$1($2)+"'],
			// partial without arguments :
			[/{{>(.+?)}}/g, '"+partials.$1()+"'],
			// default :
			[/{{(.+?)}}/g, '"+($1)+"']
		];

	function getFnStringFromTemplateString(_templateString) {
		var i;

		for (i = 0; i < regexp.length; i++) {
			templateString = templateString.replace(regexp[i][0], regexp[i][1]);
		}
		return '(' + fnBegin + templateString + '";return out})';

	}

	exports.template = function(_templateString) {
		var fn;

		try {
			fn = eval(getFnStringFromTemplateString(_templateString));
			return function (context) {
				context = context || {};
				return fn.call(context, {}, context, false, helpers, partials);
			}

		} catch (e) {
			console.error('template error:', e, getFnStringFromTemplateString(_templateString));

		}

	};

	exports.addHelper = function (_helperName, _function) {
		helpers[_helperName] = _function;

	};

	exports.addPartial = function (_partialName, _templateString) {
		partials[_partialName] = exports.template(_templateString);

	};

	return exports;

});
<|endoftext|>


<commit_before>'use strict';

module.exports = [{
  name: 'Don\'t Stop Retrievin\'',
  title: 'A single page web app for Seattle dog owners to find nearby off leash areas',
  description: 'This page was a group project I worked on in my second class at Code Fellows. The idea behind the project was to give dog owners in Seattle a means of finding the closest off leash dog parks to them. As one of four members in the group, I worked on both Javascript and HTML/CSS. We pulled our data from the data.seattle.gov api, then filtered it to get just the parks that were relevant to our project. We also used the google maps api to show users where nearby parks were in relation to their current location.',
  displayName: 'dont-stop-retrievin',
  url: 'https://dont-stop-retrieving.herokuapp.com/',
  githubUrl: 'https://github.com/Keiranbeaton/dont-stop-retrieving',
  images: [{url: require('./dsr-main.png'), text: 'Main Page View'}, {url: require('./dsr-single.png'), text: 'Single Park View'}]
},
{
  name: 'Sports Messenger',
  title: 'A single page web app that allows residents of Seattle to find Seattle parks to play pick up sports at. We were working under time constraints so this app is still a work in progress.',
  description: 'This page was the final group project I completed at Code Fellows. I was one of three people in the group, and worked mostly on Javascript, both frontend and backend. Our goal was to create an app that allowed users to search local parks based on their sporting facilities, and to rate and comment on these parks so other users would be able to find the level of competition they were looking for. We also implemented a sign up and sign in function so that only registered users could view the site, and leave comments and ratings.',
  displayName: 'sports-messenger',
  url: 'https://stormy-fjord-91599.herokuapp.com/#/home',
  githubUrl: 'https://github.com/sports-messenger/sports-messenger',
  images: [{url: require('./sm-home.png'), text: 'Main Page View'}, {url: require('./sm-signin.png'), text: 'Sign In View'}]
},
{
  name: 'Cam\'s Big Idea',
  title: 'A website that connects older professionals with businesses in need of their experience and expertise.',
  description: 'This is a project I am working on for a friend. His idea is to create a site that will help professionals who no longer want to work full time but are still interested in lending their skills and knowledge to companies in a consulting role. They create a profile where they can list their experience, education and skills, along with how many hours a week they are looking to work. These profiles can then be accessed by companies via a search page, that will allow them ',
  displayName: 'cams-big-idea',
  url: 'https://cams-big-idea.herokuapp.com/',
  githubUrl: 'https://github.com/Keiranbeaton/cams-big-idea',
  images: [{url: require('./cbi-search.png'), text: 'Find Professionals View'}, {url: require('./cbi-edit-prof.png'), text: 'Edit Profile View'}]
}];
<commit_msg>added libraries and databases to projects file<commit_after>'use strict';

module.exports = [{
  name: 'Don\'t Stop Retrievin\'',
  title: 'A single page web app for Seattle dog owners to find nearby off leash areas',
  description: 'This page was a group project I worked on in my second class at Code Fellows. The idea behind the project was to give dog owners in Seattle a means of finding the closest off leash dog parks to them. As one of four members in the group, I worked on both Javascript and HTML/CSS. We pulled our data from the data.seattle.gov api, then filtered it to get just the parks that were relevant to our project. We also used the google maps api to show users where nearby parks were in relation to their current location.',
  displayName: 'dont-stop-retrievin',
  url: 'https://dont-stop-retrieving.herokuapp.com/',
  githubUrl: 'https://github.com/Keiranbeaton/dont-stop-retrieving',
  images: [{url: require('./dsr-main.png'), text: 'Main Page View'}, {url: require('./dsr-single.png'), text: 'Single Park View'}],
  technology: ['jQuery', 'Firebase']
},
{
  name: 'Sports Messenger',
  title: 'A single page web app that allows residents of Seattle to find Seattle parks to play pick up sports at. We were working under time constraints so this app is still a work in progress.',
  description: 'This page was the final group project I completed at Code Fellows. I was one of three people in the group, and worked mostly on Javascript, both frontend and backend. Our goal was to create an app that allowed users to search local parks based on their sporting facilities, and to rate and comment on these parks so other users would be able to find the level of competition they were looking for. We also implemented a sign up and sign in function so that only registered users could view the site, and leave comments and ratings.',
  displayName: 'sports-messenger',
  url: 'https://stormy-fjord-91599.herokuapp.com/#/home',
  githubUrl: 'https://github.com/sports-messenger/sports-messenger',
  images: [{url: require('./sm-home.png'), text: 'Main Page View'}, {url: require('./sm-signin.png'), text: 'Sign In View'}],
  technology: ['Angular', 'Express']
},
{
  name: 'Cam\'s Big Idea',
  title: 'A website that connects older professionals with businesses in need of their experience and expertise.',
  description: 'This is a project I am working on for a friend. His idea is to create a site that will help professionals who no longer want to work full time but are still interested in lending their skills and knowledge to companies in a consulting role. They create a profile where they can list their experience, education and skills, along with how many hours a week they are looking to work. These profiles can then be accessed by companies via a search page, that will allow them ',
  displayName: 'cams-big-idea',
  url: 'https://cams-big-idea.herokuapp.com/',
  githubUrl: 'https://github.com/Keiranbeaton/cams-big-idea',
  images: [{url: require('./cbi-search.png'), text: 'Find Professionals View'}, {url: require('./cbi-edit-prof.png'), text: 'Edit Profile View'}],
  technology: ['Angular', 'Express', 'MongoDB']
}];
<|endoftext|>


<commit_before>// @flow
import { getLogger } from '@jitsi/logger';
import type { Dispatch } from 'redux';

import UIEvents from '../../../service/UI/UIEvents';
import {
    AUDIO_MUTE,
    createRemoteMuteConfirmedEvent,
    createToolbarEvent,
    sendAnalytics,
    VIDEO_MUTE
} from '../analytics';
import { rejectParticipantAudio, rejectParticipantVideo, showModeratedNotification } from '../av-moderation/actions';
import { shouldShowModeratedNotification } from '../av-moderation/functions';
import {
    MEDIA_TYPE,
    setAudioMuted,
    setVideoMuted,
    VIDEO_MUTISM_AUTHORITY
} from '../base/media';
import {
    getLocalParticipant,
    getRemoteParticipants,
    muteRemoteParticipant
} from '../base/participants';
import { toggleScreensharing } from '../base/tracks';
import { isModerationNotificationDisplayed } from '../notifications';

declare var APP: Object;

const logger = getLogger(__filename);

/**
 * Mutes the local participant.
 *
 * @param {boolean} enable - Whether to mute or unmute.
 * @param {MEDIA_TYPE} mediaType - The type of the media channel to mute.
 * @param {boolean} stopScreenSharing - Whether or not to stop the screensharing.
 * @returns {Function}
 */
export function muteLocal(enable: boolean, mediaType: MEDIA_TYPE, stopScreenSharing: boolean = false) {
    return (dispatch: Dispatch<any>, getState: Function) => {
        const isAudio = mediaType === MEDIA_TYPE.AUDIO;

        if (!isAudio && mediaType !== MEDIA_TYPE.VIDEO) {
            logger.error(`Unsupported media type: ${mediaType}`);

            return;
        }

        // check for A/V Moderation when trying to unmute
        if (!enable && shouldShowModeratedNotification(MEDIA_TYPE.AUDIO, getState())) {
            if (!isModerationNotificationDisplayed(MEDIA_TYPE.AUDIO, getState())) {
                dispatch(showModeratedNotification(MEDIA_TYPE.AUDIO));
            }

            return;
        }

        if (enable && stopScreenSharing) {
            dispatch(toggleScreensharing(false, false, true));
        }

        sendAnalytics(createToolbarEvent(isAudio ? AUDIO_MUTE : VIDEO_MUTE, { enable }));
        dispatch(isAudio ? setAudioMuted(enable, /* ensureTrack */ true)
            : setVideoMuted(enable, mediaType, VIDEO_MUTISM_AUTHORITY.USER, /* ensureTrack */ true));

        // FIXME: The old conference logic still relies on this event being emitted.
        typeof APP === 'undefined'
            || APP.UI.emitEvent(isAudio ? UIEvents.AUDIO_MUTED : UIEvents.VIDEO_MUTED, enable);
    };
}

/**
 * Mutes the remote participant with the given ID.
 *
 * @param {string} participantId - ID of the participant to mute.
 * @param {MEDIA_TYPE} mediaType - The type of the media channel to mute.
 * @returns {Function}
 */
export function muteRemote(participantId: string, mediaType: MEDIA_TYPE) {
    return (dispatch: Dispatch<any>) => {
        if (mediaType !== MEDIA_TYPE.AUDIO && mediaType !== MEDIA_TYPE.VIDEO) {
            logger.error(`Unsupported media type: ${mediaType}`);

            return;
        }
        sendAnalytics(createRemoteMuteConfirmedEvent(participantId, mediaType));
        dispatch(muteRemoteParticipant(participantId, mediaType));
    };
}

/**
 * Mutes all participants.
 *
 * @param {Array<string>} exclude - Array of participant IDs to not mute.
 * @param {MEDIA_TYPE} mediaType - The media type to mute.
 * @returns {Function}
 */
export function muteAllParticipants(exclude: Array<string>, mediaType: MEDIA_TYPE) {
    return (dispatch: Dispatch<any>, getState: Function) => {
        const state = getState();
        const localId = getLocalParticipant(state).id;

        if (!exclude.includes(localId)) {
            dispatch(muteLocal(true, mediaType, true));
        }

        getRemoteParticipants(state).forEach((p, id) => {
            if (exclude.includes(id)) {
                return;
            }

            dispatch(muteRemote(id, mediaType));
            if (mediaType === MEDIA_TYPE.AUDIO) {
                dispatch(rejectParticipantAudio(id));
            } else {
                dispatch(rejectParticipantVideo(id));
            }
        });
    };
}

<commit_msg>fix(av-moderation) Don't stop local screensharing on mute all<commit_after>// @flow
import { getLogger } from '@jitsi/logger';
import type { Dispatch } from 'redux';

import UIEvents from '../../../service/UI/UIEvents';
import {
    AUDIO_MUTE,
    createRemoteMuteConfirmedEvent,
    createToolbarEvent,
    sendAnalytics,
    VIDEO_MUTE
} from '../analytics';
import { rejectParticipantAudio, rejectParticipantVideo, showModeratedNotification } from '../av-moderation/actions';
import { shouldShowModeratedNotification } from '../av-moderation/functions';
import {
    MEDIA_TYPE,
    setAudioMuted,
    setVideoMuted,
    VIDEO_MUTISM_AUTHORITY
} from '../base/media';
import {
    getLocalParticipant,
    getRemoteParticipants,
    muteRemoteParticipant
} from '../base/participants';
import { toggleScreensharing } from '../base/tracks';
import { isModerationNotificationDisplayed } from '../notifications';

declare var APP: Object;

const logger = getLogger(__filename);

/**
 * Mutes the local participant.
 *
 * @param {boolean} enable - Whether to mute or unmute.
 * @param {MEDIA_TYPE} mediaType - The type of the media channel to mute.
 * @param {boolean} stopScreenSharing - Whether or not to stop the screensharing.
 * @returns {Function}
 */
export function muteLocal(enable: boolean, mediaType: MEDIA_TYPE, stopScreenSharing: boolean = false) {
    return (dispatch: Dispatch<any>, getState: Function) => {
        const isAudio = mediaType === MEDIA_TYPE.AUDIO;

        if (!isAudio && mediaType !== MEDIA_TYPE.VIDEO) {
            logger.error(`Unsupported media type: ${mediaType}`);

            return;
        }

        // check for A/V Moderation when trying to unmute
        if (!enable && shouldShowModeratedNotification(MEDIA_TYPE.AUDIO, getState())) {
            if (!isModerationNotificationDisplayed(MEDIA_TYPE.AUDIO, getState())) {
                dispatch(showModeratedNotification(MEDIA_TYPE.AUDIO));
            }

            return;
        }

        if (enable && stopScreenSharing) {
            dispatch(toggleScreensharing(false, false, true));
        }

        sendAnalytics(createToolbarEvent(isAudio ? AUDIO_MUTE : VIDEO_MUTE, { enable }));
        dispatch(isAudio ? setAudioMuted(enable, /* ensureTrack */ true)
            : setVideoMuted(enable, mediaType, VIDEO_MUTISM_AUTHORITY.USER, /* ensureTrack */ true));

        // FIXME: The old conference logic still relies on this event being emitted.
        typeof APP === 'undefined'
            || APP.UI.emitEvent(isAudio ? UIEvents.AUDIO_MUTED : UIEvents.VIDEO_MUTED, enable);
    };
}

/**
 * Mutes the remote participant with the given ID.
 *
 * @param {string} participantId - ID of the participant to mute.
 * @param {MEDIA_TYPE} mediaType - The type of the media channel to mute.
 * @returns {Function}
 */
export function muteRemote(participantId: string, mediaType: MEDIA_TYPE) {
    return (dispatch: Dispatch<any>) => {
        if (mediaType !== MEDIA_TYPE.AUDIO && mediaType !== MEDIA_TYPE.VIDEO) {
            logger.error(`Unsupported media type: ${mediaType}`);

            return;
        }
        sendAnalytics(createRemoteMuteConfirmedEvent(participantId, mediaType));
        dispatch(muteRemoteParticipant(participantId, mediaType));
    };
}

/**
 * Mutes all participants.
 *
 * @param {Array<string>} exclude - Array of participant IDs to not mute.
 * @param {MEDIA_TYPE} mediaType - The media type to mute.
 * @returns {Function}
 */
export function muteAllParticipants(exclude: Array<string>, mediaType: MEDIA_TYPE) {
    return (dispatch: Dispatch<any>, getState: Function) => {
        const state = getState();
        const localId = getLocalParticipant(state).id;

        if (!exclude.includes(localId)) {
            dispatch(muteLocal(true, mediaType, mediaType !== MEDIA_TYPE.AUDIO));
        }

        getRemoteParticipants(state).forEach((p, id) => {
            if (exclude.includes(id)) {
                return;
            }

            dispatch(muteRemote(id, mediaType));
            if (mediaType === MEDIA_TYPE.AUDIO) {
                dispatch(rejectParticipantAudio(id));
            } else {
                dispatch(rejectParticipantVideo(id));
            }
        });
    };
}

<|endoftext|>