<commit_before>"use strict";

const EventEmitter = require("events");

const noop = () => {};
const noopLogger = {
  fatal: noop,
  error: noop,
  warn : noop,
  info : noop,
  debug: noop,
  trace: noop,

  child: function() { return this; }
};

const CLIENT_PRELUDE = new Buffer("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");

module.exports = function(dependencies) {
  const tls = dependencies.tls;
  const protocol = dependencies.protocol;

  function Endpoint(options) {
    EventEmitter.call(this);

    this.options = options;
    options.host = options.host || options.address;
    options.servername = options.address;

    this._acquiredStreamSlots = 0;
    this._maximumStreamSlots = 0;

    options.ALPNProtocols = ["h2"];

    this._connect();
    this._setupHTTP2Pipeline();
  }

  Endpoint.prototype = Object.create(EventEmitter.prototype, {
    availableStreamSlots: {
      get: function() {
        return this._maximumStreamSlots - this._acquiredStreamSlots;
      }
    }
  });

  Endpoint.prototype._setupHTTP2Pipeline = function _setupHTTP2Pipeline() {
    const serializer = new protocol.Serializer(noopLogger.child("serializer"));
    const compressor = new protocol.Compressor(noopLogger.child("compressor"), "REQUEST");
    const deserializer = new protocol.Deserializer(noopLogger.child("deserializer"));
    const decompressor = new protocol.Decompressor(noopLogger.child("decompressor"), "RESPONSE");

    this._connection.pipe(compressor);
    compressor.pipe(serializer);
    serializer.pipe(this._socket);

    this._socket.pipe(deserializer);
    deserializer.pipe(decompressor);
    decompressor.pipe(this._connection);

    this._connection.on("RECEIVING_SETTINGS_HEADER_TABLE_SIZE", compressor.setTableSizeLimit.bind(compressor));
    this._connection.on("ACKNOWLEDGED_SETTINGS_HEADER_TABLE_SIZE", decompressor.setTableSizeLimit.bind(decompressor));

    this._connection.on("RECEIVING_SETTINGS_MAX_CONCURRENT_STREAMS", maxStreams => {
      this._maximumStreamSlots = maxStreams;
      this.emit("wakeup");
    });

    serializer.on("error", this.emit.bind(this, "error"));
    compressor.on("error", this.emit.bind(this, "error"));
    deserializer.on("error", this.emit.bind(this, "error"));
    decompressor.on("error", this.emit.bind(this, "error"));
  };

  Endpoint.prototype._connect = function connect() {
    this._socket = tls.connect(this.options);
    this._socket.on("secureConnect", this._connected.bind(this));
    this._socket.on("error", this.emit.bind(this, "error"));
    this._socket.write(CLIENT_PRELUDE);

    this._connection = new protocol.Connection(noopLogger, 1);
    this._connection.on("error", this.emit.bind(this, "error"));
  };

  Endpoint.prototype._connected = function connected() {
    this.emit("connect");
  };

  Endpoint.prototype.createStream = function createStream() {
    const stream = this._connection.createStream();

    this._acquiredStreamSlots += 1;
    stream.on("end", () => {
      this._acquiredStreamSlots -= 1;
      this.emit("wakeup");
    });

    return stream;
  };

  return Endpoint;
};
<commit_msg>Null-out the retain-cycle<commit_after>"use strict";

const EventEmitter = require("events");

const noop = () => {};
const noopLogger = {
  fatal: noop,
  error: noop,
  warn : noop,
  info : noop,
  debug: noop,
  trace: noop,

  child: function() { return this; }
};

const CLIENT_PRELUDE = new Buffer("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");

module.exports = function(dependencies) {
  const tls = dependencies.tls;
  const protocol = dependencies.protocol;

  function Endpoint(options) {
    EventEmitter.call(this);

    this.options = options;
    options.host = options.host || options.address;
    options.servername = options.address;

    this._acquiredStreamSlots = 0;
    this._maximumStreamSlots = 0;

    options.ALPNProtocols = ["h2"];

    this._connect();
    this._setupHTTP2Pipeline();
  }

  Endpoint.prototype = Object.create(EventEmitter.prototype, {
    availableStreamSlots: {
      get: function() {
        return this._maximumStreamSlots - this._acquiredStreamSlots;
      }
    }
  });

  Endpoint.prototype._setupHTTP2Pipeline = function _setupHTTP2Pipeline() {
    const serializer = new protocol.Serializer(noopLogger.child("serializer"));
    const compressor = new protocol.Compressor(noopLogger.child("compressor"), "REQUEST");
    const deserializer = new protocol.Deserializer(noopLogger.child("deserializer"));
    const decompressor = new protocol.Decompressor(noopLogger.child("decompressor"), "RESPONSE");

    this._connection.pipe(compressor);
    compressor.pipe(serializer);
    serializer.pipe(this._socket);

    this._socket.pipe(deserializer);
    deserializer.pipe(decompressor);
    decompressor.pipe(this._connection);

    this._connection.on("RECEIVING_SETTINGS_HEADER_TABLE_SIZE", compressor.setTableSizeLimit.bind(compressor));
    this._connection.on("ACKNOWLEDGED_SETTINGS_HEADER_TABLE_SIZE", decompressor.setTableSizeLimit.bind(decompressor));

    this._connection.on("RECEIVING_SETTINGS_MAX_CONCURRENT_STREAMS", maxStreams => {
      this._maximumStreamSlots = maxStreams;
      this.emit("wakeup");
    });

    serializer.on("error", this.emit.bind(this, "error"));
    compressor.on("error", this.emit.bind(this, "error"));
    deserializer.on("error", this.emit.bind(this, "error"));
    decompressor.on("error", this.emit.bind(this, "error"));
  };

  Endpoint.prototype._connect = function connect() {
    this._socket = tls.connect(this.options);
    this._socket.on("secureConnect", this._connected.bind(this));
    this._socket.on("error", this.emit.bind(this, "error"));
    this._socket.write(CLIENT_PRELUDE);

    this._connection = new protocol.Connection(noopLogger, 1);
    this._connection.on("error", this.emit.bind(this, "error"));
  };

  Endpoint.prototype._connected = function connected() {
    this.emit("connect");
  };

  Endpoint.prototype.createStream = function createStream() {
    let stream = this._connection.createStream();

    this._acquiredStreamSlots += 1;
    stream.on("end", () => {
      stream = null;
      this._acquiredStreamSlots -= 1;
      this.emit("wakeup");
    });

    return stream;
  };

  return Endpoint;
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Requirements
 * @ignore
 */
const TransformingTask = require('./TransformingTask.js').TransformingTask;
const co = require('co');

/**
 * @memberOf task
 * @extends task.SimpleTask
 */
class RemoveFilesTask extends TransformingTask
{
    /**
     * @inheritDocs
     */
    static get className()
    {
        return 'task/RemoveFilesTask';
    }

    /**
     * @protected
     * @returns {Array}
     */
    prepareParameters(buildConfiguration, parameters)
    {
        const promise = super.prepareParameters(buildConfiguration, parameters)
            .then((params) =>
            {
                params.removeFiles = params.removeFiles || [];
                return params;
            });
        return promise;
    }

    /**
     * @param {VinylFile} file
     * @param {model.configuration.BuildConfiguration} buildConfiguration
     * @param {Object} parameters
     * @returns {Promise<VinylFile>}
     */
    processFile(file, buildConfiguration, parameters)
    {
        const scope = this;
        const promise = co(function*()
        {
            // Prepare
            const params = yield scope.prepareParameters(buildConfiguration, parameters);

            /* istanbul ignore next */
            if (!file || !file.isNull)
            {
                scope.cliLogger.info('Invalid file <' + file + '>');
                return false;
            }

            // Remove file?
            for (const remove of params.removeFiles)
            {
                if (file.path.match(new RegExp(remove)))
                {
                    const work = scope.cliLogger.work('Removing file <' + file.path + '>');
                    scope.cliLogger.end(work);
                    return false;
                }
            }

            return file;
        });
        return promise;
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.RemoveFilesTask = RemoveFilesTask;
<commit_msg>fix(task.RemoveFilesTask): adds guards against bogus removeFiles parameter<commit_after>'use strict';

/**
 * Requirements
 * @ignore
 */
const TransformingTask = require('./TransformingTask.js').TransformingTask;
const co = require('co');

/**
 * @memberOf task
 * @extends task.SimpleTask
 */
class RemoveFilesTask extends TransformingTask
{
    /**
     * @inheritDocs
     */
    static get className()
    {
        return 'task/RemoveFilesTask';
    }

    /**
     * @protected
     * @returns {Array}
     */
    prepareParameters(buildConfiguration, parameters)
    {
        const promise = super.prepareParameters(buildConfiguration, parameters)
            .then((params) =>
            {
                params.removeFiles = params.removeFiles || [];
                return params;
            });
        return promise;
    }

    /**
     * @param {VinylFile} file
     * @param {model.configuration.BuildConfiguration} buildConfiguration
     * @param {Object} parameters
     * @returns {Promise<VinylFile>}
     */
    processFile(file, buildConfiguration, parameters)
    {
        const scope = this;
        const promise = co(function*()
        {
            // Prepare
            const params = yield scope.prepareParameters(buildConfiguration, parameters);

            /* istanbul ignore next */
            if (!file || !file.isNull)
            {
                scope.cliLogger.info('Invalid file <' + file + '>');
                return false;
            }

            if (params.removeFiles && Array.isArray(params.removeFiles))
            {
                // Remove file?
                for (const remove of params.removeFiles)
                {
                    if (file.path.match(new RegExp(remove)))
                    {
                        const work = scope.cliLogger.work('Removing file <' + file.path + '>');
                        scope.cliLogger.end(work);
                        return false;
                    }
                }
            }

            return file;
        });
        return promise;
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.RemoveFilesTask = RemoveFilesTask;
<|endoftext|>


<commit_before>define([
	'utils/warn',
	'utils/parseJSON'
], function (
	warn,
	parseJSON
) {

	'use strict';

	return function () {
		var values, counter, jsonesque, guid, errorMessage, parsed, processItems;

		if ( !this.argsList || this.dirty ) {
			values = {};
			counter = 0;

			guid = this.root._guid;

			processItems = function ( items ) {
				return items.map( function ( item ) {
					var placeholderId;

					if ( item.text ) {
						return item.text;
					}

					if ( item.fragments ) {
						return item.fragments.map( function ( fragment ) {
							return processItems( fragment.items );
						}).join( '' );
					}

					placeholderId = guid + '-' + counter++;
					values[ placeholderId ] = item.value;

					return '${' + placeholderId + '}';
				}).join( '' );
			};

			jsonesque = processItems( this.items );

			parsed = parseJSON( '[' + jsonesque + ']', values );

			if ( !parsed ) {
				errorMessage = 'Could not parse directive arguments (' + this.toString() + '). If you think this is a bug, please file an issue at http://github.com/RactiveJS/Ractive/issues';

				if ( this.root.debug ) {
					throw new Error( errorMessage );
				} else {
					warn( errorMessage );
					this.argsList = [ jsonesque ];
				}
			} else {
				this.argsList = parsed.value;
			}

			this.dirty = false;
		}

		return this.argsList;
	};

});<commit_msg>when generating directive argument lists, dont use wrapper facades<commit_after>define([
	'utils/warn',
	'utils/parseJSON'
], function (
	warn,
	parseJSON
) {

	'use strict';

	return function () {
		var values, counter, jsonesque, guid, errorMessage, parsed, processItems;

		if ( !this.argsList || this.dirty ) {
			values = {};
			counter = 0;

			guid = this.root._guid;

			processItems = function ( items ) {
				return items.map( function ( item ) {
					var placeholderId, wrapped, value;

					if ( item.text ) {
						return item.text;
					}

					if ( item.fragments ) {
						return item.fragments.map( function ( fragment ) {
							return processItems( fragment.items );
						}).join( '' );
					}

					placeholderId = guid + '-' + counter++;

					if ( wrapped = item.root._wrapped[ item.keypath ] ) {
						value = wrapped.value;
					} else {
						value = item.value;
					}

					values[ placeholderId ] = value;

					return '${' + placeholderId + '}';
				}).join( '' );
			};

			jsonesque = processItems( this.items );

			parsed = parseJSON( '[' + jsonesque + ']', values );

			if ( !parsed ) {
				errorMessage = 'Could not parse directive arguments (' + this.toString() + '). If you think this is a bug, please file an issue at http://github.com/RactiveJS/Ractive/issues';

				if ( this.root.debug ) {
					throw new Error( errorMessage );
				} else {
					warn( errorMessage );
					this.argsList = [ jsonesque ];
				}
			} else {
				this.argsList = parsed.value;
			}

			this.dirty = false;
		}

		return this.argsList;
	};

});<|endoftext|>


<commit_before>(function(exports, global) {

  var utils = undefined;
  var jayClient = undefined;

  var Submit = function(options) {
  }

  var defaultCallback = function(error, response) {
    console.log(JSON.stringify(response));
  };

  var getCallback = function(args) {
    if(typeof args[args.length -1] == 'function')
      return args.pop();
    else
      return defaultCallback;
  }

  Submit.prototype.config = function(options) {

    var self = this;
    if(typeof require === 'function' && typeof module === 'object') {
      jayson = require('../../lib/jayson');
      utils = require('../utils.js');
      jayClient = jayson.client.http(options);
    } else {
      utils = global.utils;
      var jayson = new window.Jayson(options);

      jayClient = {
        'request': function(method, params, callback) {
          return jayson.request(method, params, undefined, callback);
        }
      }
    }

    self.id = utils.generateId();

    if(!options.log)
      utils.log = function(){};

    utils.log('config with ' + JSON.stringify(options));

  };

  Submit.prototype.offloadReq = function(offloadFunc, config, cb) {
    var callback = cb;
    if(cb === undefined)
      callback = defaultCallback;

    args = [offloadFunc.toString(), config, this.id];
    //args.push(config);
    //args.push(this.id);
    utils.log('offload ' + JSON.stringify(args));
    jayClient.request('offload', args, function(error, response) {
      callback(error, response);
    });
  };

  Submit.prototype.offloadClear = function(config, cb) {
    var callback = cb;
    if(cb === undefined)
      callback = defaultCallback;

    var args = [config, this.id];

    utils.log('offloadClear ' + JSON.stringify(args));

    jayClient.request('offloadClear', args, function(error, response) {
      callback(error, response);
    });

  };

  Submit.prototype.offloadQuery = function(config, cb) {
    var callback = cb;
    if(cb === undefined)
      callback = defaultCallback;

    var args = [config, this.id];

    jayClient.request('offloadQuery', args, function(error, response) {
      callback(error, response);
    });

  };

  Submit.prototype.classReq = function(className, args, self) {

    var callback = getCallback(args);
    args = utils.toArray(args);

    self.rpcid = utils.generateId();

    args.push(self.rpcid);

    utils.log('classReq ' + className + '(' + JSON.stringify(args) + ')');

    jayClient.request(className, args, function(error, response) {
      callback(error, response);
      ret = response;
    });

  };

  Submit.prototype.classMethodReq = function(className, methodName, args, self) {

    args = utils.toArray(args);

    // attach rpcid
    args.push(self.rpcid);

    var callback = getCallback(args);
    var ret = undefined;

    utils.log('classMethodReq ' + className + '.' + methodName + '(' + JSON.stringify(args) + ')');

    jayClient.request(className + '.' + methodName, utils.toArray(args), function(error, response) {
      callback(error,response);
      ret = response;
    });

    return ret;
  };

  Submit.prototype.funcReq = function(funcName, args) {

    args = utils.toArray(args);
    var callback = getCallback(args);
    var ret = undefined;

    utils.log('funcReq ' + funcName + '(' + JSON.stringify(args) + ')');
    jayClient.request(funcName, utils.toArray(args), function(error,response) {
      ret = response;
      callback(error, response);
    });

    return ret;
  };

  Submit.prototype.rpc = function(args, funcName) {

    args = utils.toArray(args);
    var callback = getCallback(args);
    var ret = undefined;

    if(funcName !== undefined) {
      args.unshift(funcName);
    }

    utils.log('rpc: ' + JSON.stringify(args));

    jayClient.request('rpc', args, function(error,response) {
      ret = response;
      callback(error, response);
    });
  };
/*
  Submit.prototype.funcReq = function(funcName, args) {
    args = utils.toArray(args);
    var callback = getCallback(args);

    var asyncChain = $.whenSync(function(deferred) {
      jayClient.request(funcName, utils.toArray(args), function(error, response){
        callback(error, response);
        deferred.resolve(response);
      });
    });

    asyncChain.done(function(result){
      console.log('done: ' + JSON.stringify(result));
    });

  };
*/
  exports.SubmitRpc = Submit;

})(typeof exports === 'object'? exports: this.IOLIB, this.IOLIB);
<commit_msg>return sychronous rpc value<commit_after>(function(exports, global) {

  var utils = undefined;
  var jayClient = undefined;

  var Submit = function(options) {
  }

  var defaultCallback = function(error, response) {
    console.log(JSON.stringify(response));
  };

  var getCallback = function(args) {
    if(typeof args[args.length -1] == 'function')
      return args.pop();
    else
      return defaultCallback;
  }

  var parseRet = function(ret) {
    if(ret != undefined && ret.result != undefined) {
      return eval('(' + ret.result + ')');
    }

    return ret;
  }

  Submit.prototype.config = function(options) {

    var self = this;
    if(typeof require === 'function' && typeof module === 'object') {
      jayson = require('../../lib/jayson');
      utils = require('../utils.js');
      jayClient = jayson.client.http(options);
    } else {
      utils = global.utils;
      var jayson = new window.Jayson(options);

      jayClient = {
        'request': function(method, params, callback) {
          return jayson.request(method, params, undefined, callback);
        }
      }
    }

    self.id = utils.generateId();

    if(!options.log)
      utils.log = function(){};

    utils.log('config with ' + JSON.stringify(options));

  };

  Submit.prototype.offloadReq = function(offloadFunc, config, cb) {
    var callback = cb;
    if(cb === undefined)
      callback = defaultCallback;

    args = [offloadFunc.toString(), config, this.id];
    //args.push(config);
    //args.push(this.id);
    utils.log('offload ' + JSON.stringify(args));
    jayClient.request('offload', args, function(error, response) {
      callback(error, response);
    });
  };

  Submit.prototype.offloadClear = function(config, cb) {
    var callback = cb;
    if(cb === undefined)
      callback = defaultCallback;

    var args = [config, this.id];

    utils.log('offloadClear ' + JSON.stringify(args));

    jayClient.request('offloadClear', args, function(error, response) {
      callback(error, response);
    });

  };

  Submit.prototype.offloadQuery = function(config, cb) {
    var callback = cb;
    if(cb === undefined)
      callback = defaultCallback;

    var args = [config, this.id];

    jayClient.request('offloadQuery', args, function(error, response) {
      callback(error, response);
    });

  };

  Submit.prototype.classReq = function(className, args, self) {

    var callback = getCallback(args);
    args = utils.toArray(args);

    self.rpcid = utils.generateId();

    args.push(self.rpcid);

    utils.log('classReq ' + className + '(' + JSON.stringify(args) + ')');

    jayClient.request(className, args, function(error, response) {
      callback(error, response);
      ret = response;
    });

  };

  Submit.prototype.classMethodReq = function(className, methodName, args, self) {

    args = utils.toArray(args);

    // attach rpcid
    args.push(self.rpcid);

    var callback = getCallback(args);
    var ret = undefined;

    utils.log('classMethodReq ' + className + '.' + methodName + '(' + JSON.stringify(args) + ')');

    jayClient.request(className + '.' + methodName, utils.toArray(args), function(error, response) {
      callback(error,response);
      ret = response;
    });

    return ret;
  };

  Submit.prototype.funcReq = function(funcName, args) {

    args = utils.toArray(args);
    var callback = getCallback(args);
    var ret = undefined;

    utils.log('funcReq ' + funcName + '(' + JSON.stringify(args) + ')');
    jayClient.request(funcName, utils.toArray(args), function(error,response) {
      ret = response;
      callback(error, response);
    });

    return parseRet(ret);
  };

  Submit.prototype.rpc = function(args, funcName) {

    args = utils.toArray(args);
    var callback = getCallback(args);
    var ret = undefined;

    if(funcName !== undefined) {
      args.unshift(funcName);
    }

    utils.log('rpc: ' + JSON.stringify(args));

    jayClient.request('rpc', args, function(error,response) {
      ret = response;
      callback(error, response);
    });

    return parseRet(ret);
  };
/*
  Submit.prototype.funcReq = function(funcName, args) {
    args = utils.toArray(args);
    var callback = getCallback(args);

    var asyncChain = $.whenSync(function(deferred) {
      jayClient.request(funcName, utils.toArray(args), function(error, response){
        callback(error, response);
        deferred.resolve(response);
      });
    });

    asyncChain.done(function(result){
      console.log('done: ' + JSON.stringify(result));
    });

  };
*/
  exports.SubmitRpc = Submit;

})(typeof exports === 'object'? exports: this.IOLIB, this.IOLIB);
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
Copyright (c) 2014 Seth Anderson

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be appreciated
but is not required.

2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.

3. This notice may not be removed or altered from any source distribution.
-----------------------------------------------------------------------------
*/

var dgram = require("dgram"),
	loadConfig = require("./common.js").loadConfig,
	config = loadConfig(__dirname + "/../config.json"),

	_constructRconCommand = function(command){
		var buffer = new Buffer(config.cod4.password.length + command.length + 12);
		buffer.writeUInt32LE(0xffffffff, 0);
		buffer.writeUInt8(0x02, 4);
		buffer.writeUInt8("r".charCodeAt(0), 5);
		buffer.writeUInt8("c".charCodeAt(0), 6);
		buffer.writeUInt8("o".charCodeAt(0), 7);
		buffer.writeUInt8("n".charCodeAt(0), 8);
		buffer.writeUInt8(" ".charCodeAt(0), 9);
		buffer.write(config.cod4.password, 10);
		buffer.writeUInt8(" ".charCodeAt(0), 10 + config.cod4.password.length);
		buffer.write(command, 11 + config.cod4.password.length);
		buffer.writeUInt8("\n".charCodeAt(0), buffer.length - 1);
		return buffer;
	},

	_sendAndReceiveSingleCommand = function(command, callback){
		var socket = dgram.createSocket("udp4"),
			responseReceived = false;
		socket.on("message", function(data){
			callback(null, data.toString().replace("����", ""));
			responseReceived = true;
			socket.close();
		})
		.on("error", function(err){
			callback(new Error(err));
		});
		socket.bind(0, null, function(){
			var buffer = _constructRconCommand(command);
			socket.send(buffer, 0, buffer.length, config.cod4.port, config.cod4.address, function(err, bytes){
				if(err){
					console.log(err);
				}
				setTimeout(function(){
					if(!responseReceived){
						callback(new Error("Command timed out."));
					}
				}, config.cod4.commandTimeout);
			});
		});
	};

module.exports = {
	raw: function(command, callback){
		_sendAndReceiveSingleCommand(command, callback);
	},

	status: function(callback){
		_sendAndReceiveSingleCommand("status", function(err, data){
			if(err){
				callback(err);
				return;
			}
			var dataObj = {},
				lines = data.replace("\r", "").split("\n"),
				tokens, inList = false;
			for(var i = 0; i < lines.length; i += 1){
				if(lines[i].indexOf("map:") !== -1){
					tokens = lines[i].split(": ");
					dataObj.map = tokens[1];
				}else if(lines[i].indexOf("--- -----") !== -1){
					inList = true;
					dataObj.players = [];
				}else if(inList === true){
					dataObj.players.push({
						num: lines[i].substring(0, 3),
						score: lines[i].substring(4, 9),
						ping: lines[i].substring(10, 14),
						guid: lines[i].substring(15, 47),
						name: lines[i].substring(48, 63),
						lastmsg: lines[i].substring(64, 71),
						address: lines[i].substring(72, 93),
						qport: lines[i].substring(94, 99),
						rate: lines[i].substring(100)
					});
				}
			}
			callback(null, dataObj);
		});
	},

	gametype: function(callback){
		_sendAndReceiveSingleCommand("g_gametype", function(err, data){
			if(err){
				callback(err);
				return;
			}
			var dataObj = {},
				lines = data.replace("\r", "").split("\n"),
				tokens;
			for(var i = 0; i < lines.length; i += 1){
				if(lines[i].indexOf("\"g_gametype\"") !== -1){
					tokens = lines[i].split(" ");
					dataObj.gametype = tokens[2].replace("\"", "").replace("^7", "");
					dataObj.defaultGametype = tokens[4].replace("\"", "").replace("^7", "");
				}else if(lines[i].indexOf("latched") !== -1){
					tokens = lines[i].split(" ");
					dataObj.latched = tokens[1].replace("\"", "");
				}
			}
		});
	}
}
<commit_msg>Fixed cod4 gametype getter not calling callback<commit_after>/*
-----------------------------------------------------------------------------
Copyright (c) 2014 Seth Anderson

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be appreciated
but is not required.

2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.

3. This notice may not be removed or altered from any source distribution.
-----------------------------------------------------------------------------
*/

var dgram = require("dgram"),
	loadConfig = require("./common.js").loadConfig,
	config = loadConfig(__dirname + "/../config.json"),

	_constructRconCommand = function(command){
		var buffer = new Buffer(config.cod4.password.length + command.length + 12);
		buffer.writeUInt32LE(0xffffffff, 0);
		buffer.writeUInt8(0x02, 4);
		buffer.writeUInt8("r".charCodeAt(0), 5);
		buffer.writeUInt8("c".charCodeAt(0), 6);
		buffer.writeUInt8("o".charCodeAt(0), 7);
		buffer.writeUInt8("n".charCodeAt(0), 8);
		buffer.writeUInt8(" ".charCodeAt(0), 9);
		buffer.write(config.cod4.password, 10);
		buffer.writeUInt8(" ".charCodeAt(0), 10 + config.cod4.password.length);
		buffer.write(command, 11 + config.cod4.password.length);
		buffer.writeUInt8("\n".charCodeAt(0), buffer.length - 1);
		return buffer;
	},

	_sendAndReceiveSingleCommand = function(command, callback){
		var socket = dgram.createSocket("udp4"),
			responseReceived = false;
		socket.on("message", function(data){
			callback(null, data.toString().replace("����", ""));
			responseReceived = true;
			socket.close();
		})
		.on("error", function(err){
			callback(new Error(err));
		});
		socket.bind(0, null, function(){
			var buffer = _constructRconCommand(command);
			socket.send(buffer, 0, buffer.length, config.cod4.port, config.cod4.address, function(err, bytes){
				if(err){
					console.log(err);
				}
				setTimeout(function(){
					if(!responseReceived){
						callback(new Error("Command timed out."));
					}
				}, config.cod4.commandTimeout);
			});
		});
	};

module.exports = {
	raw: function(command, callback){
		_sendAndReceiveSingleCommand(command, callback);
	},

	status: function(callback){
		_sendAndReceiveSingleCommand("status", function(err, data){
			if(err){
				callback(err);
				return;
			}
			var dataObj = {},
				lines = data.replace("\r", "").split("\n"),
				tokens, inList = false;
			for(var i = 0; i < lines.length; i += 1){
				if(lines[i].indexOf("map:") !== -1){
					tokens = lines[i].split(": ");
					dataObj.map = tokens[1];
				}else if(lines[i].indexOf("--- -----") !== -1){
					inList = true;
					dataObj.players = [];
				}else if(inList === true){
					dataObj.players.push({
						num: lines[i].substring(0, 3),
						score: lines[i].substring(4, 9),
						ping: lines[i].substring(10, 14),
						guid: lines[i].substring(15, 47),
						name: lines[i].substring(48, 63),
						lastmsg: lines[i].substring(64, 71),
						address: lines[i].substring(72, 93),
						qport: lines[i].substring(94, 99),
						rate: lines[i].substring(100)
					});
				}
			}
			callback(null, dataObj);
		});
	},

	gametype: function(callback){
		_sendAndReceiveSingleCommand("g_gametype", function(err, data){
			if(err){
				callback(err);
				return;
			}
			var dataObj = {},
				lines = data.replace("\r", "").split("\n"),
				tokens;
			for(var i = 0; i < lines.length; i += 1){
				if(lines[i].indexOf("\"g_gametype\"") !== -1){
					tokens = lines[i].split(" ");
					dataObj.gametype = tokens[2].replace("\"", "").replace("^7", "");
					dataObj.defaultGametype = tokens[4].replace("\"", "").replace("^7", "");
				}else if(lines[i].indexOf("latched") !== -1){
					tokens = lines[i].split(" ");
					dataObj.latched = tokens[1].replace("\"", "");
				}
			}
			callback(null, dataObj);
		});
	}
}
<|endoftext|>


<commit_before>/*global describe,it,element,by,takeScreenshot,expect,browser,protractor*/

describe('sap.m.MultiComboBox', function() {
	"use strict";

	// Initial loading
	it("should load test page",function(){
		//click over a button that hides the caret when a control is on focus
		element(by.id("customCssButton")).click();
		expect(takeScreenshot()).toLookAs("initial");
	});

	//MultiComboBox - Default
	it("should visualize the first MultiComboBox", function () {
		var firstMultiComboBox = element(by.id("MultiComboBox2"));
		firstMultiComboBox.click();
		expect(takeScreenshot(firstMultiComboBox)).toLookAs("first_multiComboBox");
	});

	//MultiComboBox - default in fullscreen
	it("should visualize the first MultiComboBox - Default in fullscreen", function() {
		var defaultMultiComboBoxArrow = element(by.id("MultiComboBox2-arrow"));
		defaultMultiComboBoxArrow.click();
		expect(takeScreenshot()).toLookAs("default_fullscreen");
		defaultMultiComboBoxArrow.click();
	});

	//MultiComboBox - After backspace
	it("should visualize MultiComboBox after deleting text with backspace", function(){
		var defaultMultiComboBox = element(by.id("MultiComboBox2")),
			defaultMultiComboBoxArrow = element(by.id("MultiComboBox2-arrow"));
		defaultMultiComboBox.click();
		browser.actions().sendKeys("B").perform();
		browser.actions().sendKeys(protractor.Key.BACK_SPACE).perform();
		expect(takeScreenshot()).toLookAs("multicombobox-after-backspace");
		defaultMultiComboBoxArrow.click();
	});

	//MultiComboBox - After arrow navigation
	it("should visualize MultiComboBox after navigating between tokens with arrow key.", function(){
		var defaultMultiComboBox = element(by.id("MultiComboBox1")),
			defaultMultiComboBoxArrow = element(by.id("MultiComboBox1-arrow"));
		defaultMultiComboBox.click();

		browser.actions().sendKeys(protractor.Key.ARROW_LEFT).perform();
		browser.actions().sendKeys(protractor.Key.ARROW_LEFT).perform();
		expect(takeScreenshot()).toLookAs("multicombobox-after-left-arrow-navigation");
		defaultMultiComboBoxArrow.click();
	});

	//MultiComboBox - Filtering
	it("should open first MultiComboBox - Default", function() {
		var defaultMultiComboBox = element(by.id("MultiComboBox0")),
			defaultMultiComboBoxArrow = element(by.id("MultiComboBox0-arrow"));
		defaultMultiComboBox.click();
		browser.actions().sendKeys("B").perform();
		expect(takeScreenshot()).toLookAs("multicombobox-filtering");
		defaultMultiComboBoxArrow.click();
	});

	//MultiComboBox - 50% width
	it("should visualize  a MultiComboBox with 50% width", function(){
		var definedWidthMultiComboBox = element(by.id("MultiComboBox0"));
		definedWidthMultiComboBox.click();
		expect(takeScreenshot(definedWidthMultiComboBox)).toLookAs("fifty_percent_width");
	});

	//MultiComboBox with cropped tokens
	it("should visualize a MultiComboBox with cropped tokens", function(){
		browser.executeScript('sap.ui.getCore().byId("MultiComboBox1").getAggregation("tokenizer").setRenderMode("Loose");')
			.then(function () {
				expect(takeScreenshot( element(by.id("MultiComboBox1")))).toLookAs("cropped_tokens");
			})
			.then(function () {
				browser.executeScript('sap.ui.getCore().byId("MultiComboBox1").getAggregation("tokenizer").setRenderMode("Narrow");');
			});
	});

	//MultiComboBox with selectable disabled list item
	it("should visualize a MultiComboBox with selectable option that was disabled", function(){
		var selectableItemMultiComboBoxArrow = element(by.id("MultiComboBoxDisabledListItemSelectable-arrow"));
		selectableItemMultiComboBoxArrow.click();
		expect(takeScreenshot()).toLookAs("selectable_disabled_item");
		selectableItemMultiComboBoxArrow.click();
	});

	//MultiComboBox - Read only
	it("should visualize a MultiComboBox - Read only", function(){
		browser.executeScript('sap.ui.getCore().byId("MultiComboBoxReadOnly")._oTokenizer.getTokens()[4].setSelected(true);')
		.then(function() {
			var readOnlyMultiComboBox = element(by.id("MultiComboBoxReadOnly"));
			expect(takeScreenshot(readOnlyMultiComboBox)).toLookAs("read_only");
		});
		browser.executeScript('sap.ui.getCore().byId("MultiComboBoxReadOnly")._oTokenizer.getTokens()[4].setSelected(false);');
	});

	//MultiComboBox - Disabled
	it("should visualize a MultiComboBox - Disabled", function(){
		var disabledMultiComboBox = element(by.id("MultiComboBoxDisabled"));
		//click in order to ensure that there is no visual focus presented
		disabledMultiComboBox.click();
		expect(takeScreenshot(disabledMultiComboBox)).toLookAs("disabled");
	});

	//MultiComboBox - Placeholder
	it("should visualize a MultiComboBox with placeholder and without selected items", function(){
		var multiComboBoxPlaceholder = element(by.id("MultiComboBoxWithoutKey"));
		multiComboBoxPlaceholder.click();
		expect(takeScreenshot(multiComboBoxPlaceholder)).toLookAs("placeholder");
	});

	//MultiComboBox - Error state
	it("should visualize a MultiComboBox - Error state", function(){
		var errorStateMultiComboBox = element(by.id("MultiComboBoxError"));
		errorStateMultiComboBox.click();
		//capture the whole page, in order to see the value state text
		expect(takeScreenshot()).toLookAs("error_state");
	});

	//MultiComboBox - Error value state messaage with link
	it("should visualize a MultiComboBox - Error state", function(){
		var errorStateMultiComboBox = element(by.id("MultiComboBoxErrorWithLink"));
		errorStateMultiComboBox.click();
		//capture the whole page, in order to see the value state text
		expect(takeScreenshot()).toLookAs("error_state_with_link");
	});

	//MultiComboBox - Warning state
	it("should visualize a MultiComboBox - Warning State", function(){
		browser.executeScript('document.getElementById("MultiComboBoxWarning").scrollIntoView()').then(function() {
			var warningStateMultiComboBox = element(by.id("MultiComboBoxWarning"));
			warningStateMultiComboBox.click();
			//capture the whole page, in order to see the value state text
			expect(takeScreenshot()).toLookAs("warning_state_with_long_value_state");
		});
	});

	//MultiComboBox - Warning value state messaage with link
	it("should visualize a MultiComboBox - Warning State", function(){
		browser.executeScript('document.getElementById("MultiComboBoxWarning").scrollIntoView()').then(function() {
			var warningStateMultiComboBox = element(by.id("MultiComboBoxWarningWithLinks"));
			warningStateMultiComboBox.click();
			//capture the whole page, in order to see the value state text
			expect(takeScreenshot()).toLookAs("warning_state_with_link");
		});
	});

	//MultiComboBox - Success state
	it("should visualize a MultiComboBox - Success state", function(){
		browser.executeScript('document.getElementById("MultiComboBoxSuccess").scrollIntoView()').then(function() {
			var successStateMultiComboBox = element(by.id("MultiComboBoxSuccess"));
			successStateMultiComboBox.click();
			expect(takeScreenshot(successStateMultiComboBox)).toLookAs("success_state");
		});
	});

	//MultiComboBox - Binding
	it("should visualize a MultiComboBox with binding", function(){
		browser.executeScript('document.getElementById("MultiComboBoxBinding").scrollIntoView()').then(function() {
			var bindingMultiComboBox = element(by.id("MultiComboBoxBinding")),
				bindingMultiComboBoxArrow = element(by.id("MultiComboBoxBinding-arrow"));
			bindingMultiComboBoxArrow.click();
			browser.actions().sendKeys(protractor.Key.SPACE).perform();
			bindingMultiComboBoxArrow.click();
			expect(takeScreenshot(bindingMultiComboBox)).toLookAs("multiComboBox_binding_initially_selected");
		});

		browser.executeScript('document.getElementById("page1-navButton").scrollIntoView()').then(function() {
			element(by.id("page1-navButton")).click();
			element(by.id("page2-navButton")).click();
		});

		browser.executeScript('document.getElementById("MultiComboBoxBinding").scrollIntoView()').then(function() {
			var bindingMultiComboBox = element(by.id("MultiComboBoxBinding"));
			bindingMultiComboBox.click();
			expect(takeScreenshot(bindingMultiComboBox)).toLookAs("multiComboBox_binding_after_navigation");
		});
	});

	//MultiComboBox - Last selected item
	it("should visualize a MultiComboBox and select the last item to check if the popover have unnecessary scroll", function(){
		browser.executeScript('document.getElementById("MultiComboBoxFourItems").scrollIntoView()').then(function() {
			element(by.id("MultiComboBoxFourItems-arrow")).click();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.SPACE).perform();
			expect(takeScreenshot()).toLookAs("multiComboBox_with_selected_last_item");
		});
	});

	// MultiComboBox - dropwdown selection
	it("should visualize a MultiComboBox dropdown with correct selection", function() {
		browser.executeScript('document.getElementById("MultiComboBoxBinding").scrollIntoView()').then(function() {
			var oMultiComboBox = element(by.id("MultiComboBoxBinding"));
			var oMultiComboBoxArrow = element(by.id("MultiComboBoxBinding-arrow"));
			oMultiComboBox.click();
			browser.actions().sendKeys(protractor.Key.BACK_SPACE).perform();
			browser.actions().sendKeys(protractor.Key.BACK_SPACE).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			// simulate dropdown icon click
			oMultiComboBoxArrow.click();
			expect(takeScreenshot()).toLookAs("multiComboBox_dropdown_selection");
		});
	});

	//MultiComboBox Compact Mode
	it("should select Compact mode", function(){
		element(by.id("compactMode")).click();
		expect(takeScreenshot()).toLookAs("compact_mode");
		element(by.id("compactMode")).click();
	});
});
<commit_msg>[INTERNAL] sap.m.MultiComboBox: Visual tests adjusted<commit_after>/*global describe,it,element,by,takeScreenshot,expect,browser,protractor*/

describe('sap.m.MultiComboBox', function() {
	"use strict";

	// Initial loading
	it("should load test page",function(){
		//click over a button that hides the caret when a control is on focus
		element(by.id("customCssButton")).click();
		expect(takeScreenshot()).toLookAs("initial");
	});

	//MultiComboBox - Default
	it("should visualize the first MultiComboBox", function () {
		var firstMultiComboBox = element(by.id("MultiComboBox2"));
		firstMultiComboBox.click();
		expect(takeScreenshot(firstMultiComboBox)).toLookAs("first_multiComboBox");
	});

	//MultiComboBox - default in fullscreen
	it("should visualize the first MultiComboBox - Default in fullscreen", function() {
		var defaultMultiComboBoxArrow = element(by.id("MultiComboBox2-arrow"));
		defaultMultiComboBoxArrow.click();
		expect(takeScreenshot()).toLookAs("default_fullscreen");
		defaultMultiComboBoxArrow.click();
	});

	//MultiComboBox - After backspace
	it("should visualize MultiComboBox after deleting text with backspace", function(){
		var defaultMultiComboBox = element(by.id("MultiComboBox2")),
			defaultMultiComboBoxArrow = element(by.id("MultiComboBox2-arrow"));
		defaultMultiComboBox.click();
		browser.actions().sendKeys("B").perform();
		browser.actions().sendKeys(protractor.Key.BACK_SPACE).perform();
		expect(takeScreenshot()).toLookAs("multicombobox-after-backspace");
		defaultMultiComboBoxArrow.click();
	});

	//MultiComboBox - After arrow navigation
	it("should visualize MultiComboBox after navigating between tokens with arrow key.", function(){
		var defaultMultiComboBox = element(by.id("MultiComboBox1"));

		defaultMultiComboBox.click();
		browser.actions().sendKeys(protractor.Key.ARROW_LEFT).perform();
		browser.actions().sendKeys(protractor.Key.ARROW_LEFT).perform();
		expect(takeScreenshot()).toLookAs("multicombobox-left-arrow-navigation");
	});

	//MultiComboBox - Filtering
	it("should open first MultiComboBox - Default", function() {
		var defaultMultiComboBox = element(by.id("MultiComboBox0")),
			defaultMultiComboBoxArrow = element(by.id("MultiComboBox0-arrow"));
		defaultMultiComboBox.click();
		browser.actions().sendKeys("B").perform();
		expect(takeScreenshot()).toLookAs("multicombobox-filtering");
		defaultMultiComboBoxArrow.click();
	});

	//MultiComboBox - 50% width
	it("should visualize  a MultiComboBox with 50% width", function(){
		var definedWidthMultiComboBox = element(by.id("MultiComboBox0"));
		definedWidthMultiComboBox.click();
		expect(takeScreenshot(definedWidthMultiComboBox)).toLookAs("fifty_percent_width");
	});

	//MultiComboBox with cropped tokens
	it("should visualize a MultiComboBox with cropped tokens", function(){
		var croppedTokensMultiComboBox = element(by.id("MultiComboBox1"));
		croppedTokensMultiComboBox.click();
		expect(takeScreenshot( element(by.id("MultiComboBox1")))).toLookAs("cropped_tokens");
	});

	//MultiComboBox with selectable disabled list item
	it("should visualize a MultiComboBox with selectable option that was disabled", function(){
		var selectableItemMultiComboBoxArrow = element(by.id("MultiComboBoxDisabledListItemSelectable-arrow"));
		selectableItemMultiComboBoxArrow.click();
		expect(takeScreenshot()).toLookAs("selectable_disabled_item");
		selectableItemMultiComboBoxArrow.click();
	});

	//MultiComboBox - Read only
	it("should visualize a MultiComboBox - Read only", function(){
		browser.executeScript('sap.ui.getCore().byId("MultiComboBoxReadOnly")._oTokenizer.getTokens()[4].setSelected(true);')
		.then(function() {
			var readOnlyMultiComboBox = element(by.id("MultiComboBoxReadOnly"));
			expect(takeScreenshot(readOnlyMultiComboBox)).toLookAs("read_only");
		});
		browser.executeScript('sap.ui.getCore().byId("MultiComboBoxReadOnly")._oTokenizer.getTokens()[4].setSelected(false);');
	});

	//MultiComboBox - Disabled
	it("should visualize a MultiComboBox - Disabled", function(){
		var disabledMultiComboBox = element(by.id("MultiComboBoxDisabled"));
		//click in order to ensure that there is no visual focus presented
		disabledMultiComboBox.click();
		expect(takeScreenshot(disabledMultiComboBox)).toLookAs("disabled");
	});

	//MultiComboBox - Placeholder
	it("should visualize a MultiComboBox with placeholder and without selected items", function(){
		var multiComboBoxPlaceholder = element(by.id("MultiComboBoxWithoutKey"));
		multiComboBoxPlaceholder.click();
		expect(takeScreenshot(multiComboBoxPlaceholder)).toLookAs("placeholder");
	});

	//MultiComboBox - Error state
	it("should visualize a MultiComboBox - Error state", function(){
		var errorStateMultiComboBox = element(by.id("MultiComboBoxError"));
		errorStateMultiComboBox.click();
		//capture the whole page, in order to see the value state text
		expect(takeScreenshot()).toLookAs("error_state");
	});

	//MultiComboBox - Error value state messaage with link
	it("should visualize a MultiComboBox - Error state", function(){
		var errorStateMultiComboBox = element(by.id("MultiComboBoxErrorWithLink"));
		errorStateMultiComboBox.click();
		//capture the whole page, in order to see the value state text
		expect(takeScreenshot()).toLookAs("error_state_with_link");
	});

	//MultiComboBox - Warning state
	it("should visualize a MultiComboBox - Warning State", function(){
		browser.executeScript('document.getElementById("MultiComboBoxWarning").scrollIntoView()').then(function() {
			var warningStateMultiComboBox = element(by.id("MultiComboBoxWarning"));
			warningStateMultiComboBox.click();
			//capture the whole page, in order to see the value state text
			expect(takeScreenshot()).toLookAs("warning_state_with_long_value_state");
		});
	});

	//MultiComboBox - Warning value state messaage with link
	it("should visualize a MultiComboBox - Warning State", function(){
		browser.executeScript('document.getElementById("MultiComboBoxWarning").scrollIntoView()').then(function() {
			var warningStateMultiComboBox = element(by.id("MultiComboBoxWarningWithLinks"));
			warningStateMultiComboBox.click();
			//capture the whole page, in order to see the value state text
			expect(takeScreenshot()).toLookAs("warning_state_with_link");
		});
	});

	//MultiComboBox - Success state
	it("should visualize a MultiComboBox - Success state", function(){
		browser.executeScript('document.getElementById("MultiComboBoxSuccess").scrollIntoView()').then(function() {
			var successStateMultiComboBox = element(by.id("MultiComboBoxSuccess"));
			successStateMultiComboBox.click();
			expect(takeScreenshot(successStateMultiComboBox)).toLookAs("success_state");
		});
	});

	//MultiComboBox - Binding
	it("should visualize a MultiComboBox with binding", function(){
		browser.executeScript('document.getElementById("MultiComboBoxBinding").scrollIntoView()').then(function() {
			var bindingMultiComboBox = element(by.id("MultiComboBoxBinding")),
				bindingMultiComboBoxArrow = element(by.id("MultiComboBoxBinding-arrow"));
			bindingMultiComboBoxArrow.click();
			browser.actions().sendKeys(protractor.Key.SPACE).perform();
			bindingMultiComboBoxArrow.click();
			expect(takeScreenshot(bindingMultiComboBox)).toLookAs("multiComboBox_binding_initially_selected");
		});

		browser.executeScript('document.getElementById("page1-navButton").scrollIntoView()').then(function() {
			element(by.id("page1-navButton")).click();
			element(by.id("page2-navButton")).click();
		});

		browser.executeScript('document.getElementById("MultiComboBoxBinding").scrollIntoView()').then(function() {
			var bindingMultiComboBox = element(by.id("MultiComboBoxBinding"));
			bindingMultiComboBox.click();
			expect(takeScreenshot(bindingMultiComboBox)).toLookAs("multiComboBox_binding_after_navigation");
		});
	});

	//MultiComboBox - Last selected item
	it("should visualize a MultiComboBox and select the last item to check if the popover have unnecessary scroll", function(){
		browser.executeScript('document.getElementById("MultiComboBoxFourItems").scrollIntoView()').then(function() {
			element(by.id("MultiComboBoxFourItems-arrow")).click();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.SPACE).perform();
			expect(takeScreenshot()).toLookAs("multiComboBox_with_selected_last_item");
		});
	});

	// MultiComboBox - dropwdown selection
	it("should visualize a MultiComboBox dropdown with correct selection", function() {
		browser.executeScript('document.getElementById("MultiComboBoxBinding").scrollIntoView()').then(function() {
			var oMultiComboBox = element(by.id("MultiComboBoxBinding"));
			var oMultiComboBoxArrow = element(by.id("MultiComboBoxBinding-arrow"));
			oMultiComboBox.click();
			browser.actions().sendKeys(protractor.Key.BACK_SPACE).perform();
			browser.actions().sendKeys(protractor.Key.BACK_SPACE).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			browser.actions().sendKeys(protractor.Key.ARROW_DOWN).perform();
			// simulate dropdown icon click
			oMultiComboBoxArrow.click();
			expect(takeScreenshot()).toLookAs("multiComboBox_dropdown_selection");
		});
	});

	//MultiComboBox Compact Mode
	it("should select Compact mode", function(){
		element(by.id("compactMode")).click();
		expect(takeScreenshot()).toLookAs("compact_mode");
		element(by.id("compactMode")).click();
	});
});
<|endoftext|>


<commit_before>import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
import {Wrapper} from "./Wrapper";

/**
 * Container Component for BuildSnapshots.
 *
 * @param {*} props input property containing an array of build data to be
 * rendered through BuildSnapshot.
 */
export const BuildSnapshotContainer = (props) => {
  const SOURCE = '/data';
  const [data, setData] = React.useState([]);

  /* Fetch data when component is mounted.
   * Pass in empty array as second paramater to prevent
   * Infinite callbacks as component refreshes.
   * @see Here
  */
  React.useEffect(() => fetch(SOURCE).then(res => setData(res.json())), []);

  return (
    <Wrapper>
      {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)}
    </Wrapper>
  );
}
<commit_msg>Memoize component and Update javadoc<commit_after>import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
import {Wrapper} from "./Wrapper";

/**
 * Container Component for BuildSnapshots.
 *
 * @param {*} props input property containing an array of build data to be
 * rendered through BuildSnapshot.
 */
export const BuildSnapshotContainer = React.memo((props) => {
    const SOURCE = '/data';
    const [data, setData] = React.useState([]);

    /**
    * Fetch data when component is mounted.
    * Pass in empty array as second paramater to prevent
    * Infinite callbacks as component refreshes.
    * @see Fetching
    */
    React.useEffect(() => fetch(SOURCE).then(res => setData(res.json())), []);

    return (
      <Wrapper>
        {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)}
      </Wrapper>
    );
  }
);
<|endoftext|>


<commit_before>console.log('Love you, Anton ;) 🐱');

var eventData = [
  {
    "date": "January 31st 2015",
    "name": "Cal Aggie Criterium"
 },
  {
    "date": "February 7th 2015",
    "name": "John C. Schlesinger Memorial Circuit Race and Team Time Trial"
 },
  {
    "date": "February 8th 2015",
    "name": "RED KITE OMNIUM EVENT #1 - THE BUMP CIRCUIT RACE (WINTER)"
 // },
 //  {
 //    "date": "February 8th 2015",
 //    "name": "Christopher Castro Memorial Road Race "
 // },
 //  {
 //    "date": "February 14th 2015",
 //    "name": "Folsom Winter Criterium"
 // },
 //  {
 //    "date": "February 15th 2015",
 //    "name": "Pine Flat Road Race"
 // },
 //  {
 //    "date": "February 16th 2015",
 //    "name": "Dinuba Criterium"
 // },
 //  {
 //    "date": "February 21st 2015",
 //    "name": "Snelling Road Race"
 // },
 //  {
 //    "date": "February 21st 2015",
 //    "name": "UC Santa Cruz Slugapalooza"
 // },
 //  {
 //    "date": "February 22nd 2015",
 //    "name": "Original Merced Criterium"
 // },
 //  {
 //    "date": "February 27th 2015",
 //    "name": "Chico Stage Race p/b Sierra Nevada Brewing Co."
 // },
 //  {
 //    "date": "March 6th 2015",
 //    "name": "Madera County Stage Race"
 // },
 //  {
 //    "date": "March 8th 2015",
 //    "name": "RED KITE OMNIUM EVENT #2 - RED KITE CRITERIUM (MARCH)"
 // },
 //  {
 //    "date": "March 14th 2015",
 //    "name": "Wards Ferry Road Race"
 // },
 //  {
 //    "date": "March 21st 2015",
 //    "name": "UC Merced Race Weekend"
 // },
 //  {
 //    "date": "March 22nd 2015",
 //    "name": "RED KITE OMNIUM EVENT #3 - TEMPUS FUGIT INDIVIDUAL TIME TRIAL (SP"
 // },
 //  {
 //    "date": "March 22nd 2015",
 //    "name": "Chowcilla Criterium"
 // },
 //  {
 //    "date": "March 28th 2015",
 //    "name": "Fresno State Road Race Weekend"
 // },
 //  {
 //    "date": "March 28th 2015",
 //    "name": "Turlock lake Road Race"
 // },
 //  {
 //    "date": "March 29th 2015",
 //    "name": "Santa Cruz Classic Criterium"
 // },
 //  {
 //    "date": "April 4th 2015",
 //    "name": "Copperopolis Road Race"
 // },
 //  {
 //    "date": "April 19th 2015",
 //    "name": "RED KITE OMNIUM EVENT #4 - RED KITE CRITERIUM (APRIL)"
 // },
 //  {
 //    "date": "April 25th 2015",
 //    "name": "WCCC Championships p/b Cal Cycling"
 // },
 //  {
 //    "date": "April 25th 2015",
 //    "name": "Clovis Hills Criterium"
 // },
 //  {
 //    "date": "April 26th 2015",
 //    "name": "Budweiser Sequoia Cycling Classic"
 // },
 //  {
 //    "date": "April 26th 2015",
 //    "name": "Wente Vineyards Classic Road Race"
 // },
 //  {
 //    "date": "May 2nd 2015",
 //    "name": "Mike's Bikes 42nd Cat’s Hill Classic"
 // },
 //  {
 //    "date": "May 2nd 2015",
 //    "name": "Golden State Race Series"
 // },
 //  {
 //    "date": "May 3rd 2015",
 //    "name": "Salinas Criterium"
 // },
 //  {
 //    "date": "May 3rd 2015",
 //    "name": "Calaveras Time Trial "
 // },
 //  {
 //    "date": "May 8th 2015",
 //    "name": "Tour of California Women's Edition"
 // },
 //  {
 //    "date": "May 8th 2015",
 //    "name": "Honor Ride Lake Tahoe"
 // },
 //  {
 //    "date": "May 9th 2015",
 //    "name": "Berkeley Hills Road Race"
 // },
 //  {
 //    "date": "May 10th 2015",
 //    "name": "RED KITE OMNIUM EVENT #6 - RED KITE CRITERIUM (MAY)"
 // },
 //  {
 //    "date": "May 15th 2015",
 //    "name": "Mariposa Women's Stage Race"
 // },
 //  {
 //    "date": "May 23rd 2015",
 //    "name": "Death Valley Road Omnium"
 // },
 //  {
 //    "date": "May 23rd 2015",
 //    "name": "Folsom Classic Criterium"
 // },
 //  {
 //    "date": "May 25th 2015",
 //    "name": "Memorial Day Criterium"
 // },
 //  {
 //    "date": "May 30th 2015",
 //    "name": "IC3 Dash for Cash"
 // },
 //  {
 //    "date": "May 31st 2015",
 //    "name": "RED KITE OMNIUM EVENT #7 - THE BUMP CIRCUIT RACE (SPRING)"
 // },
 //  {
 //    "date": "June 6th 2015",
 //    "name": "Pescadero Coastal Classic & Elite District Championship"
 // },
 //  {
 //    "date": "June 20th 2015",
 //    "name": "RED KITE OMNIUM EVENT #8 - TRI-VALLEY CRITERIUM CLASSIC"
 // },
 //  {
 //    "date": "June 21st 2015",
 //    "name": "55th Annual Nevada City Bicycle Classic"
 // },
 //  {
 //    "date": "December 1st 2015",
 //    "name": "2015 USA Cycling Amateur Road Nationals"
 // },
 //  {
 //    "date": "June 28th 2015",
 //    "name": "The Parnassus Investments Burlingame Criterium"
 // },
 //  {
 //    "date": "July 4th 2015",
 //    "name": "Davis Bike Club 4th of July Criterium"
 // },
 //  {
 //    "date": "July 5th 2015",
 //    "name": " Lodoga Road Race (Formerly Leesville)"
 // },
 //  {
 //    "date": "July 11th 2015",
 //    "name": "Northern CA/NV District Championships"
 // },
 //  {
 //    "date": "July 12th 2015",
 //    "name": "RED KITE OMNIUM EVENT #9 - RED KITE CRITERIUM (JULY)"
 // },
 //  {
 //    "date": "July 25th 2015",
 //    "name": "San Rafael Twilight Criterium"
 // },
 //  {
 //    "date": "July 26th 2015",
 //    "name": "RED KITE OMNIUM EVENT #11 - 31st ANNUAL BERKELEY BICYCLE CLUB CRITERIU"
 // },
 //  {
 //    "date": "August 9th 2015",
 //    "name": "RED KITE OMNIUM EVENT #12 - RED KITE CRITERIUM (AUGUST)"
 // },
 //  {
 //    "date": "August 15th 2015",
 //    "name": "Dunnigan Hills Road Race"
 // },
 //  {
 //    "date": "August 23rd 2015",
 //    "name": "RED KITE OMNIUM EVENT #13 - TEMPUS FUGIT INDIVIDUAL TIME TRIAL (S"
 // },
 //  {
 //    "date": "August 23rd 2015",
 //    "name": "University Road Race"
 // },
 //  {
 //    "date": "August 29th 2015",
 //    "name": "Winters Road Race"
 // },
 //  {
 //    "date": "August 30th 2015",
 //    "name": "Vacaville Gran Prix"
 // },
 //  {
 //    "date": "September 5th 2015",
 //    "name": "RED KITE CHAMPIONSHIP WEEKEND - RED KITE OMNIUM AND NCNCA STATE CRITER"
 // },
 //  {
 //    "date": "September 7th 2015",
 //    "name": "Giro Di San Francisco"
 // },
 //  {
 //    "date": "September 12th 2015",
 //    "name": "52nd Mt. Tamalpais Hill Climb"
 // },
 //  {
 //    "date": "September 20th 2015",
 //    "name": "Fremont Peak Hill CLimb"
 // },
 //  {
 //    "date": "September 20th 2015",
 //    "name": "Oakland Grand Prix"
 // },
 //  {
 //    "date": "September 26th 2015",
 //    "name": "Henleyville Road Race"
 // },
 //  {
 //    "date": "September 27th 2015",
 //    "name": "Esparto Time Trial"
 // },
 //  {
 //    "date": "October 10th 2015",
 //    "name": "Crush Challenge presented by Amgen"
 // },
 //  {
 //    "date": "October 11th 2015",
 //    "name": "Dylan's 2015 Ride"
 }
];

var disciplineData = ["Road", "MTB", "Track", "Cyclocross", "Clinic"];
var typeData = ["Road Race", "Criterium", "Cyclocross", "Time Trial", "Cross Country", "Cross Country Marathon", "Downhill", "Dual Slalom", "Short Track Cross Country", "Super D", "Points Race", "Scratch Race", "Individual Pursuit", "Sprint", "Keirin"];
var timeData = ["8:00 AM", "8:30 AM", "9:00 AM", "9:20 AM", "10:00 AM", "10:15 AM", "11:40 AM", "12:00 PM", "12:03 PM", "1:00 PM", "1:55 PM", "2:00 PM", "2:18 PM"];
var promoterData = ["2 Wheel Racing", "Alta Alpina Cycling Club", "Alto Velo", "AntiGravity Cycling", "Back of Nowhere Enterprises", "Berkeley Bicycle Club", "Bicycle Planet", "Bicycles Plus",
"Bike Monkey", "Bike Station Aptos", "Brian Joder", "Bubba Melcher", "Cal Aggie Cycling", "Cal Cycling", "California Giant Cycling Team", "CCCX (Central Coast Cyclocross)", "Central Sierra Cyclists",
"Chico Corsa Cycling Club", "China Peak Mountain Resort"];
var streetData = ["Kearny Street", "Mission Street", "Polk Street", "Stockton Street", "Union Street", "Third Street", "22nd Street", "49-Mile Scenic Drive", "Alemany Boulevard", "Broadway",
"Castro Street", "The Embarcadero", "Filbert Street", "Great Highway", "Haight Street", "Montgomery Street", "New Montgomery Street", "Octavia Boulevard", "Skyline Boulevard", "Vermont Street", "Howard Street"];
var cityData = ["Ross", "Sacramento", "St. Helena", "Salinas", "San Anselmo", "San Bernardino", "San Bruno", "San Carlos", "San Clemente", "San Diego", "San Dimas","San Fernando", "San Francisco", "San Gabriel",
"San Jacinto", "San Joaquin", "San Jose", "San Juan Bautista", "San Juan Capistrano", "San Leandro"];

var fullEventData = eventData.map(function(element){
    var newObject = {
        id: "evt-" + getRandomNumber(10000000, 99999999),
        discipline: getRandomDiscipline(),
        type: getRandomType(),
        name: element.name,
        date: element.date,
        distanceMi: getRandomNumber(1, 200) + " Mi",
        durationMin: getRandomNumber(5, 180) + " Min",
        elevationGainFt: getRandomNumber(0, 2000) + " ft",
        startTime: getRandomTime(),
        promoter: getRandomPromoter(),
        location: {
            streetAddress: getRandomNumber(1, 1999) + " " + getRandomStreet(),
            city: getRandomCity(),
            state: "CA",
            zip: "9" + getRandomNumber(1000, 9999)
        },
        distanceToEventMi: getRandomNumber(1, 200) + " Mi",
        estimatedTravelTime: getRandomNumber(1, 5) + " h",
        flyerUrl: "http://www.ncnca.org/sites/default/files/01/01/2014%20-%202%3A29am/183%20San%20Bruno%20Mountain%20Hill%20Climb%20OKED%203.pdf",
        registrationUrl: "https://www.usacycling.org/register/2014-183"
    };
    return newObject;
});
console.log(fullEventData);

function getRandomNumber(startNumber, endNumber){
    return Math.floor((Math.random() * endNumber) + startNumber);
};

function getRandomDiscipline(){
    return disciplineData[getRandomNumber(0,disciplineData.length)];
};
function getRandomType(){
    return typeData[getRandomNumber(0,typeData.length)];
};
function getRandomTime(){
    return timeData[getRandomNumber(0,timeData.length)];
};
function getRandomPromoter(){
    return promoterData[getRandomNumber(0,promoterData.length)];
};
function getRandomStreet(){
    return streetData[getRandomNumber(0,streetData.length)];
};
function getRandomCity(){
    return cityData[getRandomNumber(0,cityData.length)];
}<commit_msg>replaced " with ' and minor reformatting to confirm to our coding standard + added util.inspect to show colored output in console<commit_after>import util from 'util';

console.log('Love you, Anton ;) 🐱');

var eventData = [{
  'date': 'January 31st 2015',
  'name': 'Cal Aggie Criterium'
}, {
  'date': 'February 7th 2015',
  'name': 'John C. Schlesinger Memorial Circuit Race and Team Time Trial'
}, {
  'date': 'February 8th 2015',
  'name': 'RED KITE OMNIUM EVENT #1 - THE BUMP CIRCUIT RACE (WINTER)'
}, /*{
  'date': 'February 8th 2015',
  'name': 'Christopher Castro Memorial Road Race '
}, {
  'date': 'February 14th 2015',
  'name': 'Folsom Winter Criterium'
}, {
  'date': 'February 15th 2015',
  'name': 'Pine Flat Road Race'
}, {
  'date': 'February 16th 2015',
  'name': 'Dinuba Criterium'
}, {
  'date': 'February 21st 2015',
  'name': 'Snelling Road Race'
}, {
  'date': 'February 21st 2015',
  'name': 'UC Santa Cruz Slugapalooza'
}, {
  'date': 'February 22nd 2015',
  'name': 'Original Merced Criterium'
}, {
  'date': 'February 27th 2015',
  'name': 'Chico Stage Race p/b Sierra Nevada Brewing Co.'
}, {
  'date': 'March 6th 2015',
  'name': 'Madera County Stage Race'
}, {
  'date': 'March 8th 2015',
  'name': 'RED KITE OMNIUM EVENT #2 - RED KITE CRITERIUM (MARCH)'
}, {
  'date': 'March 14th 2015',
  'name': 'Wards Ferry Road Race'
}, {
  'date': 'March 21st 2015',
  'name': 'UC Merced Race Weekend'
}, {
  'date': 'March 22nd 2015',
  'name': 'RED KITE OMNIUM EVENT #3 - TEMPUS FUGIT INDIVIDUAL TIME TRIAL (SP'
}, {
  'date': 'March 22nd 2015',
  'name': 'Chowcilla Criterium'
}, {
  'date': 'March 28th 2015',
  'name': 'Fresno State Road Race Weekend'
}, {
  'date': 'March 28th 2015',
  'name': 'Turlock lake Road Race'
}, {
  'date': 'March 29th 2015',
  'name': 'Santa Cruz Classic Criterium'
}, {
  'date': 'April 4th 2015',
  'name': 'Copperopolis Road Race'
}, {
  'date': 'April 19th 2015',
  'name': 'RED KITE OMNIUM EVENT #4 - RED KITE CRITERIUM (APRIL)'
}, {
  'date': 'April 25th 2015',
  'name': 'WCCC Championships p/b Cal Cycling'
}, {
  'date': 'April 25th 2015',
  'name': 'Clovis Hills Criterium'
}, {
  'date': 'April 26th 2015',
  'name': 'Budweiser Sequoia Cycling Classic'
}, {
  'date': 'April 26th 2015',
  'name': 'Wente Vineyards Classic Road Race'
}, {
  'date': 'May 2nd 2015',
  'name': 'Mike'
  s Bikes 42 nd Cat’ s Hill Classic '
}, {
  'date': 'May 2nd 2015',
  'name': 'Golden State Race Series'
}, {
  'date': 'May 3rd 2015',
  'name': 'Salinas Criterium'
}, {
  'date': 'May 3rd 2015',
  'name': 'Calaveras Time Trial '
}, {
  'date': 'May 8th 2015',
  'name': 'Tour of California Women'
  s Edition '
}, {
  'date': 'May 8th 2015',
  'name': 'Honor Ride Lake Tahoe'
}, {
  'date': 'May 9th 2015',
  'name': 'Berkeley Hills Road Race'
}, {
  'date': 'May 10th 2015',
  'name': 'RED KITE OMNIUM EVENT #6 - RED KITE CRITERIUM (MAY)'
}, {
  'date': 'May 15th 2015',
  'name': 'Mariposa Women'
  s Stage Race '
}, {
  'date': 'May 23rd 2015',
  'name': 'Death Valley Road Omnium'
}, {
  'date': 'May 23rd 2015',
  'name': 'Folsom Classic Criterium'
}, {
  'date': 'May 25th 2015',
  'name': 'Memorial Day Criterium'
}, {
  'date': 'May 30th 2015',
  'name': 'IC3 Dash for Cash'
}, {
  'date': 'May 31st 2015',
  'name': 'RED KITE OMNIUM EVENT #7 - THE BUMP CIRCUIT RACE (SPRING)'
}, {
  'date': 'June 6th 2015',
  'name': 'Pescadero Coastal Classic & Elite District Championship'
}, {
  'date': 'June 20th 2015',
  'name': 'RED KITE OMNIUM EVENT #8 - TRI-VALLEY CRITERIUM CLASSIC'
}, {
  'date': 'June 21st 2015',
  'name': '55th Annual Nevada City Bicycle Classic'
}, {
  'date': 'December 1st 2015',
  'name': '2015 USA Cycling Amateur Road Nationals'
}, {
  'date': 'June 28th 2015',
  'name': 'The Parnassus Investments Burlingame Criterium'
}, {
  'date': 'July 4th 2015',
  'name': 'Davis Bike Club 4th of July Criterium'
}, {
  'date': 'July 5th 2015',
  'name': ' Lodoga Road Race (Formerly Leesville)'
}, {
  'date': 'July 11th 2015',
  'name': 'Northern CA/NV District Championships'
}, {
  'date': 'July 12th 2015',
  'name': 'RED KITE OMNIUM EVENT #9 - RED KITE CRITERIUM (JULY)'
}, {
  'date': 'July 25th 2015',
  'name': 'San Rafael Twilight Criterium'
}, {
  'date': 'July 26th 2015',
  'name': 'RED KITE OMNIUM EVENT #11 - 31st ANNUAL BERKELEY BICYCLE CLUB CRITERIU'
}, {
  'date': 'August 9th 2015',
  'name': 'RED KITE OMNIUM EVENT #12 - RED KITE CRITERIUM (AUGUST)'
}, {
  'date': 'August 15th 2015',
  'name': 'Dunnigan Hills Road Race'
}, {
  'date': 'August 23rd 2015',
  'name': 'RED KITE OMNIUM EVENT #13 - TEMPUS FUGIT INDIVIDUAL TIME TRIAL (S'
}, {
  'date': 'August 23rd 2015',
  'name': 'University Road Race'
}, {
  'date': 'August 29th 2015',
  'name': 'Winters Road Race'
}, {
  'date': 'August 30th 2015',
  'name': 'Vacaville Gran Prix'
}, {
  'date': 'September 5th 2015',
  'name': 'RED KITE CHAMPIONSHIP WEEKEND - RED KITE OMNIUM AND NCNCA STATE CRITER'
}, {
  'date': 'September 7th 2015',
  'name': 'Giro Di San Francisco'
}, {
  'date': 'September 12th 2015',
  'name': '52nd Mt. Tamalpais Hill Climb'
}, {
  'date': 'September 20th 2015',
  'name': 'Fremont Peak Hill CLimb'
}, {
  'date': 'September 20th 2015',
  'name': 'Oakland Grand Prix'
}, {
  'date': 'September 26th 2015',
  'name': 'Henleyville Road Race'
}, {
  'date': 'September 27th 2015',
  'name': 'Esparto Time Trial'
}, {
  'date': 'October 10th 2015',
  'name': 'Crush Challenge presented by Amgen'
}, {
  'date': 'October 11th 2015',
  'name': 'Dylan'
  s 2015 Ride '
} */
];

var disciplineData = ['Road', 'MTB', 'Track', 'Cyclocross', 'Clinic'];
var typeData = ['Road Race', 'Criterium', 'Cyclocross', 'Time Trial', 'Cross Country', 'Cross Country Marathon', 'Downhill', 'Dual Slalom', 'Short Track Cross Country', 'Super D', 'Points Race', 'Scratch Race', 'Individual Pursuit', 'Sprint', 'Keirin'];
var timeData = ['8:00 AM', '8:30 AM', '9:00 AM', '9:20 AM', '10:00 AM', '10:15 AM', '11:40 AM', '12:00 PM', '12:03 PM', '1:00 PM', '1:55 PM', '2:00 PM', '2:18 PM'];
var promoterData = ['2 Wheel Racing', 'Alta Alpina Cycling Club', 'Alto Velo', 'AntiGravity Cycling', 'Back of Nowhere Enterprises', 'Berkeley Bicycle Club', 'Bicycle Planet', 'Bicycles Plus',
  'Bike Monkey', 'Bike Station Aptos', 'Brian Joder', 'Bubba Melcher', 'Cal Aggie Cycling', 'Cal Cycling', 'California Giant Cycling Team', 'CCCX (Central Coast Cyclocross)', 'Central Sierra Cyclists',
  'Chico Corsa Cycling Club', 'China Peak Mountain Resort'
];
var streetData = ['Kearny Street', 'Mission Street', 'Polk Street', 'Stockton Street', 'Union Street', 'Third Street', '22nd Street', '49-Mile Scenic Drive', 'Alemany Boulevard', 'Broadway',
  'Castro Street', 'The Embarcadero', 'Filbert Street', 'Great Highway', 'Haight Street', 'Montgomery Street', 'New Montgomery Street', 'Octavia Boulevard', 'Skyline Boulevard', 'Vermont Street', 'Howard Street'
];
var cityData = ['Ross', 'Sacramento', 'St. Helena', 'Salinas', 'San Anselmo', 'San Bernardino', 'San Bruno', 'San Carlos', 'San Clemente', 'San Diego', 'San Dimas', 'San Fernando', 'San Francisco', 'San Gabriel',
  'San Jacinto', 'San Joaquin', 'San Jose', 'San Juan Bautista', 'San Juan Capistrano', 'San Leandro'
];

var fullEventData = eventData.map(function(element) {
  var newObject = {
    id: 'evt-' + getRandomNumber(10000000, 99999999),
    discipline: getRandomDiscipline(),
    type: getRandomType(),
    name: element.name,
    date: element.date,
    distanceMi: getRandomNumber(1, 200) + ' Mi',
    durationMin: getRandomNumber(5, 180) + ' Min',
    elevationGainFt: getRandomNumber(0, 2000) + ' ft',
    startTime: getRandomTime(),
    promoter: getRandomPromoter(),
    location: {
      streetAddress: getRandomNumber(1, 1999) + ' ' + getRandomStreet(),
      city: getRandomCity(),
      state: 'CA',
      zip: '9' + getRandomNumber(1000, 9999)
    },
    distanceToEventMi: getRandomNumber(1, 200) + ' Mi',
    estimatedTravelTime: getRandomNumber(1, 5) + ' h',
    flyerUrl: 'http://www.ncnca.org/sites/default/files/01/01/2014%20-%202%3A29am/183%20San%20Bruno%20Mountain%20Hill%20Climb%20OKED%203.pdf',
    registrationUrl: 'https://www.usacycling.org/register/2014-183'
  };
  return newObject;
});

console.log(util.inspect(fullEventData, {colors: true}));

function getRandomNumber(startNumber, endNumber) {
  return Math.floor((Math.random() * endNumber) + startNumber);
};

function getRandomDiscipline() {
  return disciplineData[getRandomNumber(0, disciplineData.length)];
};

function getRandomType() {
  return typeData[getRandomNumber(0, typeData.length)];
};

function getRandomTime() {
  return timeData[getRandomNumber(0, timeData.length)];
};

function getRandomPromoter() {
  return promoterData[getRandomNumber(0, promoterData.length)];
};

function getRandomStreet() {
  return streetData[getRandomNumber(0, streetData.length)];
};

function getRandomCity() {
  return cityData[getRandomNumber(0, cityData.length)];
}
<|endoftext|>


<commit_before>import R from 'ramda'
import PubSub from 'pubsub-js'

import { TAG_COLOR_ORDER } from '@config'
import { EVENT } from '@constant'

import { nilOrEmpty } from './validator'

/* eslint-disable */
// TODO: document ?
export const Global = typeof window !== 'undefined' ? window : global
/* eslint-enable */

// see https://github.com/ramda/ramda/issues/1361
export const mapKeys = R.curry((fn, obj) => {
  return R.reduce(
    (acc, key) => {
      acc[fn(key)] = obj[key]
      return acc
    },
    {},
    R.keys(obj)
  )
})

export const sortByColor = source =>
  R.sort(
    (t1, t2) => TAG_COLOR_ORDER[t1.color] - TAG_COLOR_ORDER[t2.color],
    source
  )

export const sortByIndex = source => R.sort((a, b) => a.index - b.index, source)

/* eslint-disable */
const log = (...args) => data => {
  console.log.apply(null, args.concat([data]))
  return data
}
/* eslint-enable */

// reference: https://blog.carbonfive.com/2017/12/20/easy-pipeline-debugging-with-curried-console-log/
export const Rlog = (arg = 'Rlog: ') => R.tap(log(arg))

export const cutFrom = (val, cutnumber = 20) => {
  if (nilOrEmpty(val)) {
    return ''
  }
  if (val.length <= cutnumber) {
    return val
  }
  return `${R.slice(0, cutnumber, val)} ...`
}

// https://stackoverflow.com/questions/9461621/how-to-format-a-number-as-2-5k-if-a-thousand-or-more-otherwise-900-in-javascrip
export const prettyNum = (num, digits = 1) => {
  const si = [
    { value: 1, symbol: '' },
    { value: 1e3, symbol: 'k' },
    { value: 1e6, symbol: 'M' },
    { value: 1e9, symbol: 'G' },
    { value: 1e12, symbol: 'T' },
    { value: 1e15, symbol: 'P' },
    { value: 1e18, symbol: 'E' },
  ]
  const rx = /\.0+$|(\.[0-9]*[1-9])0+$/
  let i
  for (i = si.length - 1; i > 0; i -= 1) {
    if (num >= si[i].value) {
      break
    }
  }
  /* eslint-disable */
  if (num < 1000) {
    return (num / si[i].value).toFixed(digits).replace(rx, '$1') + si[i].symbol
  }
  return (
    (num / si[i].value).toFixed(digits).replace(rx, '$1') + si[i].symbol + '+'
  )
  /* eslint-enable  */
}

// https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript
export const numberWithCommas = x =>
  x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')

// from https://stackoverflow.com/questions/20396456/how-to-do-word-counts-for-a-mixture-of-english-and-chinese-in-javascript
// count both chinese-word and english-words
export const countWords = str => {
  const matches = str.match(/[\u00ff-\uffff]|\S+/g)
  return matches ? matches.length : 0
}

// TODO remove
export const getRandomInt = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min)) + min
}

export const send = (msg, data = {}) => {
  // TODO: check the msg is valid
  // PubSub.publishSync(msg, data)
  PubSub.publish(msg, data)
}

export const closePreviewer = (type = '') => send(EVENT.PREVIEW_CLOSE, { type })

export const errRescue = ({ type, operation, details, path }) =>
  send(EVENT.ERR_RESCUE, { type, data: { operation, details, path } })

// errRescue({type: ERR.GRAPHQL, operation: operationName, details: graphQLErrors})

/* eslint-disable */
export const debounce = (func, wait, immediate) => {
  let timeout
  return function() {
    const context = this
    const args = arguments
    const later = function() {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}
/* eslint-enable */

export const extractMentions = text => {
  const mentionsRegex = new RegExp('@([a-zA-Z0-9_.-]+)', 'gim')

  let matches = text.match(mentionsRegex)
  if (matches && matches.length) {
    matches = matches.map(match => {
      return match.slice(1)
    })
    return R.uniq(matches)
  }
  return []
}

// https://blogs.sap.com/2017/07/15/use-regular-expression-to-parse-the-image-reference-in-the-markdown-sourcre-code/
export const extractAttachments = str => {
  let m
  const regex = /!\[(.*?)\]\((.*?)\)/g

  const urls = []
  /* eslint-disable */
  while ((m = regex.exec(str)) !== null) {
    if (m.index === regex.lastIndex) {
      regex.lastIndex += 1
    }
    urls.push(m[2])
  }
  /* eslint-enable */
  return urls
}
<commit_msg>refactor(utils): cutFrom support complex chinese char<commit_after>import R from 'ramda'
import PubSub from 'pubsub-js'

import { TAG_COLOR_ORDER } from '@config'
import { EVENT } from '@constant'

/* eslint-disable */
// TODO: document ?
export const Global = typeof window !== 'undefined' ? window : global
/* eslint-enable */

// see https://github.com/ramda/ramda/issues/1361
export const mapKeys = R.curry((fn, obj) => {
  return R.reduce(
    (acc, key) => {
      acc[fn(key)] = obj[key]
      return acc
    },
    {},
    R.keys(obj)
  )
})

export const sortByColor = source =>
  R.sort(
    (t1, t2) => TAG_COLOR_ORDER[t1.color] - TAG_COLOR_ORDER[t2.color],
    source
  )

export const sortByIndex = source => R.sort((a, b) => a.index - b.index, source)

/* eslint-disable */
const log = (...args) => data => {
  console.log.apply(null, args.concat([data]))
  return data
}
/* eslint-enable */

// reference: https://blog.carbonfive.com/2017/12/20/easy-pipeline-debugging-with-curried-console-log/
export const Rlog = (arg = 'Rlog: ') => R.tap(log(arg))

/**
 * cut extra length of a string
 * 截取固定长度字符串，并添加省略号（...）
 * @param {*string} str 需要进行处理的字符串，可含汉字
 * @param {*number} len 需要显示多少个汉字，两个英文字母相当于一个汉字
 */
export const cutFrom = (str, len = 20) => {
  const reg = /[\u4e00-\u9fa5]/g // 匹配中文
  const slice = str && str.substring(0, len)
  // eslint-disable-next-line no-bitwise
  const chineseCharNum = ~~(
    slice &&
    slice.match(reg) &&
    slice.match(reg).length
  )
  const realen = slice && slice.length * 2 - chineseCharNum
  return str && str.substr(0, realen) + (realen < str.length ? '...' : '')
}

// https://stackoverflow.com/questions/9461621/how-to-format-a-number-as-2-5k-if-a-thousand-or-more-otherwise-900-in-javascrip
export const prettyNum = (num, digits = 1) => {
  const si = [
    { value: 1, symbol: '' },
    { value: 1e3, symbol: 'k' },
    { value: 1e6, symbol: 'M' },
    { value: 1e9, symbol: 'G' },
    { value: 1e12, symbol: 'T' },
    { value: 1e15, symbol: 'P' },
    { value: 1e18, symbol: 'E' },
  ]
  const rx = /\.0+$|(\.[0-9]*[1-9])0+$/
  let i
  for (i = si.length - 1; i > 0; i -= 1) {
    if (num >= si[i].value) {
      break
    }
  }
  /* eslint-disable */
  if (num < 1000) {
    return (num / si[i].value).toFixed(digits).replace(rx, '$1') + si[i].symbol
  }
  return (
    (num / si[i].value).toFixed(digits).replace(rx, '$1') + si[i].symbol + '+'
  )
  /* eslint-enable  */
}

// https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript
export const numberWithCommas = x =>
  x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')

// from https://stackoverflow.com/questions/20396456/how-to-do-word-counts-for-a-mixture-of-english-and-chinese-in-javascript
// count both chinese-word and english-words
export const countWords = str => {
  const matches = str.match(/[\u00ff-\uffff]|\S+/g)
  return matches ? matches.length : 0
}

// TODO remove
export const getRandomInt = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min)) + min
}

export const send = (msg, data = {}) => {
  // TODO: check the msg is valid
  // PubSub.publishSync(msg, data)
  PubSub.publish(msg, data)
}

export const closePreviewer = (type = '') => send(EVENT.PREVIEW_CLOSE, { type })

export const errRescue = ({ type, operation, details, path }) =>
  send(EVENT.ERR_RESCUE, { type, data: { operation, details, path } })

// errRescue({type: ERR.GRAPHQL, operation: operationName, details: graphQLErrors})

/* eslint-disable */
export const debounce = (func, wait, immediate) => {
  let timeout
  return function() {
    const context = this
    const args = arguments
    const later = function() {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}
/* eslint-enable */

export const extractMentions = text => {
  const mentionsRegex = new RegExp('@([a-zA-Z0-9_.-]+)', 'gim')

  let matches = text.match(mentionsRegex)
  if (matches && matches.length) {
    matches = matches.map(match => {
      return match.slice(1)
    })
    return R.uniq(matches)
  }
  return []
}

// https://blogs.sap.com/2017/07/15/use-regular-expression-to-parse-the-image-reference-in-the-markdown-sourcre-code/
export const extractAttachments = str => {
  let m
  const regex = /!\[(.*?)\]\((.*?)\)/g

  const urls = []
  /* eslint-disable */
  while ((m = regex.exec(str)) !== null) {
    if (m.index === regex.lastIndex) {
      regex.lastIndex += 1
    }
    urls.push(m[2])
  }
  /* eslint-enable */
  return urls
}
<|endoftext|>