<commit_before>/*!
 * coins.js - coins object for bcoin
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
 * https://github.com/bcoin-org/bcoin
 */

'use strict';

var bcoin = require('./env');
var utils = bcoin.utils;
var assert = utils.assert;
var constants = bcoin.protocol.constants;
var BufferReader = require('./reader');
var BufferWriter = require('./writer');

/**
 * Represents the outputs for a single transaction.
 * @exports Coins
 * @constructor
 * @param {TX|Object} tx/options - TX or options object.
 * @property {Hash} hash - Transaction hash.
 * @property {Number} version - Transaction version.
 * @property {Number} height - Transaction height (-1 if unconfirmed).
 * @property {Boolean} coinbase - Whether the containing
 * transaction is a coinbase.
 * @property {Coin[]} outputs - Coins.
 */

function Coins(options) {
  if (!(this instanceof Coins))
    return new Coins(options);

  this.version = 1;
  this.hash = constants.NULL_HASH;
  this.height = -1;
  this.coinbase = true;
  this.outputs = [];

  if (options)
    this.fromOptions(options);
}

/**
 * Inject properties from options object.
 * @private
 * @param {Object} options
 */

Coins.prototype.fromOptions = function fromOptions(options) {
  if (options.version != null)
    this.version = options.version;

  if (options.hash)
    this.hash = options.hash;

  if (options.height != null)
    this.height = options.height;

  if (options.coinbase != null)
    this.coinbase = options.coinbase;

  if (options.outputs)
    this.outputs = options.outputs;

  return this;
};

/**
 * Instantiate coins from options object.
 * @param {Object} options
 * @returns {Coins}
 */

Coins.fromOptions = function fromOptions(options) {
  return new Coins().fromOptions(options);
};

/**
 * Add a single coin to the collection.
 * @param {Coin} coin
 */

Coins.prototype.add = function add(coin) {
  if (this.outputs.length === 0) {
    this.version = coin.version;
    this.hash = coin.hash;
    this.height = coin.height;
    this.coinbase = coin.coinbase;
  }

  while (this.outputs.length <= coin.index)
    this.outputs.push(null);

  if (coin.script.isUnspendable()) {
    this.outputs[coin.index] = null;
    return;
  }

  this.outputs[coin.index] = coin;
};

/**
 * Test whether the collection has a coin.
 * @param {Number} index
 * @returns {Boolean}
 */

Coins.prototype.has = function has(index) {
  return this.outputs[index] != null;
};

/**
 * Get a coin.
 * @param {Number} index
 * @returns {Coin}
 */

Coins.prototype.get = function get(index) {
  var coin = this.outputs[index];
  if (!coin)
    return;

  if (coin instanceof CompressedCoin)
    coin = coin.toCoin(this, index);

  return coin;
};

/**
 * Count unspent coins.
 * @returns {Number}
 */

Coins.prototype.count = function count(index) {
  var total = 0;
  var i;

  for (i = 0; i < this.outputs.length; i++) {
    if (this.outputs[i])
      total++;
  }

  return total;
};

/**
 * Remove a coin and return it.
 * @param {Number} index
 * @returns {Coin}
 */

Coins.prototype.spend = function spend(index) {
  var coin = this.get(index);
  this.outputs[index] = null;
  return coin;
};

/**
 * Count up to the last available index.
 * @returns {Number}
 */

Coins.prototype.getLength = function getLength() {
  var last = -1;
  var i;

  for (i = 0; i < this.outputs.length; i++) {
    if (this.outputs[i])
      last = i;
  }

  return last + 1;
};

/*
 * Coins serialization:
 * version: varint
 * bits: varint ((height << 1) | coinbase-flag)
 * outputs (repeated):
 *   prefix: 0xff = spent
 *           0x00 = varint size | raw script
 *           0x01 = 20 byte pubkey hash
 *           0x02 = 20 byte script hash
 *           0x03 = 33 byte compressed key
 *   data: the data mentioned above
 *   value: varint
 */

/**
 * Serialize the coins object.
 * @param {TX|Coins} tx
 * @returns {Buffer}
 */

Coins.prototype.toRaw = function toRaw(writer) {
  var p = new BufferWriter(writer);
  var height = this.height;
  var length = this.getLength();
  var i, output, prefix, data, bits;

  // Unfortunately, we don't have a compact
  // way to store unconfirmed height.
  if (height === -1)
    height = 0x7fffffff;

  bits = height << 1;

  if (this.coinbase)
    bits |= 1;

  if (bits < 0)
    bits += 0x100000000;

  p.writeVarint(this.version);
  p.writeVarint(bits);

  for (i = 0; i < length; i++) {
    output = this.outputs[i];

    if (!output) {
      p.writeU8(0xff);
      continue;
    }

    if (output instanceof CompressedCoin) {
      p.writeBytes(output.toRaw());
      continue;
    }

    prefix = 0;

    // Attempt to compress the output scripts.
    // We can _only_ ever compress them if
    // they are serialized as minimaldata, as
    // we need to recreate them when we read
    // them.
    if (output.script.isPubkeyhash(true)) {
      prefix = 1;
      data = output.script.code[2].data;
    } else if (output.script.isScripthash()) {
      prefix = 2;
      data = output.script.code[1].data;
    } else if (output.script.isPubkey(true)) {
      prefix = 3;
      data = output.script.code[0].data;

      // Try to compress the key.
      data = bcoin.ec.compress(data);

      // If we can't compress it,
      // just store the script.
      if (!data)
        prefix = 0;
    }

    p.writeU8(prefix);

    if (prefix === 0)
      p.writeVarBytes(output.script.toRaw());
    else
      p.writeBytes(data);

    p.writeVarint(output.value);
  }

  if (!writer)
    p = p.render();

  return p;
};

/**
 * Parse serialized coins.
 * @param {Buffer} data
 * @param {Hash} hash
 * @returns {Object} A "naked" coins object.
 */

Coins.prototype.fromRaw = function fromRaw(data, hash, index) {
  var p = new BufferReader(data);
  var i = 0;
  var bits, coin, prefix, offset, size;

  this.version = p.readVarint();

  bits = p.readVarint();

  this.height = bits >>> 1;
  this.hash = hash;
  this.coinbase = (bits & 1) !== 0;

  if (this.height === 0x7fffffff)
    this.height = -1;

  while (p.left()) {
    offset = p.start();
    prefix = p.readU8();

    // Already spent.
    if (prefix === 0xff) {
      p.end();

      // Don't bother pushing outputs on if
      // we're seeking to a specific index.
      if (index != null) {
        if (i === index)
          return;
        i++;
        continue;
      }

      this.outputs.push(null);
      i++;
      continue;
    }

    // Skip past the compressed scripts.
    switch (prefix & 3) {
      case 0:
        p.seek(p.readVarint());
        break;
      case 1:
      case 2:
        p.seek(20);
        break;
      case 3:
        p.seek(33);
        break;
      default:
        assert(false, 'Bad prefix.');
    }

    // Skip past the value.
    p.readVarint();

    size = p.end();

    // Keep going if we're seeking
    // to a specific index.
    if (index != null && i !== index) {
      i++;
      continue;
    }

    // Store the offset and size
    // in the compressed coin object.
    coin = new CompressedCoin(offset, size, data);

    // We found our coin.
    if (index != null)
      return coin.toCoin(this, i);

    this.outputs.push(coin);
    i++;
  }

  // We couldn't find our coin.
  if (index != null)
    return;

  return this;
};

/**
 * Parse a single serialized coin.
 * @param {Buffer} data
 * @param {Hash} hash
 * @param {Number} index
 * @returns {Coin}
 */

Coins.parseCoin = function parseCoin(data, hash, index) {
  assert(index != null, 'Bad coin index.');
  return new Coins().fromRaw(data, hash, index);
};

/**
 * Instantiate coins from a serialized Buffer.
 * @param {Buffer} data
 * @param {Hash} hash - Transaction hash.
 * @returns {Coins}
 */

Coins.fromRaw = function fromRaw(data, hash) {
  return new Coins().fromRaw(data, hash);
};

/**
 * Inject properties from tx.
 * @private
 * @param {TX} tx
 */

Coins.prototype.fromTX = function fromTX(tx) {
  var i;

  this.version = tx.version;
  this.hash = tx.hash('hex');
  this.height = tx.height;
  this.coinbase = tx.isCoinbase();

  for (i = 0; i < tx.outputs.length; i++) {
    if (tx.outputs[i].script.isUnspendable()) {
      this.outputs.push(null);
      continue;
    }
    this.outputs.push(bcoin.coin.fromTX(tx, i));
  }

  return this;
};

/**
 * Instantiate a coins object from a transaction.
 * @param {TX} tx
 * @returns {Coins}
 */

Coins.fromTX = function fromTX(tx) {
  return new Coins().fromTX(tx);
};

/**
 * A compressed coin is an object which defers
 * parsing of a coin. Say there is a transaction
 * with 100 outputs. When a block comes in,
 * there may only be _one_ input in that entire
 * block which redeems an output from that
 * transaction. When parsing the Coins, there
 * is no sense to get _all_ of them into their
 * abstract form. A compressed coin is just a
 * pointer to that coin in the Coins buffer, as
 * well as a size. Parsing is done only if that
 * coin is being redeemed.
 * @constructor
 * @private
 * @param {Number} offset
 * @param {Number} size
 * @param {Buffer} raw
 */

function CompressedCoin(offset, size, raw) {
  if (!(this instanceof CompressedCoin))
    return new CompressedCoin(offset, size, raw);

  this.offset = offset;
  this.size = size;
  this.raw = raw;
}

/**
 * Parse the deferred data and return a Coin.
 * @param {Coins} coins
 * @param {Number} index
 * @returns {Coin}
 */

CompressedCoin.prototype.toCoin = function toCoin(coins, index) {
  var p = new BufferReader(this.raw);
  var coin = new bcoin.coin();
  var prefix, key;

  // Load in all necessary properties
  // from the parent Coins object.
  coin.version = coins.version;
  coin.coinbase = coins.coinbase;
  coin.height = coins.height;
  coin.hash = coins.hash;
  coin.index = index;

  // Seek to the coin's offset.
  p.seek(this.offset);

  prefix = p.readU8();

  // Decompress the script.
  switch (prefix & 3) {
    case 0:
      coin.script.fromRaw(p.readVarBytes());
      break;
    case 1:
      coin.script.fromPubkeyhash(p.readBytes(20));
      break;
    case 2:
      coin.script.fromScripthash(p.readBytes(20));
      break;
    case 3:
      // Decompress the key. If this fails,
      // we have database corruption!
      key = bcoin.ec.decompress(p.readBytes(33));
      coin.script.fromPubkey(key);
      break;
    default:
      assert(false, 'Bad prefix.');
  }

  coin.value = p.readVarint();

  return coin;
};

/**
 * Slice off the part of the buffer
 * relevant to this particular coin.
 * @returns {Buffer}
 */

CompressedCoin.prototype.toRaw = function toRaw() {
  return this.raw.slice(this.offset, this.offset + this.size);
};

/*
 * Expose
 */

module.exports = Coins;
<commit_msg>implement coin spent field.<commit_after>/*!
 * coins.js - coins object for bcoin
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
 * https://github.com/bcoin-org/bcoin
 */

'use strict';

var bcoin = require('./env');
var utils = bcoin.utils;
var assert = utils.assert;
var constants = bcoin.protocol.constants;
var BufferReader = require('./reader');
var BufferWriter = require('./writer');

/**
 * Represents the outputs for a single transaction.
 * @exports Coins
 * @constructor
 * @param {TX|Object} tx/options - TX or options object.
 * @property {Hash} hash - Transaction hash.
 * @property {Number} version - Transaction version.
 * @property {Number} height - Transaction height (-1 if unconfirmed).
 * @property {Boolean} coinbase - Whether the containing
 * transaction is a coinbase.
 * @property {Coin[]} outputs - Coins.
 */

function Coins(options) {
  if (!(this instanceof Coins))
    return new Coins(options);

  this.version = 1;
  this.hash = constants.NULL_HASH;
  this.height = -1;
  this.coinbase = true;
  this.outputs = [];

  if (options)
    this.fromOptions(options);
}

/**
 * Inject properties from options object.
 * @private
 * @param {Object} options
 */

Coins.prototype.fromOptions = function fromOptions(options) {
  if (options.version != null)
    this.version = options.version;

  if (options.hash)
    this.hash = options.hash;

  if (options.height != null)
    this.height = options.height;

  if (options.coinbase != null)
    this.coinbase = options.coinbase;

  if (options.outputs)
    this.outputs = options.outputs;

  return this;
};

/**
 * Instantiate coins from options object.
 * @param {Object} options
 * @returns {Coins}
 */

Coins.fromOptions = function fromOptions(options) {
  return new Coins().fromOptions(options);
};

/**
 * Add a single coin to the collection.
 * @param {Coin} coin
 */

Coins.prototype.add = function add(coin) {
  if (this.outputs.length === 0) {
    this.version = coin.version;
    this.hash = coin.hash;
    this.height = coin.height;
    this.coinbase = coin.coinbase;
  }

  while (this.outputs.length <= coin.index)
    this.outputs.push(null);

  if (coin.script.isUnspendable()) {
    this.outputs[coin.index] = null;
    return;
  }

  this.outputs[coin.index] = coin;
};

/**
 * Test whether the collection has a coin.
 * @param {Number} index
 * @returns {Boolean}
 */

Coins.prototype.has = function has(index) {
  return this.outputs[index] != null;
};

/**
 * Get a coin.
 * @param {Number} index
 * @returns {Coin}
 */

Coins.prototype.get = function get(index) {
  var coin = this.outputs[index];
  if (!coin)
    return;

  if (coin instanceof CompressedCoin)
    coin = coin.toCoin(this, index);

  return coin;
};

/**
 * Count unspent coins.
 * @returns {Number}
 */

Coins.prototype.count = function count(index) {
  var total = 0;
  var i;

  for (i = 0; i < this.outputs.length; i++) {
    if (this.outputs[i])
      total++;
  }

  return total;
};

/**
 * Remove a coin and return it.
 * @param {Number} index
 * @returns {Coin}
 */

Coins.prototype.spend = function spend(index) {
  var coin = this.get(index);
  this.outputs[index] = null;
  return coin;
};

/**
 * Count up to the last available index.
 * @returns {Number}
 */

Coins.prototype.getLength = function getLength() {
  var last = -1;
  var i;

  for (i = 0; i < this.outputs.length; i++) {
    if (this.outputs[i])
      last = i;
  }

  return last + 1;
};

/*
 * Coins serialization:
 * version: varint
 * bits: varint ((height << 1) | coinbase-flag)
 * spent-field: varint size | bitmap (0=unspent, 1=spent)
 * outputs (repeated):
 *   prefix: 0x00 = varint size | raw script
 *           0x01 = 20 byte pubkey hash
 *           0x02 = 20 byte script hash
 *           0x03 = 33 byte compressed key
 *   data: the data mentioned above
 *   value: varint
 */

/**
 * Serialize the coins object.
 * @param {TX|Coins} tx
 * @returns {Buffer}
 */

Coins.prototype.toRaw = function toRaw(writer) {
  var p = new BufferWriter(writer);
  var height = this.height;
  var length = this.getLength();
  var i, output, prefix, data, bits, field, pos, bit, oct;

  // Unfortunately, we don't have a compact
  // way to store unconfirmed height.
  if (height === -1)
    height = 0x7fffffff;

  bits = height << 1;

  if (this.coinbase)
    bits |= 1;

  if (bits < 0)
    bits += 0x100000000;

  p.writeVarint(this.version);
  p.writeVarint(bits);

  field = new Buffer(Math.ceil(length / 8));
  field.fill(0);
  pos = 0;

  for (i = 0; i < length; i++) {
    output = this.outputs[i] ? 0 : 1;
    bit = pos % 8;
    oct = (pos - bit) / 8;
    field[oct] |= output << (7 - bit);
    pos++;
  }

  p.writeVarBytes(field);

  for (i = 0; i < length; i++) {
    output = this.outputs[i];

    if (!output)
      continue;

    if (output instanceof CompressedCoin) {
      p.writeBytes(output.toRaw());
      continue;
    }

    prefix = 0;

    // Attempt to compress the output scripts.
    // We can _only_ ever compress them if
    // they are serialized as minimaldata, as
    // we need to recreate them when we read
    // them.
    if (output.script.isPubkeyhash(true)) {
      prefix = 1;
      data = output.script.code[2].data;
    } else if (output.script.isScripthash()) {
      prefix = 2;
      data = output.script.code[1].data;
    } else if (output.script.isPubkey(true)) {
      prefix = 3;
      data = output.script.code[0].data;

      // Try to compress the key.
      data = bcoin.ec.compress(data);

      // If we can't compress it,
      // just store the script.
      if (!data)
        prefix = 0;
    }

    p.writeU8(prefix);

    if (prefix === 0)
      p.writeVarBytes(output.script.toRaw());
    else
      p.writeBytes(data);

    p.writeVarint(output.value);
  }

  if (!writer)
    p = p.render();

  return p;
};

/**
 * Parse serialized coins.
 * @param {Buffer} data
 * @param {Hash} hash
 * @returns {Object} A "naked" coins object.
 */

Coins.prototype.fromRaw = function fromRaw(data, hash, index) {
  var p = new BufferReader(data);
  var i = 0;
  var bits, coin, prefix, offset, size, field, bit, oct, spent;

  this.version = p.readVarint();

  bits = p.readVarint();

  this.height = bits >>> 1;
  this.hash = hash;
  this.coinbase = (bits & 1) !== 0;

  if (this.height === 0x7fffffff)
    this.height = -1;

  field = p.readVarBytes(true);

  while (p.left()) {
    bit = i % 8;
    oct = (i - bit) / 8;
    spent = (field[oct] >>> (7 - bit)) & 1;

    // Already spent.
    if (spent) {
      // Don't bother pushing outputs on if
      // we're seeking to a specific index.
      if (index != null) {
        if (i === index)
          return;
        i++;
        continue;
      }

      this.outputs.push(null);
      i++;
      continue;
    }

    offset = p.start();
    prefix = p.readU8();

    // Skip past the compressed scripts.
    switch (prefix & 3) {
      case 0:
        p.seek(p.readVarint());
        break;
      case 1:
      case 2:
        p.seek(20);
        break;
      case 3:
        p.seek(33);
        break;
      default:
        assert(false, 'Bad prefix.');
    }

    // Skip past the value.
    p.readVarint();

    size = p.end();

    // Keep going if we're seeking
    // to a specific index.
    if (index != null && i !== index) {
      i++;
      continue;
    }

    // Store the offset and size
    // in the compressed coin object.
    coin = new CompressedCoin(offset, size, data);

    // We found our coin.
    if (index != null)
      return coin.toCoin(this, i);

    this.outputs.push(coin);
    i++;
  }

  // We couldn't find our coin.
  if (index != null)
    return;

  return this;
};

/**
 * Parse a single serialized coin.
 * @param {Buffer} data
 * @param {Hash} hash
 * @param {Number} index
 * @returns {Coin}
 */

Coins.parseCoin = function parseCoin(data, hash, index) {
  assert(index != null, 'Bad coin index.');
  return new Coins().fromRaw(data, hash, index);
};

/**
 * Instantiate coins from a serialized Buffer.
 * @param {Buffer} data
 * @param {Hash} hash - Transaction hash.
 * @returns {Coins}
 */

Coins.fromRaw = function fromRaw(data, hash) {
  return new Coins().fromRaw(data, hash);
};

/**
 * Inject properties from tx.
 * @private
 * @param {TX} tx
 */

Coins.prototype.fromTX = function fromTX(tx) {
  var i;

  this.version = tx.version;
  this.hash = tx.hash('hex');
  this.height = tx.height;
  this.coinbase = tx.isCoinbase();

  for (i = 0; i < tx.outputs.length; i++) {
    if (tx.outputs[i].script.isUnspendable()) {
      this.outputs.push(null);
      continue;
    }
    this.outputs.push(bcoin.coin.fromTX(tx, i));
  }

  return this;
};

/**
 * Instantiate a coins object from a transaction.
 * @param {TX} tx
 * @returns {Coins}
 */

Coins.fromTX = function fromTX(tx) {
  return new Coins().fromTX(tx);
};

/**
 * A compressed coin is an object which defers
 * parsing of a coin. Say there is a transaction
 * with 100 outputs. When a block comes in,
 * there may only be _one_ input in that entire
 * block which redeems an output from that
 * transaction. When parsing the Coins, there
 * is no sense to get _all_ of them into their
 * abstract form. A compressed coin is just a
 * pointer to that coin in the Coins buffer, as
 * well as a size. Parsing is done only if that
 * coin is being redeemed.
 * @constructor
 * @private
 * @param {Number} offset
 * @param {Number} size
 * @param {Buffer} raw
 */

function CompressedCoin(offset, size, raw) {
  if (!(this instanceof CompressedCoin))
    return new CompressedCoin(offset, size, raw);

  this.offset = offset;
  this.size = size;
  this.raw = raw;
}

/**
 * Parse the deferred data and return a Coin.
 * @param {Coins} coins
 * @param {Number} index
 * @returns {Coin}
 */

CompressedCoin.prototype.toCoin = function toCoin(coins, index) {
  var p = new BufferReader(this.raw);
  var coin = new bcoin.coin();
  var prefix, key;

  // Load in all necessary properties
  // from the parent Coins object.
  coin.version = coins.version;
  coin.coinbase = coins.coinbase;
  coin.height = coins.height;
  coin.hash = coins.hash;
  coin.index = index;

  // Seek to the coin's offset.
  p.seek(this.offset);

  prefix = p.readU8();

  // Decompress the script.
  switch (prefix & 3) {
    case 0:
      coin.script.fromRaw(p.readVarBytes());
      break;
    case 1:
      coin.script.fromPubkeyhash(p.readBytes(20));
      break;
    case 2:
      coin.script.fromScripthash(p.readBytes(20));
      break;
    case 3:
      // Decompress the key. If this fails,
      // we have database corruption!
      key = bcoin.ec.decompress(p.readBytes(33));
      coin.script.fromPubkey(key);
      break;
    default:
      assert(false, 'Bad prefix.');
  }

  coin.value = p.readVarint();

  return coin;
};

/**
 * Slice off the part of the buffer
 * relevant to this particular coin.
 * @returns {Buffer}
 */

CompressedCoin.prototype.toRaw = function toRaw() {
  return this.raw.slice(this.offset, this.offset + this.size);
};

/*
 * Expose
 */

module.exports = Coins;
<|endoftext|>


<commit_before>var beacon_array = [];

var beacon_num = 0;
var beacon_prefix = "beacon_";

function getNextBeaconID(){

  var newBeaconID = beacon_prefix + beacon_num;
  beacon_num++;

  return newBeaconID;
}

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });
}

function deselect2(e) {
  $('.pop2').slideFadeToggle(function() {
    e.removeClass('selected');
  });
}

$(function() {
  $('#add_beacon_data').on('click', function() {

    if($(this).hasClass('selected')) {
      deselect($(this));
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('#add_beacon_data'));
    return false;
  });

  $('#form1').on('submit', function(e){
    console.log("Submitting beacon UUID and position");

    //Beacon array with UUID values
    beacon_array.push($('#bUuid').val());

    //Clear form input fields after submit and prevent default form submission
    $('#bUuid').val('');
    e.preventDefault();
  });

  $('#message_submit').on('click', function() {
    $('.pop').slideFadeToggle();
  });

});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

$(function() {
   $('#delete_beacon_data').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect2($(this));
    } else {
      $(this).addClass('selected');
      $('.pop2').slideFadeToggle();
    }

    var beacon_list = document.getElementById("beaconSelect");
    var option = document.createElement("option");

    if(beacon_array.length == 0 && beacon_list.options.length == 0){
      console.log("Array and list empty , adding label");
      option.text = "EMPTY";
      beacon_list.add(option);
    }
    else {
      console.log("Array or list no longer empty");

      for(var uuid=0; uuid<beacon_array.length; uuid++){

        var foundInList = false;

        for(var i=0; i<beacon_list.options.length; i++){
          if(beacon_list.options[i].value==beacon_array[uuid]){
            foundInList = true;
            console.log("Found array beacon in list");
          }
        }

        if(foundInList==false){
          option.text = beacon_array[uuid];
          beacon_list.add(option);
          console.log("Map beacon not found in list, adding ...");
        }
      }

      $('#beaconSelect option').each(function(){
        if (this.value == 'EMPTY' && beacon_list.options.length > 1) {
          console.log("EMPTY exists, deleting");
          $(this).remove();
          return false;
        }
      });

    }

    return false;
  });

  $('.close2').on('click', function() {
    deselect2($('#delete_beacon_data'));
    return false;
  });

  $('#form2').on('submit', function(e){

  if($('#beaconSelect option').filter(':selected').text() != ''){
    console.log("Deleting selected beacon from array");
    var index = beacon_array.indexOf($('#beaconSelect option').filter(':selected').text());
    beacon_array.splice(index, 1);

    $('#beaconSelect option').each(function(){
      if (this.value == $('#beaconSelect option').filter(':selected').text()) {
        console.log("Deleting selected beacon from list");
        $(this).remove();
        return false;
      }
    });

  }
    e.preventDefault();
  });

   $('#message_submit2').on('click', function() {
    $('.pop2').slideFadeToggle();
  });

});<commit_msg>Fixed the Beacons menu<commit_after>var beacon_array = [];

var beacon_num = 0;
var beacon_prefix = "beacon_";

function getNextBeaconID(){

  var newBeaconID = beacon_prefix + beacon_num;
  beacon_num++;

  return newBeaconID;
}

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });
}

function deselect2(e) {
  $('.pop2').slideFadeToggle(function() {
    e.removeClass('selected');
  });
}

$(function() {
  $('#add_beacon_data').on('click', function() {

    if($(this).hasClass('selected')) {
      deselect($(this));
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('#add_beacon_data'));
    return false;
  });

  $('#form1').on('submit', function(e){
    console.log("Trying to submit beacon UUID");

    //Beacon array with UUID values
    if($('#bUuid').val() != ''){
      console.log("UUID input field isnt empty , submitting ...");
      beacon_array.push($('#bUuid').val());
    }

    //Clear form input fields after submit and prevent default form submission
    $('#bUuid').val('');
    e.preventDefault();
  });

  $('#message_submit').on('click', function() {
    $('.pop').slideFadeToggle();
  });

});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

$(function() {
   $('#delete_beacon_data').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect2($(this));
    } else {
      $(this).addClass('selected');
      $('.pop2').slideFadeToggle();
    }

    var beacon_list = document.getElementById("beaconSelect");
    var option = document.createElement("option");

    if(beacon_array.length == 0 && beacon_list.options.length == 0){
      //console.log("Array and list empty , adding label");
      console.log("Array and list empty");
      // option.text = "EMPTY";
      // beacon_list.add(option);
    }
    else {
      console.log("Array or list no longer empty");

      $('#beaconSelect option').each(function(){

            console.log("Cleaning beacon list...");
            $(this).remove();

      });

      for(var uuid=0; uuid<beacon_array.length; uuid++){

          option.text = beacon_array[uuid];
          beacon_list.add(option);
          var option = document.createElement("option");

      }

    }

    return false;
  });

  $('.close2').on('click', function() {
    deselect2($('#delete_beacon_data'));
    return false;
  });

  $('#form2').on('submit', function(e){

  if($('#beaconSelect option').filter(':selected').text() != ''){
    console.log("Deleting selected beacon from array");
    var index = beacon_array.indexOf($('#beaconSelect option').filter(':selected').text());
    beacon_array.splice(index, 1);

    $('#beaconSelect option').each(function(){
      if (this.value == $('#beaconSelect option').filter(':selected').text()) {
        console.log("Deleting selected beacon from list");
        $(this).remove();
        return false;
      }
    });

  }
    e.preventDefault();
  });

   $('#message_submit2').on('click', function() {
    $('.pop2').slideFadeToggle();
  });

});<|endoftext|>


<commit_before>'use strict'

let _       = require('underscore'),
   log      = require('loglevel'),
   generate = require('../generate'),
   init     = require('../init'),
   summary  = require('../summary'),
   submit   = require('../submit'),
   parse    = require('../parse'),
   rm       = require('../rm'),
   resolve  = require('../resolve'),
   watch    = require('../watch'),
   guard    = require('../util/validate'),
   config   = require('../config')

let defaults = _.extend({},
  {
    vc: true, agg: false,  stagger: false, sample: true, expfile: true,
    machine: 'rain', parser: 'default-key-value',
    interval: 10000, batch: 1
  },
  config.yaml('defaults'),
  {
    //give priority to a nested property if it exists
    nested: function(cmd, prop) {
      if(cmd in this && prop in this[cmd])
        return this[cmd][prop]
      return this[prop]
    }
  })

let argv = require('yargs')
  .usage("Usage: $0 <command> [options]")
  .env("DIMEBOX")
  .command('generate <experiment>', 'Generate job files', yargs => {
    return yargs
      .option('machine', {
        alias: 'm',
        default: defaults.nested('generate', 'machine'),
        describe: "The machine where the experiments will be run."
      })
    .boolean('vc')
    .describe('vc', "Grab version control information and store with jobs.")
    .default('vc', defaults.nested('generate','vc'))
    .boolean('v')
  })
  .command('summary [epoch]', 'Summary of experiment', {
    sample: { default: defaults.nested('summary', 'sample'), describe: "Print a sample job file."},
    vc: { default: defaults.nested('summary', 'vc'), describe: "Print version control information." },
    expfile: { default: defaults.nested('summary', 'expfile'), describe: "Print experiment config YAML file." }
  })
  .command('init', 'Initialize directory structure for experiments')
  .command('submit <epoch>', 'Submit all jobs for an epoch', yargs => {
    return yargs
      .option('machine', {
        alias: 'm',
        default: 'rain',
        describe: "The machine where the experiments will be run."
      })
    .boolean('dry-run')
    .describe('dry-run', "Only simulate submission of jobs.")
    .boolean('stagger')
    .describe('stagger', "Set up a chain of dependent jobs so that jobs will only be scheduled k at a time.")
    .default('stagger', defaults.nested('submit', 'stagger'))
    .boolean('v')
    .number('batch')
    .describe('batch', "Size of batch for staggered job submission.")
    .implies('batch', 'stagger')
  })
  .command('parse [options] <epoch>', 'Parse results from a given epoch', yargs => {
    return yargs
      .option('parser', {
        alias: 'p',
        default: defaults.nested('parse', 'parser'),
        describe: "Parser used to extract information from each line."
      })
      .option('tag', {
        alias: 't',
        default: 'default',
        describe: "The tag for the results to show."
      })
      .boolean('agg')
      .default('agg', defaults.nested('parse', 'agg'))
      .describe('agg', "For results that have the same key-values, summarize into mean, stddev, etc.")
  })
  .command('watch [options] <epoch>', 'Monitor the status of results for a given epoch.', {
    interval: {
      default: defaults.nested('watch', 'interval'),
      describe: "Interval in ms to watch for changes"
    }
  })
  .command('rm <epoch>', 'Remove the jobs and results for a given epoch.')
  .command('resolve <epoch>', 'Resolve a symbolic epoch to concrete epoch.')
  .completion("completion", "Output .bashrc completion script.")
  .example('dimebox generate --machine vulcan exp.yml', "Generate job files for the experiment described in exp.yml for the machine 'vulcan'")
  .example('dimebox submit --machine vulcan HEAD', "Submit job files for the last generated experiment.")
  .demand(1)
  .boolean('v')
  .help()
  .argv

log.setLevel(argv.v ? 'debug' : 'info')
log.debug("Command line arguments: ", argv)

const handler = {
  routes: {
    generate: () => generate(argv.machine, argv.experiment, argv.vc),
    summary: () => summary(argv.epoch, argv.sample, argv.vc, argv.expfile),
    init: () => init(),
    parse: () => parse(argv.epoch, argv.tag, argv.parser, argv.agg),
    rm: () => rm(argv.epoch),
    resolve: () => resolve(argv.epoch),
    watch: () => watch(argv.epoch, argv.interval),
    submit: () => {
      const batch = argv.batch || defaults.nested('submit', 'batch')
      submit(argv.machine, argv.epoch, argv['dry-run'], argv.stagger, batch);
    },
  },
  guarded: ["generate", "summary", "submit", "parse", "rm", "resolve", "watch"]
}

const command = argv._[0];

if (command in handler.routes) {
   // Make sure that we're running in a dimebox directory
   if (_.contains(handler.guarded, command))
     guard()

   handler.routes[command]();
} else {
  log.error(`Error: unknown command ${command}. Consult dimebox --help for usage.`)
  process.exit(1)
}
<commit_msg>Submit command should read defaults from correct place.<commit_after>'use strict'

let _       = require('underscore'),
   log      = require('loglevel'),
   generate = require('../generate'),
   init     = require('../init'),
   summary  = require('../summary'),
   submit   = require('../submit'),
   parse    = require('../parse'),
   rm       = require('../rm'),
   resolve  = require('../resolve'),
   watch    = require('../watch'),
   guard    = require('../util/validate'),
   config   = require('../config')

let defaults = _.extend({},
  {
    vc: true, agg: false,  stagger: false, sample: true, expfile: true,
    machine: 'rain', parser: 'default-key-value',
    interval: 10000, batch: 1
  },
  config.yaml('defaults'),
  {
    //give priority to a nested property if it exists
    nested: function(cmd, prop) {
      if(cmd in this && prop in this[cmd])
        return this[cmd][prop]
      return this[prop]
    }
  })

let argv = require('yargs')
  .usage("Usage: $0 <command> [options]")
  .env("DIMEBOX")
  .command('generate <experiment>', 'Generate job files', yargs => {
    return yargs
      .option('machine', {
        alias: 'm',
        default: defaults.nested('generate', 'machine'),
        describe: "The machine where the experiments will be run."
      })
    .boolean('vc')
    .describe('vc', "Grab version control information and store with jobs.")
    .default('vc', defaults.nested('generate','vc'))
    .boolean('v')
  })
  .command('summary [epoch]', 'Summary of experiment', {
    sample: { default: defaults.nested('summary', 'sample'), describe: "Print a sample job file."},
    vc: { default: defaults.nested('summary', 'vc'), describe: "Print version control information." },
    expfile: { default: defaults.nested('summary', 'expfile'), describe: "Print experiment config YAML file." }
  })
  .command('init', 'Initialize directory structure for experiments')
  .command('submit <epoch>', 'Submit all jobs for an epoch', yargs => {
    return yargs
      .option('machine', {
        alias: 'm',
        default: defaults.nested('submit', 'machine'),
        describe: "The machine where the experiments will be run."
      })
    .boolean('dry-run')
    .describe('dry-run', "Only simulate submission of jobs.")
    .boolean('stagger')
    .describe('stagger', "Set up a chain of dependent jobs so that jobs will only be scheduled k at a time.")
    .default('stagger', defaults.nested('submit', 'stagger'))
    .boolean('v')
    .number('batch')
    .describe('batch', "Size of batch for staggered job submission.")
    .implies('batch', 'stagger')
  })
  .command('parse [options] <epoch>', 'Parse results from a given epoch', yargs => {
    return yargs
      .option('parser', {
        alias: 'p',
        default: defaults.nested('parse', 'parser'),
        describe: "Parser used to extract information from each line."
      })
      .option('tag', {
        alias: 't',
        default: 'default',
        describe: "The tag for the results to show."
      })
      .boolean('agg')
      .default('agg', defaults.nested('parse', 'agg'))
      .describe('agg', "For results that have the same key-values, summarize into mean, stddev, etc.")
  })
  .command('watch [options] <epoch>', 'Monitor the status of results for a given epoch.', {
    interval: {
      default: defaults.nested('watch', 'interval'),
      describe: "Interval in ms to watch for changes"
    }
  })
  .command('rm <epoch>', 'Remove the jobs and results for a given epoch.')
  .command('resolve <epoch>', 'Resolve a symbolic epoch to concrete epoch.')
  .completion("completion", "Output .bashrc completion script.")
  .example('dimebox generate --machine vulcan exp.yml', "Generate job files for the experiment described in exp.yml for the machine 'vulcan'")
  .example('dimebox submit --machine vulcan HEAD', "Submit job files for the last generated experiment.")
  .demand(1)
  .boolean('v')
  .help()
  .argv

log.setLevel(argv.v ? 'debug' : 'info')
log.debug("Command line arguments: ", argv)

const handler = {
  routes: {
    generate: () => generate(argv.machine, argv.experiment, argv.vc),
    summary: () => summary(argv.epoch, argv.sample, argv.vc, argv.expfile),
    init: () => init(),
    parse: () => parse(argv.epoch, argv.tag, argv.parser, argv.agg),
    rm: () => rm(argv.epoch),
    resolve: () => resolve(argv.epoch),
    watch: () => watch(argv.epoch, argv.interval),
    submit: () => {
      const batch = argv.batch || defaults.nested('submit', 'batch')
      submit(argv.machine, argv.epoch, argv['dry-run'], argv.stagger, batch);
    },
  },
  guarded: ["generate", "summary", "submit", "parse", "rm", "resolve", "watch"]
}

const command = argv._[0];

if (command in handler.routes) {
   // Make sure that we're running in a dimebox directory
   if (_.contains(handler.guarded, command))
     guard()

   handler.routes[command]();
} else {
  log.error(`Error: unknown command ${command}. Consult dimebox --help for usage.`)
  process.exit(1)
}
<|endoftext|>


<commit_before>"use strict";
var mocha = require('gulp-mocha'),
    Q = require('q'),
    globby = Q.denodeify(require('globby')),
    Transpiler = require('../index').Transpiler,
    jshint = require('gulp-jshint'),
    jscs = require('gulp-jscs'),
    vinylPaths = require('vinyl-paths'),
    del = require('del'),
    _ = require('lodash'),
    promisePipe = require("promisepipe"),
    AndroidEmulator = require('appium-ci').AndroidEmulator,
    androidTools = require('appium-ci').androidTools,
    iosTools = require('appium-ci').iosTools,
    spawn = require('child_process').spawn,
    exec = Q.denodeify(require('child_process').exec),
    path = require('path');

var DEFAULT_OPTS = {
  files: ["*.js", "lib/**/*.js", "test/**/*.js", "!gulpfile.js"],
  transpile: true,
  transpileOut: "build",
  babelOpts: {},
  linkBabelRuntime: true,
  jscs: true,
  jshint: true,
  watch: true,
  test: {
    files: ['${testDir}/**/*-specs.js', '!${testDir}/**/*-e2e-specs.js']
  },
  coverage: {
    files: ['./test/**/*-specs.js', '!./test/**/*-e2e-specs.js']
   },
  e2eTest: {
    files: '${testDir}/**/*-e2e-specs.js'
  },
  testReporter: ( process.env.TRAVIS || process.env.CI ) ? 'spec' : 'nyan',
  testTimeout: 8000,
  buildName: null,
};

// string interpolation
var interpolate = function (s, opts) {
  return _.keys(opts).reduce(function (s, k) {
    return s.replace(new RegExp('\\$\\{\\s*' + k + '\\s*\\}', 'g') , opts[k]);
  } , s);
};

var boilerplate = function (gulp, opts) {
  var spawnWatcher = require('../index').spawnWatcher.use(gulp);
  var runSequence = Q.denodeify(require('run-sequence').use(gulp));
  var defOpts = _.clone(DEFAULT_OPTS);
  _.extend(defOpts, opts);
  opts = defOpts;

  process.env.APPIUM_NOTIF_BUILD_NAME = opts.buildName;

  gulp.task('clean', function () {
    if (opts.transpile) {
      return gulp.src(opts.transpileOut, {read: false})
                 .pipe(vinylPaths(del));
    }
  });

  var testDeps = [];
  var rootDir = '.';
  if (opts.transpile) {
    testDeps.push('transpile');
    rootDir = opts.transpileOut;
  }
  var fileAliases = {rootDir: rootDir, testDir: rootDir + '/test', libDir: rootDir + '/lib' };

  if (opts.test) {
    var testFiles = _.flatten([opts.test.files || opts.testFiles]).map(function (f) {
      return interpolate(f, fileAliases);
    });
    gulp.task('test', testDeps,  function () {
      var isForceLogMode = parseInt(process.env._FORCE_LOGS, 10) === 1;
      var mochaOpts = {
        reporter: isForceLogMode ? 'spec' : opts.testReporter,
        timeout: opts.testTimeout
      };
      // set env so our code knows when it's being run in a test env
      process.env._TESTING = 1;
      return gulp
       .src(testFiles, {read: false})
       .pipe(mocha(mochaOpts))
       .on('error', spawnWatcher.handleError);
    });
  }

  if (opts.coverage) {
    var covTestFiles = _.flatten([opts.coverage.files]).map(function (f) {
      return interpolate(f, fileAliases);
    });
    gulp.task('coverage', function () {
      return exec('rm -rf ./build').then(function() {
        return globby(covTestFiles).then(function (files) {
          var deferred = Q.defer();
          var bins = {};
          _.each(['babel-node', 'isparta', '_mocha'], function (k) { bins[k] = path.resolve(__dirname, '../node_modules/.bin', k); });
          var bin = bins['babel-node'];
          var args = ['-r3', bins.isparta, 'cover', '--report', 'text', bins._mocha, '--', '--reporter', 'dot']
            .concat(files);
          var proc = spawn(bin, args, {stdio: opts.coverage.verbose ? 'inherit' : 'pipe'});
          proc.on('close', function (code) {
            if (code === 0) {
              deferred.resolve();
            } else {
              deferred.reject(new Error('Coverage command exit code: ' + code));
            }
          });
          return deferred.promise;
        });
      });
    });
    gulp.task('coveralls', ['coverage'], function () {
      var bin = path.resolve(__dirname, '../node_modules/.bin/coveralls');
      return exec('cat ./coverage/lcov.info | ' + bin);
    });
  }

  if (opts.e2eTest) {
    var e2eTestFiles = _.flatten([opts.e2eTest.files || opts.e2eTestFiles]).map(function (f) {
      return interpolate(f, fileAliases);
    });
    gulp.task('e2e-test', testDeps,  function () {
      var isForceLogMode = parseInt(process.env._FORCE_LOGS, 10) === 1;
      var mochaOpts = {
        reporter: isForceLogMode ? 'spec' : opts.testReporter,
        timeout: opts.testTimeout
      };
      // set env so our code knows when it's being run in a test env
      process.env._TESTING = 1;
      var seq = [
        function () {
          return promisePipe(gulp
           .src(e2eTestFiles, {read: false})
           .pipe(mocha(mochaOpts))
           .on('error', spawnWatcher.handleError));
        }];
      if (opts.e2eTest.android) {
        var emu = new AndroidEmulator(opts.e2eTest.avd);
        seq = [
          function () { return androidTools.killAll(); },
          function () {
            emu.start();
            return emu.waitTillReady();
          }].concat(seq).concat([
            function () { return emu.stop(); },
            function () { return androidTools.killAll(); }
          ]);
      }
      if (opts.e2eTest.ios) {
        var xCodeVersion = opts.e2eTest.xCodeVersion || '6.1.1';
        seq = [
          function () { return iosTools.killAll(); },
          function () { return iosTools.configureXcode(xCodeVersion); },
          function () { return iosTools.resetSims(); },
        ].concat(seq).concat([
          function () { return iosTools.killAll(); }
        ]);
      }
      return seq.reduce(Q.when, new Q()).catch(spawnWatcher.handleError);
    });
  }

  if (opts.transpile) {
    gulp.task('transpile', function () {
      var transpiler = new Transpiler(opts.babelOpts);
      return gulp.src(opts.files, {base: './'})
        .pipe(transpiler.stream())
        .on('error', spawnWatcher.handleError)
        .pipe(gulp.dest(opts.transpileOut));
    });

    gulp.task('prepublish', function () {
      return runSequence('clean', 'transpile');
    });
  }

  var lintTasks = [];
  if (opts.jscs) {
    gulp.task('jscs', function () {
      return gulp
       .src(opts.files)
       .pipe(jscs())
       .on('error', spawnWatcher.handleError);
    });
    lintTasks.push('jscs');
  }

  if (opts.jshint) {
    gulp.task('jshint', function () {
      return gulp
       .src(opts.files)
       .pipe(jshint())
       .pipe(jshint.reporter('jshint-stylish'))
       .pipe(jshint.reporter('fail'))
       .on('error', spawnWatcher.handleError);
    });
    lintTasks.push('jshint');
  }

  if (opts.jscs || opts.jshint) {
    opts.lint = true;
    gulp.task('lint', lintTasks);
  }

  var defaultSequence = [];
  if (opts.transpile) defaultSequence.push('clean');
  if (opts.lint) defaultSequence.push('lint');
  if (opts.transpile && !opts.test) defaultSequence.push('transpile');
  if (opts.test) defaultSequence.push('test');
  if (opts.extraDefaultTasks) defaultSequence = defaultSequence.concat(opts.extraDefaultTasks);

  if (opts.watch) {
    spawnWatcher.clear(false);
    spawnWatcher.configure('watch', opts.files, function () {
      return runSequence.apply(null, defaultSequence);
    });
  }

  gulp.task('once', function () {
    return runSequence.apply(null, defaultSequence);
  });

  gulp.task('default', [opts.watch ? 'watch' : 'once']);
};

module.exports = {
  DEFAULTS: _.cloneDeep(DEFAULT_OPTS),
  use: function (gulp) {
    return function (opts) {
      boilerplate(gulp, opts);
    };
  }
};
<commit_msg>coverage fix<commit_after>"use strict";
var mocha = require('gulp-mocha'),
    Q = require('q'),
    globby = Q.denodeify(require('globby')),
    Transpiler = require('../index').Transpiler,
    jshint = require('gulp-jshint'),
    jscs = require('gulp-jscs'),
    vinylPaths = require('vinyl-paths'),
    del = require('del'),
    _ = require('lodash'),
    promisePipe = require("promisepipe"),
    AndroidEmulator = require('appium-ci').AndroidEmulator,
    androidTools = require('appium-ci').androidTools,
    iosTools = require('appium-ci').iosTools,
    spawn = require('child_process').spawn,
    exec = Q.denodeify(require('child_process').exec),
    path = require('path');

var DEFAULT_OPTS = {
  files: ["*.js", "lib/**/*.js", "test/**/*.js", "!gulpfile.js"],
  transpile: true,
  transpileOut: "build",
  babelOpts: {},
  linkBabelRuntime: true,
  jscs: true,
  jshint: true,
  watch: true,
  test: {
    files: ['${testDir}/**/*-specs.js', '!${testDir}/**/*-e2e-specs.js']
  },
  coverage: {
    files: ['./test/**/*-specs.js', '!./test/**/*-e2e-specs.js']
   },
  e2eTest: {
    files: '${testDir}/**/*-e2e-specs.js'
  },
  testReporter: ( process.env.TRAVIS || process.env.CI ) ? 'spec' : 'nyan',
  testTimeout: 8000,
  buildName: null,
};

// string interpolation
var interpolate = function (s, opts) {
  return _.keys(opts).reduce(function (s, k) {
    return s.replace(new RegExp('\\$\\{\\s*' + k + '\\s*\\}', 'g') , opts[k]);
  } , s);
};

var boilerplate = function (gulp, opts) {
  var spawnWatcher = require('../index').spawnWatcher.use(gulp);
  var runSequence = Q.denodeify(require('run-sequence').use(gulp));
  var defOpts = _.clone(DEFAULT_OPTS);
  _.extend(defOpts, opts);
  opts = defOpts;

  process.env.APPIUM_NOTIF_BUILD_NAME = opts.buildName;

  gulp.task('clean', function () {
    if (opts.transpile) {
      return gulp.src(opts.transpileOut, {read: false})
                 .pipe(vinylPaths(del));
    }
  });

  var testDeps = [];
  var rootDir = '.';
  if (opts.transpile) {
    testDeps.push('transpile');
    rootDir = opts.transpileOut;
  }
  var fileAliases = {rootDir: rootDir, testDir: rootDir + '/test', libDir: rootDir + '/lib' };

  if (opts.test) {
    var testFiles = _.flatten([opts.test.files || opts.testFiles]).map(function (f) {
      return interpolate(f, fileAliases);
    });
    gulp.task('test', testDeps,  function () {
      var isForceLogMode = parseInt(process.env._FORCE_LOGS, 10) === 1;
      var mochaOpts = {
        reporter: isForceLogMode ? 'spec' : opts.testReporter,
        timeout: opts.testTimeout
      };
      // set env so our code knows when it's being run in a test env
      process.env._TESTING = 1;
      return gulp
       .src(testFiles, {read: false})
       .pipe(mocha(mochaOpts))
       .on('error', spawnWatcher.handleError);
    });
  }

  if (opts.coverage) {
    var covTestFiles = _.flatten([opts.coverage.files]).map(function (f) {
      return interpolate(f, fileAliases);
    });
    gulp.task('coverage', function () {
      return exec('rm -rf ./build').then(function() {
        return globby(covTestFiles).then(function (files) {
          var deferred = Q.defer();
          var bins = {};
          _.each(['babel-node', 'isparta', '_mocha'], function (k) { bins[k] = path.resolve(__dirname, '../node_modules/.bin', k); });
          var bin = bins['babel-node'];
          var args = [ '--ignore', 'node_modules', '-r3', bins.isparta, 'cover',
            '--report', 'text', bins._mocha, '--', '--reporter', 'dot']
            .concat(files);
          var proc = spawn(bin, args, {stdio: opts.coverage.verbose ? 'inherit' : 'pipe'});
          proc.on('close', function (code) {
            if (code === 0) {
              deferred.resolve();
            } else {
              deferred.reject(new Error('Coverage command exit code: ' + code));
            }
          });
          return deferred.promise;
        });
      });
    });
    gulp.task('coveralls', ['coverage'], function () {
      var bin = path.resolve(__dirname, '../node_modules/.bin/coveralls');
      return exec('cat ./coverage/lcov.info | ' + bin);
    });
  }

  if (opts.e2eTest) {
    var e2eTestFiles = _.flatten([opts.e2eTest.files || opts.e2eTestFiles]).map(function (f) {
      return interpolate(f, fileAliases);
    });
    gulp.task('e2e-test', testDeps,  function () {
      var isForceLogMode = parseInt(process.env._FORCE_LOGS, 10) === 1;
      var mochaOpts = {
        reporter: isForceLogMode ? 'spec' : opts.testReporter,
        timeout: opts.testTimeout
      };
      // set env so our code knows when it's being run in a test env
      process.env._TESTING = 1;
      var seq = [
        function () {
          return promisePipe(gulp
           .src(e2eTestFiles, {read: false})
           .pipe(mocha(mochaOpts))
           .on('error', spawnWatcher.handleError));
        }];
      if (opts.e2eTest.android) {
        var emu = new AndroidEmulator(opts.e2eTest.avd);
        seq = [
          function () { return androidTools.killAll(); },
          function () {
            emu.start();
            return emu.waitTillReady();
          }].concat(seq).concat([
            function () { return emu.stop(); },
            function () { return androidTools.killAll(); }
          ]);
      }
      if (opts.e2eTest.ios) {
        var xCodeVersion = opts.e2eTest.xCodeVersion || '6.1.1';
        seq = [
          function () { return iosTools.killAll(); },
          function () { return iosTools.configureXcode(xCodeVersion); },
          function () { return iosTools.resetSims(); },
        ].concat(seq).concat([
          function () { return iosTools.killAll(); }
        ]);
      }
      return seq.reduce(Q.when, new Q()).catch(spawnWatcher.handleError);
    });
  }

  if (opts.transpile) {
    gulp.task('transpile', function () {
      var transpiler = new Transpiler(opts.babelOpts);
      return gulp.src(opts.files, {base: './'})
        .pipe(transpiler.stream())
        .on('error', spawnWatcher.handleError)
        .pipe(gulp.dest(opts.transpileOut));
    });

    gulp.task('prepublish', function () {
      return runSequence('clean', 'transpile');
    });
  }

  var lintTasks = [];
  if (opts.jscs) {
    gulp.task('jscs', function () {
      return gulp
       .src(opts.files)
       .pipe(jscs())
       .on('error', spawnWatcher.handleError);
    });
    lintTasks.push('jscs');
  }

  if (opts.jshint) {
    gulp.task('jshint', function () {
      return gulp
       .src(opts.files)
       .pipe(jshint())
       .pipe(jshint.reporter('jshint-stylish'))
       .pipe(jshint.reporter('fail'))
       .on('error', spawnWatcher.handleError);
    });
    lintTasks.push('jshint');
  }

  if (opts.jscs || opts.jshint) {
    opts.lint = true;
    gulp.task('lint', lintTasks);
  }

  var defaultSequence = [];
  if (opts.transpile) defaultSequence.push('clean');
  if (opts.lint) defaultSequence.push('lint');
  if (opts.transpile && !opts.test) defaultSequence.push('transpile');
  if (opts.test) defaultSequence.push('test');
  if (opts.extraDefaultTasks) defaultSequence = defaultSequence.concat(opts.extraDefaultTasks);

  if (opts.watch) {
    spawnWatcher.clear(false);
    spawnWatcher.configure('watch', opts.files, function () {
      return runSequence.apply(null, defaultSequence);
    });
  }

  gulp.task('once', function () {
    return runSequence.apply(null, defaultSequence);
  });

  gulp.task('default', [opts.watch ? 'watch' : 'once']);
};

module.exports = {
  DEFAULTS: _.cloneDeep(DEFAULT_OPTS),
  use: function (gulp) {
    return function (opts) {
      boilerplate(gulp, opts);
    };
  }
};
<|endoftext|>


<commit_before>'use strict';
var url = require('url');
var neo4j = require('neo4j-driver').v1;
var _ = require('underscore');
var nodeify = require('ascallback');

module.exports = function(options) {
  var db;
  if (!options || !options.nodeify) db =  new Seraph(options);
  else {
    db = new Proxy(new Seraph(options), {
      get: function(target, name) {
        if (name in target && typeof target[name] == 'function') {
          return function() {
            var args = [].slice.call(arguments, 0, arguments.length - 1);
            var cb = arguments[arguments.length - 1];
            nodeify(target[name].apply(target, args), cb);
          }
        } else {
          return target[name]
        }
      }
    });
  }

  var recursiveProxy = (obj) => {
    return new Proxy(obj, {
      get: (_, k) => {
        if (!obj[k]) return undefined;
        if (typeof obj[k] == 'object') return recursiveProxy(obj[k]);
        return db[obj[k]].bind(db);
      }
    });
  }

  return new Proxy(db, {
    get: (target, key) => {
      if (target[key]) return target[key];
      var proxy = proxyMap[key];
      if (!proxy) return undefined;
      if (typeof proxy == 'object') return recursiveProxy(proxy);
      else return db[proxy].bind(db);
    }
  })
}

var proxyMap = {
  node: {
    save: 'save',
    read: 'read',
    nodesWithLabel: 'nodesWithLabel',
    readLabels: 'readLabels'
  },
  constraints: {
    uniqueness: {
      create: 'createUniquenessConstraint'
    }
  }
}

class Seraph {
  constructor(options) {
    if (!options) options = 'bolt://neo4j:neo4j@localhost';
    if (typeof options != 'object') {
      var server = url.parse(options);
      options = {
        user: server.auth ? server.auth.split(':')[0] : 'neo4j',
        pass: server.auth ? server.auth.split(':')[1] : 'neo4j'
      };
      delete server.auth;
      options.server = url.format(server);
    }

    options.user = options.user || 'neo4j';
    options.pass = options.pass || 'neo4j';
    options.server = options.server || 'bolt://localhost';
    options.id = options.id || 'id';

    this.options = options;
    this.driver = options.driver ||  neo4j.driver(options.server, neo4j.auth.basic(options.user, options.pass));
    this.label = options.label === false ? false : true;
    this.unboxInts = options.unboxInts === false ? false : true;

  }

  _unboxInt(i) {
    return this.unboxInts ? i.toNumber() : i;
  }

  _unboxAll(obj) {
    Object.keys(obj).forEach((key) => {
      if (neo4j.isInt(obj[key])) obj[key] = this._unboxInt(obj[key]);
    });
    return obj;
  }

  _getId(obj, requireData) {
    return new Promise((resolve, reject) => {
      var id;
      if (requireData) {
        id = typeof obj == 'object' ? obj[this.options.id] : undefined;
      } else {
        id = typeof obj == 'object' ? obj[this.options.id] : obj;
      }

      if (id != null) id = parseInt(id, 10);
      if (isNaN(id) || id == null) return reject(new Error("Invalid ID"));
      resolve(neo4j.int(id));
    });
  }

  _processResult(result, singleOrNull) {
    var records = result.records;
    var assemble = (field) => {
      if (typeof field != 'object' || !field) return field;
      else if (neo4j.isInt(field)) return this._unboxInt(field);
      else if (field instanceof neo4j.types.Node) {
        var obj = field.properties;
        if (this.options.label) obj.labels = field.labels;
        obj[this.options.id] = this._unboxInt(field.identity);
        return this._unboxAll(obj);
      }
      else if (field instanceof neo4j.types.Relationship) {
        field.start = this._unboxInt(field.start);
        field.end = this._unboxInt(field.end);
        field[this.options.id] = this._unboxInt(field.identity);
        if (this.options.id != 'identity') delete field.identity;
        field.properties = this._unboxAll(field.properties);
        return field;
      }
      else return field;
    }
    var processed = records.map((record) => {
      if (record.keys.length == 1) return assemble(record._fields[0]);
      else {
        var row = {};
        Object.keys(record).forEach((key) => {
          row[key] = assemble(record._fields[record._fieldLookup[key]])
        });
        return row;
      }
    });
    if (singleOrNull) processed = this._selectSingleOrNull(processed);
    return processed;
  }

  _selectSingleOrNull(results) {
    return results.length > 0 ? results[0] : null;
  }

  _session() {
    return this.options.session || this.driver.session();
  }

  _endSession(sess) {
    return (passthrough) => {
      if (this.options.session != sess) sess.close();
      return passthrough;
    }
  }

  _aggregate(fn, arr, argnum, allargs) {
    var sess = this.options.session ? this : this.session();
    var aggregated = Promise.all(arr.map(arg => {
      allargs[argnum] = arg;
      return fn.apply(sess, allargs);
    }))
    if (!this.options.session) {
      aggregated = aggregated
        .then((r) => { return sess.close(), r })
        .catch((e) => {
          sess.close();
          return new Promise((_, r) => r(e))
        });
    }
    return aggregated;
  }

  _run(query, params) {
    var sess = this._session();
    return sess.run(query, params)
      .then(this._endSession(sess))
      .catch((e) => {
        this._endSession(sess)();
        return new Promise((_, r) => r(e));
      });
  }

  session() {
    var sess = this.driver.session();
    var sessSeraph = new Seraph(this.options);
    sessSeraph.session = sess;
    return sessSeraph;
  }

  close() {
    this.options.session && this.options.session.close();
  }

  query(cypher, params) {
    return this._run(cypher, params)
      .then((result) => this._processResult(result));
  }

  read(node, prop) {
    if (Array.isArray(node)) return this._aggregate(this.read, node, 0, arguments);
    return this._getId(node)
      .then((id) => {
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          RETURN ${prop ? "node." + prop : "node"}
        `, {id});
      })
      .then((result) => this._processResult(result, true))
  }

  save(node, label) {
    if (Array.isArray(node)) return this._aggregate(this.save, node, 0, arguments);
    if (arguments[2] != null) return this._saveProperty(node, arguments[1], arguments[2]);

    if (label) {
      if (!Array.isArray(label)) label = [label];
      label = label.map(l => `SET node:${l}`).join(' ');
    } else {
      label = '';
    }

    return this._getId(node)
      .then(id => {
        var props = _.omit(node, this.options.id);
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          SET node = {props} ${label}
          RETURN node
        `, { id, props });
      })
      .catch(() => {
        return this._run(`
          CREATE (node)
          SET node = {node} ${label}
          RETURN node
        `, {node})
      })
      .then((result) => this._processResult(result, true))
  }

  _saveProperty(node, key, value) {
    return this._getId(node)
      .then(id => {
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          SET node.${key} = {value}
          RETURN node
        `, { id, value });
      })
      .then((result) => this._processResult(result, true))
  }

  delete(node, detach) {
    if (Array.isArray(node)) return this._aggregate(this.delete, node, 0, arguments);
    if (detach != null && typeof detach != 'boolean') return this.remove(node, detach);

    return this._getId(node)
      .then(id => {
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          ${detach ? 'detach' : ''} DELETE node
        `, { id })
      })
      .then(() => true);
  }

  remove(node, prop) {
    if (Array.isArray(node)) return this._aggregate(this.remove, node, 0, arguments);
    return this._getId(node)
      .then(id => {
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          REMOVE node.${prop}
          RETURN node
        `, { id })
      })
      .then((result) => this._processResult(result, true))
  }

  nodesWithLabel(label) {
    return this._run(`MATCH (n:${label}) RETURN n`)
      .then((result) => this._processResult(result));
  }

  readLabels(node) {
    return this._getId(node)
      .then(id => this._run(`MATCH (node) WHERE id(node) = {id} RETURN labels(node)`, { id }))
      .then((result) => {
        var rows = this._processResult(result)
        return rows[0] || [];
      })
  }

  relate() { return this.createRel.apply(this, arguments) }
  createRel(startNode, type, endNode, properties) {
    if (Array.isArray(startNode)) return this._aggregate(this.createRel, startNode, 0, arguments);
    if (Array.isArray(endNode)) return this._aggregate(this.createRel, endNode, 2, arguments);
    properties = properties || {};

    return Promise.all([
      this._getId(startNode),
      this._getId(endNode)
    ])
    .then(ids => {
      return this._run(`
        MATCH (start), (end)
        WHERE id(start) = {startId} AND id(end) = {endId}
        CREATE (start)-[rel:`${type}`]-(end)
        SET rel = {properties}
        RETURN rel
      `, { startId: ids[0], endId: ids[1], properties });
    })
    .then((result) => this._processResult(result, true))
  }

  createUniquenessConstraint(label, key) {
    return this._run(`CREATE CONSTRAINT ON (n:${label}) ASSERT n.${key} IS UNIQUE`)
      //compat. query returns nothing anyway
      .then(() => { return { type: 'UNIQUENESS', label: label, property_keys: [key] } });
  }

}
<commit_msg>bolt: rel mapping<commit_after>'use strict';
var url = require('url');
var neo4j = require('neo4j-driver').v1;
var _ = require('underscore');
var nodeify = require('ascallback');

module.exports = function(options) {
  var db;
  if (!options || !options.nodeify) db =  new Seraph(options);
  else {
    db = new Proxy(new Seraph(options), {
      get: function(target, name) {
        if (name in target && typeof target[name] == 'function') {
          return function() {
            var args = [].slice.call(arguments, 0, arguments.length - 1);
            var cb = arguments[arguments.length - 1];
            nodeify(target[name].apply(target, args), cb);
          }
        } else {
          return target[name]
        }
      }
    });
  }

  var recursiveProxy = (obj) => {
    return new Proxy(obj, {
      get: (_, k) => {
        if (!obj[k]) return undefined;
        if (typeof obj[k] == 'object') return recursiveProxy(obj[k]);
        return db[obj[k]].bind(db);
      }
    });
  }

  return new Proxy(db, {
    get: (target, key) => {
      if (target[key]) return target[key];
      var proxy = proxyMap[key];
      if (!proxy) return undefined;
      if (typeof proxy == 'object') return recursiveProxy(proxy);
      else return db[proxy].bind(db);
    }
  })
}

var proxyMap = {
  node: {
    save: 'save',
    read: 'read',
    nodesWithLabel: 'nodesWithLabel',
    readLabels: 'readLabels'
  },
  constraints: {
    uniqueness: {
      create: 'createUniquenessConstraint'
    }
  },
  rel: {
    create: 'createRel'
  }
}

class Seraph {
  constructor(options) {
    if (!options) options = 'bolt://neo4j:neo4j@localhost';
    if (typeof options != 'object') {
      var server = url.parse(options);
      options = {
        user: server.auth ? server.auth.split(':')[0] : 'neo4j',
        pass: server.auth ? server.auth.split(':')[1] : 'neo4j'
      };
      delete server.auth;
      options.server = url.format(server);
    }

    options.user = options.user || 'neo4j';
    options.pass = options.pass || 'neo4j';
    options.server = options.server || 'bolt://localhost';
    options.id = options.id || 'id';

    this.options = options;
    this.driver = options.driver ||  neo4j.driver(options.server, neo4j.auth.basic(options.user, options.pass));
    this.label = options.label === false ? false : true;
    this.unboxInts = options.unboxInts === false ? false : true;

  }

  _unboxInt(i) {
    return this.unboxInts ? i.toNumber() : i;
  }

  _unboxAll(obj) {
    Object.keys(obj).forEach((key) => {
      if (neo4j.isInt(obj[key])) obj[key] = this._unboxInt(obj[key]);
    });
    return obj;
  }

  _getId(obj, requireData) {
    return new Promise((resolve, reject) => {
      var id;
      if (requireData) {
        id = typeof obj == 'object' ? obj[this.options.id] : undefined;
      } else {
        id = typeof obj == 'object' ? obj[this.options.id] : obj;
      }

      if (id != null) id = parseInt(id, 10);
      if (isNaN(id) || id == null) return reject(new Error("Invalid ID"));
      resolve(neo4j.int(id));
    });
  }

  _processResult(result, singleOrNull) {
    var records = result.records;
    var assemble = (field) => {
      if (typeof field != 'object' || !field) return field;
      else if (neo4j.isInt(field)) return this._unboxInt(field);
      else if (field instanceof neo4j.types.Node) {
        var obj = field.properties;
        if (this.options.label) obj.labels = field.labels;
        obj[this.options.id] = this._unboxInt(field.identity);
        return this._unboxAll(obj);
      }
      else if (field instanceof neo4j.types.Relationship) {
        field.start = this._unboxInt(field.start);
        field.end = this._unboxInt(field.end);
        field[this.options.id] = this._unboxInt(field.identity);
        if (this.options.id != 'identity') delete field.identity;
        field.properties = this._unboxAll(field.properties);
        return field;
      }
      else return field;
    }
    var processed = records.map((record) => {
      if (record.keys.length == 1) return assemble(record._fields[0]);
      else {
        var row = {};
        Object.keys(record).forEach((key) => {
          row[key] = assemble(record._fields[record._fieldLookup[key]])
        });
        return row;
      }
    });
    if (singleOrNull) processed = this._selectSingleOrNull(processed);
    return processed;
  }

  _selectSingleOrNull(results) {
    return results.length > 0 ? results[0] : null;
  }

  _session() {
    return this.options.session || this.driver.session();
  }

  _endSession(sess) {
    return (passthrough) => {
      if (this.options.session != sess) sess.close();
      return passthrough;
    }
  }

  _aggregate(fn, arr, argnum, allargs) {
    var sess = this.options.session ? this : this.session();
    var aggregated = Promise.all(arr.map(arg => {
      allargs[argnum] = arg;
      return fn.apply(sess, allargs);
    }))
    if (!this.options.session) {
      aggregated = aggregated
        .then((r) => { return sess.close(), r })
        .catch((e) => {
          sess.close();
          return new Promise((_, r) => r(e))
        });
    }
    return aggregated;
  }

  _run(query, params) {
    var sess = this._session();
    return sess.run(query, params)
      .then(this._endSession(sess))
      .catch((e) => {
        this._endSession(sess)();
        return new Promise((_, r) => r(e));
      });
  }

  session() {
    var sess = this.driver.session();
    var sessSeraph = new Seraph(this.options);
    sessSeraph.session = sess;
    return sessSeraph;
  }

  close() {
    this.options.session && this.options.session.close();
  }

  query(cypher, params) {
    return this._run(cypher, params)
      .then((result) => this._processResult(result));
  }

  read(node, prop) {
    if (Array.isArray(node)) return this._aggregate(this.read, node, 0, arguments);
    return this._getId(node)
      .then((id) => {
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          RETURN ${prop ? "node." + prop : "node"}
        `, {id});
      })
      .then((result) => this._processResult(result, true))
  }

  save(node, label) {
    if (Array.isArray(node)) return this._aggregate(this.save, node, 0, arguments);
    if (arguments[2] != null) return this._saveProperty(node, arguments[1], arguments[2]);

    if (label) {
      if (!Array.isArray(label)) label = [label];
      label = label.map(l => `SET node:${l}`).join(' ');
    } else {
      label = '';
    }

    return this._getId(node)
      .then(id => {
        var props = _.omit(node, this.options.id);
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          SET node = {props} ${label}
          RETURN node
        `, { id, props });
      })
      .catch(() => {
        return this._run(`
          CREATE (node)
          SET node = {node} ${label}
          RETURN node
        `, {node})
      })
      .then((result) => this._processResult(result, true))
  }

  _saveProperty(node, key, value) {
    return this._getId(node)
      .then(id => {
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          SET node.${key} = {value}
          RETURN node
        `, { id, value });
      })
      .then((result) => this._processResult(result, true))
  }

  delete(node, detach) {
    if (Array.isArray(node)) return this._aggregate(this.delete, node, 0, arguments);
    if (detach != null && typeof detach != 'boolean') return this.remove(node, detach);

    return this._getId(node)
      .then(id => {
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          ${detach ? 'detach' : ''} DELETE node
        `, { id })
      })
      .then(() => true);
  }

  remove(node, prop) {
    if (Array.isArray(node)) return this._aggregate(this.remove, node, 0, arguments);
    return this._getId(node)
      .then(id => {
        return this._run(`
          MATCH (node) WHERE id(node) = {id}
          REMOVE node.${prop}
          RETURN node
        `, { id })
      })
      .then((result) => this._processResult(result, true))
  }

  nodesWithLabel(label) {
    return this._run(`MATCH (n:${label}) RETURN n`)
      .then((result) => this._processResult(result));
  }

  readLabels(node) {
    return this._getId(node)
      .then(id => this._run(`MATCH (node) WHERE id(node) = {id} RETURN labels(node)`, { id }))
      .then((result) => {
        var rows = this._processResult(result)
        return rows[0] || [];
      })
  }

  relate() { return this.createRel.apply(this, arguments) }
  createRel(startNode, type, endNode, properties) {
    if (Array.isArray(startNode)) return this._aggregate(this.createRel, startNode, 0, arguments);
    if (Array.isArray(endNode)) return this._aggregate(this.createRel, endNode, 2, arguments);
    properties = properties || {};

    return Promise.all([
      this._getId(startNode),
      this._getId(endNode)
    ])
    .then(ids => {
      return this._run(`
        MATCH (start), (end)
        WHERE id(start) = {startId} AND id(end) = {endId}
        CREATE (start)-[rel:`${type}`]-(end)
        SET rel = {properties}
        RETURN rel
      `, { startId: ids[0], endId: ids[1], properties });
    })
    .then((result) => this._processResult(result, true))
  }

  createUniquenessConstraint(label, key) {
    return this._run(`CREATE CONSTRAINT ON (n:${label}) ASSERT n.${key} IS UNIQUE`)
      //compat. query returns nothing anyway
      .then(() => { return { type: 'UNIQUENESS', label: label, property_keys: [key] } });
  }

}
<|endoftext|>


<commit_before>/**
 * Browsertime (http://www.browsertime.com)
 * Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog
 * and other contributors
 * Released under the Apache 2.0 License
 */
var stats = require('./statistics'),
    fs = require('fs'),
    async = require('async'),
    path = require('path'),
    logger = require('./logger'),
    url = require('url'),
    util = require('util'),
    EventEmitter = require('async-node-events');

function Browsertime(b) {
  this.log = logger.getLog();
  EventEmitter.call(this);
  this.result = [];
  this.scripts = [];
  this.browserVersion = '';
  this.os = '';
  this.browserName = '';
  this.userAgent = '';
  this.browsers = b;

}

util.inherits(Browsertime, EventEmitter);

Browsertime.prototype.fetch = function(options, callback) {

  callback = callback || function() {};

  this._setupDefaults(options);
  this._populateScripts(options);

  var self = this;

  async.series([
    function(cb) {
      self.emit('beforeRun', cb);
    },
    function(cb) {
      self._do(options, cb);
    },
    function(cb) {
      self.emit('afterRun', cb);
    }
  ], function(err, result) {
    callback(err);
  });
};

Browsertime.prototype._do = function(options, cb) {
  var browserRuns = [];
  var self = this;
  for (var i = 1; i <= options.runs; i++) {
    browserRuns.push(self._collectFromTheBrowser(options, i, options.runs));
  }

  async.series(browserRuns,
    function(err, results) {
      var data = self._getFormattedResult(options);
      self._saveToFile(data, options, cb);
    });
};

Browsertime.prototype._collectFromTheBrowser = function(options, iteration, totalIterations) {
  var self = this;

  return function(callback) {
    async.series([
          function(cb) {
            self.emit('callingBrowser', cb);
          }
        ],
        function(err, results) {
          var driver = self.browsers.getBrowser(options.browser).getDriver(options);

          driver.getCapabilities().then(function(cap) {
            self.browserVersion = cap.get('version');
            self.os = cap.get('platform');
            self.browserName = cap.get('browserName');
          });

          // fetch the URL and wait until the load event ends or we get the time out
          self.log.info('Fetching ' + options.url + ' (' + iteration + ' of ' + totalIterations + ')');
          driver.get(options.url);
          driver.wait(function() {
                return driver.executeScript('return window.performance.timing.loadEventEnd>0')
                    .then(function(b) {
                      return b;
                    });
              },
              60000
          ).then(function() {
                // lets run all scripts
                var promises = [];
                self.scripts.forEach(function(script) {
                  promises.push(driver.executeScript(script));
                });

                var callbacks = [];
                promises.forEach(function(promise) {
                  callbacks.push(function(cb) {
                    promise.then(function(value) {
                      cb(null, value);
                    });
                  });
                });

                // when we are finished, push the result and stop the browser
                async.parallel(callbacks,
                    function(err, results) {
                      var eachRun = {};
                      results.forEach(function(metric) {
                        Object.keys(metric).forEach(function(key) {
                          eachRun[key] = metric[key];
                        });
                      });
                      self.result.push(eachRun);
                      driver.quit();
                      callback();
                    });
              },
              function() {
                driver.quit().thenFinally(function() {
                  return callback(new Error('The url ' + options.url + ' timed out'));
                });
              });
        });
  };
};

Browsertime.prototype._getFormattedResult = function(options) {
  // fetch timings for each run and make some statistics
  var timings = {};
  this.result.forEach(function(run) {
    stats.setupTimingsStatistics(timings, run);
    stats.setupStatistics(timings, run, 'speedIndex');
    stats.setupStatistics(timings, run, 'firstPaint');
    stats.setupUserTimingsStatistics(timings, run);
  });
  return {
    url: options.url,
    runs: options.runs,
    browserName: this.browserName,
    browserVersion: this.browserVersion,
    platform: this.os,
    userAgent: options.userAgent || this.userAgent,
    windowSize: 'unknown',
    browserTimeVersion: require('../package.json').version,
    statistics: stats.formatStatistics(timings),
    data: this.result
  };
};

Browsertime.prototype._saveToFile = function(data, options, cb) {
  var self = this;

  // lets store the files
  async.parallel([
      function(callback) {
        fs.writeFile(options.filename, JSON.stringify(data), function(err) {
          self.log.info('Storing ' + options.filename);
          callback(err);
        });
      },
      function(callback) {
        self.emit('savingResults', { data: data }, callback);
      }
    ], cb);
};

Browsertime.prototype._setupDefaults = function(options) {

  options.runs = options.runs || 3;
  options.filename = options.filename || path.join(process.cwd(), url.parse(options.url).hostname + '.json');
  options.seleniumServer = options.seleniumServer || 'http://localhost:4444/wd/hub';
};

Browsertime.prototype._populateScripts = function(options) {
  var scriptRoots = [path.join(__dirname, 'scripts')];
  if (options.scriptPath) {
    scriptRoots.push(path.resolve(options.scriptPath));
  }

  var self = this;

  scriptRoots.forEach(function(rootPath) {
    fs.readdirSync(rootPath).forEach(function(file) {
      self.scripts.push(require(path.join(rootPath, file)));
    });
  });
};

module.exports = Browsertime;
<commit_msg>Exit with error if fetching from browser failed.<commit_after>/**
 * Browsertime (http://www.browsertime.com)
 * Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog
 * and other contributors
 * Released under the Apache 2.0 License
 */
var stats = require('./statistics'),
    fs = require('fs'),
    async = require('async'),
    path = require('path'),
    logger = require('./logger'),
    url = require('url'),
    util = require('util'),
    EventEmitter = require('async-node-events');

function Browsertime(b) {
  this.log = logger.getLog();
  EventEmitter.call(this);
  this.result = [];
  this.scripts = [];
  this.browserVersion = '';
  this.os = '';
  this.browserName = '';
  this.userAgent = '';
  this.browsers = b;

}

util.inherits(Browsertime, EventEmitter);

Browsertime.prototype.fetch = function(options, callback) {

  callback = callback || function() {};

  this._setupDefaults(options);
  this._populateScripts(options);

  var self = this;

  async.series([
    function(cb) {
      self.emit('beforeRun', cb);
    },
    function(cb) {
      self._do(options, cb);
    },
    function(cb) {
      self.emit('afterRun', cb);
    }
  ], function(err, result) {
    callback(err);
  });
};

Browsertime.prototype._do = function(options, cb) {
  var browserRuns = [];
  var self = this;
  for (var i = 1; i <= options.runs; i++) {
    browserRuns.push(self._collectFromTheBrowser(options, i, options.runs));
  }

  async.series(browserRuns,
    function(err, results) {
      if (err) {
        self.log.error(err.message);
        return cb(err);
      }
      var data = self._getFormattedResult(options);
      self._saveToFile(data, options, cb);
    });
};

Browsertime.prototype._collectFromTheBrowser = function(options, iteration, totalIterations) {
  var self = this;

  return function(callback) {
    async.series([
          function(cb) {
            self.emit('callingBrowser', cb);
          }
        ],
        function(err, results) {
          var driver = self.browsers.getBrowser(options.browser).getDriver(options);

          driver.getCapabilities().then(function(cap) {
            self.browserVersion = cap.get('version');
            self.os = cap.get('platform');
            self.browserName = cap.get('browserName');
          });

          // fetch the URL and wait until the load event ends or we get the time out
          self.log.info('Fetching ' + options.url + ' (' + iteration + ' of ' + totalIterations + ')');
          driver.get(options.url);
          driver.wait(function() {
                return driver.executeScript('return window.performance.timing.loadEventEnd>0')
                    .then(function(b) {
                      return b;
                    });
              },
              60000
          ).then(function() {
                // lets run all scripts
                var promises = [];
                self.scripts.forEach(function(script) {
                  promises.push(driver.executeScript(script));
                });

                var callbacks = [];
                promises.forEach(function(promise) {
                  callbacks.push(function(cb) {
                    promise.then(function(value) {
                      cb(null, value);
                    });
                  });
                });

                // when we are finished, push the result and stop the browser
                async.parallel(callbacks,
                    function(err, results) {
                      var eachRun = {};
                      results.forEach(function(metric) {
                        Object.keys(metric).forEach(function(key) {
                          eachRun[key] = metric[key];
                        });
                      });
                      self.result.push(eachRun);
                      driver.quit();
                      callback();
                    });
              },
              function() {
                driver.quit().thenFinally(function() {
                  return callback(new Error('The url ' + options.url + ' timed out'));
                });
              });
        });
  };
};

Browsertime.prototype._getFormattedResult = function(options) {
  // fetch timings for each run and make some statistics
  var timings = {};
  this.result.forEach(function(run) {
    stats.setupTimingsStatistics(timings, run);
    stats.setupStatistics(timings, run, 'speedIndex');
    stats.setupStatistics(timings, run, 'firstPaint');
    stats.setupUserTimingsStatistics(timings, run);
  });
  return {
    url: options.url,
    runs: options.runs,
    browserName: this.browserName,
    browserVersion: this.browserVersion,
    platform: this.os,
    userAgent: options.userAgent || this.userAgent,
    windowSize: 'unknown',
    browserTimeVersion: require('../package.json').version,
    statistics: stats.formatStatistics(timings),
    data: this.result
  };
};

Browsertime.prototype._saveToFile = function(data, options, cb) {
  var self = this;

  // lets store the files
  async.parallel([
      function(callback) {
        fs.writeFile(options.filename, JSON.stringify(data), function(err) {
          self.log.info('Storing ' + options.filename);
          callback(err);
        });
      },
      function(callback) {
        self.emit('savingResults', { data: data }, callback);
      }
    ], cb);
};

Browsertime.prototype._setupDefaults = function(options) {

  options.runs = options.runs || 3;
  options.filename = options.filename || path.join(process.cwd(), url.parse(options.url).hostname + '.json');
  options.seleniumServer = options.seleniumServer || 'http://localhost:4444/wd/hub';
};

Browsertime.prototype._populateScripts = function(options) {
  var scriptRoots = [path.join(__dirname, 'scripts')];
  if (options.scriptPath) {
    scriptRoots.push(path.resolve(options.scriptPath));
  }

  var self = this;

  scriptRoots.forEach(function(rootPath) {
    fs.readdirSync(rootPath).forEach(function(file) {
      self.scripts.push(require(path.join(rootPath, file)));
    });
  });
};

module.exports = Browsertime;
<|endoftext|>


<commit_before>module.exports = function () {
  return require('yargs')
    .usage('$0 [options] <dbname>')
    .option('host', {
      alias: 'h',
      default: '127.0.0.1',
      describe: 'database server host or socket directory'
    })
    .option('port', {
      alias: 'p',
      default: 5432,
      describe: 'database server port'
    })
    .option('user', {
      alias: 'u',
      default: 'postgres',
      describe: 'user name to connect as'
    })
    .option('password', {
      describe: 'password to use when connecting'
    })
    .option('silent', {
      default: false,
      describe: 'should we output to stdout'
    })
    .demand(1, 'you must provide a database name')
    .help()
    .version()
}
<commit_msg>Run prettier via GitHub Action<commit_after>module.exports = function () {
  return require("yargs")
    .usage("$0 [options] <dbname>")
    .option("host", {
      alias: "h",
      default: "127.0.0.1",
      describe: "database server host or socket directory",
    })
    .option("port", {
      alias: "p",
      default: 5432,
      describe: "database server port",
    })
    .option("user", {
      alias: "u",
      default: "postgres",
      describe: "user name to connect as",
    })
    .option("password", {
      describe: "password to use when connecting",
    })
    .option("silent", {
      default: false,
      describe: "should we output to stdout",
    })
    .demand(1, "you must provide a database name")
    .help()
    .version();
};
<|endoftext|>


<commit_before>//下面这些声明让我们可以使用socket.io

var socketio = require('socket.io');
var io;
var guestNumber =1;
var nickName = {};
var nameUsed = [];
var currentRoom = {};

//启动socketio服务器
exports.listen = function(server){
    io = socketio.listen(server);//启动socketio服务器,允许他搭载在已有的HTTP服务器上
    io.set('log level',1);

    io.sockets.on('connection',function(socket){//定义每个用户连接的处理逻辑
        guestNumber = assignGuestName(socket,guestNumber,nickNames,namesUsed);//在用户连接上来时赋予其一个访客名
        joinRoom(socket,'Lobby');//在用户连接上来时把它放入聊天室Lobby里
        handleMessageBroadcasting(socket,nickNames);//处理用户的消息,更名,以及聊天室的创建和变更
        handleNameChangeAttempts(socket,nickNames,namesUsed);
        handleRoomJoining(socket);
        socket.on('rooms',function(){//用户发出请求时,向其提供已经被占用的聊天室列表
            socket.emit('rooms',io.sockets.manager.rooms);
        });
        handleClientDisconnection(socket,nickNames,namesUsed);//定义用户断开连接后的清除逻辑
    });
};

//辅助函数第一个
//分配用户昵称
function assignGuestName(socket,guestNumber,nickNames,namesUsed){
    var name = 'guest'+guestNumber; //生成新昵称
    nickNames[socket.id] = name;//把用户昵称跟客户端链接ID关联上
    socket.emit('nameResult',{//让用户知道他们的昵称
        success:true,
        name:name
    });
    namesUsed.push(name);//存放已经被占用的昵称
    return guestNumber+1; 计数
}
//辅助函数第二个
//进入聊天室
function joinRoom(socket,room){
    socket.join(room);//让用户进入房间
    currentRoom[socket.id] = room;//记录用户当前的房间
    socket.emit('joinResult',{room:room});//让用户知道了他们进入了新的房间
    socket.broadcast.to(room).emit('message',{//让房间里的其他用户知道有新用户进入了房间
        text:nickNames[socket.id]+'has joined'+room+'.'
    });
    var usersInRoom = io.sockets.clients(room);//确定有哪些用户在这个房间里
    if(usersInRoom.length>1){//如果不止一个用户在这个房间里,汇总下都是谁
        var usersInRoomSummary = 'Users currently in'+room +':';
        for(var index in usersInRoom){
            var userSocketId = usersInRoom[index].id;
            if(userSocketId !=socket.id){
                if(index>0){
                    usersInRoomSummary +=',';
                }
                usersInRoomSummary += nickNames[userSocketId];
            }
        }
        usersInRoomSummary += '.';
        socket.emit('message',{text:usersInRoomSummary});//将房间里面其他用户的汇总发送给这个用户
    }
}<commit_msg>新增辅助函数<commit_after>//下面这些声明让我们可以使用socket.io

var socketio = require('socket.io');
var io;
var guestNumber =1;
var nickName = {};
var nameUsed = [];
var currentRoom = {};

//启动socketio服务器
exports.listen = function(server){
    io = socketio.listen(server);//启动socketio服务器,允许他搭载在已有的HTTP服务器上
    io.set('log level',1);

    io.sockets.on('connection',function(socket){//定义每个用户连接的处理逻辑
        guestNumber = assignGuestName(socket,guestNumber,nickNames,namesUsed);//在用户连接上来时赋予其一个访客名
        joinRoom(socket,'Lobby');//在用户连接上来时把它放入聊天室Lobby里
        handleMessageBroadcasting(socket,nickNames);//处理用户的消息,更名,以及聊天室的创建和变更
        handleNameChangeAttempts(socket,nickNames,namesUsed);
        handleRoomJoining(socket);
        socket.on('rooms',function(){//用户发出请求时,向其提供已经被占用的聊天室列表
            socket.emit('rooms',io.sockets.manager.rooms);
        });
        handleClientDisconnection(socket,nickNames,namesUsed);//定义用户断开连接后的清除逻辑
    });
};

//辅助函数第一个
//分配用户昵称
function assignGuestName(socket,guestNumber,nickNames,namesUsed){
    var name = 'guest'+guestNumber; //生成新昵称
    nickNames[socket.id] = name;//把用户昵称跟客户端链接ID关联上
    socket.emit('nameResult',{//让用户知道他们的昵称
        success:true,
        name:name
    });
    namesUsed.push(name);//存放已经被占用的昵称
    return guestNumber+1; 计数
}
//辅助函数第二个
//进入聊天室
function joinRoom(socket,room){
    socket.join(room);//让用户进入房间
    currentRoom[socket.id] = room;//记录用户当前的房间
    socket.emit('joinResult',{room:room});//让用户知道了他们进入了新的房间
    socket.broadcast.to(room).emit('message',{//让房间里的其他用户知道有新用户进入了房间
        text:nickNames[socket.id]+'has joined'+room+'.'
    });
    var usersInRoom = io.sockets.clients(room);//确定有哪些用户在这个房间里
    if(usersInRoom.length>1){//如果不止一个用户在这个房间里,汇总下都是谁
        var usersInRoomSummary = 'Users currently in'+room +':';
        for(var index in usersInRoom){
            var userSocketId = usersInRoom[index].id;
            if(userSocketId !=socket.id){
                if(index>0){
                    usersInRoomSummary +=',';
                }
                usersInRoomSummary += nickNames[userSocketId];
            }
        }
        usersInRoomSummary += '.';
        socket.emit('message',{text:usersInRoomSummary});//将房间里面其他用户的汇总发送给这个用户
    }
}

//辅助函数第三个
//3 处理昵称变更请求
function handleNameChangeAttempts(socket,nickNames,namesUsed) {
    socket.on('nameAttempt',function(name) {
        if(name.indexOf('Guest') == 0){
            socket.emit('nameRequest',{
                success:false,
                message:'昵称不能以Guest开头'
            });
        }else{
            if(namesUsed.indexOf(name) == -1){
                var previousName = nickNames[socket.id]
            }
        }
    })
}
<|endoftext|>


<commit_before>/*
Use Prime with Class

credits to MooTools, http://github.com/kamicane and https://github.com/kentaromiura, https://github.com/keeto
*/"use strict";

var prime = require('prime');
var type  = require('mout/lang/isKind');

var Mutators = {};

// Cloning objects and arrays
var cloneOf = function(item){
	switch (type(item)){
		case 'array'  : return cloneArray(item);
		case 'object' : return cloneObject(item);
		default       : return item;
	}
};

var cloneObject = function(object){
	var clone = {};
	for (var key in object) clone[key] = cloneOf(object[key]);
	return clone;
};

var cloneArray = function(array){
	var i = array.length, clone = new Array(i);
	while (i--) clone[i] = cloneOf(array[i]);
	return clone;
};

// reset function to reset objects and arrays in the prototype
var reset = function(object){
	for (var key in object){
		var value = object[key];
		switch (type(value)){
			case 'object' : object[key] = reset(prime.create(value)); break;
			case 'array'  : object[key] = cloneArray(value);          break;
		}
	}
	return object;
};

// wrap methods to be able to use .parent()
var wrap = function(fn, name, proto){

	return function(){

		var _name       = this._callName;
		var _proto      = this._callProto;

		this._callName  = name;
		this._callProto = proto;

		var result = fn.apply(this, arguments);

		this._callName  = _name;
		this._callProto = _proto;

		return result;

	};

};

var matchers = [];

var lookup = function(key){
	var i = matchers.length;
	while (i--){
		var matcher = matchers[i],
			match = key.match(matcher);
		if (match) return ['$mutator:' + matcher, match.slice(1)];
	}
	return null;
};

var Class = prime({

	constructor: function(){
		reset(this);
		// initialize is wrapped, so can use .parent(). .constructor however isn't wrapped.
		if (this.initialize) this.initialize.apply(this, arguments);
	},

	defineMutator: function(key, fn){

		if (type(key) == 'regexp'){
			matchers.push(key);
			key = '$mutator:' + key;
		}

		Mutators[key] = fn;
		return this;

	},

	mutator: function(key, method){

		var mutator;

		if (mutator = lookup(key)){
			key = mutator.shift();
			mutator.unshift(method);
		}

		if (Mutators.hasOwnProperty(key)){
			method = Class.Mutators[key].apply(this, mutator || [method]);
			if (method == null) return;
		}

		if (key === 'mixin'){

			switch (type(method)){
				case "function" : this.implement(prime.create(method.prototype));                         break;
				case "array"    : method.forEach(function(v){this.implement({"mixin": v})}, this); break;
				case "object"   : this.implement(method);                                                 break;
			}

		} else if (typeof method === 'function' && key != 'parent'){

			this.prototype[key] = wrap(method, key, this.prototype);

		} else {

			this.prototype[key] = method;

		}
	},

	parent: function(){

		var callProto = this._callProto;
		var name      = this._callName;
		var proto     = callProto.constructor.parent;

		if (typeof proto[name] != 'function') throw new Error('parent function "' + name + '" does not exist');

		return proto[name].apply(this, arguments);

	}

});

// Check of an object is a subclass of another prime
var isSubPrimeOf = function(object, prime){
	do {
		if (object === prime) return true;
		object = object && object.parent && object.parent.constructor;
	} while (object);
	return false;
};

var classy = function(proto){

	// accept empty proto, or if the proto is a function, use that as constructor (like MooTools 1.x)
	if (!proto) proto = {};
	else if (typeof proto == 'function') proto = {constructor: proto};

	// alias old Class keys

	if (proto.Extends){
		proto.inherits = proto.Extends;
		delete proto.Extends;
	}

	if (proto.Implements){
		proto.mixin = proto.Implements;
		delete proto.Implements;
	}

	// if it will inherit from another class, that class should be a subclass of Class
	if (proto.inherits && !isSubPrimeOf(proto.inherits, Class)) throw new Error('Inherited class should be classyfied');
	if (!proto.inherits) proto.inherits = Class;

	var prim = prime(proto);

	// overload implement method
	var implement = prim.implement;
	prim.implement = function(name, value){
		if (typeof name == 'string'){
			var object = {};
			object[name] = value;
			name = object;
		}
		return implement.call(this, name);
	};

	return prim;

};

classy.prototype = Class.prototype;
classy.Mutators = Mutators;

module.exports = classy;
<commit_msg>re-implement the old simple class.<commit_after>"use strict"
/*
prime
 - prototypal inheritance
*/

var hasOwn = require("mout/object/hasOwn"),
    mixIn  = require("mout/object/mixIn"),
    create = require("mout/lang/createObject"),
    kindOf = require("mout/lang/kindOf"),

    mutators = {

    };

var hasDescriptors = true

try {
    Object.defineProperty({}, "~", {})
    Object.getOwnPropertyDescriptor({}, "~")
} catch (e){
    hasDescriptors = false
}

// we only need to be able to implement "toString" and "valueOf" in IE < 9
var hasEnumBug = !({valueOf: 0}).propertyIsEnumerable("valueOf"),
    buggy      = ["toString", "valueOf"]

var verbs = /^constructor|inherits|mixin$/

var implement = function(proto){
    var prototype = this.prototype

    for (var key in proto){
        if (key.match(verbs)) continue

        if( mutators.hasOwnProperty( key ) ){
            var mutator = mutators[ key ]
            var value = proto[ key ];

            value = mutator.call( this, value );

            if( !value ){
               continue
            }
            this[ key ] = value
        }

        if (hasDescriptors){
            var descriptor = Object.getOwnPropertyDescriptor(proto, key)
            if (descriptor){
                Object.defineProperty(prototype, key, descriptor)
                continue
            }
        }
        prototype[key] = proto[key]
    }

    if (hasEnumBug) for (var i = 0; (key = buggy[i]); i++){
        var value = proto[key]
        if (value !== Object.prototype[key]) prototype[key] = value
    }

    return this
}

var prime = function(proto){

    if (kindOf(proto) === "Function") proto = {constructor: proto}

    var superprime = proto.inherits

    // if our nice proto object has no own constructor property
    // then we proceed using a ghosting constructor that all it does is
    // call the parent's constructor if it has a superprime, else an empty constructor
    // proto.constructor becomes the effective constructor
    var constructor = (hasOwn(proto, "constructor")) ? proto.constructor : (superprime) ? function(){
        return superprime.apply(this, arguments)
    } : function(){}

    if (superprime){

        mixIn(constructor, superprime)

        var superproto = superprime.prototype
        // inherit from superprime
        var cproto = constructor.prototype = create(superproto)

        // setting constructor.parent to superprime.prototype
        // because it's the shortest possible absolute reference
        constructor.parent = superproto
        cproto.constructor = constructor
    }

    if (!constructor.implement) constructor.implement = implement

    var mixins = proto.mixin
    if (mixins){
        if (kindOf(mixins) !== "Array") mixins = [mixins]
        for (var i = 0; i < mixins.length; i++) constructor.implement(create(mixins[i].prototype))
    }

    // implement proto and return constructor
    return constructor.implement(proto)
}

prime.defineMutator = function(name ,fn ){
    mutators[ name ] = fn;
};

module.exports = prime;
<|endoftext|>