<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/float32array}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/types/float32array' ) );

/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/float64array}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/types/float64array' ) );

/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/int16array}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/types/int16array' ) );

/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/int32array}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/types/int32array' ) );

/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/int8array}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/types/int8array' ) );

/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/uint16array}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/types/uint16array' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/float32array}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/types/float32array' ) );

/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/float64array}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/types/float64array' ) );

/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/int16array}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/types/int16array' ) );

/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/int32array}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/types/int32array' ) );

/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/int8array}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/types/int8array' ) );

/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/uint16array}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/types/uint16array' ) );

/**
* @name Uint32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/uint32array}
*/
setReadOnly( ns, 'Uint32Array', require( '@stdlib/types/uint32array' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>/**
 * @author sarkiroka on 2016.04.13.
 */
var getType = require('../common/get-type');
module.exports = function validateTaskList(tasks, deep) {
	if (!deep) {
		throw new Error('too deep task signature');
	}
	for (var i = 0; i < tasks.length; i++) {
		var task = tasks[i];
		var typeOfTask = getType(task);
		if (typeOfTask != 'function') {
			if (typeOfTask == 'array') {
				validateTaskList(task, deep - 1);
			} else {
				throw new Error('the task is not a function or an array');
			}
		}
	}
};
<commit_msg>figyelmeztet a névtelen taszkokra<commit_after>/**
 * @author sarkiroka on 2016.04.13.
 */
var getType = require('../common/get-type');
module.exports = function validateTaskList(tasks, deep) {
	if (!deep) {
		throw new Error('too deep task signature');
	}
	for (var i = 0; i < tasks.length; i++) {
		var task = tasks[i];
		var typeOfTask = getType(task);
		if (typeOfTask != 'function') {
			if (typeOfTask == 'array') {
				validateTaskList(task, deep - 1);
			} else {
				throw new Error('the task is not a function or an array');
			}
		} else {//this is a task (function)
			if (!task.name) {
				console.warn('if you use an unnamed function then loose the stack of tasknames. (' + task.toString() + ')');
			}
		}
	}
};
<|endoftext|>


<commit_before>'use strict';
/**
 * @file Retrieve contacts for the account
 */

var config = require('../../../config/configuration.js');
var org = config.salesforce_org;

var request = require('request');
var fs = require('fs');

/**
 * Retrieve all contacts associated with this user account,
 *
 * @param {String} accessToken AccessToken to identify the account
 * @param {Date} since Retrieve contacts updated since this date
 * @param {Function} cb Callback. First parameter is the error (if any), then an array of all the contacts.
 */

var retrieveContacts = function(oauth, since, cb) {

  org.getSObjects(oauth, function(err, resp) {
    if(err) {
      console.error(err);
    } else {
      resp.sobjects.forEach(function(so) {
        console.log(so.name);
      });
    }
  });
}

module.exports = function(accessToken, since, cb) {
  retrieveContacts(accessToken, since, cb);
};<commit_msg>Add get columns methods<commit_after>'use strict';
/**
 * @file Retrieve contacts for the account
 */

var config = require('../../../config/configuration.js');
var org = config.salesforce_org;

var request = require('request');
var fs = require('fs');

var getColumns = function(oauth, objectType, cb) {
  var columns = [];

  org.getDescribe(objectType, oauth, function(err, res) {
    for (var index in res.fields) {
      columns.push(res.fields[index].name);
    };

    cb(null, columns.join(', '));
  });
}

/**
 * Retrieve all contacts associated with this user account,
 *
 * @param {String} accessToken AccessToken to identify the account
 * @param {Date} since Retrieve contacts updated since this date
 * @param {Function} cb Callback. First parameter is the error (if any), then an array of all the contacts.
 */

var retrieveContacts = function(oauth, since, cb) {
  getColumns(oauth, 'Contact', function(err, columns){
    var q = 'SELECT ' + columns + ' FROM Contact';
    org.query(q, oauth, function(err, res) {
      console.log(JSON.stringify(res));
    });
  });
}

module.exports = function(accessToken, since, cb) {
  retrieveContacts(accessToken, since, cb);
};<|endoftext|>


<commit_before>// Copyright (c) Cognitect, Inc.
// All rights reserved.

"use strict";

goog.provide("com.cognitect.transit");
goog.require("com.cognitect.transit.impl.reader");
goog.require("com.cognitect.transit.impl.writer");
goog.require("com.cognitect.transit.types");
goog.require("com.cognitect.transit.eq");
goog.require("com.cognitect.transit.impl.decoder");

/** @define {boolean} */
var NODE_TARGET = false;

/** @define {boolean} */
var BROWSER_TARGET = false;

goog.scope(function() {

/**
 * @class transit
 */
var transit = com.cognitect.transit;

var reader  = com.cognitect.transit.impl.reader,
    writer  = com.cognitect.transit.impl.writer,
    decoder = com.cognitect.transit.impl.decoder,
    types   = com.cognitect.transit.types,
    eq      = com.cognitect.transit.eq;

/**
 * Create a transit reader instance.
 * @method transit.reader
 * @param {string|null} type type of reader to construct.
 *     Default to "json". For verbose mode supply "json-verbose".
 * @param {Object|null} opts reader options. A JavaScript object to
 *     customize the writer Valid entries include "defaultDecoder",
 *     and "decoders". "defaultDecoder" should be JavaScript function
 *     taking two arguments, the first is the tag, the second the
 *     value. "decoders" should be an object of tags to handle. The
 *     values are functions that will receive the value of matched
 *     tag.
 * @return {transit.reader} A transit reader.
 */
transit.reader = function(type, opts) {
    if(type === "json" || type === "json-verbose" || type == null) {
        type = "json";
        var unmarshaller = new reader.JSONUnmarshaller(opts);
        return new reader.Reader(unmarshaller, opts);
    } else {
        throw new Error("Cannot create reader of type " + type);
    }
};

/**
 * Create a transit writer instance.
 * @method transit.writer
 * @param {String|null} type type of writer to construct.
 *     Defaults to "json". For verbose mode supply "json-verbose".
 * @param {Object|null} opts writer options. A JavaScript object to
 *     customize the writer. Takes "handlers", a JavaScript array containing
 *     and even number of entries. Every two entries should be a pair - a
 *     JavaScript constructor and transit writer handler instance.
 * @return {transit.writer} A transit writer.
 */
transit.writer = function(type, opts) {
    if(type === "json" || type === "json-verbose" || type == null) {
        if(type === "json-verbose") {
            if(opts == null) opts = {};
            opts["verbose"] = true;
        }
        type = "json";
        var marshaller = new writer.JSONMarshaller(opts);
        return new writer.Writer(marshaller, opts);
    } else {
        var err = new Error("Type must be \"json\"");
        err.data = {type: type};
        throw err;
    }
};

/**
 * Create a transit writer handler.
 * @method transit.makeHandler
 * @param {Object} obj An object containing 3 functions, tag, rep and stringRep.
 *    "tag" should return a string representing the tag to be written on the wire.
 *    "rep" should return the representation on the wire. "stringRep" is should return
 *    the string representation of the value.
 * @return {transit.handler} A transit write handler.
 */
transit.makeHandler = function(obj) {
    var Handler = function(){};
    Handler.prototype.tag = obj["tag"];
    Handler.prototype.rep = obj["rep"];
    Handler.prototype.stringRep = obj["stringRep"];
    return new Handler();
};

transit.makeBuilder = function(obj) {
    var Builder = function(){};
    Builder.prototype.init = obj["init"];
    Builder.prototype.add = obj["add"];
    Builder.prototype.finalize = obj["finalize"];
    return new Builder();
};

/**
 * Create a transit date.
 * @method transit.date
 * @param {Number|String} A number or string representing milliseconds since epoch.
 * @return {Date} A JavaScript Date.
 */
transit.date = types.date;

/**
 * Create a transit 64bit integer. Will return a JavaScript
 * number if a string that represents an integer value in the 53bit
 * range.
 * @method transit.integer
 * @param {Number} s A string representing an integer in the 64bit range.
 * @return {transit.integer} A 64bit long.
 */
transit.integer = types.intValue;

/**
 * Test if an object is a transit 64 bit integer.
 * @method transit.isInteger
 * @params {Object} x Any JavaScript value.
 * @return {Boolean} true if the value is a transit 64bit integer, false otherwise.
 */
transit.isInteger = types.intValue;

/**
 * Create transit UUID from high and low 64 bits. These integer values
 * can be constructed with transit.integer.
 * @method transit.uuid
 * @param {transit.integer} high The high 64 bits.
 * @param {transit.integer} low The low 64 bits.
 * @return {transit.uuid} A transit UUID.
 */
transit.uuid = types.uuid;

/**
 * Test if an object is a transit UUID.
 * @method transit.isUUID
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if the vlaue is a transit UUID instance, false otherwise.
 */
transit.isUUID = types.isUUID;

/**
 * Create a transit big decimal.
 * @method transit.bigdec
 * @param {String} s A string representing an arbitrary precisions decimal value.
 * @return {transit.bigdec} A transit big decimal.
 */
transit.bigdec =  types.bigDecimalValue;

/**
 * Test if an object is a transit big decimal.
 * @method transit.isBigDecimal
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit big decimal, false otherwise.
 */
transit.isBigDecimal = types.isBigDecimal;

/**
 * Create transit keyword.
 * @method transit.keyword
 * @param {String} name A string.
 * @return {transit.keyword} A transit keyword.
 */
transit.keyword = types.keyword;

/**
 * Test if an object is a transit keyword.
 * @method transit.isKeyword
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit keyword, false otherwise.
 */
transit.isKeyword = types.isKeyword;

/**
 * Create a transit symbol.
 * @method transit.symbol
 * @param {s} name A string.
 * @return {transit.symbol} A transit symbol instance.
 */
transit.symbol = types.symbol;

/**
 * Test if an object is a transit symbol
 * @method transit.isSymbol
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit symbol, false otherwise.
 */
transit.isSymbol = types.isSymbol;

/**
 * Create transit binary blob.
 * @method transit.binary
 * @params {String} s A base64 encoded string.
 * @return {transit.binary} A transit binary blob instance.
 */
transit.binary = types.binary;

/**
 * Test if an object is a transit binary blob.
 * @method transit.isBinary
 * @param {Object} x Any JavaScript value.
 */
transit.isBinary = types.isBinary;

/**
 * Create a transit URI.
 * @method transit.uri
 * @param {String} A string representing a valid URI.
 * @return {transit.uri} A transit URI.
 */
transit.uri = types.uri;

/**
 * Test if an object is a transit URI.
 * @method transit.isURI
 * @params {Object} Any JavaScript value.
 * @return {Boolean} true if x is a transit symbol, false otherwise.
 */
transit.isURI = types.isURI;

/**
 * Create a transit hash map. Transit maps satisfy the current version
 * of the ECMAScript 6 Map specification.
 * @method transit.map
 * @params {Array} xs A JavaScript array of alternating key value pairs.
 * @return {transit.map} A transit map.
 */
transit.map = types.map;

/**
 * Test if an object is a transit map.
 * @method transit.isMap
 * @params {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit map, false otherwise.
 */
transit.isMap =          types.isMap;

/**
 * Create a transit set. Transit sets satisfy the current version of the
 *
 */
transit.set =            types.set;
transit.isSet =          types.isSet;
transit.list =           types.list;
transit.isList =         types.isList;
transit.quoted =         types.quoted;
transit.isQuoted =       types.isQuoted;
transit.tagged =         types.taggedValue;
transit.isTaggedValue =  types.isTaggedValue;
transit.link =           types.link;
transit.isLink =         types.isLink;
transit.hash =           eq.hashCode;
transit.equals =         eq.equals;
transit.extendToEQ =     eq.extendToEQ;
transit.decoder =        decoder.decoder;
transit.UUIDfromString = types.UUIDfromString;
transit.randomUUID =     types.randomUUID;
transit.stringableKeys = writer.stringableKeys;

if(BROWSER_TARGET) {
    goog.exportSymbol("transit.reader",         transit.reader);
    goog.exportSymbol("transit.writer",         transit.writer);
    goog.exportSymbol("transit.makeBuilder",    transit.makeBuilder);
    goog.exportSymbol("transit.makeHandler",    transit.makeHandler);
    goog.exportSymbol("transit.date",           types.date);
    goog.exportSymbol("transit.integer",        types.intValue);
    goog.exportSymbol("transit.isInteger",      types.isInteger);
    goog.exportSymbol("transit.uuid",           types.uuid);
    goog.exportSymbol("transit.isUUID",         types.isUUID);
    goog.exportSymbol("transit.bigdec",         types.bigDecimalValue);
    goog.exportSymbol("transit.isBigDecimal",   types.isBigDecimal);
    goog.exportSymbol("transit.keyword",        types.keyword);
    goog.exportSymbol("transit.isKeyword",      types.isKeyword);
    goog.exportSymbol("transit.symbol",         types.symbol);
    goog.exportSymbol("transit.isSymbol",       types.isSymbol);
    goog.exportSymbol("transit.binary",         types.binary);
    goog.exportSymbol("transit.isBinary",       types.isBinary);
    goog.exportSymbol("transit.uri",            types.uri);
    goog.exportSymbol("transit.isURI",          types.isURI);
    goog.exportSymbol("transit.map",            types.map);
    goog.exportSymbol("transit.isMap",          types.isMap);
    goog.exportSymbol("transit.set",            types.set);
    goog.exportSymbol("transit.isSet",          types.isSet);
    goog.exportSymbol("transit.list",           types.list);
    goog.exportSymbol("transit.isList",         types.isList);
    goog.exportSymbol("transit.quoted",         types.quoted);
    goog.exportSymbol("transit.isQuoted",       types.isQuoted);
    goog.exportSymbol("transit.tagged",         types.taggedValue);
    goog.exportSymbol("transit.isTaggedValue",  types.idTaggedValue);
    goog.exportSymbol("transit.link",           types.link);
    goog.exportSymbol("transit.isLink",         types.isLink);
    goog.exportSymbol("transit.hash",           eq.hashCode);
    goog.exportSymbol("transit.equals",         eq.equals);
    goog.exportSymbol("transit.extendToEQ",     eq.extendToEQ);
    goog.exportSymbol("transit.decoder",        decoder.decoder);
    goog.exportSymbol("transit.UUIDfromString", types.UUIDfromString);
    goog.exportSymbol("transit.randomUUID",     types.randomUUID);
    goog.exportSymbol("transit.stringableKeys", writer.stringableKeys);
}

if(NODE_TARGET) {
    module.exports = {
        reader:         transit.reader,
        writer:         transit.writer,
        makeBuilder:    transit.makeBuilder,
        makeHandler:    transit.makeHandler,
        date:           types.date,
        integer:        types.intValue,
        isInteger:      types.isInteger,
        uuid:           types.uuid,
        isUUID:         types.isUUID,
        bigdec:         types.bigDecimalValue,
        isBigDecimal:   types.isBigDecimal,
        keyword:        types.keyword,
        isKeyword:      types.isKeyword,
        symbol:         types.symbol,
        isSymbol:       types.isSymbol,
        binary:         types.binary,
        isBinary:       types.isBinary,
        uri:            types.uri,
        isURI:          types.isURI,
        map:            types.map,
        isMap:          types.isMap,
        set:            types.set,
        isSet:          types.isSet,
        list:           types.list,
        isList:         types.isList,
        quoted:         types.quoted,
        isQuoted:       types.isQuoted,
        tagged:         types.taggedValue,
        isTaggedValue:  types.isTaggedValue,
        link:           types.link,
        isLink:         types.isLink,
        hash:           eq.hashCode,
        equals:         eq.equals,
        extendToEQ:     eq.extendToEQ,
        decoder:        decoder.decoder,
        UUIDfromString: types.UUIDfromString,
        randomUUID:     types.randomUUID,
        stringableKeys: writer.stringableKeys
    };
}

});
<commit_msg>doc wip<commit_after>// Copyright (c) Cognitect, Inc.
// All rights reserved.

"use strict";

goog.provide("com.cognitect.transit");
goog.require("com.cognitect.transit.impl.reader");
goog.require("com.cognitect.transit.impl.writer");
goog.require("com.cognitect.transit.types");
goog.require("com.cognitect.transit.eq");
goog.require("com.cognitect.transit.impl.decoder");

/** @define {boolean} */
var NODE_TARGET = false;

/** @define {boolean} */
var BROWSER_TARGET = false;

goog.scope(function() {

/**
 * @class transit
 */
var transit = com.cognitect.transit;

var reader  = com.cognitect.transit.impl.reader,
    writer  = com.cognitect.transit.impl.writer,
    decoder = com.cognitect.transit.impl.decoder,
    types   = com.cognitect.transit.types,
    eq      = com.cognitect.transit.eq;

/**
 * Create a transit reader instance.
 * @method transit.reader
 * @param {string|null} type type of reader to construct.
 *     Default to "json". For verbose mode supply "json-verbose".
 * @param {Object|null} opts reader options. A JavaScript object to
 *     customize the writer Valid entries include "defaultDecoder",
 *     and "decoders". "defaultDecoder" should be JavaScript function
 *     taking two arguments, the first is the tag, the second the
 *     value. "decoders" should be an object of tags to handle. The
 *     values are functions that will receive the value of matched
 *     tag.
 * @return {transit.reader} A transit reader.
 */
transit.reader = function(type, opts) {
    if(type === "json" || type === "json-verbose" || type == null) {
        type = "json";
        var unmarshaller = new reader.JSONUnmarshaller(opts);
        return new reader.Reader(unmarshaller, opts);
    } else {
        throw new Error("Cannot create reader of type " + type);
    }
};

/**
 * Create a transit writer instance.
 * @method transit.writer
 * @param {String|null} type type of writer to construct.
 *     Defaults to "json". For verbose mode supply "json-verbose".
 * @param {Object|null} opts writer options. A JavaScript object to
 *     customize the writer. Takes "handlers", a JavaScript array containing
 *     and even number of entries. Every two entries should be a pair - a
 *     JavaScript constructor and transit writer handler instance.
 * @return {transit.writer} A transit writer.
 */
transit.writer = function(type, opts) {
    if(type === "json" || type === "json-verbose" || type == null) {
        if(type === "json-verbose") {
            if(opts == null) opts = {};
            opts["verbose"] = true;
        }
        type = "json";
        var marshaller = new writer.JSONMarshaller(opts);
        return new writer.Writer(marshaller, opts);
    } else {
        var err = new Error("Type must be \"json\"");
        err.data = {type: type};
        throw err;
    }
};

/**
 * Create a transit writer handler.
 * @method transit.makeHandler
 * @param {Object} obj An object containing 3 functions, tag, rep and stringRep.
 *    "tag" should return a string representing the tag to be written on the wire.
 *    "rep" should return the representation on the wire. "stringRep" is should return
 *    the string representation of the value.
 * @return {transit.handler} A transit write handler.
 */
transit.makeHandler = function(obj) {
    var Handler = function(){};
    Handler.prototype.tag = obj["tag"];
    Handler.prototype.rep = obj["rep"];
    Handler.prototype.stringRep = obj["stringRep"];
    return new Handler();
};

transit.makeBuilder = function(obj) {
    var Builder = function(){};
    Builder.prototype.init = obj["init"];
    Builder.prototype.add = obj["add"];
    Builder.prototype.finalize = obj["finalize"];
    return new Builder();
};

/**
 * Create a transit date.
 * @method transit.date
 * @param {Number|String} A number or string representing milliseconds since epoch.
 * @return {Date} A JavaScript Date.
 */
transit.date = types.date;

/**
 * Create a transit 64bit integer. Will return a JavaScript
 *     number if a string that represents an integer value in the 53bit
 *     range.
 * @method transit.integer
 * @param {Number} s A string representing an integer in the 64bit range.
 * @return {transit.integer} A 64bit long.
 */
transit.integer = types.intValue;

/**
 * Test if an object is a transit 64 bit integer.
 * @method transit.isInteger
 * @params {Object} x Any JavaScript value.
 * @return {Boolean} true if the value is a transit 64bit integer, false otherwise.
 */
transit.isInteger = types.intValue;

/**
 * Create transit UUID from high and low 64 bits. These integer values
 *      can be constructed with transit.integer.
 * @method transit.uuid
 * @param {transit.integer} high The high 64 bits.
 * @param {transit.integer} low The low 64 bits.
 * @return {transit.uuid} A transit UUID.
 */
transit.uuid = types.uuid;

/**
 * Test if an object is a transit UUID.
 * @method transit.isUUID
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if the vlaue is a transit UUID instance, false otherwise.
 */
transit.isUUID = types.isUUID;

/**
 * Create a transit big decimal.
 * @method transit.bigdec
 * @param {String} s A string representing an arbitrary precisions decimal value.
 * @return {transit.bigdec} A transit big decimal.
 */
transit.bigdec =  types.bigDecimalValue;

/**
 * Test if an object is a transit big decimal.
 * @method transit.isBigDecimal
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit big decimal, false otherwise.
 */
transit.isBigDecimal = types.isBigDecimal;

/**
 * Create transit keyword.
 * @method transit.keyword
 * @param {String} name A string.
 * @return {transit.keyword} A transit keyword.
 */
transit.keyword = types.keyword;

/**
 * Test if an object is a transit keyword.
 * @method transit.isKeyword
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit keyword, false otherwise.
 */
transit.isKeyword = types.isKeyword;

/**
 * Create a transit symbol.
 * @method transit.symbol
 * @param {s} name A string.
 * @return {transit.symbol} A transit symbol instance.
 */
transit.symbol = types.symbol;

/**
 * Test if an object is a transit symbol
 * @method transit.isSymbol
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit symbol, false otherwise.
 */
transit.isSymbol = types.isSymbol;

/**
 * Create transit binary blob.
 * @method transit.binary
 * @params {String} s A base64 encoded string.
 * @return {transit.binary} A transit binary blob instance.
 */
transit.binary = types.binary;

/**
 * Test if an object is a transit binary blob.
 * @method transit.isBinary
 * @param {Object} x Any JavaScript value.
 */
transit.isBinary = types.isBinary;

/**
 * Create a transit URI.
 * @method transit.uri
 * @param {String} A string representing a valid URI.
 * @return {transit.uri} A transit URI.
 */
transit.uri = types.uri;

/**
 * Test if an object is a transit URI.
 * @method transit.isURI
 * @params {Object} Any JavaScript value.
 * @return {Boolean} true if x is a transit symbol, false otherwise.
 */
transit.isURI = types.isURI;

/**
 * Create a transit hash map. Transit maps satisfy the current version
 *     of the ECMAScript 6 Map specification.
 * @method transit.map
 * @params {Array} xs A JavaScript array of alternating key value pairs.
 * @return {transit.map} A transit map.
 */
transit.map = types.map;

/**
 * Test if an object is a transit map.
 * @method transit.isMap
 * @params {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit map, false otherwise.
 */
transit.isMap = types.isMap;

/**
 * Create a transit set. Transit sets satisfy the current version of the
 *     of the ECMAScript 6 Set specification.
 * @method transit.set
 * @param {Array} xs A JavaScript array of values.
 * @return {transit.set} A transit set.
 */
transit.set = types.set;

/**
 * Test if an object is a transit set.
 * @method transit.isSet
 * @params {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit set, false otherwise.
 */
transit.isSet = types.isSet;

/**
 * Create a transit list.
 * @method transit.list
 * @params {Array} A JavaScript array.
 * @return {transit.list} A transit list.
 */
transit.list = types.list;

/**
 * Test if an object is a transit list.
 * @method transit.list
 * @param {Object} x Any JavaScript value.
 * @return {Boolean} true if x is a transit list, false otherwise.
 */
transit.isList =         types.isList;
transit.quoted =         types.quoted;
transit.isQuoted =       types.isQuoted;
transit.tagged =         types.taggedValue;
transit.isTaggedValue =  types.isTaggedValue;
transit.link =           types.link;
transit.isLink =         types.isLink;
transit.hash =           eq.hashCode;
transit.equals =         eq.equals;

/**
 * Extend an object to hashing and equality required by
 *     transit maps and sets. Only required for custom
 *     types, JavaScript primitive types and transit
 *     types are handled.
 * @method transit.extendToEQ
 * @param {Object} x A JavaScript object, will be mutated.
 * @return {Object} x
 */
transit.extendToEQ = eq.extendToEQ;

transit.decoder =        decoder.decoder;
transit.UUIDfromString = types.UUIDfromString;
transit.randomUUID =     types.randomUUID;
transit.stringableKeys = writer.stringableKeys;

if(BROWSER_TARGET) {
    goog.exportSymbol("transit.reader",         transit.reader);
    goog.exportSymbol("transit.writer",         transit.writer);
    goog.exportSymbol("transit.makeBuilder",    transit.makeBuilder);
    goog.exportSymbol("transit.makeHandler",    transit.makeHandler);
    goog.exportSymbol("transit.date",           types.date);
    goog.exportSymbol("transit.integer",        types.intValue);
    goog.exportSymbol("transit.isInteger",      types.isInteger);
    goog.exportSymbol("transit.uuid",           types.uuid);
    goog.exportSymbol("transit.isUUID",         types.isUUID);
    goog.exportSymbol("transit.bigdec",         types.bigDecimalValue);
    goog.exportSymbol("transit.isBigDecimal",   types.isBigDecimal);
    goog.exportSymbol("transit.keyword",        types.keyword);
    goog.exportSymbol("transit.isKeyword",      types.isKeyword);
    goog.exportSymbol("transit.symbol",         types.symbol);
    goog.exportSymbol("transit.isSymbol",       types.isSymbol);
    goog.exportSymbol("transit.binary",         types.binary);
    goog.exportSymbol("transit.isBinary",       types.isBinary);
    goog.exportSymbol("transit.uri",            types.uri);
    goog.exportSymbol("transit.isURI",          types.isURI);
    goog.exportSymbol("transit.map",            types.map);
    goog.exportSymbol("transit.isMap",          types.isMap);
    goog.exportSymbol("transit.set",            types.set);
    goog.exportSymbol("transit.isSet",          types.isSet);
    goog.exportSymbol("transit.list",           types.list);
    goog.exportSymbol("transit.isList",         types.isList);
    goog.exportSymbol("transit.quoted",         types.quoted);
    goog.exportSymbol("transit.isQuoted",       types.isQuoted);
    goog.exportSymbol("transit.tagged",         types.taggedValue);
    goog.exportSymbol("transit.isTaggedValue",  types.idTaggedValue);
    goog.exportSymbol("transit.link",           types.link);
    goog.exportSymbol("transit.isLink",         types.isLink);
    goog.exportSymbol("transit.hash",           eq.hashCode);
    goog.exportSymbol("transit.equals",         eq.equals);
    goog.exportSymbol("transit.extendToEQ",     eq.extendToEQ);
    goog.exportSymbol("transit.decoder",        decoder.decoder);
    goog.exportSymbol("transit.UUIDfromString", types.UUIDfromString);
    goog.exportSymbol("transit.randomUUID",     types.randomUUID);
    goog.exportSymbol("transit.stringableKeys", writer.stringableKeys);
}

if(NODE_TARGET) {
    module.exports = {
        reader:         transit.reader,
        writer:         transit.writer,
        makeBuilder:    transit.makeBuilder,
        makeHandler:    transit.makeHandler,
        date:           types.date,
        integer:        types.intValue,
        isInteger:      types.isInteger,
        uuid:           types.uuid,
        isUUID:         types.isUUID,
        bigdec:         types.bigDecimalValue,
        isBigDecimal:   types.isBigDecimal,
        keyword:        types.keyword,
        isKeyword:      types.isKeyword,
        symbol:         types.symbol,
        isSymbol:       types.isSymbol,
        binary:         types.binary,
        isBinary:       types.isBinary,
        uri:            types.uri,
        isURI:          types.isURI,
        map:            types.map,
        isMap:          types.isMap,
        set:            types.set,
        isSet:          types.isSet,
        list:           types.list,
        isList:         types.isList,
        quoted:         types.quoted,
        isQuoted:       types.isQuoted,
        tagged:         types.taggedValue,
        isTaggedValue:  types.isTaggedValue,
        link:           types.link,
        isLink:         types.isLink,
        hash:           eq.hashCode,
        equals:         eq.equals,
        extendToEQ:     eq.extendToEQ,
        decoder:        decoder.decoder,
        UUIDfromString: types.UUIDfromString,
        randomUUID:     types.randomUUID,
        stringableKeys: writer.stringableKeys
    };
}

});
<|endoftext|>


<commit_before>'use strict';

const Command = require('../../Command.js');
const Wikia = require('node-wikia');

const warframe = new Wikia('warframe');

/**
 * Displays mods from the wiki
 */
class Mod extends Command {
  /**
   * Constructs a callable command
   * @param {Genesis} bot  The bot object
   */
  constructor(bot) {
    super(bot, 'warframe.misc.mod', 'mod', 'Search the Warframe Wiki for a mod\'s image');
    this.regex = new RegExp('^mod(.+)', 'i');
    this.noResultStr = `${this.md.codeMulti}No result for search, Operator. Attempt another search query.${this.md.blockEnd}`;
  }

  /**
   * Run the command
   * @param {Message} message Message with a command to handle, reply to,
   *                          or perform an action based on parameters.
   * @returns {string} success status
   */
  async run(message) {
    const query = this.regex.exec(message.strippedContent.match(this.regex)[0])[1];
    if (!query) {
      this.messageManager.reply(message, this.noResultStr, true, false);
      return this.messageManager.statuses.FAILURE;
    }
    const searchJson = await warframe.getSearchList({ query, limit: 1 });
    const { item: { id } } = searchJson.items;
    const detailsJson = await warframe.getArticleDetails({ ids: [id] });
    let thumbUrl = detailsJson.items[`${id}`].thumbnail;
    thumbUrl = thumbUrl ? thumbUrl.replace(/\/revision\/.*/, '') : 'https://i.imgur.com/11VCxbq.jpg';

    const list = await warframe.getArticlesList({ category: 'Mods', limit: 1000 });
    let sent = false;
    list.items.forEach((item) => {
      if (item.id === id && !sent) {
        sent = true;
        const embed = {
          title: query,
          url: detailsJson.basepath + detailsJson.items[`${id}`].url,
          color: 0xC0C0C0,
          description: `Mod result for ${query}`,
          image: {
            url: thumbUrl,
          },
        };
        this.messageManager.embed(message, embed, true, false);
      }
    });
    if (!sent) {
      this.messageManager.reply(message, this.noResultStr, true, false);
      return this.messageManager.statuses.FAILURE;
    }
    return this.messageManager.statuses.SUCCESS;
  }
}

module.exports = Mod;
<commit_msg>fix destructuring issue for mods<commit_after>'use strict';

const Command = require('../../Command.js');
const Wikia = require('node-wikia');

const warframe = new Wikia('warframe');

/**
 * Displays mods from the wiki
 */
class Mod extends Command {
  /**
   * Constructs a callable command
   * @param {Genesis} bot  The bot object
   */
  constructor(bot) {
    super(bot, 'warframe.misc.mod', 'mod', 'Search the Warframe Wiki for a mod\'s image');
    this.regex = new RegExp('^mod(.+)', 'i');
    this.noResultStr = `${this.md.codeMulti}No result for search, Operator. Attempt another search query.${this.md.blockEnd}`;
  }

  /**
   * Run the command
   * @param {Message} message Message with a command to handle, reply to,
   *                          or perform an action based on parameters.
   * @returns {string} success status
   */
  async run(message) {
    const query = this.regex.exec(message.strippedContent.match(this.regex)[0])[1];
    if (!query) {
      this.messageManager.reply(message, this.noResultStr, true, false);
      return this.messageManager.statuses.FAILURE;
    }
    const searchJson = await warframe.getSearchList({ query, limit: 1 });
    const [{ id }] = searchJson.items;
    const detailsJson = await warframe.getArticleDetails({ ids: [id] });
    let thumbUrl = detailsJson.items[`${id}`].thumbnail;
    thumbUrl = thumbUrl ? thumbUrl.replace(/\/revision\/.*/, '') : 'https://i.imgur.com/11VCxbq.jpg';

    const list = await warframe.getArticlesList({ category: 'Mods', limit: 1000 });
    let sent = false;
    list.items.forEach((item) => {
      if (item.id === id && !sent) {
        sent = true;
        const embed = {
          title: query,
          url: detailsJson.basepath + detailsJson.items[`${id}`].url,
          color: 0xC0C0C0,
          description: `Mod result for ${query}`,
          image: {
            url: thumbUrl,
          },
        };
        this.messageManager.embed(message, embed, true, false);
      }
    });
    if (!sent) {
      this.messageManager.reply(message, this.noResultStr, true, false);
      return this.messageManager.statuses.FAILURE;
    }
    return this.messageManager.statuses.SUCCESS;
  }
}

module.exports = Mod;
<|endoftext|>


<commit_before>'use strict';

const Command = require('../../models/Command.js');
const { getUsersForCall, isVulgarCheck } = require('../../CommonFunctions');

/**
 * Array of useable channel values
 * @type {Array.<String>}
 */
const useable = ['room', 'raid', 'team', 'chat'];

/**
 * Regex describing custom channel names
 * @type {RegExp}
 */
const channelNameRegex = new RegExp('-n\\s+(.+)', 'ig');
/**
 * Regex describing no text being desired
 * @type {RegExp}
 */
const noTextRegex = new RegExp('--no-text', 'ig');
/**
 * Regex describing a public channel
 * @type {RegExp}
 */
const publicRegex = new RegExp('--public', 'ig');

/**
 * Regex describing a locked channel
 * @type {RegExp}
 */
const lockedRegex = new RegExp('--locked', 'ig');

/**
 * Regex describing text being desired
 * @type {RegExp}
 */
const textRegex = new RegExp('--text', 'ig');

/**
 * Regex describing channels being hidden
 * @type {RegExp}
 */
const hiddenRegex = new RegExp('--hidden', 'ig');

/**
 * Regex describing channels being shown
 * @type {RegExp}
 */
const shownRegex = new RegExp('--shown', 'ig');

/**
 * Create temporary voice/text channels (can be expanded in the future)
 */
class Create extends Command {
  /**
   * Constructs a callable command
   * @param {Genesis} bot  The bot object
   */
  constructor(bot) {
    super(bot, 'rooms.create', 'create', 'Create a temporary room.');
    this.regex = new RegExp(`^${this.call}\\s?(room|raid|team|chat)?(\\w|-)?(?:-n(.+))?(--no-text)?(--public)?(--text)?(--hidden)?(--shown)?`, 'i');

    this.usages = [
      { description: 'Display instructions for creating temporary rooms', parameters: [] },
      {
        description: 'Create temporary text and voice channels for the calling user.',
        parameters: ['room | raid | team'],
      },
      {
        description: 'Create temporary text and voice channels for the calling user and any mentioned users/roles.',
        parameters: ['room | raid | team', 'users and/or role'],
      },
      {
        description: 'Create temporary text and voice channels for the calling user and any mentioned users/roles, with a custom name',
        parameters: ['room | raid | team', 'users and/or role', '-n name', '--no-text', '--public', '--text', '--locked'],
      },
    ];

    this.allowDM = false;
  }

  /**
   * Run the command
   * @param {Message} message Message with a command to handle, reply to,
   *                          or perform an action based on parameters.
   * @param {Object} ctx Command context for calling commands
   * @returns {string} success status
   */
  async run(message, ctx) {
    let isPublic;
    if (lockedRegex.test(message.strippedContent)) {
      isPublic = false;
    } else if (publicRegex.test(message.strippedContent)) {
      isPublic = true;
    } else {
      isPublic = !ctx.defaultRoomsLocked;
    }

    let useText;
    if (textRegex.test(message.strippedContent)) {
      useText = true;
    } else if (noTextRegex.test(message.strippedContent)) {
      useText = false;
    } else {
      useText = !ctx.defaultNoText;
    }

    let shown = false;
    if (shownRegex.test(message.strippedContent)) {
      shown = true;
    } else if (hiddenRegex.test(message.strippedContent)) {
      shown = false;
    } else {
      shown = ctx.defaultShown;
    }

    const modRole = this.message.guild.roles.get(await this.settings.getGuildSetting(message.guild, 'modRole'));
    const useModRole = modRole.id ? this.message.guild.roles.has(modRole.id) : false;

    if (ctx.tempCategory || (message.guild && message.guild.channels.has(ctx.tempCategory))) {
      useText = false;
    }

    const type = message.strippedContent.match(this.regex)[1];
    const namingResults = message.strippedContent.match(channelNameRegex);
    const userHasRoom = await this.settings.userHasRoom(message.member);

    let optName = (namingResults ? namingResults[0] : '')
      .replace('-n ', '').replace('--public', '')
      .replace('--locked', '').replace('--no-text', '')
      .replace('--text', '')
      .replace('--shown', '')
      .replace('--hidden', '')
      .trim();
    optName = optName.replace(isVulgarCheck, ''); // remove vulgar

    if (ctx.createPrivateChannel) {
      if (userHasRoom) {
        await this.messageManager.reply(message, `you already have a private room registered. If this is in error, please log a bug report with \`${ctx.prefix}bug\`.`, true, true);
        return this.messageManager.statuses.FAILURE;
      }
      if (type) {
        const roomType = type.trim();
        if (useable.includes(roomType)) {
          const users = getUsersForCall(message);
          const name = optName || `${type}-${message.member.displayName}`.toLowerCase();
          if (users.length < 11 && !message.guild.channels.find('name', name)) {
            const overwrites = this.createOverwrites({
              users,
              everyone: message.guild.defaultRole,
              author: message.author,
              isPublic,
              useText,
              useModRole,
              modRole,
            });
            let category;
            if (!ctx.tempCategory
              || !(message.guild && message.guild.channels.has(ctx.tempCategory.id))) {
              category = await message.guild
                .createChannel(name, 'category', overwrites);
            } else {
              category = ctx.tempCategory;
            }

            let textChannel;
            if (useText) {
              textChannel = await message.guild.createChannel(name.replace(/[^\w|-]/ig, ''), 'text', overwrites);
              textChannel = await textChannel.setParent(category.id);
            }

            let voiceChannel = await message.guild.createChannel(name, 'voice', overwrites);
            voiceChannel = await voiceChannel.setParent(category.id);

            if (!isPublic) {
              // manually add overwrites for "everyone"
              await category.overwritePermissions(message.guild.defaultRole.id, {
                CONNECT: false,
                VIEW_CHANNEL: shown,
              });
              if (useText) {
                await textChannel.overwritePermissions(message.guild.defaultRole.id, {
                  CONNECT: false,
                  VIEW_CHANNEL: shown,
                });
              }
              await voiceChannel.overwritePermissions(message.guild.defaultRole.id, {
                CONNECT: false,
                VIEW_CHANNEL: shown,
              });
            }

            // add channel to listenedChannels
            await this.settings
              .addPrivateRoom(
                message.guild, textChannel, voiceChannel,
                category === ctx.tempCategory ? { id: 0 } : category, message.member,
              );
            // send users invite link to new rooms
            this.sendInvites(voiceChannel, users, message.author);
            // set room limits
            this.setLimits(voiceChannel, roomType);
            this.messageManager.embed(message, {
              title: 'Channels created',
              fields: [{
                name: '_ _',
                value: `Voice Channel: ${voiceChannel.name}${
                  textChannel ? `\nText Channel: ${textChannel}` : ''}`,
              }],
            }, false, false);
            return this.messageManager.statuses.SUCCESS;
          }
          let msg = '';
          if (users.length > 10) {
            // notify caller that there's too many users if role is more than 10 people.
            msg = 'you are trying to send an invite to too many people, please keep the total number under 10';
          } else {
            msg = 'that room already exists.';
          }
          await this.messageManager.reply(message, msg, true, true);
          return this.messageManager.statuses.FAILURE;
        }
      } else {
        await this.messageManager.reply(
          message, '```haskell\n'
            + 'Sorry, you need to specify what you want to create. Right now these are available to create:'
            + `\n* ${useable.join('\n* ')}\n\`\`\``,
          true, false,
        );
        return this.messageManager.statuses.FAILURE;
      }
    }
    return this.messageManager.statuses.FAILURE;
  }

  /**
   * Send channel invites to users who were tagged in message
   * @param {VoiceChannel} voiceChannel Voice channel to create invites for
   * @param {Array.<User>} users Array of users to send invites to
   * @param {User} author Calling user who sends message
   */
  async sendInvites(voiceChannel, users, author) {
    if (voiceChannel.permissionsFor(this.bot.client.user).has('CREATE_INSTANT_INVITE')) {
      const invite = await voiceChannel.createInvite({ maxUses: users.length });
      for (const user of users) {
        this.messageManager.sendDirectMessageToUser(user, `Invite for ${voiceChannel.name} from ${author}: ${invite}`, false);
      }
    }
  }

  /**
   * Create an array of permissions overwrites for the channel
   * @param {Array.<User>} users            Array of users for whom to allow into channels
   * @param {RoleResolvable} everyone   RoleResolvable for the @everyone role
   * @param {User} author                   User object for creator of room
   * @param {boolean} isPublic              Whether or not this channel will be public
   * @param {boolean} shown                 Whether or not this channel will be visible
   * @param {boolean} useModRole            Whether or not to leverage the mod role
   * @param {boolean} modRole               Moderator role that can manage the channel
   * @returns {Array.<PermissionsOVerwrites>}
   */
  createOverwrites({users, everyone, author, isPublic, shown, useModRole, modRole}) {
    // create overwrites
    const overwrites = [];
    // this still doesn't work, need to figure out why
    if (!isPublic) {
      const evOverwrites = ['CONNECT'];
      if (!shown) {
        evOverwrites.push('VIEW_CHANNEL');
      }
      overwrites.push({
        id: everyone,
        deny: evOverwrites,
      });
      overwrites.push({
        allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'CONNECT', 'MUTE_MEMBERS', 'DEAFEN_MEMBERS', 'MOVE_MEMBERS', 'MANAGE_ROLES', 'MANAGE_CHANNELS'],
        id: this.bot.client.user.id,
      });
      // set up overwrites per-user
      users.forEach((user) => {
        overwrites.push({
          id: user.id,
          allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'CONNECT', 'SPEAK', 'USE_VAD'],
        });
      });
      overwrites.push({
        id: author.id,
        allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'CONNECT', 'SPEAK', 'USE_VAD', 'MANAGE_MESSAGES'],
      });
      // Add mod role overwrites if one is present
      if (useModRole) {
        overwrites.push({
          id: modRole,
          allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'CONNECT', 'SPEAK', 'USE_VAD', 'MANAGE_MESSAGES', 'DEAFEN_MEMBERS', 'MOVE_MEMBERS']
      });
      }
    } else {
      overwrites.push({
        id: everyone,
        allow: ['VIEW_CHANNEL', 'CONNECT'],
      });
    }
    return overwrites;
  }

  async setLimits(voiceChannel, type) {
    let limit;
    switch (type) {
      case 'team':
        limit = 4;
        break;
      case 'raid':
        limit = 8;
        break;
      case 'chat':
      case 'room':
      default:
        break;
    }
    if (limit) {
      await voiceChannel.setUserLimit(limit);
    }
    this.logger.debug(`User limit set to ${limit || 'none'} for ${voiceChannel.name}`);
  }
}

module.exports = Create;
<commit_msg>not "this" message<commit_after>'use strict';

const Command = require('../../models/Command.js');
const { getUsersForCall, isVulgarCheck } = require('../../CommonFunctions');

/**
 * Array of useable channel values
 * @type {Array.<String>}
 */
const useable = ['room', 'raid', 'team', 'chat'];

/**
 * Regex describing custom channel names
 * @type {RegExp}
 */
const channelNameRegex = new RegExp('-n\\s+(.+)', 'ig');
/**
 * Regex describing no text being desired
 * @type {RegExp}
 */
const noTextRegex = new RegExp('--no-text', 'ig');
/**
 * Regex describing a public channel
 * @type {RegExp}
 */
const publicRegex = new RegExp('--public', 'ig');

/**
 * Regex describing a locked channel
 * @type {RegExp}
 */
const lockedRegex = new RegExp('--locked', 'ig');

/**
 * Regex describing text being desired
 * @type {RegExp}
 */
const textRegex = new RegExp('--text', 'ig');

/**
 * Regex describing channels being hidden
 * @type {RegExp}
 */
const hiddenRegex = new RegExp('--hidden', 'ig');

/**
 * Regex describing channels being shown
 * @type {RegExp}
 */
const shownRegex = new RegExp('--shown', 'ig');

/**
 * Create temporary voice/text channels (can be expanded in the future)
 */
class Create extends Command {
  /**
   * Constructs a callable command
   * @param {Genesis} bot  The bot object
   */
  constructor(bot) {
    super(bot, 'rooms.create', 'create', 'Create a temporary room.');
    this.regex = new RegExp(`^${this.call}\\s?(room|raid|team|chat)?(\\w|-)?(?:-n(.+))?(--no-text)?(--public)?(--text)?(--hidden)?(--shown)?`, 'i');

    this.usages = [
      { description: 'Display instructions for creating temporary rooms', parameters: [] },
      {
        description: 'Create temporary text and voice channels for the calling user.',
        parameters: ['room | raid | team'],
      },
      {
        description: 'Create temporary text and voice channels for the calling user and any mentioned users/roles.',
        parameters: ['room | raid | team', 'users and/or role'],
      },
      {
        description: 'Create temporary text and voice channels for the calling user and any mentioned users/roles, with a custom name',
        parameters: ['room | raid | team', 'users and/or role', '-n name', '--no-text', '--public', '--text', '--locked'],
      },
    ];

    this.allowDM = false;
  }

  /**
   * Run the command
   * @param {Message} message Message with a command to handle, reply to,
   *                          or perform an action based on parameters.
   * @param {Object} ctx Command context for calling commands
   * @returns {string} success status
   */
  async run(message, ctx) {
    let isPublic;
    if (lockedRegex.test(message.strippedContent)) {
      isPublic = false;
    } else if (publicRegex.test(message.strippedContent)) {
      isPublic = true;
    } else {
      isPublic = !ctx.defaultRoomsLocked;
    }

    let useText;
    if (textRegex.test(message.strippedContent)) {
      useText = true;
    } else if (noTextRegex.test(message.strippedContent)) {
      useText = false;
    } else {
      useText = !ctx.defaultNoText;
    }

    let shown = false;
    if (shownRegex.test(message.strippedContent)) {
      shown = true;
    } else if (hiddenRegex.test(message.strippedContent)) {
      shown = false;
    } else {
      shown = ctx.defaultShown;
    }

    const modRole = message.guild.roles.get(await this.settings.getGuildSetting(message.guild, 'modRole'));
    const useModRole = modRole.id ? this.message.guild.roles.has(modRole.id) : false;

    if (ctx.tempCategory || (message.guild && message.guild.channels.has(ctx.tempCategory))) {
      useText = false;
    }

    const type = message.strippedContent.match(this.regex)[1];
    const namingResults = message.strippedContent.match(channelNameRegex);
    const userHasRoom = await this.settings.userHasRoom(message.member);

    let optName = (namingResults ? namingResults[0] : '')
      .replace('-n ', '').replace('--public', '')
      .replace('--locked', '').replace('--no-text', '')
      .replace('--text', '')
      .replace('--shown', '')
      .replace('--hidden', '')
      .trim();
    optName = optName.replace(isVulgarCheck, ''); // remove vulgar

    if (ctx.createPrivateChannel) {
      if (userHasRoom) {
        await this.messageManager.reply(message, `you already have a private room registered. If this is in error, please log a bug report with \`${ctx.prefix}bug\`.`, true, true);
        return this.messageManager.statuses.FAILURE;
      }
      if (type) {
        const roomType = type.trim();
        if (useable.includes(roomType)) {
          const users = getUsersForCall(message);
          const name = optName || `${type}-${message.member.displayName}`.toLowerCase();
          if (users.length < 11 && !message.guild.channels.find('name', name)) {
            const overwrites = this.createOverwrites({
              users,
              everyone: message.guild.defaultRole,
              author: message.author,
              isPublic,
              useText,
              useModRole,
              modRole,
            });
            let category;
            if (!ctx.tempCategory
              || !(message.guild && message.guild.channels.has(ctx.tempCategory.id))) {
              category = await message.guild
                .createChannel(name, 'category', overwrites);
            } else {
              category = ctx.tempCategory;
            }

            let textChannel;
            if (useText) {
              textChannel = await message.guild.createChannel(name.replace(/[^\w|-]/ig, ''), 'text', overwrites);
              textChannel = await textChannel.setParent(category.id);
            }

            let voiceChannel = await message.guild.createChannel(name, 'voice', overwrites);
            voiceChannel = await voiceChannel.setParent(category.id);

            if (!isPublic) {
              // manually add overwrites for "everyone"
              await category.overwritePermissions(message.guild.defaultRole.id, {
                CONNECT: false,
                VIEW_CHANNEL: shown,
              });
              if (useText) {
                await textChannel.overwritePermissions(message.guild.defaultRole.id, {
                  CONNECT: false,
                  VIEW_CHANNEL: shown,
                });
              }
              await voiceChannel.overwritePermissions(message.guild.defaultRole.id, {
                CONNECT: false,
                VIEW_CHANNEL: shown,
              });
            }

            // add channel to listenedChannels
            await this.settings
              .addPrivateRoom(
                message.guild, textChannel, voiceChannel,
                category === ctx.tempCategory ? { id: 0 } : category, message.member,
              );
            // send users invite link to new rooms
            this.sendInvites(voiceChannel, users, message.author);
            // set room limits
            this.setLimits(voiceChannel, roomType);
            this.messageManager.embed(message, {
              title: 'Channels created',
              fields: [{
                name: '_ _',
                value: `Voice Channel: ${voiceChannel.name}${
                  textChannel ? `\nText Channel: ${textChannel}` : ''}`,
              }],
            }, false, false);
            return this.messageManager.statuses.SUCCESS;
          }
          let msg = '';
          if (users.length > 10) {
            // notify caller that there's too many users if role is more than 10 people.
            msg = 'you are trying to send an invite to too many people, please keep the total number under 10';
          } else {
            msg = 'that room already exists.';
          }
          await this.messageManager.reply(message, msg, true, true);
          return this.messageManager.statuses.FAILURE;
        }
      } else {
        await this.messageManager.reply(
          message, '```haskell\n'
            + 'Sorry, you need to specify what you want to create. Right now these are available to create:'
            + `\n* ${useable.join('\n* ')}\n\`\`\``,
          true, false,
        );
        return this.messageManager.statuses.FAILURE;
      }
    }
    return this.messageManager.statuses.FAILURE;
  }

  /**
   * Send channel invites to users who were tagged in message
   * @param {VoiceChannel} voiceChannel Voice channel to create invites for
   * @param {Array.<User>} users Array of users to send invites to
   * @param {User} author Calling user who sends message
   */
  async sendInvites(voiceChannel, users, author) {
    if (voiceChannel.permissionsFor(this.bot.client.user).has('CREATE_INSTANT_INVITE')) {
      const invite = await voiceChannel.createInvite({ maxUses: users.length });
      for (const user of users) {
        this.messageManager.sendDirectMessageToUser(user, `Invite for ${voiceChannel.name} from ${author}: ${invite}`, false);
      }
    }
  }

  /**
   * Create an array of permissions overwrites for the channel
   * @param {Array.<User>} users            Array of users for whom to allow into channels
   * @param {RoleResolvable} everyone   RoleResolvable for the @everyone role
   * @param {User} author                   User object for creator of room
   * @param {boolean} isPublic              Whether or not this channel will be public
   * @param {boolean} shown                 Whether or not this channel will be visible
   * @param {boolean} useModRole            Whether or not to leverage the mod role
   * @param {boolean} modRole               Moderator role that can manage the channel
   * @returns {Array.<PermissionsOVerwrites>}
   */
  createOverwrites({users, everyone, author, isPublic, shown, useModRole, modRole}) {
    // create overwrites
    const overwrites = [];
    // this still doesn't work, need to figure out why
    if (!isPublic) {
      const evOverwrites = ['CONNECT'];
      if (!shown) {
        evOverwrites.push('VIEW_CHANNEL');
      }
      overwrites.push({
        id: everyone,
        deny: evOverwrites,
      });
      overwrites.push({
        allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'CONNECT', 'MUTE_MEMBERS', 'DEAFEN_MEMBERS', 'MOVE_MEMBERS', 'MANAGE_ROLES', 'MANAGE_CHANNELS'],
        id: this.bot.client.user.id,
      });
      // set up overwrites per-user
      users.forEach((user) => {
        overwrites.push({
          id: user.id,
          allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'CONNECT', 'SPEAK', 'USE_VAD'],
        });
      });
      overwrites.push({
        id: author.id,
        allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'CONNECT', 'SPEAK', 'USE_VAD', 'MANAGE_MESSAGES'],
      });
      // Add mod role overwrites if one is present
      if (useModRole) {
        overwrites.push({
          id: modRole,
          allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'CONNECT', 'SPEAK', 'USE_VAD', 'MANAGE_MESSAGES', 'DEAFEN_MEMBERS', 'MOVE_MEMBERS']
      });
      }
    } else {
      overwrites.push({
        id: everyone,
        allow: ['VIEW_CHANNEL', 'CONNECT'],
      });
    }
    return overwrites;
  }

  async setLimits(voiceChannel, type) {
    let limit;
    switch (type) {
      case 'team':
        limit = 4;
        break;
      case 'raid':
        limit = 8;
        break;
      case 'chat':
      case 'room':
      default:
        break;
    }
    if (limit) {
      await voiceChannel.setUserLimit(limit);
    }
    this.logger.debug(`User limit set to ${limit || 'none'} for ${voiceChannel.name}`);
  }
}

module.exports = Create;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { pipe } from 'ramda';
import { serverType } from '../servers/prop-types';
import { versionToPrintable, versionToSemVer } from '../utils/helpers/version';
import { ExternalLink } from 'react-external-link';

const SHLINK_WEB_CLIENT_VERSION = '%_VERSION_%';

const propTypes = {
  selectedServer: serverType,
  className: PropTypes.string,
  clientVersion: PropTypes.string,
};

const ShlinkVersions = ({ selectedServer, className, clientVersion = SHLINK_WEB_CLIENT_VERSION }) => {
  const { printableVersion: serverVersion } = selectedServer;
  const normalizedClientVersion = pipe(versionToSemVer(), versionToPrintable)(clientVersion);

  return (

      Client: <ExternalLink href="https://github.com/shlinkio/shlink-web-client/releases/" className="text-muted">{normalizedClientVersion}</ExternalLink> - Server: <ExternalLink href="https://github.com/shlinkio/shlink/releases/" className="text-muted">{serverVersion}</ExternalLink>

  );
};

ShlinkVersions.propTypes = propTypes;

export default ShlinkVersions;
<commit_msg>Update ShlinkVersions.js<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { pipe } from 'ramda';
import { serverType } from '../servers/prop-types';
import { versionToPrintable, versionToSemVer } from '../utils/helpers/version';
import { ExternalLink } from 'react-external-link';

const SHLINK_WEB_CLIENT_VERSION = '%_VERSION_%';

const propTypes = {
  selectedServer: serverType,
  className: PropTypes.string,
  clientVersion: PropTypes.string,
};

const ShlinkVersions = ({ selectedServer, className, clientVersion = SHLINK_WEB_CLIENT_VERSION }) => {
  const { printableVersion: serverVersion } = selectedServer;
  const normalizedClientVersion = pipe(versionToSemVer(), versionToPrintable)(clientVersion);

  return (

      Client: <ExternalLink href="https://github.com/shlinkio/shlink-web-client/releases/" className="text-muted">{normalizedClientVersion}<ExternalLink> - Server: <ExternalLink href="https://github.com/shlinkio/shlink/releases/" className="text-muted">{serverVersion}<ExternalLink>

  );
};

ShlinkVersions.propTypes = propTypes;

export default ShlinkVersions;
<|endoftext|>


<commit_before>/* @flow */
import { connect } from 'react-redux';

import React, { PureComponent } from 'react';
import { Platform, StatusBar, View } from 'react-native';
import Color from 'color';

import type { Dimensions, StatusBarStyle, ThemeType } from '../types';
import { getSession, getSettings, getTitleBackgroundColor, getTitleTextColor } from '../selectors';
import getStatusBarStyle from '../utils/getStatusBarStyle';
import getStatusBarColor from '../utils/getStatusBarColor';

type Props = {
  barStyle?: StatusBarStyle,
  hidden: boolean,
  theme: ThemeType,
  backgroundColor: string,
  safeAreaInsets: Dimensions,
  textColor: string,
  orientation: string,
};

/**
 * Controls the status bar settings depending on platform
 * and current navigation position.
 * If narrowed to a stream or topic the color of the status bar
 * matches that of the stream.
 *
 * @prop [narrow] - Currently active narrow.
 */
class ZulipStatusBar extends PureComponent<Props> {
  props: Props;

  static defaultProps = {
    hidden: false,
  };

  render() {
    const {
      theme,
      backgroundColor,
      textColor,
      hidden,
      barStyle,
      safeAreaInsets,
      orientation,
    } = this.props;
    const style = { height: hidden ? 0 : safeAreaInsets.top, backgroundColor };
    const statusBarStyle = !barStyle
      ? getStatusBarStyle(backgroundColor, textColor, theme)
      : barStyle;
    const statusBarColor = getStatusBarColor(backgroundColor, theme);
    return (
      orientation === 'PORTRAIT' && (
        <View style={style}>
          <StatusBar
            animated
            showHideTransition="slide"
            hidden={hidden && Platform.OS !== 'android'}
            backgroundColor={Color(statusBarColor).darken(0.1)}
            barStyle={statusBarStyle}
          />
        </View>
      )
    );
  }
}

export default connect((state, props) => ({
  safeAreaInsets: getSession(state).safeAreaInsets,
  theme: getSettings(state).theme,
  backgroundColor:
    props.backgroundColor
    // $FlowFixMe: Props has no `narrow` property
    || getTitleBackgroundColor(props.narrow)(state),
  // $FlowFixMe: Props has no `narrow` property
  textColor: getTitleTextColor(props.narrow)(state),
  orientation: getSession(state).orientation,
}))(ZulipStatusBar);
<commit_msg>flow: Remove a couple of error suppression comments<commit_after>/* @flow */
import { connect } from 'react-redux';

import React, { PureComponent } from 'react';
import { Platform, StatusBar, View } from 'react-native';
import Color from 'color';

import type { Dimensions, StatusBarStyle, ThemeType } from '../types';
import { getSession, getSettings, getTitleBackgroundColor, getTitleTextColor } from '../selectors';
import getStatusBarStyle from '../utils/getStatusBarStyle';
import getStatusBarColor from '../utils/getStatusBarColor';

type Props = {
  barStyle?: StatusBarStyle,
  hidden: boolean,
  theme: ThemeType,
  backgroundColor: string,
  safeAreaInsets: Dimensions,
  textColor: string,
  orientation: string,
};

/**
 * Controls the status bar settings depending on platform
 * and current navigation position.
 * If narrowed to a stream or topic the color of the status bar
 * matches that of the stream.
 *
 * @prop [narrow] - Currently active narrow.
 */
class ZulipStatusBar extends PureComponent<Props> {
  props: Props;

  static defaultProps = {
    hidden: false,
  };

  render() {
    const {
      theme,
      backgroundColor,
      textColor,
      hidden,
      barStyle,
      safeAreaInsets,
      orientation,
    } = this.props;
    const style = { height: hidden ? 0 : safeAreaInsets.top, backgroundColor };
    const statusBarStyle = !barStyle
      ? getStatusBarStyle(backgroundColor, textColor, theme)
      : barStyle;
    const statusBarColor = getStatusBarColor(backgroundColor, theme);
    return (
      orientation === 'PORTRAIT' && (
        <View style={style}>
          <StatusBar
            animated
            showHideTransition="slide"
            hidden={hidden && Platform.OS !== 'android'}
            backgroundColor={Color(statusBarColor).darken(0.1)}
            barStyle={statusBarStyle}
          />
        </View>
      )
    );
  }
}

export default connect((state, props) => ({
  safeAreaInsets: getSession(state).safeAreaInsets,
  theme: getSettings(state).theme,
  // Prettier messes up the ternary so the linter complains.
  // prettier-ignore
  backgroundColor: !props.backgroundColor
    ? getTitleBackgroundColor(props.narrow)(state)
    : props.backgroundColor,
  textColor: getTitleTextColor(props.narrow)(state),
  orientation: getSession(state).orientation,
}))(ZulipStatusBar);
<|endoftext|>


<commit_before>fdescribe('weekViewRender', function() {

	beforeEach(function() {
		affix('#cal');
	});

	describe('verify th class for today', function() {
		var nowStr = $.fullCalendar.moment(new Date()).format('YYYY-MM-DD');

		beforeEach(function() {
			$('#cal').fullCalendar({
				defaultDate: nowStr,
				defaultView: 'agendaWeek'
			});
		});

		it('should have fc-today class only on "today"', function() {
			var foundToday = false;

			$('#cal th.fc-day-header').each(function(i, headerNode) {
				var headerEl = $(headerNode);
				var dateMatchesToday = headerEl.data('date') === nowStr;
				var hasTodayClass = headerEl.hasClass('fc-today');

				expect(dateMatchesToday).toBe(hasTodayClass);

				if (hasTodayClass) {
					foundToday = true;
				}
			});

			expect(foundToday).toBe(true);
		});
	});
});
<commit_msg>kill fdescribe<commit_after>describe('weekViewRender', function() {

	beforeEach(function() {
		affix('#cal');
	});

	describe('verify th class for today', function() {
		var nowStr = $.fullCalendar.moment(new Date()).format('YYYY-MM-DD');

		beforeEach(function() {
			$('#cal').fullCalendar({
				defaultDate: nowStr,
				defaultView: 'agendaWeek'
			});
		});

		it('should have fc-today class only on "today"', function() {
			var foundToday = false;

			$('#cal th.fc-day-header').each(function(i, headerNode) {
				var headerEl = $(headerNode);
				var dateMatchesToday = headerEl.data('date') === nowStr;
				var hasTodayClass = headerEl.hasClass('fc-today');

				expect(dateMatchesToday).toBe(hasTodayClass);

				if (hasTodayClass) {
					foundToday = true;
				}
			});

			expect(foundToday).toBe(true);
		});
	});
});
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var cordova = require('cordova');
var utils = require('cordova/utils');

module.exports = {

        getDeviceInfo:function(win,fail,args){
            console.log("NativeProxy::getDeviceInfo");

            var hostNames = Windows.Networking.Connectivity.NetworkInformation.getHostNames();

            var name = "unknown";
            hostNames.some(function (nm) {
                if (nm.displayName.indexOf(".local") > -1) {
                    name = nm.displayName.split(".local")[0];
                    return true;
                }
            });

            // deviceId aka uuid

            var deviceId = "";
            Windows.System.UserProfile.UserInformation.getFirstNameAsync().then(function (fileName) {
                var path = "C:\\Users\\" + fileName + "\\Documents";
                Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(function (storageFolder) {
                    return storageFolder.createFileAsync("appDeviceIdentifier.txt", Windows.Storage.CreationCollisionOption.openIfExists);
                }).then(function (storageFile) {
                    var value = Windows.Storage.Streams.UnicodeEncoding.utf8;
                    Windows.Storage.FileIO.readTextAsync(storageFile, value).then(function (fileContent) {
                        if (fileContent) {
                            deviceId = fileContent;
                            setTimeout(function () {
                                win({ platform: "windows8", version: "8", name: name, uuid: "TODO", cordova: "2.2.0" });
                            }, 0)
                        } else {
                            deviceId = utils.createUUID();
                            Windows.Storage.FileIO.writeTextAsync(storageFile, deviceId, Windows.Storage.Streams.UnicodeEncoding.utf8).done(
                                function () {
                                    setTimeout(function () {
                                        win({ platform: "windows8", version: "8", name: name, uuid: "TODO", cordova: "2.2.0" });
                                    }, 0)
                                }, function () {
                                    fail(FileError.INVALID_MODIFICATION_ERR);
                                }

                            );
                        }
                    },
                    function () {
                        fail(FileError.ENCODING_ERR);
                    });
                }, function () {
                    fail(FileError.NOT_FOUND_ERR);
                });

            },
            fail && fail());

        }

        setTimeout(function(){
            win({platform:"windows8", version:"8", name:name, uuid:deviceId, cordova:"2.2.0"});
        },0);
    }

};

require("cordova/commandProxy").add("Device",module.exports);
<commit_msg>return the uuid we worked so hard to get<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var cordova = require('cordova');
var utils = require('cordova/utils');

module.exports = {

        getDeviceInfo:function(win,fail,args){
            console.log("NativeProxy::getDeviceInfo");

            var hostNames = Windows.Networking.Connectivity.NetworkInformation.getHostNames();

            var name = "unknown";
            hostNames.some(function (nm) {
                if (nm.displayName.indexOf(".local") > -1) {
                    name = nm.displayName.split(".local")[0];
                    return true;
                }
            });

            // deviceId aka uuid

            var deviceId = "";
            Windows.System.UserProfile.UserInformation.getFirstNameAsync().then(function (fileName) {
                var path = "C:\\Users\\" + fileName + "\\Documents";
                Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(function (storageFolder) {
                    return storageFolder.createFileAsync("appDeviceIdentifier.txt", Windows.Storage.CreationCollisionOption.openIfExists);
                }).then(function (storageFile) {
                    var value = Windows.Storage.Streams.UnicodeEncoding.utf8;
                    Windows.Storage.FileIO.readTextAsync(storageFile, value).then(function (fileContent) {
                        if (fileContent) {
                            deviceId = fileContent;
                            setTimeout(function () {
                                win({ platform: "windows8", version: "8", name: name, uuid: deviceId, cordova: "2.2.0" });
                            }, 0)
                        } else {
                            deviceId = utils.createUUID();
                            Windows.Storage.FileIO.writeTextAsync(storageFile, deviceId, Windows.Storage.Streams.UnicodeEncoding.utf8).done(
                                function () {
                                    setTimeout(function () {
                                        win({ platform: "windows8", version: "8", name: name, uuid: deviceId, cordova: "2.2.0" });
                                    }, 0)
                                }, function () {
                                    fail(FileError.INVALID_MODIFICATION_ERR);
                                }

                            );
                        }
                    },
                    function () {
                        fail(FileError.ENCODING_ERR);
                    });
                }, function () {
                    fail(FileError.NOT_FOUND_ERR);
                });

            },
            fail && fail());

        }

        setTimeout(function(){
            win({platform:"windows8", version:"8", name:name, uuid:deviceId, cordova:"2.2.0"});
        },0);
    }

};

require("cordova/commandProxy").add("Device",module.exports);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugcore may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@Export('StringUtil')

//@Require('TypeUtil')

//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------

require('bugpack').context("*", function(bugpack) {

    //-------------------------------------------------------------------------------
    // BugPack
    //-------------------------------------------------------------------------------

    var TypeUtil    = bugpack.require('TypeUtil');

    //-------------------------------------------------------------------------------
    // Declare Class
    //-------------------------------------------------------------------------------

    /**
     * @constructor
     */
    var StringUtil = function() {};

    //-------------------------------------------------------------------------------
    // Static Methods
    //-------------------------------------------------------------------------------

    /**
     * @static
     * @param {string} value
     * @return {string}
     */
    StringUtil.capitalize = function(value) {
        var strings = value.split(" ");
        var result;
        if (strings.map) {
            result = strings.map(function(string, index, array) {
                return string[0].toUpperCase() + string.substring(1);
            });
        } else {
            result = [];
            strings.forEach(function(string){
                result.push(string[0].toUpperCase() + string.substring(1));
            });
        }
        return result.join(" ");
    };

    /**
     * @static
     * @param {string} value
     * @return {string}
     */
    StringUtil.escapeString = function(value) {
        return (value + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
    };

    /**
     * @static
     * @param {string} value
     * @param {string} pad
     * @param {number} size
     * @return {string}
     */
    StringUtil.lpad = function(value, pad, size) {
        var result = value + "";
        while (result.length < size) {
            result = pad + result;
        }
        return result;
    };

    /**
     * @static
     * @param {string} value
     * @param {string=} chars
     * @return {string}
     */
    StringUtil.ltrim = function(value, chars) {
        chars = chars || "\\s";
        return value.replace(new RegExp("^[" + chars + "]+", "g"), "");
    };

    /**
     * @static
     * @param {string} value
     * @param {string} pad
     * @param {number} size
     * @return {string}
     */
    StringUtil.pad = function(value, pad, size) {
        // Ensure string
        var result = value + "";
        while (result.length < size) {
            result = pad + result + pad;
        }
        return result;
    };

    /**
     * @static
     * @param {string} value
     * @return {string}
     */
    StringUtil.pluralize = function(value) {
        //TODO also add irregular patterns
        var irregularPlurals = {
            winklevoss: "winklevii"
        };
        if (irregularPlurals[value]) {
            return irregularPlurals[value]
        } else {
            return value + "s";
        }
    };

    /**
     * @static
     * @param {string} value
     * @param {string} pad
     * @param {number} size
     * @return {string}
     */
    StringUtil.rpad = function(value, pad, size) {
        var result = value + "";
        while (result.length < size) {
            result = result + pad;
        }
        return result;
    };

    /**
     * @static
     * @param {string} value
     * @param {string=} chars
     * @return {string}
     */
    StringUtil.rtrim = function(value, chars) {
        chars = chars || "\\s";
        return value.replace(new RegExp("[" + chars + "]+$", "g"), "");
    };

    /**
     * @static
     * @param {string} value
     * @param {string} separator
     * @param {(function(string, number, Array.<string>):*)=} lineProcessor
     * @return {Array.<string>}
     */
    StringUtil.split = function(value, separator, lineProcessor) {
        var lines = value.split(separator);
        if (lineProcessor) {
            lines = lines.map(lineProcessor);
        }
        return lines;
    };

    /**
     * @static
     * @param {string} value
     * @param {string=} chars
     * @return {string}
     */
    StringUtil.trim = function(value, chars) {
        chars = chars || "\\s";
        return value.replace(new RegExp("^[" + chars + "]+|[" + chars + "]+$", "g"), "");
    };

    /**
     * @static
     * @param {string} value
     * @return {string}
     */
    StringUtil.uncapitalize = function(value) {
        var strings = value.split(" ");
        var result;
        if (strings.map) {
            result = strings.map(function(string, index, array) {
                return string[0].toLowerCase() + string.substring(1);
            });
        } else {
            result = [];
            strings.forEach(function(string) {
                result.push(string[0].toLowerCase() + string.substring(1));
            });
        }
        return result.join(" ");
    };

    //-------------------------------------------------------------------------------
    // Exports
    //-------------------------------------------------------------------------------

    bugpack.export('StringUtil', StringUtil);
});
<commit_msg>Add lowerCamelToSeparator method to StringUtil<commit_after>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugcore may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@Export('StringUtil')

//@Require('TypeUtil')

//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------

require('bugpack').context("*", function(bugpack) {

    //-------------------------------------------------------------------------------
    // BugPack
    //-------------------------------------------------------------------------------

    var TypeUtil    = bugpack.require('TypeUtil');

    //-------------------------------------------------------------------------------
    // Declare Class
    //-------------------------------------------------------------------------------

    /**
     * @constructor
     */
    var StringUtil = function() {};

    //-------------------------------------------------------------------------------
    // Static Methods
    //-------------------------------------------------------------------------------

    /**
     * @static
     * @param {string} value
     * @return {string}
     */
    StringUtil.capitalize = function(value) {
        var strings = value.split(" ");
        var result;
        if (strings.map) {
            result = strings.map(function(string, index, array) {
                return string[0].toUpperCase() + string.substring(1);
            });
        } else {
            result = [];
            strings.forEach(function(string){
                result.push(string[0].toUpperCase() + string.substring(1));
            });
        }
        return result.join(" ");
    };

    /**
     * @static
     * @param {string} value
     * @return {string}
     */
    StringUtil.escapeString = function(value) {
        return (value + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
    };

    /**
     * @static
     * @param {string} value
     * @param {string} pad
     * @param {number} size
     * @return {string}
     */
    StringUtil.lpad = function(value, pad, size) {
        var result = value + "";
        while (result.length < size) {
            result = pad + result;
        }
        return result;
    };

    /**
     * @static
     * @param {string} value
     * @param {string} separator
     * @return {string}
     */
    StringUtil.lowerCamelToSeparator = function(value, separator) {
        return value
            .replace(/([A-Z])([A-Z])/g, "$1" + separator + ("$2"))
            .replace(/([a-z\d])([A-Z])/g, "$1" + separator + ("$2"))
            .toLowerCase();
    };

    /**
     * @static
     * @param {string} value
     * @param {string=} chars
     * @return {string}
     */
    StringUtil.ltrim = function(value, chars) {
        chars = chars || "\\s";
        return value.replace(new RegExp("^[" + chars + "]+", "g"), "");
    };

    /**
     * @static
     * @param {string} value
     * @param {string} pad
     * @param {number} size
     * @return {string}
     */
    StringUtil.pad = function(value, pad, size) {
        // Ensure string
        var result = value + "";
        while (result.length < size) {
            result = pad + result + pad;
        }
        return result;
    };

    /**
     * @static
     * @param {string} value
     * @return {string}
     */
    StringUtil.pluralize = function(value) {
        //TODO also add irregular patterns
        var irregularPlurals = {
            winklevoss: "winklevii"
        };
        if (irregularPlurals[value]) {
            return irregularPlurals[value]
        } else {
            return value + "s";
        }
    };

    /**
     * @static
     * @param {string} value
     * @param {string} pad
     * @param {number} size
     * @return {string}
     */
    StringUtil.rpad = function(value, pad, size) {
        var result = value + "";
        while (result.length < size) {
            result = result + pad;
        }
        return result;
    };

    /**
     * @static
     * @param {string} value
     * @param {string=} chars
     * @return {string}
     */
    StringUtil.rtrim = function(value, chars) {
        chars = chars || "\\s";
        return value.replace(new RegExp("[" + chars + "]+$", "g"), "");
    };

    /**
     * @static
     * @param {string} value
     * @param {string} separator
     * @param {(function(string, number, Array.<string>):*)=} lineProcessor
     * @return {Array.<string>}
     */
    StringUtil.split = function(value, separator, lineProcessor) {
        var lines = value.split(separator);
        if (lineProcessor) {
            lines = lines.map(lineProcessor);
        }
        return lines;
    };

    /**
     * @static
     * @param {string} value
     * @param {string=} chars
     * @return {string}
     */
    StringUtil.trim = function(value, chars) {
        chars = chars || "\\s";
        return value.replace(new RegExp("^[" + chars + "]+|[" + chars + "]+$", "g"), "");
    };

    /**
     * @static
     * @param {string} value
     * @return {string}
     */
    StringUtil.uncapitalize = function(value) {
        var strings = value.split(" ");
        var result;
        if (strings.map) {
            result = strings.map(function(string, index, array) {
                return string[0].toLowerCase() + string.substring(1);
            });
        } else {
            result = [];
            strings.forEach(function(string) {
                result.push(string[0].toLowerCase() + string.substring(1));
            });
        }
        return result.join(" ");
    };

    //-------------------------------------------------------------------------------
    // Exports
    //-------------------------------------------------------------------------------

    bugpack.export('StringUtil', StringUtil);
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    var win = $(window);
    win.scroll(function() {
        if ($(document).height() - win.height() - win.scrollTop() < 150) {
            var formData = $('#pagination form:last').serialize();
            if (formData) {
                $('#pagination').html('

');
                $.post('./', formData, function (data) {
                    var body = $(data);
                    $('#pagination').remove();
                    $('#main_results').append('
');
                    $('#main_results').append(body.find('.result'));
                    $('#main_results').append(body.find('#pagination'));
                });
            }
        }
    });
});
<commit_msg>[mod] infinite scroll: XHR requests are sent with the header "Accept: text/html".<commit_after>$(document).ready(function() {
    var win = $(window);
    win.scroll(function() {
        if ($(document).height() - win.height() - win.scrollTop() < 150) {
            var formData = $('#pagination form:last').serialize();
            if (formData) {
                $('#pagination').html('

');
                $.ajax({
                    type: "POST",
                    url: './',
                    data: formData,
                    dataType: 'html',
                    success: function(data) {
                        var body = $(data);
                        $('#pagination').remove();
                        $('#main_results').append('
');
                        $('#main_results').append(body.find('.result'));
                        $('#main_results').append(body.find('#pagination'));
                    }
                });
            }
        }
    });
});
<|endoftext|>


<commit_before>jQuery(document).ready(function () {

    /*
    $('#nav').affix({
        offset: {
            top: $('#nav').offset().top
        }
    });
    */

    /**
     * Enable tooltips and popvers
     */
    $('[data-toggle="tooltip"]').tooltip({
        container: 'body'
    });
    //$('[data-toggle="popover"]').popover();

    /**
     * Admin event list table
     */
    $('#eventListTable').on('click-row.bs.table', function (e, row, $element) {
        location.href = row.eid;
    });

    /**
     * Admin event particioation list table
     */
    $('#participantsListTable').on('click-row.bs.table', function (e, row, $element) {
        location.href = 'participation/' + row.pid;
    });

    /**
     * Handle via prototype injected forms
     */
    $('.prototype-container').each(function (index) {
        var element = $(this),
            prototype;
        if (element.attr('data-prototype')) {
            prototype = element.data('prototype');

            var addElementHandlers = function () {
                element.find('.prototype-remove').on('click', function (e) {
                    e.preventDefault();
                    $(this).parent().parent().parent().parent().remove();
                });
                element.find('[data-toggle="popover"]').popover({
                    container: 'body',
                    placement: 'top',
                    html: true,
                    trigger: 'focus|click'
                });
            };

            element.data('index', element.find('.prototype-element').length);
            element.find('.prototype-add').on('click', function (e) {
                e.preventDefault();
                var index = element.data('index');
                var newForm = prototype.replace(/__name__/g, index);
                element.data('index', index + 1);

                element.find('.prototype-elements').append(newForm);
                addElementHandlers();
            });
            addElementHandlers();
        }
    });

});<commit_msg>Tried to provide a workaround for popover on iOs problem<commit_after>jQuery(document).ready(function () {

    /*
     $('#nav').affix({
     offset: {
     top: $('#nav').offset().top
     }
     });
     */

    /**
     * Enable tooltips and popvers
     */
    $('[data-toggle="tooltip"]').tooltip({
        container: 'body'
    });
    //$('[data-toggle="popover"]').popover();

    /**
     * Admin event list table
     */
    $('#eventListTable').on('click-row.bs.table', function (e, row, $element) {
        location.href = row.eid;
    });

    /**
     * Admin event particioation list table
     */
    $('#participantsListTable').on('click-row.bs.table', function (e, row, $element) {
        location.href = 'participation/' + row.pid;
    });

    /**
     * Handle via prototype injected forms
     */
    $('.prototype-container').each(function (index) {
        var element = $(this),
            prototype;
        if (element.attr('data-prototype')) {
            prototype = element.data('prototype');

            var addElementHandlers = function () {
                element.find('.prototype-remove').on('click', function (e) {
                    e.preventDefault();
                    $(this).parent().parent().parent().parent().remove();
                });
                element.find('[data-toggle="popover"]').popover({
                    container: 'body',
                    placement: 'top',
                    html: true,
                    trigger: 'focus'
                }).click(function (e) {
                    e.preventDefault();
                    $(this).popover('toggle');
                });
            };

            element.data('index', element.find('.prototype-element').length);
            element.find('.prototype-add').on('click', function (e) {
                e.preventDefault();
                var index = element.data('index');
                var newForm = prototype.replace(/__name__/g, index);
                element.data('index', index + 1);

                element.find('.prototype-elements').append(newForm);
                addElementHandlers();
            });
            addElementHandlers();
        }
    });

});<|endoftext|>


<commit_before>export default function selectAll(input, tree, output) {
    //compare the sequenceString being pasted in with what's already stored in the clipboard
    var sequenceLength = tree.get(['sequenceLength']);
    output({
        selectionLayer: {
        	start: 0,
        	end: sequenceLength - 2
        }
    });
}<commit_msg>changing back the difference<commit_after>export default function selectAll(input, tree, output) {
    //compare the sequenceString being pasted in with what's already stored in the clipboard
    var sequenceLength = tree.get(['sequenceLength']);
    output({
        selectionLayer: {
        	start: 0,
        	end: sequenceLength - 1
        }
    });
}<|endoftext|>