_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q52500
registerUndrier
train
function registerUndrier(constructor, fnc, options) { var path; if (typeof constructor == 'function') { path = constructor.name; } else { path = constructor; } undriers[path] = { fnc : fnc, options : options || {} }; }
javascript
{ "resource": "" }
q52501
findClass
train
function findClass(value) { var constructor, ns; // Return nothing for falsy values if (!value) { return null; } // Look for a regular class when it's just a string if (typeof value == 'string') { if (exports.Classes[value]) { return exports.Classes[value]; } return null; } if (value.path) { return fromPath(exports.Classes, value.path); } else { if (value.namespace) { ns = fromPath(exports.Classes, value.namespace); } else { ns = exports.Classes; } if (value.dry_class) { constructor = fromPath(ns, value.dry_class); } else if (value.name) { constructor = ns[value.name]; } if (!constructor && ns) { if (ns.main_class) { ns = ns.main_class; } if (ns && typeof ns.getClassForUndry == 'function') { constructor = ns.getClassForUndry(value.dry_class || value.name); } } } if (!constructor) { console.log('Could not find constructor for', value); } return constructor; }
javascript
{ "resource": "" }
q52502
regenerateArray
train
function regenerateArray(root, holder, current, seen, retrieve, undry_paths, old, current_path) { var length = current.length, temp, i; for (i = 0; i < length; i++) { // Only regenerate if it's not yet seen if (!seen.get(current[i])) { temp = current_path.slice(0); temp.push(i); current[i] = regenerate(root, current, current[i], seen, retrieve, undry_paths, old, temp); } } return current; }
javascript
{ "resource": "" }
q52503
regenerateObject
train
function regenerateObject(root, holder, current, seen, retrieve, undry_paths, old, current_path) { var path, temp, key; for (key in current) { if (current.hasOwnProperty(key)) { // Only regenerate if it's not already seen if (!seen.get(current[key])) { path = current_path.slice(0); path.push(key); temp = regenerate(root, current, current[key], seen, retrieve, undry_paths, old, path); // @TODO: Values returned by `unDry` methods also get regenerated, // even though these could contain properties coming from somewhere else, // like live HTMLCollections. Assigning anything to that will throw an error. // This is a workaround to that proble: if the value is exactly the same, // it's not needed to assign it again, so it won't throw an error, // but it's not an ideal solution. if (temp !== current[key]) { current[key] = temp; } } } } return current; }
javascript
{ "resource": "" }
q52504
regenerate
train
function regenerate(root, holder, current, seen, retrieve, undry_paths, old, current_path) { var temp; if (current && typeof current == 'object') { // Remember this object has been regenerated already seen.set(current, true); if (current instanceof Array) { return regenerateArray(root, holder, current, seen, retrieve, undry_paths, old, current_path); } if (current instanceof String) { if (current.length > -1) { current = current.toString(); if (temp = undry_paths.get(current)) { if (typeof temp.undried != 'undefined') { return temp.undried; } if (!holder) { throw new Error('Unable to resolve recursive reference'); } undry_paths.extra_pass.push([holder, temp, current_path]); return temp; } if (retrieve.hasOwnProperty(current)) { temp = retrieve[current]; } else { temp = retrieve[current] = retrieveFromPath(root, current.split(special_char)); if (typeof temp == 'undefined') { temp = retrieve[current] = getFromOld(old, current.split(special_char)); } } // Because we always regenerate parsed objects first // (JSON-dry parsing goes from string » object » regenerated object) // keys of regular objects can appear out-of-order, so we need to parse them if (temp && temp instanceof String) { // Unset the String as a valid result retrieve[current] = null; // Regenerate the string again // (We have to create a new instance, because it's already been "seen") temp = retrieve[current] = regenerate(root, holder, new String(temp), seen, retrieve, undry_paths, old, current_path); } return temp; } else { return root; } } return regenerateObject(root, holder, current, seen, retrieve, undry_paths, old, current_path); } return current; }
javascript
{ "resource": "" }
q52505
getFromOld
train
function getFromOld(old, pieces) { var length = pieces.length, result, path, rest, i; for (i = 0; i < length; i++) { path = pieces.slice(0, length - i).join('.'); result = old[path]; if (typeof result != 'undefined') { if (i == 0) { return result; } rest = pieces.slice(pieces.length - i); result = retrieveFromPath(result, rest); if (typeof result != 'undefined') { return result; } } } }
javascript
{ "resource": "" }
q52506
retrieveFromPath
train
function retrieveFromPath(current, keys) { var length = keys.length, prev, key, i; // Keys [''] always means the root if (length == 1 && keys[0] === '') { return current; } for (i = 0; i < length; i++) { key = keys[i]; // Normalize the key if (typeof key == 'number') { // Allow } else if (key.indexOf(safe_special_char) > -1) { key = key.replace(safe_special_char_rg, special_char); } prev = current; if (current) { if (current.hasOwnProperty(key)) { current = current[key]; } else { return undefined; } } else { return undefined; } } return current; }
javascript
{ "resource": "" }
q52507
fromPath
train
function fromPath(obj, path) { var pieces, here, len, i; if (typeof path == 'string') { pieces = path.split('.'); } else { pieces = path; } here = obj; // Go over every piece in the path for (i = 0; i < pieces.length; i++) { if (here != null) { if (here.hasOwnProperty(pieces[i])) { here = here[pieces[i]]; } else { return null; } } else { break; } } return here; }
javascript
{ "resource": "" }
q52508
setPath
train
function setPath(obj, keys, value, force) { var here, i; here = obj; for (i = 0; i < keys.length - 1; i++) { if (here != null) { if (here.hasOwnProperty(keys[i])) { here = here[keys[i]]; } else { if (force && here[keys[i]] == null) { here[keys[i]] = {}; here = here[keys[i]]; continue; } return null; } } } here[keys[keys.length - 1]] = value; }
javascript
{ "resource": "" }
q52509
toDryObject
train
function toDryObject(value, replacer) { var root = {'': value}; return createDryReplacer(root, replacer)(root, '', value); }
javascript
{ "resource": "" }
q52510
stringify
train
function stringify(value, replacer, space) { return JSON.stringify(toDryObject(value, replacer), null, space); }
javascript
{ "resource": "" }
q52511
walk
train
function walk(obj, fnc, result) { var is_root, keys, key, ret, i; if (!result) { is_root = true; if (Array.isArray(obj)) { result = []; } else { result = {}; } } keys = Object.keys(obj); for (i = 0; i < keys.length; i++) { key = keys[i]; if (typeof obj[key] == 'object' && obj[key] != null) { if (Array.isArray(obj[key])) { result[key] = walk(obj[key], fnc, []); } else { result[key] = walk(obj[key], fnc, {}); } result[key] = fnc(key, result[key], result); } else { // Fire the function result[key] = fnc(key, obj[key], obj); } } if (is_root) { result = fnc('', result); } return result; }
javascript
{ "resource": "" }
q52512
parse
train
function parse(object, reviver) { var undry_paths = new Map(), retrieve = {}, reviver, result, holder, entry, temp, seen, path, key, old = {}; // Create the reviver function reviver = generateReviver(reviver, undry_paths); if (typeof object == 'string') { object = JSON.parse(object); } if (!object || typeof object != 'object') { return object; } result = walk(object, reviver); if (result == null) { return result; } // To remember which objects have already been revived seen = new WeakMap(); // Maybe paths need another round of undrying undry_paths.extra_pass = []; // Iterate over all the values that require some kind of function to be revived undry_paths.forEach(function eachEntry(entry, path) { var path_array = entry.drypath, path_string = path_array.join('.'); // Regenerate this replacement wrapper first regenerate(result, null, entry, seen, retrieve, undry_paths, old, path_array.slice(0)); if (entry.unDryConstructor) { entry.undried = entry.unDryConstructor.unDry(entry.value, false); } else if (entry.unDryFunction) { entry.undried = entry.unDryFunction(entry, null, entry.value); } else { entry.undried = entry.value; } // Remember the old wrapper entry, some other references // may still point to it's children old[path_string] = entry; if (entry.drypath && entry.drypath.length) { setPath(result, entry.drypath, entry.undried); } }); for (var i = 0; i < undry_paths.extra_pass.length; i++) { entry = undry_paths.extra_pass[i]; holder = entry[0]; temp = entry[1]; path = entry[2]; for (key in holder) { if (holder[key] == temp) { holder[key] = temp.undried; break; } } path.pop(); // Annoying workaround for some circular references if (path.length && path[path.length - 1] == 'value') { path.pop(); } if (path.length) { // Get the other holder holder = retrieveFromPath(result, path); // If the holder object was not found in the result, // it was probably a child of ANOTHER holder that has already been undried & replaces // Just get the value from the object containing old references if (!holder) { holder = getFromOld(old, path); } for (key in holder) { if (holder[key] == temp) { holder[key] = temp.undried; break; } } } } // Only now we can resolve paths result = regenerate(result, result, result, seen, retrieve, undry_paths, old, []); if (result.undried != null && result.dry) { return result.undried; } return result; }
javascript
{ "resource": "" }
q52513
train
function () { var inputs = Array.prototype.slice.call(arguments, 0); return external.message.apply(this, inputs); }
javascript
{ "resource": "" }
q52514
train
function (type, item, hard) { if (hard) { return harderTypes[type](getType(item), item); } return (getType(item) === simpleTypes[type]); }
javascript
{ "resource": "" }
q52515
train
function (type, item) { switch(type) { case simpleTypes.undefined: case simpleTypes.null: return true; case simpleTypes.string: if (item.trim().length === 0) { return true; } return false; case simpleTypes.object: return (Object.keys(item).length === 0); case simpleTypes.array: return (item.length === 0); default: return false; }; }
javascript
{ "resource": "" }
q52516
train
function (inputs) { var props = { }; // Create a function to call with simple and hard types // This is done so simple types don't need to check for hard types var generateProps = function (types, hard) { for (var t in types) { if (types.hasOwnProperty(t)) { (function (prop) { Object.defineProperty(props, prop, { get: function () { for (var i = 0; i < inputs.length; ++i) { if (!checkType(prop, inputs[i], hard)) { return false; } } return true; } }); }(t)); } } }; generateProps(simpleTypes, false); generateProps(harderTypes, true); // Check whether the specified inputs even exist Object.defineProperty(props, "there", { get: function () { for (var i = 0; i < inputs.length; ++i) { if (inputs[i] === undefined || inputs[i] === null) { return false; } } return true; } }); // Check whether a passed in input is considered empty or not Object.defineProperty(props, "empty", { get: function () { for (var i = 0; i < inputs.length; ++i) { if (!checkEmpty(getType(inputs[i]), inputs[i])) { return false; } } return true; } }); return props; }
javascript
{ "resource": "" }
q52517
train
function (types, hard) { for (var t in types) { if (types.hasOwnProperty(t)) { (function (prop) { Object.defineProperty(props, prop, { get: function () { for (var i = 0; i < inputs.length; ++i) { if (!checkType(prop, inputs[i], hard)) { return false; } } return true; } }); }(t)); } } }
javascript
{ "resource": "" }
q52518
train
function (obj1, obj2, overwrite) { if (obj1 === undefined || obj1 === null) { return obj2; }; if (obj2 === undefined || obj2 === null) { return obj1; }; var obj1Type = external.is(obj1).getType(); var obj2Type = external.is(obj2).getType(); var exceptionMsg; if (acceptableForObj1.indexOf(obj1Type) === -1 || acceptableForObj2.indexOf(obj2Type) === -1) { exceptionMsg = "msngr.merge() - Only objects, arrays or a single function followed by objects can be merged!"; } if ([obj1Type, obj2Type].indexOf(internal.types.array) !== -1 && (obj1Type !== internal.types.array || obj2Type !== internal.types.array)) { exceptionMsg = "msngr.merge() - Arrays cannot be merged with objects or functions!"; } if (overwrite === true) { return obj2; } if (exceptionMsg) { throw new Error(exceptionMsg); } var result = obj1; // If we're in the weird spot of getting only arrays then concat and return // Seriously though, Mr or Mrs or Ms dev, just use Array.prototype.concat()! if (obj1Type === internal.types.array && obj2Type === internal.types.array) { return obj1.concat(obj2); } for (var key in obj2) { if (obj2.hasOwnProperty(key)) { var is = external.is(obj2[key]); if (is.object) { result[key] = result[key] || { }; result[key] = twoMerge(result[key], obj2[key]); } else if (is.array) { result[key] = result[key] || []; result[key] = result[key].concat(obj2[key]); } else { result[key] = obj2[key]; } } } return result; }
javascript
{ "resource": "" }
q52519
train
function(arr, value) { var inx = arr.indexOf(value); var endIndex = arr.length - 1; if (inx !== endIndex) { var temp = arr[endIndex]; arr[endIndex] = arr[inx]; arr[inx] = temp; } arr.pop(); }
javascript
{ "resource": "" }
q52520
train
function (uses, payload, message) { var results = []; var keys = (uses || []); for (var i = 0; i < forced.length; ++i) { if (keys.indexOf(forced[i]) === -1) { keys.push(forced[i]); } } for (var i = 0; i < keys.length; ++i) { if (middlewares[keys[i]] !== undefined) { results.push({ method: middlewares[keys[i]], params: [payload, message] }); } } return results; }
javascript
{ "resource": "" }
q52521
train
function (uses, payload, message, callback) { var middles = getMiddlewares(uses, payload, message); internal.executer(middles).series(function (result) { return callback(internal.merge.apply(this, [payload].concat(result))); }); }
javascript
{ "resource": "" }
q52522
train
function (msgOrIds, payload, callback) { var ids = (external.is(msgOrIds).array) ? msgOrIds : messageIndex.query(msgOrIds); if (ids.length > 0) { var methods = []; var toDrop = []; for (var i = 0; i < ids.length; ++i) { var msg = (external.is(msgOrIds).object) ? external.copy(msgOrIds) : external.copy(messageIndex.query(ids[i])); var obj = handlers[ids[i]]; methods.push({ method: obj.handler, params: [payload, msg] }); if (obj.once === true) { toDrop.push({ msg: msg, handler: obj.handler }); } } var execs = internal.executer(methods); for (var i = 0; i < toDrop.length; ++i) { external(toDrop[i].msg).drop(toDrop[i].handler); } execs.parallel(callback); } }
javascript
{ "resource": "" }
q52523
drawToCanvas
train
function drawToCanvas({data, width, height}) { if (typeof document === 'undefined') return null var canvas = document.createElement('canvas') canvas.width = width canvas.height = height var context = canvas.getContext('2d') var idata = context.createImageData(canvas.width, canvas.height) for (var i = 0; i < data.length; i++) { idata.data[i] = data[i] } context.putImageData(idata, 0, 0) return canvas }
javascript
{ "resource": "" }
q52524
inheritsTlSchema
train
function inheritsTlSchema(constructor, superTlSchema) { var NewType = buildType('abstract', superTlSchema); util.inherits(constructor, NewType); constructor.s_ = NewType; constructor.super_ = NewType.super_; constructor.util = NewType.util; constructor.requireTypeByName = NewType.requireTypeByName; constructor.requireTypeFromBuffer = NewType.requireTypeFromBuffer; constructor.logger = NewType.logger; }
javascript
{ "resource": "" }
q52525
buildTypeFunction
train
function buildTypeFunction(module, tlSchema) { var methodName = tlSchema.method; // Start creating the body of the new Type function var body = '\tvar self = arguments.callee;\n' + '\tvar callback = options.callback;\n' + '\tvar channel = options.channel;\n' + '\tif (!channel) {\n' + '\t\tvar msg = \'The \\\'channel\\\' option is missing, it\\\'s mandatory\';\n' + '\t\tself.logger.error(msg);\n' + '\t\tif(callback) {\n' + '\t\t\tcallback(new TypeError(msg));\n' + '\t\t}\n' + '\t\treturn;\n' + '\t}\n'; body += '\tvar reqPayload = new self.Type(options);\n' + '\tchannel.callMethod(reqPayload, callback);\n'; if (logger.isDebugEnabled()) { logger.debug('Body for %s type function:', methodName); logger.debug('\n' + body); } // Create the new Type function var typeFunction = new Function('options', body); typeFunction._name = methodName; typeFunction.requireTypeFromBuffer = ConstructorBuilder.requireTypeFromBuffer; // Create the function payload class re-calling TypeBuilder constructor. typeFunction.Type = new ConstructorBuilder(module, tlSchema, true).getType(); typeFunction.logger = getLogger(module + '.' + methodName); return typeFunction; }
javascript
{ "resource": "" }
q52526
registerTypeById
train
function registerTypeById(type) { if (registryLogger.isDebugEnabled()) { registryLogger.debug('Register Type \'%s\' by id [%s]', type.typeName, type.id); } if(type.id) { typeById[type.id] = type; } return type; }
javascript
{ "resource": "" }
q52527
requireTypeFromBuffer
train
function requireTypeFromBuffer(buffer) { var typeId = buffer.slice(0, 4).toString('hex'); var type = typeById[typeId]; if (!type) { var msg = 'Unable to retrieve a Type by Id [' + typeId + ']'; registryLogger.error(msg); throw new Error(msg); } if (registryLogger.isDebugEnabled()) { registryLogger.debug('Require Type \'%s\' by id [%s]', type.typeName, typeId); } return type; }
javascript
{ "resource": "" }
q52528
registerTypeByName
train
function registerTypeByName(type) { if (registryLogger.isDebugEnabled()) { registryLogger.debug('Register Type \'%s\' by name [%s]', type.id, type.typeName); } typeByName[type.typeName] = type; return type; }
javascript
{ "resource": "" }
q52529
requireTypeByName
train
function requireTypeByName(typeName) { var type = typeByName[typeName]; if (!type) { var msg = 'Unable to retrieve a Type by Name [' + typeName + ']'; registryLogger.error(msg); throw new Error(msg); } if (registryLogger.isDebugEnabled()) { registryLogger.debug('Require Type \'%s\' by name [%s]', type.id, typeName); } return type; }
javascript
{ "resource": "" }
q52530
toPrintable
train
function toPrintable(exclude, noColor) { var str = '{ ' + ( this._typeName ? 'T:' + this._typeName.bold : ''); if (typeof exclude !== 'object') { noColor = exclude; exclude = {}; } for (var prop in this) { if ('_' !== prop.charAt(0) && exclude[prop] !== true) { var pair = value2String(prop, this[prop], exclude[prop], noColor); if (pair.value !== undefined) { str = str.slice(-1) === ' ' ? str : str + ', '; str += (noColor ? pair.prop : pair.prop.bold.cyan) + ': ' + pair.value; } } } str += ' }'; return str; }
javascript
{ "resource": "" }
q52531
stringValue2Buffer
train
function stringValue2Buffer(stringValue, byteLength) { if ((stringValue).slice(0, 2) === '0x') { var input = stringValue.slice(2); var length = input.length; var buffers = []; var j = 0; for (var i = length; i > 0 && j < byteLength; i -= 2) { buffers.push(new Buffer(input.slice(i - 2, i), 'hex')); j++; } var buffer = Buffer.concat(buffers); var paddingLength = byteLength - buffer.length; if (paddingLength > 0) { var padding = new Buffer(paddingLength); padding.fill(0); buffer = Buffer.concat([buffer, padding]); } return buffer; } else { return bigInt2Buffer(new BigInteger(stringValue), byteLength); } }
javascript
{ "resource": "" }
q52532
buffer2StringValue
train
function buffer2StringValue(buffer) { var length = buffer.length; var output = '0x'; for (var i = length; i > 0; i--) { output += buffer.slice(i - 1, i).toString('hex'); } return output; }
javascript
{ "resource": "" }
q52533
HttpViewEngine
train
function HttpViewEngine(context) { if (this.constructor === HttpViewEngine.prototype.constructor) { throw new AbstractClassError(); } /** * @name HttpViewEngine#context * @type HttpContext * @description Gets or sets an instance of HttpContext that represents the current HTTP context. */ /** * @type {HttpContext} */ var ctx = context; Object.defineProperty(this,'context', { get: function() { return ctx; }, set: function(value) { ctx = value; }, configurable:false, enumerable:false }); }
javascript
{ "resource": "" }
q52534
isValidPath
train
function isValidPath(path) { if (path === null || path === undefined) return false; return typeof path === 'string' && path.length > 0; }
javascript
{ "resource": "" }
q52535
queryController
train
function queryController(requestUri) { try { if (requestUri === undefined) return null; //split path var segments = requestUri.pathname.split('/'); //put an exception for root controller //maybe this is unnecessary exception but we need to search for root controller e.g. /index.html, /about.html if (segments.length === 2) return 'root'; else //e.g /pages/about where segments are ['','pages','about'] //and the controller of course is always the second segment. return segments[1]; } catch (err) { throw err; } }
javascript
{ "resource": "" }
q52536
XmlCommon
train
function XmlCommon() { //constants this.DOM_ELEMENT_NODE = 1; this.DOM_ATTRIBUTE_NODE = 2; this.DOM_TEXT_NODE = 3; this.DOM_CDATA_SECTION_NODE = 4; // noinspection JSUnusedGlobalSymbols this.DOM_ENTITY_REFERENCE_NODE = 5; // noinspection JSUnusedGlobalSymbols this.DOM_ENTITY_NODE = 6; this.DOM_PROCESSING_INSTRUCTION_NODE = 7; this.DOM_COMMENT_NODE = 8; this.DOM_DOCUMENT_NODE = 9; // noinspection JSUnusedGlobalSymbols this.DOM_DOCUMENT_TYPE_NODE = 10; this.DOM_DOCUMENT_FRAGMENT_NODE = 11; // noinspection JSUnusedGlobalSymbols this.DOM_NOTATION_NODE = 12; this.REGEXP_UNICODE = function () { var tests = [' ', '\u0120', -1, // Konquerer 3.4.0 fails here. '!', '\u0120', -1, '\u0120', '\u0120', 0, '\u0121', '\u0120', -1, '\u0121', '\u0120|\u0121', 0, '\u0122', '\u0120|\u0121', -1, '\u0120', '[\u0120]', 0, // Safari 2.0.3 fails here. '\u0121', '[\u0120]', -1, '\u0121', '[\u0120\u0121]', 0, // Safari 2.0.3 fails here. '\u0122', '[\u0120\u0121]', -1, '\u0121', '[\u0120-\u0121]', 0, // Safari 2.0.3 fails here. '\u0122', '[\u0120-\u0121]', -1]; for (var i = 0; i < tests.length; i += 3) { if (tests[i].search(new RegExp(tests[i + 1])) !== tests[i + 2]) { return false; } } return true; }(); this.XML_S = '[ \t\r\n]+'; this.XML_EQ = '(' + this.XML_S + ')?=(' + this.XML_S + ')?'; this.XML_CHAR_REF = '&#[0-9]+;|&#x[0-9a-fA-F]+;'; // XML 1.0 tokens. this.XML10_VERSION_INFO = this.XML_S + 'version' + this.XML_EQ + '("1\\.0"|' + "'1\\.0')"; this.XML10_BASE_CHAR = (this.REGEXP_UNICODE) ? '\u0041-\u005a\u0061-\u007a\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff' + '\u0100-\u0131\u0134-\u013e\u0141-\u0148\u014a-\u017e\u0180-\u01c3' + '\u01cd-\u01f0\u01f4-\u01f5\u01fa-\u0217\u0250-\u02a8\u02bb-\u02c1\u0386' + '\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03ce\u03d0-\u03d6\u03da\u03dc' + '\u03de\u03e0\u03e2-\u03f3\u0401-\u040c\u040e-\u044f\u0451-\u045c' + '\u045e-\u0481\u0490-\u04c4\u04c7-\u04c8\u04cb-\u04cc\u04d0-\u04eb' + '\u04ee-\u04f5\u04f8-\u04f9\u0531-\u0556\u0559\u0561-\u0586\u05d0-\u05ea' + '\u05f0-\u05f2\u0621-\u063a\u0641-\u064a\u0671-\u06b7\u06ba-\u06be' + '\u06c0-\u06ce\u06d0-\u06d3\u06d5\u06e5-\u06e6\u0905-\u0939\u093d' + '\u0958-\u0961\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2' + '\u09b6-\u09b9\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u0a05-\u0a0a' + '\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36' + '\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8b\u0a8d' + '\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9' + '\u0abd\u0ae0\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30' + '\u0b32-\u0b33\u0b36-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b85-\u0b8a' + '\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4' + '\u0ba8-\u0baa\u0bae-\u0bb5\u0bb7-\u0bb9\u0c05-\u0c0c\u0c0e-\u0c10' + '\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c60-\u0c61\u0c85-\u0c8c' + '\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cde\u0ce0-\u0ce1' + '\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d60-\u0d61' + '\u0e01-\u0e2e\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84' + '\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5' + '\u0ea7\u0eaa-\u0eab\u0ead-\u0eae\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4' + '\u0f40-\u0f47\u0f49-\u0f69\u10a0-\u10c5\u10d0-\u10f6\u1100\u1102-\u1103' + '\u1105-\u1107\u1109\u110b-\u110c\u110e-\u1112\u113c\u113e\u1140\u114c' + '\u114e\u1150\u1154-\u1155\u1159\u115f-\u1161\u1163\u1165\u1167\u1169' + '\u116d-\u116e\u1172-\u1173\u1175\u119e\u11a8\u11ab\u11ae-\u11af' + '\u11b7-\u11b8\u11ba\u11bc-\u11c2\u11eb\u11f0\u11f9\u1e00-\u1e9b' + '\u1ea0-\u1ef9\u1f00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d' + '\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc' + '\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec' + '\u1ff2-\u1ff4\u1ff6-\u1ffc\u2126\u212a-\u212b\u212e\u2180-\u2182' + '\u3041-\u3094\u30a1-\u30fa\u3105-\u312c\uac00-\ud7a3' : 'A-Za-z'; this.XML10_IDEOGRAPHIC = (this.REGEXP_UNICODE) ? '\u4e00-\u9fa5\u3007\u3021-\u3029' : ''; this.XML10_COMBINING_CHAR = (this.REGEXP_UNICODE) ? '\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05a1\u05a3-\u05b9' + '\u05bb-\u05bd\u05bf\u05c1-\u05c2\u05c4\u064b-\u0652\u0670\u06d6-\u06dc' + '\u06dd-\u06df\u06e0-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0901-\u0903\u093c' + '\u093e-\u094c\u094d\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09bc\u09be' + '\u09bf\u09c0-\u09c4\u09c7-\u09c8\u09cb-\u09cd\u09d7\u09e2-\u09e3\u0a02' + '\u0a3c\u0a3e\u0a3f\u0a40-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a70-\u0a71' + '\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0b01-\u0b03' + '\u0b3c\u0b3e-\u0b43\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b82-\u0b83' + '\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0c01-\u0c03\u0c3e-\u0c44' + '\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c82-\u0c83\u0cbe-\u0cc4' + '\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d43' + '\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1' + '\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39' + '\u0f3e\u0f3f\u0f71-\u0f84\u0f86-\u0f8b\u0f90-\u0f95\u0f97\u0f99-\u0fad' + '\u0fb1-\u0fb7\u0fb9\u20d0-\u20dc\u20e1\u302a-\u302f\u3099\u309a' : ''; this.XML10_DIGIT = (this.REGEXP_UNICODE) ? '\u0030-\u0039\u0660-\u0669\u06f0-\u06f9\u0966-\u096f\u09e6-\u09ef' + '\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be7-\u0bef\u0c66-\u0c6f' + '\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29' : '0-9'; this.XML10_EXTENDER = (this.REGEXP_UNICODE) ? '\u00b7\u02d0\u02d1\u0387\u0640\u0e46\u0ec6\u3005\u3031-\u3035' + '\u309d-\u309e\u30fc-\u30fe' : ''; this.XML10_LETTER = this.XML10_BASE_CHAR + this.XML10_IDEOGRAPHIC; this.XML10_NAME_CHAR = this.XML10_LETTER + this.XML10_DIGIT + '\\._:' + this.XML10_COMBINING_CHAR + this.XML10_EXTENDER + '-'; this.XML10_NAME = '[' + this.XML10_LETTER + '_:][' + this.XML10_NAME_CHAR + ']*'; this.XML10_ENTITY_REF = '&' + this.XML10_NAME + ';'; this.XML10_REFERENCE = this.XML10_ENTITY_REF + '|' + this.XML_CHAR_REF; this.XML10_ATT_VALUE = '"(([^<&"]|' + this.XML10_REFERENCE + ')*)"|' + "'(([^<&']|" + this.XML10_REFERENCE + ")*)'"; this.XML10_ATTRIBUTE = '(' + this.XML10_NAME + ')' + this.XML_EQ + '(' + this.XML10_ATT_VALUE + ')'; // XML 1.1 tokens. this.XML11_VERSION_INFO = this.XML_S + 'version' + this.XML_EQ + '("1\\.1"|' + "'1\\.1')"; this.XML11_NAME_START_CHAR = (this.REGEXP_UNICODE) ? ':A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d' + '\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff' + '\uf900-\ufdcf\ufdf0-\ufffd' : ':A-Z_a-z'; this.XML11_NAME_CHAR = this.XML11_NAME_START_CHAR + ((this.REGEXP_UNICODE) ? '\\.0-9\u00b7\u0300-\u036f\u203f-\u2040-' : '\\.0-9-'); this.XML11_NAME = '[' + this.XML11_NAME_START_CHAR + '][' + this.XML11_NAME_CHAR + ']*'; this.XML11_ENTITY_REF = '&' + this.XML11_NAME + ';'; this.XML11_REFERENCE = this.XML11_ENTITY_REF + '|' + this.XML_CHAR_REF; this.XML11_ATT_VALUE = '"(([^<&"]|' + this.XML11_REFERENCE + ')*)"|' + "'(([^<&']|" + this.XML11_REFERENCE + ")*)'"; this.XML11_ATTRIBUTE = '(' + this.XML11_NAME + ')' + this.XML_EQ + '(' + this.XML11_ATT_VALUE + ')'; // XML namespace tokens. // Used in XML parser and XPath parser. this.XML_NC_NAME_CHAR = this.XML10_LETTER + this.XML10_DIGIT + '\\._' + this.XML10_COMBINING_CHAR + this.XML10_EXTENDER + '-'; this.XML_NC_NAME = '[' + this.XML10_LETTER + '_][' + this.XML_NC_NAME_CHAR + ']*'; this.XML10_TAGNAME_REGEXP = new RegExp('^(' + this.XML10_NAME + ')'); this.XML10_ATTRIBUTE_REGEXP = new RegExp(this.XML10_ATTRIBUTE, 'g'); this.XML11_TAGNAME_REGEXP = new RegExp('^(' + this.XML11_NAME + ')'); this.XML11_ATTRIBUTE_REGEXP = new RegExp(this.XML11_ATTRIBUTE, 'g'); }
javascript
{ "resource": "" }
q52537
HttpViewResult
train
function HttpViewResult(name, data) { this.name = name; this.data = data===undefined? []: data; this.contentType = 'text/html;charset=utf-8'; this.contentEncoding = 'utf8'; }
javascript
{ "resource": "" }
q52538
HttpViewContext
train
function HttpViewContext(context) { /** * Gets or sets the body of the current view * @type {String} */ this.body=''; /** * Gets or sets the title of the page if the view will be fully rendered * @type {String} */ this.title=''; /** * Gets or sets the view layout page if the view will be fully rendered * @type {String} */ this.layout = null; /** * Gets or sets the view data * @type {String} */ this.data = null; /** * Represents the current HTTP context * @type {HttpContext} */ this.context = context; /** * @name HttpViewContext#writer * @type HtmlWriter * @description Gets an instance of HtmlWriter helper class */ var writer; Object.defineProperty(this, 'writer', { get:function() { if (writer) return writer; writer = new HtmlWriter(); writer.indent = false; return writer; }, configurable:false, enumerable:false }); var self = this; Object.defineProperty(this, 'model', { get:function() { if (self.context.params) if (self.context.params.controller) return self.context.model(self.context.params.controller); return null; }, configurable:false, enumerable:false }); //class extension initiators if (typeof this.init === 'function') { //call init() method this.init(); } }
javascript
{ "resource": "" }
q52539
sanitizeHtml
train
function sanitizeHtml(html, whitelist) { return html.replace(/<[^>]*>?/gi, function(tag) { return tag.match(whitelist) ? tag : ''; }); }
javascript
{ "resource": "" }
q52540
union
train
function union(x, y) { var obj = {}; for (var i = 0; i < x.length; i++) obj[x[i]] = x[i]; for (i = 0; i < y.length; i++) obj[y[i]] = y[i]; var res = []; for (var k in obj) { if (obj.hasOwnProperty(k)) res.push(obj[k]); } return res; }
javascript
{ "resource": "" }
q52541
removeAnchors
train
function removeAnchors(text) { if(text.charAt(0) == '\x02') text = text.substr(1); if(text.charAt(text.length - 1) == '\x03') text = text.substr(0, text.length - 1); return text; }
javascript
{ "resource": "" }
q52542
convertAll
train
function convertAll(text, extra) { var result = extra.blockGamutHookCallback(text); // We need to perform these operations since we skip the steps in the converter result = unescapeSpecialChars(result); result = result.replace(/~D/g, "$$").replace(/~T/g, "~"); result = extra.previousPostConversion(result); return result; }
javascript
{ "resource": "" }
q52543
AccessDeniedError
train
function AccessDeniedError(message, innerMessage, model) { AccessDeniedError.super_.bind(this)('EACCESS', ('Access Denied' || message) , innerMessage, model); this.statusCode = 401; }
javascript
{ "resource": "" }
q52544
UniqueConstraintError
train
function UniqueConstraintError(message, innerMessage, model) { UniqueConstraintError.super_.bind(this)('EUNQ', message || 'A unique constraint violated', innerMessage, model); }
javascript
{ "resource": "" }
q52545
caseInsensitiveAttribute
train
function caseInsensitiveAttribute(name) { if (typeof name === 'string') { if (this[name]) return this[name]; //otherwise make a case insensitive search var re = new RegExp('^' + name + '$','i'); var p = Object.keys(this).filter(function(x) { return re.test(x); })[0]; if (p) return this[p]; } }
javascript
{ "resource": "" }
q52546
MethodCallExpression
train
function MethodCallExpression(name, args) { /** * Gets or sets the name of this method * @type {String} */ this.name = name; /** * Gets or sets an array that represents the method arguments * @type {Array} */ this.args = []; if (_.isArray(args)) this.args = args; }
javascript
{ "resource": "" }
q52547
HttpRoute
train
function HttpRoute(route) { if (typeof route === 'string') { this.route = { url:route }; } else if (typeof route === 'object') { this.route = route; } this.routeData = { }; this.patterns = { int:function() { return "^[1-9]([0-9]*)$"; }, boolean:function() { return "^true|false$" }, decimal:function() { return "^[+-]?[0-9]*\\.?[0-9]*$"; }, float:function() { return "^[+-]?[0-9]*\\.?[0-9]*$"; }, guid:function() { return "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"; }, plural: function() { return "^[a-zA-Z]+$"; }, string: function() { return "^'(.*)'$" }, date:function() { return "^(datetime)?'\\d{4}-([0]\\d|1[0-2])-([0-2]\\d|3[01])(?:[T ](\\d+):(\\d+)(?::(\\d+)(?:\\.(\\d+))?)?)?(?:Z(-?\\d*))?([+-](\\d+):(\\d+))?'$"; }, }; this.parsers = { int:function(v) { return parseInt(v); }, boolean:function(v) { return (/^true$/ig.test(v)); }, decimal:function(v) { return parseFloat(v); }, float:function(v) { return parseFloat(v); }, plural:function(v) { return pluralize.singular(v); }, string:function(v) { return v.replace(/^'/,'').replace(/'$/,''); }, date:function(v) { return new Date(Date.parse(v.replace(/^(datetime)?'/,'').replace(/'$/,''))); } } }
javascript
{ "resource": "" }
q52548
xpathSort
train
function xpathSort(input, sort) { if (sort.length === 0) { return; } var sortlist = []; var i; for (i = 0; i < input.contextSize(); ++i) { var node = input.nodelist[i]; var sortitem = {node: node, key: []}; var context = input.clone(node, 0, [node]); for (var j = 0; j < sort.length; ++j) { var s = sort[j]; var value = s.expr.evaluate(context); var evalue; if (s.type === 'text') { evalue = value.stringValue(); } else if (s.type === 'number') { evalue = value.numberValue(); } sortitem.key.push({value: evalue, order: s.order}); } // Make the sort stable by adding a lowest priority sort by // id. This is very convenient and furthermore required by the // spec ([XSLT] - Section 10 Sorting). sortitem.key.push({value: i, order: 'ascending'}); sortlist.push(sortitem); } sortlist.sort(xpathSortByKey); var nodes = []; for (i = 0; i < sortlist.length; ++i) { nodes.push(sortlist[i].node); } input.nodelist = nodes; input.setNode(0); }
javascript
{ "resource": "" }
q52549
xpathEval
train
function xpathEval(select, context, ns) { var str = select; if (ns !== undefined) { if (context.node) str = context.node.prepare(select, ns); } //parse statement var expr = xpathParse(str); //and return value return expr.evaluate(context); }
javascript
{ "resource": "" }
q52550
DataModelMigration
train
function DataModelMigration() { /** * Gets an array that contains the definition of fields that are going to be added * @type {Array} */ this.add = []; /** * Gets an array that contains a collection of constraints which are going to be added * @type {Array} */ this.constraints = []; /** * Gets an array that contains a collection of indexes which are going to be added or updated * @type {Array} */ this.indexes = []; /** * Gets an array that contains the definition of fields that are going to be deleted * @type {Array} */ this.remove = []; /** * Gets an array that contains the definition of fields that are going to be changed * @type {Array} */ this.change = []; /** * Gets or sets a string that contains the internal version of this migration. This property cannot be null. * @type {string} */ this.version = '0.0'; /** * Gets or sets a string that represents a short description of this migration * @type {string} */ this.description = null; /** * Gets or sets a string that represents the adapter that is going to be migrated through this operation. * This property cannot be null. */ this.appliesTo = null; /** * Gets or sets a string that represents the model that is going to be migrated through this operation. * This property may be null. */ this.model = null; }
javascript
{ "resource": "" }
q52551
removeFromArray
train
function removeFromArray(array, value, opt_notype) { var shift = 0; for (var i = 0; i < array.length; ++i) { if (array[i] === value || (opt_notype && array[i] === value)) { array.splice(i--, 1); shift++; } } return shift; }
javascript
{ "resource": "" }
q52552
DefaultCacheStrategy
train
function DefaultCacheStrategy(app) { DefaultCacheStrategy.super_.bind(this)(app); //set absoluteExpiration (from application configuration) var expiration = CACHE_ABSOLUTE_EXPIRATION; var absoluteExpiration = LangUtils.parseInt(app.getConfiguration().getSourceAt('settings/cache/absoluteExpiration')); if (absoluteExpiration>=0) { expiration = absoluteExpiration; } this[rawCacheProperty] = new NodeCache( { stdTTL:expiration }); }
javascript
{ "resource": "" }
q52553
_remove
train
function _remove(key) { var i = _keys.indexOf(key) if (i > -1) { ls.removeItem(key); _keys.splice(_keys.indexOf(key), 1); delete _config[key]; } }
javascript
{ "resource": "" }
q52554
_executeOperation
train
function _executeOperation(operation, values) { /** * Run passed method if value passed is not NaN, otherwise throw a TypeError. * * @private * @method _ifValid * * @param value {Number} * A value to check is not NaN before running method on. * * @param method {Function} * A method to run if value is not NaN. */ function _ifValid(value, method) { if (!isNaN(value)) { method(); } else { throw new TypeError('The VendNumber method must receive a valid String or Number. ' + value); } } // Ensure there's an initial value to start operations on. var returnValue = parseFloat(values[0]); // Then remove the element at index 0. values.splice(0, 1); // Convert to VendNumber _ifValid(returnValue, function () { return returnValue = new VendNumber(returnValue); }); values.forEach(function (value) { value = parseFloat(value); _ifValid(value, function () { // Convert to VendNumber value = new VendNumber(value); // e.g. 5.plus(2) where 5 and 2 are VendNumber's returnValue = returnValue[operation](value); }); }); var operationAnswer = undefined; // Set the final result of the calculation as a standard Number. _ifValid(returnValue, function () { return operationAnswer = Number(returnValue.toString()); }); if (operationAnswer) { return operationAnswer; } // End value was not valid so value errors will be displayed but we return 0 to continue. return 0; }
javascript
{ "resource": "" }
q52555
parseSubaddress
train
function parseSubaddress(user) { var parsed = { username: user }; if (user.indexOf('+')) { parsed.username = user.split('+')[0]; parsed.subaddress = user.split('+')[1]; } return parsed; }
javascript
{ "resource": "" }
q52556
train
function (bufferRatio) { // (Number) -> LatLngBounds var sw = this._southWest, ne = this._northEast, heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio, widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio; return new L.LatLngBounds( new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer), new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer)); }
javascript
{ "resource": "" }
q52557
getAbbr
train
function getAbbr(wofData) { const iso2 = getPropertyValue(wofData, 'wof:country'); // sometimes there are codes set to XX which cause an exception so check if it's a valid ISO2 code if (iso2 !== false && iso3166.is2(iso2)) { return iso3166.to3(iso2); } return null; }
javascript
{ "resource": "" }
q52558
getPropertyValue
train
function getPropertyValue(wofData, property) { if (wofData.properties.hasOwnProperty(property)) { // if the value is an array, return the first item if (wofData.properties[property] instanceof Array) { return wofData.properties[property][0]; } // otherwise just return the value as is return wofData.properties[property]; } return false; }
javascript
{ "resource": "" }
q52559
getName
train
function getName(wofData) { // if this is a US county, use the qs:a2_alt for county // eg - wof:name = 'Lancaster' and qs:a2_alt = 'Lancaster County', use latter if (isUsCounty(wofData)) { return getPropertyValue(wofData, 'qs:a2_alt'); } // attempt to use the following in order of priority and fallback to wof:name if all else fails return getLocalizedName(wofData, 'wof:lang_x_spoken') || getLocalizedName(wofData, 'wof:lang_x_official') || getLocalizedName(wofData, 'wof:lang') || getPropertyValue(wofData, 'wof:label') || getPropertyValue(wofData, 'wof:name'); }
javascript
{ "resource": "" }
q52560
getOfficialLangName
train
function getOfficialLangName(wofData, langProperty) { var languages = wofData.properties[langProperty]; // convert to array in case it is just a string if (!(languages instanceof Array)) { languages = [languages]; } if (languages.length > 1) { logger.silly(`more than one ${langProperty} specified`, wofData.properties['wof:lang_x_official'], languages); } // for now always just grab the first language in the array return `name:${languages[0]}_x_preferred`; }
javascript
{ "resource": "" }
q52561
messageHandler
train
function messageHandler( msg ) { switch (msg.type) { case 'load' : return handleLoadMsg(msg); case 'search' : return handleSearch(msg); case 'lookupById': return handleLookupById(msg); default : logger.error('Unknown message:', msg); } }
javascript
{ "resource": "" }
q52562
search
train
function search( latLon ){ var poly = context.adminLookup.search( latLon.longitude, latLon.latitude ); return (poly === undefined) ? {} : poly.properties; }
javascript
{ "resource": "" }
q52563
extractUsernameFromLink
train
function extractUsernameFromLink(steemitLink) { if (isValidSteemitLink(steemitLink)) { const usernamePos = steemitLink.search(/\/@.+\//); if (usernamePos === -1) return; const firstPart = steemitLink.slice(usernamePos + 2); // adding 2 to remove "/@" return firstPart.slice(0, firstPart.search('/')); } }
javascript
{ "resource": "" }
q52564
extractPermlinkFromLink
train
function extractPermlinkFromLink(steemitLink) { if (isValidSteemitLink(steemitLink)) { const usernamePos = steemitLink.search(/\/@.+\//); if (usernamePos === -1) return; const firstPart = steemitLink.slice(usernamePos + 1); // adding 1 to remove the first "/" return firstPart.slice(firstPart.search('/') + 1).replace('/', '').replace('#', ''); } }
javascript
{ "resource": "" }
q52565
_handleErr
train
function _handleErr (err, callback) { if (callback) { return callback(err); } else if (promisesExist) { return Promise.reject(err); } else { throw new Error(err); } }
javascript
{ "resource": "" }
q52566
train
function (options, callback) { if (!options) { return _handleErr('Search phrase cannot be empty.', callback); } return this._request({ api: options.api || 'gifs', endpoint: 'search', query: typeof options === 'string' ? { q: options } : options }, callback); }
javascript
{ "resource": "" }
q52567
train
function (id, callback) { var idIsArr = Array.isArray(id); if (!id || (idIsArr && id.length === 0)) { return _handleErr('Id required for id API call', callback); } // If an array of Id's was passed, generate a comma delimited string for // the query string. if (idIsArr) { id = id.join(); } return this._request({ api: 'gifs', query: { ids: id } }, callback); }
javascript
{ "resource": "" }
q52568
train
function (options, callback) { if (!options) { return _handleErr('Translate phrase cannot be empty.', callback); } return this._request({ api: options.api || 'gifs', endpoint: 'translate', query: typeof options === 'string' ? { s: options } : options }, callback); }
javascript
{ "resource": "" }
q52569
train
function (options, callback) { var reqOptions = { api: (options ? options.api : null) || 'gifs', endpoint: 'random' }; if (typeof options === 'string') { reqOptions.query = { tag: options }; } else if (typeof options === 'object') { reqOptions.query = options; } else if (typeof options === 'function') { callback = options; } return this._request(reqOptions, callback); }
javascript
{ "resource": "" }
q52570
train
function (options, callback) { var reqOptions = { endpoint: 'trending' }; reqOptions.api = (options ? options.api : null) || 'gifs'; // Cleanup so we don't add this to our query if (options) { delete options.api; } if (typeof options === 'object' && Object.keys(options).length !== 0) { reqOptions.query = options; } else if (typeof options === 'function') { callback = options; } return this._request(reqOptions, callback); }
javascript
{ "resource": "" }
q52571
train
function (options, callback) { if (!callback && !promisesExist) { throw new Error('Callback must be provided if promises are unavailable'); } var endpoint = ''; if (options.endpoint) { endpoint = '/' + options.endpoint; } var query; var self = this; if (typeof options.query !== 'undefined' && typeof options.query === 'object') { if (Object.keys(options.query).length === 0) { if (callback) { return callback(new Error('Options object should not be empty')); } return Promise.reject(new Error('Options object should not be empty')); } options.query.api_key = this.apiKey; query = queryStringify(options.query); } else { query = queryStringify({ api_key: self.apiKey }); } var httpOptions = { httpService: this.httpService, request: { host: API_HOSTNAME, path: API_BASE_PATH + options.api + endpoint + query }, timeout: this.timeout, fmt: options.query && options.query.fmt, https: this.https }; var makeRequest = function (resolve, reject) { httpService.get(httpOptions, resolve, reject); }; if (callback) { var resolve = function (res) { callback(null, res); }; var reject = function (err) { callback(err); }; makeRequest(resolve, reject); } else { if (!promisesExist) { throw new Error('Callback must be provided unless Promises are available'); } return new Promise(function (resolve, reject) { makeRequest(resolve, reject); }); } }
javascript
{ "resource": "" }
q52572
spawnPlayer
train
function spawnPlayer (src, out, loop, initialVolume, showOsd) { let args = buildArgs(src, out, loop, initialVolume, showOsd); console.log('args for omxplayer:', args); let omxProcess = spawn('omxplayer', args); open = true; omxProcess.stdin.setEncoding('utf-8'); omxProcess.on('close', updateStatus); omxProcess.on('error', () => { emitError('Problem running omxplayer, is it installed?.'); }); return omxProcess; }
javascript
{ "resource": "" }
q52573
BlinkStick
train
function BlinkStick (device, serialNumber, manufacturer, product) { if (isWin) { if (device) { this.device = new usb.HID(device); this.serial = serialNumber; this.manufacturer = manufacturer; this.product = product; } } else { if (device) { device.open (); this.device = device; } } this.inverse = false; this.animationsEnabled = true; var self = this; this.getSerial(function (err, result) { if (typeof(err) === 'undefined') { self.requiresSoftwareColorPatch = self.getVersionMajor() == 1 && self.getVersionMinor() >= 1 && self.getVersionMinor() <= 3; } }); }
javascript
{ "resource": "" }
q52574
_determineReportId
train
function _determineReportId(ledCount) { var reportId = 9; var maxLeds = 64; if (ledCount < 8 * 3) { reportId = 6; maxLeds = 8; } else if (ledCount < 16 * 3) { reportId = 7; maxLeds = 16; } else if (ledCount < 32 * 3) { reportId = 8; maxLeds = 32; } return { 'reportId': reportId, 'maxLeds': maxLeds }; }
javascript
{ "resource": "" }
q52575
getInfoBlock
train
function getInfoBlock (device, location, callback) { getFeatureReport(location, 33, function (err, buffer) { if (typeof(err) !== 'undefined') { callback(err); return; } var result = '', i, l; for (i = 1, l = buffer.length; i < l; i++) { if (i === 0) break; result += String.fromCharCode(buffer[i]); } callback(err, result); }); }
javascript
{ "resource": "" }
q52576
opt
train
function opt(options, name, defaultValue){ return options && options[name]!==undefined ? options[name] : defaultValue; }
javascript
{ "resource": "" }
q52577
setInfoBlock
train
function setInfoBlock (device, location, data, callback) { var i, l = Math.min(data.length, 33), buffer = new Buffer(33); buffer[0] = 0; for (i = 0; i < l; i++) buffer[i + 1] = data.charCodeAt(i); for (i = l; i < 33; i++) buffer[i + 1] = 0; setFeatureReport(location, buffer, callback); }
javascript
{ "resource": "" }
q52578
findBlinkSticks
train
function findBlinkSticks (filter) { if (filter === undefined) filter = function () { return true; }; var result = [], device, i, devices; if (isWin) { devices = usb.devices(); for (i in devices) { device = devices[i]; if (device.vendorId === VENDOR_ID && device.productId === PRODUCT_ID && filter(device)) { result.push(new BlinkStick(device.path, device.serialNumber, device.manufacturer, device.product)); } } } else { devices = usb.getDeviceList(); for (i in devices) { device = devices[i]; if (device.deviceDescriptor.idVendor === VENDOR_ID && device.deviceDescriptor.idProduct === PRODUCT_ID && filter(device)) result.push(new BlinkStick(device)); } } return result; }
javascript
{ "resource": "" }
q52579
train
function () { if (isWin) { var devices = findBlinkSticks(); return devices.length > 0 ? devices[0] : null; } else { var device = usb.findByIds(VENDOR_ID, PRODUCT_ID); if (device) return new BlinkStick(device); } }
javascript
{ "resource": "" }
q52580
train
function (callback) { var result = []; var devices = findBlinkSticks(); var i = 0; var finder = function() { if (i == devices.length) { if (callback) callback(result); } else { devices[i].getSerial(function (err, serial) { result.push(serial); i += 1; finder(); }); } }; finder(); }
javascript
{ "resource": "" }
q52581
train
function (serial, callback) { var result = []; var devices = findBlinkSticks(); var i = 0; var finder = function() { if (i == devices.length) { if (callback) callback(); } else { devices[i].getSerial(function (err, serialNumber) { if (serialNumber == serial) { if (callback) callback(devices[i]); } else { i += 1; finder(); } }); } }; finder(); }
javascript
{ "resource": "" }
q52582
getAllChildSpans
train
function getAllChildSpans(node) { return ( Array.isArray(node.children) ? node.children .map(n => (n.spans || []).concat(getAllChildSpans(n))) .reduce((all, arr) => all.concat(arr)) : [] ); }
javascript
{ "resource": "" }
q52583
compileJavascript
train
function compileJavascript(filePath) { const jsPath = filePath || 'src'; const babelPath = which.sync('babel'); const outFile = jsPath.endsWith('.js') ? `--out-file ${jsPath.replace('src/', 'dist/')}` : `-d dist`; console.log(chalk.cyan(`compling javascript ${chalk.magenta(jsPath)}`)); cp.execSync(`${babelPath} ${jsPath} ${outFile} --ignore test.js`, execArgs); console.log(chalk.green('babel compilation complete')); }
javascript
{ "resource": "" }
q52584
compileLess
train
function compileLess() { console.log(chalk.cyan(`compiling ${chalk.magenta('src/less/hierplane.less')}`)); cp.execSync(`${which.sync('lessc')} --clean-css --autoprefix="last 2 versions" src/less/hierplane.less dist/static/hierplane.min.css`); console.log(chalk.green(`wrote ${chalk.magenta('dist/static/hierplane.min.css')}`)); }
javascript
{ "resource": "" }
q52585
bundleJavascript
train
function bundleJavascript() { const bundleEntryPath = path.resolve(__dirname, '..', 'dist', 'static', 'hierplane.js'); const bundlePath = path.resolve(__dirname, '..', 'dist', 'static', 'hierplane.bundle.js'); // Put together our "bundler", which uses browserify const browserifyOpts = { entries: [ bundleEntryPath ], standalone: 'hierplane' }; // If we're watching or changes, enable watchify if (isWatchTarget) { // These are required for watchify browserifyOpts.packageCache = {}; browserifyOpts.cache = {}; // Enable the plugin browserifyOpts.plugin = [ watchify ]; }; // Construct the bundler const bundler = browserify(browserifyOpts); // Make an inline function which writes out the bundle, so that we can invoke it whenever // an update is detected if the watch target is being executed. const writeBundle = () => { console.log(chalk.cyan(`bundling ${chalk.magenta(path.relative(execArgs.cwd, bundleEntryPath))}`)); bundler.bundle().pipe(fs.createWriteStream(bundlePath)) console.log(chalk.green(`wrote ${chalk.magenta(path.relative(execArgs.cwd, bundlePath))}`)); }; // Write out the bundle once writeBundle(); // If we're supposed to watch for changes, write out the bundle whenever they occur if (isWatchTarget) { bundler.on('update', writeBundle); } }
javascript
{ "resource": "" }
q52586
iterator
train
function iterator(since) { if (stop) { return; } var attr = []; attr.push({ key: 'since', val: since }); attr.push({ key: 'events', val: events }); req({ method: 'events', endpoint: false, attr: attr }).then(function (eventArr) { //Check for event count on first request iteration if (since != 0) { eventArr.forEach(function (e) { _this.emit(lowerCaseFirst(e.type), e.data); }); } //Update event count if (eventArr.length > 0) { since = eventArr[eventArr.length - 1].id; } //Reset tries tries = 0; setTimeout(function () { return iterator(since); }, 100); }).catch(function (err) { _this.emit('error', err); //Try to regain connection & reset event counter if (tries < retries) { tries++; setTimeout(function () { return iterator(0); }, 500); } }); }
javascript
{ "resource": "" }
q52587
handleReq
train
function handleReq(config) { var authCheck = csrfTokenCheck(); return function (options, callback) { if (callback) { authCheck({ config: config, options: options, callback: callback }); } else { return new Promise(function (resolve, reject) { authCheck({ config: config, options: options, callback: function callback(err, res) { return err ? reject(err) : resolve(res); } }); }); } }; }
javascript
{ "resource": "" }
q52588
Parser
train
function Parser(config) { if (!(this instanceof Parser)) return new Parser(config); this.config = config; this.config.on('read', function read(type) { this[type](); }.bind(this)); }
javascript
{ "resource": "" }
q52589
Orchestrator
train
function Orchestrator(options) { if (!(this instanceof Orchestrator)) return new Orchestrator(options); options = options || {}; this.which = options.which || require('which').sync('haproxy'); this.pid = options.pid || ''; this.pidFile = options.pidFile || ''; this.config = options.config; this.discover = options.discover || false; this.prefix = options.prefix || ''; // // Discover a running process. // if (this.discover && !this.pid) this.read(); }
javascript
{ "resource": "" }
q52590
property
train
function property(fn, arg) { var base = [ section, name ]; return { writable: false, enumerable: false, value: function () { if (arg) base.push(arg); return fn.apply(self, base.concat( Array.prototype.slice.apply(arguments) )); } }; }
javascript
{ "resource": "" }
q52591
HAProxy
train
function HAProxy(socket, options) { if (!(this instanceof HAProxy)) return new HAProxy(socket, options); options = options || {}; // // Allow variable arguments, with socket path or just custom options. // if ('object' === typeof socket) { options = socket; socket = options.socket || null; } this.socket = socket || '/tmp/haproxy.sock'; // Path to socket this.cfg = options.config || '/etc/haproxy/haproxy.cfg'; // Config location // // Create a new `haproxy` orchestrator which interacts with the binary. // this.orchestrator = new Orchestrator({ discover: options.discover, pidFile: options.pidFile, prefix: options.prefix, which: options.which, pid: options.pid, config: this.cfg }); }
javascript
{ "resource": "" }
q52592
SimpleThumbnailGenerator
train
function SimpleThumbnailGenerator(options, generatorOptions) { options = options || {}; generatorOptions = generatorOptions || {}; if (!options.manifestFileName) { throw new Error("manifestFileName required."); } if (typeof(options.logger) === "undefined") { this._logger = Logger.get('SimpleThumbnailGenerator'); } else { if (options.logger === null) { this._logger = nullLogger; } else { this._logger = options.logger; } } this._generatorOptions = generatorOptions; this._manifestFileName = options.manifestFileName; this._expireTime = options.expireTime || 0; this._segmentRemovalTimes = { // the sn of the first fragment in the array offset: null, // the times when the corresponding fragments were removed times: [] }; // {sn, thumbnails, removalTime} // thumbnails is array of {time, name} this._segments = []; this._playlistRemoved = false; this._playlistEnded = false; this._generator = new ThumbnailGenerator(Object.assign({}, generatorOptions, { // if the user doesn't provide a temp directory get a general one tempDir: generatorOptions.tempDir || utils.getTempDir() })); this._gcTimerId = setInterval(this._gc.bind(this), 30000); this._emitter = ee({}); this._registerGeneratorListeners(); this._updateManifest(); }
javascript
{ "resource": "" }
q52593
train
function(newTempo) { clock.timeStretch(context.currentTime, [freqEvent1, freqEvent2], currentTempo / newTempo) currentTempo = newTempo }
javascript
{ "resource": "" }
q52594
train
function(track, beatInd) { var event = clock.callbackAtTime(function(event) { var bufferNode = soundBank[track].createNode() bufferNode.start(event.deadline) }, nextBeatTime(beatInd)) event.repeat(barDur) event.tolerance({late: 0.01}) beats[track][beatInd] = event }
javascript
{ "resource": "" }
q52595
train
function(track) { var request = new XMLHttpRequest() request.open('GET', 'sounds/' + track + '.wav', true) request.responseType = 'arraybuffer' request.onload = function() { context.decodeAudioData(request.response, function(buffer) { var createNode = function() { var node = context.createBufferSource() node.buffer = buffer node.connect(context.destination) return node } soundBank[track] = { createNode: createNode } }) } request.send() }
javascript
{ "resource": "" }
q52596
moveImports
train
function moveImports(code, imports) { return code.replace(RE_IMPORTS, function (_, indent, imprt) { imprt = imprt.trim(); if (imprt.slice(-1) !== ';') { imprt += ';'; } imports.push(imprt); return indent; // keep only the indentation }); }
javascript
{ "resource": "" }
q52597
clonePugOpts
train
function clonePugOpts(opts, filename) { return PUGPROPS.reduce((o, p) => { if (p in opts) { o[p] = clone(opts[p]); } return o; }, { filename }); }
javascript
{ "resource": "" }
q52598
generateData
train
function generateData() { var firstDate = new Date(); var dataProvider = []; for (var i = 0; i < 100; ++i) { var date = new Date(firstDate.getTime()); date.setDate(i); dataProvider.push({ date: date, value: Math.floor(Math.random() * 100) }); } return dataProvider; }
javascript
{ "resource": "" }
q52599
train
function(array) { this.destination = this.parse(array) // normalize length of arrays if (this.value.length != this.destination.length) { var lastValue = this.value[this.value.length - 1] , lastDestination = this.destination[this.destination.length - 1] while(this.value.length > this.destination.length) this.destination.push(lastDestination) while(this.value.length < this.destination.length) this.value.push(lastValue) } return this }
javascript
{ "resource": "" }