_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q2100
readDirectory
train
function readDirectory (srcDir) { let srcTree = {} const entries = fs.readdirSync(srcDir) entries.forEach(function (entry) { const filePath = path.join(srcDir, entry) if (fs.lstatSync(filePath).isDirectory()) { srcTree[entry] = readDirectory(filePath)
javascript
{ "resource": "" }
q2101
parseDirectory
train
function parseDirectory(dataStr) { let currChar = ''; let directory = ''; let pos = 24; while (currChar !== '\x1E') { currChar = dataStr.charAt(pos); if (currChar !== 'x1E') { directory += currChar;
javascript
{ "resource": "" }
q2102
parseDirectoryEntries
train
function parseDirectoryEntries(directoryStr) { const directoryEntries = []; let pos = 0; let count = 0; while (directoryStr.length - pos >= 12) {
javascript
{ "resource": "" }
q2103
trimNumericField
train
function trimNumericField(input) { while (input.length > 1 && input.charAt(0) === '0') {
javascript
{ "resource": "" }
q2104
addLeadingZeros
train
function addLeadingZeros(numField, length) { while (numField.toString().length < length) { numField = '0'
javascript
{ "resource": "" }
q2105
lengthInUtf8Bytes
train
function lengthInUtf8Bytes(str) { const m = encodeURIComponent(str).match(/%[89ABab]/g);
javascript
{ "resource": "" }
q2106
utf8Substr
train
function utf8Substr(str, startInBytes, lengthInBytes) { const strBytes = stringToByteArray(str); const subStrBytes = []; let count = 0; for (let i = startInBytes; count < lengthInBytes; i++) { subStrBytes.push(strBytes[i]); count++; } return byteArrayToString(subStrBytes); // Converts the byte array to a UTF-8 string. // From http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string?lq=1 function byteArrayToString(byteArray) { let
javascript
{ "resource": "" }
q2107
fetchFilePathsByType
train
function fetchFilePathsByType(distFiles, basePath, type) { return distFiles .filter(function(filePath) { return new RegExp('assets/.*\\.' + type + '$').test(filePath);
javascript
{ "resource": "" }
q2108
main
train
async function main() { const { window } = webContext(); if (window) { await windowReadiness(window); render(window);
javascript
{ "resource": "" }
q2109
render
train
function render({ document }) { console.debug("rendering"); document.querySelectorAll(".replace-with-pubcontrol").forEach(el => { el.innerHTML = ` <div>
javascript
{ "resource": "" }
q2110
windowReadiness
train
function windowReadiness({ document }) { if (document.readyState === "loading") { // Loading hasn't finished
javascript
{ "resource": "" }
q2111
objectSchema
train
function objectSchema(obj) { const props = Object.entries(obj).reduce( (reduced, [key, val]) => Object.assign(reduced,
javascript
{ "resource": "" }
q2112
bootWebWorker
train
function bootWebWorker({ Worker }) { const webWorker = Object.assign( new Worker("pubcontrol-browser-demo.webworker.js"), { onmessage: event => { console.debug("Message received from worker", event.data.type, event); } } ); webWorker.postMessage({ type: "Hello", from: "browser", content: "Hello worker. I booted you out here in pubcontrol-browser-demo." }); const url = new URL(global.location.href); const epcp = { uri: url.searchParams.get("epcp.uri"),
javascript
{ "resource": "" }
q2113
func
train
function func(ast) { var params = list(ast["params"]) var id = ast["id"]
javascript
{ "resource": "" }
q2114
parens
train
function parens(parent, child) { if (precedence(parent) >=
javascript
{ "resource": "" }
q2115
precedence
train
function precedence(ast) { var p = PRECEDENCE[ast["type"]]; if ( _.isNumber(p) ) // represents Fixnum? I'm so sorry. return p; else if ( p && p.constructor ===
javascript
{ "resource": "" }
q2116
generate_exports
train
function generate_exports (module) { // # 85 // Before module factory being invoked, mark the module as `loaded` // so we will not execute the factory function again. // `mod.loaded` indicates that a module has already been `require()`d // When there are cyclic dependencies, neuron will not fail. module.loaded = true; // During the execution of factory, // the reference of `module.exports` might be changed. // But we still set the `module.exports` as
javascript
{ "resource": "" }
q2117
get_mod
train
function get_mod (parsed) { var id = parsed.id; // id -> '@kael/[email protected]/b' return mods[id] || (mods[id] = { // package scope: s: parsed.s, // package name: 'a' n: parsed.n, // package version: '1.1.0' v: parsed.v, // module path: '/b' p: parsed.p, // module id: '[email protected]/b' id: id, // package id: '[email protected]' k: parsed.k, // version map of the current module m: {}, // loading queue l: [], // If there is no path, it must be a main entry. // Actually, there will always be a path when defining a module,
javascript
{ "resource": "" }
q2118
create_require
train
function create_require (env) { function require (id) { // `require('[email protected]')` is prohibited. prohibit_require_id_with_version(id); // When `require()` another module inside the factory, // the module of depdendencies must already been created var module = get_module(id, env, true); return get_exports(module); } // @param {string} id Module identifier. // Since 4.2.0, we only allow to asynchronously load a single module require.async = function(id, callback) { if (callback) { // `require.async('[email protected]')` is prohibited prohibit_require_id_with_version(id); var module = get_module(id, env); // If `require.async` a foreign module, it must be a main entry if (!module.main) {
javascript
{ "resource": "" }
q2119
type
train
function type (prop) { var rs = Object.prototype.toString.call(prop);
javascript
{ "resource": "" }
q2120
train
function () { if (processes && processes.length > 0) { for (var i = processes.length - 1; i >=
javascript
{ "resource": "" }
q2121
defaultStrategy
train
function defaultStrategy(projectDir, builder, cb) { const pkg = fs.realpathSync(INSTALLER_PACKAGE);
javascript
{ "resource": "" }
q2122
customStrategyInPlace
train
function customStrategyInPlace(projectDir, builder, cb) { const installerDir = path.resolve(projectDir, "node_modules", "@deskpro", INSTALLER_PACKAGE_NAME); const customInstallerTarget = path.resolve(installerDir, "src", "settings"); shelljs.rm('-rf', customInstallerTarget); const copyOptions = { overwrite: true, expand: true, dot: true }; function onCustomInstallerFilesReady (err) { builder.buildFromSource(installerDir, projectDir); cb(); }
javascript
{ "resource": "" }
q2123
customStrategy
train
function customStrategy(projectDir, builder, cb) { const dest = builder.getTargetDestination(projectDir); shelljs.rm('-rf', dest); const copyOptions = { overwrite: true, expand: true, dot: true }; const onCustomInstallerFilesReady = function (err) { builder.buildFromSource(dest, projectDir); cb(); }; const onInstallerFilesReady = function (err) { if (err) { cb(err); return; } let customInstallerSrc = path.resolve(projectDir, "src", "installer");
javascript
{ "resource": "" }
q2124
train
function (projectDir) { "use strict"; const packageJson = readPackageJson(projectDir); const extracted = extractVendors(packageJson); return
javascript
{ "resource": "" }
q2125
getCurrentValue
train
function getCurrentValue(stream, key) { if (stream._currentEvent && stream._currentEvent.type === key) { return stream._currentEvent.value; } else { var names = keyNames[key]; if (!names) { return stream[key]; }
javascript
{ "resource": "" }
q2126
train
function (version) { var splitDots = version.split("."); var nbDots = splitDots.length - 1; if (nbDots === 0) { return version + ".0.0"; } else if (nbDots === 1) { return version + ".0"; } else if (nbDots === 2) {
javascript
{ "resource": "" }
q2127
onLauncherConnect
train
function onLauncherConnect(slaveURL) { var browsers = attester.config["run-browser"]; if (browsers) { if (!Array.isArray(browsers)) { browsers = [browsers]; } var args = [slaveURL]; for (var i = 0, l = browsers.length; i < l; i++) {
javascript
{ "resource": "" }
q2128
train
function (options, overrides) { let resolved = null; if (typeof options === 'string') { //we've been give a path to a project dir or babelrc let babelrcPath; const stats = fs.statSync(options); if (stats.isDirectory()) { babelrcPath = path.join(options, '.babelrc'); } else if (stats.isFile()) { babelrcPath = options; } if (babelrcPath) { try { const babelOptions = JSON.parse(fs.readFileSync(babelrcPath)); resolved = resolveOptions(babelOptions); } catch (e) {
javascript
{ "resource": "" }
q2129
train
function (cfg, state, n) { cfg.args = cfg.args || {}; var phantomPath = cfg.phantomPath; var controlScript = pathUtil.join(__dirname, '../browsers/phantomjs-control-script.js'); var args = []; args.push(controlScript); args.push("--auto-exit"); if (cfg.args.autoExitPolling) { args.push("--auto-exit-polling=" + cfg.args.autoExitPolling); } if (typeof n == "undefined") { n = Math.round(Math.random() * 1000) % 1000; } args.push("--instance-id=" + n); args.push(cfg.slaveURL); var phantomProcess = spawn(phantomPath, args, { stdio: "pipe" });
javascript
{ "resource": "" }
q2130
train
function (cfg, state, n) { // Node 0.8 and 0.10 differently handle spawning errors ('exit' vs 'error'), but errors that happened after // launching the command are both handled in 'exit' callback return function (code, signal) { // See http://tldp.org/LDP/abs/html/exitcodes.html and http://stackoverflow.com/a/1535733/ if (code === 0 || signal == "SIGTERM" || state.resetCalled) { return; } var isNotRecoverable = (code == 127 || code == 126); if (isNotRecoverable) { ++state.erroredPhantomInstances; var path = cfg.phantomPath; if (code == 127) { logger.logError("Spawn: exited with code 127. PhantomJS executable not found. Make sure to download PhantomJS and add its folder to your system's PATH, or pass the full path directly to Attester via --phantomjs-path.\nUsed command: '" + path + "'"); } else if (code == 126) { logger.logError("Spawn: exited with code 126. Unable to execute PhantomJS. Make sure to have proper read & execute
javascript
{ "resource": "" }
q2131
train
function (cfg, state, n) { return function (err) { if (err.code == "ENOENT") { logger.logError("Spawn: exited with code ENOENT. PhantomJS executable not found. Make sure to download PhantomJS and add its folder to your system's PATH, or pass the full path directly to Attester
javascript
{ "resource": "" }
q2132
train
function () { this.addResult = function (event) { var fullUrl = event.homeURL + url; http.get(fullUrl, function (response) { var content = ""; response.on("data", function (chunk) { content += chunk; }); response.on("end", function () {
javascript
{ "resource": "" }
q2133
resolvePath
train
function resolvePath (moduleName, relativePath) { if (! moduleName) { return null; } if (! relativePath) { return null; } const mainPath = require.resolve(moduleName); if (! mainPath) { return null; } const rootLocations = []; const dirs = mainPath.split(path.sep); let lastSegment = dirs.pop(); while (lastSegment) { const location = dirs.concat(['package.json']).join(path.sep); rootLocations.push(location); lastSegment = dirs.pop(); }
javascript
{ "resource": "" }
q2134
Arguable
train
function Arguable (usage, argv, options) { this._usage = usage // These are the merged defintion and invocation options provided by the // user. this.options = options.options // The key used to create the `Destructible`. this.identifier = options.identifier // We'll use this for an exit code if it is set and if we exit normally. this.exitCode = null // Are we running as a main module? this.isMainModule = options.isMainModule // Use environment `LANG` or else language of first usage definition. this.lang = coalesce(options.lang, this._usage.language) // Extract argument patterns from usage. var patterns = this._usage.getPattern() // Extract the arguments that accept values, TODO
javascript
{ "resource": "" }
q2135
normalizePage
train
function normalizePage(content) { var data = { "head-start": [], "head": [], "head-end": [], body: [] }; if (typeof content === "string") { data.body.push(content); } else { ["head-start", "head", "head-end", "body"].forEach(function (section) { var sectionContent = content[section]; if (!sectionContent) { return; }
javascript
{ "resource": "" }
q2136
flattenHead
train
function flattenHead(obj) { var newHead = []; _arrayCopy(newHead, obj["head-start"]); _arrayCopy(newHead, obj["head"]); _arrayCopy(newHead, obj["head-end"]);
javascript
{ "resource": "" }
q2137
_arrayCopy
train
function _arrayCopy(dest, src) { if (Array.isArray(src)) {
javascript
{ "resource": "" }
q2138
replacePath
train
function replacePath (path, keys) { var index = 0; function replace (_, escaped, prefix, key, capture, group, suffix, escape) { if (escaped) { return escaped; } if (escape) { return '\\' + escape; } var repeat = suffix === '+' || suffix === '*'; var optional = suffix === '?' || suffix === '*'; keys.push({ name: key || index++, delimiter: prefix || '/', optional: optional, repeat: repeat }); prefix = prefix ? ('\\' + prefix) : ''; capture = escapeGroup(capture || group || '[^'
javascript
{ "resource": "" }
q2139
train
function (cb) { if (opts.dropCollection) { db.listCollections({name: collectionName}) .toArray(function (err, items) { if (err) return cb(err)
javascript
{ "resource": "" }
q2140
split
train
function split(secret, opts) { if (!secret || (secret && 0 === secret.length)) { throw new TypeError('Secret cannot be empty.') } if ('string' === typeof secret) { secret = Buffer.from(secret) } if (false === Buffer.isBuffer(secret)) { throw new TypeError('Expecting secret to be a buffer.') } if (!opts || 'object' !== typeof opts) { throw new TypeError('Expecting options to be an object.') } if ('number' !== typeof opts.shares) { throw new TypeError('Expecting shares to be a number.') } if (!opts.shares || opts.shares < 0 || opts.shares > MAX_SHARES) { throw new RangeError(`Shares must be 0 < shares <= ${MAX_SHARES}.`) } if ('number' !== typeof opts.threshold) { throw new TypeError('Expecting threshold to be a number.') }
javascript
{ "resource": "" }
q2141
combine
train
function combine(shares) { const chunks = [] const x = [] const y = [] const t = shares.length for (let i = 0; i < t; ++i) { const share = parse(shares[i]) if (-1 === x.indexOf(share.id)) { x.push(share.id) const bin = codec.bin(share.data, 16) const parts = codec.split(bin, 0, 2) for (let j = 0; j < parts.length; ++j) { if (!y[j]) { y[j] = [] } y[j][x.length - 1] = parts[j] } } } for (let i = 0; i < y.length;
javascript
{ "resource": "" }
q2142
train
function(sourceWasAnError, shouldNotReconnect) { log.error("[Endpoint] Connection closed " + (sourceWasAnError ? 'because of an error:' + sourceWasAnError : '')); this.connected = false; this.handshaken = false; this.connecting = false; if (!shouldNotReconnect) { log.debug('onClose():: reconnecting...'); this.handshakenBackoff.reset();
javascript
{ "resource": "" }
q2143
train
function (err) { log.error("Redis client closed " + (err ? err.message : '')); this.connected = false; this.emit('close', err);
javascript
{ "resource": "" }
q2144
train
function( iframe, options ) { var sandbox = iframe.getAttribute("sandbox"); if (typeof sandbox === "string" && !sandboxAllow.test(sandbox)) { if (options && options.force) { iframe.removeAttribute("sandbox"); } else if (!options ||
javascript
{ "resource": "" }
q2145
addAnother
train
function addAnother(schema) { var config = { properties: { another: { description: 'Add another collection? (y/n)'.magenta } } }; prompt.start(); prompt.message = ' > '; prompt.delimiter = ''; return new Promise(function(resolve, reject) { prompt.get(config, function(err, result) { if (err) return reject(err); switch (result.another.toLowerCase()) { case 'n':
javascript
{ "resource": "" }
q2146
getCollection
train
function getCollection() { var config = { properties: { collection: { description: 'Collection name and number of rows, 5 if omitted (ex: posts 10): '.magenta, type: 'string', required: true } } }; prompt.start(); prompt.message = ' > '; prompt.delimiter = ''; return new
javascript
{ "resource": "" }
q2147
getFields
train
function getFields(collection) { var message = 'What fields should "' + collection + '" have?\n', config; config = { properties: { fields: { description: message.magenta + ' Comma-separated fieldname:fieldtype pairs (ex: id:index, username:username)\n'.grey, type: 'string', required: true, pattern: FIELDS_REGEXP } } }; prompt.start(); prompt.message = ' >> '; prompt.delimiter = ''; return new Promise(function(resolve, reject) { prompt.get(config, function(err, result) {
javascript
{ "resource": "" }
q2148
writeJSON
train
function writeJSON(dbName, schema) { var baseUrl = 'http://www.filltext.com/?', promises = [], collection; for (collection in schema) { var meta = schema[collection].meta, fields = meta.fields, url; url = Object.keys(fields).map(function(key) { if (fields[key][0] === '[' && fields[key].slice(-1) === ']') { return key + '=' + fields[key]; } return key + '={' + fields[key] + '}'; }).join('&') + '&rows=' + meta.rows; console.log('Url for', collection, url); (function(c) { promises.push(fetch(baseUrl + url).then(function(response) {
javascript
{ "resource": "" }
q2149
pauseStreams
train
function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) streams = streams.pipe(PassThrough(options))
javascript
{ "resource": "" }
q2150
process
train
function process(payload) { var batteryRaw = parseInt(payload.substr(2,2),16) % 64; var temperatureRaw = (parseInt(payload.substr(0,3),16) >> 2) % 256; var battery = ((batteryRaw / 34) + 1.8).toFixed(2) + "V";
javascript
{ "resource": "" }
q2151
process
train
function process(payload) { payload = payload.toLowerCase(); var advA48 = address.process(payload.substr(4,12)); advA48.advHeader =
javascript
{ "resource": "" }
q2152
process
train
function process(data) { var uuid = data.substr(2,2) + data.substr(0,2); // NOTE: this is for legacy compatibility var advertiserData = { serviceData: { uuid:
javascript
{ "resource": "" }
q2153
process
train
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var cursor = 0; // Apple sometimes includes more than one service data while(cursor < data.length) { var appleType = data.substr(cursor,2); switch(appleType) { case '01': return; // TODO: decipher this type (one bit set in fixed length?) case '02': cursor = ibeacon.process(advertiserData, cursor); break; case '05': cursor = airdrop.process(advertiserData, cursor); break; case '07': cursor = airpods.process(advertiserData, cursor); break; case '08': cursor = service.process(advertiserData, cursor); // TODO: decipher break;
javascript
{ "resource": "" }
q2154
process
train
function process(payload) { var addressType = parseInt(payload.substr(0,1),16); var typeCode = payload.substr(1,1); var length = parseInt(payload.substr(2,2),16) % 64; var rxAdd = "public"; var txAdd = "public"; if(addressType & 0x8) { rxAdd = "random"; } if(addressType & 0x4) { txAdd = "random"; } var type; switch(typeCode) { case("0"): type = TYPE0_NAME; break; case("1"): type = TYPE1_NAME; break; case("2"): type = TYPE2_NAME; break; case("3"):
javascript
{ "resource": "" }
q2155
processEddystone
train
function processEddystone(advertiserData) { var data = advertiserData.serviceData.data; var eddystone = {}; var frameType = data.substr(0,2); switch(frameType) { // UID case '00': eddystone.type = 'UID'; eddystone.txPower = pdu.convertTxPower(data.substr(2,2)); eddystone.uid = {}; eddystone.uid.namespace = data.substr(4,20); eddystone.uid.instance = data.substr(24,12); break; // URI case '10': eddystone.type = 'URL'; eddystone.txPower = pdu.convertTxPower(data.substr(2,2)); eddystone.url = parseSchemePrefix(data.substr(4,2)); eddystone.url += parseEncodedUrl(data.substr(6)); break; // TLM case '20': eddystone.type = 'TLM'; eddystone.version = data.substr(2,2); if(eddystone.version === '00') { eddystone.batteryVoltage = parseInt(data.substr(4,4),16) + 'mV'; // TODO: export 8:8 fixed point representation interpreter to pdu eddystone.temperature = parseInt(data.substr(8,4),16); if(eddystone.temperature >
javascript
{ "resource": "" }
q2156
parseEncodedUrl
train
function parseEncodedUrl(encodedUrl) { var url = ''; for(var cChar = 0; cChar < (encodedUrl.length / 2); cChar++) { var charCode = parseInt(encodedUrl.substr(cChar*2,2),16); switch(charCode) { case 0x00: url += ".com/"; break; case 0x01: url += ".org/"; break; case 0x02: url += ".edu/"; break; case 0x03: url += ".net/"; break; case 0x04: url += ".info/"; break; case 0x05: url += ".biz/"; break; case 0x06: url += ".gov/"; break; case 0x07: url += ".com"; break; case 0x08: url += ".org"; break;
javascript
{ "resource": "" }
q2157
Identifier
train
function Identifier(type, value) { var isValue = (value != null); // Constructor for EUI-64 if((type == TYPE_EUI64) && isValue) { this.type = TYPE_EUI64; this.value = value; } // Constructor for RA-28 else if((type == TYPE_RA28) && isValue) { this.type = TYPE_RA28; this.value = value.substr(value.length - 7, 7); } // Constructor for ADVA-48 else if((type == TYPE_ADVA48) && isValue) { this.type = TYPE_ADVA48; this.value = value;
javascript
{ "resource": "" }
q2158
process
train
function process(data) { var companyIdentifierCode = data.substr(2,2); companyIdentifierCode += data.substr(0,2); var companyName = companyIdentifierCodes.companyNames[companyIdentifierCode]; if(typeof companyName === 'undefined') { companyName = 'Unknown'; } // NOTE: this is for legacy compatibility var advertiserData = { manufacturerSpecificData: { companyName : companyName, companyIdentifierCode: companyIdentifierCode, data: data.substr(4) } }; // Handle the unique case of AltBeacon if(altbeacon.isAltBeacon(advertiserData)) { altbeacon.process(advertiserData); return advertiserData.manufacturerSpecificData; } // Interpret the manufacturer specific data, if possible // Kindly respect ascending order of company identifier codes switch(companyIdentifierCode) { case '004c': apple.process(advertiserData); return advertiserData.manufacturerSpecificData; case '00f9': sticknfind.process(advertiserData);
javascript
{ "resource": "" }
q2159
process
train
function process(payload) { var advAString = payload.substr(10,2); advAString += payload.substr(8,2); advAString += payload.substr(6,2); advAString += payload.substr(4,2); advAString +=
javascript
{ "resource": "" }
q2160
process
train
function process(data) { var flags = parseInt(data, 16); var result = []; if(flags & 0x01) { result.push(BIT0_NAME); } if(flags & 0x02) { result.push(BIT1_NAME);
javascript
{ "resource": "" }
q2161
process
train
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var packetType = data.substr(0,2); switch(packetType) { case '01': snfsingle.process(advertiserData);
javascript
{ "resource": "" }
q2162
process
train
function process(advertiserData, cursor) { var iBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; iBeacon.uuid = data.substr(4,32); iBeacon.major = data.substr(36,4); iBeacon.minor = data.substr(40,4);
javascript
{ "resource": "" }
q2163
process
train
function process(advertiserData) { var altBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; altBeacon.id = data.substr(4,40); altBeacon.refRSSI = pdu.convertTxPower(data.substr(44,2));
javascript
{ "resource": "" }
q2164
isAltBeacon
train
function isAltBeacon(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var isCorrectLength = ((data.length + 6) === (LENGTH * 2));
javascript
{ "resource": "" }
q2165
process
train
function process(data) { var result = ''; for(var cChar = 0; cChar < data.length; cChar += 2) { result
javascript
{ "resource": "" }
q2166
process
train
function process(advertiserData) { var snfBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; snfBeacon.type = 'SnS Motion'; snfBeacon.timestamp = parseInt(pdu.reverseBytes(data.substr(2,8)),16); snfBeacon.temperature = parseInt(data.substr(10,2),16); if(snfBeacon.temperature > 127) { snfBeacon.temperature = 127 - snfBeacon.temperature; } snfBeacon.temperature = snfBeacon.temperature / 2; snfBeacon.temperature += (parseInt(data.substr(41,1),16)) / 4; snfBeacon.batteryVoltage = data.substr(12,2); snfBeacon.eventCounters = []; snfBeacon.eventCounters.push(data.substr(26,1) + data.substr(14,2)); snfBeacon.eventCounters.push(data.substr(27,1) + data.substr(16,2)); snfBeacon.eventCounters.push(data.substr(28,1) + data.substr(18,2)); snfBeacon.eventCounters.push(data.substr(29,1) + data.substr(20,2)); snfBeacon.eventCounters.push(data.substr(30,1) + data.substr(22,2)); snfBeacon.eventCounters.push(data.substr(31,1) + data.substr(24,2)); for(var cCounter = 0; cCounter < 6; cCounter++) {
javascript
{ "resource": "" }
q2167
process
train
function process(advertiserData) { var snfBeacon = {}; var data = advertiserData.manufacturerSpecificData.data; snfBeacon.type = 'V2 Single Payload'; snfBeacon.id = pdu.reverseBytes(data.substr(2,16)); snfBeacon.time = parseInt(pdu.reverseBytes(data.substr(18,8)),16); snfBeacon.scanCount = parseInt(data.substr(26,2),16) / 4; snfBeacon.batteryVoltage = data.substr(28,2); snfBeacon.temperature = parseInt(data.substr(30,2),16); if(snfBeacon.temperature > 127) {
javascript
{ "resource": "" }
q2168
process
train
function process(payload) { payload = payload.toLowerCase(); var ra28 = new identifier(identifier.RA28, payload.substr(0, 7)); var eui64 = ra28.toType(identifier.EUI64); eui64.flags = flags.process(payload.substr(7, 1));
javascript
{ "resource": "" }
q2169
process
train
function process(advertiserData) { var data = advertiserData.manufacturerSpecificData.data; var packetType = data.substr(0,2); switch(packetType) { // Update when
javascript
{ "resource": "" }
q2170
addColorScale
train
function addColorScale(name, colors, positions) { if (colors.length !== positions.length) { throw new Error('Invalid color
javascript
{ "resource": "" }
q2171
renderColorScaleToCanvas
train
function renderColorScaleToCanvas(name, canvas) { /* eslint-disable no-param-reassign */ const csDef = colorscales[name]; canvas.height = 1; const ctx = canvas.getContext('2d'); if (Object.prototype.toString.call(csDef) === '[object Object]') { canvas.width = 256; const gradient = ctx.createLinearGradient(0, 0, 256, 1); for (let i = 0; i < csDef.colors.length; ++i) { gradient.addColorStop(csDef.positions[i], csDef.colors[i]); } ctx.fillStyle = gradient;
javascript
{ "resource": "" }
q2172
clear
train
function clear () { var str = ''; for (var i = 0; i < 20; i++) { if (Math.random() < 0.5) { str += '\u200B';
javascript
{ "resource": "" }
q2173
setSizes
train
function setSizes(){ // Put the scatter plot on the left. scatterPlot.box = { x: 0, y: 0, width: div.clientWidth / 2, height: div.clientHeight }; // Put the bar chart on the right. barChart.box = {
javascript
{ "resource": "" }
q2174
path
train
function path(d) { return line(dimensions.map(function(p) { return
javascript
{ "resource": "" }
q2175
brush
train
function brush() { var actives = dimensions.filter(function(p) { return !y[p].brush.empty(); }), extents = actives.map(function(p) { return y[p].brush.extent(); }), selectedPaths = foregroundPaths.filter(function(d) { return actives.every(function(p, i) { return extents[i][0] <= d[p] &&
javascript
{ "resource": "" }
q2176
type
train
function type(d) { // The '+' notation parses the string as a Number. d.sepalLength = +d.sepalLength;
javascript
{ "resource": "" }
q2177
setRandomData
train
function setRandomData(data){ // Include each key with a small chance var randomKeys = Object.keys(data[0]).filter(function(d){ return Math.random() < 0.5; }), // Make a copy of the objects with only the // random keys included. dataWithRandomKeys = data.map(function (d) { var e = {}; randomKeys.forEach(function (key) { e[key] = d[key]; }); return e; }), // Include each element with a small
javascript
{ "resource": "" }
q2178
randomString
train
function randomString() { var possibilities = ['Frequency', 'Population', 'Alpha',
javascript
{ "resource": "" }
q2179
track
train
function track(property, thisArg){ if(!(property in trackedProperties)){ trackedProperties[property] = true; values[property] = model[property]; Object.defineProperty(model, property, { get: function () { return values[property]; }, set: function(newValue) { var oldValue = values[property];
javascript
{ "resource": "" }
q2180
off
train
function off(property, callback){ listeners[property] = listeners[property].filter(function
javascript
{ "resource": "" }
q2181
Model
train
function Model(defaults){ // Make sure "new" is always used, // so we can use "instanceof" to check if something is a Model. if (!(this instanceof Model)) { return new Model(defaults); } // `model` is the public API object returned from invoking `new Model()`. var model = this, // The internal stored values for tracked properties. { property -> value } values = {}, // The callback functions for each tracked property. { property -> [callback] } listeners = {}, // The set of tracked properties. { property -> true } trackedProperties = {}; // The functional reactive "when" operator. // // * `properties` An array of property names (can also be a single property string). // * `callback` A callback function that is called: // * with property values as arguments, ordered corresponding to the properties array, // * only if all specified properties have values, // * once for initialization, // * whenever one or more specified properties change, // * on the next tick of the JavaScript event loop after properties change, // * only once as a result of one or more synchronous changes to dependency properties. function when(properties, callback, thisArg){ // Make sure the default `this` becomes // the object you called `.on` on. thisArg = thisArg || this; // Handle either an array or a single string. properties = (properties instanceof Array) ? properties : [properties]; // This function will trigger the callback to be invoked. var listener = debounce(function (){ var args = properties.map(function(property){ return values[property]; }); if(allAreDefined(args)){ callback.apply(thisArg, args); } }); // Trigger the callback once for initialization. listener(); // Trigger the callback whenever specified properties change. properties.forEach(function(property){ on(property, listener); }); // Return this function so it can be removed later with `model.cancel(listener)`. return listener; } // Adds a change listener for a given property with Backbone-like behavior. // Similar to http://backbonejs.org/#Events-on function on(property, callback, thisArg){ thisArg = thisArg || this; getListeners(property).push(callback); track(property, thisArg); } // Gets or creates the array of listener functions for a given property. function getListeners(property){ return listeners[property] || (listeners[property] = []); } // Tracks a property if it is not already tracked.
javascript
{ "resource": "" }
q2182
selectDimensionsAndMaterials
train
function selectDimensionsAndMaterials() { let reverbLength = document.getElementById('reverbLengthSelect').value; switch (reverbLength) { case 'none': default: { return { dimensions: { width: 0, height: 0, depth: 0, }, materials: { left: 'transparent', right: 'transparent', front: 'transparent', back: 'transparent', up: 'transparent', down: 'transparent', }, }; } break; case 'short': { return { dimensions: { width: 1.5, height: 1.5, depth: 1.5, }, materials: { left: 'uniform', right: 'uniform', front: 'uniform', back: 'uniform', up: 'uniform', down: 'uniform', }, }; } break; case 'medium': { return {
javascript
{ "resource": "" }
q2183
ResonanceAudio
train
function ResonanceAudio(context, options) { // Public variables. /** * Binaurally-rendered stereo (2-channel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof ResonanceAudio * @instance */ /** * Ambisonic (multichannel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode} * (For rendering input soundfields). * @member {AudioNode} ambisonicInput * @memberof ResonanceAudio * @instance */ /** * Ambisonic (multichannel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode} * (For allowing external rendering / post-processing). * @member {AudioNode} ambisonicOutput * @memberof ResonanceAudio * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.ambisonicOrder == undefined) { options.ambisonicOrder = Utils.DEFAULT_AMBISONIC_ORDER; } if (options.listenerPosition == undefined) { options.listenerPosition = Utils.DEFAULT_POSITION.slice(); } if (options.listenerForward == undefined) { options.listenerForward = Utils.DEFAULT_FORWARD.slice(); } if (options.listenerUp == undefined) { options.listenerUp = Utils.DEFAULT_UP.slice(); } if (options.dimensions == undefined) { options.dimensions = {}; Object.assign(options.dimensions, Utils.DEFAULT_ROOM_DIMENSIONS); } if (options.materials ==
javascript
{ "resource": "" }
q2184
updateAngles
train
function updateAngles(xAngle, yAngle, zAngle) { let deg2rad = Math.PI / 180; let euler = new THREE.Euler( xAngle * deg2rad, yAngle * deg2rad, zAngle * deg2rad, 'YXZ'); let matrix = new THREE.Matrix4().makeRotationFromEuler(euler); camera.setRotationFromMatrix(matrix); if
javascript
{ "resource": "" }
q2185
getCursorPosition
train
function getCursorPosition(event) { let cursorX; let cursorY; let rect = htmlElement.getBoundingClientRect(); if (event.touches !== undefined) { cursorX = event.touches[0].clientX; cursorY = event.touches[0].clientY; } else
javascript
{ "resource": "" }
q2186
selectRenderingMode
train
function selectRenderingMode(event) { if (!audioReady) return; switch (document.getElementById('renderingMode').value) { case 'toa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 1; } break; case 'foa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 1; toaGain.gain.value = 0; } break; case 'panner-node': { noneGain.gain.value = 0; pannerGain.gain.value = 1;
javascript
{ "resource": "" }
q2187
updatePositions
train
function updatePositions(elements) { if (!audioReady) return; for (let i = 0; i < elements.length; i++) { let x = (elements[i].x - 0.5) * dimensions.width / 2; let y = 0; let z = (elements[i].y - 0.5) * dimensions.depth / 2; if (i == 0) { pannerNode.setPosition(x, y, z); foaSource.setPosition(x, y, z);
javascript
{ "resource": "" }
q2188
_getCoefficientsFromMaterials
train
function _getCoefficientsFromMaterials(materials) { // Initialize coefficients to use defaults. let coefficients = {}; for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property)) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } // Sanitize materials. if (materials == undefined) { materials = {}; Object.assign(materials, Utils.DEFAULT_ROOM_MATERIALS); }
javascript
{ "resource": "" }
q2189
_sanitizeCoefficients
train
function _sanitizeCoefficients(coefficients) { if (coefficients == undefined) { coefficients = {}; } for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (!(coefficients.hasOwnProperty(property))) { // If element is not present, use default coefficients.
javascript
{ "resource": "" }
q2190
_sanitizeDimensions
train
function _sanitizeDimensions(dimensions) { if (dimensions == undefined) { dimensions = {}; } for (let property in Utils.DEFAULT_ROOM_DIMENSIONS)
javascript
{ "resource": "" }
q2191
_getDurationsFromProperties
train
function _getDurationsFromProperties(dimensions, coefficients, speedOfSound) { let durations = new Float32Array(Utils.NUMBER_REVERB_FREQUENCY_BANDS); // Sanitize inputs. dimensions = _sanitizeDimensions(dimensions); coefficients = _sanitizeCoefficients(coefficients); if (speedOfSound == undefined) { speedOfSound = Utils.DEFAULT_SPEED_OF_SOUND; } // Acoustic constant. let k = Utils.TWENTY_FOUR_LOG10 / speedOfSound; // Compute volume, skip if room is not present. let volume = dimensions.width * dimensions.height * dimensions.depth; if (volume < Utils.ROOM_MIN_VOLUME) { return durations; } // Room surface area. let leftRightArea = dimensions.width * dimensions.height; let floorCeilingArea = dimensions.width * dimensions.depth; let frontBackArea = dimensions.depth * dimensions.height; let totalArea = 2 * (leftRightArea + floorCeilingArea + frontBackArea); for (let i = 0; i < Utils.NUMBER_REVERB_FREQUENCY_BANDS; i++) { // Effective absorptive area. let absorbtionArea = (coefficients.left[i] + coefficients.right[i]) * leftRightArea + (coefficients.down[i] + coefficients.up[i]) *
javascript
{ "resource": "" }
q2192
_computeReflectionCoefficients
train
function _computeReflectionCoefficients(absorptionCoefficients) { let reflectionCoefficients = []; for (let property in Utils.DEFAULT_REFLECTION_COEFFICIENTS) { if (Utils.DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { // Compute average absorption coefficient (per wall). reflectionCoefficients[property] = 0; for (let j = 0; j < Utils.NUMBER_REFLECTION_AVERAGING_BANDS; j++) { let bandIndex = j + Utils.ROOM_STARTING_AVERAGING_BAND; reflectionCoefficients[property] +=
javascript
{ "resource": "" }
q2193
_computeDistanceOutsideRoom
train
function _computeDistanceOutsideRoom(distance) { // We apply a linear ramp from 1 to 0 as the source is up to 1m outside. let gain = 1;
javascript
{ "resource": "" }
q2194
validateJSonStructure
train
function validateJSonStructure(filePath, cb) { fs.readFile(filePath, function(err, data) { if (err) { return cb(err); } try {
javascript
{ "resource": "" }
q2195
validateMetadata
train
function validateMetadata(metadataPath, cb) { validateJSonStructure(metadataPath, function(err, metadataObject)
javascript
{ "resource": "" }
q2196
validateForm
train
function validateForm(form, cb) { async.series([function(callback) { fs.exists(form, function(exists) { if (exists) { callback(null); } else { callback('File ' + path.basename(form) + ' referenced by metadata.json does not exists'); } }); },
javascript
{ "resource": "" }
q2197
validate
train
function validate(archiveDirectory, strict, cb) { // Root validation checks fs.readdir(archiveDirectory, function(err, files) { if (err) { return cb(err); } if (files.length < 2 || (files.length !== 2 && strict)) { return cb('Root directory must contain exactly one metadata file and one forms directory'); } if (files.indexOf('forms') === -1) { return cb('A forms directory should be present in the root of the zip file'); } if (files.indexOf('metadata.json') === -1) { return cb('A metadata.json file must be present in the root of the zip file'); } var metadataPath = path.join(archiveDirectory, 'metadata.json'); async.waterfall([ function(callback) { validateMetadata(metadataPath,
javascript
{ "resource": "" }
q2198
resolve
train
function resolve() { expect(arguments).to.have.length.within( 1, 4, 'Invalid arguments length when resolving an Attribute (it has to be ' + 'passed from 1 to 4 arguments)' ); var argumentArray = Array.prototype.slice.call(arguments); var TypedAttribute = attributes.types.ObjectAttribute; if (arguments.length === 1 && typeof arguments[0] !== 'string') { var attribute = objects.copy(arguments[0]); argumentArray[0] = attribute; expect(attribute).to.be.an( 'object', 'Invalid argument type when resolving an Attribute (it has to be an ' + 'object)' ); if (attribute.type) { expect(attribute.type).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (attribute.name ? ' called' + attribute.name : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(attribute.type); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; attribute.entity = attribute.type; } else { throw e; } } delete attribute.type;
javascript
{ "resource": "" }
q2199
getDefaultValue
train
function getDefaultValue(entity) { expect(arguments).to.have.length( 1, 'Invalid arguments length when getting the default value of an Attribute ' + 'to an Entity instance (it has to be given 1 argument)' );
javascript
{ "resource": "" }