<commit_before>/**
 * Base Avatar
 *
 * @param {Player} player
 */
function BaseAvatar(player)
{
    EventEmitter.call(this);

    this.id              = player.id;
    this.name            = player.name;
    this.color           = player.color;
    this.player          = player;
    this.x               = 0;
    this.y               = 0;
    this.trail           = new Trail(this);
    this.bonusStack      = new BonusStack(this);
    this.angle           = 0;
    this.velocityX       = 0;
    this.velocityY       = 0;
    this.angularVelocity = 0;
    this.alive           = true;
    this.printing        = false;
    this.score           = 0;
    this.roundScore      = 0;
    this.ready           = false;
    this.present         = true;
	BaseAvatar.prototype.velocity = 16;
	if( BaseAvatar.prototype.speed === true){
		BaseAvatar.prototype.velocity = 56;
	    this.updateVelocities();
		console.log('speed mode');
	}
	if(	BaseAvatar.prototype.speed === false){
		BaseAvatar.prototype.velocity = 16;
	    this.updateVelocities();
		console.log('normal mode');
	}

    this.updateVelocities();
}

BaseAvatar.prototype = Object.create(EventEmitter.prototype);
BaseAvatar.prototype.constructor = BaseAvatar;

if( BaseAvatar.prototype.speed === true){
	BaseAvatar.prototype.velocity = 56;
	this.updateVelocities();
	console.log('speed mode');
}
if(	BaseAvatar.prototype.speed === false){
	BaseAvatar.prototype.velocity = 16;
	this.updateVelocities();
	console.log('normal mode');
}
/**
 * Movement velocity
 *
 * @type {Number}
 */

var doneTheStuff;

	function boosta(){
		return;
	}

/**
 * Turn velocity
 *
 * @type {Float}
 */
BaseAvatar.prototype.angularVelocityBase = 2.8/1000;

/**
 * Radius
 *
 * @type {Number}
 */
BaseAvatar.prototype.radius = 0.6;

/**
 * Number of trail points that don't kill the player
 *
 * @type {Number}
 */
BaseAvatar.prototype.trailLatency = 3;

/**
 * Inverted controls
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.inverse = false;

/**
 * Invincible
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.invincible = false;

/**
 * Type of tunrn: round or straight
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.directionInLoop = true;

/**
 * Equal
 *
 * @param {Avatar} avatar
 *
 * @return {Boolean}
 */

 function sp1(){
	 BaseAvatar.prototype.speed = true;
	 boosta();
	 //BaseAvatar.prototype.setVelocity.call(this, 'velocity', 0.75 * 16);
	 //BaseAvatar.prototype.setVelocity.call(velocity);
	 if(!doneTheStuff){

	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
 function sp2(){
	 BaseAvatar.prototype.speed = false;
	 boosta();
	 if(!doneTheStuff){

	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
BaseAvatar.prototype.equal = function(avatar)
{
    return this.id === avatar.id;
};

/**
 * Set Point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.setPosition = function(x, y)
{
    this.x = x;
    this.y = y;
};

/**
 * Add point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.addPoint = function(x, y)
{
    this.trail.addPoint(x, y);
};

/**
 * Update angular velocity
 *
 * @param {Number} factor
 */
BaseAvatar.prototype.updateAngularVelocity = function(factor)
{
    if (typeof(factor) === 'undefined') {
        if (this.angularVelocity === 0) { return; }
        factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1);
    }

    this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1));
};

/**
 * Set angular velocity
 *
 * @param {Float} angularVelocity
 */
BaseAvatar.prototype.setAngularVelocity = function(angularVelocity)
{
    this.angularVelocity = angularVelocity;
};

/**
 * Set angle
 *
 * @param {Float} angle
 */
BaseAvatar.prototype.setAngle = function(angle)
{
    if (this.angle !== angle) {
        this.angle = angle;
        this.updateVelocities();
    }
};

/**
 * Update
 *
 * @param {Number} step
 */
BaseAvatar.prototype.update = function(step) {
boosta();

};

/**
 * Add angle
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updateAngle = function(step)
{
    if (this.angularVelocity) {
        if (this.directionInLoop) {
            this.setAngle(this.angle + this.angularVelocity * step);
        } else {
            this.setAngle(this.angle + this.angularVelocity * step);
            this.updateAngularVelocity(0);

        }
    }
};

/**
 * Update position
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updatePosition = function(step)
{
    this.setPosition(
        this.x + this.velocityX * step,
        this.y + this.velocityY * step
    );
};

/**
 * Set velocity
 *
 * @param {Number} step
 */
BaseAvatar.prototype.setVelocity = function(velocity)
{

    velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2);

    if (this.velocity !== velocity) {
        this.velocity = velocity;
        this.updateVelocities();
    }
};
/**
 * Update velocities
 */
BaseAvatar.prototype.updateVelocities = function()
{
	var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};

/**
 * Update base angular velocity
 */
BaseAvatar.prototype.updateBaseAngularVelocity = function()
{
    if (this.directionInLoop) {
        var ratio = this.velocity / BaseAvatar.prototype.velocity;
        this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000;
        this.updateAngularVelocity();
    }
};

/**
 * Set radius
 *
 * @param {Number} radius
 */
BaseAvatar.prototype.setRadius = function(radius)
{
    this.radius = Math.max(radius, BaseAvatar.prototype.radius/8);
};

/**
 * Set inverse
 *
 * @param {Number} inverse
 */
BaseAvatar.prototype.setInverse = function(inverse)
{
    if (this.inverse !== inverse) {
        this.inverse = inverse ? true : false;
        this.updateAngularVelocity();
    }
};

/**
 * Set invincible
 *
 * @param {Number} invincible
 */
BaseAvatar.prototype.setInvincible = function(invincible)
{
    this.invincible = invincible ? true : false;
};

/**
 * Get distance
 *
 * @param {Number} fromX
 * @param {Number} fromY
 * @param {Number} toX
 * @param {Number} toY
 *
 * @return {Number}
 */
BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY)
{
    return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2));
};

/**
 * Die
 */
BaseAvatar.prototype.die = function()
{
    this.bonusStack.clear();
    this.alive = false;
    this.addPoint(this.x, this.y);
};

/**
 * Set printing
 *
 * @param {Boolean} printing
 */
BaseAvatar.prototype.setPrinting = function(printing)
{
    printing = printing ? true : false;

    if (this.printing !== printing) {
        this.printing = printing;

        this.addPoint(this.x, this.y, true);

        if (!this.printing) {
            this.trail.clear();
        }
    }
	console.log(BaseAvatar.prototype.velocity);
	console.log(BaseAvatar.prototype.speed);
	boosta();
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.addScore = function(score)
{
    this.setRoundScore(this.roundScore + score);
};

/**
 * Resolve score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.resolveScore = function()
{
    this.setScore(this.score + this.roundScore);
    this.roundScore = 0;
};

/**
 * This round score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setRoundScore = function(score)
{
    this.roundScore = score;
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setScore = function(score)
{
    this.score = score;
};

/**
 * Set color
 *
 * @param {Number} color
 */
BaseAvatar.prototype.setColor = function(color)
{
    this.color = color;
};

/**
 * Clear
 */
BaseAvatar.prototype.clear = function()
{
    this.bonusStack.clear();

    this.x                   = this.radius;
    this.y                   = this.radius;
    this.angle               = 0;
    this.velocityX           = 0;
    this.velocityY           = 0;
    this.angularVelocity     = 0;
    this.roundScore          = 0;
    this.velocity            = BaseAvatar.prototype.velocity;
    this.alive               = true;
    this.printing            = false;
    this.color               = this.player.color;
    this.radius              = BaseAvatar.prototype.radius;
    this.inverse             = BaseAvatar.prototype.inverse;
    this.invincible          = BaseAvatar.prototype.invincible;
    this.directionInLoop     = BaseAvatar.prototype.directionInLoop;
    this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase;

    if (this.body) {
        this.body.radius = BaseAvatar.prototype.radius;
    }

    // useless? this.updateVelocities();
};

/**
 * Destroy
 */
BaseAvatar.prototype.destroy = function()
{
    this.clear();
    this.present = false;
    this.alive   = false;
};

/**
 * Serialize
 *
 * @return {Object}
 */
BaseAvatar.prototype.serialize = function()
{
    return {
        id: this.id,
        name: this.name,
        color: this.color,
        score: this.score
    };
};
<commit_msg>sdgdsg<commit_after>/**
 * Base Avatar
 *
 * @param {Player} player
 */
function BaseAvatar(player)
{
    EventEmitter.call(this);

    this.id              = player.id;
    this.name            = player.name;
    this.color           = player.color;
    this.player          = player;
    this.x               = 0;
    this.y               = 0;
    this.trail           = new Trail(this);
    this.bonusStack      = new BonusStack(this);
    this.angle           = 0;
    this.velocityX       = 0;
    this.velocityY       = 0;
    this.angularVelocity = 0;
    this.alive           = true;
    this.printing        = false;
    this.score           = 0;
    this.roundScore      = 0;
    this.ready           = false;
    this.present         = true;
	BaseAvatar.prototype.velocity = 16;
	if( BaseAvatar.prototype.speed === true){
		this.velocity = 56;
	    this.updateVelocities();
		console.log('speed mode');
	}
	if(	BaseAvatar.prototype.speed === false){
		this.velocity = 16;
	    this.updateVelocities();
		console.log('normal mode');
	}

    this.updateVelocities();
}

BaseAvatar.prototype = Object.create(EventEmitter.prototype);
BaseAvatar.prototype.constructor = BaseAvatar;

if( BaseAvatar.prototype.speed === true){
	BaseAvatar.prototype.velocity = 56;
	this.updateVelocities();
	console.log('speed mode');
}
if(	BaseAvatar.prototype.speed === false){
	BaseAvatar.prototype.velocity = 16;
	this.updateVelocities();
	console.log('normal mode');
}
/**
 * Movement velocity
 *
 * @type {Number}
 */

var doneTheStuff;

	function boosta(){
		return;
	}

/**
 * Turn velocity
 *
 * @type {Float}
 */
BaseAvatar.prototype.angularVelocityBase = 2.8/1000;

/**
 * Radius
 *
 * @type {Number}
 */
BaseAvatar.prototype.radius = 0.6;

/**
 * Number of trail points that don't kill the player
 *
 * @type {Number}
 */
BaseAvatar.prototype.trailLatency = 3;

/**
 * Inverted controls
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.inverse = false;

/**
 * Invincible
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.invincible = false;

/**
 * Type of tunrn: round or straight
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.directionInLoop = true;

/**
 * Equal
 *
 * @param {Avatar} avatar
 *
 * @return {Boolean}
 */

 function sp1(){
	 BaseAvatar.prototype.speed = true;
	 boosta();
	 //BaseAvatar.prototype.setVelocity.call(this, 'velocity', 0.75 * 16);
	 //BaseAvatar.prototype.setVelocity.call(velocity);
	 if(!doneTheStuff){

	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
 function sp2(){
	 BaseAvatar.prototype.speed = false;
	 boosta();
	 if(!doneTheStuff){

	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
BaseAvatar.prototype.equal = function(avatar)
{
    return this.id === avatar.id;
};

/**
 * Set Point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.setPosition = function(x, y)
{
    this.x = x;
    this.y = y;
};

/**
 * Add point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.addPoint = function(x, y)
{
    this.trail.addPoint(x, y);
};

/**
 * Update angular velocity
 *
 * @param {Number} factor
 */
BaseAvatar.prototype.updateAngularVelocity = function(factor)
{
    if (typeof(factor) === 'undefined') {
        if (this.angularVelocity === 0) { return; }
        factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1);
    }

    this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1));
};

/**
 * Set angular velocity
 *
 * @param {Float} angularVelocity
 */
BaseAvatar.prototype.setAngularVelocity = function(angularVelocity)
{
    this.angularVelocity = angularVelocity;
};

/**
 * Set angle
 *
 * @param {Float} angle
 */
BaseAvatar.prototype.setAngle = function(angle)
{
    if (this.angle !== angle) {
        this.angle = angle;
        this.updateVelocities();
    }
};

/**
 * Update
 *
 * @param {Number} step
 */
BaseAvatar.prototype.update = function(step) {
boosta();

};

/**
 * Add angle
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updateAngle = function(step)
{
    if (this.angularVelocity) {
        if (this.directionInLoop) {
            this.setAngle(this.angle + this.angularVelocity * step);
        } else {
            this.setAngle(this.angle + this.angularVelocity * step);
            this.updateAngularVelocity(0);

        }
    }
};

/**
 * Update position
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updatePosition = function(step)
{
    this.setPosition(
        this.x + this.velocityX * step,
        this.y + this.velocityY * step
    );
};

/**
 * Set velocity
 *
 * @param {Number} step
 */
BaseAvatar.prototype.setVelocity = function(velocity)
{

    velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2);

    if (this.velocity !== velocity) {
        this.velocity = velocity;
        this.updateVelocities();
    }
};
/**
 * Update velocities
 */
BaseAvatar.prototype.updateVelocities = function()
{
	var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};

/**
 * Update base angular velocity
 */
BaseAvatar.prototype.updateBaseAngularVelocity = function()
{
    if (this.directionInLoop) {
        var ratio = this.velocity / BaseAvatar.prototype.velocity;
        this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000;
        this.updateAngularVelocity();
    }
};

/**
 * Set radius
 *
 * @param {Number} radius
 */
BaseAvatar.prototype.setRadius = function(radius)
{
    this.radius = Math.max(radius, BaseAvatar.prototype.radius/8);
};

/**
 * Set inverse
 *
 * @param {Number} inverse
 */
BaseAvatar.prototype.setInverse = function(inverse)
{
    if (this.inverse !== inverse) {
        this.inverse = inverse ? true : false;
        this.updateAngularVelocity();
    }
};

/**
 * Set invincible
 *
 * @param {Number} invincible
 */
BaseAvatar.prototype.setInvincible = function(invincible)
{
    this.invincible = invincible ? true : false;
};

/**
 * Get distance
 *
 * @param {Number} fromX
 * @param {Number} fromY
 * @param {Number} toX
 * @param {Number} toY
 *
 * @return {Number}
 */
BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY)
{
    return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2));
};

/**
 * Die
 */
BaseAvatar.prototype.die = function()
{
    this.bonusStack.clear();
    this.alive = false;
    this.addPoint(this.x, this.y);
};

/**
 * Set printing
 *
 * @param {Boolean} printing
 */
BaseAvatar.prototype.setPrinting = function(printing)
{
    printing = printing ? true : false;

    if (this.printing !== printing) {
        this.printing = printing;

        this.addPoint(this.x, this.y, true);

        if (!this.printing) {
            this.trail.clear();
        }
    }
	console.log(BaseAvatar.prototype.velocity);
	console.log(BaseAvatar.prototype.speed);
	boosta();
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.addScore = function(score)
{
    this.setRoundScore(this.roundScore + score);
};

/**
 * Resolve score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.resolveScore = function()
{
    this.setScore(this.score + this.roundScore);
    this.roundScore = 0;
};

/**
 * This round score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setRoundScore = function(score)
{
    this.roundScore = score;
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setScore = function(score)
{
    this.score = score;
};

/**
 * Set color
 *
 * @param {Number} color
 */
BaseAvatar.prototype.setColor = function(color)
{
    this.color = color;
};

/**
 * Clear
 */
BaseAvatar.prototype.clear = function()
{
    this.bonusStack.clear();

    this.x                   = this.radius;
    this.y                   = this.radius;
    this.angle               = 0;
    this.velocityX           = 0;
    this.velocityY           = 0;
    this.angularVelocity     = 0;
    this.roundScore          = 0;
    this.velocity            = BaseAvatar.prototype.velocity;
    this.alive               = true;
    this.printing            = false;
    this.color               = this.player.color;
    this.radius              = BaseAvatar.prototype.radius;
    this.inverse             = BaseAvatar.prototype.inverse;
    this.invincible          = BaseAvatar.prototype.invincible;
    this.directionInLoop     = BaseAvatar.prototype.directionInLoop;
    this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase;

    if (this.body) {
        this.body.radius = BaseAvatar.prototype.radius;
    }

    // useless? this.updateVelocities();
};

/**
 * Destroy
 */
BaseAvatar.prototype.destroy = function()
{
    this.clear();
    this.present = false;
    this.alive   = false;
};

/**
 * Serialize
 *
 * @return {Object}
 */
BaseAvatar.prototype.serialize = function()
{
    return {
        id: this.id,
        name: this.name,
        color: this.color,
        score: this.score
    };
};
<|endoftext|>


<commit_before>import ENVIRONMENT, { ENVIRONMENTS } from '../../environment'

const baseConfig = {
  RADIUS: 50, // Thumbnail search radius
  THUMBNAIL_WIDTH: 240,
  PANORAMA_THUMBNAIL_URL: 'panorama/thumbnail/',
  AUTH_HEADER_PREFIX: 'Bearer ',
  // Allows sanity checking input of root keys based on white listing
  ROOT_KEYS: ['API_ROOT'],
  CACHE_THRESHOLD: 30, // number of records
}

const environmentConfig = {
  [ENVIRONMENTS.PRODUCTION]: {
    IIIF_ROOT: 'https://acc.images.data.amsterdam.nl/',
    API_ROOT: 'https://api.data.amsterdam.nl/',
    CMS_ROOT: 'https://cms.data.amsterdam.nl/',
    ROOT: 'https://data.amsterdam.nl/',
  },
  [ENVIRONMENTS.ACCEPTANCE]: {
    IIIF_ROOT: 'https://acc.images.data.amsterdam.nl/',
    API_ROOT: 'https://acc.api.data.amsterdam.nl/',
    CMS_ROOT: 'https://acc.cms.data.amsterdam.nl/',
    ROOT: 'https://acc.data.amsterdam.nl/',
  },
  [ENVIRONMENTS.DEVELOPMENT]: {
    IIIF_ROOT: 'https://acc.images.data.amsterdam.nl/',
    API_ROOT: 'https://acc.api.data.amsterdam.nl/',
    CMS_ROOT: 'https://acc.cms.data.amsterdam.nl/',
    ROOT: 'https://acc.data.amsterdam.nl/',
  },
}

const SHARED_CONFIG = {
  ...baseConfig,
  ...environmentConfig[ENVIRONMENT],
}

export default SHARED_CONFIG
<commit_msg>Use the production server url for the iiif-server on prod env<commit_after>import ENVIRONMENT, { ENVIRONMENTS } from '../../environment'

const baseConfig = {
  RADIUS: 50, // Thumbnail search radius
  THUMBNAIL_WIDTH: 240,
  PANORAMA_THUMBNAIL_URL: 'panorama/thumbnail/',
  AUTH_HEADER_PREFIX: 'Bearer ',
  // Allows sanity checking input of root keys based on white listing
  ROOT_KEYS: ['API_ROOT'],
  CACHE_THRESHOLD: 30, // number of records
}

const environmentConfig = {
  [ENVIRONMENTS.PRODUCTION]: {
    IIIF_ROOT: 'https://images.data.amsterdam.nl/',
    API_ROOT: 'https://api.data.amsterdam.nl/',
    CMS_ROOT: 'https://cms.data.amsterdam.nl/',
    ROOT: 'https://data.amsterdam.nl/',
  },
  [ENVIRONMENTS.ACCEPTANCE]: {
    IIIF_ROOT: 'https://acc.images.data.amsterdam.nl/',
    API_ROOT: 'https://acc.api.data.amsterdam.nl/',
    CMS_ROOT: 'https://acc.cms.data.amsterdam.nl/',
    ROOT: 'https://acc.data.amsterdam.nl/',
  },
  [ENVIRONMENTS.DEVELOPMENT]: {
    IIIF_ROOT: 'https://acc.images.data.amsterdam.nl/',
    API_ROOT: 'https://acc.api.data.amsterdam.nl/',
    CMS_ROOT: 'https://acc.cms.data.amsterdam.nl/',
    ROOT: 'https://acc.data.amsterdam.nl/',
  },
}

const SHARED_CONFIG = {
  ...baseConfig,
  ...environmentConfig[ENVIRONMENT],
}

export default SHARED_CONFIG
<|endoftext|>


<commit_before>'use babel';

import React from 'react-lite'

export default class ButtonBar extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (

          <button className="btn status">Connect</button>

          <button className="btn resume">Resume</button>
          <button className="btn step-in">Step In</button>
          <button className="btn step-out">Step Out</button>
          <button className="btn step-over">Step Over</button>

    );
  }
}
<commit_msg>Button bar click handlers.<commit_after>'use babel';

import React from 'react-lite'

export default class ButtonBar extends React.Component {

  constructor(props) {
    super(props);
  }

  // Event Handlers
  handleClickConnection(e) {
    console.log('Click Connection');
  }

  handleClickResume(e) {
    console.log('Click Resume');
  }

  handleClickStepIn(e) {
    console.log('Click Step In');
  }

  handleClickStepOut(e) {
    console.log('Click Step Out');
  }

  handleClickStepOver(e) {
    console.log('Click Step Over');
  }

  // Render
  render() {
    return (

          <button className="btn status" onClick={this.handleClickConnection}>Connect</button>

          <button className="btn resume" onClick={this.handleClickResume}>Resume</button>
          <button className="btn step-in" onClick={this.handleClickStepIn}>Step In</button>
          <button className="btn step-out" onClick={this.handleClickStepOut}>Step Out</button>
          <button className="btn step-over" onClick={this.handleClickStepOver}>Step Over</button>

    );
  }
}
<|endoftext|>


<commit_before>var fs = require('fs');
var async = require('async');
var open = require('open');
var generator = require('yeoman-generator');
var util = require('util');

// The `yo yo` generator provides users with a few common, helpful commands.
var yoyo = function yoyo() {
  generator.Base.apply(this, arguments);

  // Find the installed generators and their respective package.json files.
  this._findGenerators();

  // Start this party.
  this.home();
};

util.inherits(yoyo, generator.Base);

// Rolls through all of the generators provided by `env.generators`, finding
// their `package.json` files, then storing them internally in `this.pkgs`.
yoyo.prototype._findGenerators = function findGenerators() {
  var self = this;
  self.pkgs = {};

  var resolvedGenerators = [];
  var resolveGenerators = function (generator) {
    var generatorPath = generator.resolved.replace(/(\/.*generator[^\/]*)\/.*/, '$1/package.json');

    return function (next) {
      if (resolvedGenerators.indexOf(generatorPath) > -1 || !fs.existsSync(generatorPath)) {
        return next();
      }

      var pkg = JSON.parse(self.readFileAsString(generatorPath));
      self.pkgs[pkg.name] = pkg;

      resolvedGenerators.push(generatorPath);
    };
  };

  async.parallel(self._.map(self.env.generators, resolveGenerators), function (err) {
    if (err) {
      return self.emit('error', err);
    }
  });
};

// Display the home `yo` screen, with the intial set of options.
//
// - options - (optional)
//           - message (string) - String to print before prompt.
//           - refresh (bool) - Spawn a new `yo` command.
yoyo.prototype.home = function home(options) {
  options = options || {};

  if (options.refresh) {
    return this.spawnCommand('yo');
  }

  if (options.message) {
    console.log('\n' + options.message.cyan + '\n');
  }

  var generators = this._.chain(this.env.generators).map(function (generator) {
    var namespace = generator.namespace;
    var prettyName;

    if (namespace.substr(-4) === ':app') {
      prettyName = namespace.replace(':app', '');
      prettyName = prettyName.charAt(0).toUpperCase() + prettyName.slice(1);
      return {
        name: 'Run the ' + prettyName + ' generator',
        value: {
          method: 'initGenerator',
          args: namespace
        }
      };
    }
  }).compact().value();

  this.prompt([{
    name: 'whatNext',
    type: 'list',
    message: 'What would you like to do?',
    choices: this._.union(generators, [{
      name: 'Update your generators',
      value: {
        method: 'updateGenerators'
      }
    }, {
      name: 'Install a generator',
      value: {
        method: 'installGenerator'
      }
    }, {
      name: 'Find some help',
      value: {
        method: 'findHelp'
      }
    }, {
      name: 'Get me out of here!',
      value: {
        method: 'exit'
      }
    }])
  }], function (answer) {
    this[answer.whatNext.method](answer.whatNext.args);
  }.bind(this));
};

// Runs parallel `npm update -g`s for each detected generator.
yoyo.prototype.updateGenerators = function updateGenerators() {
  var self = this;

  var resolveGenerators = function (pkg) {
    return function (next) {
      self.spawnCommand('npm', ['update', '-g', pkg.name])
        .on('error', next)
        .on('exit', next);
    };
  };

  async.parallel(self._.map(self.pkgs, resolveGenerators), function (err) {
    if (err) {
      return self.emit('error', err);
    }

    self.home({
      message: 'You\'re all set! Is there anything else I can get you?'
    });
  });
};

// Initializes a generator.
//
// - generator - (string) The generator to initialize.
yoyo.prototype.initGenerator = function initGenerator(generator) {
  console.log((
    '\nBefore you create a new application, be sure you are running this command'
    + '\nfrom the directory you wish your application to be dropped into.'
    + '\n'
  ).yellow);

  this.spawnCommand('yo', [generator]);
};

// Serves as the response prompt for "Install a generator" as well as simply
// installs a generator if a string is passed in.
//
// - pkgName - (optional) A string that matches the NPM package name.
yoyo.prototype.installGenerator = function installGenerator(pkgName) {
  if (this._.isString(pkgName)) {
    // We know what generator we want to install
    return this.spawnCommand('npm', ['install', '-g', pkgName])
      .on('error', function (err) {
        this.emit('error', err);
      }.bind(this))
      .on('exit', function () {
        this.home({
          refresh: true
        });
      }.bind(this));
  }

  this.prompt([{
    name: 'searchTerm',
    message: 'Search NPM for generators'
  }], this.searchNpm.bind(this));
};

// Grabs all of the packages with a `yeoman-generator` keyword on NPM.
//
// - term - (object) Contains the search term & gets passed back to callback().
// - cb   - Callback to execute once generators have been found.
yoyo.prototype._findAllNpmGenerators = function findAllNpmGenerators(term, cb) {
  var url = 'http://isaacs.iriscouch.com/registry/_design/app/_view/byKeyword?startkey=[%22yeoman-generator%22]&endkey=[%22yeoman-generator%22,{}]&group_level=3';

  this.request(url, function (err, res, body) {
    if (err) {
      return this.emit('error', err);
    }

    this.npmGenerators = JSON.parse(body);
    cb(term);
  }.bind(this));
};

// Takes a search term, looks it up in the registry, prompts the user with the
// results, allowing them to choose to install it, or go back home.
//
// - term - Object with a 'searchTerm' property containing the term to search
//          NPM for.
yoyo.prototype.searchNpm = function searchNpm(term) {
  if (!this.npmGenerators) {
    return this._findAllNpmGenerators(term, this.searchNpm.bind(this));
  }

  // Find any matches from NPM.
  var choices = this._.chain(this.npmGenerators.rows).map(function (generator) {
    // Make sure it's not already installed.
    if (!this.pkgs[generator.key[1]] && generator.key.join(' ').indexOf(term.searchTerm) > -1) {
      return {
        name: generator.key[1],
        value: generator.key[1]
      };
    }
  }.bind(this)).compact().value();

  var resultsPrompt = [{
    name: 'installGenerator',
    type: 'list',
    message: choices.length > 0 ? 'Here\'s what I found. Install one?' : 'Sorry, nothing was found',
    choices: this._.union(choices, {
      name: 'Search again',
      value: 'installGenerator'
    }, {
      name: 'Return home',
      value: 'home'
    })
  }];

  this.prompt(resultsPrompt, function (answer) {
    if (this._.isFunction(this[answer.installGenerator])) {
      return this[answer.installGenerator]();
    }

    this.installGenerator(answer.installGenerator);
  }.bind(this));
};

// Prompts user with a few helpful resources, then opens it in their browser.
yoyo.prototype.findHelp = function findHelp() {
  this.prompt([{
    name: 'whereTo',
    type: 'list',
    message: 'Here are a few helpful resources.'
      + '\n\nI will open the link you select in your browser for you',
    choices: [{
      name: 'Take me to the documentation',
      value: 'https://github.com/yeoman/yeoman/wiki'
    }, {
      name: 'View Frequently Asked Questions',
      value: 'https://github.com/yeoman/yeoman/wiki/FAQ'
    }, {
      name: 'File an issue on GitHub',
      value: 'https://github.com/yeoman/yeoman/blob/master/contributing.md#issue-submission'
    }, {
      name: 'Take me back home, Yo!',
      value: {
        method: 'home',
        args: {
          message: 'I get it, you like learning on your own. I respect that.'
        }
      }
    }]
  }], function (answer) {
    if (this._.isFunction(this[answer.whereTo.method])) {
      return this[answer.whereTo.method](answer.whereTo.args);
    }

    open(answer.whereTo);
  }.bind(this));
};

// Serves as a quick escape from the `yo yo` prompts.
yoyo.prototype.exit = function exit() {
  console.log(
      '\nBye from us! Chat soon.'
    + '\n'
    + '\n            Add' + 'y'.red.bold + ' Osmani'
    + '\n          Sindr' + 'e'.red.bold + ' Sorhus'
    + '\n        Brian F' + 'o'.red.bold + 'rd'
    + '\n     Eric Bidel' + 'm'.red.bold + 'an'
    + '\n              P' + 'a'.red.bold + 'ul Irish'
    + '\n     Mickael Da' + 'n'.red.bold + 'iel'
    + '\n          Pasca' + '1'.yellow.bold + ' Hartig'
    + '\n      Stephen S' + '.'.cyan.bold + 'wchuk'
    + '\n    Frederick R' + '0'.yellow.bold + 's'
    + '\n');
};

module.exports = function (env) {
  env.register(yoyo, 'yo').create('yo');
};
<commit_msg>(yoyo) Confirm a file is package.json.<commit_after>var fs = require('fs');
var async = require('async');
var open = require('open');
var generator = require('yeoman-generator');
var util = require('util');
var path = require('path');

// The `yo yo` generator provides users with a few common, helpful commands.
var yoyo = function yoyo() {
  generator.Base.apply(this, arguments);

  // Find the installed generators and their respective package.json files.
  this._findGenerators();

  // Start this party.
  this.home();
};

util.inherits(yoyo, generator.Base);

// Rolls through all of the generators provided by `env.generators`, finding
// their `package.json` files, then storing them internally in `this.pkgs`.
yoyo.prototype._findGenerators = function findGenerators() {
  var self = this;
  self.pkgs = {};

  var resolvedGenerators = [];
  var resolveGenerators = function (generator) {
    var generatorPath = generator.resolved.replace(/(\/.*generator[^\/]*)\/.*/, '$1/package.json');

    return function (next) {
      var alreadyResolved = resolvedGenerators.indexOf(generatorPath) > -1;
      var isPackageJSON = path.basename(generatorPath) === 'package.json';

      if (alreadyResolved || !isPackageJSON || !fs.existsSync(generatorPath)) {
        return next();
      }

      var pkg = JSON.parse(self.readFileAsString(generatorPath));
      self.pkgs[pkg.name] = pkg;

      resolvedGenerators.push(generatorPath);
    };
  };

  async.parallel(self._.map(self.env.generators, resolveGenerators), function (err) {
    if (err) {
      return self.emit('error', err);
    }
  });
};

// Display the home `yo` screen, with the intial set of options.
//
// - options - (optional)
//           - message (string) - String to print before prompt.
//           - refresh (bool) - Spawn a new `yo` command.
yoyo.prototype.home = function home(options) {
  options = options || {};

  if (options.refresh) {
    return this.spawnCommand('yo');
  }

  if (options.message) {
    console.log('\n' + options.message.cyan + '\n');
  }

  var generators = this._.chain(this.env.generators).map(function (generator) {
    var namespace = generator.namespace;
    var prettyName;

    if (namespace.substr(-4) === ':app') {
      prettyName = namespace.replace(':app', '');
      prettyName = prettyName.charAt(0).toUpperCase() + prettyName.slice(1);
      return {
        name: 'Run the ' + prettyName + ' generator',
        value: {
          method: 'initGenerator',
          args: namespace
        }
      };
    }
  }).compact().value();

  this.prompt([{
    name: 'whatNext',
    type: 'list',
    message: 'What would you like to do?',
    choices: this._.union(generators, [{
      name: 'Update your generators',
      value: {
        method: 'updateGenerators'
      }
    }, {
      name: 'Install a generator',
      value: {
        method: 'installGenerator'
      }
    }, {
      name: 'Find some help',
      value: {
        method: 'findHelp'
      }
    }, {
      name: 'Get me out of here!',
      value: {
        method: 'exit'
      }
    }])
  }], function (answer) {
    this[answer.whatNext.method](answer.whatNext.args);
  }.bind(this));
};

// Runs parallel `npm update -g`s for each detected generator.
yoyo.prototype.updateGenerators = function updateGenerators() {
  var self = this;

  var resolveGenerators = function (pkg) {
    return function (next) {
      self.spawnCommand('npm', ['update', '-g', pkg.name])
        .on('error', next)
        .on('exit', next);
    };
  };

  async.parallel(self._.map(self.pkgs, resolveGenerators), function (err) {
    if (err) {
      return self.emit('error', err);
    }

    self.home({
      message: 'You\'re all set! Is there anything else I can get you?'
    });
  });
};

// Initializes a generator.
//
// - generator - (string) The generator to initialize.
yoyo.prototype.initGenerator = function initGenerator(generator) {
  console.log((
    '\nBefore you create a new application, be sure you are running this command'
    + '\nfrom the directory you wish your application to be dropped into.'
    + '\n'
  ).yellow);

  this.spawnCommand('yo', [generator]);
};

// Serves as the response prompt for "Install a generator" as well as simply
// installs a generator if a string is passed in.
//
// - pkgName - (optional) A string that matches the NPM package name.
yoyo.prototype.installGenerator = function installGenerator(pkgName) {
  if (this._.isString(pkgName)) {
    // We know what generator we want to install
    return this.spawnCommand('npm', ['install', '-g', pkgName])
      .on('error', function (err) {
        this.emit('error', err);
      }.bind(this))
      .on('exit', function () {
        this.home({
          refresh: true
        });
      }.bind(this));
  }

  this.prompt([{
    name: 'searchTerm',
    message: 'Search NPM for generators'
  }], this.searchNpm.bind(this));
};

// Grabs all of the packages with a `yeoman-generator` keyword on NPM.
//
// - term - (object) Contains the search term & gets passed back to callback().
// - cb   - Callback to execute once generators have been found.
yoyo.prototype._findAllNpmGenerators = function findAllNpmGenerators(term, cb) {
  var url = 'http://isaacs.iriscouch.com/registry/_design/app/_view/byKeyword?startkey=[%22yeoman-generator%22]&endkey=[%22yeoman-generator%22,{}]&group_level=3';

  this.request(url, function (err, res, body) {
    if (err) {
      return this.emit('error', err);
    }

    this.npmGenerators = JSON.parse(body);
    cb(term);
  }.bind(this));
};

// Takes a search term, looks it up in the registry, prompts the user with the
// results, allowing them to choose to install it, or go back home.
//
// - term - Object with a 'searchTerm' property containing the term to search
//          NPM for.
yoyo.prototype.searchNpm = function searchNpm(term) {
  if (!this.npmGenerators) {
    return this._findAllNpmGenerators(term, this.searchNpm.bind(this));
  }

  // Find any matches from NPM.
  var choices = this._.chain(this.npmGenerators.rows).map(function (generator) {
    // Make sure it's not already installed.
    if (!this.pkgs[generator.key[1]] && generator.key.join(' ').indexOf(term.searchTerm) > -1) {
      return {
        name: generator.key[1],
        value: generator.key[1]
      };
    }
  }.bind(this)).compact().value();

  var resultsPrompt = [{
    name: 'installGenerator',
    type: 'list',
    message: choices.length > 0 ? 'Here\'s what I found. Install one?' : 'Sorry, nothing was found',
    choices: this._.union(choices, {
      name: 'Search again',
      value: 'installGenerator'
    }, {
      name: 'Return home',
      value: 'home'
    })
  }];

  this.prompt(resultsPrompt, function (answer) {
    if (this._.isFunction(this[answer.installGenerator])) {
      return this[answer.installGenerator]();
    }

    this.installGenerator(answer.installGenerator);
  }.bind(this));
};

// Prompts user with a few helpful resources, then opens it in their browser.
yoyo.prototype.findHelp = function findHelp() {
  this.prompt([{
    name: 'whereTo',
    type: 'list',
    message: 'Here are a few helpful resources.'
      + '\n\nI will open the link you select in your browser for you',
    choices: [{
      name: 'Take me to the documentation',
      value: 'https://github.com/yeoman/yeoman/wiki'
    }, {
      name: 'View Frequently Asked Questions',
      value: 'https://github.com/yeoman/yeoman/wiki/FAQ'
    }, {
      name: 'File an issue on GitHub',
      value: 'https://github.com/yeoman/yeoman/blob/master/contributing.md#issue-submission'
    }, {
      name: 'Take me back home, Yo!',
      value: {
        method: 'home',
        args: {
          message: 'I get it, you like learning on your own. I respect that.'
        }
      }
    }]
  }], function (answer) {
    if (this._.isFunction(this[answer.whereTo.method])) {
      return this[answer.whereTo.method](answer.whereTo.args);
    }

    open(answer.whereTo);
  }.bind(this));
};

// Serves as a quick escape from the `yo yo` prompts.
yoyo.prototype.exit = function exit() {
  console.log(
      '\nBye from us! Chat soon.'
    + '\n'
    + '\n            Add' + 'y'.red.bold + ' Osmani'
    + '\n          Sindr' + 'e'.red.bold + ' Sorhus'
    + '\n        Brian F' + 'o'.red.bold + 'rd'
    + '\n     Eric Bidel' + 'm'.red.bold + 'an'
    + '\n              P' + 'a'.red.bold + 'ul Irish'
    + '\n     Mickael Da' + 'n'.red.bold + 'iel'
    + '\n          Pasca' + '1'.yellow.bold + ' Hartig'
    + '\n      Stephen S' + '.'.cyan.bold + 'wchuk'
    + '\n    Frederick R' + '0'.yellow.bold + 's'
    + '\n');
};

module.exports = function (env) {
  env.register(yoyo, 'yo').create('yo');
};
<|endoftext|>


<commit_before>
!function(){

  "use strict";

  var viewModel,bindableElements;

  // ObservingWrapper
  function cropArgs(args,n)
  {
    return Array.prototype.slice.call(args,n);
  }

  function getDeepPropertyNames(obj)
  {
    var proto,names,protoNames,reduceNames,i,n;

    names=Object.getOwnPropertyNames(obj);
    for(i=0,n=names.length;i<n;i++)
      if(names[i].indexOf('__')===0&&names[i].lastIndexOf('__')===names[i].length-2){
        names.splice(i,1);
        i--;
        n--;
      }

    (proto=Object.getPrototypeOf(obj)) && (names=names.concat(
      getDeepPropertyNames(proto)));

    return names;
  }

  function ObservingWrapper(sourceObject,initHandler)
  {
    this.sourceObject=sourceObject||undefined;
    this.observableKeys={};
    this.changeHandlers=[];
    this.specificHandlers={};

    Object.defineProperty(this.observableKeys,'__observingWrapper',{value:this});
    this.defineObservableProperties();
  }

  ObservingWrapper.getSourceObject = function(obj) {
    if(obj.__observingWrapper)
      return obj.__observingWrapper.sourceObject;
    return obj;
  }

  ObservingWrapper.prototype.addChangeHandler=function(){
    var key,userPropertyName,userChangeHandler;

    if(['string','number'].indexOf(typeof arguments[0])>-1 && typeof arguments
      [1]==='function')
    {
      userPropertyName=arguments[0];
      userChangeHandler=arguments[1];
    }
    else
      userChangeHandler=arguments[0];

    if(userPropertyName!==undefined){
      this.specificHandlers[userPropertyName]||(this.specificHandlers[
        userPropertyName]=[]);
      if(this.specificHandlers[userPropertyName].indexOf(userChangeHandler)===-1)
      {
        this.specificHandlers[userPropertyName].push(userChangeHandler);
        typeof this.sourceObject[userPropertyName]!=='function'&&
          userChangeHandler.call(this.sourceObject,[{name:userPropertyName,
            object:this.observableKeys,type:'update',oldValue:this.sourceObject
            [userPropertyName]}]);
      }
    }
    else{
      this.changeHandlers.indexOf(userChangeHandler)===-1&&this.changeHandlers
        .push(userChangeHandler);
      for(key in this.observableKeys)
        typeof this.sourceObject[key]!=='function'&&userChangeHandler.call(this.
          observableKeys,[{name:key,object:this.observableKeys,type:'update',
          oldValue:this.sourceObject[key]}]);
    }
  }

  ObservingWrapper.prototype.defineObservableProperties = function() {
    for(var propertyNames=getDeepPropertyNames(this.sourceObject,this.observableKeys),
      i=0,n=propertyNames.length; i<n; i++)
      this.defineObservableProperty(propertyNames[i]);
  }

  ObservingWrapper.prototype.defineObservableProperty = function(propertyName) {
    var ow=this,isEnum=typeof this.sourceObject[propertyName]!=='function';

    function get() {
      return ow.getPropertyValue(propertyName);
    }

    function set(userValue) {
      ow.setPropertyValue(propertyName, userValue);
    }

    Object.defineProperty(this.observableKeys, propertyName, {enumerable:isEnum,
      configurable:true, get:get, set:set});
  }

  ObservingWrapper.prototype.getPropertyValue=function(propertyName){
    var ow=this;
    return typeof this.sourceObject[propertyName]!=='function'
      ? this.sourceObject[propertyName]
      : function(){var len,ok,res,changes;

          len=ow.sourceObject.length,
          res=ow.sourceObject[propertyName].apply(ow.sourceObject,arguments);

          if(len&&len!==ow.sourceObject.length)
            ow.undefineObservableProperties(),
            ow.defineObservableProperties();

          ok=ow.observableKeys,changes=[{name:propertyName,object:ok,type:'call'
            ,arguments:arguments,result:res}];

          if(propertyName==='push')
            changes=[{object:ok,type:'splice',index:ow.sourceObject.length-1,
              removed:[],addedCount:1}];

          else if(propertyName==='splice')
            changes=[{object:ok,type:'splice',index:arguments[0],removed:res,
              addedCount:cropArgs(arguments,2).length}];

          ow.notifyObservers(changes);

          return res;
        };
  }

  ObservingWrapper.prototype.notifyObservers=function(changes){
    var specificHandlers,i,n;

    if(specificHandlers=this.specificHandlers[changes[0].name])
      for(i=0,n=specificHandlers.length;i<n;i++)
        specificHandlers[i].call(this.observableKeys,changes);

    for(i=0,n=this.changeHandlers.length;i<n;i++)
      this.changeHandlers[i].call(this.observableKeys,changes);
  }

  ObservingWrapper.prototype.removeChangeHandler = function() {
    var rmInd,key,userPropertyName,userChangeHandler;

    if(['string','number'].indexOf(typeof arguments[0])>-1 && typeof arguments
      [1]==='function')
    {
      userPropertyName=arguments[0];
      userChangeHandler=arguments[1];
    }
    else
      userChangeHandler=arguments[0];

    if(userPropertyName!==undefined){
      this.specificHandlers[userPropertyName]&&(rmInd=this.specificHandlers[
        userPropertyName].indexOf(userChangeHandler))>-1&&this.specificHandlers[
        userPropertyName].splice(rmInd,1);
    }
    else{
      (rmInd=this.changeHandlers.indexOf(userChangeHandler))>-1&&this.
        changeHandlers.splice(rmInd,1);

      for(key in this.specificHandlers)
        (rmInd=this.specificHandlers[key].indexOf(userChangeHandler))>-1&&this.
          specificHandlers[key].splice(rmInd,1);
    }
  }

  ObservingWrapper.prototype.setPropertyValue=function(propertyName,
    propertyValue){var oldValue;

    if(this.sourceObject[propertyName]!==propertyValue){
      oldValue=this.sourceObject[propertyName];
      this.sourceObject[propertyName]=propertyValue;
      this.notifyObservers([{name:propertyName,object:this.sourceObject,type:
        'update',oldValue:oldValue}]);
    }
  }

  ObservingWrapper.prototype.undefineObservableProperties = function() {
    for(var propertyNames=getDeepPropertyNames(this.observableKeys),i=0,n=
      propertyNames.length; i<n; i++)
      delete this.observableKeys[i];
  }

  // bindbind
  function c(){console.log.apply(console,arguments)}

  function bindElementPaths2ArraySplice(anchorElements,bindingPaths,userModelPath)
  {
    var a,ow;

    a=userModelPath.slice(0,1);
    ow=(byPath(viewModel,a)).__observingWrapper;

    if(ow===undefined){
      ow=new ObservingWrapper(byPath(viewModel,a));
      byPath(viewModel,a,ow.observableKeys);
    }

    ow.addChangeHandler(function(changes){
      for(var m=0;m<changes.length;m++)
        if(changes[m].type==='splice'){
          if(changes[m].addedCount)
            for(var k=0;k<changes[m].addedCount;k++){
              var q=changes[m].index+k-1;
              var f=anchorElements[q].cloneNode(true);
              anchorElements[q].parentNode.insertBefore(f,anchorElements[q].
                nextSibling);
              anchorElements.splice(changes[m].index+k,1,f);

              var j=q+1;
              var modelPath=userModelPath.slice();
              modelPath.splice(1,0,j);
              bindElementPaths2ModelPath(anchorElements[j],bindingPaths,modelPath);
            }
        }
    });
  }

  function bindModelProperty2Element(modelPath,element,valuePath)
  {
    c('bindModelPropertyToElement',{modelPath:modelPath,element:element,valuePath:valuePath})
    var a,b,ow;

    a=modelPath.slice(0,-1);
    b=modelPath.slice(-1)[0];

    ow=(byPath(viewModel,a)).__observingWrapper;

    if(ow===undefined){
      ow=new ObservingWrapper(byPath(viewModel,a));
      byPath(viewModel,a,ow.observableKeys);
    }

    if(valuePath[valuePath.length-1]==='nodeValue'&&!byPath(element,valuePath
      .concat().splice(0,2)))
        element.appendChild(document.createTextNode(''));

    ow.addChangeHandler(b,function(changes){
      for(var m=0;m<changes.length;m++)
        byPath(element,valuePath,changes[m].object[changes[m].name]);
    });
  }

  function bindElementPaths2ModelPath(anchorElement,bindingPaths,modelPath)
  {
    c('bindElementPaths2ModelPath',{anchorElement:anchorElement,bindingPaths:bindingPaths,modelPath:modelPath});

    for(var k=bindingPaths.length;k--;)
      bindModelProperty2Element(modelPath,anchorElement,bindingPaths[k]);
  }

  function byPath(obj,path,value)
  {
    var a,b;
    // c('byPath',{obj:obj,path:path,value:value})

    if(path.length===0)
      return obj;

    a=path.length-1;
    for(b=0;b<a;b++)
      obj=obj[path[b]];

    if(value!==undefined){
      if(path.args===undefined)
        obj[path[a]]=value;
      else{
        if(path.args.ind!==undefined)
          path.args.splice(path.args.ind,1,value);
        obj[path[a]].apply(obj,path.args);
      }
    }

    return obj[path[a]];
  }

  function findBindingPaths(node,placeholder,nodePaths,pathPrefix)
  {
    var a,b,possiblePaths,path,k;

    nodePaths=nodePaths||[];
    pathPrefix=pathPrefix||[];

    [['nodeValue'],['value']].forEach(function(path){
      var value=byPath(node,path);

      if(typeof value==='string'&&(placeholder?value.indexOf(placeholder)>-1:
        true))
          nodePaths.push(pathPrefix.concat(path));

      else if(value===null&&!placeholder)
        nodePaths.push(pathPrefix.concat(['childNodes',0,'nodeValue']));
    });

    if(placeholder){
      if(node.style)
        for(k in node.style)
          if((node.style.getPropertyValue(k)||'').indexOf(placeholder)>-1){
            path=pathPrefix.concat(['style','setProperty']);
            path.args=[k,undefined];
            path.args.ind=1;
            nodePaths.push(path);
          }

      if(node.classList&&placeholder.indexOf(' ')===-1&&node.classList.contains(
        placeholder))
      {
        path=pathPrefix.concat(['classList','remove']);
        path.args=[placeholder];
        nodePaths.push(path);

        path=pathPrefix.concat(['classList','add']);
        path.args=[undefined];
        path.args.ind=0;
        nodePaths.push(path);
      }

      if(node.attributes)
        for(k=node.attributes.length;k--;)
          if(['style','class'].indexOf(node.attributes[k].nodeName)===-1)
            if(node.attributes[k].nodeValue.indexOf(placeholder)>-1){
              path=pathPrefix.concat(['attributes',k,'nodeValue']);
              nodePaths.push(path);
            }
    }

    if((a=node.childNodes.length)&&placeholder)
      while(a--)
        findBindingPaths(node.childNodes[a],placeholder,nodePaths,pathPrefix.
          concat(['childNodes',a]));

    return nodePaths;
  }

  function mergeBindingData(destData,srcData)
  {
    var a,modelPathIn;

    modelPathIn=false;
    for(a=0;a<destData.length;a++)
      modelPathIn=destData[a].modelPath.reduce(function(r,m,i){
        return srcData.modelPath[i]===m&&r},true)||modelPathIn;

    if(!modelPathIn)
      destData.push({modelPath:srcData.modelPath,bindingPaths:srcData.bindingPaths});
  }

  function mergeItemsIntoBindable(bindable,items)
  {
    var a,b;
// c('^^',items)
    for(a=0;a<items.length;a++){
      for(b=0;b<bindable.length;b++){
        if(bindable[b].modelProperty===items[a].modelPath[0]){
          if(bindable[b].anchorElements.indexOf(items[a].anchorElement)===-1){
            if(bindable[b].anchorElements[0].parentNode===items[a].anchorElement
              .parentNode)
            {
              bindable[b].anchorElements.push(items[a].anchorElement);
              items[a]=undefined;
              break;
            }
          }
          else{
            mergeBindingData(bindable[b].bindingData,items[a])
            items[a]=undefined;
            break;
          }
        }
      }
// c('%%',items[a])
      if(items[a])
        bindable.push({anchorElements:[items[a].anchorElement],bindingData:
          [{modelPath:items[a].modelPath,bindingPaths:items[a].bindingPaths}],
          modelProperty:items[a].modelPath[0]});
    }
  }

  function collectBindableElements()
  {
    var a,b,d,e,f,g,h;

    a=document.body.getElementsByTagName('*'),f=[];

    for(b=0;b<a.length;b++){
      e=[];

      for(d=0;d<a[b].attributes.length;d++)
        if(a[b].attributes[d].name.indexOf('bb-')===0){
          g=a[b].attributes[d].name.substring(3).split(':').splice(0,2);

          e.push({anchorElement:a[b],modelPath:g,bindingPaths:
            findBindingPaths(a[b],a[b].attributes[d].value)});
        }

      if(e.length)
        mergeItemsIntoBindable(f,e);
    }

    return f;
  }

  function __collectBindableElements()
  {
    var a,b,c,d,e,f,g,h;

    a=[],g=[],b=document.body.getElementsByTagName('*');

    for(c=b.length;c--;)
      for(d=b[c].attributes.length;d--;)
        if(b[c].attributes[d].name.indexOf('bb-')===0){
          f=b[c].attributes[d].name.substring(3).split(':');

          if(-1===(e=g.indexOf(f[0])))
            g.push(f[0]),
            e=a.push({modelPath:f,bindingData:[]})-1;

          for(h=a[e].bindingData.length;h--;)
            if(a[e].bindingData[h].anchorElements[0].parentNode===b[c].parentNode)
              break;

          if(h>-1)
            a[e].bindingData[h].anchorElements.unshift(b[c]);

          else
            a[e].bindingData.push({anchorElements:[b[c]],bindingPaths:
              findBindingPaths(b[c],b[c].attributes[d].value)});
        }

    return a;
  }

  function bind()
  {
    for(var l=bindableElements.length;l--;){
      var userModelPath=bindableElements[l].modelPath;
      var u=ObservingWrapper.getSourceObject(viewModel[userModelPath[0]]);
      var w=(u&&Array.isArray(u)&&u.length)||0;

      for(var o=bindableElements[l].bindingData.length;o--;){
        var bindingPaths=bindableElements[l].bindingData[o].bindingPaths;
        var anchorElements=bindableElements[l].bindingData[o].anchorElements;

        if(w>1)
          for(var q=0;q<w-1;q++){
            if(anchorElements[q+1]!==undefined)
              continue;

            var f=anchorElements[q].cloneNode(true);
            anchorElements[q].parentNode.insertBefore(f,anchorElements[q].
              nextSibling);
            anchorElements.push(f);
          }

        if(Array.isArray(ObservingWrapper.getSourceObject(viewModel[
          userModelPath[0]])))
        {
          bindElementPaths2ArraySplice(anchorElements,bindingPaths,userModelPath);

          for(var j=viewModel[userModelPath[0]].length;j--;){
            var modelPath=userModelPath.slice();
            modelPath.splice(1,0,j);
            bindElementPaths2ModelPath(anchorElements[j],bindingPaths,modelPath);
          }
        }
        else
          bindElementPaths2ModelPath(anchorElements[0],bindingPaths,userModelPath);
      }
    }
  }

  function afterDOMContentLoaded()
  {
    bindableElements=collectBindableElements();
    c('bindableElements',bindableElements);

    if(viewModel)
      bind();
  }

  function bindbind(userViewModel)
  {
    viewModel=(new ObservingWrapper(userViewModel)).observableKeys;

    if(document.readyState==='complete')
      bind();

    return viewModel;
  }

  if(document.readyState==='complete'||document.readyState==='interactive')
    afterDOMContentLoaded();
  else
    document.addEventListener("DOMContentLoaded",afterDOMContentLoaded,false);

  if(window.define===undefined)
    window.bindbind=bindbind;
  else
    define(function(){return bindbind});

}(window)
<commit_msg>Update binding to fit new data collection object<commit_after>
!function(){

  "use strict";

  var viewModel,bindableElements;

  // ObservingWrapper
  function cropArgs(args,n)
  {
    return Array.prototype.slice.call(args,n);
  }

  function getDeepPropertyNames(obj)
  {
    var proto,names,protoNames,reduceNames,i,n;

    names=Object.getOwnPropertyNames(obj);
    for(i=0,n=names.length;i<n;i++)
      if(names[i].indexOf('__')===0&&names[i].lastIndexOf('__')===names[i].length-2){
        names.splice(i,1);
        i--;
        n--;
      }

    (proto=Object.getPrototypeOf(obj)) && (names=names.concat(
      getDeepPropertyNames(proto)));

    return names;
  }

  function ObservingWrapper(sourceObject,initHandler)
  {
    this.sourceObject=sourceObject||undefined;
    this.observableKeys={};
    this.changeHandlers=[];
    this.specificHandlers={};

    Object.defineProperty(this.observableKeys,'__observingWrapper',{value:this});
    this.defineObservableProperties();
  }

  ObservingWrapper.getSourceObject = function(obj) {
    if(obj.__observingWrapper)
      return obj.__observingWrapper.sourceObject;
    return obj;
  }

  ObservingWrapper.prototype.addChangeHandler=function(){
    var key,userPropertyName,userChangeHandler;

    if(['string','number'].indexOf(typeof arguments[0])>-1 && typeof arguments
      [1]==='function')
    {
      userPropertyName=arguments[0];
      userChangeHandler=arguments[1];
    }
    else
      userChangeHandler=arguments[0];

    if(userPropertyName!==undefined){
      this.specificHandlers[userPropertyName]||(this.specificHandlers[
        userPropertyName]=[]);
      if(this.specificHandlers[userPropertyName].indexOf(userChangeHandler)===-1)
      {
        this.specificHandlers[userPropertyName].push(userChangeHandler);
        typeof this.sourceObject[userPropertyName]!=='function'&&
          userChangeHandler.call(this.sourceObject,[{name:userPropertyName,
            object:this.observableKeys,type:'update',oldValue:this.sourceObject
            [userPropertyName]}]);
      }
    }
    else{
      this.changeHandlers.indexOf(userChangeHandler)===-1&&this.changeHandlers
        .push(userChangeHandler);
      for(key in this.observableKeys)
        typeof this.sourceObject[key]!=='function'&&userChangeHandler.call(this.
          observableKeys,[{name:key,object:this.observableKeys,type:'update',
          oldValue:this.sourceObject[key]}]);
    }
  }

  ObservingWrapper.prototype.defineObservableProperties = function() {
    for(var propertyNames=getDeepPropertyNames(this.sourceObject,this.observableKeys),
      i=0,n=propertyNames.length; i<n; i++)
      this.defineObservableProperty(propertyNames[i]);
  }

  ObservingWrapper.prototype.defineObservableProperty = function(propertyName) {
    var ow=this,isEnum=typeof this.sourceObject[propertyName]!=='function';

    function get() {
      return ow.getPropertyValue(propertyName);
    }

    function set(userValue) {
      ow.setPropertyValue(propertyName, userValue);
    }

    Object.defineProperty(this.observableKeys, propertyName, {enumerable:isEnum,
      configurable:true, get:get, set:set});
  }

  ObservingWrapper.prototype.getPropertyValue=function(propertyName){
    var ow=this;
    return typeof this.sourceObject[propertyName]!=='function'
      ? this.sourceObject[propertyName]
      : function(){var len,ok,res,changes;

          len=ow.sourceObject.length,
          res=ow.sourceObject[propertyName].apply(ow.sourceObject,arguments);

          if(len&&len!==ow.sourceObject.length)
            ow.undefineObservableProperties(),
            ow.defineObservableProperties();

          ok=ow.observableKeys,changes=[{name:propertyName,object:ok,type:'call'
            ,arguments:arguments,result:res}];

          if(propertyName==='push')
            changes=[{object:ok,type:'splice',index:ow.sourceObject.length-1,
              removed:[],addedCount:1}];

          else if(propertyName==='splice')
            changes=[{object:ok,type:'splice',index:arguments[0],removed:res,
              addedCount:cropArgs(arguments,2).length}];

          ow.notifyObservers(changes);

          return res;
        };
  }

  ObservingWrapper.prototype.notifyObservers=function(changes){
    var specificHandlers,i,n;

    if(specificHandlers=this.specificHandlers[changes[0].name])
      for(i=0,n=specificHandlers.length;i<n;i++)
        specificHandlers[i].call(this.observableKeys,changes);

    for(i=0,n=this.changeHandlers.length;i<n;i++)
      this.changeHandlers[i].call(this.observableKeys,changes);
  }

  ObservingWrapper.prototype.removeChangeHandler = function() {
    var rmInd,key,userPropertyName,userChangeHandler;

    if(['string','number'].indexOf(typeof arguments[0])>-1 && typeof arguments
      [1]==='function')
    {
      userPropertyName=arguments[0];
      userChangeHandler=arguments[1];
    }
    else
      userChangeHandler=arguments[0];

    if(userPropertyName!==undefined){
      this.specificHandlers[userPropertyName]&&(rmInd=this.specificHandlers[
        userPropertyName].indexOf(userChangeHandler))>-1&&this.specificHandlers[
        userPropertyName].splice(rmInd,1);
    }
    else{
      (rmInd=this.changeHandlers.indexOf(userChangeHandler))>-1&&this.
        changeHandlers.splice(rmInd,1);

      for(key in this.specificHandlers)
        (rmInd=this.specificHandlers[key].indexOf(userChangeHandler))>-1&&this.
          specificHandlers[key].splice(rmInd,1);
    }
  }

  ObservingWrapper.prototype.setPropertyValue=function(propertyName,
    propertyValue){var oldValue;

    if(this.sourceObject[propertyName]!==propertyValue){
      oldValue=this.sourceObject[propertyName];
      this.sourceObject[propertyName]=propertyValue;
      this.notifyObservers([{name:propertyName,object:this.sourceObject,type:
        'update',oldValue:oldValue}]);
    }
  }

  ObservingWrapper.prototype.undefineObservableProperties = function() {
    for(var propertyNames=getDeepPropertyNames(this.observableKeys),i=0,n=
      propertyNames.length; i<n; i++)
      delete this.observableKeys[i];
  }

  // bindbind
  function c(){console.log.apply(console,arguments)}

  function bindElementPaths2ArraySplice(anchorElements,bindingPaths,userModelPath)
  {
    var a,ow;

    a=userModelPath.slice(0,1);
    ow=(byPath(viewModel,a)).__observingWrapper;

    if(ow===undefined){
      ow=new ObservingWrapper(byPath(viewModel,a));
      byPath(viewModel,a,ow.observableKeys);
    }

    ow.addChangeHandler(function(changes){
      for(var m=0;m<changes.length;m++)
        if(changes[m].type==='splice'){
          if(changes[m].addedCount)
            for(var k=0;k<changes[m].addedCount;k++){
              var q=changes[m].index+k-1;
              var f=anchorElements[q].cloneNode(true);
              anchorElements[q].parentNode.insertBefore(f,anchorElements[q].
                nextSibling);
              anchorElements.splice(changes[m].index+k,1,f);

              var j=q+1;
              var modelPath=userModelPath.slice();
              modelPath.splice(1,0,j);
              bindElementPaths2ModelPath(anchorElements[j],bindingPaths,modelPath);
            }
        }
    });
  }

  function bindModelProperty2Element(modelPath,element,valuePath)
  {
    c('bindModelPropertyToElement',{modelPath:modelPath,element:element,valuePath:valuePath})
    var a,b,ow;

    a=modelPath.slice(0,-1);
    b=modelPath.slice(-1)[0];

    ow=(byPath(viewModel,a)).__observingWrapper;

    if(ow===undefined){
      ow=new ObservingWrapper(byPath(viewModel,a));
      byPath(viewModel,a,ow.observableKeys);
    }

    if(valuePath[valuePath.length-1]==='nodeValue'&&!byPath(element,valuePath
      .concat().splice(0,2)))
        element.appendChild(document.createTextNode(''));

    ow.addChangeHandler(b,function(changes){
      for(var m=0;m<changes.length;m++)
        byPath(element,valuePath,changes[m].object[changes[m].name]);
    });
  }

  function bindElementPaths2ModelPath(anchorElement,bindingPaths,modelPath)
  {
    c('bindElementPaths2ModelPath',{anchorElement:anchorElement,bindingPaths:bindingPaths,modelPath:modelPath});

    for(var k=bindingPaths.length;k--;)
      bindModelProperty2Element(modelPath,anchorElement,bindingPaths[k]);
  }

  function byPath(obj,path,value)
  {
    var a,b;
    // c('byPath',{obj:obj,path:path,value:value})

    if(path.length===0)
      return obj;

    a=path.length-1;
    for(b=0;b<a;b++)
      obj=obj[path[b]];

    if(value!==undefined){
      if(path.args===undefined)
        obj[path[a]]=value;
      else{
        if(path.args.ind!==undefined)
          path.args.splice(path.args.ind,1,value);
        obj[path[a]].apply(obj,path.args);
      }
    }

    return obj[path[a]];
  }

  function findBindingPaths(node,placeholder,nodePaths,pathPrefix)
  {
    var a,b,possiblePaths,path,k;

    nodePaths=nodePaths||[];
    pathPrefix=pathPrefix||[];

    [['nodeValue'],['value']].forEach(function(path){
      var value=byPath(node,path);

      if(typeof value==='string'&&(placeholder?value.indexOf(placeholder)>-1:
        true))
          nodePaths.push(pathPrefix.concat(path));

      else if(value===null&&!placeholder)
        nodePaths.push(pathPrefix.concat(['childNodes',0,'nodeValue']));
    });

    if(placeholder){
      if(node.style)
        for(k in node.style)
          if((node.style.getPropertyValue(k)||'').indexOf(placeholder)>-1){
            path=pathPrefix.concat(['style','setProperty']);
            path.args=[k,undefined];
            path.args.ind=1;
            nodePaths.push(path);
          }

      if(node.classList&&placeholder.indexOf(' ')===-1&&node.classList.contains(
        placeholder))
      {
        path=pathPrefix.concat(['classList','remove']);
        path.args=[placeholder];
        nodePaths.push(path);

        path=pathPrefix.concat(['classList','add']);
        path.args=[undefined];
        path.args.ind=0;
        nodePaths.push(path);
      }

      if(node.attributes)
        for(k=node.attributes.length;k--;)
          if(['style','class'].indexOf(node.attributes[k].nodeName)===-1)
            if(node.attributes[k].nodeValue.indexOf(placeholder)>-1){
              path=pathPrefix.concat(['attributes',k,'nodeValue']);
              nodePaths.push(path);
            }
    }

    if((a=node.childNodes.length)&&placeholder)
      while(a--)
        findBindingPaths(node.childNodes[a],placeholder,nodePaths,pathPrefix.
          concat(['childNodes',a]));

    return nodePaths;
  }

  function mergeBindingData(destData,srcData)
  {
    var a,modelPathIn;

    modelPathIn=false;
    for(a=0;a<destData.length;a++)
      modelPathIn=destData[a].modelPath.reduce(function(r,m,i){
        return srcData.modelPath[i]===m&&r},true)||modelPathIn;

    if(!modelPathIn)
      destData.push({modelPath:srcData.modelPath,bindingPaths:srcData.bindingPaths});
  }

  function mergeItemsIntoBindable(bindable,items)
  {
    var a,b;
// c('^^',items)
    for(a=0;a<items.length;a++){
      for(b=0;b<bindable.length;b++){
        if(bindable[b].modelProperty===items[a].modelPath[0]){
          if(bindable[b].anchorElements.indexOf(items[a].anchorElement)===-1){
            if(bindable[b].anchorElements[0].parentNode===items[a].anchorElement
              .parentNode)
            {
              bindable[b].anchorElements.push(items[a].anchorElement);
              items[a]=undefined;
              break;
            }
          }
          else{
            mergeBindingData(bindable[b].bindingData,items[a])
            items[a]=undefined;
            break;
          }
        }
      }
// c('%%',items[a])
      if(items[a])
        bindable.push({anchorElements:[items[a].anchorElement],bindingData:
          [{modelPath:items[a].modelPath,bindingPaths:items[a].bindingPaths}],
          modelProperty:items[a].modelPath[0]});
    }
  }

  function collectBindableElements()
  {
    var a,b,d,e,f,g,h;

    a=document.body.getElementsByTagName('*'),f=[];

    for(b=0;b<a.length;b++){
      e=[];

      for(d=0;d<a[b].attributes.length;d++)
        if(a[b].attributes[d].name.indexOf('bb-')===0){
          g=a[b].attributes[d].name.substring(3).split(':').splice(0,2);

          e.push({anchorElement:a[b],modelPath:g,bindingPaths:
            findBindingPaths(a[b],a[b].attributes[d].value)});
        }

      if(e.length)
        mergeItemsIntoBindable(f,e);
    }

    return f;
  }

  function __collectBindableElements()
  {
    var a,b,c,d,e,f,g,h;

    a=[],g=[],b=document.body.getElementsByTagName('*');

    for(c=b.length;c--;)
      for(d=b[c].attributes.length;d--;)
        if(b[c].attributes[d].name.indexOf('bb-')===0){
          f=b[c].attributes[d].name.substring(3).split(':');

          if(-1===(e=g.indexOf(f[0])))
            g.push(f[0]),
            e=a.push({modelPath:f,bindingData:[]})-1;

          for(h=a[e].bindingData.length;h--;)
            if(a[e].bindingData[h].anchorElements[0].parentNode===b[c].parentNode)
              break;

          if(h>-1)
            a[e].bindingData[h].anchorElements.unshift(b[c]);

          else
            a[e].bindingData.push({anchorElements:[b[c]],bindingPaths:
              findBindingPaths(b[c],b[c].attributes[d].value)});
        }

    return a;
  }

  function bind()
  {
    for(var l=0;l<bindableElements.length;l++){
      var anchorElements=bindableElements[l].anchorElements;
      var u=ObservingWrapper.getSourceObject(viewModel[bindableElements[l].modelProperty]);
      var w=(u&&Array.isArray(u)&&u.length)||0;

      for(var o=bindableElements[l].bindingData.length;o--;){
        var userModelPath=bindableElements[l].bindingData[o].modelPath;
        var bindingPaths=bindableElements[l].bindingData[o].bindingPaths;

        if(w>1)
          for(var q=0;q<w-1;q++){
            if(anchorElements[q+1]!==undefined)
              continue;

            var f=anchorElements[q].cloneNode(true);
            anchorElements[q].parentNode.insertBefore(f,anchorElements[q].
              nextSibling);
            anchorElements.push(f);
          }

        if(Array.isArray(ObservingWrapper.getSourceObject(viewModel[
          userModelPath[0]])))
        {
          bindElementPaths2ArraySplice(anchorElements,bindingPaths,userModelPath);

          for(var j=viewModel[userModelPath[0]].length;j--;){
            var modelPath=userModelPath.slice();
            modelPath.splice(1,0,j);
            bindElementPaths2ModelPath(anchorElements[j],bindingPaths,modelPath);
          }
        }
        else
          bindElementPaths2ModelPath(anchorElements[0],bindingPaths,userModelPath);
      }
    }
  }

  function afterDOMContentLoaded()
  {
    bindableElements=collectBindableElements();
    c('bindableElements',bindableElements);

    if(viewModel)
      bind();
  }

  function bindbind(userViewModel)
  {
    viewModel=(new ObservingWrapper(userViewModel)).observableKeys;

    if(['interactive','complete'].indexOf(document.readyState)>-1)
      bind();

    return viewModel;
  }

  if(['interactive','complete'].indexOf(document.readyState)>-1)
    afterDOMContentLoaded();
  else
    document.addEventListener("DOMContentLoaded",afterDOMContentLoaded,false);

  if(window.define===undefined)
    window.bindbind=bindbind;
  else
    define(function(){return bindbind});

}(window)
<|endoftext|>


<commit_before>var Package = require('pomelo-protocol');

module.exports.handle = function(socket, reason) {
  if(reason === 'kick') {
    socket.sendRaw(Package.encode(Package.TYPE_KICK));
  }
};<commit_msg>fix kick player bug<commit_after>var Package = require('pomelo-protocol').Package;

module.exports.handle = function(socket, reason) {
  if(reason === 'kick') {
    socket.sendRaw(Package.encode(Package.TYPE_KICK));
  }
};<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router(); // eslint-disable-line new-cap
const UserModel = require('../models/user');
const jwt = require('jsonwebtoken');

router.post('/authenticate', (req, res) => {
  UserModel.findOne({ username: req.body.username }, (err, user) => {
    if (err) {
      throw err;
    }

    if (!user) {
      res.json({
        status: 'fail',
        meta: {
          message: 'Authentication not possible - username not found',
          validation: {
            username: 'That username could not be found',
          },
        },
        data: null,
      });
    } else {
      const payload = {
        id: user.id,
        username: user.username,
        name: user.name.full,
        role: user.role,
      };

      const token = jwt.sign(payload, process.env.JWT_SECRET, {
        expiresIn: req.body.remember ? '14 days' : '1 day',
      });

      res.json({
        status: 'success',
        meta: null,
        data: null,
        token,
      });
    }
  });
});

module.exports = router;
<commit_msg>authenticate: using config file for jwt secret<commit_after>const express = require('express');
const router = express.Router(); // eslint-disable-line new-cap
const UserModel = require('../models/user');
const jwt = require('jsonwebtoken');
const config = require('../app/config');

// Authenticate a user
router.post('/authenticate', (req, res) => {
  UserModel.findOne({ username: req.body.username }, (err, user) => {
    if (err) {
      throw err;
    }

    if (!user) {
      res.json({
        status: 'fail',
        meta: {
          message: 'Authentication not possible - username not found',
          validation: {
            username: 'That username could not be found',
          },
        },
        data: null,
      });
    } else {
      const payload = {
        id: user.id,
        username: user.username,
        name: user.name.full,
        role: user.role,
      };

      const token = jwt.sign(payload, config.jwt.secret, {
        expiresIn: req.body.remember ? '14 days' : '1 day',
      });

      res.json({
        status: 'success',
        meta: null,
        data: null,
        token,
      });
    }
  });
});

module.exports = router;
<|endoftext|>


<commit_before>function drawYear(canvas, year, conception, birth, today) {
    var ctx = canvas.getContext('2d');
    var size = 6, header = size * 3, pad = 2;
    canvas.width = 31 * size;
    canvas.height = 12 * size + header + pad;
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = 'white';
    ctx.font = header + 'px "Lucida Console", Monaco, monospace';
    ctx.textBaseline = 'top';
    ctx.fillText(year, 0, 0);

    function inWomb(date) {
        return date.getTime() >= conception.getTime() &&
            date.getTime() < birth.getTime();
    }

    function isAlive(date) {
        return date.getTime() >= birth.getTime() &&
            date.getTime() <= today.getTime();
    }

    for (var month = 0; month < 12; month++) {
        for (var day = 1, date = new Date(year, month, day);
             date.getMonth() === month;
             date = new Date(year, month, ++day)) {
            var x = (day - 1) * size;
            var y = month * size + header + pad;
            if (isAlive(date)) {
                ctx.fillRect(x, y, size / 2, size / 2);
            } else if (inWomb(date)) {
                for (var i = 0; i < size / 2; i++) {
                    ctx.fillRect(x + i, y + i, 1, 1);
                }
            } else {
                ctx.fillRect(x, y, 1, 1);
            }
        }
    }
}

function draw(birth) {
    /* Compute important dates: conception, birth, today. */
    var gestation = 276.5 * 24 * 60 * 60 * 1000;
    var conception = new Date(birth.getTime() - gestation);
    var today = new Date();

    /* Compute start and end years. */
    var first = Math.floor(conception.getFullYear() / 5) * 5 - 5;
    var last = Math.ceil((today.getFullYear() + 1) / 5) * 5 + 4;

    /* Compute age and display it. */
    var age = today.getFullYear() - birth.getFullYear() - 1;
    if (today.getMonth() > birth.getMonth() ||
        (today.getMonth() === birth.getMonth() &&
         today.getDate() >= birth.getDate())) {
        age++;
    }
    $('#age').text('Number of Days Living at Age ' + age);

    /* Insert a canvas for each year. */
    var life = $('#life').empty();
    for (var year = first; year <= last; year++) {
        var canvas = $('<canvas/>');
        life.append(canvas);
        drawYear(canvas[0], year, conception, birth, today);
    }
}

$(document).ready(function() {
    var birth = location.search.match(/\?(\d+)-(\d+)-(\d+)/);
    if (birth === null) {
        var $year = $('form .year');
        for (var year = 1900; year <= new Date().getFullYear(); year++) {
            var $option = $('<option>' + year + '</option>', {value: year});
            $year.append($option);
        }
        $year.val(1985);
        var $month = $('form .month');
        for (var month = 1; month <= 12; month++) {
            $option = $('<option>' + month + '</option>', {value: month});
            $month.append($option);
        }
        var $day = $('form .day');
        for (var day = 1; day <= 31; day++) {
            $option = $('<option>' + day + '</option>', {value: day});
            $day.append($option);
        }
        $('form').submit(function() {
            var year = $('form .year').val();
            var month = $('form .month').val();
            var day = $('form .day').val();
            window.location = '/?' + year + '-' + month + '-' + day;
            return false;
        });
    } else {
        $('form').remove();
        draw(new Date(birth[1], birth[2] - 1, birth[3]));
    }
});
<commit_msg>Oops, not the root.<commit_after>function drawYear(canvas, year, conception, birth, today) {
    var ctx = canvas.getContext('2d');
    var size = 6, header = size * 3, pad = 2;
    canvas.width = 31 * size;
    canvas.height = 12 * size + header + pad;
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = 'white';
    ctx.font = header + 'px "Lucida Console", Monaco, monospace';
    ctx.textBaseline = 'top';
    ctx.fillText(year, 0, 0);

    function inWomb(date) {
        return date.getTime() >= conception.getTime() &&
            date.getTime() < birth.getTime();
    }

    function isAlive(date) {
        return date.getTime() >= birth.getTime() &&
            date.getTime() <= today.getTime();
    }

    for (var month = 0; month < 12; month++) {
        for (var day = 1, date = new Date(year, month, day);
             date.getMonth() === month;
             date = new Date(year, month, ++day)) {
            var x = (day - 1) * size;
            var y = month * size + header + pad;
            if (isAlive(date)) {
                ctx.fillRect(x, y, size / 2, size / 2);
            } else if (inWomb(date)) {
                for (var i = 0; i < size / 2; i++) {
                    ctx.fillRect(x + i, y + i, 1, 1);
                }
            } else {
                ctx.fillRect(x, y, 1, 1);
            }
        }
    }
}

function draw(birth) {
    /* Compute important dates: conception, birth, today. */
    var gestation = 276.5 * 24 * 60 * 60 * 1000;
    var conception = new Date(birth.getTime() - gestation);
    var today = new Date();

    /* Compute start and end years. */
    var first = Math.floor(conception.getFullYear() / 5) * 5 - 5;
    var last = Math.ceil((today.getFullYear() + 1) / 5) * 5 + 4;

    /* Compute age and display it. */
    var age = today.getFullYear() - birth.getFullYear() - 1;
    if (today.getMonth() > birth.getMonth() ||
        (today.getMonth() === birth.getMonth() &&
         today.getDate() >= birth.getDate())) {
        age++;
    }
    $('#age').text('Number of Days Living at Age ' + age);

    /* Insert a canvas for each year. */
    var life = $('#life').empty();
    for (var year = first; year <= last; year++) {
        var canvas = $('<canvas/>');
        life.append(canvas);
        drawYear(canvas[0], year, conception, birth, today);
    }
}

$(document).ready(function() {
    var birth = location.search.match(/\?(\d+)-(\d+)-(\d+)/);
    if (birth === null) {
        var $year = $('form .year');
        for (var year = 1900; year <= new Date().getFullYear(); year++) {
            var $option = $('<option>' + year + '</option>', {value: year});
            $year.append($option);
        }
        $year.val(1985);
        var $month = $('form .month');
        for (var month = 1; month <= 12; month++) {
            $option = $('<option>' + month + '</option>', {value: month});
            $month.append($option);
        }
        var $day = $('form .day');
        for (var day = 1; day <= 31; day++) {
            $option = $('<option>' + day + '</option>', {value: day});
            $day.append($option);
        }
        $('form').submit(function() {
            var year = $('form .year').val();
            var month = $('form .month').val();
            var day = $('form .day').val();
            window.location = '?' + year + '-' + month + '-' + day;
            return false;
        });
    } else {
        $('form').remove();
        draw(new Date(birth[1], birth[2] - 1, birth[3]));
    }
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var Promise = require('bluebird');
var Client = require('bitfinex');
var util = require('util');

module.exports = function(conf, trader){
    _.extend(this, conf);
    var self = this;

    var initDeferred = Promise.defer();
    this.initialized = initDeferred.promise;

    this.client = new Client(this.key, this.secret);
    ['orderbook'/*, 'wallet_balances'*/].forEach(function(command){
        self.client[command] = Promise.promisify(self.client[command]);
    })
    this.spreadAdapter = function(indata){
        var outdata = {
            exchange : 'bitfinex',
            bids : [],
            asks : []
        };

        var bids = indata.bids;
        var asks  = indata.asks;

        for (var i = 0; i < 5; i++) {
            outdata.bids.push([bids[i].price, bids[i].amount]);
            outdata.asks.push([asks[i].price, asks[i].amount]);
        };
        return outdata;
    };

    this.getSpread = function(currency){ // only USD ATM.
        return self.client.orderbook('btcusd').then(function(response){
            var data = self.spreadAdapter(response);
            _.extend(data, {exchange: 'bitfinex', currency: currency});
            trader.emit('spread_data', data);
            return data;
        });
    }

    this.getBalance = function(){

        // keeping this function intact in case I forget how deferreds work ;) / SK. 21 mars
        var deferred = Promise.defer();

        self.client.wallet_balances(function(error, data) {
            if(error) {
                console.error(error);
                return deferred.reject(error);
            }

            self.balance = {
                'USD' : parseFloat(_.find(data, {type: 'exchange', currency :'usd'}).available),
                'BTC' : parseFloat(_.find(data, {type: 'exchange', currency :'btc'}).available)
            };
            console.log('bitfinex.balance: ', self.balance);
            if(_.isNaN(self.balance.USD) || _.isNaN(self.balance.BTC)){
                deferred.reject('Bitfinex balance isNaN');
            }
            deferred.resolve(self.balance);
        });

        return deferred.promise;
    }

    this.getBalance().then(function(){
        initDeferred.resolve();
    });

}
<commit_msg>add bitfinex trading also!<commit_after>var _ = require('lodash');
var Promise = require('bluebird');
var Client = require('bitfinex');
var util = require('util');

module.exports = function(conf, trader){
    _.extend(this, conf);
    var self = this;

    var initDeferred = Promise.defer();
    this.initialized = initDeferred.promise;

    this.client = new Client(this.key, this.secret);
    ['orderbook', 'new_order', 'order_status' /*, 'wallet_balances'*/].forEach(function(command){
        self.client[command] = Promise.promisify(self.client[command]);
    })
    this.spreadAdapter = function(indata){
        var outdata = {
            exchange : 'bitfinex',
            bids : [],
            asks : []
        };

        var bids = indata.bids;
        var asks  = indata.asks;

        for (var i = 0; i < 5; i++) {
            outdata.bids.push([bids[i].price, bids[i].amount]);
            outdata.asks.push([asks[i].price, asks[i].amount]);
        };
        return outdata;
    };

    this.getSpread = function(currency){ // only USD ATM.
        return self.client.orderbook('btcusd').then(function(response){
            var data = self.spreadAdapter(response);
            _.extend(data, {exchange: 'bitfinex', currency: currency});
            trader.emit('spread_data', data);
            return data;
        });
    }

    this.getBalance = function(){

        // keeping this function intact in case I forget how deferreds work ;) / SK. 21 mars
        var deferred = Promise.defer();

        self.client.wallet_balances(function(error, data) {
            if(error) {
                console.error(error);
                return deferred.reject(error);
            }

            self.balance = {
                'USD' : parseFloat(_.find(data, {type: 'exchange', currency :'usd'}).available),
                'BTC' : parseFloat(_.find(data, {type: 'exchange', currency :'btc'}).available)
            };
            console.log('bitfinex.balance: ', self.balance);
            if(_.isNaN(self.balance.USD) || _.isNaN(self.balance.BTC)){
                deferred.reject('Bitfinex balance isNaN');
            }
            deferred.resolve(self.balance);
        });

        return deferred.promise;
    }
    this.tradeCommand = function(options){
        console.log('executing bitfinex trade: ', options);

        return this.client.new_order('btcusd', options.volume, options.price, 'all', options.buySell.toLowerCase(), 'limit').then(function(response){
            console.log('add order sent: ', response);
            return response;
        });
    }
    this.trade = function(options){
        var tradeResolver = Promise.defer();

        var neededOptions = ['currency', 'buySell', 'price', 'volume'];
        for (var i = neededOptions.length - 1; i >= 0; i--) {
            if(!_.has(options, neededOptions[i])){
                return tradeResolver.throw('Input data error').promise;
            }
        };

        this.tradeCommand(options).then(function(response){
            var id = response.order_id;
            var i = 0;

            console.log('bitfinex order id: ', id);

            function tradeChecker(response){
                if(tradeResolver.promise.isResolved()){ return ; } // quit the loop

                if(response.remaining_amount == 0){
                    console.log('order is completed!');
                    tradeResolver.resolve(response);
                    return true;
                } else if (response.is_cancelled){
                    console.log('order is cancelled!');
                    tradeResolver.reject(response);
                    return false;
                } else if(response.is_live){
                    console.log('order ', id, 'is still running, iteration', i++);
                    Promise.delay(1000).then(function(){
                        return self.client.order_status(id); // here is where the request happens
                    }).then(tradeChecker); // keep looping this baby
                } else {
                    throw new Error('Unclear bitfinex trade situation: ', response);
                }
            }
            tradeChecker(response); // verify original response
        });

        return tradeResolver.promise;
    };

    this.getBalance().then(function(){
        initDeferred.resolve();
    });

}
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var url = document.URL;
  var connectionType = util.getConnectionType();
  var score = 100;
  var message = '';

  if (url.indexOf('https://') > -1 && connectionType.indexOf('h2') === -1) {
    score = 0;
    message =
      'The page is using HTTPS but not HTTP/2. Change to HTTP/2 to follow new best practice and make the site faster.';
  }

  return {
    id: 'httpsH2',
    title: 'Serve your content using HTTP/2',
    description:
      'Using HTTP/2 together with HTTPS is the new best practice. If you use HTTPS (you should), you should also use HTTP/2.',
    advice: message,
    score: score,
    weight: 2,
    offending: [],
    tags: ['bestpractice']
  };
})();
<commit_msg>Tuned the message, HTTP2 is not always faster. It may be faster #269 (#319)<commit_after>(function() {
  'use strict';

  var url = document.URL;
  var connectionType = util.getConnectionType();
  var score = 100;
  var message = '';

  if (url.indexOf('https://') > -1 && connectionType.indexOf('h2') === -1) {
    score = 0;
    message =
      'The page is using HTTPS but not HTTP/2. Change to HTTP/2 to follow new best practice with compressed headers and maybe make the site faster.';
  }

  return {
    id: 'httpsH2',
    title: 'Serve your content using HTTP/2',
    description:
      'Using HTTP/2 together with HTTPS is the new best practice. If you use HTTPS (you should), you should also use HTTP/2 since you will then get compressed headers. However it may not be faster for all users.',
    advice: message,
    score: score,
    weight: 2,
    offending: [],
    tags: ['bestpractice']
  };
})();
<|endoftext|>


<commit_before>window.onclose = function () {

	if (window.ws) {

		window.ws.close();

	}

}

setTimeout(function () {

	window.sockets = {
		raw: new WebSocket('ws://localhost:4000/raw'),
		rendered: new WebSocket('ws://localhost:4000/rendered')
	};

	window.editor = document.getElementById('editor');

	window.spaces = 0;

	window.schedules = [];

	window.schedulesInterval = null;

	/**
	 *
	 */
	window.sockets.raw.onmessage = function (event) {

		window.editor.value = event.data;

		// Should I remove this listener?

	}

	/**
	 *
	 */
	window.sockets.rendered.onmessage = function (event) {

		var data = JSON.parse(event.data);

		document.getElementById('rendered').innerHTML = data.html;

		document.querySelectorAll('pre code').forEach(function (block) {

			hljs.highlightBlock(block)

		});

		/*document.querySelectorAll('div.tag-title').forEach(function (element) {

			element.onclick = function (event) {

				var content = document.getElementById(event.target.id.replace('-toggler', '-content'));

				console.log(content);

				if ((content.style.display === 'block') || (content.style.display === '')) {

					content.style.display = 'none';

				} else  {

					content.style.display = 'block';

				}

			};

		});*/

		// Schedules

		//clearInterval(window.schedulesInterval);

		/*data.schedules.forEach(function (newSchedule) {

			if (window.schedules.length === 0) {

				window.schedules.push(newSchedule);

			} else {

				window.schedules.forEach(function (oldSchedule) {

					if (oldSchedule.id !== newSchedule.id) {

						window.schedules.push(newSchedule);

					}

				});

			}

		});*/

		//window.schedulesInterval = setInterval(window.schedulesHandler, 1000);

	};

	/**
	 *
	 */
	window.editor.onkeydown = function (event) {

		var key = event.which;

		if (event.keyCode === 9) {

			event.preventDefault();

			var start = this.selectionStart;

			var end = this.selectionEnd;

			var target = event.target;

			var value = target.value;

			target.value = value.substring(0, start) + '\t' + value.substring(end);

			this.selectionStart = this.selectionEnd = start + 1;

		} else if ((key === 83) && (event.ctrlKey === true)) {

			event.preventDefault();

			window.sockets.raw.send(window.editor.value);

		} else if ((key === 13) || (key === 10)) {

			window.sockets.raw.send(window.editor.value);

			window.spaces = 0;

		} else if (key === 32) {

			window.spaces += 1;

			if (window.spaces === 3) {

				window.sockets.raw.send(window.editor.value);

				window.spaces = 0;

			}

		}

	};

	/**
	 *
	 */
	window.schedulesHandler = function () {

		var now = new Date().getTime();

		window.schedules.forEach(function (item, index, source) {

			var timestamp = new Date(item.iso).getTime();

			// if past, delete

			if (timestamp === now) {

				console.log('AGORA', item);

			} else if (!item.alert) {

				console.log(item);

				source[index].alert = true;

			}

		});

		console.log(window.schedules);

	};

	/**
	 *
	 */
	//window.schedulesInterval = setInterval(window.schedulesHandler, 1000);

}, 2000);<commit_msg>Handling websockets onclose<commit_after>window.onclose = function () {

	if (window.sockets.raw) {

		window.sockets.raw.close();

	}

	if (window.sockets.rendered) {

		window.sockets.rendered.close();

	}

}

setTimeout(function () {

	window.sockets = {
		raw: new WebSocket('ws://localhost:4000/raw'),
		rendered: new WebSocket('ws://localhost:4000/rendered')
	};

	window.editor = document.getElementById('editor');

	window.spaces = 0;

	window.schedules = [];

	window.schedulesInterval = null;

	/**
	 *
	 */
	window.sockets.raw.onmessage = function (event) {

		window.editor.value = event.data;

		// Should I remove this listener?

	}

	/**
	 *
	 */
	window.sockets.rendered.onmessage = function (event) {

		var data = JSON.parse(event.data);

		document.getElementById('rendered').innerHTML = data.html;

		document.querySelectorAll('pre code').forEach(function (block) {

			hljs.highlightBlock(block)

		});

		/*document.querySelectorAll('div.tag-title').forEach(function (element) {

			element.onclick = function (event) {

				var content = document.getElementById(event.target.id.replace('-toggler', '-content'));

				console.log(content);

				if ((content.style.display === 'block') || (content.style.display === '')) {

					content.style.display = 'none';

				} else  {

					content.style.display = 'block';

				}

			};

		});*/

		// Schedules

		//clearInterval(window.schedulesInterval);

		/*data.schedules.forEach(function (newSchedule) {

			if (window.schedules.length === 0) {

				window.schedules.push(newSchedule);

			} else {

				window.schedules.forEach(function (oldSchedule) {

					if (oldSchedule.id !== newSchedule.id) {

						window.schedules.push(newSchedule);

					}

				});

			}

		});*/

		//window.schedulesInterval = setInterval(window.schedulesHandler, 1000);

	};

	/**
	 *
	 */
	window.editor.onkeydown = function (event) {

		var key = event.which;

		if (event.keyCode === 9) {

			event.preventDefault();

			var start = this.selectionStart;

			var end = this.selectionEnd;

			var target = event.target;

			var value = target.value;

			target.value = value.substring(0, start) + '\t' + value.substring(end);

			this.selectionStart = this.selectionEnd = start + 1;

		} else if ((key === 83) && (event.ctrlKey === true)) {

			event.preventDefault();

			window.sockets.raw.send(window.editor.value);

		} else if ((key === 13) || (key === 10)) {

			window.sockets.raw.send(window.editor.value);

			window.spaces = 0;

		} else if (key === 32) {

			window.spaces += 1;

			if (window.spaces === 3) {

				window.sockets.raw.send(window.editor.value);

				window.spaces = 0;

			}

		}

	};

	/**
	 *
	 */
	window.schedulesHandler = function () {

		var now = new Date().getTime();

		window.schedules.forEach(function (item, index, source) {

			var timestamp = new Date(item.iso).getTime();

			// if past, delete

			if (timestamp === now) {

				console.log('AGORA', item);

			} else if (!item.alert) {

				console.log(item);

				source[index].alert = true;

			}

		});

		console.log(window.schedules);

	};

	/**
	 *
	 */
	//window.schedulesInterval = setInterval(window.schedulesHandler, 1000);

}, 2000);<|endoftext|>