_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q63600
markdownToSnapshot
test
function markdownToSnapshot(content) { const tree = mdParser.parse(content); const state = { name: null, suite: null, suiteStack: [], currentSuite: null, currentSnapshotList: null, depth: 0 }; const children = tree.children; for (let i = 0; i < children.length; i++) { const c = children[i]; switch (c.type) { case 'heading': if (c.depth === 1) { enterRootSuite(state, c); } else if (c.depth === 2) { tryExit(state, suiteDepth(c)); enterSuite(state, c); } else if (c.depth === 4) { enterSnapshot(state, c); } break; case 'code': pushSnapshotCode(state, c); break; } } return { name: state.name, suite: state.suite }; }
javascript
{ "resource": "" }
q63601
tryExit
test
function tryExit(state, depth) { while (state.depth >= depth) { state.suiteStack.pop(); state.currentSuite = state.suiteStack[state.suiteStack.length - 1]; state.currentSnapshotList = null; state.depth--; } }
javascript
{ "resource": "" }
q63602
enterRootSuite
test
function enterRootSuite(state, node) { const inlineCode = node.children[0]; const name = inlineCode.value; const suite = { children: {}, snapshots: {} } state.name = name; state.suite = suite; state.suiteStack.push(suite); state.currentSuite = suite; state.currentSnapshotList = null; state.depth = 0; }
javascript
{ "resource": "" }
q63603
enterSnapshot
test
function enterSnapshot(state, node) { const inlineCode = node.children[0]; const name = inlineCode.value; const snapshotList = []; state.currentSuite.snapshots[name] = snapshotList; state.currentSnapshotList = snapshotList; }
javascript
{ "resource": "" }
q63604
pushSnapshotCode
test
function pushSnapshotCode(state, node) { state.currentSnapshotList.push({ lang: node.lang, code: normalizeNewlines(node.value) }); }
javascript
{ "resource": "" }
q63605
transformSuite
test
function transformSuite(name, suite, depth, indentCodeBlocks) { const children = suite.children; const snapshots = suite.snapshots; const nextDepth = depth + 1; let result = suiteHeader(name, depth); let keys, i; keys = Object.keys(snapshots); for (i = 0; i < keys.length; i++) { const key = keys[i]; const snapshotList = snapshots[key]; result += transformSnapshotList(key, snapshotList, nextDepth, indentCodeBlocks); } keys = Object.keys(children); for (i = 0; i < keys.length; i++) { const key = keys[i]; result += transformSuite(key, children[key], nextDepth, indentCodeBlocks); } return result; }
javascript
{ "resource": "" }
q63606
transformSnapshotList
test
function transformSnapshotList(name, snapshotList, depth, indentCodeBlocks) { let result = snapshotHeader(name, depth); for (let i = 0; i < snapshotList.length; i++) { if (i > 0 && indentCodeBlocks) { result += '---\n\n'; } const snapshot = snapshotList[i]; const lang = snapshot.lang; const code = snapshot.code; const delimiter = safeDelimiter(code); if (indentCodeBlocks) { const lines = code.split('\n'); for (let i = 0; i < lines.length; i++) { result += ' ' + lines[i] + '\n'; } } else { result += delimiter; if (lang) { result += lang; } result += '\n' + code + '\n' + delimiter + '\n'; } result += '\n'; } return result; }
javascript
{ "resource": "" }
q63607
suiteHeader
test
function suiteHeader(name, depth) { if (depth === -1) { return "# " + serializeName(name) + "\n\n"; } return "## " + indent(depth) + serializeName(name) + "\n\n"; }
javascript
{ "resource": "" }
q63608
safeDelimiter
test
function safeDelimiter(s, delimiter) { if (delimiter === undefined) { delimiter = '```'; } while (s.indexOf(delimiter) !== -1) { delimiter += '`'; } return delimiter; }
javascript
{ "resource": "" }
q63609
defaultPathResolver
test
function defaultPathResolver(basePath, suiteName) { const suiteSourcePath = path.join(basePath, suiteName); const suiteSourceDir = path.dirname(suiteSourcePath); const sourceFileName = path.basename(suiteName); return path.join(suiteSourceDir, "__snapshots__", sourceFileName + ".md"); }
javascript
{ "resource": "" }
q63610
formatSnapshotList
test
function formatSnapshotList(list, limit) { limit = (typeof limit != 'undefined') ? limit : -1; const limitedList = limit > 0 ? list.slice(0, limit) : list; const hasMore = list.length > limitedList.length; const buildList = (snapshots) => snapshots.map((s) => s.join(' > ')).join('\n'); if (hasMore) { return buildList(limitedList.slice(0, -1)) + `\n +${list.length - limitedList.length + 1} more`; } return buildList(limitedList); }
javascript
{ "resource": "" }
q63611
formatUnusedSnapshotsWarning
test
function formatUnusedSnapshotsWarning(list, limit) { if (limit == 0) { return `Found ${list.length} unused snapshots`; } const prunedList = formatSnapshotList(list, limit); return `Found ${list.length} unused snapshots:\n${prunedList}`; }
javascript
{ "resource": "" }
q63612
snapshotPreprocessor
test
function snapshotPreprocessor(basePath, loggerFactory) { const logger = loggerFactory.create('preprocessor.snapshot'); return function (content, file, done) { const root = snapshotSerializer.deserialize(content); done(iifeWrapper('window.__snapshot__.addSuite("' + root.name + '",' + JSON.stringify(root.suite) + ');')); }; }
javascript
{ "resource": "" }
q63613
singleLinePlugin
test
function singleLinePlugin (options = {}) { options = Object.assign({}, defaultOptions, options) return { /** * Return a compatible blockRenderMap * * NOTE: Needs to be explicitly applied, the plugin system doesn’t do * anything with this at the moment. * * @type {ImmutableMap} */ blockRenderMap: Map({ 'unstyled': { element: 'div', }, }), /** * onChange * * Condense multiple blocks into a single block and (optionally) strip all * entities from the content of that block. * * @param {EditorState} editorState The current state of the editor * @return {EditorState} A new editor state */ onChange (editorState) { const blocks = editorState.getCurrentContent().getBlocksAsArray() // If we have more than one block, compress them if (blocks.length > 1) { editorState = condenseBlocks(editorState, blocks, options) } else { // We only have one content block let contentBlock = blocks[0] let text = contentBlock.getText() let characterList = contentBlock.getCharacterList() let hasEntitiesToStrip = options.stripEntities && characterListhasEntities(characterList) if (NEWLINE_REGEX.test(text) || hasEntitiesToStrip) { // Replace the text stripped of its newlines. Note that we replace // one '\n' with one ' ' so we don't need to modify the characterList text = replaceNewlines(text) // Strip entities? if (options.stripEntities) { characterList = characterList.map(stripEntityFromCharacterMetadata) } // Create a new content block based on the old one contentBlock = new ContentBlock({ key: genKey(), text: text, type: 'unstyled', characterList: characterList, depth: 0, }) // Update the editor state with the compressed version // const selection = editorState.getSelection() const newContentState = ContentState.createFromBlockArray([contentBlock]) // Create the new state as an undoable action editorState = EditorState.push(editorState, newContentState, 'insert-characters') } } return editorState }, /** * Stop new lines being inserted by always handling the return * * @param {KeyboardEvent} e Synthetic keyboard event from draftjs * @return {String} Did we handle the return or not? (pro-trip: yes, we did) */ handleReturn (e) { return 'handled' }, } }
javascript
{ "resource": "" }
q63614
replaceNewlines
test
function replaceNewlines(str) { var replacement = arguments.length <= 1 || arguments[1] === undefined ? ' ' : arguments[1]; return str.replace(NEWLINE_REGEX, replacement); }
javascript
{ "resource": "" }
q63615
condenseBlocks
test
function condenseBlocks(editorState, blocks, options) { blocks = blocks || editorState.getCurrentContent().getBlocksAsArray(); var text = (0, _immutable.List)(); var characterList = (0, _immutable.List)(); // Gather all the text/characterList and concat them blocks.forEach(function (block) { // Atomic blocks should be ignored (stripped) if (block.getType() !== 'atomic') { text = text.push(replaceNewlines(block.getText())); characterList = characterList.concat(block.getCharacterList()); } }); // Strip entities? if (options.stripEntities) { characterList = characterList.map(stripEntityFromCharacterMetadata); } // Create a new content block var contentBlock = new _draftJs.ContentBlock({ key: (0, _draftJs.genKey)(), text: text.join(''), type: 'unstyled', characterList: characterList, depth: 0 }); // Update the editor state with the compressed version var newContentState = _draftJs.ContentState.createFromBlockArray([contentBlock]); // Create the new state as an undoable action editorState = _draftJs.EditorState.push(editorState, newContentState, 'remove-range'); // Move the selection to the end return _draftJs.EditorState.moveFocusToEnd(editorState); }
javascript
{ "resource": "" }
q63616
characterListhasEntities
test
function characterListhasEntities(characterList) { var hasEntities = false; characterList.forEach(function (characterMeta) { if (characterMeta.get('entity') !== null) { hasEntities = true; } }); return hasEntities; }
javascript
{ "resource": "" }
q63617
hexRgb
test
function hexRgb(hex){ let shorthandCheck = /^([a-f\d])([a-f\d])([a-f\d])$/i, rgbRegex = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i, rgb; hex = hex.replace(shorthandCheck, function(m, r, g, b) { return r + r + g + g + b + b; }); rgb = hex.replace(/^\s+|\s+$/g, '').match(rgbRegex); // Convert it return rgb ? [ parseInt(rgb[1], 16), parseInt(rgb[2], 16), parseInt(rgb[3], 16) ] : false; }
javascript
{ "resource": "" }
q63618
ruleHandler
test
function ruleHandler(decl, result) { let input = decl.value; // Get the raw hex values and replace them let output = input.replace(/rgba\(#(.*?),/g, (match, hex) => { let rgb = hexRgb(hex), matchHex = new RegExp('#' + hex); // If conversion fails, emit a warning if (!rgb) { result.warn('not a valid hex', { node: decl }); return match; } rgb = rgb.toString(); return match.replace(matchHex, rgb); }); decl.replaceWith({ prop: decl.prop, value: output, important: decl.important }); }
javascript
{ "resource": "" }
q63619
test
function () { for (var i = 0; i < this.config.methods.length; i++) { var key = this.config.methods[i]; // Only create analytics stub if it doesn't already exist if (!analytics[key]) { analytics[key] = analytics.factory(key); } this[key] = this.factory(key); } }
javascript
{ "resource": "" }
q63620
debug
test
function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting args = exports.formatArgs.apply(self, args); var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; }
javascript
{ "resource": "" }
q63621
isBuf$1
test
function isBuf$1(obj) { return (commonjsGlobal.Buffer && commonjsGlobal.Buffer.isBuffer(obj)) || (commonjsGlobal.ArrayBuffer && obj instanceof ArrayBuffer); }
javascript
{ "resource": "" }
q63622
encode$1
test
function encode$1(num) { var encoded = ''; do { encoded = alphabet[num % length] + encoded; num = Math.floor(num / length); } while (num > 0); return encoded; }
javascript
{ "resource": "" }
q63623
decode$1
test
function decode$1(str) { var decoded = 0; for (i = 0; i < str.length; i++) { decoded = decoded * length + map[str.charAt(i)]; } return decoded; }
javascript
{ "resource": "" }
q63624
Polling$1
test
function Polling$1 (opts) { var forceBase64 = (opts && opts.forceBase64); if (!hasXHR2 || forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); }
javascript
{ "resource": "" }
q63625
onupgrade
test
function onupgrade (to) { if (transport$$1 && to.name !== transport$$1.name) { debug$2('"%s" works - aborting "%s"', to.name, transport$$1.name); freezeTransport(); } }
javascript
{ "resource": "" }
q63626
cleanup
test
function cleanup () { transport$$1.removeListener('open', onTransportOpen); transport$$1.removeListener('error', onerror); transport$$1.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); }
javascript
{ "resource": "" }
q63627
Backoff$1
test
function Backoff$1(opts) { opts = opts || {}; this.ms = opts.min || 100; this.max = opts.max || 10000; this.factor = opts.factor || 2; this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; this.attempts = 0; }
javascript
{ "resource": "" }
q63628
extract
test
function extract(str, options) { const res = babylon.parse(str, options); return res.comments; }
javascript
{ "resource": "" }
q63629
bindNgModelControls
test
function bindNgModelControls(api) { ngModel.$render = () => { api.set(ngModel.$modelValue); }; api.on('update', () => { const positions = api.get(); ngModel.$setViewValue(positions); }); }
javascript
{ "resource": "" }
q63630
createInstance
test
function createInstance() { const api = extendApi(noUiSlider.create(htmlElement, options)); setCreatedWatcher(api); setOptionsWatcher(api); if (ngModel !== null) { bindNgModelControls(api); } }
javascript
{ "resource": "" }
q63631
test
function(w) { let vow = /[aeiouy]$/; let chars = w.split(''); let before = ''; let after = ''; let current = ''; for (let i = 0; i < chars.length; i++) { before = chars.slice(0, i).join(''); current = chars[i]; after = chars.slice(i + 1, chars.length).join(''); let candidate = before + chars[i]; //it's a consonant that comes after a vowel if (before.match(ends_with_vowel) && !current.match(ends_with_vowel)) { if (after.match(starts_with_e_then_specials)) { candidate += 'e'; after = after.replace(starts_with_e, ''); } all.push(candidate); return doer(after); } //unblended vowels ('noisy' vowel combinations) if (candidate.match(ends_with_noisy_vowel_combos)) { //'io' is noisy, not in 'ion' all.push(before); all.push(current); return doer(after); //recursion } // if candidate is followed by a CV, assume consecutive open syllables if (candidate.match(ends_with_vowel) && after.match(starts_with_consonant_vowel)) { all.push(candidate); return doer(after); } } //if still running, end last syllable if (str.match(aiouy) || str.match(ends_with_ee)) { //allow silent trailing e all.push(w); } else { all[all.length - 1] = (all[all.length - 1] || '') + w; //append it to the last one } return null; }
javascript
{ "resource": "" }
q63632
addApi
test
function addApi(self, apiName, api) { for (var name in api) { var fn = api[name]; if (typeof fn === "function") api[name] = api[name].bind(self); } var tmp = null; api.replied = new Promise((resolve, reject) => { tmp = { resolve, reject }; }); api.replied.resolve = tmp.resolve; api.replied.reject = tmp.reject; self[apiName] = api; }
javascript
{ "resource": "" }
q63633
getJson
test
function getJson(path) { return httpGet({ hostname: t.options.remoteClientHostname, port: t.options.remoteClientPort, path: path, method: 'GET' }).then((obj) => { var contentType = getContentType(obj.response); if (contentType !== "application/json") LOG.warn("Expecting JSON from " + path + " but found wrong content type: " + contentType); try { return JSON.parse(obj.data); } catch(ex) { LOG.warn("Cannot parse JSON returned from " + path); return null; } }); }
javascript
{ "resource": "" }
q63634
splitName
test
function splitName(method) { var pos = method.indexOf('.'); if (pos < 0) return [ null, method ]; var domainName = method.substring(0, pos); var methodName = method.substring(pos + 1); return [ domainName, methodName ]; }
javascript
{ "resource": "" }
q63635
copyToClient
test
function copyToClient(req, res) { return httpGet({ hostname: t.options.remoteClientHostname, port: t.options.remoteClientPort, path: req.originalUrl, method: 'GET' }).then(function (obj) { var contentType = getContentType(obj.response); if (contentType) res.set("Content-Type", contentType); res.send(obj.data); }); }
javascript
{ "resource": "" }
q63636
test
function () { // Save original Error.prepareStackTrace const origPrepareStackTrace = Error.prepareStackTrace // Override with function that just returns `stack` Error.prepareStackTrace = (_, stack) => stack // Create a new `Error`, which automatically gets `stack` const err = new Error() // Evaluate `err.stack`, which calls our new `Error.prepareStackTrace` const stack = err.stack // Restore original `Error.prepareStackTrace` Error.prepareStackTrace = origPrepareStackTrace // Remove superfluous function call on stack stack.shift() // getStack --> Error return stack }
javascript
{ "resource": "" }
q63637
captureStdio
test
function captureStdio(opts, exec) { var streams = [ process.stdout, process.stderr ]; var outputs = capture(streams, opts, exec); return { stdout: outputs.shift(), stderr: outputs.shift() }; }
javascript
{ "resource": "" }
q63638
hook
test
function hook(stream, opts, exec) { var args = _shift(opts, exec); opts = args[0]; exec = args[1]; var old_write = stream.write; stream.write = (function override(stream, writer) { return function write(string, encoding, fd) { exec(string, encoding, fd); if (!opts['quiet']) { writer.apply(stream, [ string, encoding, fd ]); } } })(stream, stream.write); return function unhook() { stream.write = old_write; return true; } }
javascript
{ "resource": "" }
q63639
startCapture
test
function startCapture(stream, opts, exec) { var unhook = hook(stream, opts, exec); var str_id = random.generate(); unhooks[str_id] = unhook; stream._id = str_id; return true; }
javascript
{ "resource": "" }
q63640
_wrapIntercept
test
function _wrapIntercept(func, stream, opts, exec) { var idex = Number(arguments.length > 3); var args = _shift(arguments[idex + 1], arguments[idex + 2]); opts = args[0]; exec = args[1]; opts.quiet = true; return idex ? func(stream, opts, exec) : func(opts, exec); }
javascript
{ "resource": "" }
q63641
getNearest
test
function getNearest($select, value) { var delta = {}; $select.children('option').each(function(i, opt){ var optValue = $(opt).attr('value'), distance; if(optValue === '') return; distance = Math.abs(optValue - value); if(typeof delta.distance === 'undefined' || distance < delta.distance) { delta = {value: optValue, distance: distance}; } }); return delta.value; }
javascript
{ "resource": "" }
q63642
evenRound
test
function evenRound(x) { // There are four cases for numbers with fractional part being .5: // // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 // (where n is a non-negative integer) // // Branch here for cases 1 and 4 if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { return censorNegativeZero(Math.floor(x)); } return censorNegativeZero(Math.round(x)); }
javascript
{ "resource": "" }
q63643
addFrameAt
test
function addFrameAt(time, value, delay, array) { array.push({ time:time, value:value, delay:delay }); }
javascript
{ "resource": "" }
q63644
sentiment
test
function sentiment(options) { return transformer function transformer(node) { var concatenate = concatenateFactory() visit(node, any(options)) visit(node, concatenate) concatenate.done() } }
javascript
{ "resource": "" }
q63645
concatenateFactory
test
function concatenateFactory() { var queue = [] concatenate.done = done return concatenate // Gather a parent if not already gathered. function concatenate(node, index, parent) { if (parent && parent.type !== 'WordNode' && queue.indexOf(parent) === -1) { queue.push(parent) } } // Patch all words in `parent`. function one(node) { var children = node.children var length = children.length var polarity = 0 var index = -1 var child var hasNegation while (++index < length) { child = children[index] if (child.data && child.data.polarity) { polarity += (hasNegation ? -1 : 1) * child.data.polarity } // If the value is a word, remove any present negation. Otherwise, add // negation if the node contains it. if (child.type === 'WordNode') { if (hasNegation) { hasNegation = false } else if (isNegation(child)) { hasNegation = true } } } patch(node, polarity) } // Patch all parents. function done() { var length = queue.length var index = -1 queue.reverse() while (++index < length) { one(queue[index]) } } }
javascript
{ "resource": "" }
q63646
one
test
function one(node) { var children = node.children var length = children.length var polarity = 0 var index = -1 var child var hasNegation while (++index < length) { child = children[index] if (child.data && child.data.polarity) { polarity += (hasNegation ? -1 : 1) * child.data.polarity } // If the value is a word, remove any present negation. Otherwise, add // negation if the node contains it. if (child.type === 'WordNode') { if (hasNegation) { hasNegation = false } else if (isNegation(child)) { hasNegation = true } } } patch(node, polarity) }
javascript
{ "resource": "" }
q63647
done
test
function done() { var length = queue.length var index = -1 queue.reverse() while (++index < length) { one(queue[index]) } }
javascript
{ "resource": "" }
q63648
any
test
function any(config) { return setter // Patch data-properties on `node`s with a value and words. function setter(node) { var value var polarity if ('value' in node || node.type === 'WordNode') { value = nlcstToString(node) if (config && own.call(config, value)) { polarity = config[value] } else if (own.call(polarities, value)) { polarity = polarities[value] } if (polarity) { patch(node, polarity) } } } }
javascript
{ "resource": "" }
q63649
patch
test
function patch(node, polarity) { var data = node.data || {} data.polarity = polarity || 0 data.valence = classify(polarity) node.data = data }
javascript
{ "resource": "" }
q63650
fire
test
function fire(event, target, listener) { var returned, oldData; if (listener.d !== null) { oldData = event.data; event.data = listener.d; returned = listener.h.call(target, event, target); event.data = oldData; } else { returned = listener.h.call(target, event, target); } return returned; }
javascript
{ "resource": "" }
q63651
Delegate
test
function Delegate(root) { var /** * Keep a reference to the current instance * * @internal * @type Delegate */ that = this, /** * Maintain a list of listeners, indexed by event name * * @internal * @type Object */ listenerList = {}; if (typeof root === 'string') { root = document.querySelector(root); } if (!root || !root.addEventListener) { throw new TypeError('Root node not specified'); } /** * Attach a handler to one event for all elements that match the selector, now or in the future * * The handler function receives three arguments: the DOM event object, the node that matched the selector while the event was bubbling * and a reference to itself. Within the handler, 'this' is equal to the second argument. * The node that actually received the event can be accessed via 'event.target'. * * @param {string} eventType Listen for these events (in a space-separated list) * @param {string} selector Only handle events on elements matching this selector * @param {Object} [eventData] If this parameter is not specified, the third parameter must be the handler * @param {function()} handler Handler function - event data passed here will be in event.data * @returns {Delegate} This method is chainable */ this.on = function() { Array.prototype.unshift.call(arguments, that, listenerList, root); on.apply(that, arguments); return this; }; /** * Remove an event handler for elements that match the selector, forever * * @param {string} eventType Remove handlers for events matching this type, considering the other parameters * @param {string} [selector] If this parameter is omitted, only handlers which match the other two will be removed * @param {function()} [handler] If this parameter is omitted, only handlers which match the previous two will be removed * @returns {Delegate} This method is chainable */ this.off = function() { Array.prototype.unshift.call(arguments, that, listenerList, root); off.apply(that, arguments); return this; }; /** * Handle an arbitrary event * * @private * @param {Event} event */ this.handle = function(event) { handle.call(that, listenerList, root, event); }; }
javascript
{ "resource": "" }
q63652
fm
test
function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); }
javascript
{ "resource": "" }
q63653
test
function(structure = []) { return new Promise((resolve, reject) => { if (Array.isArray(structure) === false) { throw new Error(`'structure' must be an array`) } parseStructure(structure, opts.cwd) .then((parsedStructure) => writeStructure(parsedStructure)) .then((parsedStructure) => binStructure(parsedStructure, bin, opts.persistent)) .then(resolve, reject) }) }
javascript
{ "resource": "" }
q63654
addAndWhereDate
test
function addAndWhereDate(queryBuilder, column, from, to) { if (from && to) { queryBuilder.whereBetween(column, [from, to]); } else if (from) { queryBuilder.andWhere(column, '>=', from); } else if (to) { queryBuilder.andWhere(column, '<=', to); } }
javascript
{ "resource": "" }
q63655
_handleMultiValuedParameters
test
function _handleMultiValuedParameters(knexBuilder, attrName, parameter) { if (parameter instanceof Set) { knexBuilder = knexBuilder.whereIn(attrName, Array.from(parameter)); } else if (Array.isArray(parameter)) { knexBuilder = knexBuilder.whereIn(attrName, parameter); } else { knexBuilder = knexBuilder.where(attrName, parameter); } return knexBuilder; }
javascript
{ "resource": "" }
q63656
getKnexInstance
test
function getKnexInstance(config, registry = _registry, logger = console) { validate.notNil(config, 'Config is null or undefined'); validate.notNil(config.client, 'DB client is null or undefined'); const { host, database, user } = config.connection; const connectionTimeout = config.acquireConnectionTimeout; logger.info(`Init db: ${user}/<Password omitted>@${host} db: ${database}`); logger.info(`Timeout: ${connectionTimeout}`); const knex = module.exports._initKnexInstance(config); module.exports.registerKnexInstance(knex, registry); // unfortunately, we can't check heartbeat here and fail-fast, as this initialization is synchronous return knex; }
javascript
{ "resource": "" }
q63657
closeAllInstances
test
function closeAllInstances(registry = _registry) { const promises = []; const errors = []; while (registry.length > 0) { const knex = registry.pop(); const destructionPromise = knex.destroy().catch(e => { errors.push({ knex, cause: e }); }); promises.push(destructionPromise); } return Promise.all(promises).then(() => { return errors; }); }
javascript
{ "resource": "" }
q63658
remarkHljs
test
function remarkHljs({ aliases }) { return ast => visit(ast, 'code', node => { if (!node.data) { node.data = {}; } const lang = node.lang; const highlighted = lang ? low.highlight(aliases[lang] || lang, node.value).value : low.highlightAuto(node.value).value; node.data.hChildren = highlighted; node.data.hProperties = { className: ['hljs', lang && `language-${lang}`], }; }); }
javascript
{ "resource": "" }
q63659
render
test
function render(processor, source) { try { return processor.processSync(source).contents; } catch (exception) { const error = `Error while rendering Markdown: ${exception.message}`; console.error(error); return errorInlineHtml(error).toString(); } }
javascript
{ "resource": "" }
q63660
createColorArrow
test
function createColorArrow(defElement, color) { defElement.append("marker") .attr("id", "arrow-" + color) .attr("viewBox", "0 -5 10 10") .attr("refX", 8) .attr("markerWidth", 6) .attr("markerHeight", 6) .attr("fill", color) .attr("orient", "auto") .append("path") .attr("d", "M0,-5L10,0L0,5") .attr("class", "arrowHead"); }
javascript
{ "resource": "" }
q63661
valueParserNodesLength
test
function valueParserNodesLength (length, operator = '===') { return t.binaryExpression( operator, valueParserASTNodesLength, t.numericLiteral(length) ); }
javascript
{ "resource": "" }
q63662
sliceThen
test
function sliceThen(file, offset, len) { var p = new Promise(function(_resolve) { fs.open(file, 'r', function(err, fd){ if (err) { throw err; } var res = new Buffer(len); fs.read(fd, res, 0, len, offset, function(err, bytesRead, buffer){ if (err) { throw err; } _resolve(buffer); }); }); }); /** * Call proc with specified arguments prepending with sliced file/blob data (ArrayBuffer) been read. * @param the first argument is a function to be executed * @param other optional arguments are passed to the function following auto supplied input ArrayBuffer * @return a promise object which can be chained with further process through spread() method */ p.exec = function(proc /*, args... */) { var args = Array.prototype.slice.call(arguments, 1); return p.then(function(data) { args.unshift(data); var ret = proc.apply(null, args); return resolve(ret !== UNDEFINED && ret._spreadus_ ? ret : [ret]); }); }; return p; }
javascript
{ "resource": "" }
q63663
harvest
test
function harvest(outcomes) { return Promise.settle(outcomes).then(function(results) { if (results.length === 0) { return reject("** NOT FOUND **"); } var solved = [], failed = []; for (var i = 0; i < results.length; i++) { if (results[i].isResolved()) { solved.push(results[i].value()); } else { failed.push(results[i].reason()); } } return solved.length ? solved : failed; }); }
javascript
{ "resource": "" }
q63664
test
function(keyAt) { var hi = (arr.length >> 1) - 1, lo = 0, i = (lo + hi) >> 1, val = arr[(i << 1) + 1]; if (keyAt > arr[(hi << 1) + 1] || keyAt < 0) { return; } while (true) { if (hi - lo <= 1) { if (i < hi) { return { block_no: i, comp_offset: arr[i <<= 1], comp_size: arr[i + 2] - arr[i], decomp_offset:arr[i + 1], decomp_size: arr[i + 3] - arr[i + 1] }; } else { return; } } (keyAt < val) ? hi = i : lo = i; i = (lo + hi) >> 1; val = arr[(i << 1) + 1]; } }
javascript
{ "resource": "" }
q63665
test
function(len) { len *= _bpu; var read = conseq(_decoder.decode(newUint8Array(buf, offset, len)), this.forward(len + _tail)); return read; }
javascript
{ "resource": "" }
q63666
test
function(len) { return conseq(newUint8Array(buf, offset, len), this.forward(len === UNDEFINED ? buf.length - offset : len)); }
javascript
{ "resource": "" }
q63667
read_header_sect
test
function read_header_sect(input, len) { var scanner = Scanner(input), header_str = scanner.readUTF16(len).replace(/\0$/, ''); // need to remove tailing NUL // parse dictionary attributes var doc = new DOMParser().parseFromString(header_str,'text/xml'); var elem = doc.getElementsByTagName('Dictionary')[0]; if (!elem) { elem = doc.getElementsByTagName('Library_Data')[0]; } // console.log(doc.getElementsByTagName('Dictionary')[0].attributes); // var xml = parseXml(header_str).querySelector('Dictionary, Library_Data').attributes; for (var i = 0, item; i < elem.attributes.length; i++) { item = elem.attributes[i]; attrs[item.nodeName] = item.nodeValue; } attrs.Encrypted = parseInt(attrs.Encrypted, 10) || 0; config(); return spreadus(len + 4, input); }
javascript
{ "resource": "" }
q63668
read_keyword_summary
test
function read_keyword_summary(input, offset) { var scanner = Scanner(input); scanner.forward(offset); return { num_blocks: scanner.readNum(), num_entries: scanner.readNum(), key_index_decomp_len: _v2 && scanner.readNum(), // Ver >= 2.0 only key_index_comp_len: scanner.readNum(), key_blocks_len: scanner.readNum(), chksum: scanner.checksum_v2(), // extra field len: scanner.offset() - offset, // actual length of keyword section, varying with engine version attribute }; }
javascript
{ "resource": "" }
q63669
read_keyword_index
test
function read_keyword_index(input, keyword_summary) { var scanner = Scanner(input).readBlock(keyword_summary.key_index_comp_len, keyword_summary.key_index_decomp_len, _decryptors[1]), keyword_index = Array(keyword_summary.num_blocks), offset = 0; for (var i = 0, size; i < keyword_summary.num_blocks; i++) { keyword_index[i] = { num_entries: conseq(scanner.readNum(), size = scanner.readShort()), // UNUSED, can be ignored // first_size: size = scanner.readShort(), first_word: conseq(scanner.readTextSized(size), size = scanner.readShort()), // UNUSED, can be ignored // last_size: size = scanner.readShort(), last_word: scanner.readTextSized(size), comp_size: size = scanner.readNum(), decomp_size: scanner.readNum(), // extra fields offset: offset, // offset of the first byte for the target key block in mdx/mdd file index: i // index of this key index, used to search previous/next block }; offset += size; } return spreadus(keyword_summary, keyword_index); }
javascript
{ "resource": "" }
q63670
read_key_block
test
function read_key_block(scanner, kdx) { var scanner = scanner.readBlock(kdx.comp_size, kdx.decomp_size); for (var i = 0; i < kdx.num_entries; i++) { // scanner.readNum(); scanner.readText(); var kk = [scanner.readNum(), scanner.readText()]; } }
javascript
{ "resource": "" }
q63671
willScanKeyTable
test
function willScanKeyTable(slicedKeyBlock, num_entries, keyword_index, delay) { slicedKeyBlock.delay(delay).then(function (input) { var scanner = Scanner(input); for (var i = 0, size = keyword_index.length; i < size; i++) { // common.log('z',keyword_index[i]); read_key_block(scanner, keyword_index[i]); } }); }
javascript
{ "resource": "" }
q63672
read_record_summary
test
function read_record_summary(input, pos) { var scanner = Scanner(input), record_summary = { num_blocks: scanner.readNum(), num_entries: scanner.readNum(), index_len: scanner.readNum(), blocks_len: scanner.readNum(), // extra field len: scanner.offset(), // actual length of record section (excluding record block index), varying with engine version attribute }; // start position of record block from head of mdx/mdd file record_summary.block_pos = pos + record_summary.index_len + record_summary.len; return record_summary; }
javascript
{ "resource": "" }
q63673
read_record_block
test
function read_record_block(input, record_summary) { var scanner = Scanner(input), size = record_summary.num_blocks, record_index = Array(size), p0 = record_summary.block_pos, p1 = 0; RECORD_BLOCK_TABLE.alloc(size + 1); for (var i = 0, rdx; i < size; i++) { record_index[i] = rdx = { comp_size: scanner.readNum(), decomp_size: scanner.readNum() }; RECORD_BLOCK_TABLE.put(p0, p1); p0 += rdx.comp_size; p1 += rdx.decomp_size; } RECORD_BLOCK_TABLE.put(p0, p1); }
javascript
{ "resource": "" }
q63674
read_definition
test
function read_definition(input, block, keyinfo) { var scanner = Scanner(input).readBlock(block.comp_size, block.decomp_size); scanner.forward(keyinfo.offset - block.decomp_offset); return scanner.readText(); }
javascript
{ "resource": "" }
q63675
read_object
test
function read_object(input, block, keyinfo) { if (input.byteLength > 0) { var scanner = Scanner(input).readBlock(block.comp_size, block.decomp_size); scanner.forward(keyinfo.offset - block.decomp_offset); return scanner.readRaw(keyinfo.size); } else { throw '* OUT OF FILE RANGE * ' + keyinfo + ' @offset=' + block.comp_offset; } }
javascript
{ "resource": "" }
q63676
findWord
test
function findWord(keyinfo) { var block = RECORD_BLOCK_TABLE.find(keyinfo.offset); return _slice(block.comp_offset, block.comp_size) .exec(read_definition, block, keyinfo) .spread(function (definition) { return resolve(followLink(definition, LOOKUP.mdx)); }); }
javascript
{ "resource": "" }
q63677
reduce
test
function reduce(arr, phrase) { var len = arr.length; if (len > 1) { len = len >> 1; return phrase > _adaptKey(arr[len - 1].last_word) ? reduce(arr.slice(len), phrase) : reduce(arr.slice(0, len), phrase); } else { return arr[0]; } }
javascript
{ "resource": "" }
q63678
shrink
test
function shrink(arr, phrase) { var len = arr.length, sub; if (len > 1) { len = len >> 1; var key = _adaptKey(arr[len]); if (phrase < key) { sub = arr.slice(0, len); sub.pos = arr.pos; } else { sub = arr.slice(len); sub.pos = (arr.pos || 0) + len; } return shrink(sub, phrase); } else { return (arr.pos || 0) + (phrase <= _adaptKey(arr[0]) ? 0 : 1); } }
javascript
{ "resource": "" }
q63679
seekVanguard
test
function seekVanguard(phrase) { phrase = _adaptKey(phrase); var kdx = reduce(KEY_INDEX, phrase); // look back for the first record block containing keyword for the specified phrase if (phrase <= _adaptKey(kdx.last_word)) { var index = kdx.index - 1, prev; while (prev = KEY_INDEX[index]) { if (_adaptKey(prev.last_word) !== _adaptKey(kdx.last_word)) { break; } kdx = prev; index--; } } return loadKeys(kdx).then(function (list) { var idx = shrink(list, phrase); // look back for the first matched keyword position while (idx > 0) { if (_adaptKey(list[--idx]) !== _adaptKey(phrase)) { idx++; break; } } return [kdx, Math.min(idx, list.length - 1), list]; }); }
javascript
{ "resource": "" }
q63680
matchOffset
test
function matchOffset(list, offset) { return list.some(function(el) { return el.offset === offset ? list = [el] : false; }) ? list : []; }
javascript
{ "resource": "" }
q63681
isValidModifierKeyCombo
test
function isValidModifierKeyCombo(modifierKeys, e) { var modifierKeyNames = ['alt', 'ctrl', 'meta', 'shift'], numModKeys = modifierKeys.length, i, j, currModifierKey, isValid = true; // check that all required modifier keys were pressed for (i = 0; i < numModKeys; i += 1) { if (!e[modifierKeys[i]]) { isValid = false; break; } } // if the requirements were met, check for additional modifier keys if (isValid) { for (i = 0; i < modifierKeyNames.length; i += 1) { currModifierKey = modifierKeyNames[i] + 'Key'; // if this key was pressed if (e[currModifierKey]) { // if there are required keys, check whether the current key // is required if (numModKeys) { isValid = false; // if this is a required key, continue for (j = 0; j < numModKeys; j += 1) { if (currModifierKey === modifierKeys[j]) { isValid = true; break; } } } else { // no required keys, but one was pressed isValid = false; } } // an extra key was pressed, don't check anymore if (!isValid) { break; } } } return isValid; }
javascript
{ "resource": "" }
q63682
createKeyComboFunction
test
function createKeyComboFunction(keyFunc, modifierKeys) { return function (keyCode, modifierKeyNames) { var i, keyCombo = ''; if (arguments.length) { if (typeof keyCode === 'number') { keyFunc(keyCode); modifierKeys.length = 0; // clear the array if (modifierKeyNames && modifierKeyNames.length) { for (i = 0; i < modifierKeyNames.length; i += 1) { modifierKeys.push(modifierKeyNames[i] + 'Key'); } } } return this; } for (i = 0; i < modifierKeys.length; i += 1) { keyCombo += modifierKeys[i].slice(0, -3) + '+'; } return keyCombo + keyFunc(); }; }
javascript
{ "resource": "" }
q63683
overrideKeyDown
test
function overrideKeyDown(e) { e = e || event; // textarea elements can only contain text nodes which don't receive // keydown events, so the event target/srcElement will always be the // textarea element, however, prefer currentTarget in order to support // delegated events in compliant browsers var target = e.currentTarget || e.srcElement, // don't use the "this" keyword (doesn't work in old IE) key = e.keyCode, // the key code for the key that was pressed tab, // the string representing a tab tabLen, // the length of a tab text, // initial text in the textarea range, // the IE TextRange object tempRange, // used to calculate selection start and end positions in IE preNewlines, // the number of newline character sequences before the selection start (for IE) selNewlines, // the number of newline character sequences within the selection (for IE) initScrollTop, // initial scrollTop value used to fix scrolling in Firefox selStart, // the selection start position selEnd, // the selection end position sel, // the selected text startLine, // for multi-line selections, the first character position of the first line endLine, // for multi-line selections, the last character position of the last line numTabs, // the number of tabs inserted / removed in the selection startTab, // if a tab was removed from the start of the first line preTab, // if a tab was removed before the start of the selection whitespace, // the whitespace at the beginning of the first selected line whitespaceLen, // the length of the whitespace at the beginning of the first selected line CHARACTER = 'character'; // string constant used for the Range.move methods // don't do any unnecessary work if ((target.nodeName && target.nodeName.toLowerCase() !== 'textarea') || (key !== tabKey && key !== untabKey && (key !== 13 || !autoIndent))) { return; } // initialize variables used for tab and enter keys inWhitespace = false; // this will be set to true if enter is pressed in the leading whitespace text = target.value; // this is really just for Firefox, but will be used by all browsers that support // selectionStart and selectionEnd - whenever the textarea value property is reset, // Firefox scrolls back to the top - this is used to set it back to the original value // scrollTop is nonstandard, but supported by all modern browsers initScrollTop = target.scrollTop; // get the text selection if (typeof target.selectionStart === 'number') { selStart = target.selectionStart; selEnd = target.selectionEnd; sel = text.slice(selStart, selEnd); } else if (document.selection) { // IE range = document.selection.createRange(); sel = range.text; tempRange = range.duplicate(); tempRange.moveToElementText(target); tempRange.setEndPoint('EndToEnd', range); selEnd = tempRange.text.length; selStart = selEnd - sel.length; // whenever the value of the textarea is changed, the range needs to be reset // IE <9 (and Opera) use both \r and \n for newlines - this adds an extra character // that needs to be accounted for when doing position calculations with ranges // these values are used to offset the selection start and end positions if (newlineLen > 1) { preNewlines = text.slice(0, selStart).split(newline).length - 1; selNewlines = sel.split(newline).length - 1; } else { preNewlines = selNewlines = 0; } } else { return; // cannot access textarea selection - do nothing } // tab / untab key - insert / remove tab if (key === tabKey || key === untabKey) { // initialize tab variables tab = aTab; tabLen = tab.length; numTabs = 0; startTab = 0; preTab = 0; // multi-line selection if (selStart !== selEnd && sel.indexOf('\n') !== -1) { // for multiple lines, only insert / remove tabs from the beginning of each line // find the start of the first selected line if (selStart === 0 || text.charAt(selStart - 1) === '\n') { // the selection starts at the beginning of a line startLine = selStart; } else { // the selection starts after the beginning of a line // set startLine to the beginning of the first partially selected line // subtract 1 from selStart in case the cursor is at the newline character, // for instance, if the very end of the previous line was selected // add 1 to get the next character after the newline // if there is none before the selection, lastIndexOf returns -1 // when 1 is added to that it becomes 0 and the first character is used startLine = text.lastIndexOf('\n', selStart - 1) + 1; } // find the end of the last selected line if (selEnd === text.length || text.charAt(selEnd) === '\n') { // the selection ends at the end of a line endLine = selEnd; } else if (text.charAt(selEnd - 1) === '\n') { // the selection ends at the start of a line, but no // characters are selected - don't indent this line endLine = selEnd - 1; } else { // the selection ends before the end of a line // set endLine to the end of the last partially selected line endLine = text.indexOf('\n', selEnd); if (endLine === -1) { endLine = text.length; } } // tab key combo - insert tabs if (tabKeyComboPressed(key, e)) { numTabs = 1; // for the first tab // insert tabs at the beginning of each line of the selection target.value = text.slice(0, startLine) + tab + text.slice(startLine, endLine).replace(/\n/g, function () { numTabs += 1; return '\n' + tab; }) + text.slice(endLine); // set start and end points if (range) { // IE range.collapse(); range.moveEnd(CHARACTER, selEnd + (numTabs * tabLen) - selNewlines - preNewlines); range.moveStart(CHARACTER, selStart + tabLen - preNewlines); range.select(); } else { // the selection start is always moved by 1 character target.selectionStart = selStart + tabLen; // move the selection end over by the total number of tabs inserted target.selectionEnd = selEnd + (numTabs * tabLen); target.scrollTop = initScrollTop; } } else if (untabKeyComboPressed(key, e)) { // if the untab key combo was pressed, remove tabs instead of inserting them if (text.slice(startLine).indexOf(tab) === 0) { // is this tab part of the selection? if (startLine === selStart) { // it is, remove it sel = sel.slice(tabLen); } else { // the tab comes before the selection preTab = tabLen; } startTab = tabLen; } target.value = text.slice(0, startLine) + text.slice(startLine + preTab, selStart) + sel.replace(new RegExp('\n' + tab, 'g'), function () { numTabs += 1; return '\n'; }) + text.slice(selEnd); // set start and end points if (range) { // IE // setting end first makes calculations easier range.collapse(); range.moveEnd(CHARACTER, selEnd - startTab - (numTabs * tabLen) - selNewlines - preNewlines); range.moveStart(CHARACTER, selStart - preTab - preNewlines); range.select(); } else { // set start first for Opera target.selectionStart = selStart - preTab; // preTab is 0 or tabLen // move the selection end over by the total number of tabs removed target.selectionEnd = selEnd - startTab - (numTabs * tabLen); } } else { return; // do nothing for invalid key combinations } } else { // single line selection // tab key combo - insert a tab if (tabKeyComboPressed(key, e)) { if (range) { // IE range.text = tab; range.select(); } else { target.value = text.slice(0, selStart) + tab + text.slice(selEnd); target.selectionEnd = target.selectionStart = selStart + tabLen; target.scrollTop = initScrollTop; } } else if (untabKeyComboPressed(key, e)) { // if the untab key combo was pressed, remove a tab instead of inserting one // if the character before the selection is a tab, remove it if (text.slice(selStart - tabLen).indexOf(tab) === 0) { target.value = text.slice(0, selStart - tabLen) + text.slice(selStart); // set start and end points if (range) { // IE // collapses range and moves it by -1 tab range.move(CHARACTER, selStart - tabLen - preNewlines); range.select(); } else { target.selectionEnd = target.selectionStart = selStart - tabLen; target.scrollTop = initScrollTop; } } } else { return; // do nothing for invalid key combinations } } } else if (autoIndent) { // Enter key // insert a newline and copy the whitespace from the beginning of the line // find the start of the first selected line if (selStart === 0 || text.charAt(selStart - 1) === '\n') { // the selection starts at the beginning of a line // do nothing special inWhitespace = true; return; } // see explanation under "multi-line selection" above startLine = text.lastIndexOf('\n', selStart - 1) + 1; // find the end of the first selected line endLine = text.indexOf('\n', selStart); // if no newline is found, set endLine to the end of the text if (endLine === -1) { endLine = text.length; } // get the whitespace at the beginning of the first selected line (spaces and tabs only) whitespace = text.slice(startLine, endLine).match(/^[ \t]*/)[0]; whitespaceLen = whitespace.length; // the cursor (selStart) is in the whitespace at beginning of the line // do nothing special if (selStart < startLine + whitespaceLen) { inWhitespace = true; return; } if (range) { // IE // insert the newline and whitespace range.text = '\n' + whitespace; range.select(); } else { // insert the newline and whitespace target.value = text.slice(0, selStart) + '\n' + whitespace + text.slice(selEnd); // Opera uses \r\n for a newline, instead of \n, // so use newlineLen instead of a hard-coded value target.selectionEnd = target.selectionStart = selStart + newlineLen + whitespaceLen; target.scrollTop = initScrollTop; } } if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; return false; } }
javascript
{ "resource": "" }
q63684
overrideKeyPress
test
function overrideKeyPress(e) { e = e || event; var key = e.keyCode; if (tabKeyComboPressed(key, e) || untabKeyComboPressed(key, e) || (key === 13 && autoIndent && !inWhitespace)) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; return false; } } }
javascript
{ "resource": "" }
q63685
executeExtensions
test
function executeExtensions(hook, args) { var i, extensions = hooks[hook] || [], len = extensions.length; for (i = 0; i < len; i += 1) { extensions[i].apply(null, args); } }
javascript
{ "resource": "" }
q63686
test
function(imapMessage) { var deferred = Q.defer(); var message = new Message(); imapMessage.on('body', function(stream, info) { var buffer = ''; stream.on('data', function(chunk) { buffer += chunk.toString('utf8'); }); stream.on('end', function() { if (info.which === 'TEXT') { message.body = buffer; } else { message.headers = Imap.parseHeader(buffer); } }); }); imapMessage.on('attributes', function(attrs) { message.attributes = attrs; }); imapMessage.on('end', function() { deferred.resolve(message); }); return deferred.promise; }
javascript
{ "resource": "" }
q63687
GPT
test
function GPT( options ) { if( !(this instanceof GPT) ) { return new GPT( options ) } options = options != null ? options : {} /** @type {Number} Storage device's block size in bytes */ this.blockSize = options.blockSize || 512 /** @type {String} GUID of the GUID Partition Table */ this.guid = options.guid || GPT.GUID.ZERO /** @type {Number} GPT format revision (?) */ this.revision = options.revision || 0 /** @type {Number} Size of the GPT header in bytes */ this.headerSize = options.headerSize || GPT.HEADER_SIZE /** @type {Number} GPT header's CRC32 checksum */ this.headerChecksum = 0 /** @type {Number} Logical block address of *this* GPT */ this.currentLBA = options.currentLBA || 1 /** @type {Number} Logical block address of the secondary GPT */ this.backupLBA = options.backupLBA || 0 /** @type {Number} Address of the first user-space usable logical block */ this.firstLBA = options.firstLBA || 34 /** @type {Number} Address of the last user-space usable logical block */ this.lastLBA = options.lastLBA || 0 /** @type {Number} LBA of partition table */ this.tableOffset = options.tableOffset || GPT.TABLE_OFFSET /** @type {Number} Number of partition table entries */ this.entries = options.entries || GPT.TABLE_ENTRIES /** @type {Number} Partition entry's size in bytes */ this.entrySize = options.entrySize || GPT.TABLE_ENTRY_SIZE /** @type {Number} Partition table's CRC32 checksum */ this.tableChecksum = 0 // Array of partition entries this.partitions = [] }
javascript
{ "resource": "" }
q63688
readBackupGPT
test
function readBackupGPT(primaryGPT) { var backupGPT = new GPT({ blockSize: primaryGPT.blockSize }) var buffer = Buffer.alloc( 33 * primaryGPT.blockSize ) var offset = ( ( primaryGPT.backupLBA - 32 ) * blockSize ) fs.readSync( fd, buffer, 0, buffer.length, offset ) backupGPT.parseBackup( buffer ) return backupGPT }
javascript
{ "resource": "" }
q63689
stopcock
test
function stopcock(fn, options) { options = Object.assign( { queueSize: Math.pow(2, 32) - 1, bucketSize: 40, interval: 1000, limit: 2 }, options ); const bucket = new TokenBucket(options); const queue = []; let timer = null; function shift() { clearTimeout(timer); while (queue.length) { const delay = bucket.consume(); if (delay > 0) { timer = setTimeout(shift, delay); break; } const data = queue.shift(); data[2](fn.apply(data[0], data[1])); } } function limiter() { const args = arguments; return new Promise((resolve, reject) => { if (queue.length === options.queueSize) { return reject(new Error('Queue is full')); } queue.push([this, args, resolve]); shift(); }); } Object.defineProperty(limiter, 'size', { get: () => queue.length }); return limiter; }
javascript
{ "resource": "" }
q63690
formatQuantity
test
function formatQuantity(value, encode, pad) { if (['string', 'number', 'object'].indexOf(typeof value) === -1 || value === null) { return value; } const numberValue = numberToBN(value); const numPadding = numberValue.lt(ten) && pad === true && !numberValue.isZero() ? '0' : ''; if (numberToBN(value).isNeg()) { throw new Error(`[ethjs-format] while formatting quantity '${numberValue.toString(10)}', invalid negative number. Number must be positive or zero.`); } return encode ? `0x${numPadding}${numberValue.toString(16)}` : numberValue; }
javascript
{ "resource": "" }
q63691
formatQuantityOrTag
test
function formatQuantityOrTag(value, encode) { var output = value; // eslint-disable-line // if the value is a tag, bypass if (schema.tags.indexOf(value) === -1) { output = formatQuantity(value, encode); } return output; }
javascript
{ "resource": "" }
q63692
formatData
test
function formatData(value, byteLength) { var output = value; // eslint-disable-line var outputByteLength = 0; // eslint-disable-line // prefix only under strict conditions, else bypass if (typeof value === 'string') { output = `0x${padToEven(stripHexPrefix(value))}`; outputByteLength = getBinarySize(output); } // format double padded zeros. if (output === '0x00') { output = '0x0'; } // throw if bytelength is not correct if (typeof byteLength === 'number' && value !== null && output !== '0x' && output !== '0x0' // support empty values && (!/^[0-9A-Fa-f]+$/.test(stripHexPrefix(output)) || outputByteLength !== 2 + byteLength * 2)) { throw new Error(`[ethjs-format] hex string '${output}' must be an alphanumeric ${2 + byteLength * 2} utf8 byte hex (chars: a-fA-F) string, is ${outputByteLength} bytes`); } return output; }
javascript
{ "resource": "" }
q63693
formatObject
test
function formatObject(formatter, value, encode) { var output = Object.assign({}, value); // eslint-disable-line var formatObject = null; // eslint-disable-line // if the object is a string flag, then retreive the object if (typeof formatter === 'string') { if (formatter === 'Boolean|EthSyncing') { formatObject = Object.assign({}, schema.objects.EthSyncing); } else if (formatter === 'DATA|Transaction') { formatObject = Object.assign({}, schema.objects.Transaction); } else { formatObject = Object.assign({}, schema.objects[formatter]); } } // check if all required data keys are fulfilled if (!arrayContainsArray(Object.keys(value), formatObject.__required)) { // eslint-disable-line throw new Error(`[ethjs-format] object ${JSON.stringify(value)} must contain properties: ${formatObject.__required.join(', ')}`); // eslint-disable-line } // assume formatObject is an object, go through keys and format each Object.keys(formatObject).forEach((valueKey) => { if (valueKey !== '__required' && typeof value[valueKey] !== 'undefined') { output[valueKey] = format(formatObject[valueKey], value[valueKey], encode); } }); return output; }
javascript
{ "resource": "" }
q63694
format
test
function format(formatter, value, encode, lengthRequirement) { var output = value; // eslint-disable-line // if formatter is quantity or quantity or tag if (formatter === 'Q') { output = formatQuantity(value, encode); } else if (formatter === 'QP') { output = formatQuantity(value, encode, true); } else if (formatter === 'Q|T') { output = formatQuantityOrTag(value, encode); } else if (formatter === 'D') { output = formatData(value); // dont format data flagged objects like compiler output } else if (formatter === 'D20') { output = formatData(value, 20); // dont format data flagged objects like compiler output } else if (formatter === 'D32') { output = formatData(value, 32); // dont format data flagged objects like compiler output } else { // if value is an object or array if (typeof value === 'object' && value !== null && Array.isArray(value) === false) { output = formatObject(formatter, value, encode); } else if (Array.isArray(value)) { output = formatArray(formatter, value, encode, lengthRequirement); } } return output; }
javascript
{ "resource": "" }
q63695
formatInputs
test
function formatInputs(method, inputs) { return format(schema.methods[method][0], inputs, true, schema.methods[method][2]); }
javascript
{ "resource": "" }
q63696
test
function (files) { if (!_.isArray(files)) { throw new Error('Arguments to config-helper.mergeConfig should be an array'); } var appConfig = {}; files.forEach(function (filePath) { if (gruntFile.exists(filePath)) { var fileConfig = gruntFile.readYAML(filePath); // Use lodash to do a 'deep merge' which only overwrites the properties // specified in previous config files, without wiping out their child properties. _.merge(appConfig, fileConfig); } }); return appConfig; }
javascript
{ "resource": "" }
q63697
parseProperties
test
function parseProperties(node) { consume(); // '(' while(true) { clear(); /** * Properties always have to start with '.' or ':' * o(.x, :y) matches an object with at least an owned property * 'x' and a owned or inherited property 'y'. */ if(peek() === '.') { parseProperty(node,false); // own property } else if(peek() === ':') { parseProperty(node,true); // prototype property } else { unexpectedTokenException('. or :'); } clear(); if(peek() !== ',') { break; } consume(); // ',' } }
javascript
{ "resource": "" }
q63698
extractStringLiteral
test
function extractStringLiteral() { var literal = [], enclosing = next(); if(!(enclosing === '"' || enclosing === "'")) { throw "Unexpected token at index " + index + " expected 'string' but found " + enclosing; } while(hasNext() && peek() !== enclosing) { literal[literal.length] = next(); } consume(); // ' or " return literal.join(''); }
javascript
{ "resource": "" }
q63699
parseStringLiteral
test
function parseStringLiteral(AST) { if(peek() === '/') { newNode(extractRegex(), newNode('r=', AST).nodes); } else { newNode(extractStringLiteral(), newNode('=', AST).nodes); } }
javascript
{ "resource": "" }