<commit_before>/* Yahoo plugin
 */

App.plugin('yahoo', (function() {

    var parseName = function(name) {
        name = name.trim();

        var first_name = '';
        var last_name = '';

        var firstSpace = name.indexOf(' ');

        if(firstSpace === -1) {
            firstSpace = name.length;
        }

        first_name = name.substring(0, firstSpace);
        last_name = name.substring(firstSpace + 1, name.length);

        return {
            first_name: first_name,
            last_name: last_name
        }
    };

    // get all required data from the dom
    var getData = function(params, callback) {

        var vars = {
            from: [],
            to: [],
            cc: [],
            bcc: [],
            subject: ''
        };

        var $composeContainer = $(params.element).parents('.thread-item').first();
        var $emailContainer = $composeContainer.prev('.thread-item');

        // get your name from the top-right profile
        var fromName = $('#yucs-profile b').first().text();
        var fromEmail = $('#yucs-profile-panel b + b').text();

        // get your own name from the top right
        var from = {
            name: fromName,
            first_name: '',
            last_name: '',
            email: fromEmail + '@yahoo.com'
        };

        var parsedName = parseName(fromName);

        from.first_name = parsedName.first_name;
        from.last_name = parsedName.last_name;

        vars.from.push(from);

        $composeContainer.find('#to li').each(function() {
            var $li = $(this);
            var liText = $li.text().trim();

            // TODO check if the liText is the name or the email

            if(liText) {
                var parsedLiName = parseName(liText);

                vars.to.push({
                    name: liText,
                    first_name: parsedLiName.first_name,
                    last_name: parsedLiName.last_name,
                    email: ''
                });
            }
        });

        if(callback) {
            callback(null, vars);
        }

    };

    var setTitle = function(params, callback) {

        var response = {};

        var $subjectField = $('#subject-field');
        $subjectField.val(params.subject);

        if(callback) {
            callback(null, response);
        }

    };

    var init = function(params, callback) {

        var yahooUrl = '.mail.yahoo.com/';

        var activateExtension = false;

        // trigger the extension based on url
        if(window.location.href.indexOf(yahooUrl) !== -1) {
            activateExtension = true;
        }

        // return true as response if plugin should be activated
        if(callback) {
            // first param is the error
            // second is the response
            callback(null, activateExtension);
        }

    };

    return {
        init: init,
        getData: getData,
        setTitle: setTitle
    }

})());
<commit_msg>Fixed Yahoo compose area selector<commit_after>/* Yahoo plugin
 */

App.plugin('yahoo', (function() {

    var parseName = function(name) {
        name = name.trim();

        var first_name = '';
        var last_name = '';

        var firstSpace = name.indexOf(' ');

        if(firstSpace === -1) {
            firstSpace = name.length;
        }

        first_name = name.substring(0, firstSpace);
        last_name = name.substring(firstSpace + 1, name.length);

        return {
            first_name: first_name,
            last_name: last_name
        }
    };

    // get all required data from the dom
    var getData = function(params, callback) {

        var vars = {
            from: [],
            to: [],
            cc: [],
            bcc: [],
            subject: ''
        };

        var $composeContainer = $(params.element).parents('.compose').first();
        var $emailContainer = $composeContainer.prev('.thread-item');

        // get your name from the top-right profile
        var fromName = $('#yucs-profile b').first().text();
        var fromEmail = $('#yucs-profile-panel b + b').text();

        // get your own name from the top right
        var from = {
            name: fromName,
            first_name: '',
            last_name: '',
            email: fromEmail + '@yahoo.com'
        };

        var parsedName = parseName(fromName);

        from.first_name = parsedName.first_name;
        from.last_name = parsedName.last_name;

        vars.from.push(from);

        $composeContainer.find('#to li').each(function() {
            var $li = $(this);
            var liText = $li.text().trim();

            // TODO check if the liText is the name or the email

            if(liText) {
                var parsedLiName = parseName(liText);

                vars.to.push({
                    name: liText,
                    first_name: parsedLiName.first_name,
                    last_name: parsedLiName.last_name,
                    email: ''
                });
            }
        });

        if(callback) {
            callback(null, vars);
        }

    };

    var setTitle = function(params, callback) {

        var response = {};

        var $subjectField = $('#subject-field');
        $subjectField.val(params.subject);

        if(callback) {
            callback(null, response);
        }

    };

    var init = function(params, callback) {

        var yahooUrl = '.mail.yahoo.com/';

        var activateExtension = false;

        // trigger the extension based on url
        if(window.location.href.indexOf(yahooUrl) !== -1) {
            activateExtension = true;
        }

        // return true as response if plugin should be activated
        if(callback) {
            // first param is the error
            // second is the response
            callback(null, activateExtension);
        }

    };

    return {
        init: init,
        getData: getData,
        setTitle: setTitle
    }

})());
<|endoftext|>


<commit_before>//conditions for winning
// 1-2-3, 4-5-6, 7-8-9
// 1-4-7, 2-5-8, 3-6-9
// 1-5-9, 3-5-7

// GAME START
var gameStart = function(){

};

var player = 1;
var p1 = [];
var p2 = [];
var square = $('.square')

var playerSwitch = function(){

	if (player === 1){

		player = 2;
		redMove();
	}
	else if (player = 2){
		player = 1
		blueMove();
	}

};

square.click(function(){
	if (player === 1){
		$('#p1').show();
		$('#p2').hide();
		player = 2;

	}
	else if (player = 2){
		$('#p2').show();
		$('#p1').hide();
		player = 1

	}
});

// THE FACT THAT THE ON-CLICK HANDLER IS **INSIDE** EACH
// PLAYER MOVE FUNCTION IS PROBABLY WHY YOU KEEP GETTING REPEAT
// LOGIC FIRING AGAIN AND AGAIN

var blues = []; //stores blue players moves
var reds = []; //stores red players moves

var blueMove = function(){

  //ALERT Blue player to move!
  $('#p1').show();
  $('#p2').hide();
  // register blue players input
  $('.square').click(function(){
    $(this).toggleClass('filledBlue');
    blues.push($(this).attr('id'));

    console.log(blues);

    //disable the square from being clicked again unless new game is started
    $('

').insertAfter(this);

    // check if blue wins:
    //    yes --> reset (built into counter function)
    //    no --> red player to move

		blueCheck();
  });
};
//-------------end blueMove();

var redMove = function(){

  //ALERT red player to move!
  $('#p2').show();
  $('#p1').hide();
  // register red players input
  $('.square').click(function(){
    $(this).toggleClass('filledRed');
    reds.push($(this).attr('id'));

    console.log(reds);
    //disable the square from being clicked again unless new game is started
    $('

').insertAfter(this);

    // check if red wins:
    //    yes --> reset (built into counter function)
    //    no --> blue player to move
		redCheck();
	});
};
//--------------end redMove();

var blueCheck = function(){
  if(
    blueCounter()
  ){
    $('.blueWin').show();
    reset();
  }
  else{
    playerSwitch();
  }
};

var redCheck = function(){
  if (
    redCounter()
  ){
      $('.redWin').show();
      reset();
  }
  else{
    playerSwitch();
  }
};

// var boardCheck = function(){
//   if(
//     blueCounter()
//   ){
//     alert('A WINNER IS BLUE PLAYER!');
//     reset();
//   }
//   else if (
//     redCounter()
//   ){
//       alert('A WINNER IS RED PLAYER!')
//       reset();
//   }
//   else{
//     console.log('No Winners yet')
//     return (true);
//   }
//
// };
//-------------end boardCheck();

var blueCounter = function(){
  if(
    ($('.one').hasClass('filledBlue') && $('.two').hasClass('filledBlue') && $('.three').hasClass('filledBlue'))
    ||
    ($('.four').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.six').hasClass('filledBlue'))
    ||
    ($('.seven').hasClass('filledBlue') && $('.eight').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))

    ||

    ($('.one').hasClass('filledBlue') && $('.four').hasClass('filledBlue') && $('.seven').hasClass('filledBlue'))
    ||
    ($('.two').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.eight').hasClass('filledBlue'))
    ||
    ($('.three').hasClass('filledBlue') && $('.six').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))

    ||

    ($('.one').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))
    ||
    ($('.three').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.seven').hasClass('filledBlue'))

  ){
    return(true);
  }
};
//----------------end blueCounter();

var redCounter = function(){
  for(var i = 0; i < reds.length; i++){
     if(
       (reds[i] == "one" || "two" || "three")
       ||
       (reds[i] == "four" || "five" || "six")
       ||
       (reds[i] == "seven" || "eight" || "nine")

       ||

       (reds[i] == "one" || "four" || "seven")
       ||
       (reds[i] == "two" || "five" || "eight")
       ||
       (reds[i] == "three" || "six" || "nine")

       ||

       (reds[i] == "one" || "five" || "nine")
       ||
       (reds[i] == "three" || "five" || "seven")
     ){
         return true;
     }
  }

  // if(
  //   ($('.one').hasClass('filledRed') && $('.two').hasClass('filledRed') && $('.three').hasClass('filledRed'))
  //   ||
  //   ($('.four').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.six').hasClass('filledRed'))
  //   ||
  //   ($('.seven').hasClass('filledRed') && $('.eight').hasClass('filledRed') && $('.nine').hasClass('filledRed'))
  //
  //   ||
  //
  //   ($('.one').hasClass('filledRed') && $('.four').hasClass('filledRed') && $('.seven').hasClass('filledRed'))
  //   ||
  //   ($('.two').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.eight').hasClass('filledRed'))
  //   ||
  //   ($('.three').hasClass('filledRed') && $('.six').hasClass('filledRed') && $('.nine').hasClass('filledRed'))
  //
  //   ||
  //
  //   ($('.one').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.nine').hasClass('filledRed'))
  //   ||
  //   ($('.three').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.seven').hasClass('filledRed'))
  //
  // )
  {
      return(true);
  }
};
//-----------------end redCounter();

var reset = function(){
  $('#p1, #p2').hide();
  $('.reset').show();
  $('button.newGameStart').click(function(){
    $('.square').removeClass('filledBlue');
    $('.square').removeClass('filledRed');
    $('.clickBlock').remove();
    blues = [];
    reds=[];
    console.log('1v1 ME NOOB')
  });
};
<commit_msg>my rule checking function was NOT consistent between blue and red, derp derp derp<commit_after>//conditions for winning
// 1-2-3, 4-5-6, 7-8-9
// 1-4-7, 2-5-8, 3-6-9
// 1-5-9, 3-5-7

// GAME START
var gameStart = function(){

};

var player = 1;
var p1 = [];
var p2 = [];
var square = $('.square')

var blues = []; //stores blue players moves
var reds = []; //stores red players moves

var playerSwitch = function(){

	if (player === 1){

		player = 2;
		redMove();
	}
	else if (player = 2){
		player = 1
		blueMove();
	}

};

square.click(function(){
	if (player === 1){
		// $('#p1').show();
		// $('#p2').hide();
		$(this).toggleClass('filledBlue');
		blues.push($(this).attr('id'));
    $('

').insertAfter(this);
		//check if blue wins

		console.log(blues)
		player = 2;

	}
	else if (player = 2){
		// $('#p2').show();
		// $('#p1').hide();
		$(this).toggleClass('filledRed');
    reds.push($(this).attr('id'));
    $('

').insertAfter(this);
		//check if red wins

		console.log(reds)
		player = 1

	}
});

// THE FACT THAT THE ON-CLICK HANDLER IS **INSIDE** EACH
// PLAYER MOVE FUNCTION IS PROBABLY WHY YOU KEEP GETTING REPEAT
// LOGIC FIRING AGAIN AND AGAIN

var blueMove = function(){

  //ALERT Blue player to move!
  $('#p1').show();
  $('#p2').hide();
  // register blue players input
  $('.square').click(function(){
    $(this).toggleClass('filledBlue');
    blues.push($(this).attr('id'));

    console.log(blues);

    //disable the square from being clicked again unless new game is started
    $('

').insertAfter(this);

    // check if blue wins:
    //    yes --> reset (built into counter function)
    //    no --> red player to move

		blueCheck();
  });
};
//-------------end blueMove();

var redMove = function(){

  //ALERT red player to move!
  $('#p2').show();
  $('#p1').hide();
  // register red players input
  $('.square').click(function(){
    $(this).toggleClass('filledRed');
    reds.push($(this).attr('id'));

    console.log(reds);
    //disable the square from being clicked again unless new game is started
    $('

').insertAfter(this);

    // check if red wins:
    //    yes --> reset (built into counter function)
    //    no --> blue player to move
		redCheck();
	});
};
//--------------end redMove();

var blueCheck = function(){
  if(
    blueCounter()
  ){
    $('.blueWin').show();
    reset();
  }

};

var redCheck = function(){
  if (
    redCounter()
  ){
      $('.redWin').show();
      reset();
  }
};

// var boardCheck = function(){
//   if(
//     blueCounter()
//   ){
//     alert('A WINNER IS BLUE PLAYER!');
//     reset();
//   }
//   else if (
//     redCounter()
//   ){
//       alert('A WINNER IS RED PLAYER!')
//       reset();
//   }
//   else{
//     console.log('No Winners yet')
//     return (true);
//   }
//
// };
//-------------end boardCheck();

var blueCounter = function(){
  if(
    ($('.one').hasClass('filledBlue') && $('.two').hasClass('filledBlue') && $('.three').hasClass('filledBlue'))
    ||
    ($('.four').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.six').hasClass('filledBlue'))
    ||
    ($('.seven').hasClass('filledBlue') && $('.eight').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))

    ||

    ($('.one').hasClass('filledBlue') && $('.four').hasClass('filledBlue') && $('.seven').hasClass('filledBlue'))
    ||
    ($('.two').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.eight').hasClass('filledBlue'))
    ||
    ($('.three').hasClass('filledBlue') && $('.six').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))

    ||

    ($('.one').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))
    ||
    ($('.three').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.seven').hasClass('filledBlue'))

  ){
    return(true);
  }
};
//----------------end blueCounter();

var redCounter = function(){
  // for(var i = 0; i < reds.length; i++){
  //    if(
  //      (reds[i] == "one" || "two" || "three")
  //      ||
  //      (reds[i] == "four" || "five" || "six")
  //      ||
  //      (reds[i] == "seven" || "eight" || "nine")
	//
  //      ||
	//
  //      (reds[i] == "one" || "four" || "seven")
  //      ||
  //      (reds[i] == "two" || "five" || "eight")
  //      ||
  //      (reds[i] == "three" || "six" || "nine")
	//
  //      ||
	//
  //      (reds[i] == "one" || "five" || "nine")
  //      ||
  //      (reds[i] == "three" || "five" || "seven")
  //    ){
  //        return true;
  //    }
  // }

  if(
    ($('.one').hasClass('filledRed') && $('.two').hasClass('filledRed') && $('.three').hasClass('filledRed'))
    ||
    ($('.four').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.six').hasClass('filledRed'))
    ||
    ($('.seven').hasClass('filledRed') && $('.eight').hasClass('filledRed') && $('.nine').hasClass('filledRed'))

    ||

    ($('.one').hasClass('filledRed') && $('.four').hasClass('filledRed') && $('.seven').hasClass('filledRed'))
    ||
    ($('.two').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.eight').hasClass('filledRed'))
    ||
    ($('.three').hasClass('filledRed') && $('.six').hasClass('filledRed') && $('.nine').hasClass('filledRed'))

    ||

    ($('.one').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.nine').hasClass('filledRed'))
    ||
    ($('.three').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.seven').hasClass('filledRed'))

  )
  {
      return(true);
  }
};
//-----------------end redCounter();

var reset = function(){
  $('#p1, #p2').hide();
  $('.reset').show();
  $('button.newGameStart').click(function(){
    $('.square').removeClass('filledBlue');
    $('.square').removeClass('filledRed');
    $('.clickBlock').remove();
    blues = [];
    reds=[];
    console.log('1v1 ME NOOB')
  });
};
<|endoftext|>


<commit_before>var BaseSampler = require('./base-sampler');
var ReservoirSampler = require('./reservoir-sampler');
var inherits = require('util').inherits;
var debug = require('debug')('mongodb-collection-sample:native-sampler');

/**
 * A readable stream of sample of documents from a collection using the
 * `$sample` aggregation operator.
 *
 * @param {mongodb.DB} db
 * @param {String} collectionName to source from.
 * @param {Object} opts
 * @option {Object} query to refine possible samples [default: `{}`].
 * @option {Array} fields to only return certain fields [default: null]
 * @option {Number} size of the sample to capture [default: `5`].
 * @api public
 */
function NativeSampler(db, collectionName, opts) {
  BaseSampler.call(this, db, collectionName, opts);

  this.running = false;

  // match
  this.pipeline = [];
  if (Object.keys(this.query).length > 0) {
    this.pipeline.push({
      $match: this.query
    });
  }

  // sample size
  this.pipeline.push({
    $sample: {
      size: this.size
    }
  });

  // projection (last operation, only needs to be applied to sampled docs)
  if (this.fields && Object.keys(this.fields).length > 0) {
    this.pipeline.push({
      $project: this.fields
    });
  }
}
inherits(NativeSampler, BaseSampler);

NativeSampler.prototype._read = function() {
  if (this.running) {
    return;
  }

  this.running = true;

  var options = {
    maxTimeMS: this.maxTimeMS,
    promoteValues: this.promoteValues
  };

  this.collection.count(this.query, options, function(err, count) {
    if (err) {
      return this.emit('error', err);
    }

    debug('sampling %d documents from a collection with %d documents',
      this.size, count);

    // if we need more docs than counted, use find to return all docs
    if (count <= this.size) {
      return this.collection.find(this.query, {
        fields: this.fields
      }).on('error', this.emit.bind(this, 'error'))
        .on('data', this.push.bind(this))
        .on('end', this.push.bind(this, null));
    }

    // if we need more than 5% of all docs, use ReservoirSampler to avoid
    // the blocking sort stage (SERVER-22815)
    if (count <= this.size * 20) {
      var reservoirSampler = new ReservoirSampler(this.db, this.collectionName, this.opts);
      return reservoirSampler
      .on('error', this.emit.bind(this, 'error'))
      .on('data', this.push.bind(this))
      .on('end', this.push.bind(this, null));
    }

    // else, use native sampler with random index walk optimization
    this.db.command({atlasSize: 1}, function(errAtlas) {
      // only enable `allowDiskUse` when not connected to Atlas Free tier
      if (errAtlas && errAtlas.message.match(/no such command/)) {
        options.allowDiskUse = true;
      }
      this.collection.aggregate(this.pipeline, options)
        .on('error', this.emit.bind(this, 'error'))
        .on('data', this.push.bind(this))
        .on('end', this.push.bind(this, null));
    }.bind(this));
  }.bind(this));
};

module.exports = NativeSampler;
<commit_msg>COMPASS-890: Undo special-casing `allowDiskUse` for Atlas (#90)<commit_after>var BaseSampler = require('./base-sampler');
var ReservoirSampler = require('./reservoir-sampler');
var inherits = require('util').inherits;
var debug = require('debug')('mongodb-collection-sample:native-sampler');

/**
 * A readable stream of sample of documents from a collection using the
 * `$sample` aggregation operator.
 *
 * @param {mongodb.DB} db
 * @param {String} collectionName to source from.
 * @param {Object} opts
 * @option {Object} query to refine possible samples [default: `{}`].
 * @option {Array} fields to only return certain fields [default: null]
 * @option {Number} size of the sample to capture [default: `5`].
 * @api public
 */
function NativeSampler(db, collectionName, opts) {
  BaseSampler.call(this, db, collectionName, opts);

  this.running = false;

  // match
  this.pipeline = [];
  if (Object.keys(this.query).length > 0) {
    this.pipeline.push({
      $match: this.query
    });
  }

  // sample size
  this.pipeline.push({
    $sample: {
      size: this.size
    }
  });

  // projection (last operation, only needs to be applied to sampled docs)
  if (this.fields && Object.keys(this.fields).length > 0) {
    this.pipeline.push({
      $project: this.fields
    });
  }
}
inherits(NativeSampler, BaseSampler);

NativeSampler.prototype._read = function() {
  if (this.running) {
    return;
  }

  this.running = true;

  var options = {
    maxTimeMS: this.maxTimeMS,
    allowDiskUse: true,
    promoteValues: this.promoteValues
  };

  this.collection.count(this.query, options, function(err, count) {
    if (err) {
      return this.emit('error', err);
    }

    debug('sampling %d documents from a collection with %d documents',
      this.size, count);

    // if we need more docs than counted, use find to return all docs
    if (count <= this.size) {
      return this.collection.find(this.query, {
        fields: this.fields
      }).on('error', this.emit.bind(this, 'error'))
        .on('data', this.push.bind(this))
        .on('end', this.push.bind(this, null));
    }

    // if we need more than 5% of all docs, use ReservoirSampler to avoid
    // the blocking sort stage (SERVER-22815)
    if (count <= this.size * 20) {
      var reservoirSampler = new ReservoirSampler(this.db, this.collectionName, this.opts);
      return reservoirSampler
      .on('error', this.emit.bind(this, 'error'))
      .on('data', this.push.bind(this))
      .on('end', this.push.bind(this, null));
    }

    // else, use native sampler with random index walk optimization in the Server
    this.collection.aggregate(this.pipeline, options)
      .on('error', this.emit.bind(this, 'error'))
      .on('data', this.push.bind(this))
      .on('end', this.push.bind(this, null));
  }.bind(this));
};

module.exports = NativeSampler;
<|endoftext|>


<commit_before>import _ from 'lodash'

const CARRY_OVER_PROPERTIES = ['label', 'dependsOn', 'description', 'disabled', 'model', 'placeholder']
const ARRAY_CELL_PROPERTIES = ['autoAdd', 'compact', 'showLabel', 'sortable']

/**
 * Turns rootContainers from V1 view into cells in v2 view
 *
 * @export
 * @param {Object[]} rootContainers Containers to convert
 * @returns {object[]} Array of cells converted from rootContainers
 */
export function generateCells (rootContainers) {
  return _.chain(rootContainers).flattenDeep().map(convertCell).filter().value()
}

/**
 * Converts an complex container cell for an object into a v2 cell
 *
 * @param {object} cell Cell that should display an object
 * @returns {object} Cell converted to v2
 */
function convertObjectCell (cell) {
  return _.chain(cell.rows)
  .map(rowsToCells)
  .assign(_.pick(cell, CARRY_OVER_PROPERTIES))
  .value()
}

/**
 * Converts a container cell that displays an array into a v2 cell
 *
 * @param {object} cell Cell that should display an array
 * @returns {object} Cell converted to v2
 */
function convertArrayCell (cell) {
  const {item} = cell
  const arrayOptions = _.chain(item)
  .pick(ARRAY_CELL_PROPERTIES)
  .assign({
    itemCell: convertCell(item)
  })
  .value()
  return {
    arrayOptions,
    model: cell.model
  }
}

/**
 * Creates custom renderer information for a cell
 *
 * @param {string} renderer Name of the desired renderer
 * @param {object} properties Info for to the custom renderer
 * @returns {object} Custom renderer block
 */
function customRenderer (renderer, properties) {
  return _.assign({
    name: renderer
  }, properties)
}

/**
 * Converts v1 renderer information to v2 for a cell
 *
 * @param {object} cell Cell with a custom renderer
 * @returns {object} Custom renderer block for the given cell
 */
function convertRenderer (cell) {
  const {renderer} = cell
  if (renderer === undefined) {
    return
  }
  switch (renderer) {
    case 'boolean':
    case 'string':
    case 'number':
      return {name: renderer}
    case 'button-group':
    case 'select':
    case 'multi-select':
    case 'textarea':
    default:
      return customRenderer(renderer, cell.properties)
  }
}

/**
 * Creates class name block for v2 cell
 *
 * @param {object} cell Cell to get class names from
 * @returns {object} Class name block for the cell
 */
function grabClassNames (cell) {
  const classNames = _.pickBy({
    cell: cell.className,
    value: cell.inputClassName,
    label: cell.labelClassName
  })
  if (_.size(classNames) > 0) {
    return classNames
  }
}

/**
 * Converts a cell for simple data type (e.g. string, or number)
 *
 * @param {object} cell Cell in v1 to convert to v2
 * @returns {object} Cell converted to v2
 */
function convertBasicCell (cell) {
  return _.pickBy(_.assign({
    renderer: convertRenderer(cell)
  }, _.pick(cell, CARRY_OVER_PROPERTIES)))
}

/**
 * Determines which cell conversion function to use to convert v1 cell to v2 and converts it
 *
 * @export
 * @param {object} cell A v1 cell to convert to v2
 * @returns {object} The cell converted to v2
 */
export function convertCell (cell) {
  let cellConverter
  if (cell.item) {
    cellConverter = convertArrayCell
  } else if (cell.rows) {
    cellConverter = convertObjectCell
  } else {
    cellConverter = convertBasicCell
  }

  return _.pickBy(_.assign({
    extends: cell.container,
    classNames: grabClassNames(cell)
  }, cellConverter(cell)))
}

/**
 * Converts rows of v1 cells to v2 cells. Simplifies the row structure when possible.
 *
 * @param {object[][]} rows A set of rows to convert
 * @returns {object} A v2 cell
 */
function rowsToCells (rows) {
  const collapseRows = !_.some(rows, function (row) {
    return row.length > 1
  })
  const collapseColumns = rows.length <= 1
  let rowChain = _.chain(rows)
  if (collapseRows && collapseColumns) {
    return rowChain.flattenDeep().map(convertCell).filter().first().value()
  }
  let children
  if (collapseRows || collapseColumns) {
    children = rowChain.flattenDeep().map(convertCell).filter().value()
  } else {
    children = rowChain.map((row) => {
      return {
        children: _.map(row, convertCell)
      }
    }).filter().value()
  }
  return {
    children
  }
}

/**
 * Converts the container declarations in a v1 view to cell definitions in a v2 view
 *
 * @export
 * @param {object[]} containers Set of containers to convert
 * @returns {object} cell definitions for the v2 view.
 */
export function generateCellDefinitions (containers) {
  return _.chain(containers)
  .map(function (container) {
    const {collapsible, rows, id, className} = container
    const cell = rowsToCells(rows)

    if (!cell) {
      return null
    }

    if (className !== undefined) {
      cell.classNames = {
        cell: className
      }
    }

    if (collapsible !== undefined) {
      cell.collapsible = collapsible
    }

    return [id, cell]
  })
  .without(null)
  .fromPairs()
  .value()
}

/**
 * Converts a bunsen version 1 view into a bunsen/ui schema version 2 view
 *
 * @export
 * @param {any} v1View A v1 view to convert to v2
 * @returns {object} The v2 view generated from the given v1 view
 */
export default function viewV1ToV2 (v1View) {
  const {type} = v1View

  if (v1View.rootContainers.length === 1) {
    delete v1View.rootContainers[0].label
  }

  const cells = generateCells(v1View.rootContainers)

  const cellDefinitions = generateCellDefinitions(v1View.containers)

  return {
    version: '2.0',
    type,
    cells,
    cellDefinitions
  }
}
<commit_msg>Stop breaking container semantics<commit_after>import _ from 'lodash'

const CARRY_OVER_PROPERTIES = ['label', 'dependsOn', 'description', 'disabled', 'model', 'placeholder']
const ARRAY_CELL_PROPERTIES = ['autoAdd', 'compact', 'showLabel', 'sortable']

/**
 * Turns rootContainers from V1 view into cells in v2 view
 *
 * @export
 * @param {Object[]} rootContainers Containers to convert
 * @returns {object[]} Array of cells converted from rootContainers
 */
export function generateCells (rootContainers) {
  return _.chain(rootContainers).flattenDeep().map(convertCell).filter().value()
}

/**
 * Converts an complex container cell for an object into a v2 cell
 *
 * @param {object} cell Cell that should display an object
 * @returns {object} Cell converted to v2
 */
function convertObjectCell (cell) {
  return _.chain(cell.rows)
  .map(rowsToCells)
  .assign(_.pick(cell, CARRY_OVER_PROPERTIES))
  .value()
}

/**
 * Converts a container cell that displays an array into a v2 cell
 *
 * @param {object} cell Cell that should display an array
 * @returns {object} Cell converted to v2
 */
function convertArrayCell (cell) {
  const {item} = cell
  const arrayOptions = _.chain(item)
  .pick(ARRAY_CELL_PROPERTIES)
  .assign({
    itemCell: convertCell(item)
  })
  .value()
  return {
    arrayOptions,
    model: cell.model
  }
}

/**
 * Creates custom renderer information for a cell
 *
 * @param {string} renderer Name of the desired renderer
 * @param {object} properties Info for to the custom renderer
 * @returns {object} Custom renderer block
 */
function customRenderer (renderer, properties) {
  return _.assign({
    name: renderer
  }, properties)
}

/**
 * Converts v1 renderer information to v2 for a cell
 *
 * @param {object} cell Cell with a custom renderer
 * @returns {object} Custom renderer block for the given cell
 */
function convertRenderer (cell) {
  const {renderer} = cell
  if (renderer === undefined) {
    return
  }
  switch (renderer) {
    case 'boolean':
    case 'string':
    case 'number':
      return {name: renderer}
    case 'button-group':
    case 'select':
    case 'multi-select':
    case 'textarea':
    default:
      return customRenderer(renderer, cell.properties)
  }
}

/**
 * Creates class name block for v2 cell
 *
 * @param {object} cell Cell to get class names from
 * @returns {object} Class name block for the cell
 */
function grabClassNames (cell) {
  const classNames = _.pickBy({
    cell: cell.className,
    value: cell.inputClassName,
    label: cell.labelClassName
  })
  if (_.size(classNames) > 0) {
    return classNames
  }
}

/**
 * Converts a cell for simple data type (e.g. string, or number)
 *
 * @param {object} cell Cell in v1 to convert to v2
 * @returns {object} Cell converted to v2
 */
function convertBasicCell (cell) {
  return _.pickBy(_.assign({
    renderer: convertRenderer(cell)
  }, _.pick(cell, CARRY_OVER_PROPERTIES)))
}

/**
 * Determines which cell conversion function to use to convert v1 cell to v2 and converts it
 *
 * @export
 * @param {object} cell A v1 cell to convert to v2
 * @returns {object} The cell converted to v2
 */
export function convertCell (cell) {
  let cellConverter
  if (cell.item) {
    cellConverter = convertArrayCell
  } else if (cell.rows) {
    cellConverter = convertObjectCell
  } else {
    cellConverter = convertBasicCell
  }

  return _.pickBy(_.assign({
    extends: cell.container,
    classNames: grabClassNames(cell)
  }, cellConverter(cell)))
}

/**
 * Converts rows of v1 cells to v2 cells. Simplifies the row structure when possible.
 *
 * @param {object[][]} rows A set of rows to convert
 * @returns {object} A v2 cell
 */
function rowsToCells (rows) {
  return {
    children: _.chain(rows).map((row) => {
      return {
        children: _.map(row, convertCell)
      }
    }).filter().value()
  }
}

/**
 * Converts the container declarations in a v1 view to cell definitions in a v2 view
 *
 * @export
 * @param {object[]} containers Set of containers to convert
 * @returns {object} cell definitions for the v2 view.
 */
export function generateCellDefinitions (containers) {
  return _.chain(containers)
  .map(function (container) {
    const {collapsible, rows, id, className, label} = container
    const cell = rowsToCells(rows)

    if (!cell) {
      return null
    }

    if (className !== undefined) {
      cell.classNames = {
        cell: className
      }
    }

    if (collapsible !== undefined) {
      cell.collapsible = collapsible
    }

    if (label !== undefined) {
      cell.label = label
    }

    return [id, cell]
  })
  .without(null)
  .fromPairs()
  .value()
}

/**
 * Converts a bunsen version 1 view into a bunsen/ui schema version 2 view
 *
 * @export
 * @param {any} v1View A v1 view to convert to v2
 * @returns {object} The v2 view generated from the given v1 view
 */
export default function viewV1ToV2 (v1View) {
  const {type} = v1View

  if (v1View.rootContainers.length === 1) {
    delete v1View.rootContainers[0].label
  }

  const cells = generateCells(v1View.rootContainers)

  const cellDefinitions = generateCellDefinitions(v1View.containers)

  return {
    version: '2.0',
    type,
    cells,
    cellDefinitions
  }
}
<|endoftext|>


<commit_before>//var BigNumber = require("bignumber.js");

function Packet(id, buffer, start, end)
{
  this.sequenceId = id;
  this.buffer = buffer;
  this.offset = start;
  this.start = start;
  this.end = end;
}

// ==============================
// readers
// ==============================

Packet.prototype.reset = function() {
  this.offset = this.start;
};

Packet.prototype.length = function() {
  return this.end - this.start;
};

Packet.prototype.haveMoreData = function() {
  return this.end > this.offset;
};

Packet.prototype.skip = function(num) {
   if (!num)
     throw "Bad param in skip!"; // for some reason I keep doing skip(0) to indicate "skip one byte which should be 0"
   this.offset += num;
};

Packet.prototype.readInt8 = function()
{
  return this.buffer[this.offset++];
};

Packet.prototype.readInt16 = function()
{
  this.offset += 2;
  return this.buffer.readUInt16LE(this.offset - 2);
};

Packet.prototype.readInt32 = function()
{
  this.offset += 4;
  return this.buffer.readUInt32LE(this.offset - 4);
};

Packet.prototype.isEOF = function() {
  return this.buffer[this.offset] == 0xfe && this.length() < 9;
};

Packet.prototype.readLengthCodedNumber = function() {
   var byte1 = this.readInt8();
   if (byte1 < 0xfb)
     return byte1;
   if (byte1 == 0xfc) {
     return this.readInt8() + (this.readInt8() << 8);
   }
   if (byte1 == 0xfd) {
     return this.readInt8() + (this.readInt8() << 8) + (this.readInt8() << 16);
   }
   if (byte1 == 0xfe) {
     console.trace();
     //throw "Implement 8bytes BigNumber";
   }
   if (byte1 == 0xfb)
     return null;
   throw "Should not reach here: " + byte1;
};

Packet.prototype.readBuffer = function(len) {
  this.offset += len;
  return this.buffer.slice(this.offset - len, this.offset);
};

Packet.prototype.readLengthCodedString = function() {
  var len = this.readLengthCodedNumber();
  // TODO: check manually first byte here to avoid polymorphic return type?
  //if (len === null)
  //  return null;
  this.offset += len;
  return this.buffer.utf8Slice(this.offset - len, this.offset);
};

Packet.prototype.readNullTerminatedString = function() {
  var start = this.offset;
  var end = this.offset;
  while (this.buffer[end])
    end = end + 1; // TODO: handle OOB check
  this.offset = end + 1;
  return this.buffer.utf8Slice(start, end);
};

// TODO reuse?
Packet.prototype.readString = function(len) {
  this.offset += len;
  return this.buffer.utf8Slice(this.offset - len, this.offset);
};

// TODO: base? sign? parseFloat?
Packet.prototype.parseInt = function(len) {
  var result = 0;
  var end = this.offset + len;
  while(this.offset < end) {
    result *= 10;
    result += this.buffer[this.offset] - 48;
    this.offset++;
  }
  return result;
};

Packet.prototype.parseLengthCodedInt = function() {
  return this.parseInt(this.readLengthCodedNumber());
}

Packet.prototype.isError = function() {
  // TODO: will be changed to buffer[4]
  return this.buffer[0] == 0xff;
};

Packet.prototype.asError = function() {
  this.offset = 1;
  var code = this.readInt8();
  var sqlState = this.readBuffer(7);
  var message = this.buffer.slice(this.offset);
  console.log('SqlState', sqlState.toString(), 'message', message.toString());
  var err = new Error(message.toString());
  err.code = this.code;
  return err;
};

Packet.lengthCodedNumberLength = function(n) {
   if (n < 0xfb)
     return 1;
   if (n < 0xffff)
     return 3;
   if (n < 0xffffff)
     return 5;
   else
     return 9;
};

Packet.prototype.writeInt32 = function(n) {
  this.buffer.writeUInt32LE(n, this.offset);
  this.offset += 4;
};

Packet.prototype.writeInt24 = function(n) {
  this.writeInt8(n & 0xff);
  this.writeInt16(n >> 8);
};

Packet.prototype.writeInt16 = function(n) {
  this.buffer.writeUInt16LE(n, this.offset);
  this.offset += 2;
};

Packet.prototype.writeInt8 = function(n) {
  this.buffer[this.offset] = n;
  this.offset++;
};

Packet.prototype.writeBuffer = function(b) {
  b.copy(this.buffer, this.offset);
  this.offset += b.length;
};

// TODO: refactor following three?
Packet.prototype.writeNullTerminatedString = function(s) {
  this.buffer.write(s, this.offset);
  this.offset += s.length;
  this.writeInt8(0);
};

Packet.prototype.writeString = function(s) {
  var bytes = Buffer.byteLength(s, 'utf8');
  this.buffer.write(s, this.offset, bytes, 'utf8');
  this.offset += bytes;
};

Packet.prototype.writeLengthCodedString = function(s) {
  this.writeLengthCodedNumber(s.length);
  this.buffer.write(s, this.offset);
  this.offset += s.length;
};

Packet.prototype.writeLengthCodedNumber = function(n) {
  // TODO: null
  if (n < 0xfb)
    return this.writeInt8(n);
  if (n < 0xffff) {
    this.writeInt8(0xfc);
    return this.writeInt16(n);
  }
  if (this < 0xffffff) {
    this.writeInt8(0xfd);
    return this.writeInt24(n);
  }
  throw "No bignumbers yet";
};

Packet.prototype.writeHeader = function()
{
  var offset = this.offset;
  this.offset = 0;
  this.writeInt24(this.buffer.length - 4);
  this.writeInt8(this.sequenceId);
  this.offset = offset;
};

// TODO: base toPacket() ?

module.exports = Packet;
<commit_msg>fix for isError<commit_after>//var BigNumber = require("bignumber.js");

function Packet(id, buffer, start, end)
{
  this.sequenceId = id;
  this.buffer = buffer;
  this.offset = start;
  this.start = start;
  this.end = end;
}

// ==============================
// readers
// ==============================

Packet.prototype.reset = function() {
  this.offset = this.start;
};

Packet.prototype.length = function() {
  return this.end - this.start;
};

Packet.prototype.dump = function() {
  console.log([this.buffer.asciiSlice(this.start, this.end)], this.buffer.slice(this.start, this.end), this.length(), this.sequenceId);
};

Packet.prototype.haveMoreData = function() {
  return this.end > this.offset;
};

Packet.prototype.skip = function(num) {
   if (!num)
     throw "Bad param in skip!"; // for some reason I keep doing skip(0) to indicate "skip one byte which should be 0"
   this.offset += num;
};

Packet.prototype.readInt8 = function()
{
  return this.buffer[this.offset++];
};

Packet.prototype.readInt16 = function()
{
  this.offset += 2;
  return this.buffer.readUInt16LE(this.offset - 2);
};

Packet.prototype.readInt32 = function()
{
  this.offset += 4;
  return this.buffer.readUInt32LE(this.offset - 4);
};

Packet.prototype.isEOF = function() {
  return this.buffer[this.offset] == 0xfe && this.length() < 9;
};

Packet.prototype.readLengthCodedNumber = function() {
   var byte1 = this.readInt8();
   if (byte1 < 0xfb)
     return byte1;
   if (byte1 == 0xfc) {
     return this.readInt8() + (this.readInt8() << 8);
   }
   if (byte1 == 0xfd) {
     return this.readInt8() + (this.readInt8() << 8) + (this.readInt8() << 16);
   }
   if (byte1 == 0xfe) {
     console.trace();
     //throw "Implement 8bytes BigNumber";
   }
   if (byte1 == 0xfb)
     return null;
   throw "Should not reach here: " + byte1;
};

Packet.prototype.readBuffer = function(len) {
  this.offset += len;
  return this.buffer.slice(this.offset - len, this.offset);
};

Packet.prototype.readLengthCodedString = function() {
  var len = this.readLengthCodedNumber();
  // TODO: check manually first byte here to avoid polymorphic return type?
  //if (len === null)
  //  return null;
  this.offset += len;
  return this.buffer.utf8Slice(this.offset - len, this.offset);
};

Packet.prototype.readNullTerminatedString = function() {
  var start = this.offset;
  var end = this.offset;
  while (this.buffer[end])
    end = end + 1; // TODO: handle OOB check
  this.offset = end + 1;
  return this.buffer.utf8Slice(start, end);
};

// TODO reuse?
Packet.prototype.readString = function(len) {
  this.offset += len;
  return this.buffer.utf8Slice(this.offset - len, this.offset);
};

// TODO: base? sign? parseFloat?
Packet.prototype.parseInt = function(len) {
  var result = 0;
  var end = this.offset + len;
  while(this.offset < end) {
    result *= 10;
    result += this.buffer[this.offset] - 48;
    this.offset++;
  }
  return result;
};

Packet.prototype.parseLengthCodedInt = function() {
  return this.parseInt(this.readLengthCodedNumber());
}

Packet.prototype.isError = function() {
  return this.buffer[this.offset] == 0xff;
};

Packet.prototype.asError = function() {
  this.offset = 1;
  var code = this.readInt8();
  var sqlState = this.readBuffer(7);
  var message = this.buffer.slice(this.offset);
  console.log('SqlState', sqlState.toString(), 'message', message.toString());
  var err = new Error(message.toString());
  err.code = this.code;
  return err;
};

Packet.lengthCodedNumberLength = function(n) {
   if (n < 0xfb)
     return 1;
   if (n < 0xffff)
     return 3;
   if (n < 0xffffff)
     return 5;
   else
     return 9;
};

Packet.prototype.writeInt32 = function(n) {
  this.buffer.writeUInt32LE(n, this.offset);
  this.offset += 4;
};

Packet.prototype.writeInt24 = function(n) {
  this.writeInt8(n & 0xff);
  this.writeInt16(n >> 8);
};

Packet.prototype.writeInt16 = function(n) {
  this.buffer.writeUInt16LE(n, this.offset);
  this.offset += 2;
};

Packet.prototype.writeInt8 = function(n) {
  this.buffer[this.offset] = n;
  this.offset++;
};

Packet.prototype.writeBuffer = function(b) {
  b.copy(this.buffer, this.offset);
  this.offset += b.length;
};

// TODO: refactor following three?
Packet.prototype.writeNullTerminatedString = function(s) {
  this.buffer.write(s, this.offset);
  this.offset += s.length;
  this.writeInt8(0);
};

Packet.prototype.writeString = function(s) {
  var bytes = Buffer.byteLength(s, 'utf8');
  this.buffer.write(s, this.offset, bytes, 'utf8');
  this.offset += bytes;
};

Packet.prototype.writeLengthCodedString = function(s) {
  this.writeLengthCodedNumber(s.length);
  this.buffer.write(s, this.offset);
  this.offset += s.length;
};

Packet.prototype.writeLengthCodedNumber = function(n) {
  // TODO: null
  if (n < 0xfb)
    return this.writeInt8(n);
  if (n < 0xffff) {
    this.writeInt8(0xfc);
    return this.writeInt16(n);
  }
  if (this < 0xffffff) {
    this.writeInt8(0xfd);
    return this.writeInt24(n);
  }
  throw "No bignumbers yet";
};

Packet.prototype.writeHeader = function()
{
  var offset = this.offset;
  this.offset = 0;
  this.writeInt24(this.buffer.length - 4);
  this.writeInt8(this.sequenceId);
  this.offset = offset;
};

// TODO: base toPacket() ?

module.exports = Packet;
<|endoftext|>


<commit_before>'use strict';

var CssSyntaxError = require('./error');
var TokenType = require('./const').TokenType;
var TokenName = require('./const').TokenName;
var IS_PUNCTUATOR = require('./const').IS_PUNCTUATOR;
var SYMBOL_CATEGORY = require('./const').SYMBOL_CATEGORY;
var SYMBOL_CATEGORY_LENGTH = SYMBOL_CATEGORY.length;
var cmpStr = require('./utils').cmpStr;
var isHex = require('./utils').isHex;

var NULL = 0;
var WHITESPACE = TokenType.Whitespace;
var IDENTIFIER = TokenType.Identifier;
var NUMBER = TokenType.DecimalNumber;
var STRING = TokenType.String;
var COMMENT = TokenType.Comment;
var PUNCTUATOR = TokenType.Punctuator;

var TAB = 9;
var N = 10;
var F = 12;
var R = 13;
var SPACE = 32;
var STAR = 42;
var SLASH = 47;
var BACK_SLASH = 92;

var MIN_ARRAY_SIZE = 16 * 1024;
var OFFSET_MASK = 0x00FFFFFF;
var lastIndexOf = Array.prototype.lastIndexOf; // some browser implementations have no TypedArray#lastIndexOf
var LongArray = typeof Uint32Array !== 'undefined' ? Uint32Array : Array;

var offsetAndType = null;
var lines = null;

function firstCharOffset(source) {
    return source.charCodeAt(0) === 0xFEFF ? 1 : 0;
}

function computeLines(scanner, source) {
    var sourceLength = source.length;
    var start = firstCharOffset(source);
    var line = scanner.initLine;

    if (lines === null || lines.length < sourceLength + 1) {
        lines = new LongArray(Math.max(sourceLength + 1024, MIN_ARRAY_SIZE));
    }

    for (var i = start; i < sourceLength; i++) {
        var code = source.charCodeAt(i);

        lines[i] = line;

        if (code === N || code === R || code === F) {
            if (code === R && i + 1 < sourceLength && source.charCodeAt(i + 1) === N) {
                i++;
                lines[i] = line;
            }
            line++;
        }
    }

    lines[i] = line;

    return lines;
}

function isNewline(source, offset, code) {
    if (code === N || code === F || code === R) {
        if (code === R && offset + 1 < source.length && source.charCodeAt(offset + 1) === N) {
            return 2;
        }

        return 1;
    }

    return 0;
}

function findWhitespaceEnd(source, offset) {
    for (; offset < source.length; offset++) {
        var code = source.charCodeAt(offset);

        if (code !== SPACE && code !== TAB && code !== R && code !== N && code !== F) {
            break;
        }
    }

    return offset;
}

function findCommentEnd(source, offset) {
    var commentEnd = source.indexOf('*/', offset);

    if (commentEnd === -1) {
        return source.length;
    }

    return commentEnd + 2;
}

function findStringEnd(source, offset, quote) {
    for (; offset < source.length; offset++) {
        var code = source.charCodeAt(offset);

        // TODO: bad string
        if (code === BACK_SLASH) {
            offset++;
        } else if (code === quote) {
            offset++;
            break;
        }
    }

    return offset;
}

function findDecimalNumberEnd(source, offset) {
    for (; offset < source.length; offset++) {
        var code = source.charCodeAt(offset);

        if (code < 48 || code > 57) {  // not a 0 .. 9
            break;
        }
    }

    return offset;
}

// skip escaped unicode sequence that can ends with space
// [0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
function findEscaseEnd(source, offset) {
    for (var i = 0; i < 7 && offset + i < source.length; i++) {
        var code = source.charCodeAt(offset + i);

        if (i !== 6 && isHex(code)) {
            continue;
        }

        if (i > 0) {
            offset += i - 1 + isNewline(source, offset + i, code);
            if (code === SPACE || code === TAB) {
                offset++;
            }
        }

        break;
    }

    return offset;
}

function findIdentifierEnd(source, offset) {
    for (; offset < source.length; offset++) {
        var code = source.charCodeAt(offset);

        if (code === BACK_SLASH) {
            offset = findEscaseEnd(source, offset + 1);
        } else if (code < SYMBOL_CATEGORY_LENGTH && IS_PUNCTUATOR[code] === PUNCTUATOR) {
            break;
        }
    }

    return offset;
}

function tokenLayout(scanner, source, startPos) {
    var sourceLength = source.length;
    var tokenCount = 0;
    var prevType = 0;
    var start = startPos;
    var end;

    if (offsetAndType === null || offsetAndType.length < sourceLength + 1) {
        offsetAndType = new LongArray(Math.max(sourceLength + 1024, MIN_ARRAY_SIZE));
    }

    while (start < sourceLength) {
        var code = source.charCodeAt(start);
        var type = code < SYMBOL_CATEGORY_LENGTH ? SYMBOL_CATEGORY[code] : IDENTIFIER;

        switch (type) {
            case WHITESPACE:
                end = findWhitespaceEnd(source, start + 1);
                break;

            case PUNCTUATOR:
                if (code === STAR && prevType === SLASH) { // /*
                    type = COMMENT;
                    end = findCommentEnd(source, start + 1);

                    // rewrite prevType token
                    tokenCount--;
                    start--;
                } else {
                    type = code;
                    end = start + 1;
                }

                break;

            case NUMBER:
                end = findDecimalNumberEnd(source, start + 1);
                break;

            case STRING:
                end = findStringEnd(source, start + 1, code);
                break;

            default:
                end = findIdentifierEnd(source, start);
        }

        // console.log(type, scanner.source.substring(start, end));
        offsetAndType[tokenCount] = (type << 24) | start;

        tokenCount++;
        start = end;
        prevType = type;
    }

    offsetAndType[tokenCount] = end;

    scanner.offsetAndType = offsetAndType;
    scanner.tokenCount = tokenCount;
}

//
// scanner
//

var Scanner = function(source, initLine, initColumn) {
    var start = firstCharOffset(source);

    this.source = source;
    this.initLine = typeof initLine === 'undefined' ? 1 : initLine;
    this.initColumn = (typeof initColumn === 'undefined' ? 1 : initColumn) - start;
    this.lastLocationLine = this.initLine;
    this.lastLocationLineOffset = 1 - this.initColumn;
    this.lines = null;

    this.eof = false;
    this.currentToken = -1;
    this.tokenType = 0;
    this.tokenStart = start;
    this.tokenEnd = start;

    tokenLayout(this, source, start);
    this.next();
};

Scanner.prototype = {
    lookupType: function(offset) {
        offset += this.currentToken;

        if (offset < this.tokenCount) {
            return this.offsetAndType[offset] >> 24;
        }

        return 0;
    },
    lookupValue: function(offset, referenceStr) {
        offset += this.currentToken;

        if (offset < this.tokenCount) {
            return cmpStr(
                this.source,
                this.offsetAndType[offset] & OFFSET_MASK,
                this.offsetAndType[offset + 1] & OFFSET_MASK,
                referenceStr
            );
        }

        return false;
    },

    getTokenValue: function() {
        return this.source.substring(this.tokenStart, this.tokenEnd);
    },
    substrToCursor: function(start) {
        return this.source.substring(start, this.tokenStart);
    },

    skip: function(tokenCount) {
        if (tokenCount === 1) {
            this.next();
            return;
        }

        var next = this.currentToken + tokenCount;

        if (next < this.tokenCount) {
            this.currentToken = next;
            this.tokenType = this.offsetAndType[next] >> 24;
            this.tokenStart = this.offsetAndType[next] & OFFSET_MASK;
            this.tokenEnd = this.offsetAndType[next + 1] & OFFSET_MASK;
        } else {
            this.currentToken = this.tokenCount;
            this.eof = true;
            this.tokenType = NULL;
            this.tokenStart = this.tokenEnd = this.source.length;
        }
    },
    next: function() {
        var next = this.currentToken + 1;

        if (next < this.tokenCount) {
            this.currentToken = next;
            this.tokenType = this.offsetAndType[next] >> 24;
            this.tokenStart = this.tokenEnd;
            this.tokenEnd = this.offsetAndType[next + 1] & OFFSET_MASK;
        } else {
            this.currentToken = this.tokenCount;
            this.eof = true;
            this.tokenType = NULL;
            this.tokenStart = this.tokenEnd = this.source.length;
        }
    },

    eat: function(tokenType) {
        if (this.tokenType === tokenType) {
            this.next();
            return true;
        }

        this.error(TokenName[tokenType] + ' is expected');
    },
    expectIdentifier: function(name) {
        if (this.tokenType === IDENTIFIER && cmpStr(this.source, this.tokenStart, this.tokenEnd, name)) {
            this.next();
            return true;
        }

        this.error('Identifier `' + name + '` is expected');
    },

    getLocation: function(offset, source) {
        if (this.lines === null) {
            this.lines = computeLines(this, this.source);
        }

        var line = this.lines[offset];
        var column = offset;
        var lineOffset;

        if (line === this.initLine) {
            column += this.initColumn;
        } else {
            // try get precomputed line offset
            if (line === this.lastLocationLine) {
                lineOffset = this.lastLocationLineOffset;
            } else {
                // try avoid to compute line offset since it's expensive for long lines
                lineOffset = lastIndexOf.call(this.lines, line - 1, offset);
                this.lastLocationLine = line;
                this.lastLocationLineOffset = lineOffset;
            }

            column -= lineOffset;
        }

        return {
            source: source,
            offset: offset,
            line: line,
            column: column
        };
    },
    findLastNonSpaceLocation: function() {
        for (var i = (this.offsetAndType[this.currentToken] & OFFSET_MASK) - 1; i >= 0; i--) {
            var code = this.source.charCodeAt(i);

            if (code !== SPACE && code !== TAB && code !== R && code !== N && code !== F) {
                break;
            }
        }

        return this.getLocation(i + 1);
    },

    error: function(message, offset) {
        var location = !this.eof
            ? this.getLocation(typeof offset !== 'undefined' ? offset : this.tokenStart)
            : this.findLastNonSpaceLocation();

        throw new CssSyntaxError(
            message,
            this.source,
            location.offset,
            location.line,
            location.column
        );
    }
};

// warm up tokenizer to elimitate code branches that never execute
// fix soft deoptimizations (insufficient type feedback)
new Scanner('\n\r\r\n\f//""\'\'/*\r\n\f*/1a;.\\31\t\+2{url(a)}');

module.exports = Scanner;
<commit_msg>reduce offsetAndType reads (~33%)<commit_after>'use strict';

var CssSyntaxError = require('./error');
var TokenType = require('./const').TokenType;
var TokenName = require('./const').TokenName;
var IS_PUNCTUATOR = require('./const').IS_PUNCTUATOR;
var SYMBOL_CATEGORY = require('./const').SYMBOL_CATEGORY;
var SYMBOL_CATEGORY_LENGTH = SYMBOL_CATEGORY.length;
var cmpStr = require('./utils').cmpStr;
var isHex = require('./utils').isHex;

var NULL = 0;
var WHITESPACE = TokenType.Whitespace;
var IDENTIFIER = TokenType.Identifier;
var NUMBER = TokenType.DecimalNumber;
var STRING = TokenType.String;
var COMMENT = TokenType.Comment;
var PUNCTUATOR = TokenType.Punctuator;

var TAB = 9;
var N = 10;
var F = 12;
var R = 13;
var SPACE = 32;
var STAR = 42;
var SLASH = 47;
var BACK_SLASH = 92;

var MIN_ARRAY_SIZE = 16 * 1024;
var OFFSET_MASK = 0x00FFFFFF;
var lastIndexOf = Array.prototype.lastIndexOf; // some browser implementations have no TypedArray#lastIndexOf
var LongArray = typeof Uint32Array !== 'undefined' ? Uint32Array : Array;

var offsetAndType = null;
var lines = null;

function firstCharOffset(source) {
    return source.charCodeAt(0) === 0xFEFF ? 1 : 0;
}

function computeLines(scanner, source) {
    var sourceLength = source.length;
    var start = firstCharOffset(source);
    var line = scanner.initLine;

    if (lines === null || lines.length < sourceLength + 1) {
        lines = new LongArray(Math.max(sourceLength + 1024, MIN_ARRAY_SIZE));
    }

    for (var i = start; i < sourceLength; i++) {
        var code = source.charCodeAt(i);

        lines[i] = line;

        if (code === N || code === R || code === F) {
            if (code === R && i + 1 < sourceLength && source.charCodeAt(i + 1) === N) {
                i++;
                lines[i] = line;
            }
            line++;
        }
    }

    lines[i] = line;

    return lines;
}

function isNewline(source, offset, code) {
    if (code === N || code === F || code === R) {
        if (code === R && offset + 1 < source.length && source.charCodeAt(offset + 1) === N) {
            return 2;
        }

        return 1;
    }

    return 0;
}

function findWhitespaceEnd(source, offset) {
    for (; offset < source.length; offset++) {
        var code = source.charCodeAt(offset);

        if (code !== SPACE && code !== TAB && code !== R && code !== N && code !== F) {
            break;
        }
    }

    return offset;
}

function findCommentEnd(source, offset) {
    var commentEnd = source.indexOf('*/', offset);

    if (commentEnd === -1) {
        return source.length;
    }

    return commentEnd + 2;
}

function findStringEnd(source, offset, quote) {
    for (; offset < source.length; offset++) {
        var code = source.charCodeAt(offset);

        // TODO: bad string
        if (code === BACK_SLASH) {
            offset++;
        } else if (code === quote) {
            offset++;
            break;
        }
    }

    return offset;
}

function findDecimalNumberEnd(source, offset) {
    for (; offset < source.length; offset++) {
        var code = source.charCodeAt(offset);

        if (code < 48 || code > 57) {  // not a 0 .. 9
            break;
        }
    }

    return offset;
}

// skip escaped unicode sequence that can ends with space
// [0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
function findEscaseEnd(source, offset) {
    for (var i = 0; i < 7 && offset + i < source.length; i++) {
        var code = source.charCodeAt(offset + i);

        if (i !== 6 && isHex(code)) {
            continue;
        }

        if (i > 0) {
            offset += i - 1 + isNewline(source, offset + i, code);
            if (code === SPACE || code === TAB) {
                offset++;
            }
        }

        break;
    }

    return offset;
}

function findIdentifierEnd(source, offset) {
    for (; offset < source.length; offset++) {
        var code = source.charCodeAt(offset);

        if (code === BACK_SLASH) {
            offset = findEscaseEnd(source, offset + 1);
        } else if (code < SYMBOL_CATEGORY_LENGTH && IS_PUNCTUATOR[code] === PUNCTUATOR) {
            break;
        }
    }

    return offset;
}

function tokenLayout(scanner, source, startPos) {
    var sourceLength = source.length;
    var tokenCount = 0;
    var prevType = 0;
    var start = startPos;
    var end;

    if (offsetAndType === null || offsetAndType.length < sourceLength + 1) {
        offsetAndType = new LongArray(Math.max(sourceLength + 1024, MIN_ARRAY_SIZE));
    }

    while (start < sourceLength) {
        var code = source.charCodeAt(start);
        var type = code < SYMBOL_CATEGORY_LENGTH ? SYMBOL_CATEGORY[code] : IDENTIFIER;

        switch (type) {
            case WHITESPACE:
                end = findWhitespaceEnd(source, start + 1);
                break;

            case PUNCTUATOR:
                if (code === STAR && prevType === SLASH) { // /*
                    type = COMMENT;
                    end = findCommentEnd(source, start + 1);

                    // rewrite prevType token
                    tokenCount--;
                    prevType = offsetAndType[tokenCount] >> 24;
                    start--;
                } else {
                    type = code;
                    end = start + 1;
                }

                break;

            case NUMBER:
                end = findDecimalNumberEnd(source, start + 1);
                break;

            case STRING:
                end = findStringEnd(source, start + 1, code);
                break;

            default:
                end = findIdentifierEnd(source, start);
        }

        // console.log(type, scanner.source.substring(start, end));
        offsetAndType[tokenCount] = (prevType << 24) | start;

        tokenCount++;
        start = end;
        prevType = type;
    }

    offsetAndType[tokenCount] = (prevType << 24) | end;

    scanner.offsetAndType = offsetAndType;
    scanner.tokenCount = tokenCount;
}

//
// scanner
//

var Scanner = function(source, initLine, initColumn) {
    var start = firstCharOffset(source);

    this.source = source;
    this.initLine = typeof initLine === 'undefined' ? 1 : initLine;
    this.initColumn = (typeof initColumn === 'undefined' ? 1 : initColumn) - start;
    this.lastLocationLine = this.initLine;
    this.lastLocationLineOffset = 1 - this.initColumn;
    this.lines = null;

    this.eof = false;
    this.currentToken = -1;
    this.tokenType = 0;
    this.tokenStart = start;
    this.tokenEnd = start;

    tokenLayout(this, source, start);
    this.next();
};

Scanner.prototype = {
    lookupType: function(offset) {
        offset += this.currentToken;

        if (offset < this.tokenCount) {
            return this.offsetAndType[offset + 1] >> 24;
        }

        return 0;
    },
    lookupValue: function(offset, referenceStr) {
        offset += this.currentToken;

        if (offset < this.tokenCount) {
            return cmpStr(
                this.source,
                this.offsetAndType[offset] & OFFSET_MASK,
                this.offsetAndType[offset + 1] & OFFSET_MASK,
                referenceStr
            );
        }

        return false;
    },

    getTokenValue: function() {
        return this.source.substring(this.tokenStart, this.tokenEnd);
    },
    substrToCursor: function(start) {
        return this.source.substring(start, this.tokenStart);
    },

    skip: function(tokenCount) {
        if (tokenCount === 1) {
            this.next();
            return;
        }

        var next = this.currentToken + tokenCount;

        if (next < this.tokenCount) {
            this.currentToken = next;
            this.tokenStart = this.offsetAndType[next] & OFFSET_MASK;
            next = this.offsetAndType[next + 1];
            this.tokenType = next >> 24;
            this.tokenEnd = next & OFFSET_MASK;
        } else {
            this.currentToken = this.tokenCount;
            this.eof = true;
            this.tokenType = NULL;
            this.tokenStart = this.tokenEnd = this.source.length;
        }
    },
    next: function() {
        var next = this.currentToken + 1;

        if (next < this.tokenCount) {
            this.currentToken = next;
            this.tokenStart = this.tokenEnd;
            next = this.offsetAndType[next + 1];
            this.tokenType = next >> 24;
            this.tokenEnd = next & OFFSET_MASK;
        } else {
            this.currentToken = this.tokenCount;
            this.eof = true;
            this.tokenType = NULL;
            this.tokenStart = this.tokenEnd = this.source.length;
        }
    },

    eat: function(tokenType) {
        if (this.tokenType === tokenType) {
            this.next();
            return true;
        }

        this.error(TokenName[tokenType] + ' is expected');
    },
    expectIdentifier: function(name) {
        if (this.tokenType === IDENTIFIER && cmpStr(this.source, this.tokenStart, this.tokenEnd, name)) {
            this.next();
            return true;
        }

        this.error('Identifier `' + name + '` is expected');
    },

    getLocation: function(offset, source) {
        if (this.lines === null) {
            this.lines = computeLines(this, this.source);
        }

        var line = this.lines[offset];
        var column = offset;
        var lineOffset;

        if (line === this.initLine) {
            column += this.initColumn;
        } else {
            // try get precomputed line offset
            if (line === this.lastLocationLine) {
                lineOffset = this.lastLocationLineOffset;
            } else {
                // try avoid to compute line offset since it's expensive for long lines
                lineOffset = lastIndexOf.call(this.lines, line - 1, offset);
                this.lastLocationLine = line;
                this.lastLocationLineOffset = lineOffset;
            }

            column -= lineOffset;
        }

        return {
            source: source,
            offset: offset,
            line: line,
            column: column
        };
    },
    findLastNonSpaceLocation: function() {
        for (var i = (this.offsetAndType[this.currentToken] & OFFSET_MASK) - 1; i >= 0; i--) {
            var code = this.source.charCodeAt(i);

            if (code !== SPACE && code !== TAB && code !== R && code !== N && code !== F) {
                break;
            }
        }

        return this.getLocation(i + 1);
    },

    error: function(message, offset) {
        var location = !this.eof
            ? this.getLocation(typeof offset !== 'undefined' ? offset : this.tokenStart)
            : this.findLastNonSpaceLocation();

        throw new CssSyntaxError(
            message,
            this.source,
            location.offset,
            location.line,
            location.column
        );
    }
};

// warm up tokenizer to elimitate code branches that never execute
// fix soft deoptimizations (insufficient type feedback)
new Scanner('\n\r\r\n\f//""\'\'/*\r\n\f*/1a;.\\31\t\+2{url(a)}');

module.exports = Scanner;
<|endoftext|>


<commit_before>//!REMEMBER! the husky took the name of man and the man took the name of husky REMEMBER!!!!
var Aquaplane = {};

Aquaplane.Preloader = function () {};

Aquaplane.Preloader.prototype = {

    init: function () {

        this.input.maxPointers = 1;

        this.scale.pageAlignHorizontally = true;

    },

    preload: function () {

        this.load.path = 'assets/';

        this.load.bitmapFont('fat-and-tiny');
        this.load.bitmapFont('interfont');

        this.load.images([ 'logo']);
        this.load.spritesheet('town', 'town1.png', 700, 700, 22);
        this.load.spritesheet('crack', 'crack.png', 16, 6);
        this.load.spritesheet('husky', 'man.png', 92, 92);
        this.load.spritesheet('man', 'husky.png', 96, 96);
        this.load.spritesheet('zombie', 'zombie.png', 96, 96);
         this.load.spritesheet('zomkabob', 'zomkabob.png', 96, 96);
          this.load.spritesheet('hand', 'hand.png', 32, 32);
    },

    create: function () {

        this.state.start('Aquaplane.MainMenu');

    }

};

Aquaplane.MainMenu = function () {};

Aquaplane.MainMenu.prototype = {

    create: function () {

        var town = game.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        var logo = this.add.image( this.world.centerX, 20, 'logo');
        logo.anchor.x = 0.5;

        var start = this.add.bitmapText(this.world.centerX, 460, 'fat-and-tiny', 'CLICK TO PLAY', 64);
        start.anchor.x = 0.5;
        start.smoothed = false;
        start.tint = 0x990000;

        this.input.onDown.addOnce(this.start, this);

    },

    start: function () {

        this.state.start('Aquaplane.Game');

    }

};

Aquaplane.Game = function (game) {

    this.score = 0;
    this.scoreText = null;

    this.lives = 3;
    this.livesText = null;

    this.speed = 420;
    this.lastKey = 0;
    this.ready = false;

    this.layer = null;
    this.itemDist = ['zomkabob', 'zomkabob', 'zomkabob', 'hand', 'hand', 'hand', 'zombie'];

    this.man = null;
    this.husky = null;
    this.rope = null;

    this.timer = null;
    this.itemInterval = { count: 0, min: 500, max: 1500 };

    this.pauseKey = null;
    this.debugKey = null;
    this.showDebug = false;

};

Aquaplane.Game.prototype = {

    init: function () {

        this.score = 0;
        this.lives = 3;
        this.speed = 420;

        this.ready = false;
        this.lastKey = 0;

        this.timer = this.time.create(false);
        this.itemInterval = { count: 0, min: 500, max: 1500 };

        this.physics.startSystem(Phaser.Physics.P2JS);
        this.physics.p2.gravity.y = 0;

        this.showDebug = false;

    },

    create: function () {

        var town = game.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        this.waterParticle = this.make.bitmapData(2, 2);
        this.waterParticle.rect(0, 0, 2, 2, '#ffffff');
        this.waterParticle.update();

        this.emitter = this.add.emitter(128, 128, 128);
        this.emitter.makeParticles(this.waterParticle);

        this.emitter.gravity = 0;
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);

        this.emitter.setAlpha(1, 0.2, 500);

        this.emitter.flow(500, 20, 2, -1, true);

        this.layer = this.add.group();

        this.man = this.layer.create(0, 0, 'man');
        var man = game.add.sprite(-100, -100, 'man');
        var walk = man.animations.add('walk');
            man.animations.play('walk', 12, true)

        this.physics.p2.enable(this.man, false);

        this.man.body.mass = 0.5;
        this.man.body.damping = 0.01;
        this.man.body.fixedRotation = true;
        this.man.body.collideWorldBounds = false;

        this.husky = this.layer.create(0, 0, 'husky');
        var husky = game.add.sprite(0, 0, 'husky');
        var run = husky.animations.add('run');
        husky.animations.play('run', 12, true);

        this.physics.p2.enable(this.husky, false);

        this.husky.body.mass = 0.05;
        this.husky.body.damping = 0.01;
        this.husky.body.fixedRotation = true;
        this.husky.body.collideWorldBounds = false;

        this.manBounds = new Phaser.Rectangle(0, 0, 23, 23);
        this.huskyBounds = new Phaser.Rectangle(0, 0, 24, 24);

        var rev = new p2.RevoluteConstraint(this.man.body.data, this.husky.body.data, {
                localPivotA: [9, 0],
                localPivotB: [2, 0],
                collideConnected: false
            });

        this.physics.p2.world.addConstraint(rev);

        rev.setLimits(this.math.degToRad(-40), this.math.degToRad(40));

        rev.setStiffness(2.0);

        //  Let's create some cracks (harmless eye candy)
        //
        //  Divide screen vertically into 520px / 8 layers = 65px per layer
        //  Place 8 cracks per layer (8*8 total)

        var area = new Phaser.Rectangle(0, 70, this.game.width, 45);

        for (var i = 1; i <= 7; i++)
        {
            for (var w = 0; w < 7; w++)
            {
                var crack = this.layer.create(area.randomX, area.randomY, 'crack', this.rnd.between(0, 2));
                'crack'.anchor.y = -1.5;
                this.physics.arcade.enable(crack);
                crack.body.velocity.x = -120 + (i * -30);
            }

            area.y += 45;
        }

        this.line = new Phaser.Line(this.man.x - 28, this.man.y, this.husky.x + 6, this.husky.y - 1);

        //  The rope that attaches the husky to the man
        this.rope = this.add.graphics(0, 0);

        this.scoreText = this.add.bitmapText(16, 0, 'fat-and-tiny', 'SCORE: 0', 32);
        this.scoreText.smoothed = false;

        this.livesText = this.add.bitmapText(580, 0, 'fat-and-tiny', 'LIVES: ' + this.lives, 32);
        this.livesText.smoothed = false;

        this.cursors = this.input.keyboard.createCursorKeys();

        //  Press P to pause and resume the game
        this.pauseKey = this.input.keyboard.addKey(Phaser.Keyboard.P);
        this.pauseKey.onDown.add(this.togglePause, this);

        //  Press D to toggle the debug display
        this.debugKey = this.input.keyboard.addKey(Phaser.Keyboard.D);
        this.debugKey.onDown.add(this.toggleDebug, this);

        this.bringManOn();

    },

    togglePause: function () {

        this.game.paused = (this.game.paused) ? false : true;

    },

    toggleDebug: function () {

        this.showDebug = (this.showDebug) ? false : true;

    },

    bringManOn: function () {

        this.ready = false;

        this.man.body.x = -64;
        this.man.body.y = 300;

        this.husky.visible = true;
        this.husky.body.x = -264;
        this.husky.body.y = 300;

        this.husky.body.velocity.x = 300;

    },

    manReady: function () {

        this.ready = true;

        this.man.body.setZeroVelocity();

        this.timer.add(this.itemInterval.max, this.releaseItem, this);
        this.timer.start();

    },

    releaseItem: function (x, y) {

        if (x === undefined) { x = 700; }
        if (y === undefined) { y = this.rnd.between(80, 487); }

        var frame = this.rnd.pick(this.itemDist);

        var item = this.layer.getFirstDead(true, x, y, frame);

        this.physics.arcade.enable(item);

        if (frame === 'zombie')
        {
            item.body.setSize(32, 14, 0, 16);
        }
        else
        {
            item.body.setSize(16, 8, 0, 24);
        }

        var i = this.math.snapToFloor(y, 65) / 65;

        item.body.velocity.x = -120 + (i * -30);

        this.itemInterval.count++;

        //  Every 10 new items we'll speed things up a bit
        if (this.itemInterval.min > 100 && this.itemInterval.count % 10 === 0)
        {
            this.itemInterval.min -= 10;
            this.itemInterval.max -= 10;
        }

        //  Is the player idle? Then release another item directly towards them
        if ((this.time.time - this.lastKey) > 200)
        {
            this.lastKey = this.time.time;
            this.releaseItem(700, this.husky.y - 16);
        }
        else
        {
            this.timer.add(this.rnd.between(this.itemInterval.min, this.itemInterval.max), this.releaseItem, this);
        }

    },

    update: function () {

        this.layer.sort('y', Phaser.Group.SORT_ASCENDING);

        if (this.ready)
        {
            this.updateMan();

            //  Score based on their position on the screen
            this.score += (this.math.snapToFloor(this.husky.y, 65) / 65);
            this.scoreText.text = "SCORE: " + this.score;
        }
        else
        {
            if (this.husky.visible)
            {
                if (this.man.x >= 250)
                {
                    this.manReady();
                }
            }
            else
            {
                if (this.man.x >= 832)
                {
                    this.bringManOn();
                }
            }
        }

        this.manBounds.centerOn(this.man.x + 4, this.man.y + 8);
        this.huskyBounds.centerOn(this.husky.x + 2, this.husky.y + 10);

        this.emitter.emitX = this.man.x - 16;
        this.emitter.emitY = this.man.y + 10;

        //  Let's sort and collide
        this.layer.forEachAlive(this.checkItem, this);

    },

    updateMan: function () {

        if (this.man.x < 200)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 200;
        }
        else if (this.man.x > 650)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 650;
        }

        if (this.man.y < 100)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 100;
        }
        else if (this.man.y > 550)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 550;
        }

        if (this.cursors.left.isDown)
        {
            this.man.body.force.x = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.right.isDown)
        {
            this.man.body.force.x = this.speed;
            this.lastKey = this.time.time;
        }

        if (this.cursors.up.isDown)
        {
            this.man.body.force.y = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.down.isDown)
        {
            this.man.body.force.y = this.speed;
            this.lastKey = this.time.time;
        }

    },

    checkItem: function (item) {

        if (item === this.man || item === this.husky)
        {
            return;
        }

        if (item.x < -32)
        {
            if (item.key === 'crack')
            {
                item.x = this.rnd.between(700, 764);
            }
            else
            {
                item.kill();
            }
        }
        else
        {
            //   Check for collision
            if (this.ready && item.key !== 'crack' && this.huskyBounds.intersects(item.body))
            {
                this.loseLife();
            }
        }

    },

    loseLife: function () {

        if (this.lives === 0)
        {
            this.gameOver();
        }
        else
        {
            this.lives--;

            this.livesText.text = "LIVES: " + this.lives;

            this.ready = false;

            //  Kill the dog!
            this.husky.visible = false;

            //  Hide the rope
            this.rope.clear();

            //  Speed the man away
            this.man.body.setZeroVelocity();
            this.man.body.velocity.x = 600;

            this.itemInterval.min += 200;
            this.itemInterval.max += 200;
        }

    },

    gameOver: function () {

        this.state.start('Aquaplane.MainMenu');

    },

    preRender: function () {

        this.line.setTo(this.man.x - 48, this.man.y, this.husky.x + 46, this.husky.y - 1);

        if (this.husky.visible)
        {
            this.rope.clear();
        }

    },

    render: function () {

        if (this.showDebug)
        {
            this.game.debug.geom(this.manBounds);
            this.game.debug.geom(this.huskyBounds);
            this.layer.forEachAlive(this.renderBody, this);
            this.game.debug.geom(this.husky.position, 'rgba(255,255,0,1)');
        }

    },

    renderBody: function (sprite) {

        if (sprite === this.man || sprite === this.husky || sprite.key === 'crack')
        {
            return;
        }

        this.game.debug.body(sprite);

    }

};

var game = new Phaser.Game(700, 525, Phaser.AUTO, 'game');

game.state.add('Aquaplane.Preloader', Aquaplane.Preloader);
game.state.add('Aquaplane.MainMenu', Aquaplane.MainMenu);
game.state.add('Aquaplane.Game', Aquaplane.Game);

game.state.start('Aquaplane.Preloader');
<commit_msg>Create game.js<commit_after>//!REMEMBER! the husky took the name of man and the man took the name of husky REMEMBER!!!!
var Aquaplane = {};

Aquaplane.Preloader = function () {};

Aquaplane.Preloader.prototype = {

    init: function () {

        this.input.maxPointers = 1;

        this.scale.pageAlignHorizontally = true;

    },

    preload: function () {

        this.load.path = 'assets/';

        this.load.bitmapFont('fat-and-tiny');
        this.load.bitmapFont('interfont');

        this.load.images([ 'logo']);
        this.load.spritesheet('town', 'town1.png', 700, 700, 22);
        this.load.spritesheet('crack', 'crack.png', 16, 6);
        this.load.spritesheet('husky', 'man.png', 92, 92);
        this.load.spritesheet('man', 'husky.png', 96, 96);
        this.load.spritesheet('zombie', 'zombie.png', 96, 96);
         this.load.spritesheet('zomkabob', 'zomkabob.png', 96, 96);
          this.load.spritesheet('hand', 'hand.png', 32, 32);
    },

    create: function () {

        this.state.start('Aquaplane.MainMenu');

    }

};

Aquaplane.MainMenu = function () {};

Aquaplane.MainMenu.prototype = {

    create: function () {

        var town = game.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        var logo = this.add.image( this.world.centerX, 20, 'logo');
        logo.anchor.x = 0.5;

        var start = this.add.bitmapText(this.world.centerX, 460, 'fat-and-tiny', 'CLICK TO PLAY', 64);
        start.anchor.x = 0.5;
        start.smoothed = false;
        start.tint = 0x990000;

        this.input.onDown.addOnce(this.start, this);

    },

    start: function () {

        this.state.start('Aquaplane.Game');

    }

};

Aquaplane.Game = function (game) {

    this.score = 0;
    this.scoreText = null;

    this.lives = 3;
    this.livesText = null;

    this.speed = 420;
    this.lastKey = 0;
    this.ready = false;

    this.layer = null;
    this.itemDist = ['zomkabob', 'zomkabob', 'zomkabob', 'hand', 'hand', 'hand', 'zombie'];

    this.man = null;
    this.husky = null;
    this.rope = null;

    this.timer = null;
    this.itemInterval = { count: 0, min: 500, max: 1500 };

    this.pauseKey = null;
    this.debugKey = null;
    this.showDebug = false;

};

Aquaplane.Game.prototype = {

    init: function () {

        this.score = 0;
        this.lives = 3;
        this.speed = 420;

        this.ready = false;
        this.lastKey = 0;

        this.timer = this.time.create(false);
        this.itemInterval = { count: 0, min: 500, max: 1500 };

        this.physics.startSystem(Phaser.Physics.P2JS);
        this.physics.p2.gravity.y = 0;

        this.showDebug = false;

    },

    create: function () {

        var town = game.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        this.waterParticle = this.make.bitmapData(2, 2);
        this.waterParticle.rect(0, 0, 2, 2, '#ffffff');
        this.waterParticle.update();

        this.emitter = this.add.emitter(128, 128, 128);
        this.emitter.makeParticles(this.waterParticle);

        this.emitter.gravity = 0;
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);

        this.emitter.setAlpha(1, 0.2, 500);

        this.emitter.flow(500, 20, 2, -1, true);

        this.layer = this.add.group();

        this.man = this.layer.create(0, 0, 'man');
        var man = game.add.sprite(x, y, 'man');
        var walk = man.animations.add('walk');
            man.animations.play('walk', 12, true)

        this.physics.p2.enable(this.man, false);

        this.man.body.mass = 0.5;
        this.man.body.damping = 0.01;
        this.man.body.fixedRotation = true;
        this.man.body.collideWorldBounds = false;

        this.husky = this.layer.create(0, 0, 'husky');
        var husky = game.add.sprite(0, 0, 'husky');
        var run = husky.animations.add('run');
        husky.animations.play('run', 12, true);

        this.physics.p2.enable(this.husky, false);

        this.husky.body.mass = 0.05;
        this.husky.body.damping = 0.01;
        this.husky.body.fixedRotation = true;
        this.husky.body.collideWorldBounds = false;

        this.manBounds = new Phaser.Rectangle(0, 0, 23, 23);
        this.huskyBounds = new Phaser.Rectangle(0, 0, 24, 24);

        var rev = new p2.RevoluteConstraint(this.man.body.data, this.husky.body.data, {
                localPivotA: [9, 0],
                localPivotB: [2, 0],
                collideConnected: false
            });

        this.physics.p2.world.addConstraint(rev);

        rev.setLimits(this.math.degToRad(-40), this.math.degToRad(40));

        rev.setStiffness(2.0);

        //  Let's create some cracks (harmless eye candy)
        //
        //  Divide screen vertically into 520px / 8 layers = 65px per layer
        //  Place 8 cracks per layer (8*8 total)

        var area = new Phaser.Rectangle(0, 70, this.game.width, 45);

        for (var i = 1; i <= 7; i++)
        {
            for (var w = 0; w < 7; w++)
            {
                var crack = this.layer.create(area.randomX, area.randomY, 'crack', this.rnd.between(0, 2));
                'crack'.anchor.y = -1.5;
                this.physics.arcade.enable(crack);
                crack.body.velocity.x = -120 + (i * -30);
            }

            area.y += 45;
        }

        this.line = new Phaser.Line(this.man.x - 28, this.man.y, this.husky.x + 6, this.husky.y - 1);

        //  The rope that attaches the husky to the man
        this.rope = this.add.graphics(0, 0);

        this.scoreText = this.add.bitmapText(16, 0, 'fat-and-tiny', 'SCORE: 0', 32);
        this.scoreText.smoothed = false;

        this.livesText = this.add.bitmapText(580, 0, 'fat-and-tiny', 'LIVES: ' + this.lives, 32);
        this.livesText.smoothed = false;

        this.cursors = this.input.keyboard.createCursorKeys();

        //  Press P to pause and resume the game
        this.pauseKey = this.input.keyboard.addKey(Phaser.Keyboard.P);
        this.pauseKey.onDown.add(this.togglePause, this);

        //  Press D to toggle the debug display
        this.debugKey = this.input.keyboard.addKey(Phaser.Keyboard.D);
        this.debugKey.onDown.add(this.toggleDebug, this);

        this.bringManOn();

    },

    togglePause: function () {

        this.game.paused = (this.game.paused) ? false : true;

    },

    toggleDebug: function () {

        this.showDebug = (this.showDebug) ? false : true;

    },

    bringManOn: function () {

        this.ready = false;

        this.man.body.x = -64;
        this.man.body.y = 300;

        this.husky.visible = true;
        this.husky.body.x = -264;
        this.husky.body.y = 300;

        this.husky.body.velocity.x = 300;

    },

    manReady: function () {

        this.ready = true;

        this.man.body.setZeroVelocity();

        this.timer.add(this.itemInterval.max, this.releaseItem, this);
        this.timer.start();

    },

    releaseItem: function (x, y) {

        if (x === undefined) { x = 700; }
        if (y === undefined) { y = this.rnd.between(80, 487); }

        var frame = this.rnd.pick(this.itemDist);

        var item = this.layer.getFirstDead(true, x, y, frame);

        this.physics.arcade.enable(item);

        if (frame === 'zombie')
        {
            item.body.setSize(32, 14, 0, 16);
        }
        else
        {
            item.body.setSize(16, 8, 0, 24);
        }

        var i = this.math.snapToFloor(y, 65) / 65;

        item.body.velocity.x = -120 + (i * -30);

        this.itemInterval.count++;

        //  Every 10 new items we'll speed things up a bit
        if (this.itemInterval.min > 100 && this.itemInterval.count % 10 === 0)
        {
            this.itemInterval.min -= 10;
            this.itemInterval.max -= 10;
        }

        //  Is the player idle? Then release another item directly towards them
        if ((this.time.time - this.lastKey) > 200)
        {
            this.lastKey = this.time.time;
            this.releaseItem(700, this.husky.y - 16);
        }
        else
        {
            this.timer.add(this.rnd.between(this.itemInterval.min, this.itemInterval.max), this.releaseItem, this);
        }

    },

    update: function () {

        this.layer.sort('y', Phaser.Group.SORT_ASCENDING);

        if (this.ready)
        {
            this.updateMan();

            //  Score based on their position on the screen
            this.score += (this.math.snapToFloor(this.husky.y, 65) / 65);
            this.scoreText.text = "SCORE: " + this.score;
        }
        else
        {
            if (this.husky.visible)
            {
                if (this.man.x >= 250)
                {
                    this.manReady();
                }
            }
            else
            {
                if (this.man.x >= 832)
                {
                    this.bringManOn();
                }
            }
        }

        this.manBounds.centerOn(this.man.x + 4, this.man.y + 8);
        this.huskyBounds.centerOn(this.husky.x + 2, this.husky.y + 10);

        this.emitter.emitX = this.man.x - 16;
        this.emitter.emitY = this.man.y + 10;

        //  Let's sort and collide
        this.layer.forEachAlive(this.checkItem, this);

    },

    updateMan: function () {

        if (this.man.x < 200)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 200;
        }
        else if (this.man.x > 650)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 650;
        }

        if (this.man.y < 100)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 100;
        }
        else if (this.man.y > 550)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 550;
        }

        if (this.cursors.left.isDown)
        {
            this.man.body.force.x = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.right.isDown)
        {
            this.man.body.force.x = this.speed;
            this.lastKey = this.time.time;
        }

        if (this.cursors.up.isDown)
        {
            this.man.body.force.y = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.down.isDown)
        {
            this.man.body.force.y = this.speed;
            this.lastKey = this.time.time;
        }

    },

    checkItem: function (item) {

        if (item === this.man || item === this.husky)
        {
            return;
        }

        if (item.x < -32)
        {
            if (item.key === 'crack')
            {
                item.x = this.rnd.between(700, 764);
            }
            else
            {
                item.kill();
            }
        }
        else
        {
            //   Check for collision
            if (this.ready && item.key !== 'crack' && this.huskyBounds.intersects(item.body))
            {
                this.loseLife();
            }
        }

    },

    loseLife: function () {

        if (this.lives === 0)
        {
            this.gameOver();
        }
        else
        {
            this.lives--;

            this.livesText.text = "LIVES: " + this.lives;

            this.ready = false;

            //  Kill the dog!
            this.husky.visible = false;

            //  Hide the rope
            this.rope.clear();

            //  Speed the man away
            this.man.body.setZeroVelocity();
            this.man.body.velocity.x = 600;

            this.itemInterval.min += 200;
            this.itemInterval.max += 200;
        }

    },

    gameOver: function () {

        this.state.start('Aquaplane.MainMenu');

    },

    preRender: function () {

        this.line.setTo(this.man.x - 48, this.man.y, this.husky.x + 46, this.husky.y - 1);

        if (this.husky.visible)
        {
            this.rope.clear();
        }

    },

    render: function () {

        if (this.showDebug)
        {
            this.game.debug.geom(this.manBounds);
            this.game.debug.geom(this.huskyBounds);
            this.layer.forEachAlive(this.renderBody, this);
            this.game.debug.geom(this.husky.position, 'rgba(255,255,0,1)');
        }

    },

    renderBody: function (sprite) {

        if (sprite === this.man || sprite === this.husky || sprite.key === 'crack')
        {
            return;
        }

        this.game.debug.body(sprite);

    }

};

var game = new Phaser.Game(700, 525, Phaser.AUTO, 'game');

game.state.add('Aquaplane.Preloader', Aquaplane.Preloader);
game.state.add('Aquaplane.MainMenu', Aquaplane.MainMenu);
game.state.add('Aquaplane.Game', Aquaplane.Game);

game.state.start('Aquaplane.Preloader');
<|endoftext|>