_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q62200
_clearNumericRefinements
test
function _clearNumericRefinements(attribute) { if (isUndefined(attribute)) { if (isEmpty(this.numericRefinements)) return this.numericRefinements; return {}; } else if (isString(attribute)) { if (isEmpty(this.numericRefinements[attribute])) return this.numericRefinements; return omit(this.numericRefinements, attribute); } else if (isFunction(attribute)) { var hasChanged = false; var newNumericRefinements = reduce(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach(operators, function(values, operator) { var outValues = []; forEach(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty(outValues)) { if (outValues.length !== values.length) hasChanged = true; operatorList[operator] = outValues; } else hasChanged = true; }); if (!isEmpty(operatorList)) memo[key] = operatorList; return memo; }, {}); if (hasChanged) return newNumericRefinements; return this.numericRefinements; } }
javascript
{ "resource": "" }
q62201
addHierarchicalFacet
test
function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }
javascript
{ "resource": "" }
q62202
addFacetRefinement
test
function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }
javascript
{ "resource": "" }
q62203
addExcludeRefinement
test
function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }
javascript
{ "resource": "" }
q62204
addDisjunctiveFacetRefinement
test
function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }
javascript
{ "resource": "" }
q62205
addTagRefinement
test
function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }
javascript
{ "resource": "" }
q62206
removeFacet
test
function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter(this.facets, function(f) { return f !== facet; }) }); }
javascript
{ "resource": "" }
q62207
removeDisjunctiveFacet
test
function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }
javascript
{ "resource": "" }
q62208
removeHierarchicalFacet
test
function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }
javascript
{ "resource": "" }
q62209
removeFacetRefinement
test
function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }
javascript
{ "resource": "" }
q62210
removeExcludeRefinement
test
function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }
javascript
{ "resource": "" }
q62211
removeDisjunctiveFacetRefinement
test
function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }
javascript
{ "resource": "" }
q62212
removeTagRefinement
test
function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }
javascript
{ "resource": "" }
q62213
toggleFacetRefinement
test
function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }
javascript
{ "resource": "" }
q62214
test
function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }
javascript
{ "resource": "" }
q62215
isFacetRefined
test
function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }
javascript
{ "resource": "" }
q62216
isExcludeRefined
test
function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }
javascript
{ "resource": "" }
q62217
getRefinedDisjunctiveFacets
test
function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection( keys(this.numericRefinements), this.disjunctiveFacets ); return keys(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }
javascript
{ "resource": "" }
q62218
setParameter
test
function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }
javascript
{ "resource": "" }
q62219
setQueryParameters
test
function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys(params); forEach(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }
javascript
{ "resource": "" }
q62220
test
function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map(path, trim); }
javascript
{ "resource": "" }
q62221
runCommand
test
function runCommand(cmd, args) { var prev = null; console.log(chalk.cyanBright(cmd) + " " + args.map(arg => { if (arg.startsWith("-")) return chalk.gray("\\") + "\n " + chalk.bold(arg); return arg; }).join(" ") + "\n"); var proc = child_process.spawnSync(cmd, args, { stdio: "inherit" }); if (proc.error) throw proc.error; if (proc.status !== 0) throw Error("exited with " + proc.status); return proc; }
javascript
{ "resource": "" }
q62222
compileIntrinsics
test
function compileIntrinsics() { var target = path.join(sourceDirectory, "passes", "WasmIntrinsics.cpp"); runCommand("python", [ path.join(binaryenDirectory, "scripts", "embedwast.py"), path.join(sourceDirectory, "passes", "wasm-intrinsics.wast"), target ]); sourceFiles.push(target); }
javascript
{ "resource": "" }
q62223
compileShared
test
function compileShared() { runCommand("python", [ path.join(emscriptenDirectory, "em++") ].concat(sourceFiles).concat(commonOptions).concat([ "-o", "shared.bc" ])); }
javascript
{ "resource": "" }
q62224
compileJs
test
function compileJs(options) { runCommand("python", [ path.join(emscriptenDirectory, "em++"), "shared.bc" ].concat(commonOptions).concat([ "--post-js", options.post, "--closure", "1", "-s", "WASM=0", "-s", "EXPORTED_FUNCTIONS=[" + exportedFunctionsArg + "]", "-s", "ALLOW_MEMORY_GROWTH=1", "-s", "ELIMINATE_DUPLICATE_FUNCTIONS=1", "-s", "MODULARIZE_INSTANCE=1", "-s", "EXPORT_NAME=\"Binaryen\"", "-o", options.out, "-Oz" ])); }
javascript
{ "resource": "" }
q62225
compileWasm
test
function compileWasm(options) { run("python", [ path.join(emscriptenDirectory, "em++"), "shared.bc" ].concat(commonOptions).concat([ "--post-js", options.post, "--closure", "1", "-s", "EXPORTED_FUNCTIONS=[" + exportedFunctionsArg + "]", "-s", "ALLOW_MEMORY_GROWTH=1", "-s", "BINARYEN=1", "-s", "BINARYEN_METHOD=\"native-wasm\"", "-s", "MODULARIZE_INSTANCE=1", "-s", "EXPORT_NAME=\"Binaryen\"", "-o", options.out, "-Oz" ])); }
javascript
{ "resource": "" }
q62226
pluginState
test
function pluginState () { return { _sync: { signedIn: false, userId: null, unsubscribe: {}, pathVariables: {}, patching: false, syncStack: { inserts: [], updates: {}, propDeletions: {}, deletions: [], debounceTimer: null, }, fetched: {}, stopPatchingTimeout: null } }; }
javascript
{ "resource": "" }
q62227
helpers
test
function helpers(originVal, newVal) { if (isArray(originVal) && isArrayHelper(newVal)) { newVal = newVal.executeOn(originVal); } if (isNumber(originVal) && isIncrementHelper(newVal)) { newVal = newVal.executeOn(originVal); } return newVal; // always return newVal as fallback!! }
javascript
{ "resource": "" }
q62228
makeBatchFromSyncstack
test
function makeBatchFromSyncstack(state, getters, Firebase, batchMaxCount) { if (batchMaxCount === void 0) { batchMaxCount = 500; } // get state & getter variables var firestorePath = state._conf.firestorePath; var firestorePathComplete = getters.firestorePathComplete; var dbRef = getters.dbRef; var collectionMode = getters.collectionMode; // make batch var batch = Firebase.firestore().batch(); var log = {}; var count = 0; // Add 'updates' to batch var updates = grabUntilApiLimit('updates', count, batchMaxCount, state); log['updates: '] = updates; count = count + updates.length; // Add to batch updates.forEach(function (item) { var id = item.id; var docRef = (collectionMode) ? dbRef.doc(id) : dbRef; if (state._conf.sync.guard.includes('id')) delete item.id; // @ts-ignore batch.update(docRef, item); }); // Add 'propDeletions' to batch var propDeletions = grabUntilApiLimit('propDeletions', count, batchMaxCount, state); log['prop deletions: '] = propDeletions; count = count + propDeletions.length; // Add to batch propDeletions.forEach(function (item) { var id = item.id; var docRef = (collectionMode) ? dbRef.doc(id) : dbRef; if (state._conf.sync.guard.includes('id')) delete item.id; // @ts-ignore batch.update(docRef, item); }); // Add 'deletions' to batch var deletions = grabUntilApiLimit('deletions', count, batchMaxCount, state); log['deletions: '] = deletions; count = count + deletions.length; // Add to batch deletions.forEach(function (id) { var docRef = dbRef.doc(id); batch.delete(docRef); }); // Add 'inserts' to batch var inserts = grabUntilApiLimit('inserts', count, batchMaxCount, state); log['inserts: '] = inserts; count = count + inserts.length; // Add to batch inserts.forEach(function (item) { var newRef = dbRef.doc(item.id); batch.set(newRef, item); }); // log the batch contents if (state._conf.logging) { console.group('[vuex-easy-firestore] api call batch:'); console.log("%cFirestore PATH: " + firestorePathComplete + " [" + firestorePath + "]", 'color: grey'); Object.keys(log).forEach(function (key) { console.log(key, log[key]); }); console.groupEnd(); } return batch; }
javascript
{ "resource": "" }
q62229
iniModule
test
function iniModule (userConfig, FirebaseDependency) { // prepare state._conf var conf = copy(merge({ state: {}, mutations: {}, actions: {}, getters: {} }, defaultConfig, userConfig)); if (!errorCheck(conf)) return; var userState = conf.state; var userMutations = conf.mutations; var userActions = conf.actions; var userGetters = conf.getters; delete conf.state; delete conf.mutations; delete conf.actions; delete conf.getters; // prepare rest of state var docContainer = {}; if (conf.statePropName) docContainer[conf.statePropName] = {}; var restOfState = merge(userState, docContainer); // if 'doc' mode, set merge initial state onto default values if (conf.firestoreRefType === 'doc') { var defaultValsInState = (conf.statePropName) ? restOfState[conf.statePropName] : restOfState; conf.sync.defaultValues = copy(merge(defaultValsInState, conf.sync.defaultValues)); } return { namespaced: true, state: merge(pluginState(), restOfState, { _conf: conf }), mutations: merge(userMutations, pluginMutations(merge(userState, { _conf: conf }))), actions: merge(userActions, pluginActions(FirebaseDependency)), getters: merge(userGetters, pluginGetters(FirebaseDependency)) }; }
javascript
{ "resource": "" }
q62230
setDefaultValues
test
function setDefaultValues (obj, defaultValues) { if (!isWhat.isPlainObject(defaultValues)) console.error('[vuex-easy-firestore] Trying to merge target:', obj, 'onto a non-object (defaultValues):', defaultValues); if (!isWhat.isPlainObject(obj)) console.error('[vuex-easy-firestore] Trying to merge a non-object:', obj, 'onto the defaultValues:', defaultValues); var result = merge({ extensions: [convertTimestamps] }, defaultValues, obj); return findAndReplaceAnything.findAndReplace(result, '%convertTimestamp%', null, { onlyPlainObjects: true }); }
javascript
{ "resource": "" }
q62231
getId
test
function getId(payloadPiece, conf, path, fullPayload) { if (isWhat.isString(payloadPiece)) return payloadPiece; if (isWhat.isPlainObject(payloadPiece)) { if ('id' in payloadPiece) return payloadPiece.id; var keys = Object.keys(payloadPiece); if (keys.length === 1) return keys[0]; } return ''; }
javascript
{ "resource": "" }
q62232
vuexEasyFirestore
test
function vuexEasyFirestore(easyFirestoreModule, _a) { var _b = _a === void 0 ? { logging: false, preventInitialDocInsertion: false, FirebaseDependency: Firebase$2 } : _a, _c = _b.logging, logging = _c === void 0 ? false : _c, _d = _b.preventInitialDocInsertion, preventInitialDocInsertion = _d === void 0 ? false : _d, _e = _b.FirebaseDependency, FirebaseDependency = _e === void 0 ? Firebase$2 : _e; if (FirebaseDependency) { setFirebaseDependency(FirebaseDependency); setFirebaseDependency$1(FirebaseDependency); } return function (store) { // Get an array of config files if (!isWhat.isArray(easyFirestoreModule)) easyFirestoreModule = [easyFirestoreModule]; // Create a module for each config file easyFirestoreModule.forEach(function (config) { config.logging = logging; if (config.sync && config.sync.preventInitialDocInsertion === undefined) { config.sync.preventInitialDocInsertion = preventInitialDocInsertion; } var moduleName = vuexEasyAccess.getKeysFromPath(config.moduleName); store.registerModule(moduleName, iniModule(config, FirebaseDependency)); }); }; }
javascript
{ "resource": "" }
q62233
parseCSV
test
function parseCSV(csvFilePath, attributeFields) { return new Promise((resolve, reject) => { try { csv(csvFilePath, data => resolve(_transformToHierarchy(data, attributeFields))); // lol hello Lisp } catch (err) { reject(err); } }); }
javascript
{ "resource": "" }
q62234
parseJSON
test
function parseJSON(jsonFilePath) { return new Promise((resolve, reject) => { try { json(jsonFilePath, data => resolve([data])); } catch (err) { reject(err); } }); }
javascript
{ "resource": "" }
q62235
parseFlatJSON
test
function parseFlatJSON(jsonFilePath, attributeFields) { return new Promise((resolve, reject) => { try { json(jsonFilePath, data => resolve(_transformToHierarchy(data, attributeFields))); } catch (err) { reject(err); } }); }
javascript
{ "resource": "" }
q62236
checkPropTypes
test
function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (true) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ) } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } }
javascript
{ "resource": "" }
q62237
invokeGuardedCallback
test
function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { hasError = false; caughtError = null; invokeGuardedCallbackImpl$1.apply(reporter, arguments); }
javascript
{ "resource": "" }
q62238
getClosestInstanceFromNode
test
function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } while (!node[internalInstanceKey]) { if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var inst = node[internalInstanceKey]; if (inst.tag === HostComponent || inst.tag === HostText) { // In Fiber, this will always be the deepest root. return inst; } return null; }
javascript
{ "resource": "" }
q62239
getInstanceFromNode$1
test
function getInstanceFromNode$1(node) { var inst = node[internalInstanceKey]; if (inst) { if (inst.tag === HostComponent || inst.tag === HostText) { return inst; } else { return null; } } return null; }
javascript
{ "resource": "" }
q62240
getNodeFromInstance$1
test
function getNodeFromInstance$1(inst) { if (inst.tag === HostComponent || inst.tag === HostText) { // In Fiber this, is just the state node right now. We assume it will be // a host component or host text. return inst.stateNode; } // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. invariant(false, 'getNodeFromInstance: Invalid argument.'); }
javascript
{ "resource": "" }
q62241
traverseEnterLeave
test
function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (true) { if (!from) { break; } if (from === common) { break; } var alternate = from.alternate; if (alternate !== null && alternate === common) { break; } pathFrom.push(from); from = getParent(from); } var pathTo = []; while (true) { if (!to) { break; } if (to === common) { break; } var _alternate = to.alternate; if (_alternate !== null && _alternate === common) { break; } pathTo.push(to); to = getParent(to); } for (var i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (var _i = pathTo.length; _i-- > 0;) { fn(pathTo[_i], 'captured', argTo); } }
javascript
{ "resource": "" }
q62242
makePrefixMap
test
function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; return prefixes; }
javascript
{ "resource": "" }
q62243
test
function () { var Interface = this.constructor.Interface; for (var propName in Interface) { { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } } this.dispatchConfig = null; this._targetInst = null; this.nativeEvent = null; this.isDefaultPrevented = functionThatReturnsFalse; this.isPropagationStopped = functionThatReturnsFalse; this._dispatchListeners = null; this._dispatchInstances = null; { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse)); Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {})); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {})); } }
javascript
{ "resource": "" }
q62244
getCompositionEventType
test
function getCompositionEventType(topLevelType) { switch (topLevelType) { case TOP_COMPOSITION_START: return eventTypes.compositionStart; case TOP_COMPOSITION_END: return eventTypes.compositionEnd; case TOP_COMPOSITION_UPDATE: return eventTypes.compositionUpdate; } }
javascript
{ "resource": "" }
q62245
isFallbackCompositionEnd
test
function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case TOP_KEY_UP: // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case TOP_KEY_DOWN: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case TOP_KEY_PRESS: case TOP_MOUSE_DOWN: case TOP_BLUR: // Events are not possible without cancelling IME. return true; default: return false; } }
javascript
{ "resource": "" }
q62246
getValueForProperty
test
function getValueForProperty(node, name, expected, propertyInfo) { { if (propertyInfo.mustUseProperty) { var propertyName = propertyInfo.propertyName; return node[propertyName]; } else { var attributeName = propertyInfo.attributeName; var stringValue = null; if (propertyInfo.type === OVERLOADED_BOOLEAN) { if (node.hasAttribute(attributeName)) { var value = node.getAttribute(attributeName); if (value === '') { return true; } if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return value; } if (value === '' + expected) { return expected; } return value; } } else if (node.hasAttribute(attributeName)) { if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { // We had an attribute but shouldn't have had one, so read it // for the error message. return node.getAttribute(attributeName); } if (propertyInfo.type === BOOLEAN) { // If this was a boolean, it doesn't matter what the value is // the fact that we have it is the same as the expected. return expected; } // Even if this property uses a namespace we use getAttribute // because we assume its namespaced name is the same as our config. // To use getAttributeNS we need the local name which we don't have // in our config atm. stringValue = node.getAttribute(attributeName); } if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return stringValue === null ? expected : stringValue; } else if (stringValue === '' + expected) { return expected; } else { return stringValue; } } } }
javascript
{ "resource": "" }
q62247
getTargetInstForInputEventPolyfill
test
function getTargetInstForInputEventPolyfill(topLevelType, targetInst) { if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. return getInstIfValueChanged(activeElementInst); } }
javascript
{ "resource": "" }
q62248
test
function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER; var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT; if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (!isOutEvent && !isOverEvent) { // Must not be a mouse or pointer in or out - ignoring. return null; } var win = void 0; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from = void 0; var to = void 0; if (isOutEvent) { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var eventInterface = void 0, leaveEventType = void 0, enterEventType = void 0, eventTypePrefix = void 0; if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) { eventInterface = SyntheticMouseEvent; leaveEventType = eventTypes$2.mouseLeave; enterEventType = eventTypes$2.mouseEnter; eventTypePrefix = 'mouse'; } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) { eventInterface = SyntheticPointerEvent; leaveEventType = eventTypes$2.pointerLeave; enterEventType = eventTypes$2.pointerEnter; eventTypePrefix = 'pointer'; } var fromNode = from == null ? win : getNodeFromInstance$1(from); var toNode = to == null ? win : getNodeFromInstance$1(to); var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget); leave.type = eventTypePrefix + 'leave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget); enter.type = eventTypePrefix + 'enter'; enter.target = toNode; enter.relatedTarget = fromNode; accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; }
javascript
{ "resource": "" }
q62249
listenTo
test
function listenTo(registrationName, mountAt) { var isListening = getListeningForDocument(mountAt); var dependencies = registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { switch (dependency) { case TOP_SCROLL: trapCapturedEvent(TOP_SCROLL, mountAt); break; case TOP_FOCUS: case TOP_BLUR: trapCapturedEvent(TOP_FOCUS, mountAt); trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function, // but this ensures we mark both as attached rather than just one. isListening[TOP_BLUR] = true; isListening[TOP_FOCUS] = true; break; case TOP_CANCEL: case TOP_CLOSE: if (isEventSupported(getRawEventName(dependency))) { trapCapturedEvent(dependency, mountAt); } break; case TOP_INVALID: case TOP_SUBMIT: case TOP_RESET: // We listen to them on the target DOM elements. // Some of them bubble so we don't want them to fire twice. break; default: // By default, listen on the top level to all non-media events. // Media events don't bubble so adding the listener wouldn't do anything. var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1; if (!isMediaEvent) { trapBubbledEvent(dependency, mountAt); } break; } isListening[dependency] = true; } } }
javascript
{ "resource": "" }
q62250
getEventTargetDocument
test
function getEventTargetDocument(eventTarget) { return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument; }
javascript
{ "resource": "" }
q62251
constructSelectEvent
test
function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. var doc = getEventTargetDocument(nativeEventTarget); if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement$1); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement$1; accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; }
javascript
{ "resource": "" }
q62252
test
function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) { firstChild.nodeValue = text; return; } } node.textContent = text; }
javascript
{ "resource": "" }
q62253
createDangerousStringForStyles
test
function createDangerousStringForStyles(styles) { { var serialized = ''; var delimiter = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (styleValue != null) { var isCustomProperty = styleName.indexOf('--') === 0; serialized += delimiter + hyphenateStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty); delimiter = ';'; } } return serialized || null; } }
javascript
{ "resource": "" }
q62254
test
function (containerChildSet, workInProgress) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; while (node !== null) { if (node.tag === HostComponent || node.tag === HostText) { appendChildToContainerChildSet(containerChildSet, node.stateNode); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } }
javascript
{ "resource": "" }
q62255
safelyCallComponentWillUnmount
test
function safelyCallComponentWillUnmount(current$$1, instance) { { invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance); if (hasCaughtError()) { var unmountError = clearCaughtError(); captureCommitPhaseError(current$$1, unmountError); } } }
javascript
{ "resource": "" }
q62256
computeUniqueAsyncExpiration
test
function computeUniqueAsyncExpiration() { var currentTime = requestCurrentTime(); var result = computeAsyncExpiration(currentTime); if (result <= lastUniqueAsyncExpiration) { // Since we assume the current time monotonically increases, we only hit // this branch when computeUniqueAsyncExpiration is fired multiple times // within a 200ms window (or whatever the async bucket size is). result = lastUniqueAsyncExpiration + 1; } lastUniqueAsyncExpiration = result; return lastUniqueAsyncExpiration; }
javascript
{ "resource": "" }
q62257
stringify
test
function stringify(content) { if (typeof content === 'string' && stringifiedRegexp.test(content)) { return content; } return JSON.stringify(content, null, 2); }
javascript
{ "resource": "" }
q62258
getLoaderOptions
test
function getLoaderOptions(loaderPath, rule) { let multiRuleProp; if (isWebpack1) { multiRuleProp = 'loaders'; } else if (rule.oneOf) { multiRuleProp = 'oneOf'; } else { multiRuleProp = 'use'; } const multiRule = typeof rule === 'object' && Array.isArray(rule[multiRuleProp]) ? rule[multiRuleProp] : null; let options; if (multiRule) { const rules = [].concat(...multiRule.map(r => (r.use || r))); options = rules.map(normalizeRule).find(r => loaderPath.includes(r.loader)).options; } else { options = normalizeRule(rule).options; } return options; }
javascript
{ "resource": "" }
q62259
normalizeRule
test
function normalizeRule(rule) { if (!rule) { throw new Error('Rule should be string or object'); } let data; if (typeof rule === 'string') { const parts = rule.split('?'); data = { loader: parts[0], options: parts[1] ? parseQuery(`?${parts[1]}`) : null }; } else { const options = isWebpack1 ? rule.query : rule.options; data = { loader: rule.loader, options: options || null }; } return data; }
javascript
{ "resource": "" }
q62260
findParent
test
function findParent(node, handle) { let current = node while (current) { if (handle(current)) { return current } current = current.parent } }
javascript
{ "resource": "" }
q62261
pure
test
function pure(node, withChildren, after) { var _this2 = this; var t = assign$1({}, node); delete t._id; delete t.parent; delete t.children; delete t.open; delete t.active; delete t.style; delete t.class; delete t.innerStyle; delete t.innerClass; delete t.innerBackStyle; delete t.innerBackClass; var _arr = keys$1(t); for (var _i = 0; _i < _arr.length; _i++) { var key = _arr[_i]; if (key[0] === '_') { delete t[key]; } } if (withChildren && node.children) { t.children = node.children.slice(); t.children.forEach(function (v, k) { t.children[k] = _this2.pure(v, withChildren); }); } if (after) { return after(t, node) || t; } return t; }
javascript
{ "resource": "" }
q62262
offset2
test
function offset2() { return { x: this.offset.x + this.nodeInnerEl.offsetWidth, y: this.offset.y + this.nodeInnerEl.offsetHeight }; }
javascript
{ "resource": "" }
q62263
offsetToViewPort
test
function offsetToViewPort() { var r = this.nodeInnerEl.getBoundingClientRect(); r.x = r.left; r.y = r.top; return r; }
javascript
{ "resource": "" }
q62264
currentTreeRootSecondChildExcludingDragging
test
function currentTreeRootSecondChildExcludingDragging() { var _this = this; return this.currentTree.rootData.children.slice(0, 3).filter(function (v) { return v !== _this.node; })[1]; }
javascript
{ "resource": "" }
q62265
appendPrev
test
function appendPrev(info) { if (isNodeDroppable(info.targetPrev)) { th.appendTo(info.dplh, info.targetPrev); if (!info.targetPrev.open) info.store.toggleOpen(info.targetPrev); } else { insertDplhAfterTo(info.dplh, info.targetPrev, info); } }
javascript
{ "resource": "" }
q62266
appendCurrentTree
test
function appendCurrentTree(info) { if (isNodeDroppable(info.currentTree.rootData)) { th.appendTo(info.dplh, info.currentTree.rootData); } }
javascript
{ "resource": "" }
q62267
stripViewFromSelector
test
function stripViewFromSelector (selector) { // Don't strip it out if it's one of these 4 element types // (see https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m for reference) const keepView = [ 'XCUIElementTypeScrollView', 'XCUIElementTypeCollectionView', 'XCUIElementTypeTextView', 'XCUIElementTypeWebView', ].includes(selector); if (!keepView && selector.indexOf('View') === selector.length - 4) { return selector.substr(0, selector.length - 4); } else { return selector; } }
javascript
{ "resource": "" }
q62268
getPidUsingPattern
test
async function getPidUsingPattern (pgrepPattern) { const args = ['-nif', pgrepPattern]; try { const {stdout} = await exec('pgrep', args); const pid = parseInt(stdout, 10); if (isNaN(pid)) { log.debug(`Cannot parse process id from 'pgrep ${args.join(' ')}' output: ${stdout}`); return null; } return `${pid}`; } catch (err) { log.debug(`'pgrep ${args.join(' ')}' didn't detect any matching processes. Return code: ${err.code}`); return null; } }
javascript
{ "resource": "" }
q62269
killAppUsingPattern
test
async function killAppUsingPattern (pgrepPattern) { for (const signal of [2, 15, 9]) { if (!await getPidUsingPattern(pgrepPattern)) { return; } const args = [`-${signal}`, '-if', pgrepPattern]; try { await exec('pkill', args); } catch (err) { log.debug(`pkill ${args.join(' ')} -> ${err.message}`); } await B.delay(100); } }
javascript
{ "resource": "" }
q62270
getPIDsListeningOnPort
test
async function getPIDsListeningOnPort (port, filteringFunc = null) { const result = []; try { // This only works since Mac OS X El Capitan const {stdout} = await exec('lsof', ['-ti', `tcp:${port}`]); result.push(...(stdout.trim().split(/\n+/))); } catch (e) { return result; } if (!_.isFunction(filteringFunc)) { return result; } return await B.filter(result, async (x) => { const {stdout} = await exec('ps', ['-p', x, '-o', 'command']); return await filteringFunc(stdout); }); }
javascript
{ "resource": "" }
q62271
removeAllSessionWebSocketHandlers
test
async function removeAllSessionWebSocketHandlers (server, sessionId) { if (!server || !_.isFunction(server.getWebSocketHandlers)) { return; } const activeHandlers = await server.getWebSocketHandlers(sessionId); for (const pathname of _.keys(activeHandlers)) { await server.removeWebSocketHandler(pathname); } }
javascript
{ "resource": "" }
q62272
verifyApplicationPlatform
test
async function verifyApplicationPlatform (app, isSimulator) { log.debug('Verifying application platform'); const infoPlist = path.resolve(app, 'Info.plist'); if (!await fs.exists(infoPlist)) { log.debug(`'${infoPlist}' does not exist`); return null; } const {CFBundleSupportedPlatforms} = await plist.parsePlistFile(infoPlist); log.debug(`CFBundleSupportedPlatforms: ${JSON.stringify(CFBundleSupportedPlatforms)}`); if (!_.isArray(CFBundleSupportedPlatforms)) { log.debug(`CFBundleSupportedPlatforms key does not exist in '${infoPlist}'`); return null; } const isAppSupported = (isSimulator && CFBundleSupportedPlatforms.includes('iPhoneSimulator')) || (!isSimulator && CFBundleSupportedPlatforms.includes('iPhoneOS')); if (isAppSupported) { return true; } throw new Error(`${isSimulator ? 'Simulator' : 'Real device'} architecture is unsupported by the '${app}' application. ` + `Make sure the correct deployment target has been selected for its compilation in Xcode.`); }
javascript
{ "resource": "" }
q62273
isLocalHost
test
function isLocalHost (urlString) { try { const {hostname} = url.parse(urlString); return ['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(hostname); } catch { log.warn(`'${urlString}' cannot be parsed as a valid URL`); } return false; }
javascript
{ "resource": "" }
q62274
normalizePlatformVersion
test
function normalizePlatformVersion (originalVersion) { const normalizedVersion = util.coerceVersion(originalVersion, false); if (!normalizedVersion) { throw new Error(`The platform version '${originalVersion}' should be a valid version number`); } const {major, minor} = new semver.SemVer(normalizedVersion); return `${major}.${minor}`; }
javascript
{ "resource": "" }
q62275
updateProjectFile
test
async function updateProjectFile (agentPath, newBundleId) { let projectFilePath = `${agentPath}/${PROJECT_FILE}`; try { // Assuming projectFilePath is in the correct state, create .old from projectFilePath await fs.copyFile(projectFilePath, `${projectFilePath}.old`); await replaceInFile(projectFilePath, new RegExp(WDA_RUNNER_BUNDLE_ID.replace('.', '\.'), 'g'), newBundleId); // eslint-disable-line no-useless-escape log.debug(`Successfully updated '${projectFilePath}' with bundle id '${newBundleId}'`); } catch (err) { log.debug(`Error updating project file: ${err.message}`); log.warn(`Unable to update project file '${projectFilePath}' with ` + `bundle id '${newBundleId}'. WebDriverAgent may not start`); } }
javascript
{ "resource": "" }
q62276
resetProjectFile
test
async function resetProjectFile (agentPath) { let projectFilePath = `${agentPath}/${PROJECT_FILE}`; try { // restore projectFilePath from .old file if (!await fs.exists(`${projectFilePath}.old`)) { return; // no need to reset } await fs.mv(`${projectFilePath}.old`, projectFilePath); log.debug(`Successfully reset '${projectFilePath}' with bundle id '${WDA_RUNNER_BUNDLE_ID}'`); } catch (err) { log.debug(`Error resetting project file: ${err.message}`); log.warn(`Unable to reset project file '${projectFilePath}' with ` + `bundle id '${WDA_RUNNER_BUNDLE_ID}'. WebDriverAgent has been ` + `modified and not returned to the original state.`); } }
javascript
{ "resource": "" }
q62277
getAdditionalRunContent
test
function getAdditionalRunContent (platformName, wdaRemotePort) { const runner = `WebDriverAgentRunner${isTvOS(platformName) ? '_tvOS' : ''}`; return { [runner]: { EnvironmentVariables: { USE_PORT: wdaRemotePort } } }; }
javascript
{ "resource": "" }
q62278
getWDAUpgradeTimestamp
test
async function getWDAUpgradeTimestamp (bootstrapPath) { const carthageRootPath = path.resolve(bootstrapPath, CARTHAGE_ROOT); if (await fs.exists(carthageRootPath)) { const {mtime} = await fs.stat(carthageRootPath); return mtime.getTime(); } return null; }
javascript
{ "resource": "" }
q62279
parseContainerPath
test
async function parseContainerPath (remotePath, containerRootSupplier) { const match = CONTAINER_PATH_PATTERN.exec(remotePath); if (!match) { log.errorAndThrow(`It is expected that package identifier ` + `starts with '${CONTAINER_PATH_MARKER}' and is separated from the ` + `relative path with a single slash. '${remotePath}' is given instead`); } let [, bundleId, relativePath] = match; let containerType = null; const typeSeparatorPos = bundleId.indexOf(CONTAINER_TYPE_SEPARATOR); // We only consider container type exists if its length is greater than zero // not counting the colon if (typeSeparatorPos > 0 && typeSeparatorPos < bundleId.length - 1) { containerType = bundleId.substring(typeSeparatorPos + 1); log.debug(`Parsed container type: ${containerType}`); bundleId = bundleId.substring(0, typeSeparatorPos); } const containerRoot = _.isFunction(containerRootSupplier) ? await containerRootSupplier(bundleId, containerType) : containerRootSupplier; const resultPath = path.posix.resolve(containerRoot, relativePath); verifyIsSubPath(resultPath, containerRoot); return [bundleId, resultPath]; }
javascript
{ "resource": "" }
q62280
pushFileToSimulator
test
async function pushFileToSimulator (device, remotePath, base64Data) { const buffer = Buffer.from(base64Data, 'base64'); if (CONTAINER_PATH_PATTERN.test(remotePath)) { const [bundleId, dstPath] = await parseContainerPath(remotePath, async (appBundle, containerType) => await getAppContainer(device.udid, appBundle, null, containerType)); log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` + `Will put the data into '${dstPath}'`); if (!await fs.exists(path.dirname(dstPath))) { log.debug(`The destination folder '${path.dirname(dstPath)}' does not exist. Creating...`); await mkdirp(path.dirname(dstPath)); } await fs.writeFile(dstPath, buffer); return; } const dstFolder = await tempDir.openDir(); const dstPath = path.resolve(dstFolder, path.basename(remotePath)); try { await fs.writeFile(dstPath, buffer); await addMedia(device.udid, dstPath); } finally { await fs.rimraf(dstFolder); } }
javascript
{ "resource": "" }
q62281
pullFromSimulator
test
async function pullFromSimulator (device, remotePath, isFile) { let pathOnServer; if (CONTAINER_PATH_PATTERN.test(remotePath)) { const [bundleId, dstPath] = await parseContainerPath(remotePath, async (appBundle, containerType) => await getAppContainer(device.udid, appBundle, null, containerType)); log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` + `Will get the data from '${dstPath}'`); pathOnServer = dstPath; } else { const simRoot = device.getDir(); pathOnServer = path.posix.join(simRoot, remotePath); verifyIsSubPath(pathOnServer, simRoot); log.info(`Got the full item path: ${pathOnServer}`); } if (!await fs.exists(pathOnServer)) { log.errorAndThrow(`The remote ${isFile ? 'file' : 'folder'} at '${pathOnServer}' does not exist`); } const buffer = isFile ? await fs.readFile(pathOnServer) : await zip.toInMemoryZip(pathOnServer); return Buffer.from(buffer).toString('base64'); }
javascript
{ "resource": "" }
q62282
pullFromRealDevice
test
async function pullFromRealDevice (device, remotePath, isFile) { await verifyIFusePresence(); const mntRoot = await tempDir.openDir(); let isUnmountSuccessful = true; try { let dstPath = path.resolve(mntRoot, remotePath); let ifuseArgs = ['-u', device.udid, mntRoot]; if (CONTAINER_PATH_PATTERN.test(remotePath)) { const [bundleId, pathInContainer] = await parseContainerPath(remotePath, mntRoot); dstPath = pathInContainer; log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` + `Will get the data from '${dstPath}'`); ifuseArgs = ['-u', device.udid, '--container', bundleId, mntRoot]; } else { verifyIsSubPath(dstPath, mntRoot); } await mountDevice(device, ifuseArgs); isUnmountSuccessful = false; try { if (!await fs.exists(dstPath)) { log.errorAndThrow(`The remote ${isFile ? 'file' : 'folder'} at '${dstPath}' does not exist`); } const buffer = isFile ? await fs.readFile(dstPath) : await zip.toInMemoryZip(dstPath); return Buffer.from(buffer).toString('base64'); } finally { await exec('umount', [mntRoot]); isUnmountSuccessful = true; } } finally { if (isUnmountSuccessful) { await fs.rimraf(mntRoot); } else { log.warn(`Umount has failed, so not removing '${mntRoot}'`); } } }
javascript
{ "resource": "" }
q62283
createSim
test
async function createSim (caps, platform = PLATFORM_NAME_IOS) { const appiumTestDeviceName = `appiumTest-${UUID.create().toString().toUpperCase()}-${caps.deviceName}`; const udid = await createDevice( appiumTestDeviceName, caps.deviceName, caps.platformVersion, { platform } ); return await getSimulator(udid); }
javascript
{ "resource": "" }
q62284
getExistingSim
test
async function getExistingSim (opts) { const devices = await getDevices(opts.platformVersion); const appiumTestDeviceName = `appiumTest-${opts.deviceName}`; let appiumTestDevice; for (const device of _.values(devices)) { if (device.name === opts.deviceName) { return await getSimulator(device.udid); } if (device.name === appiumTestDeviceName) { appiumTestDevice = device; } } if (appiumTestDevice) { log.warn(`Unable to find device '${opts.deviceName}'. Found '${appiumTestDevice.name}' (udid: '${appiumTestDevice.udid}') instead`); return await getSimulator(appiumTestDevice.udid); } return null; }
javascript
{ "resource": "" }
q62285
test
function () { const data = this.data; let objectEls; // Push entities into list of els to intersect. if (data.objects) { objectEls = this.el.sceneEl.querySelectorAll(data.objects); } else { // If objects not defined, intersect with everything. objectEls = this.el.sceneEl.children; } // Convert from NodeList to Array this.els = Array.prototype.slice.call(objectEls); }
javascript
{ "resource": "" }
q62286
intersect
test
function intersect (el) { let radius, mesh, distance, extent; if (!el.isEntity) { return; } mesh = el.getObject3D('mesh'); if (!mesh) { return; } box.setFromObject(mesh).getSize(size); extent = Math.max(size.x, size.y, size.z) / 2; radius = Math.sqrt(2 * extent * extent); box.getCenter(meshPosition); if (!radius) { return; } distance = position.distanceTo(meshPosition); if (distance < radius + colliderRadius) { collisions.push(el); distanceMap.set(el, distance); } }
javascript
{ "resource": "" }
q62287
test
function () { const gamepad = this.getGamepad(); if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) { return new THREE.Vector2(); } return new THREE.Vector2( (gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0) + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0), (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0) + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0) ); }
javascript
{ "resource": "" }
q62288
URLSearchParamsPolyfill
test
function URLSearchParamsPolyfill(search) { search = search || ""; // support construct object with another URLSearchParams instance if (search instanceof URLSearchParams || search instanceof URLSearchParamsPolyfill) { search = search.toString(); } this [__URLSearchParams__] = parseToDict(search); }
javascript
{ "resource": "" }
q62289
RequestQueue
test
function RequestQueue(opts) { if (!opts || typeof (opts) !== 'object') { opts = {}; } this.size = (opts.size > 0) ? opts.size : Infinity; this.timeout = (opts.timeout > 0) ? opts.timeout : 0; this._queue = []; this._timer = null; this._frozen = false; }
javascript
{ "resource": "" }
q62290
MessageTracker
test
function MessageTracker(opts) { assert.object(opts); assert.string(opts.id); assert.object(opts.parser); this.id = opts.id; this._msgid = 0; this._messages = {}; this._abandoned = {}; this.parser = opts.parser; var self = this; this.__defineGetter__('pending', function () { return Object.keys(self._messages); }); }
javascript
{ "resource": "" }
q62291
connectSocket
test
function connectSocket(cb) { cb = once(cb); function onResult(err, res) { if (err) { if (self.connectTimer) { clearTimeout(self.connectTimer); self.connectTimer = null; } self.emit('connectError', err); } cb(err, res); } function onConnect() { if (self.connectTimer) { clearTimeout(self.connectTimer); self.connectTimer = null; } socket.removeAllListeners('error') .removeAllListeners('connect') .removeAllListeners('secureConnect'); tracker.id = nextClientId() + '__' + tracker.id; self.log = self.log.child({ldap_id: tracker.id}, true); // Move on to client setup setupClient(cb); } var port = (self.port || self.socketPath); if (self.secure) { socket = tls.connect(port, self.host, self.tlsOptions); socket.once('secureConnect', onConnect); } else { socket = net.connect(port, self.host); socket.once('connect', onConnect); } socket.once('error', onResult); initSocket(); // Setup connection timeout handling, if desired if (self.connectTimeout) { self.connectTimer = setTimeout(function onConnectTimeout() { if (!socket || !socket.readable || !socket.writeable) { socket.destroy(); self._socket = null; onResult(new ConnectionError('connection timeout')); } }, self.connectTimeout); } }
javascript
{ "resource": "" }
q62292
initSocket
test
function initSocket() { tracker = new MessageTracker({ id: self.url ? self.url.href : self.socketPath, parser: new Parser({log: log}) }); // This won't be set on TLS. So. Very. Annoying. if (typeof (socket.setKeepAlive) !== 'function') { socket.setKeepAlive = function setKeepAlive(enable, delay) { return socket.socket ? socket.socket.setKeepAlive(enable, delay) : false; }; } socket.on('data', function onData(data) { if (log.trace()) log.trace('data event: %s', util.inspect(data)); tracker.parser.write(data); }); // The "router" tracker.parser.on('message', function onMessage(message) { message.connection = self._socket; var callback = tracker.fetch(message.messageID); if (!callback) { log.error({message: message.json}, 'unsolicited message'); return false; } return callback(message); }); tracker.parser.on('error', function onParseError(err) { self.emit('error', new VError(err, 'Parser error for %s', tracker.id)); self.connected = false; socket.end(); }); }
javascript
{ "resource": "" }
q62293
setupClient
test
function setupClient(cb) { cb = once(cb); // Indicate failure if anything goes awry during setup function bail(err) { socket.destroy(); cb(err || new Error('client error during setup')); } // Work around lack of close event on tls.socket in node < 0.11 ((socket.socket) ? socket.socket : socket).once('close', bail); socket.once('error', bail); socket.once('end', bail); socket.once('timeout', bail); self._socket = socket; self._tracker = tracker; // Run any requested setup (such as automatically performing a bind) on // socket before signalling successful connection. // This setup needs to bypass the request queue since all other activity is // blocked until the connection is considered fully established post-setup. // Only allow bind/search/starttls for now. var basicClient = { bind: function bindBypass(name, credentials, controls, callback) { return self.bind(name, credentials, controls, callback, true); }, search: function searchBypass(base, options, controls, callback) { return self.search(base, options, controls, callback, true); }, starttls: function starttlsBypass(options, controls, callback) { return self.starttls(options, controls, callback, true); }, unbind: self.unbind.bind(self) }; vasync.forEachPipeline({ func: function (f, callback) { f(basicClient, callback); }, inputs: self.listeners('setup') }, function (err, res) { if (err) { self.emit('setupError', err); } cb(err); }); }
javascript
{ "resource": "" }
q62294
Graph
test
function Graph(gridIn, options) { options = options || {}; this.nodes = []; this.diagonal = !!options.diagonal; this.grid = []; for (var x = 0; x < gridIn.length; x++) { this.grid[x] = []; for (var y = 0, row = gridIn[x]; y < row.length; y++) { var node = new GridNode(x, y, row[y]); this.grid[x][y] = node; this.nodes.push(node); } } this.init(); }
javascript
{ "resource": "" }
q62295
test
function(path, i) { if(i >= path.length) { // finished removing path, set start positions return setStartClass(path, i); } elementFromNode(path[i]).removeClass(css.active); setTimeout(function() { removeClass(path, i+1); }, timeout*path[i].getCost()); }
javascript
{ "resource": "" }
q62296
forEach
test
function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { var result = callback(array[i], i); if (result) { return result; } } } return undefined; }
javascript
{ "resource": "" }
q62297
arrayToMap
test
function arrayToMap(array, makeKey) { var result = {}; forEach(array, function (value) { result[makeKey(value)] = value; }); return result; }
javascript
{ "resource": "" }
q62298
createWatchedFileSet
test
function createWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } var watchedFiles = []; var nextFileToCheck = 0; var watchTimer; function getModifiedTime(fileName) { return _fs.statSync(fileName).mtime; } function poll(checkedIndex) { var watchedFile = watchedFiles[checkedIndex]; if (!watchedFile) { return; } _fs.stat(watchedFile.fileName, function (err, stats) { if (err) { watchedFile.callback(watchedFile.fileName); } else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { watchedFile.mtime = getModifiedTime(watchedFile.fileName); watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0); } }); } // this implementation uses polling and // stat due to inconsistencies of fs.watch // and efficiency of stat on modern filesystems function startWatchTimer() { watchTimer = setInterval(function () { var count = 0; var nextToCheck = nextFileToCheck; var firstCheck = -1; while ((count < chunkSize) && (nextToCheck !== firstCheck)) { poll(nextToCheck); if (firstCheck < 0) { firstCheck = nextToCheck; } nextToCheck++; if (nextToCheck === watchedFiles.length) { nextToCheck = 0; } count++; } nextFileToCheck = nextToCheck; }, interval); } function addFile(fileName, callback) { var file = { fileName: fileName, callback: callback, mtime: getModifiedTime(fileName) }; watchedFiles.push(file); if (watchedFiles.length === 1) { startWatchTimer(); } return file; } function removeFile(file) { watchedFiles = ts.copyListRemovingItem(file, watchedFiles); } return { getModifiedTime: getModifiedTime, poll: poll, startWatchTimer: startWatchTimer, addFile: addFile, removeFile: removeFile }; }
javascript
{ "resource": "" }
q62299
startWatchTimer
test
function startWatchTimer() { watchTimer = setInterval(function () { var count = 0; var nextToCheck = nextFileToCheck; var firstCheck = -1; while ((count < chunkSize) && (nextToCheck !== firstCheck)) { poll(nextToCheck); if (firstCheck < 0) { firstCheck = nextToCheck; } nextToCheck++; if (nextToCheck === watchedFiles.length) { nextToCheck = 0; } count++; } nextFileToCheck = nextToCheck; }, interval); }
javascript
{ "resource": "" }