_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q8600
routeTypes
train
function routeTypes(routeMap) { var typeSet = {}; var keys = Object.keys(routeMap); for (var i = 0, len = keys.length; i < len; i++) { var route = routeMap[keys[i]]; var type = routeType(route); typeSet[type] = true; } // Use RouteTypeFields ordering var typeList = []; var fields = Object.keys(RouteTypeFields); for (var i = 0, len = fields.length; i < len; i++) { var type = RouteTypeFields[fields[i]]; if (typeSet[type]) { typeList.push(type) } } return typeList; }
javascript
{ "resource": "" }
q8601
GoogleAuthCodeStrategy
train
function GoogleAuthCodeStrategy(options, verify) { options = options || {}; options.authorizationURL = options.authorizationURL || 'https://accounts.google.com/o/oauth2/v2/auth'; options.tokenURL = options.tokenURL || 'https://www.googleapis.com/oauth2/v4/token'; this._passReqToCallback = options.passReqToCallback; OAuth2Strategy.call(this, options, verify); this.name = 'google-authcode'; }
javascript
{ "resource": "" }
q8602
isValidDate
train
function isValidDate(date) { if (moment.isMoment(date)) { return date.isValid(); } else { return moment(date).isValid(); } }
javascript
{ "resource": "" }
q8603
isValidQuery
train
function isValidQuery(definition) { var requiredKeys = [ 'event_name', 'resource_type', 'tracker_id' ]; return _.all(requiredKeys, function(key) { return _.has(definition, key); }); }
javascript
{ "resource": "" }
q8604
train
function( fn ){ var req; var fnName; if( $$.is.object(fn) && fn.fn ){ // manual fn req = fnAs( fn.fn, fn.name ); fnName = fn.name; fn = fn.fn; } else if( $$.is.fn(fn) ){ // auto fn req = fn.toString(); fnName = fn.name; } else if( $$.is.string(fn) ){ // stringified fn req = fn; } else if( $$.is.object(fn) ){ // plain object if( fn.proto ){ req = ''; } else { req = fn.name + ' = {};'; } fnName = fn.name; fn = fn.obj; } req += '\n'; var protoreq = function( val, subname ){ if( val.prototype ){ var protoNonempty = false; for( var prop in val.prototype ){ protoNonempty = true; break; }; if( protoNonempty ){ req += fnAsRequire( { name: subname, obj: val, proto: true }, val ); } } }; // pull in prototype if( fn.prototype && fnName != null ){ for( var name in fn.prototype ){ var protoStr = ''; var val = fn.prototype[ name ]; var valStr = stringifyFieldVal( val ); var subname = fnName + '.prototype.' + name; protoStr += subname + ' = ' + valStr + ';\n'; if( protoStr ){ req += protoStr; } protoreq( val, subname ); // subobject with prototype } } // pull in properties for obj/fns if( !$$.is.string(fn) ){ for( var name in fn ){ var propsStr = ''; if( fn.hasOwnProperty(name) ){ var val = fn[ name ]; var valStr = stringifyFieldVal( val ); var subname = fnName + '["' + name + '"]'; propsStr += subname + ' = ' + valStr + ';\n'; } if( propsStr ){ req += propsStr; } protoreq( val, subname ); // subobject with prototype } } return req; }
javascript
{ "resource": "" }
q8605
train
function( m ){ var _p = this._private; if( _p.webworker ){ _p.webworker.postMessage( m ); } if( _p.child ){ _p.child.send( m ); } return this; // chaining }
javascript
{ "resource": "" }
q8606
train
function( fn, as ){ for( var i = 0; i < this.length; i++ ){ var thread = this[i]; thread.require( fn, as ); } return this; }
javascript
{ "resource": "" }
q8607
train
function( fn ){ var pass = this._private.pass.shift(); return this.random().pass( pass ).run( fn ); }
javascript
{ "resource": "" }
q8608
train
function( m ){ for( var i = 0; i < this.length; i++ ){ var thread = this[i]; thread.message( m ); } return this; // chaining }
javascript
{ "resource": "" }
q8609
train
function( fn ){ var self = this; var _p = self._private; var subsize = self.spreadSize(); // number of pass eles to handle in each thread var pass = _p.pass.shift().concat([]); // keep a copy var runPs = []; for( var i = 0; i < this.length; i++ ){ var thread = this[i]; var slice = pass.splice( 0, subsize ); var runP = thread.pass( slice ).run( fn ); runPs.push( runP ); var doneEarly = pass.length === 0; if( doneEarly ){ break; } } return $$.Promise.all( runPs ).then(function( thens ){ var postpass = new Array(); var p = 0; // fill postpass with the total result joined from all threads for( var i = 0; i < thens.length; i++ ){ var then = thens[i]; // array result from thread i for( var j = 0; j < then.length; j++ ){ var t = then[j]; // array element postpass[ p++ ] = t; } } return postpass; }); }
javascript
{ "resource": "" }
q8610
train
function( cmp ){ var self = this; var P = this._private.pass[0].length; var subsize = this.spreadSize(); var N = this.length; cmp = cmp || function( a, b ){ // default comparison function if( a < b ){ return -1; } else if( a > b ){ return 1; } return 0; }; self.require( cmp, '_$_$_cmp' ); return self.spread(function( split ){ // sort each split normally var sortedSplit = split.sort( _$_$_cmp ); resolve( sortedSplit ); }).then(function( joined ){ // do all the merging in the main thread to minimise data transfer // TODO could do merging in separate threads but would incur add'l cost of data transfer // for each level of the merge var merge = function( i, j, max ){ // don't overflow array j = Math.min( j, P ); max = Math.min( max, P ); // left and right sides of merge var l = i; var r = j; var sorted = []; for( var k = l; k < max; k++ ){ var eleI = joined[i]; var eleJ = joined[j]; if( i < r && ( j >= max || cmp(eleI, eleJ) <= 0 ) ){ sorted.push( eleI ); i++; } else { sorted.push( eleJ ); j++; } } // in the array proper, put the sorted values for( var k = 0; k < sorted.length; k++ ){ // kth sorted item var index = l + k; joined[ index ] = sorted[k]; } }; for( var splitL = subsize; splitL < P; splitL *= 2 ){ // merge until array is "split" as 1 for( var i = 0; i < P; i += 2*splitL ){ merge( i, i + splitL, i + 2*splitL ); } } return joined; }); }
javascript
{ "resource": "" }
q8611
fromString
train
function fromString (string) { assert.equal(typeof string, 'string') return from(function (size, next) { if (string.length <= 0) return this.push(null) const chunk = string.slice(0, size) string = string.slice(size) next(null, chunk) }) }
javascript
{ "resource": "" }
q8612
repoSha
train
function repoSha (options, callback) { var user = options.user var repo = options.repo var path = options.path || null var branch = options.branch || 'master' var token = options.token || null if (!user || !repo || !path) { return callback(new Error('must specify user, repo, path')) } var url = '/repos/' + user + '/' + repo + '/contents/' + path request({ url: url, qs: { access_token: token, ref: branch } }, function (err, json) { if (err) return callback(err) if (json.message) return callback(new Error(json.message)) if (json.sha) return callback(null, json.sha) callback(new Error('could not get sha for ' + url)) }) }
javascript
{ "resource": "" }
q8613
setVersioningContext
train
function setVersioningContext(context, key, value) { const { versioning } = context; versioning[key] = value; if (key === 'previous') { process.env.EMBER_DEPLOY_PREVIOUS_VERSION = value; } if (key === 'current') { process.env.EMBER_DEPLOY_CURRENT_VERSION = value; } return { versioning }; }
javascript
{ "resource": "" }
q8614
flatten
train
function flatten (flags, allowShorthand, allowExtendedShorthand) { let map = {} Object.keys(flags).forEach((k) => { const { alias, type, validate } = flags[k] let value = { name: k } if (type) value.type = type if (validate) value.validate = validate // include the name as value that can be invoked // also include the shorthands if allowed map[k] = value if (allowShorthand) map[`-${k}`] = value if (allowExtendedShorthand) map[`--${k}`] = value // If the alias is a string we don't need to map anything if (typeof alias === 'string') { if (allowShorthand) map[`-${alias}`] = value if (allowExtendedShorthand) map[`--${alias}`] = value map[alias] = value // the default alias is included } // If the alias is an array, we should map over the values and set them if (Array.isArray(alias)) { alias.forEach((a) => { if (allowShorthand) map[`-${a}`] = value if (allowExtendedShorthand) map[`--${a}`] = value // the default alias is included map[a] = value }) } }) return map }
javascript
{ "resource": "" }
q8615
db
train
function db(objectName) { if (_.isBoolean(save.hasLoaded)) deasync.loopWhile(() => !save.hasLoaded); if (!_.has(objects, objectName)) objects[objectName] = {}; return createMethods(objects[objectName], save.bind(null, objectName)); }
javascript
{ "resource": "" }
q8616
__deserializeBoolean
train
function __deserializeBoolean(type, start, options) { let end = start; let data = type === DATA_TYPE.TRUE; return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8617
__deserializeInt8
train
function __deserializeInt8(buffer, start, options) { let end = start + 1; let dataView = new DataView(buffer); let data = dataView.getInt8(start); return { anchor: end, value:options.use_native_types ? data : Int8.from(data) }; }
javascript
{ "resource": "" }
q8618
__deserializeInt16
train
function __deserializeInt16(buffer, start, options) { let end = start + 2; let dataView = new DataView(buffer); let data = dataView.getInt16(start, true); return { anchor: end, value:options.use_native_types ? data : Int16.from(data) }; }
javascript
{ "resource": "" }
q8619
__deserializeInt32
train
function __deserializeInt32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getInt32(start, true); return { anchor: end, value:options.use_native_types ? data : Int32.from(data) }; }
javascript
{ "resource": "" }
q8620
__deserializeInt64
train
function __deserializeInt64(buffer, start, options) { let step = 4; let length = 2; let end = start + (step * length); let dataView = new DataView(buffer); let dataArray = []; for (let i = start; i < end; i += step) { dataArray.push(dataView.getUint32(i, true)); } let data = new Int64(new Uint32Array(dataArray)); return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8621
__deserializeIntVar
train
function __deserializeIntVar(buffer, start, options) { const dataBuff = new Uint8Array(buffer); if ( dataBuff[start] > 127 ) { throw new Error( "Cannot support IntVar whose size is greater than 127 bytes" ); } let index = 0, data_size = dataBuff[start], end = start + 1; const result_buffer = new Uint8Array(data_size); while( data_size-- > 0 ) { result_buffer[index] = dataBuff[end]; index++; end++; } let data = new IntVar(result_buffer); return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8622
__deserializeUInt8
train
function __deserializeUInt8(buffer, start, options) { let end = start + 1; let dataView = new DataView(buffer); let data = dataView.getUint8(start); return { anchor: end, value:options.use_native_types ? data : UInt8.from(data) }; }
javascript
{ "resource": "" }
q8623
__deserializeUInt16
train
function __deserializeUInt16(buffer, start, options) { let end = start + 2; let dataView = new DataView(buffer); let data = dataView.getUint16(start, true); return { anchor: end, value:options.use_native_types ? data : UInt16.from(data) }; }
javascript
{ "resource": "" }
q8624
__deserializeUInt32
train
function __deserializeUInt32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getUint32(start, true); return { anchor: end, value:options.use_native_types ? data : UInt32.from(data) }; }
javascript
{ "resource": "" }
q8625
__deserializeUIntVar
train
function __deserializeUIntVar(buffer, start, options) { const dataBuff = new Uint8Array(buffer); if ( dataBuff[start] > 127 ) { throw new Error( "Cannot support UIntVar whose size is greater than 127 bytes" ); } let index = 0, data_size = dataBuff[start], end = start + 1; const result_buffer = new Uint8Array(data_size); while( data_size-- > 0 ) { result_buffer[index] = dataBuff[end]; index++; end++; } let data = new UIntVar(result_buffer); return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8626
__deserializeFloat32
train
function __deserializeFloat32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getFloat32(start, true); return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8627
__deserializeFloat64
train
function __deserializeFloat64(buffer, start, options) { let end = start + 8; let dataView = new DataView(buffer); let data = dataView.getFloat64(start, true); return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8628
__deserializeArray
train
function __deserializeArray(buffer, start, options) { let dataView = new DataView(buffer); let length = dataView.getUint32(start, true); start += 4; let end = start + length; let data = []; while (start < end) { let subType, subData; ({ anchor: start, value: subType } = __deserializeType(buffer, start, options)); ({ anchor: start, value: subData } = __deserializeData(subType, buffer, start, options)); data.push(subData); } return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8629
__deserializeObject
train
function __deserializeObject(buffer, start, options) { let dataView = new DataView(buffer); let length = dataView.getUint32(start, true); start += 4; let end = start + length; let data = {}; while (start < end) { let subType, subKey, subData; ({ anchor: start, value: subType } = __deserializeType(buffer, start, options)); ({ anchor: start, value: subKey } = __deserializeShortString(buffer, start, options)); ({ anchor: start, value: subData } = __deserializeData(subType, buffer, start, options)); data[subKey] = subData; } return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8630
__deserializeDate
train
function __deserializeDate(buffer, start, options) { let end = start + 8; let dataView = new DataView(buffer); let data = new Date(dataView.getFloat64(start, true)); return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8631
__deserializeObjectId
train
function __deserializeObjectId(buffer, start, options) { let step = 1; let length = 12; let end = start + length; let dataView = new DataView(buffer); let dataArray = []; for (let i = start; i < end; i += step) { dataArray.push(dataView.getUint8(i)); } let data = new ObjectId(Uint8Array.from(dataArray).buffer); return { anchor: end, value: data }; }
javascript
{ "resource": "" }
q8632
__deserializeArrayBuffer
train
function __deserializeArrayBuffer(buffer, start, options) { let end = start + 4; let [length] = new Uint32Array(buffer.slice(start, end)); end = end + length; return {anchor:end, value:buffer.slice(start+4, end)}; }
javascript
{ "resource": "" }
q8633
getRegex
train
function getRegex(regex, flags) { var result = typeOf(regex) === 'String' ? new RegExp(regex, flags || '') : regex if (typeOf(result) !== 'RegExp') { throw new Error( NAME + ': option "regex" must be a string or a RegExp object') } return result }
javascript
{ "resource": "" }
q8634
getMatchFn
train
function getMatchFn(valueFn) { return function () { var len = arguments.length // Create a RegExp match object. var match = Array.prototype.slice.call(arguments, 0, -2) .reduce(function (map, g, i) { map[i] = g return map }, {index: arguments[len - 2], input: arguments[len - 1]}) // Call the original function. return valueFn(match) } }
javascript
{ "resource": "" }
q8635
replace
train
function replace(regex, source, options) { var valueOrFn = getValueOrMatchFn(options.value) source.replace(regex, function () { return '' }) return source.replace(regex, valueOrFn) }
javascript
{ "resource": "" }
q8636
validateDependency
train
function validateDependency(packageJson, dependency) { const version = findDependency(dependency.package, packageJson); if (!version) { return; } let major; try { major = semverUtils.parseRange(version)[0].major; } catch (exception) { console.log('DvhbWebpack: cannot parse ' + dependency.name + ' version which is "' + version + '".'); console.log('DvhbWebpack might not work properly. Please report this issue at ' + consts.BUGS_URL); console.log(); } if (major < dependency.from) { throw new DvhbWebpackError('DvhbWebpack: ' + dependency.name + ' ' + dependency.from + ' is required, ' + 'you are using version ' + major + '.'); } else if (major > dependency.to) { console.log('DvhbWebpack: ' + dependency.name + ' is supported up to version ' + dependency.to + ', ' + 'you are using version ' + major + '.'); console.log('DvhbWebpack might not work properly, report bugs at ' + consts.BUGS_URL); console.log(); } }
javascript
{ "resource": "" }
q8637
toRouteMap
train
function toRouteMap(routeList) { var routeMap = {}; for (var i = 0, len = routeList.length; i < len; i++) { var route = routeList[i]; routeMap[route['path']] = route; } return routeMap; }
javascript
{ "resource": "" }
q8638
train
function() { var doc = this; var newDoc = {}; _.forEach(this, function(v, k) { if (doc.hasOwnProperty(k) && !_.startsWith(k, '$')) newDoc[k] = _.clone(v); }); return newDoc; }
javascript
{ "resource": "" }
q8639
train
function() { var doc = this; var outDoc = doc.toObject(); // Rely on the toObject() syntax to strip out rubbish doc.getOIDs().forEach(function(node) { switch (node.fkType) { case 'objectId': var oidLeaf = _.get(doc, node.docPath); if (_.isUndefined(oidLeaf)) return; // Ignore undefined if (!o.utilities.isObjectID(oidLeaf)) { if (_.has(oidLeaf, '_id')) { // Already populated? _.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf._id)); } else { // Convert to an OID _.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf)); } } break; case 'objectIdArray': var oidLeaf = _.get(doc, node.schemaPath); _.set(outDoc, node.schemaPath, oidLeaf.map(function(leaf) { return o.utilities.isObjectID(leaf) ? leaf : o.utilities.objectID(leaf); })); break; default: return; // Ignore unsupported OID types } }); return outDoc; }
javascript
{ "resource": "" }
q8640
train
function() { var doc = this; var stack = []; _.forEach(model.$oids, function(fkType, schemaPath) { if (fkType.type == 'subDocument') return; // Skip sub-documents (as they are stored against the parent anyway) stack = stack.concat(doc.getNodesBySchemaPath(schemaPath) .map(function(node) { node.fkType = fkType.type; return node; }) ); }); return stack; }
javascript
{ "resource": "" }
q8641
generateJS
train
function generateJS( data ) { var preparedData = prepareValues( data ); var content = JSON.stringify( preparedData, null, options.indention ); var output = outputPattern.js.replace( "{{name}}", options.name ).replace( "{{vars}}", content ); return options.singlequote ? output.replace( /"/g, "'" ) : output; }
javascript
{ "resource": "" }
q8642
createClient
train
function createClient() { rpc.emit('createClient', 'test', { nick : 'simpleircbot', user : 'testuser', server : 'localhost', realname: 'realbot', port: 6667, secure: false, retryCount: 2, retryWait: 3000 }); }
javascript
{ "resource": "" }
q8643
nodePosition
train
function nodePosition(node) { let name = node.nodeName let position = 1 while ((node = node.previousSibling)) { if (node.nodeName === name) position += 1 } return position }
javascript
{ "resource": "" }
q8644
resolve
train
function resolve(path, root, resolver) { try { // Add a default value to each path part lacking a prefix. let nspath = path.replace(/\/(?!\.)([^\/:\(]+)(?=\/|$)/g, '/_default_:$1') return platformResolve(nspath, root, resolver) } catch (err) { return fallbackResolve(path, root) } }
javascript
{ "resource": "" }
q8645
fallbackResolve
train
function fallbackResolve(path, root) { let steps = path.split("/") let node = root while (node) { let step = steps.shift() if (step === undefined) break if (step === '.') continue let [name, position] = step.split(/[\[\]]/) name = name.replace('_default_:', '') position = position ? parseInt(position) : 1 node = findChild(node, name, position) } return node }
javascript
{ "resource": "" }
q8646
platformResolve
train
function platformResolve(path, root, resolver) { let document = getDocument(root) let r = document.evaluate(path, root, resolver, FIRST_ORDERED_NODE_TYPE, null) return r.singleNodeValue }
javascript
{ "resource": "" }
q8647
findChild
train
function findChild(node, name, position) { for (node = node.firstChild ; node ; node = node.nextSibling) { if (nodeName(node) === name && --position === 0) break } return node }
javascript
{ "resource": "" }
q8648
logEvent
train
function logEvent(ctx, data, request) { if (!data) return; var obj = {}; var msg = ''; if (ctx.includeTags && Array.isArray(data.tags)) { obj.tags = ctx.joinTags ? data.tags.join(ctx.joinTags) : data.tags; } if (request) obj.req_id = request.id; if (data instanceof Error) { ctx.log.child(obj)[ctx.level](data); return; } var type = typeof data.data; if (type === 'string') { msg = data.data; } else if (ctx.includeData && data.data !== undefined) { if (ctx.mergeData && type === 'object' && !Array.isArray(data.data)) { lodash.assign(obj, data.data); if (obj.id === obj.req_id) delete obj.id; } else { obj.data = data.data; } } else if (ctx.skipUndefined) { return; } ctx.log[ctx.level](obj, msg); }
javascript
{ "resource": "" }
q8649
__serializeIntVar
train
function __serializeIntVar(data) { if ( data.size > 127 ) { throw new Error( "Cannot support IntVar whose size is greater than 127 bytes" ); } const size = new Uint8Array([data.size]); return [size.buffer, data.toBytes().buffer]; }
javascript
{ "resource": "" }
q8650
__serializeUIntVar
train
function __serializeUIntVar(data) { if ( data.size > 127 ) { throw new Error( "Cannot support UIntVar whose size is greater than 127 bytes" ); } const size = new Uint8Array([data.size]); return [size.buffer, data.toBytes().buffer]; }
javascript
{ "resource": "" }
q8651
__serializeArray
train
function __serializeArray(data, options=DEFAULT_OPTIONS) { let dataBuffers = []; // ignore undefined value for (let key in data) { let subData = data[key]; let subType = __getType(subData, options); let subTypeBuffer = __serializeType(subType); let subDataBuffers = __serializeData(subType, subData, options); dataBuffers.push(subTypeBuffer, ...subDataBuffers); } let length = __getLengthByArrayBuffers(dataBuffers); let lengthData = new Uint32Array([length]); return [lengthData.buffer, ...dataBuffers]; }
javascript
{ "resource": "" }
q8652
__serializeObject
train
function __serializeObject(data, options=DEFAULT_OPTIONS) { let dataBuffers = []; let allKeys = (options.sort_key === true) ? Object.keys(data).sort() : Object.keys(data); // ignore undefined value for (let key of allKeys) { let subData = data[key]; if (subData === undefined) continue; let subType = __getType(subData, options); let subTypeBuffer = __serializeType(subType); let keyBuffers = __serializeShortString(key); let subDataBuffers = __serializeData(subType, subData, options); dataBuffers.push(subTypeBuffer, ...keyBuffers, ...subDataBuffers); } let length = __getLengthByArrayBuffers(dataBuffers); let lengthData = new Uint32Array([length]); return [lengthData.buffer, ...dataBuffers]; }
javascript
{ "resource": "" }
q8653
__serializeArrayBuffer
train
function __serializeArrayBuffer(data) { let length = data.byteLength; let lengthData = new Uint32Array([length]); return [lengthData.buffer, data]; }
javascript
{ "resource": "" }
q8654
train
function (newMode, noSave) { if (mode != newMode) { mode = newMode; if (!noSave) { saveState(); } } if (!uaSniffed.isIE || mode != "moving") { timer = setTimeout(refreshState, 1); } else { inputStateObj = null; } }
javascript
{ "resource": "" }
q8655
train
function () { var currState = inputStateObj || new TextareaState(panels); if (!currState) { return false; } if (mode == "moving") { if (!lastState) { lastState = currState; } return; } if (lastState) { if (undoStack[stackPtr - 1].text != lastState.text) { undoStack[stackPtr++] = lastState; } lastState = null; } undoStack[stackPtr++] = currState; undoStack[stackPtr + 1] = null; if (callback) { callback(); } }
javascript
{ "resource": "" }
q8656
train
function (event) { if (!event.ctrlKey && !event.metaKey) { var keyCode = event.keyCode; if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) { // 33 - 40: page up/dn and arrow keys // 63232 - 63235: page up/dn and arrow keys on safari setMode("moving"); } else if (keyCode == 8 || keyCode == 46 || keyCode == 127) { // 8: backspace // 46: delete // 127: delete setMode("deleting"); } else if (keyCode == 13) { // 13: Enter setMode("newlines"); } else if (keyCode == 27) { // 27: escape setMode("escape"); } else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) { // 16-20 are shift, etc. // 91: left window key // I think this might be a little messed up since there are // a lot of nonprinting keys above 20. setMode("typing"); } } }
javascript
{ "resource": "" }
q8657
train
function (inputElem, listener) { util.addEvent(inputElem, "input", listener); inputElem.onpaste = listener; inputElem.ondrop = listener; util.addEvent(inputElem, "keypress", listener); util.addEvent(inputElem, "keydown", listener); }
javascript
{ "resource": "" }
q8658
train
function () { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (startType !== "manual") { var delay = 0; if (startType === "delayed") { delay = elapsedTime; } if (delay > maxDelay) { delay = maxDelay; } timeout = setTimeout(makePreviewHtml, delay); } }
javascript
{ "resource": "" }
q8659
train
function (isCancel) { util.removeEvent(doc.body, "keydown", checkEscape); var text = input.value; if (isCancel) { text = null; } else { // Fixes common pasting errors. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://'); if (!/^(?:https?|ftp):\/\//.test(text)) text = 'http://' + text; } dialog.parentNode.removeChild(dialog); callback(text); return false; }
javascript
{ "resource": "" }
q8660
train
function (eventType, params) { params = params || { bubbles: false, cancelable: false, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false }; var mouseEvent = document.createEvent('MouseEvent'); mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, 0, null); return mouseEvent; }
javascript
{ "resource": "" }
q8661
train
function (source, opts, cb) { var callback, options; if (arguments.length === 2) { options = defaults(); callback = opts; } else { options = defaults(opts); callback = cb; } try { source = api.clean(source); callback(null, api.insert(source, getToc(source, options))); } catch (err) { callback(err, null); } }
javascript
{ "resource": "" }
q8662
Kit
train
function Kit(str, variables, forbiddenPaths) { this._variables = variables || {}; this._forbiddenPaths = forbiddenPaths || []; // Import file if (fs.existsSync(str)) { this.fileContents = fs.readFileSync(str).toString(); this.filename = path.basename(str); this._fileDir = path.dirname(str); if (this._forbiddenPaths.indexOf(str) !== -1) { throw new Error('Error: infinite import loop detected. (e.g. File A imports File B, which imports File A.) You must fix this before the file can be compiled.'); } this._forbiddenPaths.push(str); } // Anonymous string else { this.fileContents = str.toString(); this.filename = '<anonymous>'; this._fileDir = ''; } }
javascript
{ "resource": "" }
q8663
encodeProblemUrlChars
train
function encodeProblemUrlChars(url) { if (!url) return ""; var len = url.length; return url.replace(_problemUrlChars, function (match, offset) { if (match == "~D") // escape for dollar return "%24"; if (match == ":") { if (offset == len - 1 || /[0-9\/]/.test(url.charAt(offset + 1))) return ":" } return "%" + match.charCodeAt(0).toString(16); }); }
javascript
{ "resource": "" }
q8664
reducer
train
function reducer (type, records) { return reduce(records, function (hash, record) { record = outputRecord.call(self, type, msgpack.decode(record)) hash[record[primaryKey]] = record return hash }, {}) }
javascript
{ "resource": "" }
q8665
train
function (name, data) { console.log("Custom handler for " + name); // Send information of the "deployment_info" event to an external service (here: Just an echo service) request("https://echo.getpostman.com/get?name=" + name + "&startTime=" + data.timestamp, function (error, response, body) { body = JSON.parse(body); if (!error && response.statusCode == 200) { console.log("Here's the data we have just sent to the echo service:"); console.log("--------------------"); console.log(JSON.stringify(body.args)); // Show the sent data console.log("--------------------"); } }); }
javascript
{ "resource": "" }
q8666
compile
train
function compile(fragments, template) { var walker = document.createTreeWalker(template, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT); var bindings = [], currentNode, parentNode, previousNode; // Reset first node to ensure it isn't a fragment walker.nextNode(); walker.previousNode(); // find bindings for each node do { currentNode = walker.currentNode; parentNode = currentNode.parentNode; bindings.push.apply(bindings, getBindingsForNode(fragments, currentNode, template)); if (currentNode.parentNode !== parentNode) { // currentNode was removed and made a template walker.currentNode = previousNode || walker.root; } else { previousNode = currentNode; } } while (walker.nextNode()); return bindings; }
javascript
{ "resource": "" }
q8667
splitTextNode
train
function splitTextNode(fragments, node) { if (!node.processed) { node.processed = true; var regex = fragments.binders.text._expr; var content = node.nodeValue; if (content.match(regex)) { var match, lastIndex = 0, parts = [], fragment = document.createDocumentFragment(); while ((match = regex.exec(content))) { parts.push(content.slice(lastIndex, regex.lastIndex - match[0].length)); parts.push(match[0]); lastIndex = regex.lastIndex; } parts.push(content.slice(lastIndex)); parts = parts.filter(notEmpty); node.nodeValue = parts[0]; for (var i = 1; i < parts.length; i++) { var newTextNode = document.createTextNode(parts[i]); newTextNode.processed = true; fragment.appendChild(newTextNode); } node.parentNode.insertBefore(fragment, node.nextSibling); } } }
javascript
{ "resource": "" }
q8668
ethCopticToJDN
train
function ethCopticToJDN(year, month, day, era) { return (era + 365) + 365 * (year - 1) + Math.floor(year / 4) + 30 * month + day - 31; }
javascript
{ "resource": "" }
q8669
jdnToGregorian
train
function jdnToGregorian(jdn, JD_OFFSET = JD_EPOCH_OFFSET_GREGORIAN, leapYear = isGregorianLeap) { const nMonths = 12; const monthDays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const r2000 = mod((jdn - JD_OFFSET), 730485); const r400 = mod((jdn - JD_OFFSET), 146097); const r100 = mod(r400, 36524); const r4 = mod(r100, 1461); let n = mod(r4, 365) + 365 * Math.floor(r4 / 1460); const s = Math.floor(r4 / 1095); const aprime = 400 * Math.floor((jdn - JD_OFFSET) / 146097) + 100 * Math.floor(r400 / 36524) + 4 * Math.floor(r100 / 1461) + Math.floor(r4 / 365) - Math.floor(r4 / 1460) - Math.floor(r2000 / 730484); const year = aprime + 1; const t = Math.floor((364 + s - n) / 306); let month = t * (Math.floor(n / 31) + 1) + (1 - t) * (Math.floor((5 * (n - s) + 13) / 153) + 1); n += 1 - Math.floor(r2000 / 730484); let day = n; if ((r100 === 0) && (n === 0) && (r400 !== 0)) { month = 12; day = 31; } else { monthDays[2] = (leapYear(year)) ? 29 : 28; for (let i = 1; i <= nMonths; i += 1) { if (n <= monthDays[i]) { day = n; break; } n -= monthDays[i]; } } return { year, month, day }; }
javascript
{ "resource": "" }
q8670
guessEra
train
function guessEra(jdn, JD_AM = JD_EPOCH_OFFSET_AMETE_MIHRET, JD_AA = JD_EPOCH_OFFSET_AMETE_ALEM) { return (jdn >= (JD_AM + 365)) ? JD_AM : JD_AA; }
javascript
{ "resource": "" }
q8671
gregorianToJDN
train
function gregorianToJDN(year = 1, month = 1, day = 1, JD_OFFSET = JD_EPOCH_OFFSET_GREGORIAN) { const s = Math.floor(year / 4) - Math.floor((year - 1) / 4) - Math.floor(year / 100) + Math.floor((year - 1) / 100) + Math.floor(year / 400) - Math.floor((year - 1) / 400); const t = Math.floor((14 - month) / 12); const n = 31 * t * (month - 1) + (1 - t) * (59 + s + 30 * (month - 3) + Math.floor((3 * month - 7) / 5)) + day - 1; const j = JD_OFFSET + 365 * (year - 1) + Math.floor((year - 1) / 4) - Math.floor((year - 1) / 100) + Math.floor((year - 1) / 400) + n; return j; }
javascript
{ "resource": "" }
q8672
jdnToEthiopic
train
function jdnToEthiopic(jdn, era = JD_EPOCH_OFFSET_AMETE_MIHRET) { const r = mod((jdn - era), 1461); const n = mod(r, 365) + 365 * Math.floor(r / 1460); const year = 4 * Math.floor((jdn - era) / 1461) + Math.floor(r / 365) - Math.floor(r / 1460); const month = Math.floor(n / 30) + 1; const day = mod(n, 30) + 1; return { year, month, day }; }
javascript
{ "resource": "" }
q8673
Fragments
train
function Fragments(options) { if (!options || !options.observations) { throw new TypeError('Must provide an observations instance to Fragments in options.'); } this.compiling = false; this.observations = options.observations; this.globals = options.observations.globals; this.formatters = options.observations.formatters; this.animations = {}; this.animateAttribute = 'animate'; this.binders = { element: { _wildcards: [] }, attribute: { _wildcards: [], _expr: /{{\s*(.*?)\s*}}(?!})/g, _delimitersOnlyInDefault: false }, text: { _wildcards: [], _expr: /{{\s*(.*?)\s*}}(?!})/g } }; // Text binder for text nodes with expressions in them this.registerText('__default__', registerTextDefault); function registerTextDefault(value) { this.element.textContent = (value != null) ? value : ''; } // Text binder for text nodes with expressions in them to be converted to HTML this.registerText('{*}', function(value) { if (this.content) { this.content.remove(); this.content = null; } if (typeof value === 'string' && value || value instanceof Node) { this.content = View.makeInstanceOf(toFragment(value)); this.element.parentNode.insertBefore(this.content, this.element.nextSibling); } }); // Catchall attribute binder for regular attributes with expressions in them this.registerAttribute('__default__', function(value) { if (value != null) { this.element.setAttribute(this.name, value); } else { this.element.removeAttribute(this.name); } }); this.addOptions(options); }
javascript
{ "resource": "" }
q8674
train
function(html) { if (!html) { throw new TypeError('Invalid html, cannot create a template from: ' + html); } var fragment = toFragment(html); if (fragment.childNodes.length === 0) { throw new Error('Cannot create a template from ' + html + ' because it is empty.'); } var template = Template.makeInstanceOf(fragment); this.compileTemplate(template); return template; }
javascript
{ "resource": "" }
q8675
train
function(template) { if (template && !template.compiled) { // Set compiling flag on fragments, but don't turn it false until the outermost template is done var lastCompilingValue = this.compiling; this.compiling = true; // Set this before compiling so we don't get into infinite loops if there is template recursion template.compiled = true; template.bindings = compile(this, template); this.compiling = lastCompilingValue; } return template; }
javascript
{ "resource": "" }
q8676
train
function(element) { if (!element.bindings) { element.bindings = compile(this, element); View.makeInstanceOf(element); } return element; }
javascript
{ "resource": "" }
q8677
train
function(context, expr, callback, callbackContext) { if (typeof context === 'string') { callbackContext = callback; callback = expr; expr = context; context = null; } var observer = this.observations.createObserver(expr, callback, callbackContext); if (context) { observer.bind(context, true); } return observer; }
javascript
{ "resource": "" }
q8678
removeColumn
train
function removeColumn(values, col, colsPerRow) { var n = 0; for (var i = 0, l = values.length; i < l; i++) { if (i % colsPerRow !== col) values[n++] = values[i]; } values.length = n; }
javascript
{ "resource": "" }
q8679
toArray
train
function toArray(matrix, array) { for (var i = 0, l = matrix.length; i < l; i++) { array[i] = matrix[i]; } return array; }
javascript
{ "resource": "" }
q8680
getData
train
function getData(matrix, array) { toArray(matrix, array); array.rows = matrix.rows; array.cols = matrix.cols; return array; }
javascript
{ "resource": "" }
q8681
getOperation
train
function getOperation(opType) { var opname = Object.keys(APISPEC.operations) .filter(function(operation) { return operation === opType; }); if (!opname.length) { throw new ReferenceError('Operation is not supported'); } // avoid mutation return util._extend({}, APISPEC.operations[opname[0]]); }
javascript
{ "resource": "" }
q8682
getOperationContext
train
function getOperationContext(opType, options) { var operation = getOperation(opType); options = options || {}; options.visibility = !options.token ? 'public' : 'private'; options.apiRoot = APISPEC.root; operation.headers = operation.headers || {}; operation.headers['GData-Version'] = Number(APISPEC.version).toFixed(1); if (options.token) { operation.headers['Authorization'] = 'Bearer ' + options.token; delete options.token; } operation.url = tpl(operation.url, options); operation.body = options.body; operation.strictSSL = false; return operation; }
javascript
{ "resource": "" }
q8683
boundRat
train
function boundRat (r) { var f = ratToFloat(r) return [ nextafter(f, -Infinity), nextafter(f, Infinity) ] }
javascript
{ "resource": "" }
q8684
boundEdges
train
function boundEdges (points, edges) { var bounds = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = points[e[0]] var b = points[e[1]] bounds[i] = [ nextafter(Math.min(a[0], b[0]), -Infinity), nextafter(Math.min(a[1], b[1]), -Infinity), nextafter(Math.max(a[0], b[0]), Infinity), nextafter(Math.max(a[1], b[1]), Infinity) ] } return bounds }
javascript
{ "resource": "" }
q8685
boundPoints
train
function boundPoints (points) { var bounds = new Array(points.length) for (var i = 0; i < points.length; ++i) { var p = points[i] bounds[i] = [ nextafter(p[0], -Infinity), nextafter(p[1], -Infinity), nextafter(p[0], Infinity), nextafter(p[1], Infinity) ] } return bounds }
javascript
{ "resource": "" }
q8686
dedupPoints
train
function dedupPoints (floatPoints, ratPoints, floatBounds) { var numPoints = ratPoints.length var uf = new UnionFind(numPoints) // Compute rational bounds var bounds = [] for (var i = 0; i < ratPoints.length; ++i) { var p = ratPoints[i] var xb = boundRat(p[0]) var yb = boundRat(p[1]) bounds.push([ nextafter(xb[0], -Infinity), nextafter(yb[0], -Infinity), nextafter(xb[1], Infinity), nextafter(yb[1], Infinity) ]) } // Link all points with over lapping boxes boxIntersect(bounds, function (i, j) { uf.link(i, j) }) // Do 1 pass over points to combine points in label sets var noDupes = true var labels = new Array(numPoints) for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j !== i) { // Clear no-dupes flag, zero out label noDupes = false // Make each point the top-left point from its cell floatPoints[j] = [ Math.min(floatPoints[i][0], floatPoints[j][0]), Math.min(floatPoints[i][1], floatPoints[j][1]) ] } } // If no duplicates, return null to signal termination if (noDupes) { return null } var ptr = 0 for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j === i) { labels[i] = ptr floatPoints[ptr++] = floatPoints[i] } else { labels[i] = -1 } } floatPoints.length = ptr // Do a second pass to fix up missing labels for (var i = 0; i < numPoints; ++i) { if (labels[i] < 0) { labels[i] = labels[uf.find(i)] } } // Return resulting union-find data structure return labels }
javascript
{ "resource": "" }
q8687
dedupEdges
train
function dedupEdges (edges, labels, useColor) { if (edges.length === 0) { return } if (labels) { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = labels[e[0]] var b = labels[e[1]] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } else { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = e[0] var b = e[1] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } if (useColor) { edges.sort(compareLex3) } else { edges.sort(compareLex2) } var ptr = 1 for (var i = 1; i < edges.length; ++i) { var prev = edges[i - 1] var next = edges[i] if (next[0] === prev[0] && next[1] === prev[1] && (!useColor || next[2] === prev[2])) { continue } edges[ptr++] = next } edges.length = ptr }
javascript
{ "resource": "" }
q8688
snapRound
train
function snapRound (points, edges, useColor) { // 1. find edge crossings var edgeBounds = boundEdges(points, edges) var crossings = getCrossings(points, edges, edgeBounds) // 2. find t-junctions var vertBounds = boundPoints(points) var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds) // 3. cut edges, construct rational points var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor) // 4. dedupe verts var labels = dedupPoints(points, ratPoints, vertBounds) // 5. dedupe edges dedupEdges(edges, labels, useColor) // 6. check termination if (!labels) { return (crossings.length > 0 || tjunctions.length > 0) } // More iterations necessary return true }
javascript
{ "resource": "" }
q8689
cleanPSLG
train
function cleanPSLG (points, edges, colors) { // If using colors, augment edges with color data var prevEdges if (colors) { prevEdges = edges var augEdges = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] augEdges[i] = [e[0], e[1], colors[i]] } edges = augEdges } // First round: remove duplicate edges and points var modified = preRound(points, edges, !!colors) // Run snap rounding until convergence while (snapRound(points, edges, !!colors)) { modified = true } // Strip color tags if (!!colors && modified) { prevEdges.length = 0 colors.length = 0 for (var i = 0; i < edges.length; ++i) { var e = edges[i] prevEdges.push([e[0], e[1]]) colors.push(e[2]) } } return modified }
javascript
{ "resource": "" }
q8690
convertRawTheme
train
function convertRawTheme(theme) { if (!Array.isArray(theme.constants)) { return { constants: Object.keys(theme.constants).map(key => theme.constants[key]), styles: [].concat(theme.styles), animations: [].concat(theme.animations) } } else return theme; }
javascript
{ "resource": "" }
q8691
expand
train
function expand(str, opts) { opts = opts || {}; if (typeof str !== 'string') { throw new TypeError('expand-object expects a string.'); } if (!/[.|:=]/.test(str) && /,/.test(str)) { return toArray(str); } var m; if ((m = /(\w+[:=]\w+\.)+/.exec(str)) && !/[|,+]/.test(str)) { var val = m[0].split(':').join('.'); str = val + str.slice(m[0].length); } var arr = splitString(str, '|'); var len = arr.length, i = -1; var res = {}; if (isArrayLike(str) && arr.length === 1) { return expandArrayObj(str, opts); } while (++i < len) { var val = arr[i]; // test for `https://foo` if (/\w:\/\/\w/.test(val)) { res[val] = ''; continue; } var re = /^((?:\w+)\.(?:\w+))[:.]((?:\w+,)+)+((?:\w+):(?:\w+))/; var m = re.exec(val); if (m && m[1] && m[2] && m[3]) { var arrVal = m[2]; arrVal = arrVal.replace(/,$/, ''); var prop = arrVal.split(','); prop = prop.concat(toObject(m[3])); res = set(res, m[1], prop); } else if (!/[.,\|:=]/.test(val)) { res[val] = opts.toBoolean ? true : ''; } else { res = expandObject(res, val, opts); } } return res; }
javascript
{ "resource": "" }
q8692
getService
train
function getService (classList) { let service Object.keys(services).forEach(key => { if (classList.contains('socialshares-' + key)) { service = services[key] service.name = key } }) return service }
javascript
{ "resource": "" }
q8693
openDialog
train
function openDialog (url) { const width = socialshares.config.dialog.width const height = socialshares.config.dialog.height // Center the popup const top = (window.screen.height / 2 - height / 2) const left = (window.screen.width / 2 - width / 2) window.open(url, 'Share', `width=${width},height=${height},top=${top},left=${left},menubar=no,toolbar=no,resizable=yes,scrollbars=yes`) }
javascript
{ "resource": "" }
q8694
fetchData
train
async function fetchData(key, transformation, cacheMiss) { // TODO: needs better caching logic var data = cache.get(key); if (data) { return data; } try { data = transformation(await cacheMiss()); } catch (err) { throw new Error('The response contains invalid data'); } cache.put(key, data); return data; }
javascript
{ "resource": "" }
q8695
querySheetInfo
train
async function querySheetInfo(sheetId) { var key = util.createIdentifier('sheet_info', sheetId); return await fetchData(key, api.converter.sheetInfoResponse, () => executeRequest('sheet_info', {sheetId: sheetId}) ); }
javascript
{ "resource": "" }
q8696
createWorksheet
train
async function createWorksheet(sheetId, worksheetTitle, options) { options = Object.assign({ title: worksheetTitle }, options); let payload = api.converter.createWorksheetRequest(options); let response = await executeRequest('create_worksheet', { body: payload, sheetId: sheetId }); cache.clear(); // converts worksheetData to model return api.converter.workSheetInfoResponse(response); }
javascript
{ "resource": "" }
q8697
dropWorksheet
train
async function dropWorksheet(sheetId, worksheetId) { let response = await executeRequest('drop_worksheet', { sheetId: sheetId, worksheetId: worksheetId }); cache.clear(); return response; }
javascript
{ "resource": "" }
q8698
insertEntries
train
async function insertEntries(worksheetInfo, entries, options) { let response; let insertEntry = (entry) => { var payload = Object.assign({ body: api.converter.createEntryRequest(entry) }, worksheetInfo ); return executeRequest('create_entry', payload); }; if (options.ordered) { for (let entry of entries) { response = await insertEntry(entry); } } else { response = await Promise.all(entries.map(entry => insertEntry(entry))); } cache.clear(); return response; }
javascript
{ "resource": "" }
q8699
updateEntries
train
async function updateEntries(worksheetInfo, entries) { let requests = entries.map(entry => { var payload = Object.assign({ body: api.converter.updateEntryRequest(entry), entityId: entry._id }, worksheetInfo ); return executeRequest('update_entry', payload); }); let response = Promise.all(requests); cache.clear(); return response; }
javascript
{ "resource": "" }