<commit_before>// include core Park class
var Park = require("../park");

var s_apiBase = Symbol();
var s_apiKey = Symbol();
var s_resortID = Symbol();

/**
 * Implements the Merlin Park API framework. Thorpe Park, Alton Towers, Chessington etc. use this API framework
 * @class
 * @extends Park
 */
class MerlinPark extends Park {
    /**
     * Create new Merlin Object.
     * This object should not be called directly, but rather extended for each of the individual Merlin parks
     * @param {Object} options
     * @param {String} options.api_base Base URL to access the API
     * @param {String} options.api_key API key to access this park's API
     */
    constructor(options = {}) {
        options.name = options.name || "Merlin Park";

        // hard-code UserAgent for these parks
        //  do this before calling super, so we don't get a randomly generated one
        options.useragent = "Apache-HttpClient/UNAVAILABLE (java 1.4)";

        // inherit from base class
        super(options);

        // custom API options
        if (!options.api_base) throw new Error("Merlin Parks require an API base to work");
        this[s_apiBase] = options.api_base;
        if (!options.api_key) throw new Error("Merlin Parks require an API key");
        this[s_apiKey] = options.api_key;

        // optional resort ID (for Chessington etc.)
        this[s_resortID] = options.resort_id;
    }

    /**
     * Fetch Wait Times for Merlin Park
     */
    FetchWaitTimes() {
        return new Promise(function(resolve, reject) {
            // request challenge string
            this.HTTP({
                method: "POST",
                url: `${this[s_apiBase]}/queue-times`,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Connection": "Keep-Alive"
                }
            }).then(function(data) {
                if (!data.challenge) return reject(`Failed to get challenge string from API: ${JSON.stringify(data)}`);
                this.Log(`Got challenge string ${data.challenge} for park ${this.Name}`);

                this.GenerateAPIResponse(data.challenge).then(function(response) {
                    this.Log(`Generated response string ${response}`);

                    // make API request with our response request
                    this.HTTP({
                        method: "POST",
                        url: `${this[s_apiBase]}/queue-times`,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Connection": "Keep-Alive"
                        },
                        body: {
                            response: response,
                            challenge: data.challenge,
                            resort: this[s_resortID] || null
                        }
                    }).then(function(waittimes) {
                        // park API results differ ever so slightly. Chessington has it under "queue-times", Alton Towers just returns an array
                        var rideData = (waittimes['queue-times'] || waittimes);

                        for (var i = 0, ride; ride = rideData[i++];) {
                            var rideName = this._GetRideName(ride);
                            // skip if we have no name for this asset
                            if (!rideName) continue;

                            // apply each wait time data
                            var rideObject = this.GetRideObject({
                                id: ride.id,
                                name: rideName,
                            });

                            if (!rideObject) {
                                this.Log(`Failed to find ride with ID ${ride.id}`);
                            } else {
                                // update ride wait time
                                rideObject.WaitTime = ride.status == "closed" ? -1 : (ride.time || -1);
                            }
                        }

                        resolve();
                    }.bind(this), reject);
                }.bind(this), reject);
            }.bind(this), reject);
        }.bind(this));
    }

    /**
     * Generate a response to a challenge for this park
     * @returns {Promise<String>} Promise resolving with the challenge response for this park
     */
    GenerateAPIResponse(challenge) {
        // each park does this very slightly differently, so each park needs to implement their own version of this
        if (this._APIRespond === undefined) {
            return Promise.reject("Park needs to implement API response function _APIRespond to make API requests");
        }
        return Promise.resolve(this._APIRespond(challenge));
    }

    /**
     * The API Base URL for this park
     * @returns {String} API Base URL
     */
    get APIBase() {
        return this[s_apiBase];
    }

    /**
     * API Key for this park
     * @returns {String} Park's API Key
     */
    get APIKey() {
        return this[s_apiKey];
    }
}

// export the class
module.exports = MerlinPark;<commit_msg>Legacy API has changed it's wait time field name. Update to fix Chessington.<commit_after>// include core Park class
var Park = require("../park");

var s_apiBase = Symbol();
var s_apiKey = Symbol();
var s_resortID = Symbol();

/**
 * Implements the Merlin Park API framework. Thorpe Park, Alton Towers, Chessington etc. use this API framework
 * @class
 * @extends Park
 */
class MerlinPark extends Park {
    /**
     * Create new Merlin Object.
     * This object should not be called directly, but rather extended for each of the individual Merlin parks
     * @param {Object} options
     * @param {String} options.api_base Base URL to access the API
     * @param {String} options.api_key API key to access this park's API
     */
    constructor(options = {}) {
        options.name = options.name || "Merlin Park";

        // hard-code UserAgent for these parks
        //  do this before calling super, so we don't get a randomly generated one
        options.useragent = "Apache-HttpClient/UNAVAILABLE (java 1.4)";

        // inherit from base class
        super(options);

        // custom API options
        if (!options.api_base) throw new Error("Merlin Parks require an API base to work");
        this[s_apiBase] = options.api_base;
        if (!options.api_key) throw new Error("Merlin Parks require an API key");
        this[s_apiKey] = options.api_key;

        // optional resort ID (for Chessington etc.)
        this[s_resortID] = options.resort_id;
    }

    /**
     * Fetch Wait Times for Merlin Park
     */
    FetchWaitTimes() {
        return new Promise(function(resolve, reject) {
            // request challenge string
            this.HTTP({
                method: "POST",
                url: `${this[s_apiBase]}/queue-times`,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Connection": "Keep-Alive"
                }
            }).then(function(data) {
                if (!data.challenge) return reject(`Failed to get challenge string from API: ${JSON.stringify(data)}`);
                this.Log(`Got challenge string ${data.challenge} for park ${this.Name}`);

                this.GenerateAPIResponse(data.challenge).then(function(response) {
                    this.Log(`Generated response string ${response}`);

                    // make API request with our response request
                    this.HTTP({
                        method: "POST",
                        url: `${this[s_apiBase]}/queue-times`,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Connection": "Keep-Alive"
                        },
                        body: {
                            response: response,
                            challenge: data.challenge,
                            resort: this[s_resortID] || null
                        }
                    }).then(function(waittimes) {
                        // park API results differ ever so slightly. Chessington has it under "queue-times", Alton Towers just returns an array
                        var rideData = (waittimes['queue-times'] || waittimes);

                        for (var i = 0, ride; ride = rideData[i++];) {
                            var rideName = this._GetRideName(ride);
                            // skip if we have no name for this asset
                            if (!rideName) continue;

                            // apply each wait time data
                            var rideObject = this.GetRideObject({
                                id: ride.id,
                                name: rideName,
                            });

                            if (!rideObject) {
                                this.Log(`Failed to find ride with ID ${ride.id}`);
                            } else {
                                // update ride wait time
                                rideObject.WaitTime = ride.status == "closed" ? -1 : (ride.wait_time || -1);
                            }
                        }

                        resolve();
                    }.bind(this), reject);
                }.bind(this), reject);
            }.bind(this), reject);
        }.bind(this));
    }

    /**
     * Generate a response to a challenge for this park
     * @returns {Promise<String>} Promise resolving with the challenge response for this park
     */
    GenerateAPIResponse(challenge) {
        // each park does this very slightly differently, so each park needs to implement their own version of this
        if (this._APIRespond === undefined) {
            return Promise.reject("Park needs to implement API response function _APIRespond to make API requests");
        }
        return Promise.resolve(this._APIRespond(challenge));
    }

    /**
     * The API Base URL for this park
     * @returns {String} API Base URL
     */
    get APIBase() {
        return this[s_apiBase];
    }

    /**
     * API Key for this park
     * @returns {String} Park's API Key
     */
    get APIKey() {
        return this[s_apiKey];
    }
}

// export the class
module.exports = MerlinPark;<|endoftext|>


<commit_before>var inChannels = 4;

var intParams = [
    2,   3,   2,    7,   6,   3 ];

var intDepthwiseFilter = [
  111, 112, 113,  114, 115, 116,   121, 122, 123,  124, 125, 126,
  211, 212, 213,  214, 215, 216,   221, 222, 223,  224, 225, 226,
  311, 312, 313,  314, 315, 316,   321, 322, 323,  324, 325, 326,
  411, 412, 413,  414, 415, 416,   421, 422, 423,  424, 425, 426 ];

var intPointwiseFilter = [
  1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158,
  1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258,
  1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358 ];

var intBias = [
  2171, 2172, 2173 ];

var integerWeights = intParams.concat( intDepthwiseFilter, intPointwiseFilter, intBias );

var encodedWeightBase = 36;
var encodedWeightCharCount = 5;
var encodedWeights = integerWeights.map(
      integerWeight => integerWeight.toString(encodedWeightBase).padStart(encodedWeightCharCount, "0") );
var strEncodedWeights = "".concat(...encodedWeights);

// For converting to the integer itself.
var weightValueOffset = 0;
var weightValueDivisor = 1;

var theEntities = SeparableConv2d.Layer.StringArrayToSeparableConv2dEntities(
      [strEncodedWeights], encodedWeightCharCount, encodedWeightBase, weightValueOffset, weightValueDivisor );

var entity = theEntities[0];
tf.util.assert(
  entity.params.filterHeight == intParams[0],
  `entity.params.filterHeight ${entity.params.filterHeight} != ${intParams[0]}`);

tf.util.assert(
  entity.params.filterWidth == intParams[1], `entity.params.filterWidth ${entity.params.filterWidth} != ${intParams[1]}`);

tf.util.assert(
  entity.params.channelMultiplier == intParams[2], `entity.params.channelMultiplier ${entity.params.channelMultiplier} != ${intParams[2]}`);

tf.util.assert(
  entity.params.dilationHeight == intParams[3], `entity.params.dilationHeight ${entity.params.dilationHeight} != ${intParams[3]}`);

tf.util.assert(
  entity.params.dilationWidth == intParams[4], `entity.params.dilationWidth ${entity.params.dilationWidth} != ${intParams[4]}`);

tf.util.assert(
  entity.params.outChannels == intParams[5], `entity.params.outChannels ${entity.params.outChannels} != ${intParams[5]}`);

var theDepthwiseShape = [intParams[0], intParams[1], inChannels, intParams[2]];
tf.util.assert(
  tf.util.arraysEqual(entity.depthwise.shape, theDepthwiseShape),
  `entity.depthwise.shape ${entity.depthwise.shape} != ${theDepthwiseShape}`);

tf.util.assert(
  tf.util.arraysEqual(entity.depthwise.filter, intDepthwiseFilter),
  `entity.depthwise.filter ${entity.depthwise.filter} != ${intDepthwiseFilter}`);

var thePointwiseShape = [1, 1, inChannels * intParams[2], intParams[3]];
tf.util.assert(
  tf.util.arraysEqual(entity.pointwise.shape, thePointwiseShape),
  `entity.pointwise.shape ${entity.pointwise.shape} != ${thePointwiseShape}`);

tf.util.assert(
  tf.util.arraysEqual(entity.pointwise.filter, intPointwiseFilter),
  `entity.pointwise.filter ${entity.pointwise.filter} != ${intPointwiseFilter}`);

var theBiasShape = [1, 1, intParams[5]];
tf.util.assert(
  tf.util.arraysEqual(entity.bias.shape, theBiasShape),
  `entity.bias.shape ${entity.bias.shape} != ${theBiasShape}`);

tf.util.assert(
  tf.util.arraysEqual(entity.bias.filter, intBias),
  `entity.bias.filter ${entity.bias.filter} != ${intBias}`);

<commit_msg>Update SeparableConv2d_test.js<commit_after>var inChannels = 4;

var intParams = [
    2,   3,   2,    7,   6,   3 ];

var intDepthwiseFilter = [
  111, 112, 113,  114, 115, 116,   121, 122, 123,  124, 125, 126,
  211, 212, 213,  214, 215, 216,   221, 222, 223,  224, 225, 226,
  311, 312, 313,  314, 315, 316,   321, 322, 323,  324, 325, 326,
  411, 412, 413,  414, 415, 416,   421, 422, 423,  424, 425, 426 ];

var intPointwiseFilter = [
  1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158,
  1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258,
  1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358 ];

var intBias = [
  2171, 2172, 2173 ];

var integerWeights = intParams.concat( intDepthwiseFilter, intPointwiseFilter, intBias );

var encodedWeightBase = 36;
var encodedWeightCharCount = 5;
var encodedWeights = integerWeights.map(
      integerWeight => integerWeight.toString(encodedWeightBase).padStart(encodedWeightCharCount, "0") );
var strEncodedWeights = "".concat(...encodedWeights);

// For converting to the integer itself.
var weightValueOffset = 0;
var weightValueDivisor = 1;

var theEntities = SeparableConv2d.Layer.StringArrayToSeparableConv2dEntities(
      [strEncodedWeights], encodedWeightCharCount, encodedWeightBase, weightValueOffset, weightValueDivisor );

var entity = theEntities[ 0 ];
var layer = entity[ 0 ];
tf.util.assert(
  layer.params.filterHeight == intParams[0],
  `layer.params.filterHeight ${layer.params.filterHeight} != ${intParams[0]}`);

tf.util.assert(
  layer.params.filterWidth == intParams[1], `layer.params.filterWidth ${layer.params.filterWidth} != ${intParams[1]}`);

tf.util.assert(
  layer.params.channelMultiplier == intParams[2], `layer.params.channelMultiplier ${layer.params.channelMultiplier} != ${intParams[2]}`);

tf.util.assert(
  layer.params.dilationHeight == intParams[3], `layer.params.dilationHeight ${layer.params.dilationHeight} != ${intParams[3]}`);

tf.util.assert(
  layer.params.dilationWidth == intParams[4], `layer.params.dilationWidth ${layer.params.dilationWidth} != ${intParams[4]}`);

tf.util.assert(
  layer.params.outChannels == intParams[5], `layer.params.outChannels ${layer.params.outChannels} != ${intParams[5]}`);

var theDepthwiseShape = [intParams[0], intParams[1], inChannels, intParams[2]];
tf.util.assert(
  tf.util.arraysEqual(layer.depthwise.shape, theDepthwiseShape),
  `layer.depthwise.shape ${entity.depthwise.shape} != ${theDepthwiseShape}`);

tf.util.assert(
  tf.util.arraysEqual(layer.depthwise.filter, intDepthwiseFilter),
  `layer.depthwise.filter ${entity.depthwise.filter} != ${intDepthwiseFilter}`);

var thePointwiseShape = [1, 1, inChannels * intParams[2], intParams[3]];
tf.util.assert(
  tf.util.arraysEqual(layer.pointwise.shape, thePointwiseShape),
  `layer.pointwise.shape ${layer.pointwise.shape} != ${thePointwiseShape}`);

tf.util.assert(
  tf.util.arraysEqual(layer.pointwise.filter, intPointwiseFilter),
  `layer.pointwise.filter ${layer.pointwise.filter} != ${intPointwiseFilter}`);

var theBiasShape = [1, 1, intParams[5]];
tf.util.assert(
  tf.util.arraysEqual(layer.bias.shape, theBiasShape),
  `layer.bias.shape ${layer.bias.shape} != ${theBiasShape}`);

tf.util.assert(
  tf.util.arraysEqual(layer.bias.filter, intBias),
  `layer.bias.filter ${layer.bias.filter} != ${intBias}`);

<|endoftext|>


<commit_before>var pluralize = require('pluralize');
/**
 * View helpers (see http://expressjs.com/api.html#app.locals)
 */
var pluralise = function(word, count){
  return pluralize(word, count, true);
};

var formatMoney = function(num){
  return num.toFixed(2);
};

var epdqParams = function(){
  return edpqResponse.parameters;
};

var postage = function(){
  return (typeof edpqParams['postage'] != 'undefined' && edpqParams['postage'] == 'yes');
};

var documentCount = function(){
  var documentCount = epdqParams['document_count'];
  return (typeof documentCount == 'undefined' ? 0 : new Number(documentCount));
};

var registrationCount = function(){
  var registrationCount = epdqParams['document_count'];
  return (typeof registrationCount == 'undefined' ? 0 : new Number(registrationCount));
};

module.exports = function(app){
  if (typeof app == 'undefined') throw new Error("You must app to this module!");
  app.locals.pluralise = pluralise;
  app.locals.formatMoney = formatMoney;
  app.locals.epdqParams = epdqParams;
  app.locals.postage = postage;
  app.locals.documentCount = documentCount;
  app.locals.registrationCount = registrationCount;
}
<commit_msg>Add titlecase helper<commit_after>var pluralize = require('pluralize');
/**
 * View helpers (see http://expressjs.com/api.html#app.locals)
 */
var pluralise = function(word, count){
  return pluralize(word, count, true);
};

var titleCase = function(word){
  return word.charAt(0).toUpperCase() + word.slice(1);
};

var formatMoney = function(num){
  return num.toFixed(2);
};

var epdqParams = function(){
  return edpqResponse.parameters;
};

var postage = function(){
  return (typeof edpqParams['postage'] != 'undefined' && edpqParams['postage'] == 'yes');
};

var documentCount = function(){
  var documentCount = epdqParams['document_count'];
  return (typeof documentCount == 'undefined' ? 0 : new Number(documentCount));
};

var registrationCount = function(){
  var registrationCount = epdqParams['document_count'];
  return (typeof registrationCount == 'undefined' ? 0 : new Number(registrationCount));
};

module.exports = function(app){
  if (typeof app == 'undefined') throw new Error("You must app to this module!");
  app.locals.pluralise = pluralise;
  app.locals.titleCase = titleCase;
  app.locals.formatMoney = formatMoney;
  app.locals.epdqParams = epdqParams;
  app.locals.postage = postage;
  app.locals.documentCount = documentCount;
  app.locals.registrationCount = registrationCount;
}
<|endoftext|>


<commit_before>// yeah, nasty, but it allows me to switch from a RTF to plain text if we're running a iOS
var noop = function () {},
    rootClassName = document.body.className;

if (jsbin.mobile || jsbin.tablet || rootClassName.indexOf('ie6') !== -1 || rootClassName.indexOf('ie7') !== -1) {
  $('body').addClass('mobile');
  jsbin.lameEditor = true;
  Editor = function (el, options) {
    this.textarea = el;
    this.win = { document : this.textarea };
    this.ready = true;
    this.wrapping = document.createElement('div');

    var textareaParent = this.textarea.parentNode;
    this.wrapping.appendChild(this.textarea);
    textareaParent.appendChild(this.wrapping);

    this.textarea.style.opacity = 1;
    // this.textarea.style.width = '100%';

    $(this.textarea).blur(throttle(function () {
      $(document).trigger('codeChange', { panelId: el.id });
    }, 200));

    options.initCallback && $(options.initCallback);
  };

  Editor.prototype = {
    getWrapperElement: function () {
      return this.wrapping;
    },
    getScrollerElement: function () {
      return this.textarea;
    },
    setOption: function (type, handler) {
      if (type == 'onChange') {
        $(this.textarea).change(handler);
      }
    },
    setCode: function (code) {
      this.textarea.value = code;
    },
    getCode: function () {
      return this.textarea.value;
    },
    getValue: function () {
      return this.textarea.value;
    },
    setValue: function (code)  {
      this.textarea.value = code;
    },
    focus: noop,
    getCursor: function () {
      return { line: 0, ch: 0 };
    },
    setCursor: noop,
    currentLine: function () {
      return 0;
    },
    cursorPosition: function () {
      return { character: 0 };
    },
    nthLine: noop,
    refresh: noop,
    selectLines: noop
  };

  CodeMirror = function () {};

  CodeMirror.fromTextArea = function (el, options) {
      return new Editor(el, options);
  };

  CodeMirror.keyMap = { basic: {} };

}<commit_msg>Add 'on' to mobile CodeMirror to fix mobile errors.<commit_after>// yeah, nasty, but it allows me to switch from a RTF to plain text if we're running a iOS
var noop = function () {},
    rootClassName = document.body.className;

if (jsbin.mobile || jsbin.tablet || rootClassName.indexOf('ie6') !== -1 || rootClassName.indexOf('ie7') !== -1) {
  $('body').addClass('mobile');
  jsbin.lameEditor = true;
  Editor = function (el, options) {
    this.textarea = el;
    this.win = { document : this.textarea };
    this.ready = true;
    this.wrapping = document.createElement('div');

    var textareaParent = this.textarea.parentNode;
    this.wrapping.appendChild(this.textarea);
    textareaParent.appendChild(this.wrapping);

    this.textarea.style.opacity = 1;
    // this.textarea.style.width = '100%';

    $(this.textarea).blur(throttle(function () {
      $(document).trigger('codeChange', { panelId: el.id });
    }, 200));

    options.initCallback && $(options.initCallback);
  };

  Editor.prototype = {
    getWrapperElement: function () {
      return this.wrapping;
    },
    getScrollerElement: function () {
      return this.textarea;
    },
    setOption: function (type, handler) {
      if (type == 'onChange') {
        $(this.textarea).change(handler);
      }
    },
    setCode: function (code) {
      this.textarea.value = code;
    },
    getCode: function () {
      return this.textarea.value;
    },
    getValue: function () {
      return this.textarea.value;
    },
    setValue: function (code)  {
      this.textarea.value = code;
    },
    focus: noop,
    getCursor: function () {
      return { line: 0, ch: 0 };
    },
    setCursor: noop,
    currentLine: function () {
      return 0;
    },
    cursorPosition: function () {
      return { character: 0 };
    },
    nthLine: noop,
    refresh: noop,
    selectLines: noop,
    on: noop
  };

  CodeMirror = function () {};

  CodeMirror.fromTextArea = function (el, options) {
      return new Editor(el, options);
  };

  CodeMirror.keyMap = { basic: {} };

}<|endoftext|>


<commit_before>var config = {};

//Overall environment settings are stored under config.env
config.env = {};
config.env.prod = (process.env.NODE_ENV === 'production') ? 'production' : null;

var LOCAL_HOST = 'localhost';
var DEV_HOST = 'dev.bridgeit.io';
var PROD_HOST = 'api.bridgeit.mobi';

config.env.host = DEV_HOST;
if (process.env.BRIDGEIT_HOST) {
    config.env.host = process.env.BRIDGEIT_HOST;
}

//Communication between services on either the dev or prod environments should use
//this proxy as the host instead.
config.env.proxyHost = 'web1';

//Everything related to this specific service.  Many of these should be overridden in the
//service's own specific config.js file.
config.service = {};
config.service.name = 'defaultServiceName';
config.service.scheme = 'http';
config.service.host = config.env.host;
config.service.port = 55555;
config.service.resourcePort = config.env.host === LOCAL_HOST ? config.service.port : '';
config.service.referrer = config.service.scheme + '://' + config.service.host;
config.service.path = '/' + config.service.name;
config.service.server = 'Service description not provided';
config.service.desc = config.service.server;
config.service.version = '1.0.0';

//Information for communicating with the Notification service.
config.notify = {};
config.notify.scheme = 'http';
config.notify.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.notify.port = config.env.host === LOCAL_HOST ? ':8080' : '';
config.notify.path = '/push/rest';
config.notify.url = config.notify.scheme + '://' + config.notify.host + config.notify.port + config.notify.path;
config.notify.referrer = config.notify.scheme + '://' + config.notify.host + config.notify.port + '/' + config.service.name;

//Information for communicating with the MongoDB service.
config.database = {};
config.database.scheme = 'mongodb';
config.database.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : 'db1';
config.database.port = 27017;

//TODO: database.path and database.url should likely be removed give we know make connections
//to databases using our own strategy based on account name rather than service.
config.database.path = config.service.name;
config.database.url = config.database.scheme + '://' + config.database.host + ':' + config.database.port + '/' + config.database.path;

config.database.clientExpiry = 1800000;
config.database.sharedConnections = false;

//Information for communicating with the Auth service.
config.auth = {};
config.auth.scheme = 'http';
config.auth.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.auth.port = config.env.host === LOCAL_HOST ? ':55010' : '';
config.auth.path = '/auth';
config.auth.url = config.auth.scheme + '://' + config.auth.host + config.auth.port + config.auth.path;
config.auth.enabled = config.env.prod ? true : false;

//Information for communicating with the Metrics service.
config.metrics = {};
config.metrics.scheme = 'http';
config.metrics.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.metrics.port = config.env.host === LOCAL_HOST ? ':55040' : '';
config.metrics.path = '/metrics';
config.metrics.url = config.metrics.scheme + '://' + config.metrics.host + config.metrics.port + config.metrics.path;
config.metrics.enabled = config.env.prod ? true : false;

//Information for communicating with the Docs service.
config.doc = {};
config.doc.scheme = 'http';
config.doc.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.doc.port = config.env.host === LOCAL_HOST ? ':55080' : '';
config.doc.path = '/docs';
config.doc.url = config.doc.scheme + '://' + config.doc.host + config.doc.port + config.doc.path;

//Information for communicating with the Locate service.
config.locate = {};
config.locate.scheme = 'http';
config.locate.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.locate.port = config.env.host === LOCAL_HOST ? ':55020' : '';
config.locate.path = '/locate';
config.locate.url = config.locate.scheme + '://' + config.locate.host + config.locate.port + config.locate.path;

//Information for communicating with the Context service.
config.context = {};
config.context.scheme = 'http';
config.context.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.context.port = config.env.host === LOCAL_HOST ? ':55060' : '';
config.context.path = '/context';
config.context.url = config.context.scheme + '://' + config.context.host + config.context.port + config.context.path;

//Default CORS settings.
config.cors = {};
//config.cors.path = '/\.*/';
config.cors.origin = '*';
config.cors.methods = 'GET, POST, DELETE, PUT';
config.cors.headers = 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, If-Unmodified-Since, X-File-Name, Cache-Control, Origin, X-HTTP-Method-Override, Accept, Authorization, X-Pingother, If-Match, If-None-Match ';

//Default logging settings.
config.logging = {};
config.logging.logName = "defaultLogger";
config.logging.logFile = __dirname + '/' + config.service.name + '.log';
config.logging.logLevel = config.env.prod ? 'info' : 'debug';
config.logging.defaults = {
    logName: config.logging.logName,
    logFile: config.logging.logFile,
    logLevel: config.logging.logLevel
};

//Export the config object so that services can use it and override as required.
module.exports = config;

//Configuration settings that rely on being calculated from other values should
//be added to this function.  Whenever one or more configuration values are updated,
//this function should be called to ensure all the values are properly re-evaluated.
//While this is not terribly elegant or efficient, it is fairly simple, compatible with
//what we have and retains the high degree of readability for all the settings.  Since
//the configuration typically only gets modified once when the service is first started
//up, the impact is minimal.  Settings that rely on the config.env properties should
//not be recalculated or they cannot be overridden.
function reconfigure() {

    config.service.path = '/' + config.service.name;
    config.service.resourcePort = config.env.host === LOCAL_HOST ? config.service.port : '';

    config.notify.url = config.notify.scheme + '://' + config.notify.host + config.notify.port + config.notify.path;
    config.notify.referrer = config.notify.scheme + '://' + config.notify.host + config.notify.port + '/' + config.service.name;

    config.database.path = config.service.name;
    config.database.url = config.database.scheme + '://' + config.database.host + ':' + config.database.port + '/' + config.database.path;

    config.auth.url = config.auth.scheme + '://' + config.auth.host + config.auth.port + config.auth.path;

    config.doc.url = config.doc.scheme + '://' + config.doc.host + config.doc.port + config.doc.path;

    config.locate.url = config.locate.scheme + '://' + config.locate.host + config.locate.port + config.locate.path;

    config.context.url = config.context.scheme + '://' + config.context.host + config.context.port + config.context.path;

    config.metrics.url = config.metrics.scheme + '://' + config.metrics.host + config.metrics.port + config.metrics.path;

    config.logging.defaults = {
        logName: config.logging.logName,
        logFile: config.logging.logFile,
        logLevel: config.logging.logLevel
    };

}
module.exports.reconfigure = reconfigure;
<commit_msg>NTFY-192: add the record return limit value to the configuration file<commit_after>var config = {};

//Overall environment settings are stored under config.env
config.env = {};
config.env.prod = (process.env.NODE_ENV === 'production') ? 'production' : null;

var LOCAL_HOST = 'localhost';
var DEV_HOST = 'dev.bridgeit.io';
var PROD_HOST = 'api.bridgeit.mobi';

config.env.host = DEV_HOST;
if (process.env.BRIDGEIT_HOST) {
    config.env.host = process.env.BRIDGEIT_HOST;
}

//Communication between services on either the dev or prod environments should use
//this proxy as the host instead.
config.env.proxyHost = 'web1';

//Everything related to this specific service.  Many of these should be overridden in the
//service's own specific config.js file.
config.service = {};
config.service.name = 'defaultServiceName';
config.service.scheme = 'http';
config.service.host = config.env.host;
config.service.port = 55555;
config.service.resourcePort = config.env.host === LOCAL_HOST ? config.service.port : '';
config.service.referrer = config.service.scheme + '://' + config.service.host;
config.service.path = '/' + config.service.name;
config.service.server = 'Service description not provided';
config.service.desc = config.service.server;
config.service.version = '1.0.0';

//Information for communicating with the Notification service.
config.notify = {};
config.notify.scheme = 'http';
config.notify.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.notify.port = config.env.host === LOCAL_HOST ? ':8080' : '';
config.notify.path = '/push/rest';
config.notify.url = config.notify.scheme + '://' + config.notify.host + config.notify.port + config.notify.path;
config.notify.referrer = config.notify.scheme + '://' + config.notify.host + config.notify.port + '/' + config.service.name;

//Information for communicating with the MongoDB service.
config.database = {};
config.database.scheme = 'mongodb';
config.database.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : 'db1';
config.database.port = 27017;

//TODO: database.path and database.url should likely be removed give we know make connections
//to databases using our own strategy based on account name rather than service.
config.database.path = config.service.name;
config.database.url = config.database.scheme + '://' + config.database.host + ':' + config.database.port + '/' + config.database.path;

config.database.clientExpiry = 1800000;
config.database.sharedConnections = false;

//Information for communicating with the Auth service.
config.auth = {};
config.auth.scheme = 'http';
config.auth.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.auth.port = config.env.host === LOCAL_HOST ? ':55010' : '';
config.auth.path = '/auth';
config.auth.url = config.auth.scheme + '://' + config.auth.host + config.auth.port + config.auth.path;
config.auth.enabled = config.env.prod ? true : false;

//Information for communicating with the Metrics service.
config.metrics = {};
config.metrics.scheme = 'http';
config.metrics.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.metrics.port = config.env.host === LOCAL_HOST ? ':55040' : '';
config.metrics.path = '/metrics';
config.metrics.url = config.metrics.scheme + '://' + config.metrics.host + config.metrics.port + config.metrics.path;
config.metrics.enabled = config.env.prod ? true : false;

//Information for communicating with the Docs service.
config.doc = {};
config.doc.scheme = 'http';
config.doc.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.doc.port = config.env.host === LOCAL_HOST ? ':55080' : '';
config.doc.path = '/docs';
config.doc.url = config.doc.scheme + '://' + config.doc.host + config.doc.port + config.doc.path;

//Information for communicating with the Locate service.
config.locate = {};
config.locate.scheme = 'http';
config.locate.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.locate.port = config.env.host === LOCAL_HOST ? ':55020' : '';
config.locate.path = '/locate';
config.locate.url = config.locate.scheme + '://' + config.locate.host + config.locate.port + config.locate.path;

//Information for communicating with the Context service.
config.context = {};
config.context.scheme = 'http';
config.context.host = config.env.host === LOCAL_HOST ? LOCAL_HOST : config.env.proxyHost;
config.context.port = config.env.host === LOCAL_HOST ? ':55060' : '';
config.context.path = '/context';
config.context.url = config.context.scheme + '://' + config.context.host + config.context.port + config.context.path;

//Configuration defaults for the CRUD related features.
config.crud = {};
config.crud.defaultLimit = 100;

//Default CORS settings.
config.cors = {};
//config.cors.path = '/\.*/';
config.cors.origin = '*';
config.cors.methods = 'GET, POST, DELETE, PUT';
config.cors.headers = 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, If-Unmodified-Since, X-File-Name, Cache-Control, Origin, X-HTTP-Method-Override, Accept, Authorization, X-Pingother, If-Match, If-None-Match ';

//Default logging settings.
config.logging = {};
config.logging.logName = "defaultLogger";
config.logging.logFile = __dirname + '/' + config.service.name + '.log';
config.logging.logLevel = config.env.prod ? 'info' : 'debug';
config.logging.defaults = {
    logName: config.logging.logName,
    logFile: config.logging.logFile,
    logLevel: config.logging.logLevel
};

//Export the config object so that services can use it and override as required.
module.exports = config;

//Configuration settings that rely on being calculated from other values should
//be added to this function.  Whenever one or more configuration values are updated,
//this function should be called to ensure all the values are properly re-evaluated.
//While this is not terribly elegant or efficient, it is fairly simple, compatible with
//what we have and retains the high degree of readability for all the settings.  Since
//the configuration typically only gets modified once when the service is first started
//up, the impact is minimal.  Settings that rely on the config.env properties should
//not be recalculated or they cannot be overridden.
function reconfigure() {

    config.service.path = '/' + config.service.name;
    config.service.resourcePort = config.env.host === LOCAL_HOST ? config.service.port : '';

    config.notify.url = config.notify.scheme + '://' + config.notify.host + config.notify.port + config.notify.path;
    config.notify.referrer = config.notify.scheme + '://' + config.notify.host + config.notify.port + '/' + config.service.name;

    config.database.path = config.service.name;
    config.database.url = config.database.scheme + '://' + config.database.host + ':' + config.database.port + '/' + config.database.path;

    config.auth.url = config.auth.scheme + '://' + config.auth.host + config.auth.port + config.auth.path;

    config.doc.url = config.doc.scheme + '://' + config.doc.host + config.doc.port + config.doc.path;

    config.locate.url = config.locate.scheme + '://' + config.locate.host + config.locate.port + config.locate.path;

    config.context.url = config.context.scheme + '://' + config.context.host + config.context.port + config.context.path;

    config.metrics.url = config.metrics.scheme + '://' + config.metrics.host + config.metrics.port + config.metrics.path;

    config.logging.defaults = {
        logName: config.logging.logName,
        logFile: config.logging.logFile,
        logLevel: config.logging.logLevel
    };

}
module.exports.reconfigure = reconfigure;
<|endoftext|>


<commit_before>var dest = "./build";
var src = './src';
var port = 3000;

module.exports = {
    nodemon: {
        script: './server.js',
        ext: 'js',
        ignore: ['build/*', 'node_modules/*'],
        env: {
            'NODE_ENV': 'development',
            'DEBUG': 'Server',
            'PORT': port
        }
    },
    browserSync: {
        // Don't use browsersync's static browser.
        // We just proxy into the actual server.js here.
        proxy: 'localhost:' + port,
        port: port + 1,
        notify: false,
        open: false
    },
    sass: {
        src: src + "/sass/**/*.{sass,scss}",
        dest: dest + "/css",
        settings: {
            // Required if you want to use SASS syntax
            // See https://github.com/dlmanning/gulp-sass/issues/81
            sourceComments: 'map',
            imagePath: '/images' // Used by the image-url helper
        }
    },
    images: {
        src: src + "/images/**",
        dest: dest + "/images"
    },
    markup: {
        src: src + "/html/**/*.html",
        dest: dest
    },
    browserify: {
        // A separate bundle will be generated for each
        // bundle config in the list below
        bundleConfigs: [{
            entries: src + '/javascript/client.js',
            dest: dest + '/js',
            outputName: 'client.js',
            extensions: ['.js', '.jsx']
        }]
    },
    production: {
        cssSrc: dest + '/css/*.css',
        jsSrc: dest + '/js/*.js',
        dest: dest
    },
    heroku: {
        development: {
            branch: 'dev',
            remoteName: 'dev',
            remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_DEV.git',
            website: 'http://HEROKU_APP_NAME_DEV.herokuapp.com'
        },
        staging: {
            branch: 'staging',
            remoteName: 'staging',
            remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_STAGING.git',
            website: 'http://HEROKU_APP_NAME_STAGING.herokuapp.com'
        },
        production: {
            branch: 'master',
            remoteName: 'prod',
            remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_PRODUCTION.git',
            website: 'http://HEROKU_APP_NAME_PRODUCTION.herokuapp.com'
        }
    },
    settings: {
        src: './settings.json',
        dest: dest
    }
};
<commit_msg>Ensure nodemon restarts on jsx file changes<commit_after>var dest = "./build";
var src = './src';
var port = 3000;

module.exports = {
    nodemon: {
        script: './server.js',
        ext: 'js,jsx',
        ignore: ['build/*', 'node_modules/*'],
        env: {
            'NODE_ENV': 'development',
            'DEBUG': 'Server',
            'PORT': port
        }
    },
    browserSync: {
        // Don't use browsersync's static browser.
        // We just proxy into the actual server.js here.
        proxy: 'localhost:' + port,
        port: port + 1,
        notify: false,
        open: false
    },
    sass: {
        src: src + "/sass/**/*.{sass,scss}",
        dest: dest + "/css",
        settings: {
            // Required if you want to use SASS syntax
            // See https://github.com/dlmanning/gulp-sass/issues/81
            sourceComments: 'map',
            imagePath: '/images' // Used by the image-url helper
        }
    },
    images: {
        src: src + "/images/**",
        dest: dest + "/images"
    },
    markup: {
        src: src + "/html/**/*.html",
        dest: dest
    },
    browserify: {
        // A separate bundle will be generated for each
        // bundle config in the list below
        bundleConfigs: [{
            entries: src + '/javascript/client.js',
            dest: dest + '/js',
            outputName: 'client.js',
            extensions: ['.js', '.jsx']
        }]
    },
    production: {
        cssSrc: dest + '/css/*.css',
        jsSrc: dest + '/js/*.js',
        dest: dest
    },
    heroku: {
        development: {
            branch: 'dev',
            remoteName: 'dev',
            remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_DEV.git',
            website: 'http://HEROKU_APP_NAME_DEV.herokuapp.com'
        },
        staging: {
            branch: 'staging',
            remoteName: 'staging',
            remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_STAGING.git',
            website: 'http://HEROKU_APP_NAME_STAGING.herokuapp.com'
        },
        production: {
            branch: 'master',
            remoteName: 'prod',
            remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_PRODUCTION.git',
            website: 'http://HEROKU_APP_NAME_PRODUCTION.herokuapp.com'
        }
    },
    settings: {
        src: './settings.json',
        dest: dest
    }
};
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.min.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
        'public/lib/angular-ui-grid/ui-grid.min.css'
      ],
      js: [
        'public/lib/angular/angular.min.js',
        'public/lib/angular-resource/angular-resource.min.js',
        'public/lib/angular-animate/angular-animate.min.js',
        'public/lib/angular-messages/angular-messages.min.js',
        'public/lib/angular-ui-router/release/angular-ui-router.min.js',
        'public/lib/angular-ui-utils/ui-utils.min.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
        'public/lib/angular-file-upload/angular-file-upload.min.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/angular-ui-grid/ui-grid.min.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js'
  }
};
<commit_msg>change config<commit_after>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.min.css',
        'public/lib/angular-ui-grid/ui-grid.min.css'
      ],
      js: [
        'public/lib/angular/angular.min.js',
        'public/lib/angular-resource/angular-resource.min.js',
        'public/lib/angular-animate/angular-animate.min.js',
        'public/lib/angular-messages/angular-messages.min.js',
        'public/lib/angular-ui-router/release/angular-ui-router.min.js',
        'public/lib/angular-ui-utils/ui-utils.min.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
        'public/lib/angular-file-upload/angular-file-upload.min.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/angular-ui-grid/ui-grid.min.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js'
  }
};
<|endoftext|>


<commit_before>/**
* Scavenger hunts plugin. Only works in a room with the id 'scavengers'.
* This game shows a hint. Once a player submits the correct answer, they move on to the next hint.
* You finish upon correctly answering the third hint.
* In an official hunt, the first three to finish within 60 seconds achieve blitz.
*/

var scavengers = {
	status: 'off',
	blitz: null,
	hints: null,
	answers: null,
	participants: {},
	finished: [],
	result: null
};

var scavengersRoom = Rooms.get('scavengers');
if (scavengersRoom) {
	if (scavengersRoom.plugin) {
		scavengers = scavengersRoom.plugin;
	} else {
		scavengersRoom.plugin = scavengers;
	}
}

exports.commands = {
	scavenger: 'scavengers',
	scavengers: function (target, room, user) {
		return this.parse('/join scavengers');
	},
	startofficialhunt: 'starthunt',
	starthunt: function (target, room, user, connection, cmd) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (!this.can('mute', null, room)) return false;
		if (scavengers.status === 'on') return this.errorReply('There is already an active scavenger hunt.');
		var targets = target.split(target.includes('|') ? '|' : ',');
		if (!targets[0] || !targets[1] || !targets[2] || !targets[3] || !targets[4] || !targets[5] || targets[6]) {
			return this.errorReply('You must specify three hints and three answers.');
		}
		if (cmd === 'startofficialhunt') {
			if (!this.can('ban', null, room)) return false;
			scavengers.blitz = setTimeout(function () {
				scavengers.blitz = null;
			}, 60000);
		}
		scavengers.status = 'on';
		scavengers.hints = [targets[0].trim(), targets[2].trim(), targets[4].trim()];
		scavengers.answers = [toId(targets[1]), toId(targets[3]), toId(targets[5])];
		var result = (cmd === 'startofficialhunt' ? 'An official' : 'A new') + ' Scavenger Hunt has been started by  ' + Tools.escapeHTML(user.name) + '! The first hint is: ' + Tools.escapeHTML(scavengers.hints[0]);
		Rooms.rooms.scavengers.addRaw('
' + result + '
');
	},
	joinhunt: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		if (user.userid in scavengers.participants) return this.errorReply('You are already participating in the current scavenger hunt.');
		scavengers.participants[user.userid] = {room: 0};
		this.sendReply('You joined the scavenger hunt! Use the command /scavenge to answer. The first hint is: ' + scavengers.hints[0]);
	},
	scavenge: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		if (!scavengers.participants[user.userid]) return this.errorReply('You are not participating in the current scavenger hunt. Use the command /joinhunt to participate.');
		if (scavengers.participants[user.userid].room >= 3) return this.sendReply('You have already finished!');
		target = toId(target);
		var roomnum = scavengers.participants[user.userid].room;
		if (scavengers.answers[roomnum] === target) {
			scavengers.participants[user.userid].room++;
			roomnum++;
			if (roomnum < 3) {
				this.sendReply('Well done! Your ' + (roomnum === 1 ? 'second' : 'final') + ' hint is: ' + scavengers.hints[roomnum]);
			} else {
				scavengers.finished.push(user.name);
				var position = scavengers.finished.length;
				var result = '' + Tools.escapeHTML(user.name) + ' has finished the hunt ';
				result += (position === 1) ? 'and is the winner!' : (position === 2) ? 'in 2nd place!' : (position === 3) ? 'in 3rd place!' : 'in ' + position + 'th place!';
				result += (position < 4 && scavengers.blitz ? ' [BLITZ]' : '');
				Rooms.rooms.scavengers.addRaw('
' + result + '
');
			}
		} else {
			this.sendReply('That is not the answer - try again!');
		}
	},
	scavengerhint: 'scavengerstatus',
	scavengerstatus: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		if (!scavengers.participants[user.userid]) return this.errorReply('You are not participating in the current scavenger hunt. Use the command /joinhunt to participate.');
		if (scavengers.participants[user.userid].room >= 3) return this.sendReply('You have finished the current scavenger hunt.');
		var roomnum = scavengers.participants[user.userid].room;
		this.sendReply('You are on hint number ' + (roomnum + 1) + ': ' + scavengers.hints[roomnum]);
	},
	endhunt: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (!this.can('mute', null, room)) return false;
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		var winner = scavengers.finished[0];
		var second = scavengers.finished[1];
		var third = scavengers.finished[2];
		var consolation = scavengers.finished.slice(3).join(', ');
		var msg = 'The Scavenger Hunt was ended by ' + Tools.escapeHTML(user.name) + '. ';
		if (winner) {
			msg += '
Winner: ' + Tools.escapeHTML(winner) + '.';
			if (second) msg += ' Second place: ' + Tools.escapeHTML(second) + '.';
			if (third) msg += ' Third place: ' + Tools.escapeHTML(third) + '.';
			if (consolation) msg += ' Consolation prize to: ' + Tools.escapeHTML(consolation) + '.';
		} else {
			msg += 'No user has completed the hunt.';
		}
		msg += '
Solution: ' + Tools.escapeHTML(scavengers.answers.join(', ')) + '.';
		scavengers.result = msg;
		this.parse('/resethunt');
	},
	resethunt: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (!this.can('mute', null, room)) return false;
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		scavengers.status = 'off';
		if (scavengers.blitz) clearTimeout(scavengers.blitz);
		scavengers.blitz = null;
		scavengers.hints = null;
		scavengers.answers = null;
		scavengers.participants = {};
		scavengers.finished = [];
		if (scavengers.result) {
			Rooms.rooms.scavengers.addRaw('
' + scavengers.result + '
');
		} else {
			Rooms.rooms.scavengers.addRaw('
The Scavenger Hunt was reset by ' + Tools.escapeHTML(user.name) + '.
');
		}
		scavengers.result = null;
	},
	scavengershelp: 'scavengerhelp',
	scavengerhelp: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (!this.canBroadcast()) return;
		this.sendReplyBox(
			'Player commands:
' +
			'- /scavengers - Join the scavengers room
' +
			'- /joinhunt - Join the current scavenger hunt
' +
			'- /scavenge guess - Attempt to answer the hint
' +
			'- /scavengerstatus - Get your current game status
' +
			'
' +
			'Staff commands:
' +
			'- /starthunt hint, answer, hint, answer, hint, answer - Start a new scavenger hunt (Requires: % @ # & ~)
' +
			'- /startofficialhunt hint, answer, hint, answer, hint, answer - Start an official hunt with 60 seconds blitz period (Requires: @ # & ~)
' +
			'- /endhunt - Finish the current hunt and announce the winners (Requires: % @ # & ~)
' +
			'- /resethunt - Reset the scavenger hunt to mint status (Requires: % @ # & ~)'
		);
	}
};
<commit_msg>Delete scavengers.js<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router';

import Pagination from "../../components/Pagination";
import OrganizationStore from "../../stores/OrganizationStore";
import SessionStore from "../../stores/SessionStore";

class OrganizationRow extends Component {
  render() {
    return(

        {this.props.organization.id}
        <Link to={`/organizations/${this.props.organization.id}`}>{this.props.organization.name}</Link>
        {this.props.organization.displayName}

    );
  }
}

class ListOrganizations extends Component {
  constructor() {
    super();

    this.state = {
      pageSize: 20,
      organizations: [],
      isAdmin: false,
      pageNumber: 1,
      pages: 1,
    };

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

  componentDidMount() {
    this.updatePage(this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.updatePage(nextProps);
  }

  updatePage(props) {
    const page = (props.location.query.page === undefined) ? 1 : props.location.query.page;

    OrganizationStore.getAll("", this.state.pageSize, (page-1) * this.state.pageSize, (totalCount, organizations) => {
      this.setState({
    	organizations: organizations,
        pageNumber: page,
        pages: Math.ceil(totalCount / this.state.pageSize),
      });
      window.scrollTo(0, 0);
    });
  }

  componentWillMount() {
    this.setState({
      isAdmin: SessionStore.isAdmin(),
    });

    SessionStore.on("change", () => {
      this.setState({
        isAdmin: SessionStore.isAdmin(),
      });
    });
  }

  render () {
    const OrganizationRows = this.state.organizations.map((organization, i) => <OrganizationRow key={organization.id} organization={organization} />);

    return(

Organizations

              <Link to="/organizations/create"><button type="button" className="btn btn-default">Create organization</button></Link>

                  ID
                  Name
                  Display name
                  Can have gateways

                {OrganizationRows}

          <Pagination pages={this.state.pages} currentPage={this.state.pageNumber} pathname="/" />

    );
  }
}

export default ListOrganizations;
<commit_msg>Fix organization pagination (UI).<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router';

import Pagination from "../../components/Pagination";
import OrganizationStore from "../../stores/OrganizationStore";
import SessionStore from "../../stores/SessionStore";

class OrganizationRow extends Component {
  render() {
    return(

        {this.props.organization.id}
        <Link to={`/organizations/${this.props.organization.id}`}>{this.props.organization.name}</Link>
        {this.props.organization.displayName}

    );
  }
}

class ListOrganizations extends Component {
  constructor() {
    super();

    this.state = {
      pageSize: 20,
      organizations: [],
      isAdmin: false,
      pageNumber: 1,
      pages: 1,
    };

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

  componentDidMount() {
    this.updatePage(this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.updatePage(nextProps);
  }

  updatePage(props) {
    const page = (props.location.query.page === undefined) ? 1 : props.location.query.page;

    OrganizationStore.getAll("", this.state.pageSize, (page-1) * this.state.pageSize, (totalCount, organizations) => {
      this.setState({
    	organizations: organizations,
        pageNumber: page,
        pages: Math.ceil(totalCount / this.state.pageSize),
      });
      window.scrollTo(0, 0);
    });
  }

  componentWillMount() {
    this.setState({
      isAdmin: SessionStore.isAdmin(),
    });

    SessionStore.on("change", () => {
      this.setState({
        isAdmin: SessionStore.isAdmin(),
      });
    });
  }

  render () {
    const OrganizationRows = this.state.organizations.map((organization, i) => <OrganizationRow key={organization.id} organization={organization} />);

    return(

Organizations

              <Link to="/organizations/create"><button type="button" className="btn btn-default">Create organization</button></Link>

                  ID
                  Name
                  Display name
                  Can have gateways

                {OrganizationRows}

          <Pagination pages={this.state.pages} currentPage={this.state.pageNumber} pathname="organizations" />

    );
  }
}

export default ListOrganizations;
<|endoftext|>


<commit_before>// @flow
import React from "react"
import Typography from "@material-ui/core/Typography"
import Grid from "@material-ui/core/Grid"
import ListItem from "@material-ui/core/ListItem"
import useStyles from "../styles"

type Props = {
  data: {
    /** Type of content to display (i.e. Strain Descriptor, Genotypes, etc.) */
    title: string,
    /** The actual data for that field */
    content: string,
  },
}

const DetailsListItem = ({ data }: Props) => {
  const classes = useStyles()

  return (
    <ListItem className={classes.details} divider>
      <Grid item xs={3} className={classes.listTitle}>
        <Typography variant="body2">{data.title}</Typography>
      </Grid>
      <Grid item xs={9} className={classes.listContent}>
        {data.content}
      </Grid>
    </ListItem>
  )
}

export default DetailsListItem
<commit_msg>refactor: use Typography for both parts of details list item<commit_after>// @flow
import React from "react"
import Typography from "@material-ui/core/Typography"
import Grid from "@material-ui/core/Grid"
import ListItem from "@material-ui/core/ListItem"
import useStyles from "../styles"

type Props = {
  data: {
    /** Type of content to display (i.e. Strain Descriptor, Genotypes, etc.) */
    title: string,
    /** The actual data for that field */
    content: string,
  },
}

const DetailsListItem = ({ data }: Props) => {
  const classes = useStyles()

  return (
    <ListItem className={classes.details} divider>
      <Grid item xs={3} className={classes.listTitle}>
        <Typography variant="body2">{data.title}</Typography>
      </Grid>
      <Grid item xs={9} className={classes.listContent}>
        <Typography variant="body1">{data.content}</Typography>
      </Grid>
    </ListItem>
  )
}

export default DetailsListItem
<|endoftext|>


<commit_before>
module.exports = readJson
readJson.processJson = processJson
readJson.unParsePeople = unParsePeople
readJson.parsePeople = parsePeople

var fs = require("./graceful-fs")
  , semver = require("./semver")
  , path = require("path")
  , log = require("./log")
  , npm = require("../../npm")
  , cache = {}
  , timers = {}
function readJson (jsonFile, opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (cache.hasOwnProperty(jsonFile)) {
    log.verbose(jsonFile, "from cache")
    return cb(null, cache[jsonFile])
  }
  fs.readFile(path.join(path.dirname(jsonFile), "wscript"), function (er, data) {
    opts.file = jsonFile
    if (er) opts.wscript = false
    else opts.wscript = data.toString().match(/(^|\n)def build\b/)
                      && data.toString().match(/(^|\n)def configure\b/)
    fs.readFile(jsonFile, processJson(opts, cb))
  })
}
function processJson (opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (typeof cb !== "function") {
    var thing = cb, cb = null
    return P(null, thing)
  } else return P

  function P (er, thing) {
    if (er) {
      if (cb) return cb(er, thing)
      throw er
    }
    if (typeof thing === "object" && !Buffer.isBuffer(thing)) {
      return processObject(opts, cb)(er, thing)
    } else {
      return processJsonString(opts, cb)(er, thing)
    }
  }
}
function processJsonString (opts, cb) { return function (er, jsonString) {
  jsonString += ""
  if (er) return cb(er, jsonString)
  var json
  try {
    json = JSON.parse(jsonString)
  } catch (ex2) { try {
    json = process.binding("evals").Script.runInNewContext("(\n"+jsonString+"\n)")
  } catch (ex) {
    var e = new Error(
      "Failed to parse json\n"+ex.message+"\n"+ex2.message+"\n"+jsonString)
    if (cb) return cb(e)
    throw e
  }}
  return processObject(opts, cb)(er, json)
}}
function processObject (opts, cb) { return function (er, json) {
  if (json.overlay) {
    ;["node", "npm"].forEach(function (k) {
      if (!json.overlay[k]) return undefined
      for (var i in json.overlay[k]) json[i] = json.overlay[k][i]
    })
  }

  // slashes would be a security risk.
  // anything else will just fail harmlessly.
  if (!json.name) {
    var e = new Error("No 'name' field found in package.json")
    if (cb) return cb(e)
    throw e
  }
  json.name = json.name.trim()
  if (json.name.charAt(0) === "." || json.name.match(/[\/@\s]/)) {
    var msg = "Invalid name: "
            + JSON.stringify(json.name)
            + " may not start with '.' or contain '/' or '@' or whitespace"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  var tag = opts.tag
  if (tag && tag.indexOf(json.version) === 0) {
    tag = tag.substr(json.version.length)
  }
  if (tag && tag.indexOf("-1-LINK") !== -1) {
    tag = tag.substr(tag.indexOf("-1-LINK"))
  }
  if (tag && semver.valid(json.version + tag)) {
    json.version += tag
  }

  // FIXME: uncomment in 0.3.0, once it's not likely that people will
  // have a bunch of main.js files kicking around any more, and remove
  // this functionality from lib/build.js
  //
  // if (json.main) {
  //   if (!json.modules) json.modules = {}
  //   json.modules.index = json.main
  //   delete json.main
  // }

  if (opts.wscript) {
    var scripts = json.scripts = json.scripts || {}
    if (!scripts.install && !scripts.preinstall) {
      // don't fail if it was unexpected, just try.
      scripts.preinstall = "node-waf configure build"
    }
  }

  if (!(semver.valid(json.version))) {
    var e = new Error("Invalid version: "+json.version+"\n"
                     +"Must be X.Y.Z, with an optional trailing tag.\n"
                     +"See the section on 'version' in `npm help json`"
                     )
    if (cb) return cb(e)
    throw e
  }
  json.version = semver.clean(json.version)

  if (json.main) json.main = json.main.replace(/(\.js|\.node)$/, '')

  if (json.bin && typeof json.bin === "string") {
    var b = {}
    b[ path.basename( json.bin ) ] = json.bin
    json.bin = b
  }

  if (json["dev-dependencies"] && !json.devDependencies) {
    json.devDependencies = json["dev-dependencies"]
    delete json["dev-dependencies"]
  }
  ;["dependencies", "devDependencies"].forEach(function (d) {
    if (!json[d]) return
    json[d] = depObjectify(json[d])
  })

  json._id = json.name+"@"+json.version
  json = testEngine(json)
  json = parsePeople(json)
  json._npmVersion = npm.version
  json._nodeVersion = process.version
  if (opts.file) {
    log.verbose(opts.file, "caching")
    cache[opts.file] = json
    // just in case this is a long-running process...
    if (timers[opts.file]) clearTimeout(timers[opts.file])
    timers[opts.file] = setTimeout(function () {
      delete cache[opts.file]
      delete timers[opts.file]
    }, 1000 * 60 * 60 * 24)
  }
  if (cb) cb(null,json)
  return json
}}
function depObjectify (deps) {
  if (!Array.isArray(deps)) return deps
  var o = {}
  deps.forEach(function (d) {
    d = d.trim().split(/(:?[@\s><=])/)
    o[d.shift()] = d.join("").trim().replace(/^@/, "")
  })
  return o
}
function testEngine (json) {
  // if engines is empty, then assume that node is allowed.
  log.silly(json, "testEngine")
  if ( !json.engines
      || Array.isArray(json.engines)
        && !json.engines.length
      || typeof json.engines === "object"
        && !Object.keys(json.engines).length
      ) {
    json.engines = { "node" : "*" }
  }
  if (typeof json.engines === "string") {
    if (semver.validRange(json.engines) !== null) {
      json.engines = { "node" : json.engines }
    } else json.engines = [ json.engines ]
  }

  var nodeVer = process.version.replace(/\+$/, '')
    , ok = false
  if (Array.isArray(json.engines)) {
    // Packages/1.0 commonjs style, with an array.
    // hack it to just hang a "node" member with the version range,
    // then do the npm-style check below.
    for (var i = 0, l = json.engines.length; i < l; i ++) {
      var e = json.engines[i].trim()
      if (e.substr(0, 4) === "node") {
        json.engines.node = e.substr(4)
        break
      }
    }
  }
  if (json.engines.node === "") json.engines.node = "*"
  if (json.engines.node && null === semver.validRange(json.engines.node)) {
    log.warn(json.engines.node, "not a valid range.  Please see `npm help json`")
  }
  json._nodeSupported = semver.satisfies(nodeVer, json.engines.node || "undefined")
  return json
}

function unParsePeople (json) { return parsePeople(json, true) }
function parsePeople (json, un) {
  var fn = un ? unParsePerson : parsePerson
  if (json.author) json.author = fn(json.author)
  ;["maintainers", "contributors"].forEach(function (set) {
    if (Array.isArray(json[set])) json[set] = json[set].map(fn)
  })
  return json
}
function unParsePerson (person) {
  if (typeof person === "string") return person
  var name = person.name
    , url = person.url ? (" ("+person.url+")") : ""
    , email = person.email ? (" <"+person.email+">") : ""
  return name+email+url
}
function parsePerson (person) {
  if (typeof person !== "string") return person
  var name = person.match(/^([^\(<]+)/)
    , url = person.match(/\(([^\)]+)\)/)
    , email = person.match(/<([^>]+)>/)
    , obj = { "name" : (name && name[0] || person).trim() }
  if (email) obj.email = email[1]
  if (url) obj.url = url[1]
  return obj
}
<commit_msg>Don't allow + in package names.<commit_after>
module.exports = readJson
readJson.processJson = processJson
readJson.unParsePeople = unParsePeople
readJson.parsePeople = parsePeople

var fs = require("./graceful-fs")
  , semver = require("./semver")
  , path = require("path")
  , log = require("./log")
  , npm = require("../../npm")
  , cache = {}
  , timers = {}
function readJson (jsonFile, opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (cache.hasOwnProperty(jsonFile)) {
    log.verbose(jsonFile, "from cache")
    return cb(null, cache[jsonFile])
  }
  fs.readFile(path.join(path.dirname(jsonFile), "wscript"), function (er, data) {
    opts.file = jsonFile
    if (er) opts.wscript = false
    else opts.wscript = data.toString().match(/(^|\n)def build\b/)
                      && data.toString().match(/(^|\n)def configure\b/)
    fs.readFile(jsonFile, processJson(opts, cb))
  })
}
function processJson (opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (typeof cb !== "function") {
    var thing = cb, cb = null
    return P(null, thing)
  } else return P

  function P (er, thing) {
    if (er) {
      if (cb) return cb(er, thing)
      throw er
    }
    if (typeof thing === "object" && !Buffer.isBuffer(thing)) {
      return processObject(opts, cb)(er, thing)
    } else {
      return processJsonString(opts, cb)(er, thing)
    }
  }
}
function processJsonString (opts, cb) { return function (er, jsonString) {
  jsonString += ""
  if (er) return cb(er, jsonString)
  var json
  try {
    json = JSON.parse(jsonString)
  } catch (ex2) { try {
    json = process.binding("evals").Script.runInNewContext("(\n"+jsonString+"\n)")
  } catch (ex) {
    var e = new Error(
      "Failed to parse json\n"+ex.message+"\n"+ex2.message+"\n"+jsonString)
    if (cb) return cb(e)
    throw e
  }}
  return processObject(opts, cb)(er, json)
}}
function processObject (opts, cb) { return function (er, json) {
  if (json.overlay) {
    ;["node", "npm"].forEach(function (k) {
      if (!json.overlay[k]) return undefined
      for (var i in json.overlay[k]) json[i] = json.overlay[k][i]
    })
  }

  // slashes would be a security risk.
  // anything else will just fail harmlessly.
  if (!json.name) {
    var e = new Error("No 'name' field found in package.json")
    if (cb) return cb(e)
    throw e
  }
  json.name = json.name.trim()
  if (json.name.charAt(0) === "." || json.name.match(/[\/@\s\+%]/)) {
    var msg = "Invalid name: "
            + JSON.stringify(json.name)
            + " may not start with '.' or contain /, @, +, or whitespace"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  var tag = opts.tag
  if (tag && tag.indexOf(json.version) === 0) {
    tag = tag.substr(json.version.length)
  }
  if (tag && tag.indexOf("-1-LINK") !== -1) {
    tag = tag.substr(tag.indexOf("-1-LINK"))
  }
  if (tag && semver.valid(json.version + tag)) {
    json.version += tag
  }

  // FIXME: uncomment in 0.3.0, once it's not likely that people will
  // have a bunch of main.js files kicking around any more, and remove
  // this functionality from lib/build.js
  //
  // if (json.main) {
  //   if (!json.modules) json.modules = {}
  //   json.modules.index = json.main
  //   delete json.main
  // }

  if (opts.wscript) {
    var scripts = json.scripts = json.scripts || {}
    if (!scripts.install && !scripts.preinstall) {
      // don't fail if it was unexpected, just try.
      scripts.preinstall = "node-waf configure build"
    }
  }

  if (!(semver.valid(json.version))) {
    var e = new Error("Invalid version: "+json.version+"\n"
                     +"Must be X.Y.Z, with an optional trailing tag.\n"
                     +"See the section on 'version' in `npm help json`"
                     )
    if (cb) return cb(e)
    throw e
  }
  json.version = semver.clean(json.version)

  if (json.main) json.main = json.main.replace(/(\.js|\.node)$/, '')

  if (json.bin && typeof json.bin === "string") {
    var b = {}
    b[ path.basename( json.bin ) ] = json.bin
    json.bin = b
  }

  if (json["dev-dependencies"] && !json.devDependencies) {
    json.devDependencies = json["dev-dependencies"]
    delete json["dev-dependencies"]
  }
  ;["dependencies", "devDependencies"].forEach(function (d) {
    if (!json[d]) return
    json[d] = depObjectify(json[d])
  })

  json._id = json.name+"@"+json.version
  json = testEngine(json)
  json = parsePeople(json)
  json._npmVersion = npm.version
  json._nodeVersion = process.version
  if (opts.file) {
    log.verbose(opts.file, "caching")
    cache[opts.file] = json
    // just in case this is a long-running process...
    if (timers[opts.file]) clearTimeout(timers[opts.file])
    timers[opts.file] = setTimeout(function () {
      delete cache[opts.file]
      delete timers[opts.file]
    }, 1000 * 60 * 60 * 24)
  }
  if (cb) cb(null,json)
  return json
}}
function depObjectify (deps) {
  if (!Array.isArray(deps)) return deps
  var o = {}
  deps.forEach(function (d) {
    d = d.trim().split(/(:?[@\s><=])/)
    o[d.shift()] = d.join("").trim().replace(/^@/, "")
  })
  return o
}
function testEngine (json) {
  // if engines is empty, then assume that node is allowed.
  log.silly(json, "testEngine")
  if ( !json.engines
      || Array.isArray(json.engines)
        && !json.engines.length
      || typeof json.engines === "object"
        && !Object.keys(json.engines).length
      ) {
    json.engines = { "node" : "*" }
  }
  if (typeof json.engines === "string") {
    if (semver.validRange(json.engines) !== null) {
      json.engines = { "node" : json.engines }
    } else json.engines = [ json.engines ]
  }

  var nodeVer = process.version.replace(/\+$/, '')
    , ok = false
  if (Array.isArray(json.engines)) {
    // Packages/1.0 commonjs style, with an array.
    // hack it to just hang a "node" member with the version range,
    // then do the npm-style check below.
    for (var i = 0, l = json.engines.length; i < l; i ++) {
      var e = json.engines[i].trim()
      if (e.substr(0, 4) === "node") {
        json.engines.node = e.substr(4)
        break
      }
    }
  }
  if (json.engines.node === "") json.engines.node = "*"
  if (json.engines.node && null === semver.validRange(json.engines.node)) {
    log.warn(json.engines.node, "not a valid range.  Please see `npm help json`")
  }
  json._nodeSupported = semver.satisfies(nodeVer, json.engines.node || "undefined")
  return json
}

function unParsePeople (json) { return parsePeople(json, true) }
function parsePeople (json, un) {
  var fn = un ? unParsePerson : parsePerson
  if (json.author) json.author = fn(json.author)
  ;["maintainers", "contributors"].forEach(function (set) {
    if (Array.isArray(json[set])) json[set] = json[set].map(fn)
  })
  return json
}
function unParsePerson (person) {
  if (typeof person === "string") return person
  var name = person.name
    , url = person.url ? (" ("+person.url+")") : ""
    , email = person.email ? (" <"+person.email+">") : ""
  return name+email+url
}
function parsePerson (person) {
  if (typeof person !== "string") return person
  var name = person.match(/^([^\(<]+)/)
    , url = person.match(/\(([^\)]+)\)/)
    , email = person.match(/<([^>]+)>/)
    , obj = { "name" : (name && name[0] || person).trim() }
  if (email) obj.email = email[1]
  if (url) obj.url = url[1]
  return obj
}
<|endoftext|>


<commit_before>const async = require('async')
const utils = require('ethereumjs-util')
const BN = utils.BN
const rlp = utils.rlp
const Account = require('ethereumjs-account').default
const Transaction = require('ethereumjs-tx').Transaction
const Block = require('ethereumjs-block')

exports.dumpState = function (state, cb) {
  function readAccounts (state) {
    return new Promise((resolve, reject) => {
      let accounts = []
      var rs = state.createReadStream()
      rs.on('data', function (data) {
        let account = new Account(data.value)
        account.address = data.key
        accounts.push(account)
      })

      rs.on('end', function () {
        resolve(accounts)
      })
    })
  }

  function readStorage (state, account) {
    return new Promise((resolve, reject) => {
      let storage = {}
      let storageTrie = state.copy()
      storageTrie.root = account.stateRoot
      let storageRS = storageTrie.createReadStream()

      storageRS.on('data', function (data) {
        storage[data.key.toString('hex')] = data.value.toString('hex')
      })

      storageRS.on('end', function () {
        resolve(storage)
      })
    })
  }

  readAccounts(state).then(function (accounts) {
    async.mapSeries(accounts, function (account, cb) {
      readStorage(state, account).then((storage) => {
        account.storage = storage
        cb(null, account)
      })
    },
    function (err, results) {
      if (err) {
        cb(err, null)
      }
      for (let i = 0; i < results.length; i++) {
        console.log('SHA3\'d address: ' + results[i].address.toString('hex'))
        console.log('\tstate root: ' + results[i].stateRoot.toString('hex'))
        console.log('\tstorage: ')
        for (let storageKey in results[i].storage) {
          console.log('\t\t' + storageKey + ': ' + results[i].storage[storageKey])
        }
        console.log('\tnonce: ' + (new BN(results[i].nonce)).toString())
        console.log('\tbalance: ' + (new BN(results[i].balance)).toString())
      }
      return cb()
    })
  })
}

var format = exports.format = function (a, toZero, isHex) {
  if (a === '') {
    return Buffer.alloc(0)
  }

  if (a.slice && a.slice(0, 2) === '0x') {
    a = a.slice(2)
    if (a.length % 2) a = '0' + a
    a = Buffer.from(a, 'hex')
  } else if (!isHex) {
    a = Buffer.from(new BN(a).toArray())
  } else {
    if (a.length % 2) a = '0' + a
    a = Buffer.from(a, 'hex')
  }

  if (toZero && a.toString('hex') === '') {
    a = Buffer.from([0])
  }

  return a
}

/**
 * makeTx using JSON from tests repo
 * @param {[type]} txData the transaction object from tests repo
 * @returns {Object}        object that will be passed to VM.runTx function
 */
exports.makeTx = function (txData, hf) {
  var tx = new Transaction({}, { hardfork: hf })
  tx.nonce = format(txData.nonce)
  tx.gasPrice = format(txData.gasPrice)
  tx.gasLimit = format(txData.gasLimit)
  tx.to = format(txData.to, true, true)
  tx.value = format(txData.value)
  tx.data = format(txData.data, false, true) // slice off 0x
  if (txData.secretKey) {
    var privKey = format(txData.secretKey, false, true)
    tx.sign(privKey)
  } else {
    tx.v = Buffer.from(txData.v.slice(2), 'hex')
    tx.r = Buffer.from(txData.r.slice(2), 'hex')
    tx.s = Buffer.from(txData.s.slice(2), 'hex')
  }
  return tx
}

exports.verifyPostConditions = function (state, testData, t, cb) {
  var hashedAccounts = {}
  var keyMap = {}

  for (var key in testData) {
    var hash = utils.keccak256(Buffer.from(utils.stripHexPrefix(key), 'hex')).toString('hex')
    hashedAccounts[hash] = testData[key]
    keyMap[hash] = key
  }

  var q = async.queue(function (task, cb2) {
    exports.verifyAccountPostConditions(state, task.address, task.account, task.testData, t, cb2)
  }, 1)

  var stream = state.createReadStream()

  stream.on('data', function (data) {
    var acnt = new Account(rlp.decode(data.value))
    var key = data.key.toString('hex')
    var testData = hashedAccounts[key]
    var address = keyMap[key]
    delete keyMap[key]

    if (testData) {
      q.push({
        address: address,
        account: acnt,
        testData: testData
      })
    } else {
      t.fail('invalid account in the trie: ' + key)
    }
  })

  stream.on('end', function () {
    function onEnd () {
      for (hash in keyMap) {
        t.fail('Missing account!: ' + keyMap[hash])
      }
      cb()
    }

    if (q.length()) {
      q.drain = onEnd
    } else {
      onEnd()
    }
  })
}

/**
 * verifyAccountPostConditions using JSON from tests repo
 * @param {[type]}   state    DB/trie
 * @param {[type]}   string   Account Address
 * @param {[type]}   account  to verify
 * @param {[type]}   acctData postconditions JSON from tests repo
 * @param {Function} cb       completion callback
 */
exports.verifyAccountPostConditions = function (state, address, account, acctData, t, cb) {
  t.comment('Account: ' + address)
  t.equal(format(account.balance, true).toString('hex'), format(acctData.balance, true).toString('hex'), 'correct balance')
  t.equal(format(account.nonce, true).toString('hex'), format(acctData.nonce, true).toString('hex'), 'correct nonce')

  // validate storage
  var origRoot = state.root
  var storageKeys = Object.keys(acctData.storage)

  var hashedStorage = {}
  for (var key in acctData.storage) {
    hashedStorage[utils.keccak256(utils.setLength(Buffer.from(key.slice(2), 'hex'), 32)).toString('hex')] = acctData.storage[key]
  }

  if (storageKeys.length > 0) {
    state.root = account.stateRoot
    var rs = state.createReadStream()
    rs.on('data', function (data) {
      var key = data.key.toString('hex')
      var val = '0x' + rlp.decode(data.value).toString('hex')

      if (key === '0x') {
        key = '0x00'
        acctData.storage['0x00'] = acctData.storage['0x00'] ? acctData.storage['0x00'] : acctData.storage['0x']
        delete acctData.storage['0x']
      }

      t.equal(val, hashedStorage[key], 'correct storage value')
      delete hashedStorage[key]
    })

    rs.on('end', function () {
      for (var key in hashedStorage) {
        if (hashedStorage[key] !== '0x00') {
          t.fail('key: ' + key + ' not found in storage')
        }
      }

      state.root = origRoot
      cb()
    })
  } else {
    cb()
  }
}

/**
 * verifyGas by computing the difference of coinbase account balance
 * @param {Object} results  to verify
 * @param {Object} testData from tests repo
 */
exports.verifyGas = function (results, testData, t) {
  var coinbaseAddr = testData.env.currentCoinbase
  var preBal = testData.pre[coinbaseAddr] ? testData.pre[coinbaseAddr].balance : 0

  if (!testData.post[coinbaseAddr]) {
    return
  }

  var postBal = new BN(testData.post[coinbaseAddr].balance)
  var balance = postBal.sub(preBal).toString()
  if (balance !== '0') {
    var amountSpent = results.gasUsed.mul(testData.transaction.gasPrice)
    t.equal(amountSpent.toString(), balance, 'correct gas')
  } else {
    t.equal(results, undefined)
  }
}

/**
 * verifyLogs
 * @param {Object} results  to verify
 * @param {Object} testData from tests repo
 */
exports.verifyLogs = function (logs, testData, t) {
  if (testData.logs) {
    testData.logs.forEach(function (log, i) {
      var rlog = logs[i]
      t.equal(rlog[0].toString('hex'), log.address, 'log: valid address')
      t.equal('0x' + rlog[2].toString('hex'), log.data, 'log: valid data')
      log.topics.forEach(function (topic, i) {
        t.equal(rlog[1][i].toString('hex'), topic, 'log: invalid topic')
      })
    })
  }
}

/**
 * toDecimal - converts buffer to decimal string, no leading zeroes
 * @param  {Buffer}
 * @returns {String}
 */
exports.toDecimal = function (buffer) {
  return new BN(buffer).toString()
}

/**
 * fromDecimal - converts decimal string to buffer
 * @param {String}
 *  @returns {Buffer}
 */
exports.fromDecimal = function (string) {
  return Buffer.from(new BN(string).toArray())
}

/**
 * fromAddress - converts hexString address to 256-bit buffer
 * @param  {String} hexString address for example '0x03'
 * @returns {Buffer}
 */
exports.fromAddress = function (hexString) {
  return utils.setLength(Buffer.from(new BN(hexString.slice(2), 16).toArray()), 32)
}

/**
 * toCodeHash - applies keccak256 to hexCode
 * @param {String} hexCode string from tests repo
 * @returns {Buffer}
 */
exports.toCodeHash = function (hexCode) {
  return utils.keccak256(Buffer.from(hexCode.slice(2), 'hex'))
}

exports.makeBlockHeader = function (data) {
  var header = {}
  header.timestamp = format(data.currentTimestamp)
  header.gasLimit = format(data.currentGasLimit)
  if (data.previousHash) {
    header.parentHash = format(data.previousHash, false, true)
  }
  header.coinbase = utils.setLength(format(data.currentCoinbase, false, true), 20)
  header.difficulty = format(data.currentDifficulty)
  header.number = format(data.currentNumber)
  return header
}

/**
 * makeBlockFromEnv - helper to create a block from the env object in tests repo
 * @param {Object} env object from tests repo
 * @param {Object} transactions transactions for the block
 * @returns {Object} the block
 */
exports.makeBlockFromEnv = function (env, transactions) {
  return new Block({
    header: exports.makeBlockHeader(env),
    transactions: transactions || {},
    uncleHeaders: []
  })
}

/**
 * makeRunCodeData - helper to create the object for VM.runCode using
 *   the exec object specified in the tests repo
 * @param {Object} exec    object from the tests repo
 * @param {Object} account that the executing code belongs to
 * @param {Object} block   that the transaction belongs to
 * @returns {Object}       object that will be passed to VM.runCode function
 */
exports.makeRunCodeData = function (exec, account, block) {
  return {
    account: account,
    origin: format(exec.origin, false, true),
    code: format(exec.code), // slice off 0x
    value: format(exec.value),
    address: format(exec.address, false, true),
    caller: format(exec.caller, false, true),
    data: format(exec.data), // slice off 0x
    gasLimit: format(exec.gas),
    gasPrice: format(exec.gasPrice),
    block: block
  }
}

/**
 * setupPreConditions given JSON testData
 * @param {[type]}   state    - the state DB/trie
 * @param {[type]}   testData - JSON from tests repo
 * @param {Function} done     - callback when function is completed
 */
exports.setupPreConditions = function (state, testData, done) {
  var keysOfPre = Object.keys(testData.pre)

  async.eachSeries(keysOfPre, function (key, callback) {
    var acctData = testData.pre[key]
    var account = new Account()

    account.nonce = format(acctData.nonce)
    account.balance = format(acctData.balance)

    var codeBuf = Buffer.from(acctData.code.slice(2), 'hex')
    var storageTrie = state.copy()
    storageTrie.root = null

    async.series([

      function (cb2) {
        var keys = Object.keys(acctData.storage)

        async.forEachSeries(keys, function (key, cb3) {
          var val = acctData.storage[key]
          val = rlp.encode(Buffer.from(val.slice(2), 'hex'))
          key = utils.setLength(Buffer.from(key.slice(2), 'hex'), 32)

          storageTrie.put(key, val, cb3)
        }, cb2)
      },
      function (cb2) {
        account.setCode(state, codeBuf, cb2)
      },
      function (cb2) {
        account.stateRoot = storageTrie.root

        if (testData.exec && key === testData.exec.address) {
          testData.root = storageTrie.root
        }
        state.put(Buffer.from(utils.stripHexPrefix(key), 'hex'), account.serialize(), function () {
          cb2()
        })
      }
    ], callback)
  }, done)
}

/**
 * Returns an alias for specified hardforks to meet test dependencies requirements/assumptions.
 * @param {String} forkConfig - the name of the hardfork for which an alias should be returned
 * @returns {String} Either an alias of the forkConfig param, or the forkConfig param itself
 */
exports.getRequiredForkConfigAlias = function (forkConfig) {
  if (String(forkConfig).match(/^petersburg$/i)) {
    return 'ConstantinopleFix'
  }
  return forkConfig
}
<commit_msg>Skip zero storage slots read from state tests<commit_after>const async = require('async')
const utils = require('ethereumjs-util')
const BN = utils.BN
const rlp = utils.rlp
const Account = require('ethereumjs-account').default
const Transaction = require('ethereumjs-tx').Transaction
const Block = require('ethereumjs-block')

exports.dumpState = function (state, cb) {
  function readAccounts (state) {
    return new Promise((resolve, reject) => {
      let accounts = []
      var rs = state.createReadStream()
      rs.on('data', function (data) {
        let account = new Account(data.value)
        account.address = data.key
        accounts.push(account)
      })

      rs.on('end', function () {
        resolve(accounts)
      })
    })
  }

  function readStorage (state, account) {
    return new Promise((resolve, reject) => {
      let storage = {}
      let storageTrie = state.copy()
      storageTrie.root = account.stateRoot
      let storageRS = storageTrie.createReadStream()

      storageRS.on('data', function (data) {
        storage[data.key.toString('hex')] = data.value.toString('hex')
      })

      storageRS.on('end', function () {
        resolve(storage)
      })
    })
  }

  readAccounts(state).then(function (accounts) {
    async.mapSeries(accounts, function (account, cb) {
      readStorage(state, account).then((storage) => {
        account.storage = storage
        cb(null, account)
      })
    },
    function (err, results) {
      if (err) {
        cb(err, null)
      }
      for (let i = 0; i < results.length; i++) {
        console.log('SHA3\'d address: ' + results[i].address.toString('hex'))
        console.log('\tstate root: ' + results[i].stateRoot.toString('hex'))
        console.log('\tstorage: ')
        for (let storageKey in results[i].storage) {
          console.log('\t\t' + storageKey + ': ' + results[i].storage[storageKey])
        }
        console.log('\tnonce: ' + (new BN(results[i].nonce)).toString())
        console.log('\tbalance: ' + (new BN(results[i].balance)).toString())
      }
      return cb()
    })
  })
}

var format = exports.format = function (a, toZero, isHex) {
  if (a === '') {
    return Buffer.alloc(0)
  }

  if (a.slice && a.slice(0, 2) === '0x') {
    a = a.slice(2)
    if (a.length % 2) a = '0' + a
    a = Buffer.from(a, 'hex')
  } else if (!isHex) {
    a = Buffer.from(new BN(a).toArray())
  } else {
    if (a.length % 2) a = '0' + a
    a = Buffer.from(a, 'hex')
  }

  if (toZero && a.toString('hex') === '') {
    a = Buffer.from([0])
  }

  return a
}

/**
 * makeTx using JSON from tests repo
 * @param {[type]} txData the transaction object from tests repo
 * @returns {Object}        object that will be passed to VM.runTx function
 */
exports.makeTx = function (txData, hf) {
  var tx = new Transaction({}, { hardfork: hf })
  tx.nonce = format(txData.nonce)
  tx.gasPrice = format(txData.gasPrice)
  tx.gasLimit = format(txData.gasLimit)
  tx.to = format(txData.to, true, true)
  tx.value = format(txData.value)
  tx.data = format(txData.data, false, true) // slice off 0x
  if (txData.secretKey) {
    var privKey = format(txData.secretKey, false, true)
    tx.sign(privKey)
  } else {
    tx.v = Buffer.from(txData.v.slice(2), 'hex')
    tx.r = Buffer.from(txData.r.slice(2), 'hex')
    tx.s = Buffer.from(txData.s.slice(2), 'hex')
  }
  return tx
}

exports.verifyPostConditions = function (state, testData, t, cb) {
  var hashedAccounts = {}
  var keyMap = {}

  for (var key in testData) {
    var hash = utils.keccak256(Buffer.from(utils.stripHexPrefix(key), 'hex')).toString('hex')
    hashedAccounts[hash] = testData[key]
    keyMap[hash] = key
  }

  var q = async.queue(function (task, cb2) {
    exports.verifyAccountPostConditions(state, task.address, task.account, task.testData, t, cb2)
  }, 1)

  var stream = state.createReadStream()

  stream.on('data', function (data) {
    var acnt = new Account(rlp.decode(data.value))
    var key = data.key.toString('hex')
    var testData = hashedAccounts[key]
    var address = keyMap[key]
    delete keyMap[key]

    if (testData) {
      q.push({
        address: address,
        account: acnt,
        testData: testData
      })
    } else {
      t.fail('invalid account in the trie: ' + key)
    }
  })

  stream.on('end', function () {
    function onEnd () {
      for (hash in keyMap) {
        t.fail('Missing account!: ' + keyMap[hash])
      }
      cb()
    }

    if (q.length()) {
      q.drain = onEnd
    } else {
      onEnd()
    }
  })
}

/**
 * verifyAccountPostConditions using JSON from tests repo
 * @param {[type]}   state    DB/trie
 * @param {[type]}   string   Account Address
 * @param {[type]}   account  to verify
 * @param {[type]}   acctData postconditions JSON from tests repo
 * @param {Function} cb       completion callback
 */
exports.verifyAccountPostConditions = function (state, address, account, acctData, t, cb) {
  t.comment('Account: ' + address)
  t.equal(format(account.balance, true).toString('hex'), format(acctData.balance, true).toString('hex'), 'correct balance')
  t.equal(format(account.nonce, true).toString('hex'), format(acctData.nonce, true).toString('hex'), 'correct nonce')

  // validate storage
  var origRoot = state.root
  var storageKeys = Object.keys(acctData.storage)

  var hashedStorage = {}
  for (var key in acctData.storage) {
    hashedStorage[utils.keccak256(utils.setLength(Buffer.from(key.slice(2), 'hex'), 32)).toString('hex')] = acctData.storage[key]
  }

  if (storageKeys.length > 0) {
    state.root = account.stateRoot
    var rs = state.createReadStream()
    rs.on('data', function (data) {
      var key = data.key.toString('hex')
      var val = '0x' + rlp.decode(data.value).toString('hex')

      if (key === '0x') {
        key = '0x00'
        acctData.storage['0x00'] = acctData.storage['0x00'] ? acctData.storage['0x00'] : acctData.storage['0x']
        delete acctData.storage['0x']
      }

      t.equal(val, hashedStorage[key], 'correct storage value')
      delete hashedStorage[key]
    })

    rs.on('end', function () {
      for (var key in hashedStorage) {
        if (hashedStorage[key] !== '0x00') {
          t.fail('key: ' + key + ' not found in storage')
        }
      }

      state.root = origRoot
      cb()
    })
  } else {
    cb()
  }
}

/**
 * verifyGas by computing the difference of coinbase account balance
 * @param {Object} results  to verify
 * @param {Object} testData from tests repo
 */
exports.verifyGas = function (results, testData, t) {
  var coinbaseAddr = testData.env.currentCoinbase
  var preBal = testData.pre[coinbaseAddr] ? testData.pre[coinbaseAddr].balance : 0

  if (!testData.post[coinbaseAddr]) {
    return
  }

  var postBal = new BN(testData.post[coinbaseAddr].balance)
  var balance = postBal.sub(preBal).toString()
  if (balance !== '0') {
    var amountSpent = results.gasUsed.mul(testData.transaction.gasPrice)
    t.equal(amountSpent.toString(), balance, 'correct gas')
  } else {
    t.equal(results, undefined)
  }
}

/**
 * verifyLogs
 * @param {Object} results  to verify
 * @param {Object} testData from tests repo
 */
exports.verifyLogs = function (logs, testData, t) {
  if (testData.logs) {
    testData.logs.forEach(function (log, i) {
      var rlog = logs[i]
      t.equal(rlog[0].toString('hex'), log.address, 'log: valid address')
      t.equal('0x' + rlog[2].toString('hex'), log.data, 'log: valid data')
      log.topics.forEach(function (topic, i) {
        t.equal(rlog[1][i].toString('hex'), topic, 'log: invalid topic')
      })
    })
  }
}

/**
 * toDecimal - converts buffer to decimal string, no leading zeroes
 * @param  {Buffer}
 * @returns {String}
 */
exports.toDecimal = function (buffer) {
  return new BN(buffer).toString()
}

/**
 * fromDecimal - converts decimal string to buffer
 * @param {String}
 *  @returns {Buffer}
 */
exports.fromDecimal = function (string) {
  return Buffer.from(new BN(string).toArray())
}

/**
 * fromAddress - converts hexString address to 256-bit buffer
 * @param  {String} hexString address for example '0x03'
 * @returns {Buffer}
 */
exports.fromAddress = function (hexString) {
  return utils.setLength(Buffer.from(new BN(hexString.slice(2), 16).toArray()), 32)
}

/**
 * toCodeHash - applies keccak256 to hexCode
 * @param {String} hexCode string from tests repo
 * @returns {Buffer}
 */
exports.toCodeHash = function (hexCode) {
  return utils.keccak256(Buffer.from(hexCode.slice(2), 'hex'))
}

exports.makeBlockHeader = function (data) {
  var header = {}
  header.timestamp = format(data.currentTimestamp)
  header.gasLimit = format(data.currentGasLimit)
  if (data.previousHash) {
    header.parentHash = format(data.previousHash, false, true)
  }
  header.coinbase = utils.setLength(format(data.currentCoinbase, false, true), 20)
  header.difficulty = format(data.currentDifficulty)
  header.number = format(data.currentNumber)
  return header
}

/**
 * makeBlockFromEnv - helper to create a block from the env object in tests repo
 * @param {Object} env object from tests repo
 * @param {Object} transactions transactions for the block
 * @returns {Object} the block
 */
exports.makeBlockFromEnv = function (env, transactions) {
  return new Block({
    header: exports.makeBlockHeader(env),
    transactions: transactions || {},
    uncleHeaders: []
  })
}

/**
 * makeRunCodeData - helper to create the object for VM.runCode using
 *   the exec object specified in the tests repo
 * @param {Object} exec    object from the tests repo
 * @param {Object} account that the executing code belongs to
 * @param {Object} block   that the transaction belongs to
 * @returns {Object}       object that will be passed to VM.runCode function
 */
exports.makeRunCodeData = function (exec, account, block) {
  return {
    account: account,
    origin: format(exec.origin, false, true),
    code: format(exec.code), // slice off 0x
    value: format(exec.value),
    address: format(exec.address, false, true),
    caller: format(exec.caller, false, true),
    data: format(exec.data), // slice off 0x
    gasLimit: format(exec.gas),
    gasPrice: format(exec.gasPrice),
    block: block
  }
}

/**
 * setupPreConditions given JSON testData
 * @param {[type]}   state    - the state DB/trie
 * @param {[type]}   testData - JSON from tests repo
 * @param {Function} done     - callback when function is completed
 */
exports.setupPreConditions = function (state, testData, done) {
  var keysOfPre = Object.keys(testData.pre)

  async.eachSeries(keysOfPre, function (key, callback) {
    var acctData = testData.pre[key]
    var account = new Account()

    account.nonce = format(acctData.nonce)
    account.balance = format(acctData.balance)

    var codeBuf = Buffer.from(acctData.code.slice(2), 'hex')
    var storageTrie = state.copy()
    storageTrie.root = null

    async.series([

      function (cb2) {
        var keys = Object.keys(acctData.storage)

        async.forEachSeries(keys, function (key, cb3) {
          const valBN = new BN(acctData.storage[key].slice(2), 16)
          if (valBN.isZero()) {
            return cb3()
          }
          let val = rlp.encode(valBN.toArrayLike(Buffer, 'be'))
          key = utils.setLength(Buffer.from(key.slice(2), 'hex'), 32)

          storageTrie.put(key, val, cb3)
        }, cb2)
      },
      function (cb2) {
        account.setCode(state, codeBuf, cb2)
      },
      function (cb2) {
        account.stateRoot = storageTrie.root

        if (testData.exec && key === testData.exec.address) {
          testData.root = storageTrie.root
        }
        state.put(Buffer.from(utils.stripHexPrefix(key), 'hex'), account.serialize(), function () {
          cb2()
        })
      }
    ], callback)
  }, done)
}

/**
 * Returns an alias for specified hardforks to meet test dependencies requirements/assumptions.
 * @param {String} forkConfig - the name of the hardfork for which an alias should be returned
 * @returns {String} Either an alias of the forkConfig param, or the forkConfig param itself
 */
exports.getRequiredForkConfigAlias = function (forkConfig) {
  if (String(forkConfig).match(/^petersburg$/i)) {
    return 'ConstantinopleFix'
  }
  return forkConfig
}
<|endoftext|>