_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q8200
train
function( options, callback ) { var self = this var url = '/ratings/rest/v1/json/flight/' + options.carrier + '/' + options.flightNumber var extensions = [] if( Array.isArray( options.extendedOptions ) ) { extensions = extensions.concat( options.extendedOptions ) } return this._clientRequest({ url: url, extendedOptions: extensions, qs: { departureAirport: options.departureAirport, codeType: options.codeType, } }, function( error, data ) { callback.call( self, error, data ) }) }
javascript
{ "resource": "" }
q8201
train
function( options, callback ) { debug( 'route', options ) var self = this var year = options.date.getFullYear() var month = options.date.getMonth() + 1 var day = options.date.getDate() var direction = /^dep/i.test( options.direction ) ? 'dep' : 'arr' var url = 'flightstatus/rest/v2/json/route/status/' + options.departureAirport + '/' + options.arrivalAirport + '/' + direction + '/' + year + '/' + month + '/' + day var extensions = [ 'useInlinedReferences' ] if( Array.isArray( options.extendedOptions ) ) { extensions = extensions.concat( options.extendedOptions ) } return this._clientRequest({ url: url, extendedOptions: extensions, qs: { maxFlights: options.maxFlights, codeType: options.codeType, numHours: options.numHours, utc: options.utc, hourOfDay: options.hourOfDay, } }, function( error, data ) { callback.call( self, error, data ) }) }
javascript
{ "resource": "" }
q8202
randomId
train
function randomId () { const res = new Array(32) const alphabet = 'ABCDEF0123456789' for (let i = 0; i < 32; i++) { res[i] = alphabet[Math.floor(Math.random() * 16)] } return res.join('') }
javascript
{ "resource": "" }
q8203
signIn
train
function signIn (selection) { return dom.create('div').class('sign-in') .add(dom.create('input').class('username-input')) .add(dom.create('input').class('password-input')) .add(dom.create('button').class('sign-in-button').text('Sign in')) }
javascript
{ "resource": "" }
q8204
isEntity
train
function isEntity (d) { return isText(d.type) && Array.isArray(d.params) && Array.isArray(d.content) }
javascript
{ "resource": "" }
q8205
inspect
train
function inspect(stringsOrOpts, ...values) { if (Array.isArray(stringsOrOpts)) { return DEFAULT_INSPECT(stringsOrOpts, ...values); } return inspector(stringsOrOpts); }
javascript
{ "resource": "" }
q8206
noisyRule
train
function noisyRule(context, parser, onError) { parser.on('startTag', (name, attrs, selfClosing, location) => { onError({ rule: name, message: getAttribute(attrs, 'message') || '', location, }); }); }
javascript
{ "resource": "" }
q8207
execute
train
function execute(argv) { const opts = Options.parse(argv); if (opts.version) { /* eslint-disable global-require */ console.log(`v${ require('../package.json').version }`); return Promise.resolve(0); } if (opts.help || !opts._.length) { console.log(Options.generateHelp()); return Promise.resolve(0); } return lint(resolvePatterns(opts), opts); }
javascript
{ "resource": "" }
q8208
compareAscending
train
function compareAscending(a, b) { var ai = a.index, bi = b.index; a = a.criteria; b = b.criteria; // ensure a stable sort in V8 and other engines // http://code.google.com/p/v8/issues/detail?id=90 if (a !== b) { if (a > b || typeof a == 'undefined') { return 1; } if (a < b || typeof b == 'undefined') { return -1; } } return ai < bi ? -1 : 1; }
javascript
{ "resource": "" }
q8209
createBound
train
function createBound(func, thisArg, partialArgs, indicator) { var isFunc = isFunction(func), isPartial = !partialArgs, key = thisArg; // juggle arguments if (isPartial) { var rightIndicator = indicator; partialArgs = thisArg; } else if (!isFunc) { if (!indicator) { throw new TypeError; } thisArg = func; } function bound() { // `Function#bind` spec // http://es5.github.com/#x15.3.4.5 var args = arguments, thisBinding = isPartial ? this : thisArg; if (!isFunc) { func = thisArg[key]; } if (partialArgs.length) { args = args.length ? (args = nativeSlice.call(args), rightIndicator ? args.concat(partialArgs) : partialArgs.concat(args)) : partialArgs; } if (this instanceof bound) { // ensure `new bound` is an instance of `func` noop.prototype = func.prototype; thisBinding = new noop; noop.prototype = null; // mimic the constructor's `return` behavior // http://es5.github.com/#x13.2.2 var result = func.apply(thisBinding, args); return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); } return bound; }
javascript
{ "resource": "" }
q8210
findKey
train
function findKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg); forOwn(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; }
javascript
{ "resource": "" }
q8211
reduceRight
train
function reduceRight(collection, callback, accumulator, thisArg) { var iterable = collection, length = collection ? collection.length : 0, noaccum = arguments.length < 3; if (typeof length != 'number') { var props = keys(collection); length = props.length; } callback = lodash.createCallback(callback, thisArg, 4); forEach(collection, function(value, index, collection) { index = props ? props[--length] : --length; accumulator = noaccum ? (noaccum = false, iterable[index]) : callback(accumulator, iterable[index], index, collection); }); return accumulator; }
javascript
{ "resource": "" }
q8212
findIndex
train
function findIndex(array, callback, thisArg) { var index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg); while (++index < length) { if (callback(array[index], index, array)) { return index; } } return -1; }
javascript
{ "resource": "" }
q8213
unzip
train
function unzip(array) { var index = -1, length = array ? array.length : 0, tupleLength = length ? max(pluck(array, 'length')) : 0, result = Array(tupleLength); while (++index < length) { var tupleIndex = -1, tuple = array[index]; while (++tupleIndex < tupleLength) { (result[tupleIndex] || (result[tupleIndex] = Array(length)))[index] = tuple[tupleIndex]; } } return result; }
javascript
{ "resource": "" }
q8214
bind
train
function bind(func, thisArg) { // use `Function#bind` if it exists and is fast // (in V8 `Function#bind` is slower except when partially applied) return support.fastBind || (nativeBind && arguments.length > 2) ? nativeBind.call.apply(nativeBind, arguments) : createBound(func, thisArg, nativeSlice.call(arguments, 2)); }
javascript
{ "resource": "" }
q8215
bindAll
train
function bindAll(object) { var funcs = arguments.length > 1 ? concat.apply(arrayRef, nativeSlice.call(arguments, 1)) : functions(object), index = -1, length = funcs.length; while (++index < length) { var key = funcs[index]; object[key] = bind(object[key], object); } return object; }
javascript
{ "resource": "" }
q8216
defer
train
function defer(func) { var args = nativeSlice.call(arguments, 1); return setTimeout(function() { func.apply(undefined, args); }, 1); }
javascript
{ "resource": "" }
q8217
memoize
train
function memoize(func, resolver) { var cache = {}; return function() { var key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]); return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); }; }
javascript
{ "resource": "" }
q8218
wrap
train
function wrap(value, wrapper) { return function() { var args = [value]; push.apply(args, arguments); return wrapper.apply(this, args); }; }
javascript
{ "resource": "" }
q8219
train
function( obj ) { _each( slice.call( arguments, 1), function( source ) { var prop; for ( prop in source ) { if ( source[prop] !== void 0 ) { obj[ prop ] = source[ prop ]; } } }); return obj; }
javascript
{ "resource": "" }
q8220
string_starts_with
train
function string_starts_with(str, what) { return (str.substr(0, what.length) === what) ? true : false; }
javascript
{ "resource": "" }
q8221
create_constructor
train
function create_constructor(type_name) { if(Object.prototype.hasOwnProperty.call(constructors, type_name)) { return constructors[type_name]; } if(!( Object.prototype.hasOwnProperty.call(_schema.definitions, type_name) && is.def(_schema.definitions[type_name]) )) { throw new TypeError("No definition for " + type_name); } var definition = _schema.definitions[type_name]; // ParentType is either SchemaObject or another definition var ParentType = SchemaObject; if( is.obj(definition) && is.def(definition.$ref) && string_starts_with(definition.$ref, '#/definitions/') ) { ParentType = create_constructor( definition.$ref.split('/').slice(2).join('/') ); } // FIXME: If a type has $refs, we should create a copy of schema which defines all those $refs. // Currently just copies schema and changes it to point our definition. Not ideal solution. var copy_definition = JSON.parse(JSON.stringify(_schema)); copy_definition.oneOf = [{"$ref": '#/definitions/'+type_name }]; /* This is our real constructor which will be called in `new Function()` */ function _constructor(self, opts) { var tmp; // Check opts validity var validity = SchemaObject.validate(opts, copy_definition); if(!validity.valid) { throw new TypeError("bad argument: " + util.inspect(validity) ); } // Call parent constructors ParentType.call(self, opts); // Call custom constructors //util.debug( util.inspect( _user_defined_constructors )); if(Object.prototype.hasOwnProperty.call(_user_defined_constructors, type_name)) { tmp = _user_defined_constructors[type_name].call(self, opts); if(is.def(tmp)) { SchemaObject.prototype._setValueOf.call(self, tmp); } //util.debug( util.inspect( tmp ) ); } // Setup getters and setters if schema has properties //util.debug( "\ndefinition = \n----\n" + util.inspect( definition ) + "\n----\n\n" ); if(definition && definition.properties) { Object.getOwnPropertyNames(definition.properties).forEach(function(key) { self.__defineGetter__(key, function(){ return self.valueOf()[key]; }); self.__defineSetter__(key, function(val){ // FIXME: Implement value validation and do not use `.valueOf()`! self.valueOf()[key] = val; }); }); } } var func_name = escape_func_name(type_name); // JavaScript does not support better way to change function names... var code = [ 'function '+func_name+' (opts) {', ' if(!(this instanceof '+func_name+')) {', ' return new '+func_name+'(opts);', ' };', ' _constructor.call(this, this, opts);', '};' ]; var Type = (new Function('_constructor', 'return '+code.join('\n')))(_constructor); util.inherits(Type, ParentType); /* Returns source code for type */ //Type.toSource = function() { // return '(new Function(\'' + [''+_constructor, ''+Type].join('\n') + '))();'; //}; constructors[type_name] = Type; // User-defined methods function post_user_defines(context) { if(Object.prototype.hasOwnProperty.call(_user_defined_methods, type_name)) { _user_defined_methods[type_name].call(context, Type, context); } } post_user_defines({'constructors':constructors, 'schema':_schema}); return constructors[type_name]; }
javascript
{ "resource": "" }
q8222
post_user_defines
train
function post_user_defines(context) { if(Object.prototype.hasOwnProperty.call(_user_defined_methods, type_name)) { _user_defined_methods[type_name].call(context, Type, context); } }
javascript
{ "resource": "" }
q8223
setEnabledSources
train
function setEnabledSources(config) { for (let source in config) { setSourceEnabled(source, config[source]); } haveSourcesBeenSelected = true; }
javascript
{ "resource": "" }
q8224
convertParamValues
train
function convertParamValues(parsedSql, values) { var ret = []; _.each(parsedSql.params, function(param) { if( !_.has(values, param.name) ) { throw new Error("No value found for parameter: " + param.name); } ret.push(values[param.name]); }); return ret; }
javascript
{ "resource": "" }
q8225
train
function(links) { this.dependencies = _buildDependencies(links); this.tasks = graph.tsort(this.dependencies).reverse(); this.index = 0; }
javascript
{ "resource": "" }
q8226
train
function (tagName, tagAttributes) { if (this._done) { return; } this._openElementStack.push(tagName); try { this._errorIfUnexpectedTag(tagName); for (var attributeName in tagAttributes) { var attributeValue = tagAttributes[attributeName]; this._errorIfUnexpectedAttribute(tagName, attributeName); this._errorIfUnexpectedAttributeValue(tagName, attributeName, attributeValue); } } catch (err) { this._finish(err); } }
javascript
{ "resource": "" }
q8227
LRUItem
train
function LRUItem(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; }
javascript
{ "resource": "" }
q8228
ScriptError
train
function ScriptError(code, op, ip) { if (!(this instanceof ScriptError)) return new ScriptError(code, op, ip); Error.call(this); this.type = 'ScriptError'; this.code = code; this.message = code; this.op = -1; this.ip = -1; if (typeof op === 'string') { this.message = op; } else if (op) { this.message = `${code} (op=${op.toSymbol()}, ip=${ip})`; this.op = op.value; this.ip = ip; } if (Error.captureStackTrace) Error.captureStackTrace(this, ScriptError); }
javascript
{ "resource": "" }
q8229
Network
train
function Network(options) { if (!(this instanceof Network)) return new Network(options); assert(!Network[options.type], 'Cannot create two networks.'); this.type = options.type; this.seeds = options.seeds; this.magic = options.magic; this.port = options.port; this.checkpointMap = options.checkpointMap; this.lastCheckpoint = options.lastCheckpoint; this.checkpoints = []; this.halvingInterval = options.halvingInterval; this.genesis = options.genesis; this.genesisBlock = options.genesisBlock; this.pow = options.pow; this.block = options.block; this.bip30 = options.bip30; this.activationThreshold = options.activationThreshold; this.minerWindow = options.minerWindow; this.deployments = options.deployments; this.deploys = options.deploys; this.unknownBits = ~consensus.VERSION_TOP_MASK; this.keyPrefix = options.keyPrefix; this.addressPrefix = options.addressPrefix; this.requireStandard = options.requireStandard; this.rpcPort = options.rpcPort; this.minRelay = options.minRelay; this.feeRate = options.feeRate; this.maxFeeRate = options.maxFeeRate; this.selfConnect = options.selfConnect; this.requestMempool = options.requestMempool; this.time = new TimeData(); this._init(); }
javascript
{ "resource": "" }
q8230
overwriteKeys
train
function overwriteKeys(baseObject, overrideObject, createNew) { if (!baseObject) { baseObject = {}; } if (createNew) { baseObject = JSON.parse(JSON.stringify(baseObject)); } Object.keys(overrideObject).forEach(function(key) { if (isObjectAndNotArray(baseObject[key]) && isObjectAndNotArray(overrideObject[key])) { overwriteKeys(baseObject[key], overrideObject[key]); } else { baseObject[key] = overrideObject[key]; } }); return baseObject; }
javascript
{ "resource": "" }
q8231
ShouldPlayerStand
train
function ShouldPlayerStand(playerCards, dealerCard, handValue, handCount, options) { var shouldStand = false; if (handValue.soft) { // Don't stand until you hit 18 if (handValue.total > 18) { shouldStand = true; } else if (handValue.total == 18) { // Stand against dealer 2-8, and against a dealer Ace in single deck if they dealer will stand on soft 17 shouldStand = ((dealerCard >= 2) && (dealerCard <= 8)) || ((dealerCard == 1) && (options.numberOfDecks == 1) && !options.hitSoft17); } } else { // Stand on 17 or above if (handValue.total > 16) { shouldStand = true; } else if (handValue.total > 12) { // 13-16 you should stand against dealer 2-6 shouldStand = (dealerCard >= 2) && (dealerCard <= 6); } else if (handValue.total == 12) { // Stand on dealer 4-6 shouldStand = (dealerCard >= 4) && (dealerCard <= 6); } // Advanced option - in single deck a pair of 7s should stand against a dealer 10 if ((options.strategyComplexity != "simple") && (handValue.total == 14) && (playerCards[0] == 7) && (dealerCard == 10) && (options.numberOfDecks == 1)) { shouldStand = true; } } return shouldStand; }
javascript
{ "resource": "" }
q8232
Pool
train
function Pool(options) { if (!(this instanceof Pool)) return new Pool(options); AsyncObject.call(this); this.options = new PoolOptions(options); this.network = this.options.network; this.logger = this.options.logger.context('net'); this.chain = this.options.chain; this.mempool = this.options.mempool; this.server = this.options.createServer(); this.nonces = this.options.nonces; this.locker = new Lock(true); this.connected = false; this.disconnecting = false; this.syncing = false; this.spvFilter = null; this.txFilter = null; this.blockMap = new Set(); this.txMap = new Set(); this.compactBlocks = new Set(); this.invMap = new Map(); this.pendingFilter = null; this.pendingRefill = null; this.checkpoints = false; this.headerChain = new List(); this.headerNext = null; this.headerTip = null; this.peers = new PeerList(); this.authdb = new BIP150.AuthDB(this.options); this.hosts = new HostList(this.options); this.id = 0; if (this.options.spv) this.spvFilter = Bloom.fromRate(20000, 0.001, Bloom.flags.ALL); if (!this.options.mempool) this.txFilter = new RollingFilter(50000, 0.000001); this._init(); }
javascript
{ "resource": "" }
q8233
TXMeta
train
function TXMeta(options) { if (!(this instanceof TXMeta)) return new TXMeta(options); this.tx = new TX(); this.mtime = util.now(); this.height = -1; this.block = null; this.time = 0; this.index = -1; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8234
PaymentACK
train
function PaymentACK(options) { if (!(this instanceof PaymentACK)) return new PaymentACK(options); this.payment = new Payment(); this.memo = null; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8235
hash256
train
function hash256(data) { const out = Buffer.allocUnsafe(32); ctx.init(); ctx.update(data); ctx._finish(out); ctx.init(); ctx.update(out); ctx._finish(out); return out; }
javascript
{ "resource": "" }
q8236
hmac
train
function hmac(data, key) { mctx.init(key); mctx.update(data); return mctx.finish(); }
javascript
{ "resource": "" }
q8237
polymod
train
function polymod(pre) { const b = pre >>> 25; return ((pre & 0x1ffffff) << 5) ^ (-((b >> 0) & 1) & 0x3b6a57b2) ^ (-((b >> 1) & 1) & 0x26508e6d) ^ (-((b >> 2) & 1) & 0x1ea119fa) ^ (-((b >> 3) & 1) & 0x3d4233dd) ^ (-((b >> 4) & 1) & 0x2a1462b3); }
javascript
{ "resource": "" }
q8238
serialize
train
function serialize(hrp, data) { let chk = 1; let i; for (i = 0; i < hrp.length; i++) { const ch = hrp.charCodeAt(i); if ((ch >> 5) === 0) throw new Error('Invalid bech32 character.'); chk = polymod(chk) ^ (ch >> 5); } if (i + 7 + data.length > 90) throw new Error('Invalid bech32 data length.'); chk = polymod(chk); let str = ''; for (let i = 0; i < hrp.length; i++) { const ch = hrp.charCodeAt(i); chk = polymod(chk) ^ (ch & 0x1f); str += hrp[i]; } str += '1'; for (let i = 0; i < data.length; i++) { const ch = data[i]; if ((ch >> 5) !== 0) throw new Error('Invalid bech32 value.'); chk = polymod(chk) ^ ch; str += CHARSET[ch]; } for (let i = 0; i < 6; i++) chk = polymod(chk); chk ^= 1; for (let i = 0; i < 6; i++) str += CHARSET[(chk >>> ((5 - i) * 5)) & 0x1f]; return str; }
javascript
{ "resource": "" }
q8239
deserialize
train
function deserialize(str) { let dlen = 0; if (str.length < 8 || str.length > 90) throw new Error('Invalid bech32 string length.'); while (dlen < str.length && str[(str.length - 1) - dlen] !== '1') dlen++; const hlen = str.length - (1 + dlen); if (hlen < 1 || dlen < 6) throw new Error('Invalid bech32 data length.'); dlen -= 6; const data = Buffer.allocUnsafe(dlen); let chk = 1; let lower = false; let upper = false; let hrp = ''; for (let i = 0; i < hlen; i++) { let ch = str.charCodeAt(i); if (ch < 0x21 || ch > 0x7e) throw new Error('Invalid bech32 character.'); if (ch >= 0x61 && ch <= 0x7a) { lower = true; } else if (ch >= 0x41 && ch <= 0x5a) { upper = true; ch = (ch - 0x41) + 0x61; } hrp += String.fromCharCode(ch); chk = polymod(chk) ^ (ch >> 5); } chk = polymod(chk); let i; for (i = 0; i < hlen; i++) chk = polymod(chk) ^ (str.charCodeAt(i) & 0x1f); i++; while (i < str.length) { const ch = str.charCodeAt(i); const v = (ch & 0x80) ? -1 : TABLE[ch]; if (ch >= 0x61 && ch <= 0x7a) lower = true; else if (ch >= 0x41 && ch <= 0x5a) upper = true; if (v === -1) throw new Error('Invalid bech32 character.'); chk = polymod(chk) ^ v; if (i + 6 < str.length) data[i - (1 + hlen)] = v; i++; } if (lower && upper) throw new Error('Invalid bech32 casing.'); if (chk !== 1) throw new Error('Invalid bech32 checksum.'); return [hrp, data.slice(0, dlen)]; }
javascript
{ "resource": "" }
q8240
convert
train
function convert(data, output, frombits, tobits, pad, off) { const maxv = (1 << tobits) - 1; let acc = 0; let bits = 0; let j = 0; if (pad !== -1) output[j++] = pad; for (let i = off; i < data.length; i++) { const value = data[i]; if ((value >> frombits) !== 0) throw new Error('Invalid bech32 bits.'); acc = (acc << frombits) | value; bits += frombits; while (bits >= tobits) { bits -= tobits; output[j++] = (acc >>> bits) & maxv; } } if (pad !== -1) { if (bits > 0) output[j++] = (acc << (tobits - bits)) & maxv; } else { if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) throw new Error('Invalid bech32 bits.'); } return output.slice(0, j); }
javascript
{ "resource": "" }
q8241
encode
train
function encode(hrp, version, hash) { const output = POOL65; if (version < 0 || version > 16) throw new Error('Invalid bech32 version.'); if (hash.length < 2 || hash.length > 40) throw new Error('Invalid bech32 data length.'); const data = convert(hash, output, 8, 5, version, 0); return serialize(hrp, data); }
javascript
{ "resource": "" }
q8242
decode
train
function decode(str) { const [hrp, data] = deserialize(str); if (data.length === 0 || data.length > 65) throw new Error('Invalid bech32 data length.'); if (data[0] > 16) throw new Error('Invalid bech32 version.'); const version = data[0]; const output = data; const hash = convert(data, output, 5, 8, -1, 1); if (hash.length < 2 || hash.length > 40) throw new Error('Invalid bech32 data length.'); return new AddrResult(hrp, version, hash); }
javascript
{ "resource": "" }
q8243
NetAddress
train
function NetAddress(options) { if (!(this instanceof NetAddress)) return new NetAddress(options); this.host = '0.0.0.0'; this.port = 0; this.services = 0; this.time = 0; this.hostname = '0.0.0.0:0'; this.raw = IP.ZERO_IP; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8244
train
function(err, commandName, config, resultFunction) { //max Number in javascript is 9,007,199,254,740,992. At 10,000 requests per second, that is 28,561 years until we get an overflow on messageId messageId += 1; messageStack[messageId] = resultFunction; //tell the parent process to run the command process.send({id: messageId, err: err, commandName: commandName, config: config}); }
javascript
{ "resource": "" }
q8245
murmur3
train
function murmur3(data, seed) { const tail = data.length - (data.length % 4); const c1 = 0xcc9e2d51; const c2 = 0x1b873593; let h1 = seed; let k1; for (let i = 0; i < tail; i += 4) { k1 = (data[i + 3] << 24) | (data[i + 2] << 16) | (data[i + 1] << 8) | data[i]; k1 = mul32(k1, c1); k1 = rotl32(k1, 15); k1 = mul32(k1, c2); h1 ^= k1; h1 = rotl32(h1, 13); h1 = sum32(mul32(h1, 5), 0xe6546b64); } k1 = 0; switch (data.length & 3) { case 3: k1 ^= data[tail + 2] << 16; case 2: k1 ^= data[tail + 1] << 8; case 1: k1 ^= data[tail + 0]; k1 = mul32(k1, c1); k1 = rotl32(k1, 15); k1 = mul32(k1, c2); h1 ^= k1; } h1 ^= data.length; h1 ^= h1 >>> 16; h1 = mul32(h1, 0x85ebca6b); h1 ^= h1 >>> 13; h1 = mul32(h1, 0xc2b2ae35); h1 ^= h1 >>> 16; if (h1 < 0) h1 += 0x100000000; return h1; }
javascript
{ "resource": "" }
q8246
Chain
train
function Chain(options) { if (!(this instanceof Chain)) return new Chain(options); AsyncObject.call(this); this.options = new ChainOptions(options); this.network = this.options.network; this.logger = this.options.logger.context('chain'); this.workers = this.options.workers; this.db = new ChainDB(this.options); this.locker = new Lock(true); this.invalid = new LRU(100); this.state = new DeploymentState(); this.tip = new ChainEntry(); this.height = -1; this.synced = false; this.orphanMap = new Map(); this.orphanPrev = new Map(); this.subscribers = {}; this.subscribeJobs = {}; this._subscribes = { cmds: [], cp: null }; this._notifies = { cmds: [], cp: null }; }
javascript
{ "resource": "" }
q8247
DeploymentState
train
function DeploymentState() { if (!(this instanceof DeploymentState)) return new DeploymentState(); this.flags = Script.flags.MANDATORY_VERIFY_FLAGS; this.flags &= ~Script.flags.VERIFY_P2SH; this.lockFlags = common.lockFlags.MANDATORY_LOCKTIME_FLAGS; this.bip34 = false; this.bip91 = false; this.bip148 = false; }
javascript
{ "resource": "" }
q8248
createVirtualLessFileFromBowerJson
train
function createVirtualLessFileFromBowerJson(bowerJsonPath) { return new PromiseConstructor(function(fullfill, reject) { bowerJson.read(bowerJsonPath, { validate: false }, function(err, bowerJsonData) { if (err) { return reject(err); } if (!bowerJsonData.main) { err = bowerJsonPath + ' has no "main" property.'; return reject(new Error(err)); } // convert bower json into less file var virtualLessFile = bowerJsonData.main.filter(function(filename) { return path.extname(filename) === '.less'; }).map(function(filename) { return '@import "' + filename + '";'; }).join('\n'); if (virtualLessFile) { var file = { contents: virtualLessFile, filename: bowerJsonPath }; return fullfill(file); } else { err = 'Couldn\'t find a less file in ' + bowerJsonPath + '.'; return reject(new Error(err)); } }); }); }
javascript
{ "resource": "" }
q8249
train
function (cb) { sails.log.verbose('Loading app Gulpfile...'); // Start task depending on environment if(sails.config.environment === 'production'){ return this.runTask('prod', cb); } this.runTask('default', cb); }
javascript
{ "resource": "" }
q8250
_sanitize
train
function _sanitize (chunk) { if (chunk && typeof chunk === 'object' && chunk.toString) { chunk = chunk.toString(); } if (typeof chunk === 'string') { chunk = chunk.replace(/^[\s\n]*/, ''); chunk = chunk.replace(/[\s\n]*$/, ''); } return chunk; }
javascript
{ "resource": "" }
q8251
background
train
function background(options) { options = options || {}; // ReSharper disable once UnusedParameter return function (config) { var values = []; [ 'attachment', 'clip', 'color', 'image', 'origin', 'position', 'repeat', 'size' ].forEach(function (prop) { if (options.hasOwnProperty(prop)) { values.push(options[prop]); } }); if (values.length) { return [['background', values.join(' ')]]; } return []; }; }
javascript
{ "resource": "" }
q8252
PingPacket
train
function PingPacket(nonce) { if (!(this instanceof PingPacket)) return new PingPacket(nonce); Packet.call(this); this.nonce = nonce || null; }
javascript
{ "resource": "" }
q8253
PongPacket
train
function PongPacket(nonce) { if (!(this instanceof PongPacket)) return new PongPacket(nonce); Packet.call(this); this.nonce = nonce || encoding.ZERO_U64; }
javascript
{ "resource": "" }
q8254
GetBlocksPacket
train
function GetBlocksPacket(locator, stop) { if (!(this instanceof GetBlocksPacket)) return new GetBlocksPacket(locator, stop); Packet.call(this); this.version = common.PROTOCOL_VERSION; this.locator = locator || []; this.stop = stop || null; }
javascript
{ "resource": "" }
q8255
GetHeadersPacket
train
function GetHeadersPacket(locator, stop) { if (!(this instanceof GetHeadersPacket)) return new GetHeadersPacket(locator, stop); GetBlocksPacket.call(this, locator, stop); }
javascript
{ "resource": "" }
q8256
BlockPacket
train
function BlockPacket(block, witness) { if (!(this instanceof BlockPacket)) return new BlockPacket(block, witness); Packet.call(this); this.block = block || new MemBlock(); this.witness = witness || false; }
javascript
{ "resource": "" }
q8257
TXPacket
train
function TXPacket(tx, witness) { if (!(this instanceof TXPacket)) return new TXPacket(tx, witness); Packet.call(this); this.tx = tx || new TX(); this.witness = witness || false; }
javascript
{ "resource": "" }
q8258
FilterLoadPacket
train
function FilterLoadPacket(filter) { if (!(this instanceof FilterLoadPacket)) return new FilterLoadPacket(filter); Packet.call(this); this.filter = filter || new Bloom(); }
javascript
{ "resource": "" }
q8259
FilterAddPacket
train
function FilterAddPacket(data) { if (!(this instanceof FilterAddPacket)) return new FilterAddPacket(data); Packet.call(this); this.data = data || DUMMY; }
javascript
{ "resource": "" }
q8260
MerkleBlockPacket
train
function MerkleBlockPacket(block) { if (!(this instanceof MerkleBlockPacket)) return new MerkleBlockPacket(block); Packet.call(this); this.block = block || new MerkleBlock(); }
javascript
{ "resource": "" }
q8261
SendCmpctPacket
train
function SendCmpctPacket(mode, version) { if (!(this instanceof SendCmpctPacket)) return new SendCmpctPacket(mode, version); Packet.call(this); this.mode = mode || 0; this.version = version || 1; }
javascript
{ "resource": "" }
q8262
CmpctBlockPacket
train
function CmpctBlockPacket(block, witness) { if (!(this instanceof CmpctBlockPacket)) return new CmpctBlockPacket(block, witness); Packet.call(this); this.block = block || new bip152.CompactBlock(); this.witness = witness || false; }
javascript
{ "resource": "" }
q8263
GetBlockTxnPacket
train
function GetBlockTxnPacket(request) { if (!(this instanceof GetBlockTxnPacket)) return new GetBlockTxnPacket(request); Packet.call(this); this.request = request || new bip152.TXRequest(); }
javascript
{ "resource": "" }
q8264
BlockTxnPacket
train
function BlockTxnPacket(response, witness) { if (!(this instanceof BlockTxnPacket)) return new BlockTxnPacket(response, witness); Packet.call(this); this.response = response || new bip152.TXResponse(); this.witness = witness || false; }
javascript
{ "resource": "" }
q8265
EncinitPacket
train
function EncinitPacket(publicKey, cipher) { if (!(this instanceof EncinitPacket)) return new EncinitPacket(publicKey, cipher); Packet.call(this); this.publicKey = publicKey || encoding.ZERO_KEY; this.cipher = cipher || 0; }
javascript
{ "resource": "" }
q8266
EncackPacket
train
function EncackPacket(publicKey) { if (!(this instanceof EncackPacket)) return new EncackPacket(publicKey); Packet.call(this); this.publicKey = publicKey || encoding.ZERO_KEY; }
javascript
{ "resource": "" }
q8267
AuthChallengePacket
train
function AuthChallengePacket(hash) { if (!(this instanceof AuthChallengePacket)) return new AuthChallengePacket(hash); Packet.call(this); this.hash = hash || encoding.ZERO_HASH; }
javascript
{ "resource": "" }
q8268
AuthReplyPacket
train
function AuthReplyPacket(signature) { if (!(this instanceof AuthReplyPacket)) return new AuthReplyPacket(signature); Packet.call(this); this.signature = signature || encoding.ZERO_SIG64; }
javascript
{ "resource": "" }
q8269
AuthProposePacket
train
function AuthProposePacket(hash) { if (!(this instanceof AuthProposePacket)) return new AuthProposePacket(hash); Packet.call(this); this.hash = hash || encoding.ZERO_HASH; }
javascript
{ "resource": "" }
q8270
UnknownPacket
train
function UnknownPacket(cmd, data) { if (!(this instanceof UnknownPacket)) return new UnknownPacket(cmd, data); Packet.call(this); this.cmd = cmd; this.data = data; }
javascript
{ "resource": "" }
q8271
SigCache
train
function SigCache(size) { if (!(this instanceof SigCache)) return new SigCache(size); if (size == null) size = 10000; assert(util.isU32(size)); this.size = size; this.keys = []; this.valid = new Map(); }
javascript
{ "resource": "" }
q8272
SigCacheEntry
train
function SigCacheEntry(sig, key) { this.sig = Buffer.from(sig); this.key = Buffer.from(key); }
javascript
{ "resource": "" }
q8273
sanitize
train
function sanitize (fn) { return function (/* path, ...middleware */) { var middleware = [] var startindex = 0 var endindex = arguments.length var path var options if (typeof arguments[0] === 'string') { path = arguments[0] startindex = 1 } if (typeof arguments[arguments.length - 1] === 'object') { endindex = arguments.length - 1 options = arguments[endindex] } // Concat all the middleware functions. for (var i = startindex; i < endindex; i++) { middleware.push(arguments[i]) } middleware = flatten(middleware) if (middleware.length === 0) { throw new TypeError('Expected a function but got no arguments') } if (middleware.length === 1) { middleware = middleware[0] } else { middleware = compose(middleware) } fn.call(this, path, middleware, extend({}, this._options, options)) return this } }
javascript
{ "resource": "" }
q8274
RBT
train
function RBT(compare, unique) { if (!(this instanceof RBT)) return new RBT(compare, unique); assert(typeof compare === 'function'); this.root = SENTINEL; this.compare = compare; this.unique = unique || false; }
javascript
{ "resource": "" }
q8275
RBTSentinel
train
function RBTSentinel() { this.key = null; this.value = null; this.color = BLACK; this.parent = null; this.left = null; this.right = null; }
javascript
{ "resource": "" }
q8276
train
function (playerCards, dealerCard, handValue, handCount, dealerCheckedBlackjack, options) { // If exactComposition isn't set, no override if (options.strategyComplexity != "exactComposition") { return null; } // Now look at strategies based on game options if ((options.numberOfDecks == 2) && (!options.hitSoft17)) { return TwoDeckStandSoft17(playerCards, dealerCard, handValue, handCount, dealerCheckedBlackjack, options); } }
javascript
{ "resource": "" }
q8277
globcmd
train
function globcmd(globstr) { var dir = arguments.length <= 1 || arguments[1] === undefined ? process.cwd() : arguments[1]; return new Promise(function (resolve, reject) { if (!globstr || !globstr.length) { return reject(new Error('No glob string given.')); } // Use glob to read the files in the dir (0, _glob2.default)(String(globstr), { cwd: dir }, function (err, files) { if (err) return reject(err); // Files if (files.length === 0) { reject(new Error('No files match the glob string "' + globstr + '"')); } // Append the matching file to an array resolve(files.map(function (filename) { return { path: _path2.default.resolve(dir, filename), relative: _path2.default.relative(dir, filename) }; })); }); }); }
javascript
{ "resource": "" }
q8278
init
train
function init(options, callback) { if (!options.clientId) { throw new Error('client id not specified'); } core.setClientId(options.clientId); if (options.nw) { if (options.nw === true) { core.log('NW.js 0.13 is experimental.'); gui.setGUIType('nw13'); } else { gui.setGUIType('nw', options.nw); } } else if (options.electron) { gui.setGUIType('electron'); } auth.initSession(options.session, callback); }
javascript
{ "resource": "" }
q8279
mine
train
function mine(data, target, min, max) { let nonce = min; data.writeUInt32LE(nonce, 76, true); // The heart and soul of the miner: match the target. while (nonce <= max) { // Hash and test against the next target. // if (rcmp(digest.hash256(data), target) <= 0) // cfc // if (rcmp(powHash(data), target) <= 0) // ctl if (rcmp(calHash(data), target) <= 0) return nonce; // Increment the nonce to get a different hash. nonce++; // Update the raw buffer. data.writeUInt32LE(nonce, 76, true); } return -1; }
javascript
{ "resource": "" }
q8280
Payment
train
function Payment(options) { if (!(this instanceof Payment)) return new Payment(options); this.merchantData = null; this.transactions = []; this.refundTo = []; this.memo = null; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8281
isNodeIgnored
train
function isNodeIgnored(node) { const parent = node.parent; if (!parent) { // Root was reached. return false; } if (parent.some((child) => (child.type === 'comment' && PATTERN_IGNORE.test(child.text)))) { // Instruction to ignore the node was detected. return true; } // Check the instruction on one level above. return isNodeIgnored(parent); }
javascript
{ "resource": "" }
q8282
train
function ( contour, indices ) { var n = contour.length; if ( n < 3 ) return null; var result = [], verts = [], vertIndices = []; /* we want a counter-clockwise polygon in verts */ var u, v, w; if ( area( contour ) > 0.0 ) { for ( v = 0; v < n; v ++ ) verts[ v ] = v; } else { for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; } var nv = n; /* remove nv - 2 vertices, creating 1 triangle every time */ var count = 2 * nv; /* error detection */ for ( v = nv - 1; nv > 2; ) { /* if we loop, it is probably a non-simple polygon */ if ( ( count -- ) <= 0 ) { //** Triangulate: ERROR - probable bad polygon! //throw ( "Warning, unable to triangulate polygon!" ); //return null; // Sometimes warning is fine, especially polygons are triangulated in reverse. console.log( 'Warning, unable to triangulate polygon!' ); if ( indices ) return vertIndices; return result; } /* three consecutive vertices in current polygon, <u,v,w> */ u = v; if ( nv <= u ) u = 0; /* previous */ v = u + 1; if ( nv <= v ) v = 0; /* new v */ w = v + 1; if ( nv <= w ) w = 0; /* next */ if ( snip( contour, u, v, w, nv, verts ) ) { var a, b, c, s, t; /* true names of the vertices */ a = verts[ u ]; b = verts[ v ]; c = verts[ w ]; /* output Triangle */ result.push( [ contour[ a ], contour[ b ], contour[ c ] ] ); vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); /* remove v from the remaining polygon */ for ( s = v, t = v + 1; t < nv; s++, t++ ) { verts[ s ] = verts[ t ]; } nv --; /* reset error detection counter */ count = 2 * nv; } } if ( indices ) return vertIndices; return result; }
javascript
{ "resource": "" }
q8283
parseNode
train
function parseNode(line) { current = { is : 'NODE', type : 'NODE', id : line.substr(10, 10).trim().toLowerCase(), initialStorage : line.substr(20, 10).trim(), areaCapfactor : line.substr(30, 10).trim(), endingStorage : line.substr(40, 10).trim() }; }
javascript
{ "resource": "" }
q8284
URI
train
function URI(options) { if (!(this instanceof URI)) return new URI(options); this.address = new Address(); this.amount = -1; this.label = null; this.message = null; this.request = null; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8285
TX
train
function TX(options) { if (!(this instanceof TX)) return new TX(options); this.version = 1; this.inputs = []; this.outputs = []; this.locktime = 0; this.mutable = false; this._hash = null; this._hhash = null; this._whash = null; this._raw = null; this._size = -1; this._witness = -1; this._sigops = -1; this._hashPrevouts = null; this._hashSequence = null; this._hashOutputs = null; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8286
MappedLock
train
function MappedLock() { if (!(this instanceof MappedLock)) return MappedLock.create(); this.jobs = new Map(); this.busy = new Set(); this.destroyed = false; }
javascript
{ "resource": "" }
q8287
decode
train
function decode (param) { try { return decodeURIComponent(param) } catch (_) { var err = new Error('Failed to decode param "' + param + '"') err.status = 400 throw err } }
javascript
{ "resource": "" }
q8288
ChainEntry
train
function ChainEntry(options) { if (!(this instanceof ChainEntry)) return new ChainEntry(options); this.hash = encoding.NULL_HASH; this.version = 1; this.prevBlock = encoding.NULL_HASH; this.merkleRoot = encoding.NULL_HASH; this.time = 0; this.bits = 0; this.nonce = 0; this.height = 0; this.chainwork = ZERO; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8289
PaymentRequest
train
function PaymentRequest(options) { if (!(this instanceof PaymentRequest)) return new PaymentRequest(options); this.version = -1; this.pkiType = null; this.pkiData = null; this.paymentDetails = new PaymentDetails(); this.signature = null; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8290
VerifyError
train
function VerifyError(msg, code, reason, score, malleated) { Error.call(this); assert(typeof code === 'string'); assert(typeof reason === 'string'); assert(score >= 0); this.type = 'VerifyError'; this.message = ''; this.code = code; this.reason = reason; this.score = score; this.hash = msg.hash('hex'); this.malleated = malleated || false; this.message = `Verification failure: ${reason}` + ` (code=${code} score=${score} hash=${msg.rhash()})`; if (Error.captureStackTrace) Error.captureStackTrace(this, VerifyError); }
javascript
{ "resource": "" }
q8291
Pagelet
train
function Pagelet(bigpipe) { if (!(this instanceof Pagelet)) return new Pagelet(bigpipe); var self = this; // // Create one single Fortress instance that orchestrates all iframe based client // code. This sandbox variable should never be exposed to the outside world in // order to prevent leaking. // this.sandbox = sandbox = sandbox || new Fortress(); this.bigpipe = bigpipe; // // Add an initialized method which is __always__ called when the pagelet is // either destroyed directly, errored or loaded. // this.initialized = one(function initialized() { self.broadcast('initialized'); }); }
javascript
{ "resource": "" }
q8292
shout
train
function shout(name) { pagelet.bigpipe.emit.apply(pagelet.bigpipe, [ name.join(':'), pagelet ].concat(Array.prototype.slice.call(arguments, 1))); return pagelet; }
javascript
{ "resource": "" }
q8293
train
function(buffer) { var inputSize = buffer.length; // Holds an array that represents the count of various characters. var charCount = []; // Loop through the bytes and increase charCount. for (var a = 0; a < inputSize; a++) { var temp = buffer.readUInt8(a); if (charCount[temp] !== undefined) { charCount[temp]++; } else { charCount[temp] = 1; } } // The average number of times a specific character should occur. var expectedCount = inputSize / 256; var chiSquare = 0; for (var i = 0; i < 256; i++) { // Ideally this would be close to 0. a = (charCount[i] !== undefined ? charCount[i] : 0) - expectedCount; chiSquare += (a * a) / expectedCount; } return calculateChiSquareProbability(parseFloat(chiSquare.toFixed(2)), 255); }
javascript
{ "resource": "" }
q8294
calculateChiSquareProbability
train
function calculateChiSquareProbability(x, df) { if (x <= 0.0 || df < 1) return 1.0; var a = 0.5 * x; if (df > 1) var y = calculateExponent(-a); var s = 2.0 * calculateNormalZProbability(-Math.sqrt(x)); if (df > 2) { x = 0.5 * (df - 1.0); var z = 0.5; if (a > BIG_X) { var e = LOG_SQRT_PI; var c = Math.log(a); while (z <= x) { e = Math.log(z) + e; s += calculateExponent(c * z - a - e); z += 1.0; } return (s); } else { e = I_SQRT_PI / Math.sqrt(a); c = 0.0; while (z <= x) { e = e * (a / z); c = c + e; z += 1.0; } return (c * y + s); } } return s; }
javascript
{ "resource": "" }
q8295
calculateNormalZProbability
train
function calculateNormalZProbability(z) { if (z == 0.0) { var x = 0.0; } else { var y = 0.5 * Math.abs(z); // Here comes the magic. if (y >= Z_MAX * 0.5) { x = 1.0; } else if (y < 1.0) { var w = y * y; x = 0.000124818987 * w -0.001075204047; x *= w +0.005198775019; x *= w -0.019198292004; x *= w +0.059054035642; x *= w -0.151968751364; x *= w +0.319152932694; x *= w -0.531923007300; x *= w +0.797884560593; x *= y * 2.0; } else { y -= 2.0; x = -0.000045255659 * y +0.000152529290; x *= y -0.000019538132; x *= y -0.000676904986; x *= y +0.001390604284; x *= y -0.000794620820; x *= y -0.002034254874; x *= y +0.006549791214; x *= y -0.010557625006; x *= y -0.010557625006; x *= y +0.011630447319; x *= y -0.009279453341; x *= y +0.005353579108; x *= y -0.002141268741; x *= y +0.000535310849; x *= y +0.999936657524; } } return z > 0.0 ? (x + 1.0) * 0.5 : (1.0 - x) * 0.5; }
javascript
{ "resource": "" }
q8296
Child
train
function Child(file) { if (!(this instanceof Child)) return new Child(file); EventEmitter.call(this); bindExit(); children.add(this); this.init(file); }
javascript
{ "resource": "" }
q8297
bindExit
train
function bindExit() { if (exitBound) return; exitBound = true; listenExit(() => { for (const child of children) child.destroy(); }); }
javascript
{ "resource": "" }
q8298
listenExit
train
function listenExit(handler) { const onSighup = () => { process.exit(1 | 0x80); }; const onSigint = () => { process.exit(2 | 0x80); }; const onSigterm = () => { process.exit(15 | 0x80); }; const onError = (err) => { if (err && err.stack) console.error(String(err.stack)); else console.error(String(err)); process.exit(1); }; process.once('exit', handler); if (process.listenerCount('SIGHUP') === 0) process.once('SIGHUP', onSighup); if (process.listenerCount('SIGINT') === 0) process.once('SIGINT', onSigint); if (process.listenerCount('SIGTERM') === 0) process.once('SIGTERM', onSigterm); if (process.listenerCount('uncaughtException') === 0) process.once('uncaughtException', onError); process.on('newListener', (name) => { switch (name) { case 'SIGHUP': process.removeListener(name, onSighup); break; case 'SIGINT': process.removeListener(name, onSigint); break; case 'SIGTERM': process.removeListener(name, onSigterm); break; case 'uncaughtException': process.removeListener(name, onError); break; } }); }
javascript
{ "resource": "" }
q8299
parsePalette
train
function parsePalette (palette) { var vars = { camelCased : {}, paramCased : {} }; Object.keys(palette).forEach(function (key) { var hex = color(palette[key]).hexString(); vars.camelCased[cameled(key)] = hex; vars.paramCased[dashed(key)] = hex; }); return vars; }
javascript
{ "resource": "" }